PageSourceSearch

https://stjosephmo.gov/-1442400649.js

js stjosephmo.gov collected 2026-10-02 10:15:05 UTC 728,293 bytes, 13,665 lines download raw bytes

1/*
2The following errors were found when attempting to minify this file:
3- Line 1675: Parse error. syntax error
4- Line 1680: Parse error. syntax error
5- Line 1681: Parse error. syntax error
6- Line 1682: Parse error. 'try' without 'catch' or 'finally'
7- Line 1684: Parse error. syntax error
8- Line 1686: Parse error. syntax error
9- Line 1688: Parse error. syntax error
10- Line 1689: Parse error. missing ; before statement
11- Line 1692: Parse error. syntax error
12- Line 1694: Parse error. syntax error
13- Line 1695: Parse error. syntax error
14- Line 1696: Parse error. invalid return
15- Line 1697: Parse error. syntax error
16- Line 5011: Parse error. illegal character
17- Line 5011: Parse error. missing ; before statement
18- Line 5011: Parse error. missing ; before statement
19- Line 5011: Parse error. unterminated regular expression literal
20- Line 5013: Parse error. missing ; before statement
21- Line 5014: Parse error. syntax error
22- Line 5018: Parse error. syntax error
23- Line 5020: Parse error. missing ; before statement
24- Line 5023: Parse error. syntax error
25- Line 5024: Parse error. syntax error
26- Line 5030: Parse error. syntax error
27- Line 5032: Parse error. missing ; before statement
28- Line 5035: Parse error. syntax error
29- Line 5036: Parse error. syntax error
30- Line 5042: Parse error. syntax error
31- Line 5044: Parse error. missing ; before statement
32- Line 5047: Parse error. syntax error
33- Line 5048: Parse error. syntax error
34- Line 5051: Parse error. syntax error
35- Line 5054: Parse error. missing ; before statement
36- Line 5060: Parse error. syntax error
37- Line 5062: Parse error. missing ; before statement
38- Line 5067: Parse error. syntax error
39- Line 5070: Parse error. missing ; before statement
40- Line 5071: Parse error. syntax error
41- Line 5090: Parse error. syntax error
42- Line 5092: Parse error. missing ; before statement
43- Line 5093: Parse error. missing ; before statement
44- Line 5094: Parse error. syntax error
45- Line 5095: Parse error. syntax error
46- Line 5097: Parse error. missing ; before statement
47- Line 5101: Parse error. syntax error
48- Line 5107: Parse error. syntax error
49- Line 5109: Parse error. missing ; before statement
50- Line 5117: Parse error. invalid return
51- Line 5143: Parse error. syntax error
52- Line 5909: Parse error. missing ; before statement
53- Line 5910: Parse error. missing ; before statement
54- Line 5911: Parse error. missing ; before statement
55- Line 5912: Parse error. missing ; before statement
56- Line 5913: Parse error. missing ; before statement
57- Line 5914: Parse error. missing ; before statement
58- Line 7181: Parse error. missing ; before statement
59- Line 7208: Parse error. syntax error
60- Line 7235: Parse error. illegal character
61- Line 7235: Parse error. illegal character
62- Line 7235: Parse error. missing ) after argument list
63- Line 7235: Parse error. missing ; before statement
64- Line 7235: Parse error. illegal character
65- Line 7235: Parse error. syntax error
66- Line 7237: Parse error. syntax error
67- Line 8196: Parse error. syntax error
68- Line 8472: Parse error. missing ; before statement
69- Line 10822: Parse error. syntax error
70- Line 10832: Parse error. missing ) in parenthetical
71- Line 10834: Parse error. syntax error
72- Line 10837: Parse error. invalid return
73- Line 10842: Parse error. invalid return
74- Line 10855: Parse error. illegal character
75- Line 10855: Parse error. missing ; before statement
76- Line 10855: Parse error. illegal character
77- Line 10858: Parse error. illegal character
78- Line 10858: Parse error. missing ; before statement
79- Line 10858: Parse error. illegal character
80- Line 10863: Parse error. illegal character
81- Line 10863: Parse error. missing ; before statement
82- Line 10863: Parse error. illegal character
83- Line 10866: Parse error. syntax error
84- Line 10868: Parse error. syntax error
85- Line 10869: Parse error. missing ; before statement
86- Line 10871: Parse error. syntax error
87- Line 10873: Parse error. syntax error
88- Line 10874: Parse error. missing ; before statement
89- Line 10911: Parse error. syntax error
90- Line 10913: Parse error. syntax error
91- Line 10926: Parse error. invalid return
92- Line 10932: Parse error. invalid return
93- Line 10946: Parse error. syntax error
94- Line 10950: Parse error. invalid return
95- Line 10951: Parse error. syntax error
96- Line 10954: Parse error. invalid return
97- Line 10960: Parse error. invalid return
98- Line 10961: Parse error. syntax error
99- Line 10963: Parse error. syntax error
100- Line 10966: Parse error. invalid return
101- Line 10971: Parse error. invalid return
102- Line 10976: Parse error. syntax error
103- Line 10977: Parse error. missing ; before statement
104- Line 10979: Parse error. syntax error
105- Line 10981: Parse error. missing ; before statement
106- Line 10986: Parse error. syntax error
107- Line 10989: Parse error. syntax error
108- Line 11000: Parse error. invalid return
109- Line 11003: Parse error. syntax error
110- Line 11004: Parse error. missing ; before statement
111- Line 11005: Parse error. syntax error
112- Line 11008: Parse error. syntax error
113- Line 11017: Parse error. invalid return
114- Line 11018: Parse error. syntax error
115- Line 11020: Parse error. syntax error
116- Line 11023: Parse error. invalid return
117- Line 11027: Parse error. invalid return
118- Line 11029: Parse error. syntax error
119- Line 11030: Parse error. syntax error
120- Line 11031: Parse error. syntax error
121- Line 11034: Parse error. syntax error
122- Line 11035: Parse error. missing ; before statement
123- Line 11038: Parse error. syntax error
124- Line 11039: Parse error. syntax error
125- Line 11041: Parse error. syntax error
126- Line 11042: Parse error. syntax error
127- Line 11045: Parse error. syntax error
128- Line 11047: Parse error. syntax error
129- Line 11049: Parse error. syntax error
130- Line 11051: Parse error. syntax error
131- Line 11053: Parse error. syntax error
132- Line 11056: Parse error. syntax error
133- Line 11062: Parse error. syntax error
134- Line 11065: Parse error. missing ; before statement
135- Line 11066: Parse error. missing ; before statement
136- Line 11067: Parse error. syntax error
137- Line 11071: Parse error. continue must be inside loop
138- Line 11076: Parse error. invalid return
139- Line 11077: Parse error. syntax error
140- Line 11083: Parse error. syntax error
141- Line 11084: Parse error. syntax error
142- Line 11085: Parse error. invalid return
143- Line 11085: Parse error. illegal character
144*/
145/// <reference name="MicrosoftAjax.js" />
146/// <reference name="Util.js" />
147/// <reference path="GlobalJSFunctionsDetail.js" />
148
149//Callback global variables for Slideshow.
150var callbackfnDocumentCenter = null;
151var callbackfnSlideshowSave = null;
152var $popUp_Slideshow = null;
153var parentID_Slideshow = null;
154var slideshowFolderDefault = '';
155var numbersOnly = new RegExp('^[0-9]*$');
156//Global variable for ThemeProperties modal
157var $popup_ThemeProperties = null;
158//Callback variables for Slideshow.
159var SetCursorPosition = null;
160
161// Prevents errors for Internet Explorer (modes prior to 9).
162// They will occur unless the developer tools are open.
163if (!window.console) {
164	var noop = function () { };
165
166	// Note: MSIE will override this once the dev. tools are open.
167	window.console = {
168		log: noop, clear: noop, warn: noop, error: noop, assert: noop,
169		dir: noop, count: noop, profile: noop, profileEnd: noop,
170		trace: noop, info: noop, memoryProfile: noop, memoryProfileEnd: noop,
171		exception: noop, debug: noop, dirxml: noop, group: noop, groupEnd: noop,
172		markTimeline: noop, time: noop, timeEnd: noop, groupCollapsed: noop
173	};
174}
175
176// User-agent sniffing for functions that rely on the user-agent
177// to determine version of Safari. Avoid using this variable and
178// check for the presence of features instead (best-practice).
179var isWebKit = (navigator.userAgent.toLowerCase().indexOf('webkit') > -1);
180
181// Determines if an array contains an object.
182// Uses == equality, case-sensitive. a containsExact() could do === equality.
183if (!Array.prototype.contains) {
184	Array.prototype.contains = function (item) {
185		for (var i = 0; i < this.length; i++) {
186			if (this[i] == item)
187				return true;
188		}
189		return false;
190	}
191}
192
193// Gets index of an item if it is present in the array, else returns -1.
194if (!Array.prototype.indexOf) {
195	Array.prototype.indexOf = function (item) {
196		for (var i = 0; i < this.length; i++) {
197			if (this[i] == item)
198				return i;
199		}
200		return -1;
201	}
202}
203
204// Implement ECMAScript 5 String.trim() and friends for browsers that
205// don't have it (e.g. Firefox prior to 3.5, Internet Explorer 6, 7, 8).
206if (!String.prototype.trim) {
207	String.prototype.trim = function () {
208		return this.replace(/^\s+/g, "").replace(/\s+$/g, "");
209	}
210	String.prototype.trimLeft = function () {
211		return this.replace(/^\s+/g, "");
212	}
213	String.prototype.trimRight = function () {
214		return this.replace(/\s+$/g, "");
215	}
216}
217
218// Implement .NET-style left-padding method.
219String.prototype.padLeft = function (desiredLength, paddingChar) {
220	paddingChar += '';
221	desiredLength = parseInt(desiredLength);
222
223	if (paddingChar.length > 1)
224		paddingChar = paddingChar.charAt(0);
225	else if (paddingChar.length < 1)
226		return this;
227
228	if (this.length >= desiredLength)
229		return this;
230	else {
231		var arr = new Array();
232		var padNum = desiredLength - this.length;
233
234		for (var i = 0; i < padNum; i++)
235			arr.push(paddingChar);
236
237		return arr.join('') + this;
238	}
239}
240
241// Implement .NET-style right-padding method.
242String.prototype.padRight = function (desiredLength, paddingChar) {
243	paddingChar += '';
244	desiredLength = parseInt(desiredLength);
245
246	if (paddingChar.length > 1)
247		paddingChar = paddingChar.charAt(0);
248	else if (paddingChar.length < 1)
249		return this;
250
251	if (this.length >= desiredLength)
252		return this;
253	else {
254		var arr = new Array();
255		var padNum = desiredLength - this.length;
256
257		for (var i = 0; i < padNum; i++)
258			arr.push(paddingChar);
259
260		return this + arr.join('');
261	}
262}
263
264String.isNullOrEmpty = function (text) {
265	return (text == null || text == '');
266}
267
268// Adds static method to regular expressions that escapes meta-characters.
269if (!RegExp.metaEscape) {
270	RegExp.metaEscape = function (text) {
271		if (text == null)
272			return null;
273		else if (typeof (text) != "string")
274			text += '';
275
276		return text.replace(/(\\|\/|\<|\>|\:|\.|\*|\+|\?|\$|\[|\]|\(|\)|\{|\}|\||\&)/g, '\\$1');
277	};
278}
279
280// Copies text data to clipboard in WebKit browsers (Chrome/Safari).
281function toWebkitClipboard(text) {
282	// Create element in DOM with text to copy.
283	var tmp = document.createElement('div');
284	tmp.textContent = text;
285	document.body.appendChild(tmp);
286
287	// Get current user selection, and remove selection current ranges.
288	var curSelection = window.getSelection();
289	curSelection.removeAllRanges();
290
291	// Create new selection range with DOM element containing text to copy.
292	var textRange = document.createRange();
293	textRange.selectNode(tmp);
294	curSelection.addRange(textRange);
295
296	// Execute COPY DHTML command.
297	document.execCommand("Copy");
298
299	// Clean-up.
300	document.body.removeChild(tmp);
301}
302
303// Copies value in stringVal to the clipboard, displaying the successMessage if hideAlert is false.
304// NOTE: Replace this with something like toWebkitClipboard() at some point.
305function toClipboardEx(stringVal, hideAlert, successMessage) {
306	if (window.clipboardData) {		// Internet Explorer
307		if (!window.clipboardData.setData("Text", stringVal) && !hideAlert)
308			hideAlert = true;
309	}
310	else if ((window.WebKitPoint || !window.netscape) && !window.opera) {
311		toWebkitClipboard(stringVal);
312	}
313	else if (window.netscape) {	// Mozilla Firefox and derivitives (Netscape, Seamonkey)...
314		try {
315			// Request full access to the XPCOM (Cross-Platform COM) API.
316			netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
317		}
318		catch (e) {
319			// Unable to obtain access, user rejected or setting in about:config not set right.
320			alert('Please type "about:config" in your browser and press enter. Type "signed.applets.codebase_principal_support" in Filter. Double click to change the value to "true". Then come back and click on the link again.\n\nIf you have already performed this action, make sure when you are asked whether to allow or deny the browser permission, that you are allowing it.');
321			return;
322		}
323
324		// Create an instance of the clipboard class.
325		var clipBoard = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
326
327		// Create an instance of the Transferable class (used to talk to the clipboard).
328		var clipTrans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
329
330		// Set clipboard format for text only.
331		clipTrans.addDataFlavor('text/unicode');
332
333		// Create XPCOM string, set data to copy of stringVal.
334		var clipString = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
335		var copyText = stringVal;
336		clipString.data = copyText;
337
338		// Note: This code may be bugged in some scenarios! 1 char does not always equal 2 bytes in UTF-16!
339		// Set data to transfer to the clipboard (length * 2, since 1 char is usually 2 bytes in UTF-16).
340		clipTrans.setTransferData("text/unicode", clipString, copyText.length * 2);
341
342		// Transfer data to the global clipboard.
343		clipBoard.setData(clipTrans, null, clipBoard.kGlobalClipboard);
344	}
345
346	if (!hideAlert)
347		alert(successMessage);
348
349	return true;
350}
351
352function toClipboard(stringVal, hideAlert) {
353	return toClipboardEx(stringVal, hideAlert, "The link has been copied to your clipboard.");
354}
355
356function getClipboard() {
357	if (window.clipboardData) {
358		return window.clipboardData.getData('Text');
359	} else if (window.netscape) {
360		try {
361			netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
362		}
363		catch (e) {
364			alert('Please type "about:config" in your browser and press enter. Type "signed.applets.codebase_principal_support" in Filter. Double click to change the value to "true". Then come back and click on the link again.\n\nIf you have already performed this action, make sure when you are asked whether to allow or deny the browser permission, that you are allowing it.');
365			return;
366		}
367
368		// Create instances of the Clipboard and Transferable objects.
369		var clipBoard = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
370		var clipTrans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
371
372		// Get data from global clipboard, place in clipTrans object.
373		clipTrans.addDataFlavor('text/unicode');
374		clipBoard.getData(clipTrans, clipBoard.kGlobalClipboard);
375
376		// Create objects to pass to getTransferData, which uses XPCOM String
377		// and Integer classes instead of those normally used by JavaScript.
378		var objStr = new Object(); var objNumBytes = new Object();
379		try {
380			clipTrans.getTransferData('text/unicode', objStr, objNumBytes);
381		}
382		catch (error) {
383			return '';
384		}
385
386		// Query whichever interface is available, opting to use nsISupportsWString.
387		if (objStr) {
388			if (Components.interfaces.nsISupportsWString)
389				objStr = objStr.value.QueryInterface(Components.interfaces.nsISupportsWString);
390			else if (Components.interfaces.nsISupportsString)
391				objStr = objStr.value.QueryInterface(Components.interfaces.nsISupportsString);
392			else
393				objStr = null;
394		}
395
396		// Note: This code may be bugged in some scenarios! 1 char does not always equal 2 bytes in UTF-16!
397		// Get data out of the XPCOM string and into a normal JS string.
398		if (objStr)
399			return (objStr.data.substring(0, objNumBytes.value / 2));
400	}
401	return;
402}
403
404// Gets the computed style of an element (browser-independent).
405var getCurrentStyle = (document.defaultView ?
406	function (elem) {
407		return document.defaultView.getComputedStyle(elem, '');
408	} :
409	function (elem) {
410		return elem.currentStyle;
411	}
412);
413
414// Gets children nodes of an HTML DOM element matching the tag name specified.
415function getChildNodesByTag(domElement, tagName) {
416	var cn = domElement.childNodes;
417	var nodesPresent = 0, retVal = new Array();
418	retVal.length = cn.length;
419
420	tagName = tagName.toUpperCase();
421	for (var cv = 0;
421 cv < cn.length; cv++) {
422		if (cn[cv].nodeType == 1 && cn[cv].nodeName == tagName)
423			retVal[nodesPresent++] = cn[cv];
424	}
425
426	return retVal.slice(0, nodesPresent);
427}
428
429// Returns true on Safari browsers 1.3.4 and older (bad date object behavior in old Safari).
430// Check does not work properly if user-agent has been modified by user.
431var isSafariVersion13OrOlder = (isWebKit ?
432	function () {
433		var navAppVersion = navigator.appVersion;
434		var phraseToFind = 'AppleWebKit/';
435		var foundStartAt = navAppVersion.indexOf(phraseToFind) + phraseToFind.length;
436		var foundEndAt = navAppVersion.indexOf(' ', foundStartAt + 1);
437		return (parseInt(navAppVersion.substring(foundStartAt, foundEndAt)) < 320);
438	} :
439	function () {
440		return false;
441	}
442);
443
444// Returns true on Safari browsers 2.0.4 and older (textbox/button not stylable before 3.x).
445// Check does not work properly if user-agent has been modified by user.
446var isSafariVersion20OrOlder = (isWebKit ?
447	function () {
448		var navAppVersion = navigator.appVersion;
449		var phraseToFind = 'AppleWebKit/';
450		var foundStartAt = navAppVersion.indexOf(phraseToFind) + phraseToFind.length;
451		var foundEndAt = navAppVersion.indexOf(' ', foundStartAt + 1);
452		return (parseInt(navAppVersion.substring(foundStartAt, foundEndAt)) < 525);
453	} :
454	function () {
455		return false;
456	}
457);
458
459// Returns true if an event fired too soon after another event.
460// Mechanism used on older Safari browsers to prevent
461// double-fire problems (especially with key presses).
462function safariEventRateLimitBlock() {
463	if (isWebKit && isSafariVersion13OrOlder()) {
464		if (safariRateLimited != 0)
465			return true;
466		else {
467			safariRateLimited = setTimeout('safariRateLimited = 0;', 10);
468			return false;
469		}
470	}
471}
472
473// Get coordinates relative to document (works out container issues).
474// Wrote this so it works in quirks or standards mode.
475function getDocumentCoordinates(element) {
476	var htmlElem = document.body.parentNode;
477	var bodyElem = document.body;
478	var pos = { "x": 0, "y": 0 };
479	pos.toString = function () { return this.x + ', ' + this.y; }
480	while (element != null) {
481		pos.x += element.offsetLeft;
482		pos.y += element.offsetTop;
483		switch (element.offsetParent) {
484			case htmlElem:
485			case bodyElem:
486			case null:
487				return pos;
488		}
489		element = element.offsetParent;
490	}
491}
492
493// Attach an event handler to an object (browser-independent).
494// First clause is W3C DOM method, second is DHTML (IE).
495var addEvent = (window.addEventListener ?
496	function (obj, evType, fn, useCapture) {
497		try {
498			obj.addEventListener(evType, fn, useCapture);
499		} catch (e) { }
500		return true;
501	} :
502	function (obj, evType, fn, useCapture) {
503		try {
504			return obj.attachEvent('on' + evType, fn);
505		} catch (e) { }
506	}
507);
508
509// Release an event handler from an object (browser-independent).
510// First clause is W3C DOM method, second is DHTML (IE).
511var removeEvent = (window.removeEventListener ?
512	function (obj, evType, fn, useCapture) {
513		try {
514			obj.removeEventListener(evType, fn, useCapture);
515		} catch (e) { }
516		return true;
517	} :
518	function (obj, evType, fn, useCapture) {
519		try {
520			obj.detachEvent('on' + evType, fn);
521		} catch (e) { }
522		return true;
523	}
524);
525
526// Stops a DOM event from propagating further than the current handler.
527// Note: Returning false from event handlers in IE 6/7/8 does the same thing.
528function stopEventPropagation(evObj) {
529	if (evObj.preventDefault)
530		evObj.preventDefault();
531
532	// Calling cancelButton after stopPropagation
533	// may negate the stopPropagation so do not do it. -KB
534	if (evObj.stopPropagation)
535		evObj.stopPropagation();
536	else if (evObj.cancelBubble)
537		evObj.cancelBubble();
538}
539
540// These functions assists in obscuring email addresses:
541function mailTo(obj) {
542	//alert('mailto:'+eval(obj.getAttribute('id')));
543	obj.setAttribute('href', 'mailto:' + eval(obj.getAttribute('id')));
544}
545
546function js_mail(obj, Emails) {
547	var mail_link = Emails[0];
548	for (var email = 1; email < Emails.length; email++)
549		if (Emails[email] != null && Emails[email] != '' && Emails[email].substr(1, 4) != 'href') mail_link = mail_link + Emails[email];
550
551	obj.setAttribute('href', 'mailto:' + mail_link);
552}
553
554// Used to prevent right-click menu from appearing for some clients that wanted this ability.
555function antiContextMenuHook() {
556	// Note: Opera is not hookable.
557	var showAlert = function () { alert('All images are protected by Copyright. Do not use without permission.'); }
558	var mdClick = function (e) {
559		if (!document.all) {
560			if (e.button == 2 || e.button == 3)
561				showAlert();
562		}
563		else if (event && event.button == 2)
564			showAlert();
565	}
566	var cmClick = function (e) {
567		if (navigator.userAgent.toLowerCase().indexOf('khtml') > -1) {
568			// Safari, Konquerer
569			if (e.preventDefault)
570				e.preventDefault();
571			showAlert();
572		}
573		if (e.stopPropagation)
574			e.stopPropagation(); // Mozilla Firefox 2.0
575		return false; // IE 6.0 and 7.0
576	}
577	document.onmousedown = mdClick;
578	document.oncontextmenu = cmClick;
579}
580
581// Form validation functions:
582function RegExValidate(expression, value, param) {
583    var re = new RegExp(expression, param);
584    if (value != '' && value != undefined) {
585        if (value.match(re)) return true;
586        else return false;
587    }
588    else return true;
589}
590
591// Used for validating emailaddress for special scenarios like continuous periods. - VB
592function checkSpecialScenarios(s) {
593    var bugchars = '!#$^&*()|}{[]?><~%:;/,=`"'; 
594	var i;
595	var lchar = "";
596	// Search through string's characters one by one.
597	// If character is not in bag.
598	for (i = 0; i < s.length; i++) {
599		// Check that current character isn't whitespace.
600		var c = s.charAt(i);
601		if (i > 0) lchar = s.charAt(i - 1)
602		if (bugchars.indexOf(c) != -1 || (lchar == "." && c == ".")) return false;
603	}
604	return true;
605}
606
607// JavaScript version of CivicPlus.CMS.Site.Validation.IsValidEmailAddress();
608function emailValidate(emailAddress) {
609	var emailAddressTrimmed = TrimString(emailAddress + "");
610	if (emailAddressTrimmed != "") {
611		if (checkSpecialScenarios(emailAddressTrimmed) == false)
612			return false;
613		if (emailAddressTrimmed.replace(/[^@]/g, '').length > 1)
614			return false;
615		var parts = emailAddressTrimmed.splitRemoveEmpties('@');
616		if (emailAddressTrimmed.substr(emailAddressTrimmed.length - 1) == '@')
617			return false;
618		if (parts.length == 2) {
619			for (var i = 0; i < parts.length; i++) {
620				if (((!RegExValidate('^[A-Z0-9]$', parts[i].substr(0, 1), 'i') || !RegExValidate('^[A-Z0-9]$', parts[i].substr(parts[i].length - 1), 'i')) && i == 1) || (!RegExValidate('^[A-Z0-9_%-\\.]+$', parts[i].substr(0, parts[i].length - 1), 'i')))
621					return false;
622			}
623			var lastDotPos = parts[1].lastIndexOf('.');
624			if (lastDotPos < 0 || parts[1].substr(lastDotPos).length < 3 || (!RegExValidate('^[A-Z]+$', parts[1].substr(lastDotPos + 1), 'i')))
625				return false;
626			else
627				return true;
628		}
629		else
630			return false;
631	}
632	else
633		return false;
634}
635
636// Returns: 0 - success, 1 - illegal value, 2 - too large, 3 - too small, 4 - blank.
637function intValidateWithRange(value, min, max) {
638	if (value == '' || value == null) return 4;
639	if (RegExValidate('^(-|)[0-9]*$', value, 'i')) {
640		try { var pint = parseInt(value); } catch (ex) { return 1; }
641		if (pint < min) return 3; else if (pint > max) return 2; return 0;
642	} else
643		return 1;
644}
645
646// Split function that remotes empty entries.
647String.prototype.splitRemoveEmpties = function (separator, howmany) {
648	var splitArr;
649	var returnArr = new Array();
650
651	if (arguments.length == 2)
652		splitArr = this.split(separator, howmany);
653	else
654		splitArr = this.split(separator);
655
656	for (var i = 0; i < splitArr.length; i++) {
657		if (splitArr[i] != '')
658			returnArr.push(splitArr[i]);
659	}
660
661	return returnArr;
662}
663
664// JavaScript equivalent of a function in GlobalFunctionsDetail.aspx.
665// Do not use this function unless you have a good reason (e.g. textarea length on client must match size on server).
666// KNOWN: Does not do entities properly, matches server behavior (where's the semi-colon?).
667function SQLSafe(strInput) {
668	return strInput.replace(/\'/g, "&#39").replace(/\"/g, "&#34");
669}
670
671// Returns true if the string is empty. Will blow up on NULLs.
672function FieldIsEmpty(strInput) {
673	if (strInput == undefined)
674		return true;
675	return TrimString(strInput).length == 0;
676}
677
678// Removes leading and trailing white space from a string. Will blow up on NULLs.
679function TrimString(strInput) {
680	return strInput.replace(/^\s+/g, "").replace(/\s+$/g, "");
681}
682
683// Returns true if the value is an integer value.
684function isInteger(strInput) {
685	var leadingZeros = calculateLeadingZeroStrings(strInput);
686
687	return leadingZeros == strInput || (strInput == leadingZeros + parseInt(strInput).toString());
688}
689
690// Returns true if the value is a real number.
691function isRealNumber(strInput) {
692	var leadingZeros = calculateLeadingZeroStrings(strInput);
693
694	return leadingZeros == strInput || (strInput == leadingZeros + parseFloat(strInput));
695}
696
697function calculateLeadingZeroStrings(strInput) {
698	var leadingZeros = "";
699
700	if (strInput != null) {
701	for (var i = 0; i < strInput.length; i++) {
702		if (strInput[i] == "0") {
703			leadingZeros += "0";
704		}
705		else {
706			break;
707		}
708	}
709	}
710
711	return leadingZeros;
712}
713
714// Date validator class.
715function dateValidator() {
716	this.firstValidDate = new Date('01/01/1753');
717	this.lastValidDate = new Date('01/01/3000');
718	this.strStartDateID = 'Start/Begin Date';
719	this.strEndDateID = 'End/Stop/Expiration Date';
720	this.strStartTimeID = 'Start Time';
721	this.strEndTimeID = 'End Time';
722	this.ysnRequireStartDateIfEndSpecified = false;
723	this.ysnStartDateRequired = false;
724	this.ysnEndDateRequired = false;
725	this.ysnStartTimeRequired = false;
726	this.ysnEndTimeRequired = false;
727	this.ysnAllowEqualDates = false;
728	this.ysnAllowTimeOnly = false;
729	this.ysnCent = false; //Allow only four digit years
730	var dtiEndDate;
731	var dtiStartDate;
732	var dtiStartTime;
733	var dtiEndTime;
734	this.timesAlreadyValidated = false;
735	this.datesAlreadyValidated = false;
736
737	this.setStartDate = function (date) {
738		dtiStartDate = this.cleanDate(date);
739	}
740
741	this.setEndDate = function (date) {
742		dtiEndDate = this.cleanDate(date);
743	}
744
745	this.setStartDateRequired = function (required) {
746		this.ysnStartDateRequired = required;
747	}
748
749	this.setEndDateRequired = function (required) {
750		this.ysnEndDateRequired = required;
751	}
752
753	this.setRequireStartDateIfEndSpecified = function (required) {
754		this.ysnRequireStartDateIfEndSpecified = required;
755	}
756
757	this.cleanDate = function (date) {
758		if (date) {
759			if (typeof isMobileView != 'undefined' && isMobileView) {
760				date = this.ChangeDateFormatForMobileView(date);
761			}
762			else if (RegExValidate('^([0-9-\\/]*?)([0-9]{2,4})$', date, 'i')) {
763				var year = RegExp.$2;
764				if (year.length == 2) {
765					if (year >= 50) date = RegExp.$1 + "19" + year;
766					else date = RegExp.$1 + "20" + year;
767				}
768				date = date.replace('\-', '/', 'g');
769			}
770		}
771		return date;
772	}
773
774	this.ChangeDateFormatForMobileView = function (date) {
775		var rxDatePattern = /^\d{4}\-\d{1,2}\-\d{1,2}$/; //Regex for yyyy-mm-dd format
776		var match = date.match(rxDatePattern);
777		if (match != null) {
778			var dateArray = date.split('-');
779			var dateFormat = getDateFormat().toLowerCase();
780			if (dateFormat == "mm/dd/yyyy")
781				date = dateArray[1] + '/' + dateArray[2] + '/' + dateArray[0];
782			else if (dateFormat == "dd/mm/yyyy")
783				date = dateArray[2] + '/' + dateArray[1] + '/' + dateArray[0];
784		}
785		return date;
786	}
787
788	this.dateValidate = function (dtiDate, ysnRequired, strID) {
789		if (!ysnRequired && (dtiDate == null || dtiDate == '')) return true;
790		else if (ysnRequired && (dtiDate == null || dtiDate == '')) {
791			if (strID) this.error = strID + ' cannot be blank.';
792			else this.error = ' cannot be blank';
793			this.errorNumber = 1;
794			return false;
795		}
796		else if (RegExValidate('^(1[0-2]|0?[1-9])(/|-)(0?[1-9]|[1-2][0-9]|3[0-1])\\2([0-9]{4}|[0-9]{2})$', dtiDate, 'i')) {
797			var month = RegExp.$1;
798			var day = RegExp.$3;
799			var year = RegExp.$4;
800
801			if (year.length == 2 && this.ysnCent == true) {
802				if (strID) this.error = strID + ' requires a four digit year';
803				else this.error = 'Please use a four digit year';
804				return false;
805			}
806			if (year.length == 4 && (year > 3000 || year < 1753)) {
807				this.error = dtiDate + '\nis outside of the date range.';
808				this.errorNumber = 2;
809				return false;
810			}
811			if (day == 31 && (month == 4 || month == 6 || month == 9 || month == 11)) {
812				this.error = 'This month doesn\'t have 31 days';
813				this.errorNumber = 3;
814				return false;
815			}
816			if (day >= 30 && month == 2) {
817				this.error = 'February doesn\'t have ' + day + ' days';
818				this.errorNumber = 4;
819				return false;
820			}
821			if (month == 2 && day == 29 && !(year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))) {
822				this.error = 'This is not a leap year\nFebruary doesn\'t have 29 days.';
823				this.errorNumber = 5;
824				return false;
825			}
826			return true;
827		} else {
828			if (strID) this.error = strID + ' is not a valid date format.\nPlease use ' + getDateFormat().toUpperCase() + '.';
829			else this.error = dtiDate + '\n is an invalid date format.\nPlease use ' + getDateFormat().toUpperCase() + '.';
830			this.errorNumber = 6;
831			return false;
832		}
833		return false;
834	}
835
836	this.dateOrderValidate = function () {
837		if (this.dateValidate(dtiStartDate, this.ysnStartDateRequired, this.strStartDateID) && this.dateValidate(dtiEndDate, this.ysnEndDateRequired, this.strEndDateID)) {
838			if (this.ysnRequireStartDateIfEndSpecified && !dtiStartDate && dtiEndDate) {
839				this.error = 'A Start Date must be specified if an End Date was entered.';
840				this.errorNumber = 9;
841				return false;
842			}
843			if (!dtiStartDate || !dtiEndDate) return true;
844			else {
845				var StartDate = new Date(dtiStartDate);
846				var EndDate = new Date(dtiEndDate);
847			}
848			if (StartDate.getTime() < EndDate.getTime()) return true;
849			else if (StartDate.getTime() == EndDate.getTime() && this.ysnAllowEqualDates == true) {
850				this.ysnDatesAreEqual = true;
851				return true;
852			} else {
853				this.error = 'The End Date must be after the Start Date.';
854				this.errorNumber = 7;
855				return false;
856			}
857		}
858		else return false;
859	}
860
861	this.dateValidateNew = function (dtiDate, ysnRequired, strID) {
862		var month;
863		var day;
864		var year;
865		if (dtiDate === undefined)
866			dtiDate = '';
867
868        if (!ysnRequired && (dtiDate == '' || !dtiDate)) return true;
869
870		if (ysnRequired && dtiDate == '') {
871			if (strID) this.error = strID + ' is required';
872			else this.error = ' is required';
873			this.errorNumber = 1;
874			return false;
875		}
876
877		var dateFormat = getDateFormat().toLowerCase();
878
879		if (typeof isMobileView != 'undefined' && isMobileView) {
880			dtiDate = this.ChangeDateFormatForMobileView(dtiDate);
881		}
882
883		if ((dateFormat == "mm/dd/yyyy") && (RegExValidate('^(1[0-2]|0?[1-9])(/|-)(0?[1-9]|[1-2][0-9]|3[0-1])\\2([0-9]{4}|[0-9]{2})$', dtiDate, 'i'))) {
884			month = RegExp.$1;
885			day = RegExp.$3;
886			year = RegExp.$4;
887
888			return this.validDateParts(month, day, year);
889		}
890
891		if ((dateFormat == "dd/mm/yyyy") && (RegExValidate('^(0?[1-9]|[1-2][0-9]|3[0-1])(/|-)(1[0-2]|0?[1-9])\\2([0-9]{4}|[0-9]{2})$', dtiDate, 'i'))) {
892			month = RegExp.$3;
893			day = RegExp.$1;
894			year = RegExp.$4;
895
896			return this.validDateParts(month, day, year);
897		}
898
899		if (strID) this.error = strID + ' is not a valid date format.\nPlease use ' + dateFormat.toUpperCase() + '.';
900		else this.error = dtiDate + '\n is an invalid date format.\nPlease use ' + dateFormat.toUpperCase() + '.';
901		this.errorNumber = 6;
902
903		return false;
904	}
905
906	this.validDateParts = function (month, day, year) {
907		if (year.length == 2 && this.ysnCent == true) {
908			if (strID) this.error = strID + ' requires a four digit year';
909			else this.error = 'Please use a four digit year';
910			return false;
911		}
912		if (year.length == 4 && (year > 3000 || year < 1753)) {
913			this.error = dtiDate + '\nis outside of the date range.';
914			this.errorNumber = 2;
915			return false;
916		}
917		if (day == 31 && (month == 4 || month == 6 || month == 9 || month == 11)) {
918			this.error = 'This month doesn\'t have 31 days';
919			this.errorNumber = 3;
920			return false;
921		}
922		if (day >= 30 && month == 2) {
923			this.error = 'February doesn\'t have ' + day + ' days';
924			this.errorNumber = 4;
925			return false;
926		}
927		if (month == 2 && day == 29 && !(year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))) {
928			this.error = 'This is not a leap year\nFebruary doesn\'t have 29 days.';
929			this.errorNumber = 5;
930			return false;
931		}
932		return true;
933	}
934
935	this.dateOrderValidateNew = function () {
936		//If sending in US format run dateValidateNew first becuase it expects dates in daybeforemonth format
937		if (this.datesAlreadyValidated || (this.dateValidateNew(dtiStartDate, this.ysnStartDateRequired, this.strStartDateID) && this.dateValidateNew(dtiEndDate, this.ysnEndDateRequired, this.strEndDateID))) {
938			if (this.ysnRequireStartDateIfEndSpecified && !dtiStartDate && dtiEndDate) {
939				this.error = 'A Start Date must be specified if an End Date was entered.'
940				this.errorNumber = 9; return false;
941			}
942			if (!dtiStartDate || !dtiEndDate || dtiEndDate == "NaN/NaN/NaN" || dtiStartDate == "NaN/NaN/NaN") return true;
943			else {
944				//Expects dates in US format 
945				var StartDate = new Date(dtiStartDate);
946				var EndDate = new Date(dtiEndDate);
947			}
948			if (StartDate.getTime() < EndDate.getTime()) return true;
949			else if (StartDate.getTime() == EndDate.getTime() && this.ysnAllowEqualDates == true) {
950				this.ysnDatesAreEqual = true;
951				return true;
952			}
953			else {
954				this.error = 'The End Date must be after the Start Date.';
955				this.errorNumber = 7; return false;
956			}
957		}
958		else return false;
959	}
960
961	this.getStandardDate = function (dateText) {
962		$.ajax({
963			url: '/Utility/GetDate?dateText=' + dateText,
964			async: false,
965			type: 'GET',
966			dataType: 'json',
967			success: function (data) {
968				dateText = data.date;
969			},
970			error: function (jqXHR, textStatus, errorThrown) {
971			}
972		});
973
974		return dateText;
975	}
976
977	this.smallDateTimeMaxValueValidate = function () {
978		var StartDate = new Date(dtiStartDate);
979		var EndDate = new Date(dtiEndDate);
980		var MaxDate = new Date('05/06/2079 23:59:59');
981		var result = true;
982		if (StartDate <= MaxDate && EndDate <= MaxDate) {
983			result = true;
984		}
985		else if (StartDate > MaxDate) {
986			this.error = "The Start Date must be less than '5/6/2079'.";
987			this.errorNumber = 2;
988			result = false;
989		}
990		else if (EndDate > MaxDate) {
991			this.error = "The End Date must be less than '5/6/2079'.";
992			this.errorNumber = 3;
993			result = false;
994		}
995		return result;
996	}
997
998	this.format = function (format, date) {
999		if (!date) date = new Date();
1000		var day = date.getDate();
1001		var month = date.getMonth() + 1;
1002		var year = date.getFullYear();
1003		return format.toLowerCase().replace(/dd/g, day).replace(/mm/g, month).replace(/y{1,4}/g, year)
1004	}
1005
1006	this.timeValidate = function (ditTime, ysnRequired, strID) {
1007		if (!ysnRequired && ditTime == '') return true;
1008		else if (ysnRequired && ditTime == '') {
1009			if (strID) this.error = strID + ' is required';
1010			else this.error = 'Time is required';
1011			this.errorNumber = 1;
1012			return false;
1013		}
1014		else if (RegExValidate('^(1[0-2]|0?[1-9]):([0-5]?[0-9])(:([0-5][0-9]))?$', ditTime, 'i')) return true;
1015		else {
1016			if (strID) this.error = strID + ' is not a valid time format. Please use H
1016H:MM.';
1017			else this.error = ' is not a valid time format. Please use HH:MM.';
1018			this.errorNumber = 8;
1019			return false;
1020		}
1021	}
1022
1023	this.timeValidate24Hour = function (ditTime, ysnRequired, strID) {
1024		if (!ysnRequired && ditTime == '') return true;
1025		else if (ysnRequired && ditTime == '') {
1026			if (strID) this.error = strID + ' is required';
1027			else this.error = 'Time is required';
1028			this.errorNumber = 1;
1029			return false;
1030		}
1031		else if (RegExValidate('^([01]?[0-9]|2[0-3]):([0-5]?[0-9])(:([0-5][0-9]))?$', ditTime, 'i')) return true;
1032		else {
1033			if (strID) this.error = strID + ' is not valid.';
1034			else this.error = ' is not valid.';
1035			this.errorNumber = 8;
1036			return false;
1037		}
1038	}
1039	this.timeOrderValidate = function () {
1040		if (!this.ysnAllowTimeOnly && ((!dtiStartDate && this.dtiStartTime) || (!dtiEndDate && this.dtiEndTime))) {
1041			this.error = 'You only submited a time.\nPlease provide a day as well.';
1042			this.errorNumber = 10;
1043			this.startDateBlank = (!dtiStartDate && this.dtiStartTime);
1044			this.endDateBlank = (!dtiEndDate && this.dtiEndTime);
1045			return false;
1046		}
1047		if (this.timesAlreadyValidated || (this.timeValidate(this.dtiStartTime, this.ysnStartTimeRequired, this.strStartTimeID) && this.timeValidate(this.dtiEndTime, this.ysnEndTimeRequired, this.strEndTimeID))) {
1048			if (!this.ysnDatesAreEqual) return true;
1049
1050			if (!this.dtiStartTime && !this.ysnStartTimeRequired) return true;
1051			if (!this.dtiEndTime && !this.ysnEndTimeRequired) return true;
1052			
1053			var dtiStartTime = this.convertTo24Hour(this.dtiStartTime, this.strStartAMPM, dtiStartDate);
1054			var dtiEndTime = this.convertTo24Hour(this.dtiEndTime, this.strEndAMPM, dtiEndDate);
1055
1056			if (dtiStartTime.getTime() < dtiEndTime.getTime()) return true;
1057			else if (dtiStartTime.getTime() == dtiEndTime.getTime() && this.ysnAllowEqualTimes == true) {
1058				this.ysnTimesAreEqual = true;
1059				return true;
1060			}
1061			else {
1062				this.error = 'The End Time must be after the Start Time if the Start and End Dates are the same.'
1063				this.errorNumber = 9;
1064				return false;
1065			}
1066		}
1067		return false;
1068	}
1069
1070	this.convertTo24Hour = function (time, AMPM, date) {
1071		if (!date) date = "1/1/70";
1072
1073		var dtTime = time.indexOf(AMPM) == -1 ? new Date(date + " " + time + " " + AMPM) : new Date(date + " " + time);
1074		if (dtTime == 'Invalid Date') {
1075			var dayBeforeMonthOn = getDateFormat().toLocaleLowerCase() == "dd/mm/yyyy" ? true : false;
1076			if (dayBeforeMonthOn) {
1077				var dateArray = date.split('/');
1078				date = dateArray[1] + '/' + dateArray[0] + '/' + dateArray[2];
1079				dtTime = time.indexOf(AMPM) == -1 ? new Date(date + " " + time + " " + AMPM) : new Date(date + " " + time);
1080			}
1081		}
1082		return dtTime;
1083	}
1084}
1085
1086// Helper function for inputAlert().
1087function inputEmailValidate(obj, required) {
1088	if (required == null || required == false)
1089		return (obj.value == '' || emailValidate(obj.value) == true)
1090	else
1091		return (obj.value != '' && emailValidate(obj.value) == true)
1092}
1093
1094// Note: This function does not match standard validation behavior! Users are supposed to see
1095// a summary of problems with their inputs and not be alerted multiple times!
1096// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
1097// Calls another validation routine, and determines success/failure on result of call (true/false).
1098// Displays error message on validation failure. Returns result of call.
1099function inputAlert(call, obj, required, errorMessage) {
1100	call = eval('input' + call + 'Validate');
1101	if (call(obj, required) == false) {
1102		if (errorMessage == null)
1103			errorMessage = 'Please enter a single valid email address without any extra body, subject, etc. information (ie [email protected]).';
1104		obj.setAttribute('autocomplete', 'off');
1105		obj.focus();
1106		obj.setAttribute('autocomplete', 'on');
1107		alert(errorMessage);
1108		return false;
1109	}
1110	else
1111		return true;
1112}
1113
1114// Takes array of required fields and checks whether they have a value or not
1115// If empty fields found, formats a javascript alert to inform the user and returns true
1116function checkRequiredFieldsEmpty(requiredFieldList) {
1117	var badList = new Array();
1118	for (var i = 0, len = requiredFieldList.length; i < len; i++) {
1119		var $this = requiredFieldList[i];
1120		var $fieldId = $('#' + $this);
1121		if (($fieldId.length > 0) && (FieldIsEmpty($fieldId.val()))) {
1122			var $label = $('label[for=' + $this + ']');
1123			if ($label.length > 0)
1124				badList.push($label.text().trim());
1125			else
1126				badList.push($this);
1127		}
1128	}
1129	if (badList.length > 0) {
1130		var msg = badList.join(" cannot be blank.\r\n");
1131		msg += " cannot be blank.";
1132		msg = msg.replace(/\*/g, '');
1133		alert(msg);
1134		return true;
1135	}
1136	return false;
1137}
1138// End Form Validation functions.
1139
1140// Begin AJAX functions:
1141// See http://blogs.msdn.com/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx
1142// If you are curious why the XMLHTTP versions specified are and why others are not.
1143function makeErrorRequest(url, status) {
1144	var http_error_request = false;
1145	var origin = location.pathname;
1146
1147	if (window.XMLHttpRequest) { // Mozilla, Safari, IE7
1148		http_error_request = new XMLHttpRequest();
1149		if (http_error_request.overrideMimeType)
1150			http_error_request.overrideMimeType("text/html");
1151	} else if (window.ActiveXObject) { // IE6
1152		try {
1153			http_error_request = new ActiveXObject("Msxml2.XMLHTTP.6.0");
1154		} catch (e) {
1155			try {
1156				http_error_request = new ActiveXObject("Msxml2.XMLHTTP"); // Version 3.0
1157			} catch (e) { }
1158		}
1159	}
1160
1161	http_error_request.onreadystatechange = function () { }
1162	http_error_request.open("GET", "/AJAX-error.ashx?url=" + escape(url) + "&status=" + status + "&origin=" + escape(origin), true);
1163	http_error_request.send(null);
1164	//if(status == 403)
1165	//window.location = '/admin/AccessDenied.aspx?fromURL=' + window.location.pathname.substr(7);
1166}
1167
1168// Makes AJAX request, additionally supporting POST data (makeHttpRequest doesn't).
1169// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
1170// Note: It's YOUR responsibility as a developer to make sure data
1171// placed in formData is formatted as it should be. Form data should be
1172// in Query String format with the value portions escape()'d. -KB
1173function makeHttpRequestEx(URL, formData, callbackFunc, ysnReturnXML) {
1174
1175	URL = window.location.origin + URL;
1176
1177	if (formData != null) {
1178		$.ajax({
1179			type: 'POST',
1180			url: URL,
1181			data: formData,
1182			success: callbackFunc
1183		});
1184	}
1185	else {
1186		$.ajax({
1187			type: 'GET',
1188			url: URL,
1189			success: callbackFunc
1190		});
1191}
1192}
1193
1194// NOTE: Do not use this in new code, use $.ajax() instead.
1195// Makes AJAX request. Used in n-menu code.
1196function makeHttpRequest(url, callback_function, return_xml) {
1197	var http_request = false;
1198
1199	if (window.XMLHttpRequest) { // Mozilla, Safari, IE7
1200		http_request = new XMLHttpRequest();
1201		if (http_request.overrideMimeType && !return_xml)
1202			http_request.overrideMimeType("text/html");
1203	} else if (window.ActiveXObject) { // IE6
1204		try {
1205			http_request = new ActiveXObject("Msxml2.XMLHTTP.6.0");
1206		} catch (e) {
1207			try {
1208				http_request = new ActiveXObject("MSxml2.XMLHTTP"); // Version 3
1209			} catch (e) { }
1210		}
1211	}
1212
1213	if (!http_request) {
1214		alert("Unfortunately, your browser doesn't support this feature.");
1215		return false;
1216	}
1217
1218	http_request.onreadystatechange = function () {
1219		if (http_request.readyState == 4) {
1220			--ajax_call_counter;
1221
1222			//try {
1223			if (http_request.status == 200) {
1224				if (return_xml)
1225					eval(callback_function + ', http_request.responseXML)');
1226				else {
1227					if (http_request.responseText.search(/<form action='error.asp' method=post>/i) < 0)
1228						eval(callback_function + ', http_request.responseText)');
1229					else
1230						makeErrorRequest(url, http_request.status);
1231				}
1232			}
1233			else if (http_request.status)
1234				makeErrorRequest(url, http_request.status);
1235			//} catch (e) {
1236			// If this happens, there is no way to notify anyone
1237			// of the previous error. It might be their connection died,
1238			// or failed in some other way.
1239
1240			//alert('An error occured while reporting the previous error.');
1241			//var USER_EXPLAIN_ERR_EN = '\n\nTechnical Details:\n' + e.name + ' - ';
1242			// IE 6 & 7: No Line Number, No Filename
1243			//if (document.all && !window.opera) {
1244			//	alert(USER_EXPLAIN_ERR_EN + e.description + ' (line unavailable, code: ' + e.number + ')' + '\n\nJavaScript Callback:\n' + callback_function + ', <responseData>);');
1245			//}
1246			// Opera and Firefox 1.5+: Line Number + Filename
1247			//else {
1248			//	alert(USER_EXPLAIN_ERR_EN + e.message + '\n' + e.fileName + ', line ' + e.lineNumber + '\n\nJavaScript Callback:\n' + callback_function + ', <responseData>);');
1249			//}
1250			//}
1251
1252			http_request = null;
1253		}
1254	}
1255
1256	http_request.open("GET", url, true);
1257	http_request.send(null);
1258}
1259// Invoked on window.onunload for pages using synchronous AHAH.
1260// Catches switches to different pages and window closes.
1261// -=-=-=-=-
1262// Note: It is synchronous instead of asynchronous to ensure
1263// the operation completes before a close. This is SHAH.
1264//
1265function destroyAHAH(e) {
1266	var http_request;
1267
1268	if (window.XMLHttpRequest) { // Mozilla, Safari, IE7
1269		http_request = new XMLHttpRequest();
1270		if (http_request.overrideMimeType) {
1271			http_request.overrideMimeType("text/html");
1272		}
1273	} else if (window.ActiveXObject) { // IE6
1274		try {
1275			http_request = new ActiveXObject("MSXML2.XMLHTTP.6.0");
1276		} catch (e) {
1277			try {
1278				http_request = new ActiveXObject("MSXML2.XMLHTTP"); // Version 3
1279			} catch (e) { }
1280		}
1281	}
1282
1283	if (!http_request) return;
1284	http_request.open("GET", 'http://' + window.location.host + '/AJAX-NMenuLoader.ashx?clearCache=1', false);
1285	http_request.send(null);
1286	//alert(http_request.status + ': if 200, the session cache object was term\'d where needed be.');
1287}
1288// End AJAX functions.
1289
1290//
1291//  slideShow class
1292//  vars:
1293//  slideShowId						constructor param for the id of the image that will have the Slide Show
1294//  slideShowLink					constructor param for the id of the link that will be around the image that has Slide Show, use '' for no link
1295//  slideShowSpeed					optional constructor param for the speed of the slide show, default = 5000
1296//  filterName						optional constructor param for the IE filter, default = blendTrans
1297//  filterAttr1						optional constructor param for the IE filter, default = duration=3
1298//  filterAttr2						optional constructor param for the IE filter
1299//  filterAttr3						optional constructor param for the IE filter
1300//  j								counter for the object
1301//  picArr							array of pictures
1302//  altArr							array of alt text
1303//  linkArr							array of links
1304//  methods:
1305//  addImage(n, img, alt, caption, lngCaption, link)	add an image with alt text and a link, n specifies which postion in the arrays
1306//  runSlideShow()					continually calls nextSlide to run the Slide Show
1307//  nextSlide()						applies the transition and advances the Slide Show image 1 spot in the arrays
1308//  mouseOver()						detects and loads that image to the Main Image Display & draws border around the slected 
1308image & removed border from the Other small image icons
1309function slideShow(slideShowId, slideShowLink, slideShowSpeed, filterName, filterAttr1, filterAttr2, filterAttr3, slideShowLinkTarget, layout, externalLink) {
1310	if (!slideShowLinkTarget || slideShowLinkTarget == null || slideShowLinkTarget == "undefined" || slideShowLinkTarget == "")
1311		slideShowLinkTarget = "_self";
1312	if (!layout || layout == null || layout == "undefined")
1313		layout = 1;
1314
1315	this.slideShowId = document.getElementById(slideShowId);
1316
1317	this.picArr = new Array();
1318	this.altArr = new Array();
1319	this.captionArr = new Array();
1320	this.lngCaptionArr = new Array();
1321	this.linkArr = new Array();
1322	this.linkTargetArr = new Array();
1323	var useStyle = false;
1324	var captionFilter = "";
1325	var cssRule = false;
1326	var pos = 0;
1327
1328	//Get The filter for IE.//
1329	for (i = 0; i < document.styleSheets.length; i++) {
1330		var styles = document.styleSheets[i];
1331		do {
1332			if (styles.href && styles.href.indexOf("style.css") > -1) {
1333				if (styles.cssRules) {
1334					cssRule = styles.cssRules[pos];
1335				}
1336				else if (styles.rules) {
1337					cssRule = styles.rules[pos];
1338				}
1339			}
1340			if (cssRule && cssRule.selectorText != undefined && cssRule.selectorText.indexOf('slideCaption') != -1) {
1341				useStyle = true;
1342				captionFilter = cssRule.style.filter;
1343				break;
1344			}
1345			pos++;
1346		} while (cssRule && !useStyle)
1347		if (useStyle) break;
1348	}
1349	var useStyle = $('.slideCaption').attr('class') == 'slideCaption';
1350
1351	// If junk data causes one slideshow to fail the others should not.
1352	if (this.slideShowId == null) {
1353		this.addImage = function (n, img, alt, link, linkTarget, caption, lngCaption, externalLink) { }
1354		this.runSlideShow = function () { }
1355		this.nextSlide = function () { }
1356		this.mouseOver = function (elem, imgPath, altText) { }
1357		return;
1358	}
1359
1360	var tmpElem = document.createElement('a');
1361	if (slideShowLink && slideShowLink != '') {
1362		do {
1363			slideShowLink = (slideShowLink).replace("%38", "&");
1364		} while ((slideShowLink).indexOf("%38") != -1)
1365		tmpElem.href = slideShowLink;
1366		if (slideShowLinkTarget && slideShowLinkTarget != '')
1367			tmpElem.target = slideShowLinkTarget;
1368
1369		var ssID = this.slideShowId.id.replace("cvpSlideShowImage", "");
1370		var capt = document.getElementById('slideCaption' + ssID);
1371		tmpElem.onclick = "";
1372		if (capt && capt.children && capt.children.length > 0)
1373			capt.children[0].removeAttribute("onclick");
1374	}
1375	else
1376		tmpElem.removeAttribute('href');
1377
1378	this.j = 1;
1379	if (slideShowSpeed == null || slideShowSpeed == '')
1380		this.slideShowSpeed = 4000;
1381	else
1382		this.slideShowSpeed = slideShowSpeed * 1000;
1383	if (filterAttr1 == null || filterAttr1 == '')
1384		filterAttr1 = 2;
1385	if (filterName == null || filterName == '' || filterName.toLowerCase() == 'blendtrans')
1386		this.filterName = 'BlendTrans(duration=' + filterAttr1;
1387	else if (filterName.toLowerCase() != 'none')
1388		this.filterName = 'progid:DXImageTransform.Microsoft.' + filterName + ', duration=' + filterAttr1;
1389	if (filterAttr2 != null && filterAttr2 != '' && filterAttr2 != 'null')
1390		this.filterName = this.filterName + ',' + filterAttr2;
1391	if (filterAttr3 != null && filterAttr3 != '' && filterAttr3 != 'null')
1392		this.filterName = this.filterName + ',' + filterAttr3;
1393	if (filterName.toLowerCase() == 'none')
1394		this.filterName = filterName;
1395	else
1396		this.filterName = this.filterName + ')';
1397
1398	switch (layout) {
1399		case 1: // Standard
1400			tmpElem.style.border = 'none';
1401			tmpElem.style.background = 'transparent';
1402			//tmpElem.style.border = 'medium none';
1403			//tmpElem.style.background = 'transparent none repeat scroll 0% 0%';
1404			tmpElem.id = slideShowId + '_link';
1405			this.slideShowLink = tmpElem;
1406			this.slideShowId.parentNode.insertBefore(tmpElem, this.slideShowId);
1407			this.slideShowId.parentNode.removeChild(this.slideShowId);
1408			this.slideShowLink.appendChild(this.slideShowId);
1409			break;
1410		case 5: // StandardFiveBottom
1411			//DO NOT COPY for this case - follow 12 for a better code.
1412			//tmpElem.style.border = 'none';
1413			//tmpElem.style.background = 'transparent';
1414			tmpElem.style.border = 'medium none';
1415			tmpElem.style.background = 'transparent none repeat scroll 0% 0%';
1416			tmpElem.id = slideShowId + '_link';
1417			this.slideShowLink = tmpElem;
1418			this.slideShowId.parentNode.insertBefore(tmpElem, this.slideShowId);
1419			//this.slideShowId.parentNode.removeChild(this.slideShowId);
1420			this.slideShowLink.appendChild(this.slideShowId);
1421			var tmpElemHTML = this.slideShowLink.innerHTML;
1422
1423			var td = this.slideShowId.parentNode.parentNode;
1424			this.slideShowId.parentNode.parentNode.removeChild(this.slideShowId.parentNode);
1425
1426			var newSection = document.createElement("div");
1427			newSection.setAttribute("id", "SubSection1");
1428
1429			var cpSlideShowWrapper1 = document.createElement("div");
1430			cpSlideShowWrapper1.setAttribute("id", "cpSlideShowWrapper1");
1431			cpSlideShowWrapper1.style.padding = "5px";
1432			cpSlideShowWrapper1.style.background = "rgb(70, 43, 16) none repeat scroll 0% 0%";
1433			cpSlideShowWrapper1.style.position = "relative";
1434			cpSlideShowWrapper1.style.width = "416px";
1435			//cpSlideShowWrapper1.style.-moz-background-clip = "border";
1436			//cpSlideShowWrapper1.style.-moz-background-origin = "padding";
1437			//cpSlideShowWrapper1.style.-moz-background-inline-policy = "continuous";
1438			cpSlideShowWrapper1.style.height = "254px";
1439
1440			var imageHead = document.createElement("div");
1441			imageHead.style.padding = "4px";
1442			imageHead.style.background = "rgb(241, 239, 234) none repeat scroll 0% 0%";
1443			imageHead.style.align = "left";
1444			imageHead.style.width = "406px";
1445			//-moz-background-clip: border;
1446			//-moz-background-origin: padding;
1447			//-moz-background-inline-policy: continuous;
1448			imageHead.style.float = "left";
1449			imageHead.style.height = "198px";
1450			imageHead.style.align = "left";
1451
1452			imageHead.innerHTML = tmpElemHTML;
1453			cpSlideShowWrapper1.appendChild(imageHead);
1454
1455			var imageRows = document.createElement("div");
1456			imageRows.setAttribute("id", "imageRows");
1457			imageRows.style.position = "relative";
1458			imageRows.style.align = "left";
1459			imageRows.style.margin = "5px 0px 0px 0px";
1460			imageRows.style.width = "416px";
1461			imageRows.style.float = "left";
1462			imageRows.style.height = "42px";
1463			imageRows.style.clear = "both";
1464
1465			cpSlideShowWrapper1.appendChild(imageRows);
1466			newSection.appendChild(cpSlideShowWrapper1);
1467			td.appendChild(newSection);
1468
1469			this.slideShowId = document.getElementById(slideShowId);
1470			if (isie) {
1471				this.slideShowId.style.height = "100%";
1472				this.slideShowId.style.width = "100%";
1473			}
1474			else {
1475				this.slideShowId.setAttribute("height", "100%");
1476				this.slideShowId.setAttribute("width", "100%");
1477			}
1478			break;
1479		case 12: //This case would handle the new 12 image slideshow without Rotation. & with mouseover
1480			tmpElem.id = slideShowId + '_link';
1481			this.slideShowLink = tmpElem;
1482			this.slideShowId.parentNode.insertBefore(tmpElem, this.slideShowId);
1483			this.slideShowLink.appendChild(this.slideShowId);
1484			var tmpElemHTML = this.slideShowLink.innerHTML;
1485
1486			var td = this.slideShowId.parentNode.parentNode;
1487
1488			// If the slideshow is in the middle of the page's content, we
1489			// have to keep track of its next sibling, so we put the 12-thumbnail
1490			// content in the new location.
1491			var nextSibling = this.slideShowLink.nextSibling;
1492
1493			this.slideShowId.parentNode.parentNode.removeChild(this.slideShowId.parentNode);
1494
1495			var newSection = document.createElement("div");
1496			newSection.setAttribute("id", "SubSectionFor" + slideShowId);
1497
1498			var cpSlideShowWrapper1 = document.createElement("div");
1499			cpSlideShowWrapper1.setAttribute("id", "cpSlideShowWrapper" + slideShowId);
1500
1501			//Remove these in-line style Height and Width after CSS changes
1502			cpSlideShowWrapper1.style.width = "441px";
1503			cpSlideShowWrapper1.style.height = "190px";
1504			cpSlideShowWrapper1.style.padding = "5px";
1505			cpSlideShowWrapper1.style.position = "relative";
1506			cpSlideShowWrapper1.style.clear = "both";
1507
1508			var imageHead = document.createElement("div");
1509			imageHead.setAttribute("id", "imageHead");
1510			//Remove these in-line style Height and Width after CSS changes
1511			imageHead.style.width = "201px"; //185 px
1512			imageHead.style.height = "168px";
1513			imageHead.style.padding = "8px";
1514			imageHead.style.align = "left";
1515			imageHead.style.styleFloat = "left";
1516			imageHead.style.cssFloat = "left";
1517			imageHead.innerHTML = tmpElemHTML;
1518			cpSlideShowWrapper1.appendChild(imageHead);
1519
1520			var imageRowsHeader = document.createElement("div");
1521			imageRowsHeader.setAttribute("id", "imageRowsHeader");
1522			imageRowsHeader.style.position = "relative";
1523			imageRowsHeader.style.align = "right";
1524			imageRowsHeader.style.styleFloat = "right";
1525			imageRowsHeader.style.cssFloat = "right";
1526			imageRowsHeader.style.width = "216px"; //247px
1527			imageRowsHeader.style.height = "18px";
1528
1529			//Image Link
1530			var slideImageHeaderLink = document.createElement("a");
1531			slideImageHeaderLink.setAttribute("href", "/gallery.aspx");
1532
1533			//Image Header
1534			var slideImageHeader = document.createElement("img");
1535			slideImageHeader.setAttribute("id", slideShowId + "Header");
1536			slideImageHeader.setAttribute("src", "/images/pages/ImageHeader.jpg");
1537			slideImageHeader.setAttribute("target", "_blank");
1538			slideImageHeader.style.width = "198px"; //247px
1539			slideImageHeader.style.height = "18px";
1540			slideImageHeader.setAttribute("border", "0");
1541
1542			slideImageHeaderLink.appendChild(slideImageHeader);
1543			imageRowsHeader.appendChild(slideImageHeaderLink);
1544
1545			cpSlideShowWrapper1.appendChild(imageRowsHeader);
1546
1547			var imageRows = document.createElement("div");
1548			imageRows.setAttribute("id", "imageRows");
1549			imageRows.style.position = "relative";
1550			imageRows.style.align = "right";
1551			//imageRows.style.margin = "28px 0px 0px 0px";
1552			imageRows.style.styleFloat = "right";
1553			imageRows.style.cssFloat = "right";
1554			imageRows.style.width = "216px"; //247px
1555			imageRows.style.height = "145px";
1556			imageRows.style.padding = "4px";
1557
1558			cpSlideShowWrapper1.appendChild(imageRows);
1559			newSection.appendChild(cpSlideShowWrapper1);
1560
1561			var scriptTag = td.firstChild;
1562			while (scriptTag) {
1563				if (scriptTag.nodeType == 1 && scriptTag.tagName == 'SCRIPT')
1564					break;
1565				scriptTag = scriptTag.nextSibling;
1566			}
1567			if (nextSibling != null)
1568				td.insertBefore(newSection, nextSibling);
1569			else
1570				td.insertBefore(newSection, scriptTag);
1571
1572			this.slideShowId = document.getElementById(slideShowId);
1573			//Remove these in-line style Height and Width after CSS changes
1574			if (isie) {
1575				this.slideShowId.style.height = "100%";
1576				this.slideShowId.style.width = "100%";
1577			}
1578			else {
1579				this.slideShowId.setAttribute("height", "100%");
1580				this.slideShowId.setAttribute("width", "100%");
1581			}
1582			break;
1583		default:
1584			break;
1585	}
1586
1587	this.addImage = function (n, img, alt, link, linkTarget, caption, lngCaption, isExternal) {
1588		if (layout == 12 && n > 11)
1589			return; // Allow only upto 12 thumbnail images for Standard 12 Bottom layout
1590
1591		if (!linkTarget || linkTarget == null || linkTarget == "undefined" || linkTarget == "")
1592			linkTarget = "_self";
1593
1594		this.picArr[n] = new Image();
1595		this.picArr[n].src = img;
1596		do {
1597			alt = (alt).replace("%39", "'");
1598		} while ((alt).indexOf("%39") != -1)
1599		this.altArr[n] = alt;
1600		this.captionArr[n] = caption;
1601		this.lngCaptionArr[n] = lngCaption;
1602
1603		do {
1604			link = (link).replace("%38", "&");
1605		} while ((link).indexOf("%38") != -1)
1606		this.linkArr[n] = link;
1607
1608		this.linkTargetArr[n] = linkTarget;
1609
1610		switch (layout) {
1611			case 5:
1612				var slideImage = document.createElement("img");
1613				slideImage.setAttribute("id", slideShowId + n);
1614				if (isie) {
1615					slideImage.style.height = "40";
1616					slideImage.style.width = "40";
1617				}
1618				else {
1619					slideImage.setAttribute("height", "40");
1620					slideImage.setAttribute("width", "40");
1621				}
1622				if (n == 0)
1623					slideImage.setAttribute("border", "1");
1624				else
1625					slideImage.setAttribute("border", "0");
1626				slideImage.style.borderStyle = "solid";
1627				slideImage.style.borderColor = "#FFFF00";
1628				slideImage.setAttribute("src", img);
1629				slideImage.setAttribute("alt", alt);
1630				slideImage.setAttribute("link", link);
1631				slideImage.setAttribute("target", linkTarget);
1632				slideImage.setAttribute("class", "photoGalleryImgArray");
1633
1634				if (n == 0)
1635					slideImage.style.margin = "0px 0px 0px 0px";
1636				else
1637					slideImage.style.margin = "0px 0px 0px 6px";
1638				this.imageRows = document.getElementById("imageRows");
1639				this.imageRows.appendChild(slideImage);
1640				break;
1641			case 12: //This case would handle the new 12 image slideshow without Rotation. & with mouseover
1642				var slideImage = document.createElement("img");
1643				slideImage.setAttribute("id", slideShowId + n);
1644				//Remove these in-line style 'Padding' after CSS changes
1645				if (n == 0) {
1646					if (isie)
1647						slideImage.style.cssText = "margin:6px 6px; border: 2px solid transparent; background-color: lightblue; padding: 3px; height:30px; width:30px;";
1648					else
1649						slideImage.setAttribute('style', 'margin:6px 6px; border: 2px solid transparent; background-color: lightblue; padding: 3px; height:30px; width:30px;');
1650				}
1651				else {
1652					if (isie)
1653						slideImage.style.cssText = "margin:6px 6px; border: 2px solid transparent ; background-color: white; padding: 3px; height:30px; width:30px;";
1654					else
1655						slideImage.setAttribute('style', 'margin:6px 6px; border: 2px solid transparent ; background-color: white; padding: 3px;height:30px; width:30px;');
1656				}
1657				slideImage.setAttribute("src", img);
1658				slideImage.setAttribute("alt", alt);
1659				slideImage.setAttribute("link", link);
1660				slideImage.setAttribute("target", linkTarget);
1661				slideImage.setAttribute("class", "photoGalleryImgArray");
1662				var siObj = eval(slideShowId.replace("Image", ""));
1663				slideImage.onmouseover = function () { siObj.mouseOver(slideShowId + n, img, alt); };
1664
1665				this.imageRows = document.getElementById("imageRows");
1666				this.imageRows.appendChild(slideImage);
1667				break;
1668			default:
1669				break;
1670		}
1671	}
1672
1673	this.mouseOver = function (elem, imgPath, altText) {
1674		//Set the Main Display image to mouseOver Image
1675		this.slideShowId.setAttribute("src", imgPath);
1676		this.slideShowId.alt = altText;
1677
1678		//Loop through all other images and set the border to 1
1679		this.ImageRows = document.getElementById("imageRows");
1680		this.ImageRows.Images = this.ImageRows.getElementsByTagName("img");
1681		var j = 0;
1682		while (j < this.ImageRows.Images.length) {
1683			if (this.ImageRows.Images[j] == document.getElementById(elem)) {
1684				if (isie)
1685					this.ImageRows.Images[j].style.cssText = "margin:6px 6px; border: 2px solid transparent; background-color: lightblue; padding: 3px; height:30px; width:30px;";
1686				else
1687					this.ImageRows.Images[j].setAttribute('style', 'margin:6px 6px; border: 2px solid transparent; background-color: lightblue; padding: 3px;height:30px; width:30px;');
1688			}
1689			else {
1690				if (isie)
1691					this.ImageRows.Images[j].style.cssText = "margin:6px 6px; border: 2px solid transparent; background-color:white; padding: 3px;height:30px; width:30px;";
1692				else
1693					this.ImageRows.Images[j].setAttribute('style', 'margin:6px 6px; border: 2px solid transparent; background-color:white; padding: 3px;height:30px; width:30px;');
1694			}
1695			j++;
1696		}
1697	}
1698
1699	this.runSlideShow = function () {
1700		switch (layout) {
1701			case 12:
1702			case 5:
1703				//Do nothing, do not run a slideshow
1704				break;
1705			default:
1706				if (this.picArr.length > 1) {
1707					var self = this; 					//  reference to get around context loss of this during setTimeout()
1708					this.timeoutId = setTimeout(function () { self.nextSlide(); self.runSlideShow(); }, this.slideShowSpeed);
1709				}
1710				break;
1711		}
1712	}
1713
1714	this.nextSlide = function () {
1715		var ssID = this.slideShowId.id.replace("cvpSlideShowImage", "");
1716		var capt = document.getElementById('slideCaption' + ssID);
1717		var lngCapt = document.getElementById('slideCaptionLng' + ssID);
1718		if (document.all && this.slideShowId.filters && this.slideShowId.filters.length > 0 && this.filterName.toLowerCase() != 'none') {
1719			this.slideShowId.style.filter = this.filterName;
1720			this.slideShowId.filters.item(0).apply();
1721			if (capt) {
1722				capt.style.filter = captionFilter + " " + this.filterName;
1723				capt.filters.item(capt.filters.length - 1).apply();
1724				if (lngCapt) {
1725					lngCapt.style.filter = captionFilter + " " + this.filterName;
1726					lngCapt.filters.item(lngCapt.filters.length - 1).apply();
1727				}
1728			}
1729		}
1730		this.slideShowId.setAttribute('src', this.picArr[this.j].src);
1731		this.slideShowId.setAttribute('alt', this.altArr[this.j]);
1732		this.slideShowId.setAttribute('title', this.altArr[this.j]);
1733
1734		var height = '';
1735		var marginTop = useStyle ? "-61px" : "0px";
1736		var paddingTop = "3px";
1737		if (this.captionArr[this.j] == "") {
1738			height = "0px";
1739		}
1740		else if (this.lngCaptionArr[this.j] == "") {
1741			height = "31px";
1742			marginTop = useStyle ? "-35px" : "0px";
1743			paddingTop = useStyle ? "-4px" : "0px";
1744		}
1745		else
1746			height = useStyle ? "55px" : "";
1747
1748		if (capt) {
1749			capt.innerHTML = useStyle ? this.captionArr[this.j] : "<strong>" + this.captionArr[this.j] + "</strong>";
1750			capt.style.marginTop = marginTop;
1751			capt.style.height = height;
1752			capt.style.paddingLeft = useStyle ? "15px" : "5px";
1753			capt.style.paddingRight = useStyle ? "10px" : "5px";
1754			capt.style.paddingTop = paddingTop;
1755
1756			if (height != "0px" && lngCapt != null) {
1757				lngCapt.innerHTML = this.lngCaptionArr[this.j];
1758				lngCapt.style.marginTop = useStyle ? "-38px" : "0px";
1759				lngCapt.style.paddingLeft = useStyle ? "15px" : "5px";
1760				lngCapt.style.paddingRight = useStyle ? "10px" : "5px";
1761				lngCapt.style.paddingTop = paddingTop;
1762				lngCapt.style.overflow = 'hidden';
1763			}
1764			else if (lngCapt != null) {
1765				lngCapt.style.marginTop = "0px";
1766				lngCapt.innerHTML = "";
1767				lngCapt.height = "0px";
1768			}
1769		}
1770
1771		var slideLink = this.linkArr[this.j]
1772		var slideLinkTarget = this.linkTargetArr[this.j]
1773		if (slideLink && slideLink != '') {
1774			tmpElem.href = slideLink;
1775			this.slideShowLink.removeAttribute("onclick");
1776			tmpElem.onclick = "";
1777			if (capt)
1778				capt.innerHTML = useStyle ? "<a class = 'slideCaptionHyperlink' href=" + slideLink + " target = " + slideLinkTarget + ">" + this.captionArr[this.j] + "</a>" :
1779                                             "<a class = 'Hyperlink' href=" + slideLink + " target = " + slideLinkTarget + ">" + this.captionArr[this.j] + "</a>";
1780			if (slideLinkTarget && slideLinkTarget != '')
1781				tmpElem.target = slideLinkTarget;
1782		}
1783		else {
1784			tmpElem.removeAttribute('href');
1785			if (capt)
1786				capt.removeAttribute('href');
1787		}
1788		if (document.all && this.slideShowId.filters && this.slideShowId.filters.length > 0 && filterName.toLowerCase() != 'none') {
1789			this.slideShowId.filters.item(0).play();
1790			if (capt) {
1791				capt.filters.item(capt.filters.length - 1).play();
1792				lngCapt.filters.item(lngCapt.filters.length - 1).play();
1793			}
1794		}
1795
1796		var slideImageId, slideImage;
1797		if (layout == 5) {
1798			// Set the selected image's border
1799			if (this.j == 0)
1800				slideImageId = slideShowId + (this.picArr.length - 1);
1801			else
1802				slideImageId = slideShowId + (this.j - 1);
1803			slideImage = document.getElementById(slideImageId);
1804			slideImage.setAttribute("border", "0");
1805
1806			slideImageId = slideShowId + this.j;
1807			slideImage = document.getElementById(slideImageId);
1808			slideImage.setAttribute("border", "1");
1809		}
1810
1811		this.j++;
1812		if (this.j >= this.picArr.length)
1813			this.j = 0;
1814	}
1815}
1816
1817function validateMultiFileUpload(el, useWhiteList) {
1818	try {
1819		const fileNames = [...el.files].map(file => file.name);
1820		const xhr = new XMLHttpRequest();
1821		xhr.open('POST', '/Utility/AreValidFileNames', false);
1822		xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
1823		const data = new FormData();
1824		fileNames.forEach(fileName => {
1825			data.append("paths[]", fileName);
1826		})
1827
1828		xhr.send(data);
1829		const response = JSON.parse(xhr.responseText);
1830		const isValid = response.every(x => x === true);
1831
1832		for (const fileName of fileNames) {
1833			if (!isAllowedFileExtension(fileName, useWhiteList) || !isValid) {
1834				return false;
1835			}
1836		}
1837		return true;
1838	} catch (e) {
1839		console.error(e);
1840		return false;
1841	}
1842}
1843
1844//el is the pointer to the input type="file"
1845//example usage: <input type="file" size="38" name="txtFile" onChange="validateFileUpload(this);">
1846function validateFileUpload(el, useWhiteList) {
1847	var val = el.value;
1848	var cbox = document.getElementById(el.name + "_pdf");
1849	if (cbox) {
1850		cbox.disabled = true;
1851		cbox.checked = false;
1852	}
1853	if (val.length > 0) {
1854		var isValid = false;
1855		if (val.indexOf(':\\fakepath\\') > -1)
1856			val = val.substring(12);
1857		$.ajax({
1858			async: false,
1859			type: "POST",
1860			url: '/Utility/IsValidFileName',
1861			data: { path: val },
1862			dataType: "json",
1863			success: function (response) {
1864				if (typeof (response.d) != "undefined") {
1865					response = response.d;
1866				}
1867				if (response.result == "True")
1868					isValid = true;
1869			}
1870		});
1871		if (!isAllowedFileExtension(val, useWhiteList) || !isValid) {
1872			alert("The file you are trying to upload is not an allowed file type or has an invalid file name. These are the accepted characters: A-z 0-9 ~ ! ( ) - + = [ ] { } , . _");
1873			var tempElem = el.cloneNode(false);
1874			tempElem.value = "";
1875			el.parentNode.replaceChild(tempElem, el);
1876			el.focus();
1877			return false;
1878		}
1879		if (cbox) {
1880			cbox.disabled = !isAllowedFileExtensionPDF(val);
1881			if (cbox.disabled) cbox.checked = false;
1882		}
1883	}
1884	return true;
1885}
1886
1887// Recommended you use isAllowedFileExtensionWhiteList() instead. Do not use this method
1888// where useWhiteList is false or null, that is not secure (uses blacklist rather than whitelist).
1889function isAllowedFileExtension(filename, useWhiteList) {
1890	if (filename + '' == '')
1891		return true;
1892
1893	// Cut out the path portion (why not use lastIndexOf()?).
1894	while (filename.indexOf("/", 0) > 0)
1895		filename = filename.substr(filename.indexOf("/", 0) + 1, filename.length - filename.indexOf("/", 0))
1896	while (filename.indexOf("\\", 0) > 0)
1897		filename = filename.substr(filename.indexOf("\\", 0) + 1, filename.length - filename.indexOf("\\", 0))
1898
1899	var lastPeriod = filename.indexOf(".", 0);
1900	var i = lastPeriod;
1901
1902	while (lastPeriod > 0) {
1903		i = lastPeriod;
1904		lastPeriod = filename.indexOf(".", i + 1);
1905	}
1906
1907	var fileExtension = (i > 0 ? filename.substr(i + 1, filename.length - i) : "");
1908
1909	if (useWhiteList)
1910		return isAllowedFileExtensionWhiteList('.' + fileExtension)
1911	else {
1912		switch (fileExtension.toUpperCase()) {
1913			case "ASA":
1914			case "ASAX":
1915			case "ASBX":
1916			case "ASCX":
1917			case "ASP":
1918			case "ASPX":
1919			case "BAT":
1920			case "CAB":
1921			case "CF":
1922			case "CFM":
1923			case "CGI":
1924			case "COM":
1925			case "CONFIG":
1926			case "DLL":
1927			case "EXE":
1928			case "HTA":
1929			case "LHA":
1930			case "LHZ":
1931			case "MIM":
1932			case "PIF":
1933			case "PL":
1934			case "SYS":
1935			case "UUE":
1936			case "VBS":
1937			case "VXD":
1938			case "WEBINFO":
1939			case "WIZ":
1940			case "WSH":
1941				{
1942					return false;
1943					break;
1944				}
1945			default:
1946				{
1947					return true;
1948					break;
1949				}
1950		}
1951	}
1952}
1953
1954// Makes sure a file being uploaded for PDF conversion is supported.
1955// Note: Server logic should additionally chop out paths and other evil things (e.g. Windows Device Names like 'CON', 'AUX', etc).
1956function isAllowedFileExtensionPDF(filename) {
1957	//cut out the path portion
1958	while (filename.indexOf("/", 0) > 0)
1959		filename = filename.substr(filename.indexOf("/", 0) + 1, filename.length - filename.indexOf("/", 0))
1960	while (filename.indexOf("\\", 0) > 0)
1961		filename = filename.substr(filename.indexOf("\\", 0) + 1, filename.length - filename.indexOf("\\", 0))
1962
1963	var lastPeriod, i, fileExtension;
1964	lastPeriod = filename.indexOf(".", 0);
1965	i = lastPeriod;
1966	while (lastPeriod > 0) {
1967		i = lastPeriod;
1968		lastPeriod = filename.indexOf(".", i + 1);
1969	}
1970
1971	if (i > 0)
1972		fileExtension = filename.substr(i + 1, filename.length - i).toUpperCase();
1973	else
1974		fileExtension = "";
1975
1976	switch (fileExtension) {
1977		case "HTM":
1978		case "HTML":
1979		case "DOC":
1980		case "DOCX":
1981		case "XLS":
1982		case "XLSX":
1983		case "TXT":
1984			{
1985				return true;
1986				break;
1987			}
1988		default:
1989			{
1990				return false;
1991				break;
1992			}
1993	}
1994}
1995
1996// returns true if it is a valid US or Canadian zip code.
1997// supports ZIP, ZIP+4 and Canadian zip code format
1998// * intCountryCode is a ISO 3166-1 numeric value.
1999function isZipCode(strInput, intCountryCode) {
2000	var countryCodeRe = {
2001		840: /^\d{5}([\-]\d{4})?$/, // USA
2002		124: /^[ABCEGHJ-NPRSTVXY]\d[ABCEGHJ-NPRSTV-Z][ -]?\d[ABCEGHJ-NPRSTV-Z]\d$/i, //Canada
2003		36: /^(?:(?:[2-8]\d|9[0-7]|0?[28]|0?9(?=09))(?:\d{2}))$/ //Australia
2004	};
2005	if (intCountryCode in countryCodeRe) {
2006		return countryCodeRe[intCountryCode].test(strInput);
2007	}
2008	return strInput.length > 0;
2009}
2010
2011// returns name to assign postal/zip code.
2012function getZipCodeName(intCountryCode) {
2013	if (intCountryCode == 840) // USA
2014		return 'Zip';
2015	else// if (intCountryCode == 124) // Canada
2016		return 'Postal';
2017}
2018
2019function updateAddressPlaceholdersForCanadinaClients(zipElementId, stateElementId) {
2020	document.getElementById(stateElementId).setAttribute('placeholder', 'Province');
2021	document.getElementById(stateElementId).style.width = '5em';
2022	document.getElementById(zipElementId).setAttribute('placeholder', 'Postal Code');
2023}
2024
2025function getLowerCaseStateString() {
2026	if (intCountryCode == 124)
2027		return "province";
2028	else// if (intCountryCode == 840) <- neutral setting (en-US).
2029		return "state";
2030}
2031
2032// Gets card type. Will return one of the following values (or an empty string for unknown/invalid cards):
2033// * Master = M
2034// * Visa = V
2035// * Discover = D
2036// * American Express = A
2037function getCreditCardType(cardNumber) {
2038	switch (cardNumber.substr(0, 2)) {
2039		case "50":
2040		case "51":
2041		case "52":
2042		case "53":
2043		case "54":
2044		case "55":
2045			return "M";
2046		case "65":
2047			return "D";
2048	}
2049	switch (cardNumber.substr(0, 1)) {
2050		case "4":
2051			return "V";
2052	}
2053	switch (cardNumber.substr(0, 4)) {
2054		case "6011":
2055			return "D";
2056	}
2057	switch (cardNumber.substr(0, 2)) {
2058		case "34":
2059		case "37":
2060			return "A";
2061	}
2062
2063	// Card unknown/invalid.
2064	return '';
2065}
2066
2067// Validates credit card numbers. cardType is an optional argument.
2068function isValidCreditCardNumber(cardNumber, cardType) {
2069	var isValid = false;
2070	var ccCheckRegExp = /[^\d ]/;
2071
2072	isValid = !ccCheckRegExp.test(cardNumber);
2073
2074	if (isValid) {
2075		// Get card type if not explicitly specified.
2076		if (cardType == null)
2077			cardType = getCreditCardType(cardNumber);
2078
2079		// If unknown/unsupported/invalid card type, abort/fail.
2080		if (cardType == '')
2081			return false;
2082
2083		var cardNumbersOnly = cardNumber.replace(/ /g, "");
2084		var cardNumberLength = cardNumbersOnly.length;
2085		var lengthIsValid = false;
2086		var patternIsValid = false;
2087		var patternRegExp;
2088
2089		switch (cardType) {
2090			case "V":
2091				{ // visa
2092					lengthIsValid = (cardNumberLength == 13 || cardNumberLength == 16);
2093					patternRegExp = /^4/;
2094					break;
2095				}
2096			case "M":
2097				{ // mastercard
2098					lengthIsValid = (cardNumberLength == 16);
2099					patternRegExp = /^5[0-5]/;
2100					break;
2101				}
2102			case "A":
2103				{ // amercian express
2104					lengthIsValid = (cardNumberLength == 15);
2105					patternRegExp = /^3[4,7]/;
2106					break;
2107				}
2108			case "D":
2109				{ // discover
2110					lengthIsValid = (cardNumberLength == 16);
2111					patternRegExp = /^6011/;
2112					break;
2113				}
2114				/*case "J":
2115				{ // jcb
2116				lengthIsValid = (cardNumberLength == 15) || (cardNumberLength == 16);
2117				patternRegExp = /^[3,1800,2131]/;
2118				break;
2119				}
2120				case "C":
2121				{ // diner's club
2122				lengthIsValid = (cardNumberLength == 14);
2123				patternRegExp = /^3[0,6,8]/;
2124				break;
2125				}*/
2126			default:
2127				patternRegExp = /^$/;
2128		}
2129
2130		patternIsValid = patternRegExp.test(cardNumbersOnly);
2131		isValid = patternIsValid && lengthIsValid;
2132	}
2133
2134	if (isValid) {
2135		var numberProduct;
2136		var numberProductDigitIndex;
2137		var checkSumTotal = 0;
2138
2139		for (digitCounter = cardNumberLength - 1; digitCounter >= 0; digitCounter--) {
2140			checkSumTotal += parseInt(cardNumbersOnly.charAt(digitCounter));
2141			digitCounter--;
2142			numberProduct = String((cardNumbersOnly.charAt(digitCounter) * 2));
2143			for (var productDigitCounter = 0; productDigitCounter < numberProduct.length; productDigitCounter++)
2144				checkSumTotal += parseInt(numberProduct.charAt(productDigitCounter));
2145		}
2146
2147		isValid = (checkSumTotal % 10 == 0);
2148	}
2149
2150	return isValid;
2151}
2152
2153// Confirms data given is legal.
2154function isDate(varDateToCheck) {
2155	var objDate = new dateValidator();
2156	return objDate.dateValidate(varDateToCheck, true, 'Date');
2157}
2158
2159// Confirms data given is legal.
2160function isDateNew(varDateToCheck) {
2161	var objDate = new dateValidator();
2162	return objDate.dateValidateNew(varDateToCheck, true, 'Date');
2163}
2164
2165// TODO: JavaScript - Remove this function. Better ways to handle this.
2166// Date comparison function.
2167function dateDiff(dtiDateEntered, dtiDateToday) {
2168	var date1 = new Date();
2169	var date2 = new Date();
2170	var diff = new Date();
2171	// Initialize the first date
2172	var date1temp = new Date(dtiDateEntered);
2173	date1.setTime(date1temp.getTime());
2174	// Initialize the second date
2175	var date2temp = new Date(dtiDateToday);
2176	date2.setTime(date2temp.getTime());
2177	// sets difference date to difference of first date and second date
2178	diff.setTime(date1.getTime() - date2.getTime());
2179	timediff = diff.getTime();
2180	days = Math.floor(timediff / (86400000)); // 1000 * 60 * 60 * 24
2181	timediff -= days * (86400000);
2182	return days;
2183}
2184
2185// .NET JavaScript debugging function.
2186// TO-DO: Add sections for 'add_' and 'remove_' event prefixes.
2187function debugDisplayMembers(obj) {
2188	var getters = new Array();
2189	var setters = new Array();
2190	var others = new Array();
2191	var sKey;
2192
2193	for (var key in obj) {
2194		sKey = key + "";
2195		if (!((sKey.length > 0) && (sKey[0] == '_'))) {
2196			switch (sKey.substr(0, 4)) {
2197				case 'get_':
2198					getters.push(key);
2199					break;
2200				case 'set_':
2201					setters.push(key);
2202					break;
2203				default:
2204					others.push(key);
2205			}
2206		}
2207	}
2208
2209	getters.sort();
2210	setters.sort();
2211	others.sort();
2212
2213	alert(others.join(", ") + "\r\n\r\n" +
2214		getters.join(", ") + "\r\n\r\n" +
2215		setters.join(", "));
2216}
2217
2218// BEGIN PSEUDO-FORMS CODE
2219// Do not call any of these methods directly in your application code.
2220// Pseudo-forms are transparent, you shouldn't need to use these methods.
2221addEvent(window, 'load', initializePseudoForms, false);
2222
2223// Allows IE to recognize tag "subform". You cannot legally nest
2224// FORM tags inside FORM tags and at least Firefox pretends they're not
2225// in the DOM period. This is problematic, so the tag was renamed.
2226// Done for FORMS inside of FORMs trick to get around ASP.NET form limitations
2227// for content we cannot control (User Pages, Info Advanced HTML, etc).
2228document.createElement('subform');
2229
2230// Initialize pseudo-forms. Called on window load.
2231function initializePseudoForms() {
2232	// Make sure we're in an HTML document (not XUL).
2233	if (document.body) {
2234		var subForms = document.body.getElementsByTagName('subform');
2235		for (var i = 0; i < subForms.length; i++)
2236			setupPseudoForm(subForms[i]);
2237	}
2238}
2239
2240// Sets up pseudo-form.
2241function setupPseudoForm(pseudoFormElement) {
2242	// Re-routes form submission elements (no javascript used/necessary).
2243	// (those being input.type=submit, button.type=submit, and input.type=image)
2244	var rerouteElement = function (input, pseudoFormElement, newTagName, newType, copyInnerHTML) {
2245		var replacement = document.createElement(newTagName);
2246		replacement.setAttribute('type', newType);
2247		var onClickDest, onClickSrc = replacement.getAttribute('onclick');
2248		if (onClickSrc != null)
2249			replacement.removeAttribute('onclick');
2250		cloneAttributes(input, replacement);
2251		if (onClickSrc != null) {
2252			eval("window.tmp = function(event) { " + onClick + " }");
2253			onClickSrc = window.tmp;
2254			window.tmp = null;
2255			onClickDest = function (ev) {
2256				ev = (window.event ? window.event : ev);
2257				if (onClickSrc(ev) == false)
2258					return;
2259				pseudoFormElement._submitter = replacement;
2260				pseudoFormElement._submevent = ev;
2261				pseudoFormElement.submit();
2262			}
2263		}
2264		else {
2265			onClickDest = function (ev) {
2266				ev = (window.event ? window.event : ev);
2267				pseudoFormElement._submitter = replacement;
2268				pseudoFormElement._submevent = ev;
2269				pseudoFormElement.submit();
2270			}
2271		}
2272
2273		// Return replacement routine.
2274		var fn = function () {
2275			var inputParent = input.parentNode;
2276			var inputRightAfter = input.nextSibling;
2277			var inputDisabled = input.disabled; // For Internet Explorer (it forgets).
2278			var inputHTML = (copyInnerHTML ? input.innerHTML : null);
2279			inputParent.removeChild(input); input = null;
2280			if (copyInnerHTML)
2281				replacement.innerHTML = inputHTML;
2282			inputParent.insertBefore(replacement, inputRightAfter);
2283			replacement.disabled = inputDisabled;
2284			addEvent(replacement, 'click', onClickDest, false);
2285		}
2286		return fn;
2287	}
2288
2289	// Re-route submits (needs to be done early on).
2290	var inputs, input, inc, repls;
2291	repls = new Array();
2292	inputs = pseudoFormElement.getElementsByTagName('input');
2293	for (var i = 0; i < inputs.length; i++) {
2294		input = inputs[i];
2295		switch (input.type.toLowerCase()) {
2296			case 'submit':
2297				repls.push(rerouteElement(input, pseudoFormElement, 'input', 'button', false));
2298				break;
2299			case 'image':
2300				repls.push(rerouteElement(input, pseudoFormElement, 'img', 'image', false));
2301				break;
2302		}
2303	}
2304	inputs = pseudoFormElement.getElementsByTagName('button');
2305	for (var i = 0; i < inputs.length; i++) {
2306		input = inputs[i];
2307		switch (input.type.toLowerCase()) {
2308			case 'submit':
2309				repls.push(rerouteElement(input, pseudoFormElement, 'button', 'button', true));
2310				break;
2311		}
2312	}
2313	for (var i = 0; i < repls.length; i++)
2314		repls[i]();
2315
2316	// Implement properties for pseudo-form.
2317	var name = pseudoFormElement.getAttribute('name');
2318	if (name && name != '') {
2319		document[name] = pseudoFormElement;
2320		document.forms[name] = pseudoFormElement;
2321	}
2322	pseudoFormElement.method = pseudoFormElement.getAttribute('method');
2323	if (pseudoFormElement.method == null || pseudoFormElement.method == '')
2324		pseudoFormElement.method = 'get';
2325	pseudoFormElement.enctype = pseudoFormElement.getAttribute('enctype');
2326	if (pseudoFormElement.enctype == null || pseudoFormElement.enctype == '')
2327		pseudoFormElement.enctype = 'application/x-www-form-urlencoded';
2328	pseudoFormElement.target = pseudoFormElement.getAttribute('target');
2329	pseudoFormElement.action = pseudoFormElement.getAttribute('action');
2330	pseudoFormElement.acceptCharset = pseudoFormElement.getAttribute('accept-charset');
2331
2332	// Initialize.
2333	var elements = new Array(); // elements in pseudo-form (for form.elements).
2334	var simpleInputs = new Array(); // simple value inputs and textareas, no additional logic.
2335	var stateInputs = new Array(); // checkboxes and radiobuttons.
2336	var dropdowns = new Array(); // drop-downs and lists.
2337	pseudoFormElement.elements = elements;
2338	pseudoFormElement._simple = simpleInputs;
2339	pseudoFormElement._state = stateInputs;
2340	pseudoFormElement._dropdown = dropdowns;
2341
2342	// Registers element for the pseudo-form.
2343	var registerElement = function (input) {
2344		// Add to elements array.
2345		elements.push(input);
2346		// Add as property.
2347		if (input.name != '' && input.name != null) {
2348			obj = pseudoFormElement[input.name];
2349			if (obj == null)
2350				pseudoFormElement[input.name] = input;
2351			else if (obj instanceof Array)
2352				obj.push(input);
2353			else {
2354				var arr = new Array();
2355				arr.push(obj);
2356				arr.push(input);
2357				pseudoFormElement[input.name] = arr;
2358			}
2359		}
2360	}
2361
2362	// Add methods (can be overridden by form elements /w same names, just like real forms).
2363	pseudoFormElement.submit = function () { submitPseudoForm(this, false); }
2364	pseudoFormElement.reset = document.aspnetForm.reset; // HACK (we'll fix it if someone complains)
2365
2366	// Register elements, and categorize them for form submission.
2367	inputs = pseudoFormElement.getElementsByTagName('input');
2368	for (var i = 0; i < inputs.length; i++) {
2369		input = inputs[i];
2370		switch (input.type.toLowerCase()) {
2371			case 'checkbox':
2372			case 'radio':
2373				stateInputs.push(input);
2374				registerElement(input);
2375				break;
2376			case 'text':
2377			case 'hidden':
2378			case 'password':
2379				simpleInputs.push(input);
2380				registerElement(input);
2381				break;
2382			default:
2383				registerElement(input);
2384		}
2385	}
2386	inputs = pseudoFormElement.getElementsByTagName('textarea');
2387	for (var i = 0; i < inputs.length; i++) {
2388		input = inputs[i];
2389		simpleInputs.push(input);
2390		registerElement(input);
2391	}
2392	inputs = pseudoFormElement.getElementsByTagName('select');
2393	for (var i = 0; i < inputs.length; i++) {
2394		input = inputs[i];
2395		dropdowns.push(input);
2396		registerElement(input);
2397	}
2398	inputs = pseudoFormElement.getElementsByTagName('button');
2399	for (var i = 0; i < inputs.length; i++)
2400		registerElement(inputs[i]);
2401}
2402
2403// Copies attributes from one element to another. Copy should occur
2404// before destElement is added to the DOM, as some things become read-only.
2405// ID and CLASS need to be handled specially for compatiblity reasons.
2406// Warning: TYPE is not supported (blame IE)!
2407function cloneAttributes(srcElement, destElement) {
2408	var attr;
2409	for (var i = 0; i < srcElement.attributes.length; i++) {
2410		attr = srcElement.attributes[i];
2411		switch (attr.name.toLowerCase()) {
2412			case 'name':
2413				if ((attr.value + '').toLowerCase() == 'submit')
2414					destElement.setAttribute('name', 'submit_button');
2415				else
2416					destElement.setAttribute('name', attr.value);
2417				break;
2418			case 'class':
2419				destElement.className = attr.value;
2420				break;
2421			case 'id':
2422				destElement.id = attr.value;
2423				break;
2424			case 'type':
2425			case 'form':
2426				break;
2427			default:
2428						try { destElement.setAttribute(attr.name, attr.value); }
2429						catch (e) { }
2430		}
2431	}
2432}
2433
2434// Called by pseudo-form when submit() is invoked.
2435function submitPseudoForm(pseudoFormElement, debugMode) {
2436	var inputs, input;
2437	var spawner = pseudoFormElement._submitter;
2438	var spawnerEvent = pseudoFormElement._submevent;
2439	pseudoFormElement._submitter = null;
2440	pseudoFormElement._submevent = null;
2441
2442	// Destroy form if it already exists (possible if target not implicit/explicit "_self").
2443	if (pseudoFormElement._form != null)
2444		document.body.removeChild(pseudoFormElement._form);
2445	pseudoFormElement._form = null;
2446
2447	// Fire pseudo-onsubmit event (remember that just like in real forms, only fires on non-J/S submits).
2448	var onsubmit = pseudoFormElement.getAttribute('onsubmit');
2449	if (onsubmit != null && onsubmit != '' && spawnerEvent) {
2450		eval("window.tmp = function(event) { " + onsubmit + " }");
2451		onsubmit = window.tmp;
2452		window.tmp = null;
2453		if (onsubmit(spawnerEvent) == false)
2454			return false;
2455	}
2456
2457	// Create actual form to forward submission to.
2458	var newForm = document.createElement('form');
2459	pseudoFormElement._form = newForm;
2460
2461	// Transfer some standard HTML/XHTML attributes.
2462	newForm.dir = pseudoFormElement.dir;
2463	newForm.lang = pseudoFormElement.lang;
2464	newForm.title = pseudoFormElement.title;
2465
2466	// Setup actual form action, accept, accept-charset, encoding, method, and target.
2467	var action = pseudoFormElement.getAttribute('action');
2468	var method = pseudoFormElement.getAttribute('method');
2469	var target = pseudoFormElement.getAttribute('target');
2470	var enctype = pseudoFormElement.getAttribute('enctype');
2471	var accept = pseudoFormElement.getAttribute('accept');
2472	var acceptCharset = pseudoFormElement.getAttribute('accept-charset');
2473	if (action)
2474		newForm.action = action;
2475	if (method)
2476		newForm.method = method;
2477	if (target)
2478		newForm.target = target;
2479	if (enctype)
2480		newForm.enctype = enctype;
2481	if (accept)
2482		newForm.accept = accept;
2483	if (acceptCharset)
2484		newForm.acceptCharset = acceptCharset;
2485
2486	// Method used to create hidden input copies.
2487	var newHiddenInput = function (name, value) {
2488		var ret = document.createElement('input');
2489		ret.type = 'hidden';
2490		ret.value = value;
2491		ret.name = name;
2492		newForm.appendChild(ret);
2493	}
2494
2495	// Create element for spawner if one exists (submitted w/o JS, e.g. input.type=submit).
2496	if (spawner && spawner.name != null && spawner.name != '')
2497		newHiddenInput(spawner.name, spawner.value);
2498
2499	// Forward text, textarea, hidden, and password input values.
2500	inputs = pseudoFormElement._simple;
2501	for (var i = 0; i < inputs.length; i++) {
2502		input = inputs[i];
2503		if ((!input.disabled) && (input.style.display != 'none'))
2504			newHiddenInput(input.name, input.value);
2505	}
2506
2507	// Forward checkbox and radio-button values.
2508	inputs = pseudoFormElement._state;
2509	for (var i = 0; i < inputs.length; i++) {
2510		input = inputs[i];
2511		if ((!input.disabled) && (input.style.display != 'none')) {
2512			if (input.checked)
2513				newHiddenInput(input.name, input.value);
2514		}
2515	}
2516
2517	// Forward drop-down/list selections.
2518	// Blame for text/value condition and necessity of options loop lies with IE.
2519	// 1) Specifically, IE 7  and IE 7 mode don't give the implicit value if it's left off.
2520	// 2) IE 8 should support retrieval of all values from the select.value prop, but doesn't.
2521	inputs = pseudoFormElement._dropdown;
2522	for (var i = 0; i < inputs.length; i++) {
2523		input = inputs[i];
2524		if ((!input.disabled) && (input.style.display != 'none')) {
2525			for (var j = 0; j < input.options.length; j++) {
2526				if (input.options[j].selected) {
2527					if (input.options[j].value == '')
2528						newHiddenInput(input.name, input.options[j].text);
2529					else
2530						newHiddenInput(input.name, input.options[j].value);
2531				}
2532			}
2533		}
2534	}
2535
2536	document.body.appendChild(newForm);
2537	if (debugMode)
2538		alert(newForm.innerHTML);
2539	newForm.submit();
2540}
2541// END PSEUDO-FORMS CODE
2542
2543function phoneStripFormatting(value) {
2544	/// <summary>Strips formatting characters (for display purposes only) from the NANP phone number given.</summary>
2545	/// <param name="value" type="String">Phone number.</summary>
2546	/// <returns type="String">Phone number with formatting cahracter removed.</returns>
2547	return (value + '').replace(/\(/g, '').replace(/\)/g, '').replace(/\s/g, '').replace(/\-/g, '');
2548}
2549
2550function phoneReformat(value, delim) {
2551	/// <summary>Reformats a number for display purposes using delimiter specified.</summary>
2552	/// <param name="value" type="String">The phone number.</summary>
2553	/// <param name="delim" type="String">The delimiter used. If argument is not passed, a hyphen is used.</summary>
2554	/// <returns type="String">Reformatted phone number.</returns>
2555	value = phoneStripFormatting(value);
2556
2557	if (delim == null)
2558		delim = '-';
2559
2560	return value.substr(0, 3) + delim + value.substr(3, 3) + delim + value.substr(6)
2561}
2562
2563function phoneObfuscate(value, secret, delim) {
2564	/// <summary>Reformats a number for display purposes, obfuscating the first 6 digits.</summary>
2565	/// <param name="value" type="String">The phone number.</summary>
2566	/// <param name="secret" type="String">The obfuscation character or string to use in place of a digit in the number. If argument is not pased, a asterisk is used.</summary>
2567	/// <param name="delim" type="String">The delimiter used. If argument is not passed, a hyphen is used.</summary>
2568	/// <returns type="String">Reformatted, obfuscated phone number.</returns>
2569	value = phoneStripFormatting(value);
2570
2571	if (secret == null)
2572		secret = '*';
2573
2574	if (delim == null)
2575		delim = '-';
2576
2577	secret = secret + secret + secret + delim;
2578	return secret + secret + value.substr(6);
2579}
2580
2581function phoneValidate(value, intCountryCode) {
2582	/// <summary>Validates that phone numbers appear to adhere to the NANP format (North American Numbering Plan).</summary>
2583	/// <remarks>
2584	/// Expects area code to be present, and no country code (e.g. 555-555-0123 is valid, 1-555-555-0123 is not).
2585	/// Does not validate that numbers are legal (e.g. area code 123 is invalid, area codes cannot begin with 1).
2586	/// </remarks>
2587	/// <param name="value" type="String">Phone number.</summary>
2588	/// <returns type="Boolean">Whether or not number passed a basic format validation.</returns>
2589	value = phoneStripFormatting(value);
2590	if (value.length == 10)
2591		return numbersOnly.test(value);
2592	else if (value.length == 8 && intCountryCode == 36) //For Australia
2593		return numbersOnly.test(value);
2594	else
2595		return false;
2596}
2597
2598//gets the cookie, if it exists
2599function getCookieValue(cookiename) {
2600	var ck = document.cookie;
2601	var cn = cookiename + "=";
2602	var pos = ck.indexOf(cn);
2603
2604	if (pos != -1) {
2605		var start = pos + cn.length;
2606		var end = ck.indexOf(";", start);
2607		if (end == -1) end = ck.length;
2608		var cookieValue = ck.substring(start, end);
2609		return (cookieValue);
2610	}
2611
2612	return (null);
2613}
2614
2615window['getCookieValue'] = getCookieValue;
2616
2617function setCookieValue(cname, cvalue, exdays) {
2618    var d = new Date();
2619    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
2620    var expires = "expires=" + d.toUTCString();
2621    document.cookie = cname + "=" + cvalue + "; " + expires + "; path=/";
2622}
2623
2624//Gets no of days between 2 dates provided in a string format('mm/dd/yyyy')
2625function dayDifference(first, second) {
2626	return Math.floor((Date.parse(first) - Date.parse(second)) / 86400000);
2627}
2628
2629// Returns whether or not file extension given is acceptable.
2630// Client-side version of FileSystemSafety.IsAllowedFileExtension().
2631function isAllowedFileExtensionWhiteList(ext) {
2632
2633	// Check if the URL contains the string "Admin"
2634	const allowed = window.location.pathname.toLowerCase().startsWith("/admin") ? 1 : 0;
2635
2636	if (!window.acceptedFileExtensions) {
2637		window.acceptedFileExtensions =
2638		{
2639			'.123': 1, '.3g2': 1, '.3gp': 1, '.3gp2': 1, '.7z': allowed, '.aac': 1, '.abw': 1, '.abx': 1, '.accdb': 1, '.accde': 1,
2640			'.accdr': 1, '.accdt': 1, '.accfl': 1, '.ace': allowed, '.ade': 1, '.adp': 1, '.aeh': 1, '.ai': 1, '.aif': 1, '.aiff': 1,
2641			'.amr': 1, '.apng': 1, '.arc': allowed, '.art': 1, '.asc': 1, '.asf': 1, '.asx': 1, '.atom': 1, '.au': 1, '.avi': 1,
2642			'.awt': 1, '.azw': 1, '.azw1': 1, '.b64': 1, '.backup': 1, '.bin': 1, '.bmp': 1, '.bz': 1, '.bz2': 1, '.bzip': 1,
2643			'.bzip2': allowed, '.cab': allowed, '.cad': 1, '.caf': 1, '.cal': 1, '.cgm': 1, '.crtx': 1, '.css': 1, '.csv': 1, '.cwk': 1, '.dap': 1, '.db': 1,
2644			'.dbf': 1, '.dcr': 1, '.dds': 1, '.dex': 1, '.dib': 1, '.dif': 1, '.diz': 1, '.dmg': 1, '.doc': 1, '.docm': 1,
2645			'.docx': 1, '.dot': 1, '.dotm': 1, '.dotx': 1, '.drw': 1, '.ds_store': 1, '.dv': 1, '.dvr-ms': 1, '.dwf': 1, '.dwg': 1,
2646			'.dxf': 1, '.emf': 1, '.eml': 1, '.emlx': 1, '.emz': 1, '.eot': 1, '.eps': 1, '.fbp': 1, '.fdp': 1, '.fhtml': 1,
2647			'.file': 1, '.flac': 1, '.flc': 1, '.fli': 1, '.flp': 1, '.flv': 1, '.fm': 1, '.fm2': 1, '.fm3': 1, '.fm5': 1,
2648			'.fmp': 1, '.fnt': 1, '.fon': 1, '.fp': 1, '.fp3': 1, '.fp5': 1, '.fp7': 1, '.fphtml': 1, '.fpt': 1, '.fpweb': 1,
2649			'.fpx': 1, '.gg': 1, '.gif': 1, '.gnumeric': 1, '.gra': 1, '.gsm': 1, '.gz': allowed, '.hdmov': 1, '.hdp': 1, '.hqx': 1,
2650			'.htm': 1, '.html': 1, '.ical': 1, '.icns': 1, '.ico': 1, '.ics': 1, '.ifo': 1, '.indd': 1, '.isf': 1, '.isu': 1,
2651			'.ivs': 1, '.jbf': 1, '.jfif': 1, '.jpe': 1, '.jpeg': 1, '.jpf': 1, '.jpg': 1, '.jxr': 1, '.key': 1, '.kml': 1, '.kmz': 1,
2652			'.knt': 1, '.kth': 1, '.lhz': 1, '.lit': 1, '.log': 1, '.lrc': 1, '.lrf': 1, '.lrx': 1, '.lst': 1, '.lyr': 1,
2653			'.m4a': 1, '.m4b': 1, '.m4p': 1, '.m4r': 1, '.mdb': 1, '.mde': 1, '.mht': 1, '.mhtml': 1, '.mid': 1, '.midi': 1,
2654			'.mim': 1, '.mix': 1, '.mng': 1, '.mobi': 1, '.mod': 1, '.moi': 1, '.mov': 1, '.movie': 1, '.mp3': 1, '.mp4': 1,
2655			'.mpa': 1, '.mpc': 1, '.mpe': 1, '.mpeg': 1, '.mpg': 1, '.mpv2': 1, '.msg': 1, '.mswmm': 1, '.mxd': 1, '.numbers': 1,
2656			'.odb': 1, '.odf': 1, '.odg': 1, '.ods': 1, '.odx': 1, '.ofm': 1, '.oft': 1, '.ogg': 1, '.ogm': 1, '.ogv': 1,
2657			'.one': 1, '.onepkg': 1, '.opx': 1, '.osis': 1, '.ost': 1, '.otf': 1, '.oth': 1, '.p65': 1, '.p7b': 1, '.pages': 1,
2658			'.pbm': 1, '.pcast': 1, '.pcf': 1, '.pcm': 1, '.pct': 1, '.pcx': 1, '.pdc': 1, '.pdd': 1, '.pdf': 1, '.pdp': 1,
2659			'.pfx': 1, '.pgf': 1, '.pic': 1, '.pict': 1, '.pkg': 1, '.pmd': 1, '.pmf': 1, '.png': 1, '.pot': 1, '.pothtml': 1,
2660			'.potm': 1, '.potx': 1, '.ppam': 1, '.pps': 1, '.ppsm': 1, '.ppsx': 1, '.ppt': 1, '.ppthtml': 1, '.pptm': 1, '.pptx': 1,
2661			'.prc': 1, '.ps': 1, '.psd': 1, '.psp': 1, '.pspimage': 1, '.pst': 1, '.pub': 1, '.pubhtml': 1, '.pubmhtml': 1, '.qbb': 1,
2662			'.qcp': 1, '.qt': 1, '.qxd': 1, '.qxp': 1, '.ra': 1, '.ram': 1, '.ramm': 1, '.rar': allowed, '.raw': 1, '.rax': 1,
2663			'.rm': 1, '.rmh': 1, '.rmi': 1, '.rmm': 1, '.rmvb': 1, '.rmx': 1, '.rp': 1, '.rss': 1, '.rt': 1, '.rtf': 1,
2664			'.rts': 1, '.rv': 1, '.sbx': 1, '.sdf': 1, '.sea': 1, '.shs': 1, '.sit': 1, '.sitx': 1, '.smil': 1, '.snapfireshow': 1,
2665			'.snp': 1, '.stc': 1, '.svg': 1, '.svgz': 1, '.swf': 1, '.sxc': 1, '.sxi': 1, '.tab': 1, '.tar': allowed, '.tex': 1,
2666			'.tga': 1, '.thmx': 1, '.tif': 1, '.tiff': 1, '.tpz': 1, '.tr': 1, '.trm': 1, '.tsv': 1, '.ttf': 1, '.txt': 1,
2667			'.uue': 1, '.vcf': 1, '.vob': 1, '.vrml': 1, '.vsc': 1, '.vsd': 1, '.wab': 1, '.wav': 1, '.wax': 1, '.wbk': 1,
2668			'.wbmp': 1, '.wdp': 1, '.webarchive': 1, '.webloc': 1, '.wk1': 1, '.wk3': 1, '.wm': 1, '.wma': 1, '.wmf': 1, '.wmmp': 1,
2669			'.wmv': 1, '.wmx': 1, '.wpd': 1, '.wps': 1, '.wri': 1, '.wvx': 1, '.xbm': 1, '.xcf': 1, '.xg0': 1, '.xg1': 1,
2670			'.xg2': 1, '.xg3': 1, '.xg4': 1, '.xht': 1, '.xhtm': 1, '.xhtml': 1, '.xif': 1, '.xlam': 1, '.xlb': 1, '.xlc': 1,
2671			'.xld': 1, '.xlk': 1, '.xlm': 1, '.xls': 1, '.xlsb': 1, '.xlshtml': 1, '.xlsm': 1, '.xlsmhtml': 1, '.xlsx': 1, '.xlt': 1,
2672			'.xlthtml': 1, '.xltm': 1, '.xltx': 1, '.xlv': 1, '.xlw': 1, '.xml': 1, '.xpi': 1, '.xps': 1, '.xsf': 1, '.xsn': 1,
2673			'.xtp': 1, '.zabw': 1, '.zip': allowed, '.zipx': allowed
2674		};
2675	}
2676
2677	return (window.acceptedFileExtensions[(ext + '').toLowerCase()] === 1);
2678}
2679
2680function handleServiceMethodError(error) {
2681	throw new Error('A server-side error occurred during the execution of an AJAX request (' +
2682		error.get_exceptionType() +
2683		')!\r\n\r\nAdditional Information:\r\n' +
2684		error.get_message() +
2685		'\r\n\r\nStack Trace:\r\n' +
2686		error.get_stackTrace().trim());
2687}
2688
2689function toggleDisplay(elem) {
2690	elem.style.display =
2691		(elem.style.display == 'none' ? '' : 'none');
2692}
2693
2694// BEGIN Old Character Counter
2695var APENDED_TEXT_LEN = typeof intCountryCode !== 'undefined' && intCountryCode === 840 && typeof FeatureToggles !== 'undefined' ? 9 : 0;
2696var MAX_MESSAGE_SIZE_SMS = 160 - APENDED_TEXT_LEN;
2697var trackLengths = new Array();
2698
2699function registerCharCounter(input, outputElemID, maxMessageSize) {
2700	var outputElem = document.getElementById(outputElemID);
2701	var id = input.id;
2702	var tracker;
2703
2704	tracker = new Object();
2705	tracker.oldLength = -1;
2706	tracker.outputElem = outputElem;
2707	tracker.input = input;
2708	trackLengths[id] = tracker;
2709
2710	setInterval(
2711		'var tracker = trackLengths[\'' + id + '\'];\r\n' +
2712		'var newLength = (tracker.input.value + \'\').length;\r\n' +
2713		'if (newLength != tracker.oldLength) {\r\n' +
2714		'	if (newLength > ' + maxMessageSize + ')' +
2715		'		tracker.outputElem.innerHTML = (newLength - ' + maxMessageSize + ') + " Characters Over";\r\n' +
2716		'	else\r\n' +
2717		'		tracker.outputElem.innerHTML = (' + maxMessageSize + ' - newLength) + " Characters Remaining";\r\n' +
2718		'	\r\n' +
2719		'	tracker.oldLength = newLength;\r\n' +
2720		'}\r\n', 100);
2721}
2722// END Old Character Counter
2723
2724function elemInsideOrEq(elemFirst, elemSecond) {
2725	/// <summary>Gets whether or not second element specified is inside or is equal to first element.</summary>
2726	/// <param name="elemFirst" type="domElement">First element.</param>
2727	/// <param name="elemSecond" type="domElement">Second element.</param>
2728	if (elemFirst == elemSecond)
2729		return true;
2730
2731	if (elemFirst && elemSecond) {
2732		elemSecond = elemSecond.parentNode;
2733
2734		while (elemSecond != null) {
2735			if (elemSecond == elemFirst)
2736				return true;
2737
2738			elemSecond = elemSecond.parentNode;
2739		}
2740	}
2741
2742	return false;
2743}
2744
2745// Do not use in new code. Use jQuery with event.preventDefault().
2746function hookAnchorClick(anchor, fn) {
2747	/// <summary>Hooks an anchor onclick and prevents default HREF behavior.</summary>
2748	/// <param name="anchor" type="domElement">The DOM element to attach the event handler for.</param>
2749	/// <param name="fn" type="Function">Function to be called when anchor is clicked. Should have sender and event argument, in that order.</param>
2750	var clickHandler = function (event) {
2751		var sender;
2752
2753		if (window.event) {
2754			event = window.event;
2755			sender = event.srcElement;
2756		}
2757		else
2758			sender = event.target;
2759
2760		fn(sender, event);
2761
2762		if (event.stopPropagation)
2763			event.stopPropagation();
2764		else
2765			event.cancelBubble = true;
2766
2767		return false;
2768	}
2769
2770	// HACK: MSIE/Opera onclick fails to operate correctly.
2771	if (isie || isie8 || isie7 || isie6 || (document.documentMode < 8) || window.opera)
2772		anchor.onmousedown = clickHandler;
2773	else
2774		anchor.onclick = clickHandler;
2775}
2776
2777// For ClientCharacterCounter control.
2778var registeredCounters = null;
2779function registerCounter(assocElem, counterElem, fmtStandard, fmtOver, maxChars) {
2780	if (assocElem == null || counterElem == null || maxChars == null || fmtStandard == null || fmtOver == null)
2781		return;
2782
2783	if (registeredCounters == null) {
2784		registeredCounters = [];
2785
2786		setInterval(function () {
2787			for (var i = 0, l = registeredCounters.length; i < l; i++) {
2788				if (registeredCounters[i].counter && registeredCounters[i].input) {
2789					var len;
2790					if (typeof registeredCounters[i].input.value === 'undefined')
2791						len = registeredCounters[i].input.val().length;
2792					else
2793						len = registeredCounters[i].input.value.length;
2794					var prevLen = registeredCounters[i].prevLen;
2795
2796					if (len == prevLen)
2797						continue;
2798					else {
2799						registeredCounters[i].prevLen = len;
2800
2801						var max = registeredCounters[i].maxChars;
2802						var numToDisplay = max - len;
2803
2804						var fmtToUse = (numToDisplay >= 0
2805							? registeredCounters[i].fmtStandard
2806							: registeredCounters[i].fmtOver);
2807
2808						if (numToDisplay >= 0)
2809							registeredCounters[i].counter.className = 'counterUnderLimit';
2810						else
2811							registeredCounters[i].counter.className = 'counterOverLimit';
2812
2813						numToDisplay = Math.abs(numToDisplay);
2814
2815						registeredCounters[i].counter.innerHTML = fmtToUse
2816							.replace(/\{0\}/g, numToDisplay)
2817							.replace(/\{1\}/g, (numToDisplay == 1 ? '' : 's'));
2818					}
2819				}
2820			}
2821		}, 100);
2822	}
2823
2824	registeredCounters.push({
2825		"fmtStandard": fmtStandard,
2826		"fmtOver": fmtOver,
2827		"counter": counterElem,
2828		"input": assocElem,
2829		"prevLen": -1,
2830		"maxChars": maxChars
2831	});
2832}
2833
2834// Detects if nextElementSibling/previousElementSibling are present.
2835function detectElementSiblingSupport() {
2836	var p = document.createElement('div');
2837	var c1 = document.createElement('div');
2838	var c2 = document.createElement('div');
2839
2840	p.appendChild(c1);
2841	p.appendChild(c2);
2842
2843	return (c1.nextElementSibling != null);
2844}
2845
2846// Gets next sibling element. Version for browsers missing nextElementSibling DOM property.
2847function nextElementSibling(elem) {
2848	elem = elem.nextSibling;
2849
2850	while (elem != null) {
2851		if (elem.nodeType == 1)
2852			return elem;
2853
2854		elem = elem.nextSibling;
2855	}
2856
2857	return null;
2858}
2859
2860// Gets previous sibling element. Version for browsers missing previousElementSibling DOM property.
2861function previousElementSibling(elem) {
2862	elem = elem.previousSibling;
2863
2864	while (elem != null) {
2865		if (elem.nodeType == 1)
2866			return elem;
2867
2868		elem = elem.previousSibling;
2869	}
2870
2871	return null;
2872}
2873
2874// Gets first child element. Version for browsers missing firstElementChild DOM property.
2875function firstElementChild(elem) {
2876	elem = elem.firstChild;
2877
2878	while (elem != null) {
2879		if (elem.nodeType == 1)
2880			return elem;
2881
2882		elem = elem.nextSibling;
2883	}
2884
2885	return null;
2886}
2887
2888if (detectElementSiblingSupport()) {
2889	// If browsers support built-in DOM properties, just use those.
2890	nextElementSibling = function (elem) { return elem.nextElementSibling; }
2891	previousElementSibling = function (elem) { return elem.previousElementSibling; }
2892	firstElementChild = function (elem) { return elem.firstElementChild; }
2893}
2894
2895function haltEvent(event, windowEvent) {
2896	if (windowEvent & !window.opera)
2897		windowEvent.cancelBubble();
2898	else {
2899		if (event.stopPropagation)
2900			event.stopPropagation();
2901
2902		if (event.preventDefault)
2903			event.preventDefault();
2904	}
2905}
2906
2907// Gets absolute left offset.
2908function absoluteOffsetLeft(oElem) {
2909	var oLeft = 0;
2910
2911	while (oElem != null) {
2912		oLeft += oElem.offsetLeft;
2913		oElem = oElem.offsetParent;
2914	}
2915
2916	return oLeft;
2917}
2918
2919function imposeMaxLength(e, Object, MaxLen) {
2920	//Truncate to maximum length
2921	if (Object.value.length > MaxLen)
2922		Object.value = Object.value.substring(0, MaxLen);
2923
2924	//ALLOW:        BACKSPACE           DELETE                  LEFT ARROW              UP ARROW            RIGHT ARROW             DOWN ARROW
2925	if ((e.keyCode == '8') || (e.keyCode == '46') || (e.keyCode == '37') || (e.keyCode == '38') || (e.keyCode == '39') || (e.keyCode == '40'))
2926		return true;
2927
2928	return (Object.value.length <= MaxLen);
2929}
2930
2931function checkURL(val, showAlert) {
2932	val = TrimString(val);
2933	if (val != '' && (val.substr(0, 7) != 'http://' && val.substr(0, 8) != 'https://' && val.substr(0, 6) != 'ftp://' && val.substr(0, 1) != '/')) {
2934		if (arguments.length == 1 || showAlert)
2935			alert('All URLs must begin with http:// or https:// or ftp://.\nAll internal links must start with a /.');
2936
2937		return false;
2938	}
2939	return true;
2940}
2941
2942function toSQLSafe(formvar) {
2943	var s = String(formvar);
2944	s = (s.replace(/'/gi, "&#39")).replace(/"/gi, "&#34");
2945	return s;
2946}
2947
2948function cancelFE(needsConfirm) {
2949	if (needsConfirm) {
2950		if (!confirm("You will discard any unsaved changes. Do you want to proceed?"))
2951			return;
2952	}
2953	window.parent.closeModalDialog('editItemBehavior');
2954	return false;
2955}
2956
2957function getThumbNailPath(path, width, height) {
2958	var lastSlashPos = path.lastIndexOf('/');
2959	var filename = path.substr(lastSlashPos + 1);
2960	var directory = path.substr(0, lastSlashPos);
2961	var lastDotPos = filename.lastIndexOf('.');
2962	var filenameWithOutExtension = filename.substr(0, lastDotPos)
2963	var fileExtension = filename.substr(lastDotPos)
2964	return directory + "/ThumbNails/" + filenameWithOutExtension + "_" + width + "x" + height + "_thumb" + fileExtension;
2965}
2966
2967function measureHtml(html, fontStyle) {
2968	var tmp = document.createElement('span');
2969	tmp.style.display = 'inline';
2970	tmp.style.position = 'absolute';
2971	tmp.style.top = '-1000px';
2972	tmp.style.left = '-1000px';
2973	tmp.style.font = fontStyle;
2974	tmp.innerHTML = html;
2975
2976	document.body.appendChild(tmp);
2977	var retVal = { width: tmp.clientWidth, height: tmp.clientHeight };
2978	document.body.removeChild(tmp);
2979
2980	return retVal;
2981}
2982
2983function fileValidateError(errorType) {
2984	if (errorType == 1)
2985		alert("A file you tried to upload was not of a permitted type. Only *.jpeg, *.jpg, *.gif, *.png, *.bmp are allowed");
2986	else
2987		alert("You have an invalid character in your filename. These are the accepted characters: a-z 0-9 ~ !( ) - + = [ ] { } , . $");
2988}
2989
2990function getNumericThousandsSeparator() {
2991	var dummy = new Number(11111111);
2992	var thousandSep = dummy.toLocaleString().replace(/1/g, '');
2993	return (thousandSep.length > 0 ? thousandSep.charAt(0) : ',');
2994}
2995
2996function getNumericDecimalSeparator() {
2997	var dummy = new Number(1.1);
2998	var thousandSep = dummy.toLocaleString().replace(/1/g, '');
2999	return (thousandSep.length > 0 ? thousandSep.charAt(0) : '.');
3000}
3001
3002function ChangeDateFormat(elem) {
3003	if (elem.value != "") {
3004		var Error = false;
3005		var dateSplit = (elem.value).split("/");
3006
3007		if (dateSplit.length == 3) {
3008			if (dateSplit[0] <= 12 && dateSplit[1] <= 31) {
3009				var d = new Date(elem.value);
3010				var currentDate = new Date();
3011
3012				var selectedDate = d.getDate();
3013				var selectedMonth = d.getMonth();
3014				var SelectedYear = d.getFullYear();
3015
3016				if (isNaN(selectedDate))
3017					Error = true;
3018				else if (isNaN(selectedDate))
3019					Error = true;
3020				else if (isNaN(selectedDate))
3021					Error = true;
3022				if (Error == false) {
3023					if (selectedDate.toString().length == 1)
3024						selectedDate = '0' + selectedDate;
3025
3026					selectedMonth++;
3027
3028					if (selectedMonth.toString().length == 1)
3029						selectedMonth = '0' + selectedMonth;
3030
3031					currentYear = currentDate.getFullYear();
3032
3033					if (SelectedYear.toString().substr(0, 2) < 20)
3034						SelectedYear = currentYear;
3035					elem.value = selectedMonth + '/' + selectedDate + '/' + SelectedYear;
3036				}
3037			}
3038			else
3039				Error = true;
3040		}
3041		else
3042			Error = true;
3043
3044		if (Error == true) {
3045			alert('Date should be in the format MM/DD/YYY');
3046			elem.value = "";
3047		}
3048	}
3049}
3050
3051function ChangeDateFormatNew(elem) {
3052	return isDateNew(elem.value);
3053}
3054
3055function isSilverlightInstalled() {
3056	var isSilverlightInstalled = false;
3057	try {
3058		//check on IE
3059		try {
3060			var slControl = new ActiveXObject('AgControl.AgControl');
3061			isSilverlightInstalled = true;
3062			isSilverlightInstalled = true;
3063		}
3064		catch (e) {
3065			//either not installed or not IE. Check Firefox.
3066			if (navigator.plugins["Silverlight Plug-In"]) {
3067				isSilverlightInstalled = true;
3068			}
3069		}
3070	}
3071	catch (e) {
3072		//we don't want to leak exceptions. However, you may want
3073		//to add exception tracking code here.
3074	}
3075	return isSilverlightInstalled;
3076}
3077
3078function setModalClass(cssClass, behaviorID) {
3079	var modalContainer = document.getElementById(behaviorID._PopupControlID);
3080
3081	if (modalContainer)
3082		modalContainer.className = 'modalContainer modalContainerCP ' + cssClass;
3083}
3084
3085function setModalClassFE(cssClass, behaviorID) {
3086	var modalContainer = document.getElementById(behaviorID._PopupControlID);
3087
3088	if (modalContainer)
3089		modalContainer.className = 'modalContainer ' + cssClass;
3090}
3091
3092//------------------- Copy Link ---------------------//
3093function showCopyLinkWindow(relatedLink, absoluteAddress, behavior, ifrID) {
3094	if (behavior) {
3095		setModalClass('modalCopyLink', behavior);
3096		var iFrame = document.getElementById(ifrID);
3097		iFrame.src = '/common/admin/CopyLink.aspx?relatedLink=' + encodeURIComponent(relatedLink) + '&absoluteAddress=' + encodeURIComponent(absoluteAddress);
3098		iFrame.style.display = 'block';
3099		behavior.show();
3100	} else {
3101		openCpModal({
3102			title: 'Copy Link',
3103			className: 'modalCopyLink',
3104			isFrontEnd: false,
3105			useIframe: true,
3106			url: '/common/admin/CopyLink.aspx?relatedLink=' + encodeURIComponent(relatedLink) + '&absoluteAddress=' + encodeURIComponent(absoluteAddress)
3107		});
3108	}
3109}
3110
3111function showCopyLinkWindowUsingAddress(absoluteAddress) {
3112	var relatedUrl = absoluteAddress.replace(window.location.host, '');
3113	relatedUrl = relatedUrl.replace(window.location.protocol + '//', '');
3114
3115	var behavior = $find('copyLinkBehavior');
3116	if (behavior)
3117		showCopyLinkWindow(relatedUrl, absoluteAddress, behavior, 'copyLinkDialog');
3118	else
3119		showCopyLinkWindow(relatedUrl, absoluteAddress, $find('editItemBehavior'), 'liveEditDialog');
3120}
3121
3122function showCopyLinkWindowUsingRelatedLink(relatedUrl) {
3123	var absoluteUrl = window.location.protocol + '//' + window.location.host + relatedUrl;
3124
3125	var behavior = $find('copyLinkBehavior');
3126	if (behavior)
3127		showCopyLinkWindow(relatedUrl, absoluteUrl, behavior, 'copyLinkDialog');
3128	else
3129		showCopyLinkWindow(relatedUrl, absoluteUrl, $find('editItemBehavior'), 'liveEditDialog');
3130}
3131
3132function closeCopyModal() {
3133	var behavior = $find('copyLinkBehavior');
3134	if (behavior)
3135		behavior.hide();
3136	else {
3137		behavior = $find('editItemBehavior');
3138		if (behavior)
3139			behavior.hide();
3140		else
3141			closeCpModal();
3142	}
3143}
3144//------------------- Copy Link End---------------------//
3145
3146//Parses the query string for the specified paramter and returns the value
3147//Returns "" if the parameter is not found
3148function GetQueryStringParameter(name) {
3149	name = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
3150	var regexS = "[\\?&]" + name + "=([^&#]*)";
3151	var regex = new RegExp(regexS);
3152	var results = regex.exec(window.location.href);
3153	if (results == null)
3154		return "";
3155	else
3156		return results[1];
3157}
3158
3159function setModalTitle(title, behaviorID) {
3160	if (behaviorID) {
3161		$('#' + behaviorID._PopupControlID).find('.modalTitle').text(title);
3162	}
3163	else {
3164		//if behaviorID is not provided, do the same as setModalTitle on FrontEnd.js
3165		var titleElem = document.getElementById('ctl00_LiveEditModalTitle');
3166
3167		if (titleElem == null)
3168			titleElem = document.getElementById('ctl00_ct100_LiveEditModalTitle');
3169
3170		if (titleElem == null)
3171			titleElem = document.getElementById('ctl00_ctl00_NotifyMeModalTitle');
3172
3173		if (titleElem)
3174			titleElem.innerHTML = title;
3175	}
3176}
3177
3178//------------------- Copy Link End---------------------//
3179
3180function isNull(object, replacement) {
3181	return object == null ? replacement : object;
3182}
3183
3184// Validates domain of email with service (ensures MX record present, DNS name valid, acceptable format).
3185// The callbacks object should contain the following methods:
3186// * badFormat - Email format invalid. Will also be thrown for null/empty email addresses.
3187// * mxMissing - MX record missing for the domain.
3188// * dnsError - A DNS error occurred (domain invalid, invalid characters in domain, etc).
3189// * success - The email appears to be valid.
3190function validateEmailDomain(emailAddress, callbacks) {
3191	$.ajax({
3192		type: "POST",
3193		url: "/Services/ValidateEmail.ashx",
3194		data: { email: emailAddress },
3195		success: function (data, textStatus, jqXHR) {
3196			switch (data.d) {
3197				case 1:
3198					callbacks.badFormat(emailAddress);
3199					break;
3200				case 2:
3201					callbacks.mxMissing(emailAddress);
3202					break;
3203				case 3:
3204					callbacks.dnsError(emailAddress);
3205					break;
3206				case 0:
3207				default:
3208					callbacks.success(emailAddress);
3209					break;
3210			}
3211		}
3212	});
3213}
3214
3215//Called when opening action menu.
3216function openPopUp(id, event) {
3217	var $popUp = $(document.getElementById(id));
3218
3219	if ($popUp.hasClass('popped')) {
3220		//do not do anything if popup is already open.
3221		return false;
3222	}
3223
3224	//Hide all popups already open if nesessary.
3225	$('.popUp').fadeOut(200).removeClass('popped');
3226	$('.popUpParent').removeClass('popped');
3227
3228	//Open popup
3229	$popUp.fadeIn(200);
3230	$popUp.addClass('popped');
3231	$popUp.parents('.popUpParent').addClass('popped');
3232
3233	//prevent triggering any other event.
3234	if (window.event)
3235		window.event.cancelBubble = true;
3236	else
3237		event.stopPropagation();
3238}
3239
3240function SignIn() {
3241	window.location.href = '/MyAccount?from=url&url=' + window.location.pathname + window.location.search;
3242}
3243
3244function SignOut() {
3245	window.location.href = '/publiclogin.aspx?out=true&txtRedirect=' + window.location.pathname.substring(1) + window.location.search;
3246}
3247
3248function removeIEParagraphs(editor) {
3249	editor.attachEventHandler("onkeyup", function (e) {
3250		if (e.keyCode == 8 || e.keyCode == 46 || e.keyCode == 13) {
3251			var result = '';
3252			var re = new RegExp("<[P]>&nbsp;<\\/[P]>", "gi");
3253
3254			var m = re.exec(editor.get_html(true));
3255
3256			if (m == null) {
3257				return;
3258			} else {
3259				result = editor.get_html(true).replace(re, '<BR>');
3260				editor.set_html(result);
3261			}
3262		}
3263	});
3264}
3265
3266//To toggle the slide show and image manger menu items based on if the img is a from a slide show or not.
3267function setMenuItems(editor) {
3268	var contextMenu = editor.getContextMenuByTagName("IMG");
3269	if (!contextMenu) return;
3270
3271	//Attach to the context menu show event, obtain editor selection and determine which tools to show
3272	contextMenu.add_show(function () {
3273		//Must be an image, the context menu would not fire
3274		var sel = editor.getSelectedElement();
3275
3276		//An array of menu item objects
3277		var menuItems = contextMenu.get_items();
3278		var menuItem = null;
3279
3280		//reset to show all and then disable the menu item based on currently selection
3281		for (i = 0; i < menuItems.length; i++) {
3282			menuItems[i].get_element().style.display = "";
3283			menuItems[i].get_element().parentNode.style.display = "";
3284		} //end for
3285
3286		if (sel.getAttribute("slideshowimage")) {
3287			menuItem = menuItems[menuItems.length - 3];
3288			menuItem.get_element().style.display = "none";
3289			menuItem.get_element().parentNode.style.display = "none";
3290
3291			menuItem = menuItems[menuItems.length - 2];
3292			menuItem.get_element().style.display = "none";
3293			menuItem.get_element().parentNode.style.display = "none";
3294		} else {
3295			menuItem = menuItems[menuItems.length - 1];
3296			menuItem.get_element().style.display = "none";
3297			menuItem.get_element().parentNode.style.display = "none";
3298		}
3299	});
3300}
3301
3302function integersOnly(e, input) {
3303	var charCode = (e.which) ? e.which : e.keyCode;
3304
3305	var keyChar = String.fromCharCode(charCode);
3306	var currentValue = $(input).val();
3307	var allowNegativeSign = !$(input).hasClass("positive") && currentValue.indexOf('-') == -1 && (currentValue.length == 0 || currentValue == window.getSelection().toString());
3308	if (keyChar == '-' && allowNegativeSign)
3309		return true;
3310
3311	if (charCode > 31 && (charCode < 48 || charCode > 57))
3312		return false;
3313
3314	return true;
3315}
3316
3317function decimalOnly(e, input, skipSelected) {
3318	skipSelected = (skipSelected == undefined || skipSelected == null) ? false : skipSelected;
3319
3320	var charCode = (e.which) ? e.which : e.keyCode;
3321
3322	var keyChar = String.fromCharCode(charCode);
3323	var currentValue = $(input).val();
3324	var hasDecimalPoint = currentValue.indexOf('.') != -1;
3325	if ((keyChar == '.' && !hasDecimalPoint))
3326		return true;
3327
3328	if (!skipSelected && isTextSelected(input))
3329		return true;
3330
3331	return integersOnly(e, input);
3332}
3333
3334function isTextSelected(input) {
3335	if (typeof input.selectionStart == "number") {
3336		return input.selectionStart == 0 && input.selectionEnd == input.value.length;
3337	} else if (typeof document.selection != "undefined") {
3338		input.focus();
3339		return document.selection.createRange().text == input.value;
3340	}
3341}
3342
3343function validFileName(e) {
3344	var charCode = (e.which) ? e.which : e.keyCode;
3345	var keyChar = String.fromCharCode(charCode);
3346	var invalidCharacters = "\\/:*?\"<>|',";
3347
3348	return invalidCharacters.indexOf(keyChar) < 0;
3349}
3350
3351function isValidURL(value) {
3352	return /^(https?:\/\/|ftp:\/\/|\/).+/i.test(value);
3353}
3354function isValidAbsoluteURL(value) {
3355	try {
3356		var parsedUrl = new URL(value, window.location.href);
3357	} catch (e) {
3358		return false;
3359	}
3360	return /^(https?|ftp):\/\//i.test(value) && /^(https?|ftp):$/.test(parsedUrl.protocol) && parsedUrl.host != '';
3361}
3362
3363function validateLink(link) {
3364	if (link != '') {
3365		if ((link.indexOf('http://') == -1) &&
3366		 (link.indexOf('https://') == -1) &&
3367		 (link.substr(0, 1) != '/')) {
3368			return false;
3369		}
3370	}
3371	return true;
3372}
3373
3374// Check if string is a whole number(digits only).
3375function isWholeNumber(val) {
3376	return String(val).search(/^(([1-9]{1}\d{0,2},(\d{3},)*\d{3})|([1-9]{1}\d{0,}))$/) != -1;
3377}
3378
3379// Checks that an input string is a decimal number
3380function isDecimalOrZero(val) {
3381	isDecimal_re = /^\d{1,5}(\.\d{1,2})?$/;
3382	return String(val).search(isDecimal_re) != -1;
3383}
3384
3385//Allows login to CPC
3386function RebuildCSS(menu) {
3387	if (confirm('This will take some time\nand the site may look funny during the process.\nAre you sure?')) {
3388		var frmARC = document.forms.frmAdminRebuldCSS;
3389		frmARC.ysnNeedInclude.value = '1';
3390		frmARC.intMenu.value = menu;
3391		frmARC.submit();
3392	}
3393}
3394
3395//Allows login to CPC
3396function adminGetHelp(helpUrl, newWindow) {
3397	document.cpconnect.action = document.cpconnect.action.split('?')[0] + '?from=url&url=' + encodeURIComponent(helpUrl);
3398	cpconnecttLogin();
3399}
3400
3401function connectCPC() {
3402	document.cpconnect.action = document.cpconnect.action.split('?')[0];
3403	var ifr = document.createElement('iframe');
3404	ifr.name = "submitCPCFrame";
3405	ifr.id = "submitCPCFrame";
3406	ifr.style.display = 'none';
3407	var frm = $(document.cpconnect).clone().get(0);
3408	frm.name = "iframeCPCConnect"
3409	frm.target = 'submitCPCFrame';
3410	ifr.appendChild(frm);
3411	document.body.appendChild(ifr);
3412	frm.submit();
3413}
3414
3415function showFeatureNotAvailablePopup(hypothesisID) {
3416	var data = {
3417		id: hypothesisID
3418	};
3419
3420	$('.emailPage').removeClass('emailPage');
3421
3422	$.ajax({
3423		url: '/FeatureNotAvailable/Popup',
3424		type: 'GET',
3425		data: {
3426			hypothesisID: hypothesisID
3427		},
3428		cache: false,
3429		success: function (response) {
3430			if (response.action == 'modal') {
3431				openCpModal({
3432					title: 'Feature Not Yet Available',
3433					className: 'featureNotAvailableModal moduleContentNew modalContainer',
3434					htmlContent: response.html,
3435					autoAdjust: true,
3436					isFrontEnd: true,
3437					elementID: 'featureNotAvailableModal'
3438				});
3439			} else {
3440				window.location = '/FeatureNotAvailable?hypothesisID='
3441                    + hypothesisID
3442                    + '&referrerUrl=' + window.location;
3443			}
3444		},
3445		beforeSend: function () {
3446			ajaxPostBackStart('Loading');
3447		},
3448		complete: function () {
3449			ajaxPostBackEnd();
3450		}
3451	});
3452}
3453
3454function getDateFormat() {
3455	if (!gDateFormat) {
3456		$.ajax({
3457			url: "/GetDateFormat",
3458			type: "GET",
3459			success: function (response) {
3460				if (response.DateFormat)
3461					gDateFormat = response.DateFormat;
3462			},
3463			error: function (xhr, textStatus, exception) {
3464				gDateFormat = "MM/dd/yyyy";
3465			},
3466			async: false
3467		});
3468	}
3469
3470	return gDateFormat == null ? "MM/dd/yyyy" : gDateFormat;	
3471
3472}
3473
3474function getdDateFormat() {
3475	var dateFormat;
3476
3477	$.ajax({
3478		url: '/Utility/GetdDateFormat',
3479		async: false,
3480		type: 'GET',
3481		dataType: 'json',
3482		success: function (data) {
3483			dateFormat = data.dateFormat;
3484		},
3485		error: function (jqXHR, textStatus, errorThrown) {
3486			dateFormat = "mm/dd/yyyy";
3487		}
3488	});
3489
3490	return dateFormat;
3491}
3492
3493function getDateFromInput(datePickerID, keepDayBeforeMonth) {
3494	var datePicker = $(datePickerID);
3495	var date;
3496	var dateFormat = keepDayBeforeMonth ? getDateFormat() : "mm/dd/yyyy";
3497	//See if datepicker if so becuase of UK format we cannot just grab the value
3498	if (!isNaN(datePicker.data('tDatePicker')) && datePicker.data('tDatePicker') && datePicker.data('tDatePicker').value()) {
3499	    var dateValTmp = new dateValidator();
3500		date = dateValTmp.format(dateFormat,new Date(datePicker.data('tDatePicker').value()));
3501	} else {
3502		if (datePicker.val()) {
3503			var dayBeforeMonthOn = getDateFormat().toLocaleLowerCase() == "dd/mm/yyyy" ? true : false;
3504			//Check if valid date before trying to format            			
3505			var dateString = checkDateFormatReturnUSString(datePicker.val(), dayBeforeMonthOn);
3506			var dateVal = new dateValidator();
3507			if (dateVal.dateValidateNew(dateString, false)) {
3508				date = dateVal.format(dateFormat,new Date(checkDateFormatReturnUSString(dateString, false)));
3509			} else {
3510				//Send the date string formatted eventhough invalid date. Allow date validation to return approiate error
3511				if (keepDayBeforeMonth) {
3512					date = dateString;
3513				} else {
3514					date = checkDateFormatReturnUSString(dateString, true);
3515				}
3516			}
3517		}
3518	}
3519	return date;
3520}
3521
3522function formatUkDateReturnUSString(dateStr, isForce) {
3523	var retVal;
3524	if (isForce || getDateFormat().toLocaleLowerCase() == "dd/mm/yyyy") {
3525		dateStr = dateStr.replace(/\-/g, '/');
3526		dateStr = dateStr.split("/");
3527		retVal = dateStr[1] + "/" + dateStr[0] + "/" + dateStr[2];
3528	} else {
3529		retVal = dateStr;
3530	}
3531	return retVal;
3532}
3533
3534function formatRFC3339DateReturnString(dateStr, keepDayBeforeMonth) {
3535	var retVal;
3536	var dateStrMod = dateStr.replace(/\-/g, '/');
3537	dateStrMod = dateStr.split("/");
3538	if (dateStrMod.length == 3 && dateStrMod[0].length == 4) {
3539		if (keepDayBeforeMonth && getDateFormat().toLowerCase() == "dd/mm/yyyy") {
3540			retVal = dateStrMod[2] + "/" + dateStrMod[1] + "/" + dateStrMod[0];
3541        } else {
3542			retVal = dateStrMod[1] + "/" + dateStrMod[2] + "/" + dateStrMod[0];
3543		}
3544	} else {
3545		retVal = dateStr;
3546	}
3547	return retVal;
3548}
3549
3550function checkDateFormatReturnUSString(dateStr, keepDayBeforeMonth) {
3551	var retVal;
3552	if (dateStr) {
3553		var splitDate = dateStr;
3554		dateStr = dateStr.replace(/\-/g, '/');
3555		splitDate = dateStr.split("/");
3556		if (splitDate.length == 3) {
3557			if (splitDate[0].length == 4) {
3558				retVal = formatRFC3339DateReturnString(dateStr, keepDayBeforeMonth);
3559			} else if (keepDayBeforeMonth) {
3560				retVal = dateStr;
3561			} else {
3562				var dateVal = new dateValidator();
3563				retVal = formatUkDateReturnUSString(dateVal.cleanDate(dateStr));
3564			}
3565		} else {
3566			retVal = dateStr;
3567		}
3568	}
3569	return retVal;
3570}
3571
3572//IE no longer displays as IE by design code to determin if it is IE11
3573function isIE11() {
3574	var trident = !!navigator.userAgent.match(/Trident\/7.0/);
3575	var net = !!navigator.userAgent.match(/.NET4.0E/);
3576	return trident && net;
3577}
3578
3579function isValidUrl(url) {
3580	return url.match(/^(ht|f)tps?:\/\/[a-z0-9-\.]+\.[a-z]{2,4}\/?([^\s<>\#%"\,\{\}\\|\\\^\[\]`]+)?$/);
3581}
3582
3583function isValidAbsoluteUrl(value) {
3584	return isValidAbsoluteURL(value);
3585}
3586
3587//Replaces the given tag with the tag to replace inside the element for all occurences of the tag within the element.
3588//$element - The element to perform the replace to
3589//tagToReplace - Tag to be replaced replace provided as string, ex: "i", "b", "strong" etc
3590//tagToReplaceWith - Tag to replace with, provided as string, ex: "i", "b", "strong" etc
3591function replaceTag($element, tagToReplace, tagToReplaceWith) {
3592    var $tagElemsToReplace = $element.find(tagToReplace);
3593    $tagElemsToReplace.each(function () {
3594        var $tagElem = $(this);
3595        var tagElemeHtml = $tagElem.html();
3596        $tagElem.replaceWith('<' + tagToReplaceWith + '>' + tagElemeHtml + '</' + tagToReplaceWith + '>');        
3597    });
3598}
3599
3600window.addEventListener("load", function () {
3601	if (MutationObserver != null) {
3602		if ($('.contentContainerOld').length > 0 && ($('.spellchecker').length > 0 || $('[id^="DialogOpener"]').length > 0)) {
3603			var observer = new MutationObserver(function moveTelerikModalOverlay(mutations) {
3604				mutations.forEach(function (mutation) {
3605					if (!mutation.addedNodes) return;
3606
3607					for (var i = 0; i < mutation.addedNodes.length; i++) {
3608						// do things to your newly added nodes here
3609						var node = mutation.addedNodes[i];
3610
3611						if (node.classList != null && node.classList.contains("TelerikModalOverlay")) {
3612							$('.contentContainerOld').after(node);
3613						}
3614					}
3615				});
3616			});
3617
3618			observer.observe(document.getElementsByClassName('contentContainerOld')[0], {
3619				childList: true,
3620				subtree: true,
3621				attributes: false,
3622				characterData: false
3623			});
3624		}
3625	}
3626});
3627
3628if (!Array.prototype.includes) {
3629	Array.prototype.includes = function (searchElement) {
3630		'use strict';
3631		if (this == null) {
3632			throw new TypeError('Array.prototype.includes called on null or undefined');
3633		}
3634
3635		var O = Object(this);
3636		var len = parseInt(O.length, 10) || 0;
3637		if (len === 0) {
3638			return false;
3639		}
3640		var n = parseInt(arguments[1], 10) || 0;
3641		var k;
3642		if (n >= 0) {
3643			k = n;
3644		} else {
3645			k = len + n;
3646			if (k < 0) { k = 0; }
3647		}
3648		var currentElement;
3649		while (k < len) {
3650			currentElement = O[k];
3651			if (searchElement === currentElement ||
3652			   (searchElement !== searchElement && currentElement !== currentElement)) { // NaN !== NaN
3653				return true;
3654			}
3655			k++;
3656		}
3657		return false;
3658	};
3659}
3660
3661function isMsie() {
3662	ua = navigator.userAgent;
3663	/* MSIE used to detect old browsers and Trident used to newer ones*/
3664	var is_ie = ua.indexOf("MSIE ") > -1 || ua.indexOf("Trident/") > -1;
3665
3666	return is_ie;
3667}
3668
3669function isMozilla() {
3670	return navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
3671}
3672
3673function browserVersion() {
3674	ua = navigator.userAgent;
3675	var browserVersion = null;
3676	var verOffset = null;
3677	if (isMsie()) {
3678		verOffset = ua.indexOf("rv:");
3679		browserVersion = ua.slice(verOffset + 3).slice(0, 4);
3680	}
3681	else if (isMozilla()) {
3682		verOffset = ua.indexOf("Firefox")
3683		browserVersion=  ua.substring(verOffset + 8)
3684	}
3685	return browserVersion;
3686}
3687
3688function setDatepickerHighlightedDate(date, datePickerId) {
3689	var dateFormat = getdDateFormat();
3690	var momentDate = moment(date, dateFormat.toUpperCase()).format('MM/DD/YYYY');
3691	if (momentDate.toLowerCase() !== "invalid date") {
3692		$('#' + datePickerId).pickadate('picker').set('highlight', date, { format: dateFormat });
3693	}
3694}
3695;
3696/// <reference path="../../Common/Controls/jquery-ui-1.14.2/jquery-ui.js" />
3697if (!window.Core) {
3698	window.Core = new CoreNamespace();
3699}
3700
3701function AJAX(url, type, json, callBack, showLoadingMessage, contentType, forceCallBack, suppressErrorMessage) {
3702	contentType = contentType || 'application/x-www-form-urlencoded; charset=UTF-8';
3703	showLoadingMessage = showLoadingMessage == null ? true : showLoadingMessage;
3704	forceCallBack = forceCallBack == null ? false : forceCallBack;
3705	if (typeof (suppressErrorMessage) === 'undefined') suppressErrorMessage = false;
3706	$.ajax({
3707		url: url,
3708		type: type,
3709		contentType: contentType,
3710		data: json,
3711		success: function (response) {
3712			if (response.ErrorMessage && !forceCallBack) {
3713				if (response.ErrorMessage.indexOf('You do not have permission to perform this action.') != -1 && !isUserLoggedIn()) { // 079B4F43 
3714					alert('You are not logged in. Please login to continue.');
3715					location.href = '/myaccount?from=url&url=' + window.location.pathname;
3716				} else {
3717					alert(response.ErrorMessage);
3718				}
3719			}
3720			else if (response.RedirectURL && !forceCallBack)
3721				window.location.href = response.RedirectURL;
3722			else if (callBack)
3723				callBack(response);
3724		},
3725		beforeSend: function () {
3726			if (showLoadingMessage) {
3727				ajaxPostBackStart('Loading');
3728			}
3729		},
3730		complete: function () {
3731			if (showLoadingMessage) {
3732				ajaxPostBackEnd();
3733			}
3734		},
3735		error: function (xhr, textStatus, exception) {
3736			if (!suppressErrorMessage) {
3737				alert('Error: ' + xhr.statusText + '\nStatus: ' + xhr.status);
3738			}
3739		}
3740	});
3741}
3742
3743function isUserLoggedIn() {
3744	var result = true; // if there is an error lets not show the login message.
3745	$.ajaxSetup({ async: false, ignoreEditor: true });
3746	$.post('/Utility/IsUserLoggedIn', function (data) {
3747		result = data;
3748	});
3749	$.ajaxSetup({ async: true, ignoreEditor: false });
3750	return result;
3751}
3752
3753///Method to pause a javascript execution for x seconds, works like sleep(). VB
3754function sleep(seconds) {
3755	var max_sec = new Date().getTime();
3756	while (new Date() < max_sec + seconds * 1000) { }
3757	return true;
3758}
3759
3760if (!String.prototype.format) {
3761	String.prototype.format = function () {
3762		var args = arguments;
3763		return this.replace(/{(\d+)}/g, function (match, number) {
3764			return typeof args[number] != 'undefined'
3765				? args[number]
3766				: match
3767				;
3768		});
3769	};
3770}
3771
3772if (!String.prototype.isNullOrWhiteSpace) {
3773	String.prototype.isNullOrWhiteSpace = function () {
3774		return this == null || this.trim() == '';
3775	};
3776}
3777
3778function isValidMoney(value) {
3779	var isValid = false;
3780	if (value && value != '')
3781		isValid = /^\$?\s*\d+(,\d{3})*(\.\d{1,2})?$/.test(value);
3782	return isValid;
3783};
3784
3785if (typeof String.prototype.startsWith != 'function') {
3786	String.prototype.startsWith = function (str) {
3787		return this.slice(0, str.length) == str;
3788	};
3789}
3790
3791String.prototype.format = String.prototype.f = function () {
3792	var s = this,
3793		i = arguments.length;
3794
3795	while (i--) {
3796		s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
3797	}
3798	return s;
3799};
3800
3801//Creates a javascript namespace, if one already exists, just returns that namespace.
3802function createNamespace(namespaceString) {
3803	var parts = namespaceString.split('.'),
3804		parent = window,
3805		currentPart = '',
3806		nsLength = parts.length;
3807
3808	for (var i = 0, length = nsLength; i < length; i++) {
3809		currentPart = parts[i];
3810		parent[currentPart] = parent[currentPart] || {};
3811		parent = parent[currentPart];
3812	}
3813	return parent;
3814}
3815$(function () {
3816
3817	// Ensures a dependency exists. If it doesn't acquire it.
3818	function ensure(dependencyExists, dependencyUrl, onceItExistsCallback) {
3819		if (dependencyExists) {
3820			onceItExistsCallback();
3821			return;
3822		}
3823		$.getScript(dependencyUrl, onceItExistsCallback);
3824	}
3825
3826	var ajaxControlToolkit = window.AjaxControlToolkit;
3827	// This is hack override in order to fix problems with Ajax Toolkit Drag and Drop in newer browsers. It substitutes in jQuery Draggable if it is available.
3828	// A more proper fix is ideal, but extremely expensive as it would require replacing over a hundred instances of invocations of the old modal.
3829	// There isn't a clean way to integrate in the new modal system. JE
3830	// https://system.netsuite.com/app/crm/support/issuedb/issue.nl?id=3809568&l=T
3831	if (ajaxControlToolkit && ajaxControlToolkit.ModalPopupBehavior) {
3832		ajaxControlToolkit.ModalPopupBehavior.prototype._attachPopup = function () {
3833			/// <summary>
3834			/// Attach the event handlers for the popup
3835			/// </summary>
3836
3837			if (this._DropShadow && !this._dropShadowBehavior) {
3838				this._dropShadowBehavior = $create(ajaxControlToolkit.DropShadowBehavior, {}, null, null, this._popupElement);
3839			}
3840
3841			var _this = this;
3842			// Drag and Drop Replacement. Acquire any dependencies on the fly.
3843			ensure($.ui, "/Common/Controls/jquery-ui-1.14.2/jquery-ui.min.js", function () {
3844				$("#" + _this._PopupControlID).draggable({ handle: '#' + _this._PopupDragHandleControlID });
3845				$("#" + _this._PopupDragHandleControlID).css('cursor', 'move');
3846			});
3847
3848			$addHandler(window, 'resize', this._resizeHandler);
3849			$addHandler(window, 'scroll', this._scrollHandler);
3850			this._windowHandlersAttached = true;
3851		}
3852	}
3853});
3854
3855String.prototype.replaceAll = function (search, replacement) {
3856	var target = this;
3857	return target.replace(new RegExp(search, 'g'), replacement);
3858};
3859
3860function executeViewMapPostClickActions($element) {
3861	//Hide the view map element post click(to avoid clicking repeatedly)
3862	$element.hide('fast');
3863
3864	//Collect analytics around map clicks
3865	var url = '/CollectGoogleMapClicks/Execute';
3866	var moduleId = $element.data('moduleid');
3867	$.ajax({
3868		url: url,
3869		type: 'POST',
3870		data: {
3871			url: window.location.href,
3872			moduleId: moduleId
3873		},
3874		success: function (json) {
3875			//send data to telemetry
3876			appInsights.trackEvent("googlemapclicked", json);
3877		},
3878		error: function (xhr, textStatus, exception) {
3879			alert("Error: " + xhr.statusText + "\nStatus: " + xhr.status);
3880		}
3881	});
3882}
3883
3884function importModal(options) {
3885	if (window.ImportModalInstance === undefined) {
3886		var script = document.createElement("script");
3887		script.onload = function () {
3888			window.ImportModalInstance.init(options);
3889		};
3890		script.src = "/Assets/Scripts/ImportModal.js";
3891		document.head.appendChild(script);
3892	}
3893	else
3894		window.ImportModalInstance.init(options);
3895}
3896
3897function exportModal(options) {
3898	if (window.ExportModalInstance === undefined) {
3899		var script = document.createElement("script");
3900		script.onload = function () {
3901			window.ExportModalInstance.init(options);
3902		};
3903		script.src = "/Assets/Scripts/ExportModal.js";
3904		document.head.appendChild(script);
3905	}
3906	else
3907		window.ExportModalInstance.init(options);
3908}
3909
3910document.addEventListener("DOMContentLoaded", function () {
3911	var modal = document.querySelector(".importModal");
3912	if (modal !== null) {
3913		try {
3914			if (!modal.classList.contains("processed")) {
3915				var options = modal.dataset.importconfig;
3916				if (options) {
3917					modal.addEventListener("click",
3918						function (e) {
3919							e.preventDefault();
3920							importModal(JSON.parse(options));
3921						});
3922					//Avoid further processing if the event gets triggered multiple times during page load
3923					modal.classList.add("processed");
3924				}
3925			}
3926		} catch (err) {
3927			console.error("Unable to initialize import modal");
3928		}
3929	}
3930	var modalExport = document.querySelector(".exportModal");
3931	if (modalExport !== null) {
3932		try {
3933			if (!modalExport.classList.contains("processed")) {
3934				var options = modalExport.dataset.exportconfig;
3935				if (options) {
3936					modalExport.addEventListener("click",
3937						function (e) {
3938							e.preventDefault();
3939							exportModal(JSON.parse(options));
3940						});
3941					//Avoid further processing if the event gets triggered multiple times during page load
3942					modalExport.classList.add("processed");
3943				}
3944			}
3945		} catch (err) {
3946			console.error("Unable to initialize export modal");
3947		}
3948	}
3949});
3950$(document).ready(function () {
3951	if (window.isResponsiveEnabled && !window.pageHandleResponsive) {
3952		function executeRWDResizeEvents(event) {
3953			var listener = function (e) {
3954				if ($('#hdnPageID').length == 0) {
3955					var breakpointWidth = 600,
3956					viewportWidth = $(window).width(),
3957					currentCookieValue = getCookieValue('viewportWidth');
3958					currentCookieValue = currentCookieValue == null || currentCookieValue == '' ? 0 : Number(currentCookieValue);
3959					document.cookie = 'viewportWidth=' + viewportWidth + '; path=/';
3960					if ((viewportWidth < breakpointWidth && currentCookieValue >= breakpointWidth) ||
3961					(viewportWidth >= breakpointWidth && currentCookieValue < breakpointWidth)) {
3962						window.location.reload();
3963					}
3964				}
3965			};
3966
3967			if (window.addEventListener) {
3968				window.addEventListener(event, listener, false);
3969			} else if (window.attachEvent) {
3970				window.attachEvent("on" + event, listener);
3971			}
3972		}
3973
3974		executeRWDResizeEvents('resize');
3975	}
3976	
3977	// Always reset the viewport width now that the document is fully loaded and we can make it more accurate.
3978	// (Sometimes on load it comes back much wider than it should)	
3979	document.cookie = 'viewportWidth=' + $(window).width() + '; path=/';
3980});
3981;
3982function Animations() {
3983	const animationsJsonEl = $('.activeWidgetSkinComponentsOnPageJson');
3984	const animationsJson = animationsJsonEl.html();
3985	if (animationsJson)
3986		this.components = JSON.parse(animationsJson);
3987	this.selectors = [
3988		'', '.widgetHeader', '.widgetBody', '.widgetItem', '.widgetTitle', '.widgetMeta', '.widgetBody .bullets',
3989		'a:link', '.readOn:link', '.widgetViewAll:link', '.widgetRSS:link', '.widgetFooter', '.cpTabs',
3990		'.cpTabs > li > a:link', '.cpTabPanel',
3991		'.separated .half:after, .separated .third:after, .separated .fourth:after, .separated .fifth:after, .separated.cpGrid .col:after ', '.miniCalendarHeader', '.miniCalendar > table', '.miniCalendar th', '.miniCalendar td > span', '.miniCalendar td > a', '.miniCalendar .today > span', '.miniCalendar .not > span', '.miniCalendar'
3992	];
3993	animationsJsonEl.remove();
3994}
3995
3996Animations.prototype.Apply = function () {
3997	var self = this;
3998	self.addClassToContainers();
3999	self.bindContainerTriggers();
4000	self.addClassAndTriggerToSkinComponents();
4001};
4002
4003/// Gets the css class to be applied from the hidden element already present on the page and applies the css class to the Container(Structural/Content)
4004Animations.prototype.addClassToContainers = function () {
4005	var $hiddenAnimationElements = $('.hiddenAnimations');
4006	if ($hiddenAnimationElements != null) {
4007		$hiddenAnimationElements.each(function () {
4008			//Get hidden element
4009			var $hiddenAnimationElement = $(this);
4010			//Get css class from it
4011			var cssClass = $hiddenAnimationElement.data('animationclass');
4012			var startCssClass = cssClass + '_Start';
4013			var triggerData = $hiddenAnimationElement.data('trigger');
4014			//Apply that class to parent container, depending on container type
4015			//For Strctural container
4016			if ($hiddenAnimationElement.parent('[data-cprole=structuralContainer]') != null) {
4017				$hiddenAnimationElement.parent('[data-cprole=structuralContainer]').addClass(startCssClass);
4018				$hiddenAnimationElement.parent('[data-cprole=structuralContainer]').addClass(triggerData);
4019				setTimeout(function () {
4020						$hiddenAnimationElement.parent('[data-cprole=structuralContainer]').addClass(cssClass);
4021						$hiddenAnimationElement.parent('[data-cprole=structuralContainer]').removeClass(startCssClass);
4022					},
4023					10);
4024			}
4025			//For Content Container
4026			if ($hiddenAnimationElement.parent('[data-cprole=contentContainer]') != null) {
4027				$hiddenAnimationElement.parent('[data-cprole=contentContainer]').addClass(startCssClass);
4028				$hiddenAnimationElement.parent('[data-cprole=contentContainer]').addClass(triggerData);
4029				setTimeout(function () {
4030						$hiddenAnimationElement.parent('[data-cprole=contentContainer]').addClass(cssClass);
4031						$hiddenAnimationElement.parent('[data-cprole=contentContainer]').removeClass(startCssClass);
4032					},
4033					10);
4034			}
4035		});
4036	}
4037};
4038
4039//Apply animation class to widget skin components on page
4040Animations.prototype.addClassAndTriggerToSkinComponents = function () {
4041	var self = this;
4042	var $widgetsHavingSkinsApplied = $("[class*='skin']");
4043
4044	if ($widgetsHavingSkinsApplied != null) {
4045		//array of unique skin ids
4046		var $uniqueSkinIds = [];
4047		$widgetsHavingSkinsApplied.each(function () {
4048			//Get skin class
4049			var skinClass = $(this).attr('class').match(/.skin\d+/g)[0];
4050			//Parse skinId off of skin class
4051			var skinId = parseInt(skinClass.match(/\d+/)[0]);
4052			//Insert if not there in array
4053			if ($.inArray(skinId, $uniqueSkinIds) === -1)
4054				$uniqueSkinIds.push(skinId);
4055		});
4056
4057		$.each($uniqueSkinIds, function (index, value) {
4058			var skinId = value;
4059			for (var i = 0; i < self.selectors.length; i++) {
4060				//Find all widget skincomponents on the page using this skin.
4061				var $skinComponentsOnPageUsingThisSkin = $('.skin' + skinId + ' ' + self.selectors[i] + '');
4062				var animationClass = self.classAndTrigger(skinId, i).className;
4063				var animationTrigger = self.classAndTrigger(skinId, i).triggerName;
4064				var scrollOffset = self.classAndTrigger(skinId, i).scrollOffset;
4065				if (animationClass !== undefined) {
4066					//Apply animation class
4067					$skinComponentsOnPageUsingThisSkin.addClass(animationClass + '_Start').addClass(animationClass).removeClass(animationClass + '_Start');
4068				}
4069				if (animationTrigger !== undefined && animationTrigger !== 'hover') {
4070					//Apply animation trigger
4071					$skinComponentsOnPageUsingThisSkin.addClass(animationTrigger + 'AnimationTrigger');
4072					$skinComponentsOnPageUsingThisSkin.data("scrolloffset", scrollOffset);
4073				}
4074			}
4075		});
4076	}
4077};
4078
4079///Get animation class given the component and skin Id
4080Animations.prototype.classAndTrigger = function (skinId, componentTypeId) {
4081	var self = this;
4082	var components = self.components;
4083	var classAndTrigger = {};
4084	if (components && components.length > 0) {
4085		for (var i = 0; i < components.length; i++) {
4086			if (components[i].WidgetSkinID === skinId && components[i].ComponentType === componentTypeId) {
4087				classAndTrigger.className = components[i].AnimationClass;
4088				classAndTrigger.triggerName = components[i].TriggerNameLowerCase;
4089				classAndTrigger.scrollOffset = components[i].ScrollOffset;
4090				return classAndTrigger;
4091			}
4092		}
4093	}
4094	return classAndTrigger;
4095};
4096
4097/// Gets the css class to be applied from the hidden element already present on the page and applies the css class to the Nav container(Main/Side)
4098Animations.prototype.applyAnimationClassToNavContainers = function ($olSubMenu, menuType) {
4099	var mainMenu = 2;
4100	var sideMenu = 1;
4101	var cssClass;
4102	var triggerData;
4103	var $mainNavHiddenElement = $('#mainNav').children('[class*="hiddenAnimations"]');
4104	var $secondaryNavHiddenElement = $('#secondaryNav').children('[class*="hiddenAnimations"]');
4105
4106	if ($('#mainNav').length > 0 && menuType === mainMenu) {
4107		cssClass = $mainNavHiddenElement.data('animationclass');
4108		triggerData = $mainNavHiddenElement.data('trigger');
4109		$olSubMenu.addClass(cssClass);
4110		setTimeout(function () {
4111				$olSubMenu.addClass(cssClass);
4112				$olSubMenu.addClass('animation-triggered');
4113				$olSubMenu.removeClass(cssClass + '_Start');
4114			},
4115			10);
4116	};
4117	if ($('#secondaryNav').length > 0 && menuType === sideMenu) {
4118		cssClass = $secondaryNavHiddenElement.data('animationclass');
4119		triggerData = $secondaryNavHiddenElement.data('trigger');
4120		$olSubMenu.addClass(cssClass);
4121		setTimeout(function () {
4122			$olSubMenu.addClass(cssClass);
4123			$olSubMenu.addClass('animation-triggered');
4124			$olSubMenu.removeClass(cssClass + '_Start');
4125		},
4126			10);
4127	};
4128};
4129
4130Animations.prototype.applyAnimationClassToMegaMenuContainer = function ($megaMenuContainer, timeOut) {
4131	var cssClass;
4132	var $megaMenuHiddenElement = $('.megaMenuContainer').children('[class*="hiddenAnimations"]');
4133
4134	$megaMenuContainer.mouseleave(function () {
4135		if (!$('.megaMenuContainer').children('.pinned').length > 0) {
4136			$(this).removeClass('animation-triggered');
4137		}
4138	});
4139
4140	if ($('.megaMenuContainer').length > 0) {
4141		cssClass = $megaMenuHiddenElement.data('animationclass');
4142		setTimeout(function () {
4143				$megaMenuContainer.addClass('animation-triggered');
4144				$megaMenuContainer.removeClass(cssClass + '_Start');
4145			},
4146			timeOut);
4147	};
4148};
4149
4150/// Gets the css class to be applied from the hidden element already present on the page and applies the css class to the Nav container(Main/Side)
4151Animations.prototype.applyInitial = function ($olSubMenu, menuType) {
4152	var mainMenu = 2;
4153	var sideMenu = 1;
4154	var cssClass;
4155	var triggerData;
4156	var $mainNavHiddenElement = $('#mainNav').children('[class*="hiddenAnimations"]');
4157	var $secondaryNavHiddenElement = $('#secondaryNav').children('[class*="hiddenAnimations"]');
4158	if ($('#mainNav').length > 0 && menuType === mainMenu) {
4159		cssClass = $mainNavHiddenElement.data('animationclass');
4160		triggerData = $mainNavHiddenElement.data('trigger');
4161		$olSubMenu.addClass(cssClass + '_Start').addClass(triggerData);
4162	};
4163	if ($('#secondaryNav').length > 0 && menuType === sideMenu) {
4164		cssClass = $secondaryNavHiddenElement.data('animationclass');
4165		triggerData = $secondaryNavHiddenElement.data('trigger');
4166		$olSubMenu.addClass(cssClass + '_Start').addClass(triggerData);
4167	};
4168};
4169
4170Animations.prototype.bindContainerTriggers = function () {
4171	$(document)
4172		.delegate('[class*="clickAnimationTrigger"]',
4173			'click',
4174			function () {
4175				$(this).addClass('animation-triggered');
4176			});
4177
4178	$(window).scroll(function () {
4179		$('.scrollAnimationTrigger').not('.cpCarousel .widgetItem.scrollAnimationTrigger').each(function () {
4180			var scrollOffsetPercentage = $(this).data('scrolloffset') / 100;
4181			if (isNaN(scrollOffsetPercentage))
4182				scrollOffsetPercentage = $(this).children().first().data('scrolloffset') / 100;
4183			if (scrollOffsetPercentage != 0 && ($(window).scrollTop() + ($(window).height() * (1 - scrollOffsetPercentage))) >
4184				$(this).offset().top && ($(this).offset().top + $(this).height()) > $(window).scrollTop())
4185				$(this).addClass('animation-triggered');
4186		});
4187
4188		$('.cpCarousel .widgetItem.scrollAnimationTrigger').each(
4189			function () {
4190				$(this).addClass('animation-triggered');
4191			}
4192		);
4193	});
4194};
4195function StickyStructuralContainers() {
4196	//Add sticky class to structuralStructuralContainer
4197	var stickyContainers = $('div.stickyInnerDiv.sticky');
4198	if (stickyContainers.length > 0) {
4199		stickyContainers.each(function () {
4200			$(this).parent().addClass('stickyStructuralContainer stickySticky');
4201		});
4202		var $stickyContainer = $(".stickyStructuralContainer.stickySticky");
4203		var pos = $stickyContainer.css('position');
4204		var isStickyCurrently = pos === 'relative' || pos === 'sticky';
4205		var divToolbars = $("#divToolbars")[0];
4206		if (divToolbars && isStickyCurrently) {
4207			$stickyContainer.css('top',
4208				(divToolbars.getBoundingClientRect().height + parseInt($('#divToolbars').css('margin-top'))) + "px");
4209		}
4210	}
4211
4212	//Add sticky class to structural container inside of stickyStructuralContainer
4213	var structuralContainersUnderSticky = $('div.structuralUnderStickyInnerDiv');
4214	if (structuralContainersUnderSticky.length > 0) {
4215		structuralContainersUnderSticky.each(function () {
4216			//To prevent adding classes to main structural container
4217			if ($(this).find('div.structuralUnderStickyInnerDiv').length == 0) {
4218				$(this).parent().addClass($(this).attr('class'));
4219			}
4220		});
4221	}
4222}
4223
4224StickyStructuralContainers.prototype.init = function () {
4225	var self = this;
4226	var stickyContainers = $('div.stickyInnerDiv.sticky');
4227	var paddingCalc = $("#divToolbars").outerHeight() - parseInt($("#divToolbars").css('padding-top'));
4228	if (stickyContainers.length > 0) {
4229		var bottomOfSticky = $('.stickyStructuralContainer.stickySticky').outerHeight();
4230		$('#bodyWrapper').addClass('noTransition');
4231		$('.stickyStructuralContainer.stickySticky').next().css('padding-top', bottomOfSticky + 'px');
4232
4233		if (stickyContainers.find('.anchorOffset')) {
4234			document.documentElement.style.setProperty('--header-offset', bottomOfSticky + $('#divToolbars').outerHeight() + 10 + 'px');
4235		}
4236	}
4237
4238	//Adjusted / re - calculate the padding for sibling of sticky structural container.
4239	window.Pages.onResizeHandlers = window.Pages.onResizeHandlers || [];
4240	window.Pages.onResizeHandlers.push(function () {
4241		$('.stickySticky').each(function () {
4242			var padding = $(this).outerHeight() - 1 + 'px';
4243			var self = this;
4244			if ($('.stickySticky').next().attr('data-cprole') == "banner") {
4245				$('.stickySticky').next().find('[id^="structuralContainer"]').first().css('padding-top', padding);
4246			} else {
4247				window.setTimeout(function () {
4248					$(self).next().css('padding-top', padding);
4249				}, 500);
4250			}
4251		});
4252	});
4253
4254	//set up scroll events
4255	var stickyCollapsedContainers = $('div.stickyInnerDiv.stickyCollapsedWhenScrolled');
4256	if (stickyCollapsedContainers.length > 0 && !window.isMobileBrowserIncludingTablets) {
4257		stickyCollapsedContainers.each(function () {
4258			$(this).parent().addClass('stickyStructuralContainer stickyStickyCollapsedWhenScrolled');
4259			if ($(this).hasClass('stickyFadeAnimation')) {
4260				$(this).parent().addClass('stickyStickyFadeAnimation');
4261			} else if ($(this).hasClass('stickySlideDownAnimation')) {
4262				$(this).parent().addClass('stickyStickySlideDownAnimation');
4263			}
4264		});
4265
4266		var bottomOfStickyCollapsed = $('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled').offset().top +
4267			$('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled').outerHeight() -
4268			$("#divToolbars").height();
4269		var hideWhenExpandedHeights = self.getAllHeights($('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled .structuralUnderStickyInnerDiv.hideWhenExpanded'));
4270		var hideWhenCollapsedHeights = self.getAllHeights($('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled .structuralUnderStickyInnerDiv.hideWhenCollapsed'));
4271
4272		var scrollDownTrigger = self.getStickyScrollBreakpoint(bottomOfStickyCollapsed, hideWhenExpandedHeights, hideWhenCollapsedHeights);
4273
4274		self.showHideStickyContainers(true, scrollDownTrigger, paddingCalc);
4275
4276		self.bindScrollForSticky(bottomOfStickyCollapsed,
4277			hideWhenExpandedHeights,
4278			hideWhenCollapsedHeights);
4279
4280		if (stickyCollapsedContainers.find('.anchorOffset')) {
4281			document.documentElement.style.setProperty('--header-offset', bottomOfStickyCollapsed + $('#divToolbars').outerHeight() + 10 + 'px');
4282		}
4283	}
4284	else {
4285		stickyContainers = $('div.stickyInnerDiv');
4286		if (stickyContainers.length > 0 && stickyContainers.find('.structuralUnderStickyInnerDiv.showInMobile').length > 0) {
4287			stickyContainers.find('.structuralUnderStickyInnerDiv').not('.showInMobile')
4288				.each(function () {
4289					$(this).hide();
4290				});
4291		}
4292	}
4293}
4294
4295StickyStructuralContainers.prototype.bindScrollForSticky = function (bottomOfStickyCollapsed, hideWhenExpandedHeights, hideWhenCollapsedHeights) {
4296	var self = this;
4297	var scrollDownTrigger = self.getStickyScrollBreakpoint(bottomOfStickyCollapsed, hideWhenExpandedHeights, hideWhenCollapsedHeights);
4298	var paddingCalc = $("#divToolbars").outerHeight() - parseInt($("#divToolbars").css('padding-top'));
4299
4300	$(window)
4301		.scroll(function () {
4302			self.showHideStickyContainers(false, scrollDownTrigger, paddingCalc);
4303		});
4304}
4305
4306StickyStructuralContainers.prototype.showHideStickyContainers = function (initialLoad, scrollDownTrigger, paddingCalc) {
4307	var $stickyStructuralContainer = $('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled');
4308	var wS = $(window).scrollTop();
4309
4310	if (wS >= scrollDownTrigger + paddingCalc) {
4311		$stickyStructuralContainer.addClass('stickyCollapsed');
4312
4313		$(".stickyStructuralContainer.stickyStickyCollapsedWhenScrolled")
4314			.css('top', $("#divToolbars").outerHeight() + "px");
4315
4316		//Structrual overrides content container so show/hide if content container doesn't have a structural container around it
4317		$('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled .hideWhenExpanded')
4318			.each(function () {
4319				if ($(this).parents('.structuralUnderStickyInnerDiv') === 0) {
4320					$(this).show();
4321				}
4322			});
4323
4324		$('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled .hideWhenCollapsed')
4325			.each(function () {
4326				if ($(this).parents('.structuralUnderStickyInnerDiv') === 0) {
4327					$(this).hide();
4328				}
4329			});
4330
4331		//Structrual overrides content container so show/hide structural containers and any content containers under it that would be opposite behavior
4332		$('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled .structuralUnderStickyInnerDiv.hideWhenCollapsed').hide();
4333		$('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled .structuralUnderStickyInnerDiv.hideWhenExpanded').show();
4334		$('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled .hideWhenExpanded').find('.hideWhenCollapsed').show();
4335		$('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled .hideWhenCollapsed').find('.hideWhenExpanded').hide();
4336
4337		//Animate the slide down
4338		$('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled.stickyStickyFadeAnimation.stickyCollapsed')
4339			.addClass('stickyAnimFade');
4340		$('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled.stickyStickySlideDownAnimation.stickyCollapsed')
4341			.addClass('stickyAnimSlideDown');
4342
4343		if ($('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled.stickyCollapsed').length > 0 &&
4344			!$('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled.stickyCollapsed').hasClass('stickyAnimComplete')
4345		) {
4346			setTimeout(function () {
4347				$('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled.stickyCollapsed')
4348					.addClass('stickyAnimComplete');
4349			},
4350				0);
4351
4352			$('#stickyPlaceholder').css('height', scrollDownTrigger + paddingCalc + 'px');
4353			if (!window.isRemoveSetHeights)
4354				SetHeights();
4355		}
4356
4357	} else {
4358		if (($('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled.stickyCollapsed').length > 0 &&
4359			$('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled.stickyCollapsed').hasClass('stickyAnimComplete'))
4360			|| initialLoad) {
4361			$(".stickyStructuralContainer.stickyStickyCollapsedWhenScrolled").css('top', 'auto');
4362
4363			//Structrual overrides content container so show/hide if content container doesn't have a structural container around it
4364			$('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled .hideWhenExpanded')
4365				.each(function () {
4366					if ($(this).parents('.structuralUnderStickyInnerDiv') === 0) {
4367						$(this).hide();
4368					}
4369				});
4370
4371			$('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled .hideWhenCollapsed')
4372				.each(function () {
4373					if ($(this).parents('.structuralUnderStickyInnerDiv') === 0) {
4374						$(this).show();
4375					}
4376				});
4377
4378			//Structrual overrides content container so show/hide structural containers and any content containers under it that would be opposite behavior
4379			$('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled .structuralUnderStickyInnerDiv.hideWhenExpanded').hide();
4380			$('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled .structuralUnderStickyInnerDiv.hideWhenCollapsed').show();
4381			$('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled .hideWhenExpanded').find('.hideWhenCollapsed').hide();
4382			$('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled .hideWhenCollapsed').find('.hideWhenExpanded').show();
4383
4384			$('#stickyPlaceholder').css('height', '0');
4385
4386			$('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled.stickyStickyFadeAnimation.stickyCollapsed')
4387				.removeClass('stickyAnimFade');
4388			$('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled.stickyStickySlideDownAnimation.stickyCollapsed')
4389				.removeClass('stickyAnimSlideDown');
4390			$stickyStructuralContainer.removeClass('stickyCollapsed stickyAnimComplete');
4391			if (!window.isRemoveSetHeights)
4392				SetHeights();
4393		}
4394	}
4395}
4396
4397StickyStructuralContainers.prototype.getAllHeights = function (elements) {
4398	var heights = 0;
4399	if (elements && elements.length > 0) {
4400		elements.each(function () {
4401			if ($(this).parents('.structuralUnderStickyInnerDiv.hideWhenExpanded').length === 0
4402				&& $(this).parents('.structuralUnderStickyInnerDiv.hideWhenCollapsed').length === 0)
4403				heights += $(this).height();
4404		});
4405	}
4406	return heights;
4407}
4408
4409
4410StickyStructuralContainers.prototype.getStickyScrollBreakpoint = function (bottomOfStickyCollapsed, hideWhenExpandedHeights, hideWhenCollapsedHeights) {
4411	var scrollDownTrigger;
4412	var $stickyStructuralContainer = $('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled');
4413	var toolBarAndStickyHeight = $stickyStructuralContainer.outerHeight() -
4414		$("#divToolbars").height();
4415
4416	//Logic for when there are structural containers
4417	if ($('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled .structuralUnderStickyInnerDiv.hideWhenCollapsed').length > 0
4418		|| $('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled .structuralUnderStickyInnerDiv.hideWhenExpanded').length > 0) {
4419		//If page loaded and already collapsed and has both show and hide containers
4420		if ($('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled.stickyCollapsed .structuralUnderStickyInnerDiv.hideWhenCollapsed').length > 0 &&
4421			$('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled.stickyCollapsed .structuralUnderStickyInnerDiv.hideWhenExpanded').length > 0) {
4422			scrollDownTrigger = hideWhenCollapsedHeights + toolBarAndStickyHeight - hideWhenExpandedHeights;
4423			//If page loaded and NOT collapsed and has both show and hide containers
4424		} else if ($('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled .structuralUnderStickyInnerDiv.hideWhenCollapsed').length > 0 &&
4425			$('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled .structuralUnderStickyInnerDiv.hideWhenExpanded').length > 0) {
4426			scrollDownTrigger = toolBarAndStickyHeight;
4427			//If page loaded and collapsed and has only visible containers when collapsed
4428		} else if (
4429			$('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled.stickyCollapsed .structuralUnderStickyInnerDiv.hideWhenExpanded').length > 0) {
4430			scrollDownTrigger = toolBarAndStickyHeight - hideWhenExpandedHeights;
4431			//If page loaded and collapsed and has only visible containers when expanded
4432		} else if (
4433			$('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled.stickyCollapsed .structuralUnderStickyInnerDiv.hideWhenCollapsed').length > 0) {
4434			scrollDownTrigger = hideWhenCollapsedHeights + toolBarAndStickyHeight;
4435			//If page loaded and NOT collapsed and has only one style of visible container (collapsed or non)
4436		} else if ($('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled .structuralUnderStickyInnerDiv.hideWhenCollapsed').length > 0 ||
4437			$('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled .structuralUnderStickyInnerDiv.hideWhenExpanded').length > 0) {
4438			scrollDownTrigger = toolBarAndStickyHeight;
4439		} else {
4440			scrollDownTrigger = toolBarAndStickyHeight;
4441		}
4442		//Logic for when there are only content containers. Same scenarios as strucrual
4443	} else {
4444		if ($('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled.stickyCollapsed .hideWhenCollapsed').length > 0 &&
4445			$('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled.stickyCollapsed .hideWhenExpanded').length > 0) {
4446			scrollDownTrigger = hideWhenCollapsedHeights + toolBarAndStickyHeight - hideWhenExpandedHeights;
4447		} else if ($('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled .hideWhenCollapsed').length > 0 &&
4448			$('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled .hideWhenExpanded').length > 0) {
4449			scrollDownTrigger = toolBarAndStickyHeight;
4450		} else if (
4451			$('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled.stickyCollapsed .hideWhenExpanded').length > 0) {
4452			scrollDownTrigger = toolBarAndStickyHeight - hideWhenExpandedHeights;
4453		} else if (
4454			$('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled.stickyCollapsed .hideWhenCollapsed').length > 0) {
4455			scrollDownTrigger = hideWhenCollapsedHeights + toolBarAndStickyHeight;
4456		} else if ($('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled .hideWhenCollapsed').length > 0 ||
4457			$('.stickyStructuralContainer.stickyStickyCollapsedWhenScrolled .hideWhenExpanded').length > 0) {
4458			scrollDownTrigger = toolBarAndStickyHeight;
4459		} else {
4460			scrollDownTrigger = toolBarAndStickyHeight;
4461		}
4462	}
4463
4464	return scrollDownTrigger;
4465};
4466var commonLocalization = null;
4467var userAgent = window.navigator.userAgent;
4468var iOSSafari = userAgent.match(/iP(ad|hone)/i) && userAgent.match(/WebKit/i) && !userAgent.match(/CriOS/i);
4469var hashRegex = /^(#cc[A-z0-9]{8}-[A-z0-9]{4}-[A-z0-9]{4}-[A-z0-9]{4}-[A-z0-9]{12})$/;
4470var stickyStructuralContainers = null;
4471
4472if (window.location.hash && hashRegex.test(window.location.hash)) {
4473	var targetHash = window.location.hash;
4474	window.location.hash = '';
4475	scroll(0, 0);
4476	setTimeout(function () {
4477		scroll(0, 0);
4478	}, 1);
4479}
4480
4481if (window.isResponsiveEnabled) {
4482	loadMediaFramework();
4483}
4484
4485function loadMediaFramework() {
4486	Modernizr.load([
4487		//test old browsers to use polyfills
4488		{
4489			test: window.addEventListener,
4490			nope: "/Assets/Scripts/RWD/eventListener.js"
4491		},
4492		{
4493			test: window.matchMedia,
4494			nope: "/Assets/Scripts/RWD/media.match.js"
4495		},
4496		{
4497			test: Modernizr.touch,
4498			yep: "/Assets/Scripts/RWD/quo.debug.js"
4499		},
4500		//Load Media Framework after polyfills if needed
4501		getAbsoluteUrl("/Assets/Scripts/RWD/MediaFramework.js")
4502	]);
4503}
4504
4505(function () {
4506	var timer = 4000;
4507	var incrementTimer = function () { timer = timer * 1.25; };
4508
4509	var timeOutFunction = function () {
4510		setTimeout(timeOutFunction, timer);
4511		setBannerHeights();
4512		incrementTimer();
4513	};
4514	timeOutFunction();
4515}());
4516
4517$(document).ready(function () {
4518
4519	if (!window.isResponsiveEnabled) {
4520		//Setup execution of events when resizing
4521		var timeout = 250; //time out to debounce event
4522		window.Pages = window.Pages || {};
4523		window.Pages.onResizeHandlers = window.Pages.onResizeHandlers || [];
4524
4525		if (typeof updateMegaMenusOnBrowserResize === 'function')
4526			window.Pages.onResizeHandlers.push(updateMegaMenusOnBrowserResize);
4527
4528		if ($('#hdnWidgetManager').length == 0 && typeof rearrangeFlyoutsOnResizeEvents === 'function')
4529			window.Pages.onResizeHandlers.push(rearrangeFlyoutsOnResizeEvents);
4530
4531		function executeResizeEvents(event) {
4532			var timer;
4533			var listener = function (e) {
4534				//Execute the handlers for resize events.
4535				timer && clearTimeout(timer);
4536				timer = setTimeout(function () {
4537					for (var i = 0; i < window.Pages.onResizeHandlers.length; i++) {
4538						if (typeof (window.Pages.onResizeHandlers[i]) === 'function') {
4539							window.Pages.onResizeHandlers[i]();
4540						}
4541					}
4542				}, timeout);
4543			};
4544
4545			if (window.addEventListener) {
4546				window.addEventListener(event, listener, false);
4547			} else if (window.attachEvent) {
4548				window.attachEvent("on" + event, listener);
4549			}
4550		}
4551
4552		executeResizeEvents('resize');
4553		executeResizeEvents('orientationChange');
4554	}
4555
4556	if (window.isResponsiveEnabled) {
4557		//Inserts data-label on each table cell in froala editor. Needed for responsive view
4558		$.each($.find('.fr-view table'), function (tableIndex, tableValue) {
4559			$(tableValue).parent().addClass('responsiveEditor');
4560			if($(tableValue).find('thead th').length === 1) {
4561				$(this).addClass('singleHeaderTable');
4562			}
4563			$.each($(tableValue).find('thead th'), function (headerIndex, headerValue) {
4564				$.each($(tableValue).find('tbody tr'), function (rowIndex, rowValue) {
4565					$($(rowValue).find('td')[headerIndex]).attr('data-label', headerValue.textContent);
4566				});
4567			});
4568		});
4569	}
4570
4571	$('#divToolbars').css('overflow-x', 'visible');
4572	$('#divToolbars').css('overflow-y', 'visible');
4573
4574	browserFailOvers();
4575
4576	var GetCookie = function (cname) {
4577		var name = cname + "=";
4578		var ca = document.cookie.split(';');
4579		for (var i = 0; i < ca.length; i++) {
4580			var c = ca[i];
4581			while (c.charAt(0) == ' ') c = c.substring(1);
4582			if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
4583		}
4584		return "";
4585	}
4586
4587	var IsLiveEditOn = function () {
4588		return GetCookie("enableLiveEdit") === "true";
4589	};
4590
4591	if (IsLiveEditOn() && isUserLoggedIn()) {
4592		$('body').addClass('liveEditOn');
4593	}
4594
4595	setTimeout(function () {
4596		$('.mobile.header .mobileMenu').css('top', $('#divToolbars .mobileAlertBar').outerHeight(true));
4597	}, 10);
4598
4599	$('div.mobile.header > a.mobileMenu').unbind().click(function (e) {
4600		e.preventDefault();
4601		$('#menuPanel').css('top', $('#divToolbars').outerHeight(true));
4602		$('#menuPanel').toggle('slide');
4603		window.scrollTo(0, 0);
4604	});
4605
4606	// Set Heights really fast at first then after 4 seconds slow it down.
4607	if (typeof SetHeights === 'function') {
4608
4609		var stretchContainers = (typeof window.dynamicStretchContainers === 'function');
4610		var setHeightInterval = setInterval(function () {
4611			if (!window.isRemoveSetHeights)
4612				SetHeights();
4613			if (stretchContainers) window.dynamicStretchContainers();
4614		}, 50);
4615
4616		setTimeout(function () {
4617			clearInterval(setHeightInterval);
4618			if (IsLiveEditOn()) {
4619				setInterval(function () {
4620					if (!window.isRemoveSetHeights)
4621						SetHeights();
4622					if (stretchContainers) window.dynamicStretchContainers();
4623				}, 2000);
4624			}
4625		}, 4000);
4626
4627	}
4628
4629	//Do not execute for WidgetManager, it has a slightly different logic thats handled in WidgetManager code itself.
4630	if ($('#hdnWidgetManager').length == 0) {
4631		if (typeof rearrangeFlyouts === 'function') {
4632			setTimeout(function () {
4633				setInterval(function () {
4634					rearrangeFlyouts(false);
4635				}, 2000);
4636			}, 2000);
4637		}
4638	}
4639
4640	window.setTimeout(function () { moveMegaMenusInDOM({ direction: $('#megaMenuPopupDirection').val() }); }, 50);
4641
4642	frontEnd_removeAttributesFromGraphicLinks();
4643
4644	if ($('.viewArchiveLink').length > 0) {
4645		$('body').addClass('cpViewArchiveOn');
4646	}
4647
4648	//workaround to make legacy LE modal to be centered correctly
4649	$("body").append($("#ctl00_ctl00_MainContent_ctl00_liveEditPopupWindow")).append($("#editItemBehavior_backgroundElement"));
4650
4651	//Workaround to adjust the toolbar dropdowns dynamically based on the .cpToolbar height + some other initialization stuff for Layout.
4652	Core.Layout.toggleFeatureColumn();
4653
4654	Core.Layout.attachTabbedWidgetTabHandlers();
4655
4656	//when clicking on error details links
4657	$("a.errorDetails").on("click.errorDetails", function (e) {
4658		e.preventDefault();
4659		$(this).next("div").slideToggle('fast');
4660	});
4661
4662	$("img.imageHover").on("mouseenter.imageHover", function () {
4663		$(this).attr('src', $(this).data("hover"));
4664	}).on("mouseleave.imageHover", function () {
4665		$(this).attr('src', $(this).data("image"));
4666	});
4667
4668	// Setup handlers for My Account toolbar
4669	var $Favorites = $('#favoritesList');
4670	var $UserMenu = $('.cpToolbar .userMenu .popOut');
4671	$Favorites.hide();
4672	$UserMenu.hide();
4673
4674	$('a[href="#favoritesList"]').click(function (e) {
4675		e.preventDefault();
4676		if ($Favorites.hasClass('open')) {
4677			$Favorites.slideUp(200);
4678		} else {
4679			slideToggle($Favorites, true, 200);
4680		}
4681		$Favorites.toggleClass('open');
4682	});
4683
4684	$('.cpToolbar .popOutContainer > a').click(function (e) {
4685		if ($UserMenu.hasClass('open')) {
4686			$UserMenu.slideUp(200);
4687		} else {
4688			$UserMenu.slideDown(200);
4689		}
4690		$UserMenu.toggleClass('open');
4691	});
4692
4693	//Authentication
4694	$('.requireSignIn').on("keypress", function () {
4695		$(this).click();
4696	});
4697
4698	$('.requireSignIn').on("mouseup", function (event) {
4699		event.preventDefault();
4700		$(this).click(function (event) { event.preventDefault(); });
4701		var $self = $(this);
4702		$.ajax({
4703			url: '/Saml/IsSamlLoginEnabled?loginPage=LoginPageMyAccount',
4704			type: 'GET',
4705			success: function (response) { RequireSignInSuccess(response, $self) },
4706			async: false
4707		});
4708	});
4709
4710	function RequireSignInSuccess(response, $elem) {
4711		if (response.IsSamlLoginEnabled) {
4712			window.location = '/Admin/Saml/LogonRequest?RelayState=' + window.location.pathname.substring(1);
4713		}
4714		else {
4715			var popupBasedAuthenticationJs = new PopupBasedAuthentication();
4716			popupBasedAuthenticationJs.requireLoggedIn($elem.attr('href'), '');
4717		}
4718	}
4719
4720	flipHandlesIfNecessary();
4721	$(window).scroll(function () {
4722		$('.flipHandles').removeClass('flipHandles');
4723	});
4724
4725	if (location.search.toLowerCase().indexOf('preview=yes') > -1 || location.search.toLowerCase().indexOf('print=yes') > -1) {
4726		$('body').addClass('printPreview');
4727	}
4728	else {
4729		$('body').removeClass('printPreview');
4730	}
4731
4732	$('#viewFullWebsiteOnMobile').unbind('click').click(function () {
4733		var curDate = new Date();
4734		curDate.setHours(curDate.getHours() + 2);
4735		var curDateInUTCStringFormat = curDate.toUTCString();
4736		document.cookie = "forceMobileOff=true; expires=" + curDateInUTCStringFormat + "; path=/";
4737	});
4738
4739	$('#backToMobileView').unbind('click').click(function () {
4740		//expire the cookie
4741		document.cookie = "forceMobileOff=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
4742	});
4743
4744	if ($("iframe").length > 0) {
4745		$.getScript('/Assets/Scripts/attrchange.js', function () {
4746			$.getScript('/Assets/Scripts/attrchange_ext.js', function () {
4747				$("iframe").attrchange({ callback: function (event) { if (!window.isRemoveSetHeights) SetHeights(); } });
4748			});
4749		});
4750	}
4751
4752	//Apply classes to parent containers and initialize the stickyStructuralContainers class
4753	if (typeof (StickyStructuralContainers) === 'function') {
4754		stickyStructuralContainers = new StickyStructuralContainers();
4755	}
4756
4757	var liveEditEnabled = getCookieValue("enableLiveEdit") === "true";
4758	if (typeof (Animations) === 'function') {
4759		var animations = new Animations();
4760		//If live edit enabled, give it a delay for animation classes to apply properly.
4761		if (liveEditEnabled) {
4762			setTimeout(function () {
4763				animations.Apply();
4764			},
4765				100);
4766		} else {
4767			//Apply animation classes and triggers
4768			animations.Apply();
4769		}
4770	}
4771
4772	//Fixes image cache problem on iOS safari
4773	if (/iPhone|iPad|iPod/i.test(navigator.userAgent)) {
4774		$(".graphicButtonLink").removeAttr("onmouseover");
4775	}
4776
4777	$('.cp-modificationProhibited').on("click", function () {
4778		if ($(this).hasClass('cp-modificationProhibited')) {
4779			showWidgetDisabledPopUp();
4780		}
4781	});
4782
4783	$('.pageCopyEditWidgetModal').on("click", function () {
4784		savePageCopy();
4785	});
4786
4787	$('.closeEditWidgetModal').on("click", function () {
4788		closeModal();
4789	});
4790
4791	$('.viewMap, .viewMapAsLink').on("click", function () {
4792		executeViewMapPostClickActions($(this));
4793	});
4794
4795	// Mobile skip link handler
4796	if (window.FeatureToggles && window.FeatureToggles.isActive("CMS.JqueryUpgrade.UpgradeTo371"))
4797        initializeSkipLinkHandlers();
4798});
4799
4800$(window).on("load", function () {
4801	if (stickyStructuralContainers) {
4802		stickyStructuralContainers.init();
4803		// Fire resize handlers to recalculate any height adjustments required after sticky container setup.
4804		var resizeHandlers = window.Pages && window.Pages.onResizeHandlers || [];
4805		resizeHandlers.forEach(function (handler) { handler(); });
4806	}
4807	$('[class*="pageloadAnimationTrigger"]').each(
4808		function () {
4809			$(this).addClass('animation-triggered');
4810		});
4811
4812	setTimeout(function () {
4813		//Fix for blank target elements with rel attributes to avoid phishing attack.
4814		var blankTargetElements = $("[target='_blank']");
4815		$.each(blankTargetElements, function (index, element) {
4816			$(element).attr("rel", "noopener");
4817		});
4818	}, 175);
4819
4820	$('body').find('table').removeAttr('border');
4821	$('body').find('table').removeAttr('cellspacing');
4822	$('body').find('table').removeAttr('cellpadding');
4823});
4824
4825function flipHandlesIfNecessary() {
4826	$('.widget').unbind('mouseover').mouseover(function (e) {
4827		var $this = $(this);
4828		var $innerCol = $this.parents('div.inner.col');
4829		if ($innerCol != null && !$innerCol.hasClass('flipHandles') && $('#ysnEnableLiveEdit').is(':checked')) {
4830			var $removeHandle = $innerCol.find('.handle.remove');
4831			var $toolbarHeight = $('.cpToolbars').outerHeight(true);
4832			var $removeHandleHeight = $removeHandle.outerHeight();
4833			if ($removeHandle.length > 0) {
4834				var $removeHandleTop = $removeHandle.offset().top - $(document).scrollTop();
4835				if (parseFloat($toolbarHeight - $removeHandleTop) >= parseFloat($removeHandleHeight / 3))
4836					$innerCol.addClass('flipHandles');
4837				else
4838					$innerCol.removeClass('flipHandles');
4839			}
4840		}
4841	});
4842}
4843
4844function reinitCarousels() {
4845	if (window.carouselsToInit && window.carouselsToInit != undefined) {
4846		for (var i = 0; i < window.carouselsToInit.length; i++) {
4847			carouselsToInit[i]();
4848		}
4849	}
4850}
4851
4852function SetHeights() {
4853	if ($('body').hasClass('mobile') || $('.pageContent.dragging').length > 1 || !window.Core.performSetHeights) {
4854		return;
4855	}
4856
4857	var originalScrollPosition = $('body').scrollTop();
4858	if (!originalScrollPosition) {
4859		originalScrollPosition = $('html').scrollTop();
4860	}
4861
4862	// Grow the heights and set them in place.
4863	$('.inner.col, .outer.col, .resize, .indicator.vertical, div.widgetSpacer').css('height', 'auto');
4864
4865	var adjustColumnHeights = function () {
4866		if (typeof CustomAdjustHeights === 'function') {
4867			CustomAdjustHeights();
4868			return;
4869		}
4870		$('.row.nest.wide').each(function () {
4871			var height = $(this).outerHeight();
4872			if (height < 15) {
4873				height = 15;
4874			}
4875			$(this).children('.inner.col, .resize, .indicator.vertical').css('height', height + "px");
4876		});
4877
4878		$('.row.outer.wide:not(.autoWidths)').each(function () {
4879			var height = $(this).outerHeight();
4880			if (height < 15) {
4881				height = 15;
4882			}
4883			$(this).children('.outer.col, .resize, .indicator.vertical, .row.nest.first.last > .inner.col')
4884				.css('height', height + "px");
4885			$(this).find('.outer.col > .row.nest.first.last > .inner.col').css('height', height + "px");
4886
4887		});
4888	};
4889
4890	adjustColumnHeights();
4891
4892	var autoWidthRowsHandler = function ($this) {
4893		var height = 15;
4894		$this.children('.col').each(function () {
4895			var columnHeight = $(this).outerHeight();
4896			if (columnHeight > height) {
4897				height = columnHeight;
4898			}
4899		});
4900		$this.find('.indicator.vertical').height(height);
4901	};
4902
4903	$('.outer.row.autoWidths.wide').each(function () {
4904		autoWidthRowsHandler($(this));
4905
4906		$(this).find('.row').each(function () {
4907			autoWidthRowsHandler($(this));
4908		});
4909	});
4910
4911	if (!window.isResponsiveEnabled || getCookieValue("enableLiveEdit") === "true") {
4912		$('div.widgetSpacer').each(function () {
4913			var $spacer = $(this);
4914			var $innerCol = $spacer.parent(),
4915				$innerRow = $innerCol.parent();
4916
4917			if ($innerRow.hasClass("first") && $innerRow.hasClass("last")) {
4918				var outerRowHeight = $innerRow.parent().parent().height(),
4919					innerColPadding = $innerCol.css("padding-top").replace("px", ""),
4920					spacerHeight = outerRowHeight - (2 * parseInt(innerColPadding, 10));
4921				$spacer.height(spacerHeight);
4922				$innerCol.height(spacerHeight);
4923			} else {
4924				var innerColHeight = $innerCol.innerHeight();
4925				if (innerColHeight > 30)
4926					$spacer.height(innerColHeight);
4927				else
4928					$spacer.height(30); //default spacer height
4929			}
4930		});
4931	}
4932
4933	adjustColumnHeights();
4934
4935	$('.outer.col').height('auto');
4936	if (!iOSSafari) {
4937		$('html,body').scrollTop(originalScrollPosition);
4938	}
4939	setBannerHeights();
4940	reinitCarousels();
4941}
4942
4943function frontEnd_removeAttributesFromGraphicLinks() {
4944	$('.widgetGraphicLinks li.GraphicLinks > a > img').removeAttr('height').removeAttr('width');
4945}
4946
4947function closeModalDialog(behaviourID) {
4948	var behavior = $find(behaviourID);
4949
4950	if (behavior)
4951		behavior.hide();
4952	else
4953		closeCpModal();
4954}
4955
4956function SetMegaMenuToOpenAbove() {
4957	moveMegaMenusInDOM({ direction: '1' });
4958}
4959function SetMegaMenuToOpenBelow() {
4960	moveMegaMenusInDOM({ direction: '0' });
4961}
4962
4963function changeModalDialogHeight(height, showDetails) {
4964	var ifr = document.getElementById('liveEditDialog');
4965	if (ifr)
4966		ifr.style.height = height + 'px';
4967	if (showDetails != '')
4968		document.cookie = "showAddDetails=" + showDetails + ";";
4969}
4970
4971function setModalClassForEditItemBehavior(cssClass, showDetails) {
4972	var behaviorID = $find('editItemBehavior');
4973	var modalContainer = document.getElementById(behaviorID._PopupControlID);
4974	if (modalContainer)
4975		modalContainer.className = 'modalContainer modalContainerCP ' + cssClass;
4976	if (showDetails != '')
4977		document.cookie = "showAddDetails=" + showDetails + ";";
4978}
4979
4980function loadStyleSheet(href, id) {
4981	var styleSheet = document.createElement('link');
4982	styleSheet.type = 'text/css';
4983	styleSheet.rel = 'stylesheet';
4984	styleSheet.setAttribute('href', href);
4985	if (id) {
4986		styleSheet.setAttribute('id', id);
4987	}
4988	var head = document.getElementsByTagName('head')[0];
4989	head.appendChild(styleSheet);
4990}
4991
4992function enableLiveEdit(checked) {
4993
4994	var $liveEditTabs = $('#liveEditTabs');
4995	if (checked) {
4996		document.cookie = "enableLiveEdit=true; expires=12/31/2999; path=/";
4997		$('.handle').show();
4998		$('#bodyWrapper').removeClass('noTransition');
4999		$('#LiveEditCSS').prop('disabled', false);
5000		var versionTitle = $('#versionHeadLine').text();
5001		$('#versionHeadLine').html('<a id="versionHeadLineOptionsHandle" href="#" class="handle options" title="Version Options">Version Options</a>');
5002		$('#versionHeadLine').append($('<span contenteditable="true">').attr('data-versiontitle', versionTitle).text(versionTitle));
5003		$('#versionHeadLineOptionsHandle').unbind().click(function () {
5004			versionActions(ContentCollectionInstance.VersionID, 'edit', { "pageID": ContentCollectionInstance.PageID, "versionID": ContentCollectionInstance.VersionID });
5005		});
5006		if ($('#404Content').length > 0 || $('#pagePageID').val() === '') {
5007			location.reload();
5008		} else if ($liveEditTabs.length > 0) {
5009			redrawContextualInnerToolbar(window.ContentCollectionInstance.PageID, window.ContentCollectionInstance.VersionID);
5010			window.ContentCollectionInstance.reloadContent();
5011			InitializeContainers();
5012			setTimeout(window.ContentCollectionInstance.refreshNavContainers, 10);
5013			refreshMegaMenusForLiveEdit();
5014			showLiveEditElement($liveEditTabs);
5015			if (liveEditTabs.currentState !== 'closed') {
5016				liveEditTabs.setBodyPadding();
5017			}
5018		} else {
5019			$.ajax({
5020				url: '/LiveEditMarkup',
5021				type: 'GET',
5022				cache: false,
5023				async: false,
5024				success: function (response) {
5025					var $body = $('body');
5026					$body.append(response).addClass('liveEditOn');
5027					loadStyleSheet('/Areas/Pages/Assets/Styles/Home.css');
5028					loadStyleSheet('/Assets/AdminRefresh/LiveEdit/Styles/LiveEdit.css', 'LiveEditCSS');
5029					if (!window.ContentCollectionInstance) {
5030						window.ContentCollectionInstance = new ContentCollectionClass();
5031						window.ContentCollectionInstance.init();
5032					}
5033
5034					if (!window.ResizeData) {
5035						window.ResizeData = new ResizeClass();
5036					}
5037					redrawContextualInnerToolbar(window.ContentCollectionInstance.PageID, window.ContentCollectionInstance.VersionID);
5038					var moduleID = $('#pageModuleID').val();
5039					if (moduleID == '') {
5040						moduleID = 76;
5041					} else {
5042						moduleID = Number(moduleID);
5043					}
5044					renderLiveEditTabs(moduleID);
5045
5046					window.ContentCollectionInstance.reloadContent();
5047					InitializeContainers();
5048					setTimeout(window.ContentCollectionInstance.refreshNavContainers, 10);
5049					refreshMegaMenusForLiveEdit();
5050				},
5051				error: function (xhr, textStatus, exception) {
5052					alert("Error: " + xhr.statusText + "\nStatus: " + xhr.status);
5053				}
5054			});
5055		}
5056		triggerStickyStructuralInitLogic();
5057		//no responsive when live edit enabled, so default to wide view
5058		$('.widget.narrow').each(function () {
5059			var $this = $(this);
5060			$this.removeClass('narrow').addClass('wide');
5061		});
5062		$('.tabbedWidgetNarrow.cpTabs:not(.accordion)').hide();
5063		$('.tabbedWidget.cpTabs').show();
5064		Core.Layout.attachTabbedWidgetTabHandlers();
5065		if ($('script:contains("audioeye.com")').length >= 1) {
5066			$('script:contains("audioeye.com")').remove();
5067		}
5068	}
5069	else {
5070		document.cookie = "enableLiveEdit=false; expires=12/31/2999; path=/";
5071		$('#liveEditMenu').hide();
5072		setTimeout(window.ContentCollectionInstance.refreshNavContainers, 10);
5073		refreshMegaMenusForLiveEdit();
5074		var publishedVersion = $liveEditTabs.length > 0 && $('#hdnVersionStatus').val() === '40';
5075		var isPublishedVersionAndContainsTabbedWidget = publishedVersion && $('.widgetTabbed').length > 0;
5076		if (!publishedVersion || isPublishedVersionAndContainsTabbedWidget)
5077			location.reload();
5078
5079		$('body.liveEditOn').removeClass('liveEditOn').addClass('liveEditOff');
5080		window.ContentCollectionInstance.reloadContent(null, null, true);
5081		loadMediaFramework();
5082		$('#bodyWrapper').attr('style', '');
5083		$('#versionHeadLineOptionsHandle').remove();
5084		$('#versionHeadLine').text($('#versionHeadLine').text());
5085		$('a.editCustomHtml').hide();
5086		hideLiveEditElement($liveEditTabs);
5087		hideLiveEditElement($('#innerToolbar'));
5088		triggerStickyStructuralInitLogic();
5089		setTimeout(function () {
5090			$('#LiveEditCSS').prop('disabled', true);
5091		}, 666);
5092		//For some reason, loadMediaFramework doesnt load MediaFramework.js on disabling live edit, this forces it to download it again hence fixing a responsive issue.
5093		if (window.cpMedia) {
5094			window.cpMedia = undefined;
5095			var scriptSrc = '';
5096			var script = document.createElement('script');
5097			script.async = false;
5098			script.type = 'text/javascript';
5099			scriptSrc = '/Assets/Scripts/RWD/MediaFramework.js';
5100			script.src = scriptSrc;
5101			document.body.appendChild(script);
5102		}
5103		Core.Layout.attachTabbedWidgetTabHandlers();
5104		$.ajax({
5105			url: '/IncludeScript/AudioEyeScript/',
5106			type: 'GET',
5107			cache: false,
5108			async: false,
5109			success: function (response) {
5110				if (response) {
5111					var scriptText = $(response)[2].innerText;
5112					var s = document.createElement("script");
5113					s.type = "text/javascript";
5114					s.text = scriptText;
5115					document.body.appendChild(s);
5116				}
5117			},
5118			error: function (xhr, textStatus, exception) {
5119				alert("Error: " + xhr.statusText + "\nStatus: " + xhr.status);
5120			}
5121		});
5122	}
5123
5124	//If IE, simply perform location.reload in order to execute _rootfrontend file again to render the IE meta tag according to settings. This tag cannot be 
5125	//added dynamically, so a reload is required for (https://civicplus.tpondemand.com/entity/29964).
5126	if (window.isie) {
5127		location.reload();
5128		return;
5129	}
5130
5131}
5132
5133function refreshMegaMenusForLiveEdit() {
5134	setTimeout(function () {
5135		var megaMenuContentContainers = $('[data-displaymegamenu="True"]')
5136			.map(function () {
5137				$('#mainNavMegaMenu' + $(this).data('pageid') + ' div.pageContent').html('Loading...');
5138				return $('#mainNavMegaMenu' + $(this).data('pageid') + ' div.pageContent').data('containerid');
5139			}).toArray();
5140		window.Pages.megaMenuLoaded.resolve();
5141		reloadSharedContentContainers(megaMenuContentContainers);
5142	}, 200);
5143}
5144
5145function showHideUnpublishedItems(checked) {
5146	if (checked) {
5147		document.cookie = "showAll=true; expires=12/31/2999 23:59:59; path=/";
5148		document.getElementById('ysnLiveEditShowMyActionItems').checked = true;
5149		document.getElementById('ysnLiveEditShowMyActionItems').disabled = true;
5150	}
5151}
5152
5153function showHideUnpublishedItems(checked) {
5154	var actionItemsCheckbox = document.getElementById('ysnLiveEditShowMyActionItems');
5155	document.cookie = `showAll=${checked}; expires=12/31/2999 23:59:59; path=/`;
5156
5157	if (actionItemsCheckbox) {
5158		actionItemsCheckbox.checked = checked;
5159		actionItemsCheckbox.disabled = checked;
5160		showHideActionItems(checked);
5161	}
5162}
5163
5164function showHideActionItems(checked) {
5165	if (checked)
5166		document.cookie = "showActionItems=true; expires=12/31/2999 23:59:59; path=/";
5167	else
5168		document.cookie = "showActionItems=false; expires=12/31/2999 23:59:59; path=/";
5169
5170	if (typeof redrawContent == 'function')
5171		redrawContent();
5172	else
5173		location.reload(true);
5174}
5175
5176function showHideLiveEditControl(checked) {
5177	if (checked)
5178		document.cookie = "showLiveEditControls=true; expires=12/31/2999 23:59:59;";
5179	else
5180		document.cookie = "showLiveEditControls=false; expires=12/31/2999 23:59:59;";
5181
5182	//if (typeof redrawContent == 'function' && !$.browser.msie)
5183	//	redrawContent();
5184	//else
5185	location.reload(true);
5186}
5187
5188function disableCustomHtmlRendering(checked) {
5189	if (checked)
5190		document.cookie = "disableCustomHtmlRendering=true; expires=12/31/2999 23:59:59; path=/";
5191	else
5192		document.cookie = "disableCustomHtmlRendering=false; expires=12/31/2999 23:59:59; path=/";
5193
5194	location.reload(true);
5195}
5196
5197// Print preview.
5198function pPreview(mode) {
5199	var printStr = 'PREVIEW=YES';
5200	if (mode == 1)
5201		printStr = 'PRINT=YES';
5202	var url = document.URL.split("#")[0];
5203	window.open(url + (url.indexOf("?") == -1 ? '?' : '&') + printStr, '_blank');
5204}
5205
5206function Navigate(txtAction) {
5207	if (txtAction.lastIndexOf("&") == txtAction.length - 1)
5208		txtAction = txtAction.slice(0, -1);
5209	document.frmNavigate.action = txtAction;
5210	location.href = txtAction;
5211}
5212
5213// todo: rename to openModalDialog, to match closeModalDialog
5214function openGenericModalDialog(height, className, title, src) {
5215	document.getElementById('ctl00_LiveEditModalTitle').innerHTML = title;
5216
5217	behavior = $find('editItemBehavior');
5218
5219	if (behavior) {
5220		var ifr = document.getElementById('liveEditDialog');
5221		var target = document.getElementById('ctl00_ctl00_MainContent_ctl00_liveEditPopupWindow');
5222
5223		ifr.src = src;
5224
5225		if (className)
5226			target.className = 'modalContainer ' + className;
5227		if (height)
5228			ifr.style.height = height;
5229
5230		ifr.style.display = 'block';
5231
5232		behavior.show();
5233	}
5234}
5235
5236function expandCollapseCategory(catID) {
5237	if (commonLocalization == null) {
5238		commonLocalization = GetJson('/Localization/Index');
5239	}
5240
5241	if (document.getElementById(catID).style.display == 'none') {
5242		$('#cat' + catID + ' > a').attr('title', commonLocalization.CollapseThisCategory);
5243		document.getElementById(catID).style.display = 'block';
5244		document.getElementById('a_' + catID).innerHTML = '&#9660;';
5245	}
5246	else {
5247		$('#cat' + catID + ' > a').attr('title', commonLocalization.ExpandThisCategory);
5248		document.getElementById(catID).style.display = 'none';
5249		document.getElementById('a_' + catID).innerHTML = '&#9658;';
5250	}
5251}
5252
5253function slideToggle(element, bShow, duration) {
5254	var $el = $(element)
5255		, visible = $el.is(":visible");
5256
5257	// if the bShow isn't present, get the current visibility and reverse it
5258	if (arguments.length == 1) bShow = !visible;
5259
5260	// if the current visiblilty is the same as the requested state, cancel
5261	if (bShow == visible) return false;
5262
5263	$.each($el, function (i, e) {
5264		var $e = $(e);
5265		var visible = $e.is(":visible");
5266		var height = $e.show().height();
5267		if (!$e.data("originalHeight")) {
5268			$e.data("originalHeight", height);
5269		};
5270		if (!visible) $e.hide().css({ height: 0 });
5271	});
5272
5273	// expand the knowledge (instead of slideDown/Up, use custom animation which applies fix)
5274	if (bShow) {
5275		$.each($el, function (i, e) {
5276			$e = $(e);
5277			$e.show().animate({ height: $e.data("originalHeight") }, { duration: duration });
5278		});
5279	} else {
5280		$el.animate({ height: 0 }, {
5281			duration: duration, complete: function () {
5282				$el.hide();
5283			}
5284		});
5285	}
5286	$el.queue(function () { $el.height('auto'); $(this).dequeue(); });
5287}
5288
5289
5290$(window).on("load", function () {
5291	removeEmptyFeaturedAreas();
5292	//Run these once here since window.load invokes after images are loaded as well in the DOM. This fixes one of the issues where the landscape version of the page on ipad etc has images all messed up
5293	//since SetHeights run before the images are loaded in the DOM
5294	if (window.isResponsiveEnabled) {
5295		if (typeof SetHeights === 'function' && !window.isRemoveSetHeights)
5296			SetHeights();
5297		if (typeof dynamicStretchContainers === 'function')
5298			dynamicStretchContainers();
5299	}
5300});
5301
5302function GetSignIn() {
5303	$.get('Services/ForgotPassword.ashx?Username=' + encodeURIComponent(userName), function (data) {
5304		if (data == -1)
5305			alert($("#Localization_AccountDoesNotExist").val());
5306		else
5307			alert($("#Localization_PasswordReminder").val());
5308	});
5309}
5310
5311function PerformSignIn() {
5312	var userName = $('#UserName').val();
5313	var password = $('#Password').val();
5314	var rememberMe = $('#RememberMe').val();
5315	var emailAddress = $('#UserName').val();
5316	var url;
5317	$.post('/MyAccount/SignInJson?' +
5318		'UserName=' + userName +
5319		'&Password=' + password +
5320		'&RememberMe=' + rememberMe +
5321		'&EmailAddress=' + emailAddress
5322		, function (data) {
5323			if (data.status != 1)
5324				alert(data.msg);
5325			else {
5326				if (data.HasAcceptedTerms == true) {
5327					url = getParameterByName('url');
5328					url = url == '' ? window.location.href : url;
5329					try {
5330						var redirectUrl = new URL(url, window.location.href);
5331						if (redirectUrl.protocol === window.location.protocol && redirectUrl.host === window.location.host)
5332							window.location.href = redirectUrl.href;
5333					} catch (e) { }
5334				}
5335				else {
5336					window.location.href = '/MyAccount/Terms';
5337				}
5338			}
5339		});
5340}
5341
5342function SignIn() {
5343	window.location.href = '/MyAccount?from=url&url=' + window.location.pathname + window.location.search;
5344}
5345
5346function SignOut() {
5347		var url = '/publiclogin.aspx?out=true&txtRedirect=' + window.location.pathname.substring(1) + window.location.search;
5348		var dn = getParameterByName('dn');
5349		if (dn != undefined) {
5350			if (!dn.toLowerCase().startsWith('http'))
5351				dn = 'http://' + dn;
5352			try {
5353				var dnUrl = new URL(dn);
5354				if (dnUrl.protocol === 'http:' || dnUrl.protocol === 'https:') {
5355					url = dn + url;
5356				}
5357			} catch (e) { }
5358		}
5359
5360		window.location.href = url;
5361}
5362
5363function getParameterByName(name) {
5364	var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
5365	return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
5366}
5367
5368//Share current page url using common mvc modal (only for mvc modules)
5369function openShareEmailPageModal(subject) {
5370	var emailSubject = (subject && subject != '') ? subject : document.title;
5371	openCpModal({
5372		type: 'POST',
5373		data: {
5374			subject: emailSubject
5375		},
5376		title: 'Email This Page',
5377		className: 'emailPage',
5378		url: '/EmailPage/Home/EmailPageModal'
5379	});
5380}
5381
5382function openShareEmailPageModalWithReferrel(subject, urlReferrer) {
5383	var emailSubject = (subject && subject != '') ? subject : document.title;
5384	openCpModal({
5385		type: 'POST',
5386		data: {
5387			subject: emailSubject,
5388			specificUrlReferrer: urlReferrer
5389		},
5390		title: 'Email This Page',
5391		className: 'emailPage',
5392		url: '/EmailPage/Home/EmailPageModalWithSpecificUrl',
5393		elementID: 'mvcModal'
5394	});
5395}
5396
5397//Share current page url redirecting to email page (for legacy pages do not support new mvc modal)
5398function openShareEmailPage(subject) {
5399	var emailSubject = (subject && subject != '') ? subject : document.title;
5400	window.location.href = '/EmailPage/?subject=' + escape(emailSubject);
5401}
5402
5403//Layout Banners
5404function renderBanner(bannerPlaceHolderID, bannerSlotID, bannerOption, bannerImage, imageFolder, imageTag) {
5405	var $bannerSlot = $('#' + bannerSlotID);
5406	var $bannerPlaceHolder = $('#' + bannerPlaceHolderID);
5407	var images = bannerOption.BannerImages;
5408	const sequenceId = Date.now() % (images.length || 1);
5409	bannerImage = bannerOption.BannerMode === 2 ? images[sequenceId] : bannerImage;
5410	//render external banner
5411	$bannerPlaceHolder.replaceWith(createBannerExternalMarkup($bannerSlot, bannerOption, bannerImage, imageFolder, imageTag));
5412	var stickyContainers = $('div.stickyInnerDiv.sticky');
5413	if (stickyContainers.length > 0) {
5414		$('#bodyWrapper .bannerObject.external').css('top', '0');
5415	}
5416	setTimeout(function () {
5417		if (!window.isRemoveSetHeights)
5418			SetHeights();
5419	}, 5500);
5420}
5421
5422function centerImage(parentWidth, parentHeight, imageWidth, imageHeight) {
5423	var left = 0;
5424	//Adjust width to view port proportionally
5425	var proportionRatio = 1;
5426	if (imageWidth > parentWidth) {
5427		proportionRatio = (imageWidth - parentWidth) / imageWidth;
5428		imageHeight -= imageHeight * proportionRatio;
5429	} else if (imageWidth < parentWidth) {
5430		proportionRatio = (parentWidth - imageWidth) / imageWidth;
5431		imageHeight += imageHeight * proportionRatio;
5432	}
5433	imageWidth = parentWidth;
5434
5435	if (imageHeight < parentHeight) {
5436		//Readjust Height to view port proportionally
5437		proportionRatio = (parentHeight - imageHeight) / imageHeight;
5438		imageWidth += imageWidth * proportionRatio; imageHeight = parentHeight;
5439		left = -1 * (imageWidth - parentWidth) / 2; //move left to center image
5440	}
5441
5442	return { imageWidth: imageWidth, imageHeight: imageHeight, left: left };
5443}
5444
5445function createBannerExternalMarkup($bannerSlot, bannerOption, bannerImage, imageFolder, imageTag) {
5446	if (!window.isRemoveSetHeights)
5447		SetHeights();
5448	if (typeof window.dynamicStretchContainers === 'function') window.dynamicStretchContainers();
5449
5450	var parentHeight = $bannerSlot.parent().outerHeight(true);
5451	var windowHeight = $(window).height();
5452	var imageHeight = bannerImage.Height;
5453	var isBackgroundBanner = $bannerSlot.parent().attr("id") == "bodyWrapper" || $bannerSlot.parent().parent().attr("id") == "bodyWrapper";
5454	var left = 0;
5455
5456	if (isBackgroundBanner && windowHeight > parentHeight) {
5457		parentHeight = windowHeight;
5458	}
5459
5460	var imageWidth = bannerImage.Width;
5461	if (bannerOption.ImageScale) {
5462		var parentWidth = $bannerSlot.outerWidth(true);
5463		if (isBackgroundBanner) {
5464			parentHeight = windowHeight;
5465		}
5466		var centerValues = centerImage(parentWidth, parentHeight, imageWidth, imageHeight);
5467		imageWidth = centerValues.imageWidth;
5468		parentHeight = centerValues.imageHeight;
5469		left = centerValues.left;
5470	}
5471
5472	if (bannerImage.FileName.startsWith('/')) {
5473		imageFolder = '';
5474	}
5475
5476	var $img = (!imageTag)
5477		? $('<img class="bannerObject" src="' + imageFolder + bannerImage.FileName + '" alt="">')
5478		: $(imageTag);
5479	$img.attr("width", imageWidth + "px");
5480	$img.css("position", "absolute");
5481
5482	switch (bannerOption.ImageAlignment) {
5483		case 1:
5484		case "Left":
5485			$img.css("left", "0");
5486			$img.css("margin", "0");
5487			break;
5488		case 2:
5489		case "Center":
5490			$img.css("left", "50%");
5491			$img.css("margin", "0 0 0 -" + Math.round(bannerImage.Width / 2) + "px");
5492			break;
5493		case 3:
5494		case "Right":
5495			$img.css("right", "0px");
5496			$img.css("margin", "0");
5497			break;
5498	}
5499
5500	var position = 'position: ' + (bannerOption.ImageScroll ? 'absolute;' : 'fixed;');
5501	var $bodyWrapper = $("#bodyWrapper");
5502	if (!bannerOption.ImageScroll) {
5503		left += parseInt($bodyWrapper.css("padding-left"), 10); //workaround for fixed position
5504	}
5505
5506	var html = '<div class="bannerObject external" id="bannerDiv' + $bannerSlot.attr('id') + '" style="min-height: ' + parentHeight + 'px ;top: 0px; left: ' + left + 'px; right: 0; ' + position + ' overflow: hidden; z-index: -999999; padding: 0px;"></div>';
5507
5508	var $html = $(html).append($img);
5509	$html.attr('data-image-scale', bannerOption.ImageScale);
5510
5511	var oldScreenHeight = screen.height;
5512	var oldScreenWidth = screen.width;
5513	//bind windows resize event if needed
5514	$(window).unbind('resize.banner' + bannerOption.SlotName);
5515	if (bannerOption.ImageScale) {
5516		$(window).bind('resize.banner' + bannerOption.SlotName, function () {
5517			if (screen.height !== oldScreenHeight && screen.width !== oldScreenWidth) {
5518				oldScreenHeight = screen.height;
5519				oldScreenWidth = screen.width;
5520				resize($bannerSlot);
5521			}
5522		});
5523	}
5524	///private function that takes care of resizing when image scale
5525	var resize = function ($bannerSlotContainer) {
5526		var parentHeight = $bannerSlotContainer.parent().outerHeight(true);
5527		var windowHeight = $(window).height();
5528		var left = 0;
5529
5530		if (isBackgroundBanner && windowHeight > parentHeight) {
5531			parentHeight = windowHeight;
5532		}
5533
5534		var imageWidth = bannerImage.Width;
5535		if (bannerOption.ImageScale) {
5536			var parentWidth = $bannerSlotContainer.outerWidth(true);
5537			if (isBackgroundBanner) {
5538				parentHeight = windowHeight;
5539			}
5540			var centerValues = centerImage(parentWidth, parentHeight, imageWidth, imageHeight);
5541			imageWidth = centerValues.imageWidth;
5542			parentHeight = centerValues.imageHeight;
5543			left = centerValues.left;
5544		}
5545
5546		if (!bannerOption.ImageScroll) {
5547			left += parseInt($bodyWrapper.css("padding-left"), 10); //workaround for fixed position
5548		}
5549
5550		$html.css("left", left);
5551		$html.find('img.bannerObject').width(imageWidth);
5552		$html.css("min-height", parentHeight + "px");
5553	};
5554
5555	window.Pages = window.Pages || {};
5556	window.Pages.Banners = window.Pages.Banners || {};
5557	$(window.Pages.Banners).bind('ExternalBannersResize', function () { resize($bannerSlot); }); // resize external banners
5558
5559	if (jQuery.resize) {
5560		$bannerSlot.children(":not(.bannerObject, script)").unbind("resize").bind("resize", function () { $(window.Pages.Banners).trigger('ExternalBannersResize'); });
5561	}
5562
5563	if (bannerOption.ImageScale) {
5564		window.Pages.onResizeHandlers = window.Pages.onResizeHandlers || [];
5565		window.Pages.onResizeHandlers.push(function () {
5566			$(window.Pages.Banners).trigger('ExternalBannersResize');
5567		});
5568	}
5569
5570	setTimeout(function () {
5571		if (!window.isRemoveSetHeights)
5572			SetHeights();
5573	}, 8000);
5574	return $html;
5575};
5576
5577function setBannerHeights() {
5578	$('div.bannerObject.external').each(function () {
5579		var $this = $(this);
5580		var isBackgroundBanner = $this.parent().attr("id") == "bodyWrapper" || $this.parent().parent().attr("id") == "bodyWrapper";
5581		var parentHeight = parentHeight = $this.parent().outerHeight(true);
5582		var windowHeight = $(window).height();
5583
5584		if (isBackgroundBanner && windowHeight > parentHeight) {
5585			parentHeight = windowHeight;
5586		}
5587
5588		if ($this.attr('data-image-scale') === "true") {
5589			$this.css('min-height', $this.find('img').height());
5590		} else {
5591			$this.css('min-height', parentHeight);
5592		}
5593	});
5594}
5595
5596//Creates slideshow markup for external banners.
5597function createBannerExternalMarkupForSlideshow($bannerSlot, bannerOption, imageFolder, bannerImagesJSON, bannerMode, rotatingSequence) {
5598	if (!window.isRemoveSetHeights)
5599		SetHeights();
5600	if (typeof window.dynamicStretchContainers === 'function') window.dynamicStretchContainers();
5601
5602	var parentHeight = $bannerSlot.parent().outerHeight(true);
5603	var parentWidth = $bannerSlot.outerWidth(true);
5604	var windowHeight = $(window).height();
5605	var isBackgroundBanner = $bannerSlot.parent().attr("id") == "bodyWrapper" || $bannerSlot.parent().parent().attr("id") == "bodyWrapper";
5606	var greaterImageWidth = 0, greaterImageHeight = 0;
5607	var left = 0;
5608
5609	if (isBackgroundBanner && windowHeight > parentHeight) {
5610		parentHeight = windowHeight;
5611	}
5612
5613	var img = '';
5614	for (var i = 0; i < bannerImagesJSON.length; i++) {
5615		var bannerImage = bannerImagesJSON[i];
5616		var imageWidth = bannerImagesJSON[i].Width;
5617		if (imageWidth > greaterImageWidth)
5618			greaterImageWidth = imageWidth;
5619		if (bannerImagesJSON[i].Height > greaterImageHeight)
5620			greaterImageHeight = bannerImagesJSON[i].Height;
5621		var alignmentCss = "";
5622		switch (bannerOption.ImageAlignment) {
5623			case 1:
5624			case "Left":
5625				alignmentCss += 'left: 0;  margin: 0;';
5626				break;
5627			case 2:
5628			case "Center":
5629				alignmentCss += ' left: 50%; margin: 0 0 0 -' + Math.round(bannerImage.Width / 2) + 'px;';
5630				break;
5631			case 3:
5632			case "Right":
5633				alignmentCss += ' right: 0px; margin: 0;';
5634				break;
5635		}
5636		if (bannerOption.ImageScale) {
5637			imageWidth = parentWidth;
5638		}
5639
5640		var tempImageFolder = imageFolder;
5641		if (bannerImagesJSON[i].FileName.startsWith('/')) {
5642			tempImageFolder = '';
5643		}
5644
5645		if (bannerMode === 'Slideshow') {
5646			if (i > 0) {
5647				img += '<img class="bannerObject" width="' + imageWidth + 'px" style="position: absolute; display: none;' + alignmentCss + '" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-is-delayed="true" data-delayed-image="' + tempImageFolder + bannerImagesJSON[i].FileName + '" alt="">';
5648			} else {
5649				img += '<img class="bannerObject" width="' + imageWidth + 'px" style="position: absolute;' + alignmentCss + '" src="' + tempImageFolder + bannerImagesJSON[i].FileName + '" data-is-delayed="false" alt="">';
5650			}
5651		}
5652		else if (bannerMode === 'Rotating') {
5653			if (rotatingSequence < 0) {
5654				rotatingSequence = 0;
5655			}
5656			var rotSeqLessOne = rotatingSequence === 0 ? bannerImagesJSON.length - 1 : rotatingSequence - 1;
5657			var rotSeqPlusOne = rotatingSequence === bannerImagesJSON.length - 1 ? 0 : rotatingSequence + 1;
5658			if (bannerOption.SlideshowControlsPosition === 0 || bannerOption.SlideshowControlsPosition === 'None') {
5659				if (i === rotatingSequence) {
5660					img += '<img class="bannerObject" width="' + imageWidth + 'px" style="position: absolute;' + alignmentCss + '" src="' + tempImageFolder + bannerImagesJSON[i].FileName + '" data-is-delayed="false" alt="">';
5661				}
5662			} else {
5663				if (i === rotSeqLessOne || i === rotatingSequence || i === rotSeqPlusOne) {
5664					img += '<img class="bannerObject" width="' + imageWidth + 'px" style="position: absolute;' + alignmentCss + '" src="' + tempImageFolder + bannerImagesJSON[i].FileName + '" data-is-delayed="false" alt="">';
5665				} else {
5666					img += '<img class="bannerObject" width="' + imageWidth + 'px" style="position: absolute;' + alignmentCss + '" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-is-delayed="true" data-delayed-image="' + tempImageFolder + bannerImagesJSON[i].FileName + '" alt="">';
5667				}
5668			}
5669		}
5670
5671	}
5672
5673	var position = 'position: ' + (bannerOption.ImageScroll ? 'absolute;' : 'fixed;');
5674	var $bodyWrapper = $("#bodyWrapper");
5675	if (!bannerOption.ImageScroll) {
5676		left += parseInt($bodyWrapper.css("padding-left"), 10); //workaround for fixed position
5677	}
5678	var html = '<div class="bannerObject external" id="bannerDiv' + $bannerSlot.attr('id') + '" style="min-height: ' + parentHeight + 'px ;top: 0; left: ' + left + 'px; right: 0; ' + position + ' overflow: hidden; z-index: -999999; padding: 0px;">'
5679		+ img + '</div>';
5680
5681	var $html = $(html);
5682	$html.attr('data-image-scale', bannerOption.ImageScale);
5683
5684	///private function that takes care of resizing when image scale
5685	var resize = function ($bannerSlotContainer) {
5686		var parentHeight = $bannerSlotContainer.parent().outerHeight(true);
5687		var windowHeight = $(window).height();
5688		var left = 0;
5689
5690		if (isBackgroundBanner && windowHeight > parentHeight) {
5691			parentHeight = windowHeight;
5692		}
5693
5694		var imageWidth = greaterImageWidth;
5695		if (bannerOption.ImageScale) {
5696			var parentWidth = $bannerSlotContainer.outerWidth(true);
5697			if (isBackgroundBanner) {
5698				parentHeight = windowHeight;
5699			}
5700			var centerValues = centerImage(parentWidth, parentHeight, imageWidth, greaterImageHeight);
5701			imageWidth = centerValues.imageWidth;
5702			parentHeight = centerValues.imageHeight;
5703			left = centerValues.left;
5704		}
5705
5706		if (!bannerOption.ImageScroll) {
5707			left += parseInt($bodyWrapper.css("padding-left"), 10); //workaround for fixed position
5708		}
5709
5710		$html.css("left", left);
5711		$html.find('img.bannerObject').width(imageWidth);
5712		$html.css("min-height", parentHeight + "px");
5713	};
5714
5715	var displayArrows = function ($bannerSlotContainer) {
5716		var $bannerSlideshowControls = $('#bannerSlideshowControls_' + $bannerSlotContainer[0].id);
5717		var windowWidth = $(window).width();
5718		if ($bannerSlideshowControls.length > 0 && windowWidth < 416) {
5719			$bannerSlideshowControls.hide();
5720			$html.removeClass('fixedBanner');
5721		} else if ($bannerSlideshowControls.length > 0 && windowWidth >= 416 && !$bannerSlideshowControls.hasClass("none")) {
5722			$bannerSlideshowControls.show().removeAttr('style');
5723			$html.addClass('fixedBanner');
5724		}
5725	}
5726
5727	//bind windows resize event if needed
5728	$(window).unbind('resize.banner' + bannerOption.SlotName);
5729	if (bannerOption.ImageScale) {
5730		window.Pages.onResizeHandlers = window.Pages.onResizeHandlers || [];
5731		window.Pages.onResizeHandlers.push(function () {
5732			resize($bannerSlot);
5733		});
5734		resize($bannerSlot);
5735	}
5736
5737	window.Pages.onResizeHandlers = window.Pages.onResizeHandlers || [];
5738	window.Pages.onResizeHandlers.push(function () {
5739		displayArrows($bannerSlot);
5740	});
5741
5742	var $bannerSlideshowControls = $('#bannerSlideshowControls_' + $bannerSlot[0].id);
5743	if ($bannerSlideshowControls.length > 0) {
5744		$html.addClass('fixedBanner');
5745	}
5746
5747	return $html;
5748}
5749
5750//Render Slideshow for External banners.
5751function renderExternalBannerSlideshow(bannerSlotID, bannerOption, imageFolder, bannerMode) {
5752	var bannerImagesJSON = bannerOption.BannerImages;
5753
5754	if (!bannerOption.SlideShowSlideTiming) {
5755		bannerOption.SlideShowSlideTiming = 1;
5756	}
5757	if (!bannerOption.SlideShowTransitionTiming) {
5758		bannerOption.SlideShowTransitionTiming = 1;
5759	}
5760	
5761	const rotatingSequence = bannerMode === 'Rotating' ? Date.now() % (bannerImagesJSON.length || 1) : 0;
5762
5763	var slideTransitionTiming = parseFloat(bannerOption.SlideShowSlideTiming) * 1000;
5764	var transitionTiming = parseFloat(bannerOption.SlideShowTransitionTiming) * 1000;
5765
5766	var $bannerSlot = $('#' + bannerSlotID);
5767	var imagesHtml = createBannerExternalMarkupForSlideshow($bannerSlot, bannerOption, imageFolder, bannerImagesJSON, bannerMode, rotatingSequence);
5768
5769	var $imagesHtml = $(imagesHtml);
5770	$imagesHtml.insertAfter($('#bannerImagesJSON' + bannerOption.BannerOptionID));
5771
5772	var images = null;
5773	images = $('div#bannerDiv' + bannerSlotID).find('img.bannerObject');
5774
5775	if (bannerOption.SlideshowTransition == '1') // 1 corresponds to "none"
5776	{
5777		transitionTiming = 0; // A 0 transition time is the same as no transition.
5778	}
5779
5780	//Moves banner controls to the body level of the DOM to avoid layout issues with z-index
5781	if ($('.bannerSlideshowControlsNew.centered.container').length > 0) {
5782		var $banner = $('#' + bannerSlotID);
5783		$banner.prepend($('#bannerSlideshowControls_' + bannerSlotID));
5784	}
5785	else {
5786		$(document.body).append($('#bannerSlideshowControls_' + bannerSlotID));
5787	}
5788
5789	var ss = new SimpleSlideshow(images, transitionTiming, slideTransitionTiming, bannerMode, parseInt(rotatingSequence));
5790
5791	if (window.FeatureToggles.isActive("CMS.DesignCenter.EnablePauseAndPlayForBannerSlideshow")) {
5792		$('#bannerSlideshowPlayPauseBtn_' + bannerSlotID).click(function () {
5793			ss.togglePause();
5794		});
5795	}
5796}
5797
5798function SimpleSlideshow($images, transitionTime, slideTime, bannerMode, rotatingSequence) {
5799	"use strict";
5800	var slideshowRef = this;
5801	var $imageToBeShown = null;
5802	var $currentImage = null;
5803	var $nextImage = null;
5804	var $previousImage = null;
5805	//Setting the imageToShowIndex = -1 make sure that the 1st image showing in the slideshow is the 1st image in the slideshow.
5806	var imageToShowIndex = -1;
5807	var nextImageIndex = -1;
5808	var previousImageIndex = 0;
5809	var paused = false;
5810	var numberOfImages = $images.length;
5811	var onLoad = false;
5812	//Setting imageToShowIndex as the next rotating sequence if slideshow enhancements are enabled and option is refreshing
5813	if (bannerMode === 'Rotating' && numberOfImages > 1) {
5814		imageToShowIndex = rotatingSequence - 1;
5815		onLoad = true;
5816	}
5817
5818	var DEBUG = false;
5819	var diag = function (msg) {
5820		if (DEBUG) {
5821			console.log('[Simple Slideshow] ' + msg);
5822		}
5823	};
5824
5825	slideshowRef.autoFadeNext = function () {
5826		if (!paused && bannerMode == 'Slideshow') {
5827			slideshowRef.goToNext();
5828		}
5829	};
5830
5831	slideshowRef.goToNext = function () {
5832		imageToShowIndex = imageToShowIndex >= (numberOfImages - 1) ? 0 : imageToShowIndex + 1;
5833		previousImageIndex = imageToShowIndex == 0 ? numberOfImages - 1 : imageToShowIndex - 1;
5834		nextImageIndex = imageToShowIndex < numberOfImages - 1 ? imageToShowIndex + 1 : 0;
5835
5836		$imageToBeShown = $($images[imageToShowIndex]);
5837		$nextImage = $($images[nextImageIndex]);
5838		if ($nextImage.data('is-delayed') == true) {
5839			$nextImage.attr('src', $nextImage.data('delayed-image'));
5840			(new Image()).src = $nextImage.data('delayed-image');
5841			$nextImage.data('is-delayed', 'false');
5842			$nextImage.data('delayed-image', '');
5843		}
5844		$currentImage = $($images[previousImageIndex]);
5845		diag('Automatic transition next. Image To Show Index: ' +
5846			imageToShowIndex +
5847			', Previous Image Index: ' +
5848			previousImageIndex);
5849		slideshowRef.sendBehindFront($imageToBeShown).show();
5850
5851		if (!onLoad) {
5852
5853			if (numberOfImages == 1) {
5854				slideshowRef.sendToFront($currentImage).show();
5855			}
5856			else if (numberOfImages > 1) {
5857				slideshowRef.sendToFront($currentImage)
5858					.show()
5859					.fadeOut(transitionTime,
5860						function () {
5861							diag('Fade out.');
5862							setTimeout(slideshowRef.autoFadeNext, slideTime);
5863						});
5864			}
5865		}
5866	};
5867
5868	slideshowRef.goToPrevious = function () {
5869		imageToShowIndex = imageToShowIndex == 0 ? numberOfImages - 1 : imageToShowIndex - 1;
5870		previousImageIndex = imageToShowIndex == 0 ? numberOfImages - 1 : imageToShowIndex - 1;
5871		nextImageIndex = imageToShowIndex < numberOfImages - 1 ? imageToShowIndex + 1 : 0;
5872
5873		$imageToBeShown = $($images[imageToShowIndex]);
5874		$previousImage = $($images[previousImageIndex]);
5875		if ($previousImage.data('is-delayed') == true) {
5876			$previousImage.attr('src', $previousImage.data('delayed-image'));
5877			(new Image()).src = $previousImage.data('delayed-image');
5878			$previousImage.data('is-delayed', 'false');
5879			$previousImage.data('delayed-image', '');
5880		}
5881		$currentImage = $($images[nextImageIndex]);
5882
5883		diag('Automatic transition next. Image To Show Index: ' +
5884			imageToShowIndex +
5885			', Previous Image Index: ' +
5886			nextImageIndex);
5887		slideshowRef.sendBehindFront($imageToBeShown).show();
5888		slideshowRef.sendToFront($currentImage)
5889			.show()
5890			.fadeOut(transitionTime,
5891				function () {
5892					diag('Fade out.');
5893					setTimeout(slideshowRef.autoFadeNext, slideTime);
5894				});
5895
5896	};
5897
5898	this.pause = function () {
5899		paused = true;
5900		togglePlayPauseButton();
5901	}
5902
5903	this.play = function () {
5904		paused = false;
5905		togglePlayPauseButton();
5906		slideshowRef.autoFadeNext();
5907	};
5908
5909	this.togglePause = function () {
5910		if (paused) {
5911			this.play();
5912		} else {
5913			this.pause();
5914		}
5915	};
5916
5917	function togglePlayPauseButton() {
5918		if (paused) {
5919			$('#slideshowPlayIcon').show();
5920			$('#slideshowPauseIcon').hide();
5921			$('.bannerSlideshowPlayPause-btn').attr('aria-label', 'Play Slideshow');
5922		} else {
5923			$('#slideshowPlayIcon').hide();
5924			$('#slideshowPauseIcon').show();
5925			$('.bannerSlideshowPlayPause-btn').attr('aria-label', 'Pause Slideshow');
5926		}
5927	}
5928
5929	this.sendToFront = function ($image) {
5930		$image.css('z-index', '3');
5931		return $image;
5932	};
5933
5934	this.sendBehindFront = function ($image) {
5935		$image.css('z-index', '2');
5936		return $image;
5937	};
5938
5939	window.setTimeout(function () {
5940		slideshowRef.autoFadeNext();
5941	}, 500);
5942
5943	if (bannerMode == 'Rotating' && numberOfImages > 1) {
5944		this.goToNext();
5945	}
5946
5947	var disabledNext = false;
5948	var disabledPrevious = false;
5949	$('a[id*="arrowNext_"],button[id*="arrowNext_"]').click(function (e) {
5950		if (disabledNext) {
5951			e.preventDefault();
5952			return false;
5953		}
5954		slideshowRef.pause();
5955		slideshowRef.goToNext();
5956		disabledNext = true;
5957		setTimeout(function () {
5958			disabledNext = false;
5959		}, 1000);
5960		e.preventDefault();
5961	});
5962
5963	$('a[id*="arrowPrev_"],button[id*="arrowPrev_"]').click(function (e) {
5964		if (disabledPrevious) {
5965			e.preventDefault();
5966			return false;
5967		}
5968		slideshowRef.pause();
5969		slideshowRef.goToPrevious();
5970		disabledPrevious = true;
5971		setTimeout(function () {
5972			disabledPrevious = false;
5973		}, 1000);
5974		e.preventDefault();
5975	});
5976	onLoad = false;
5977}
5978
5979//External banner for videos
5980function renderBannerVideo(bannerPlaceHolderID, bannerSlotID, bannerVideo, videoTag) {
5981	if (bannerVideo == null)
5982		return;
5983	var $bannerSlot = $('#' + bannerSlotID);
5984	var $bannerPlaceHolder = $('#' + bannerPlaceHolderID);
5985	var isBackgroundBanner = $bannerSlot.parent().attr("id") == "bodyWrapper" || $bannerSlot.parent().parent().attr("id") == "bodyWrapper";
5986
5987	var html = '<div class="bannerObject external" id="bannerDiv' + $bannerSlot.attr('id') + '" style="top: 0; left: 0px; right: 0; position: absolute; overflow: hidden; z-index: -999999; padding: 0px;"></div>';
5988	var $html = $(html);
5989
5990	// Inserting html elements before resizing because they need to be on DOM beforehand.
5991	$bannerPlaceHolder.after($html);
5992	// Workaround. videotag needs to be added with jquery html() function in order to prevent issues with cache JQuery version has
5993	$bannerPlaceHolder.next().html(videoTag);
5994
5995	///private function that takes care of resizing for video
5996	var resize = function ($bannerSlotContainer) {
5997		var parentHeight = $bannerSlotContainer.parent().outerHeight(true);
5998		var windowHeight = $(window).height();
5999		var left = 0;
6000
6001		if (isBackgroundBanner && windowHeight > parentHeight) {
6002			parentHeight = windowHeight;
6003		}
6004
6005		var videoHeight = bannerVideo.VideoHeight;
6006		var videoWidth = bannerVideo.VideoWidth;
6007		//by default video will always scale
6008		var parentWidth = $bannerSlotContainer.outerWidth(true);
6009		if (isBackgroundBanner) {
6010			parentHeight = windowHeight;
6011		}
6012		var centerValues = centerImage(parentWidth, parentHeight, videoWidth, videoHeight);
6013		videoWidth = centerValues.imageWidth;
6014		parentHeight = centerValues.imageHeight;
6015		left = centerValues.left;
6016
6017		var $html = $bannerPlaceHolder.next();
6018		$html.css("left", left);
6019		$html.find('video').css("width", videoWidth + "px");
6020		$html.find('img').css("width", videoWidth + "px");
6021		$html.css("min-height", parentHeight + "px");
6022	};
6023
6024	//bind windows resize event if needed
6025	$(window).unbind('resize.banner' + bannerSlotID);
6026	window.Pages.onResizeHandlers = window.Pages.onResizeHandlers || [];
6027	window.Pages.onResizeHandlers.push(function () {
6028		resize($bannerSlot);
6029	});
6030	//adjust resize first time
6031	resize($bannerSlot);
6032
6033	// Pause/Play button event binding
6034
6035	if (window.FeatureToggles.isActive("CMS.DesignCenter.EnablePauseAndPlayForBannerVideo") && $('button[id*="bannerVideoToggleBtn_"]').length) {
6036		$('button[id*="bannerVideoToggleBtn_"]').click(function (e) {
6037			e.preventDefault();
6038			toggleVideoPlayPause($bannerSlot)
6039		});
6040	}
6041
6042	if (window.FeatureToggles.isActive("CMS.DesignCenter.EnablePauseAndPlayForBannerVideo")){
6043		$('button[id*="bannerVideoToggleBtn_"]').on('keydown', function (e) {
6044			if (e.key === 'Enter' || e.key === ' ') {
6045				e.preventDefault();
6046				toggleVideoPlayPause($bannerSlot);
6047			}
6048		});
6049	}
6050}
6051
6052function toggleVideoPlayPause($bannerSlot) {
6053	let playIcon = $("#videoPlayIcon");
6054	let pauseIcon = $("#videoPauseIcon");
6055	let iconTitle = $("#videoIconTitle");
6056	let button = $(".bannerVideoToggle-btn");
6057	let $bannerObject = $bannerSlot.children('.bannerObject');
6058	let video = $bannerObject.find('video')[0];
6059	if (video) {
6060		if (video.paused) {
6061			video.play();
6062			playIcon.hide();
6063			pauseIcon.show();
6064			button.attr("aria-label", "Pause Video");
6065			iconTitle.text("Pause Video");
6066		} 
6067		else {
6068			video.pause();
6069			playIcon.show();
6070			pauseIcon.hide();
6071			button.attr("aria-label", "Play Video");
6072			iconTitle.text("Play Video");
6073		}
6074	}
6075}
6076
6077//removes empty feature areas
6078function removeEmptyFeaturedAreas() {
6079	$('div[id^="featureArea"]').each(function () {
6080		if ($(this).html().trim() == "") {
6081			$(this).parent().css("display", "none");
6082		}
6083	});
6084
6085	$('div[id^="featureContent"]').each(function () {
6086		if ($(this).html().trim() == "") {
6087			$(this).css("display", "none");
6088		}
6089	});
6090}
6091
6092function setWidgetServiceHovering($widgetHeader, bindKeyPress, additionalLogic) {
6093	if (window.isMobileBrowserIncludingTablets) {
6094		setWidgetServiceClicking($widgetHeader, bindKeyPress, additionalLogic);
6095		return;
6096	}
6097	var $widgetBody = $widgetHeader.next();
6098	var $parent = $widgetHeader.parent();
6099	var timeOutID = null;
6100	var hideDelay = 400;
6101	var showDelay = 300;
6102	$widgetHeader.bind("mouseenter.services", function () {
6103		clearTimeout(timeOutID);
6104		timeOutID = setTimeout(function () {
6105			if (!$widgetBody.is(':visible'))
6106				adjustFlyoutPosition($parent, $widgetBody);
6107			$widgetBody.show();
6108			additionalLogic();
6109		}, showDelay);
6110	});
6111	$widgetHeader.bind("mouseleave.services", function () {
6112		clearTimeout(timeOutID);
6113		timeOutID = setTimeout(function () {
6114			$widgetBody.hide();
6115			additionalLogic();
6116		}, hideDelay);
6117	});
6118	$widgetBody.children().bind("mouseenter.services", function () {
6119		clearTimeout(timeOutID);
6120		timeOutID = setTimeout(function () {
6121			if (!$widgetBody.is(':visible'))
6122				adjustFlyoutPosition($parent, $widgetBody);
6123			$widgetBody.show();
6124			additionalLogic();
6125		}, showDelay);
6126	});
6127	$widgetBody.children().bind("mouseleave.services", function () {
6128		clearTimeout(timeOutID);
6129		timeOutID = setTimeout(function () {
6130			$widgetBody.hide();
6131			additionalLogic();
6132		}, hideDelay);
6133	});
6134
6135	if (bindKeyPress) {
6136		$widgetHeader.unbind("keypress").bind("keypress", function (e) {
6137			if (e.which === 13) {
6138				$widgetHeader.trigger("mouseenter.services");
6139			}
6140		});
6141	}
6142}
6143
6144function setWidgetServiceClicking($widgetHeader, bindKeyPress, additionalLogic) {
6145	var $widgetBody = $widgetHeader.next();
6146	var $parent = $widgetHeader.parent();
6147
6148	var click = function (e) {
6149		e.stopPropagation();
6150		e.preventDefault();
6151		//If the Flyout is for a megamenu, add a class of forMegaMenu.
6152		if ($widgetHeader.parents('.megaMenu').length > 0)
6153			$widgetBody.addClass('forMegaMenu');
6154		if (!$widgetBody.is(':visible'))
6155			adjustFlyoutPosition($parent, $widgetBody);
6156		$widgetBody.toggle();
6157		if (!window.isRemoveSetHeights)
6158			SetHeights();
6159
6160		additionalLogic();
6161	};
6162
6163	$widgetHeader.unbind("click").bind("click", click);
6164
6165	if (bindKeyPress) {
6166		$widgetHeader.unbind("keypress").bind("keypress", function (e) {
6167			if (e.which === 13) {
6168				click(e);
6169			}
6170		});
6171	}
6172}
6173
6174function setWidgetSearchClicking($widgetHeader) {
6175	var $widgetBody = $widgetHeader.next();
6176	$widgetHeader.unbind("click").bind("click", function (e) {
6177		e.stopPropagation();
6178		e.preventDefault();
6179		$widgetBody.toggle();
6180		if (!window.isRemoveSetHeights)
6181			SetHeights()
6182	});
6183}
6184
6185//removes empty feature content areas for IE7
6186function removeEmptyFeaturedAreas() {
6187	$('div[class^="html5aside"]').each(function () {
6188		if ($(this).html().trim() === "") {
6189			$(this).remove();
6190		}
6191	});
6192}
6193
6194
6195LayoutClass.prototype.debouncedStyleSheetUpdate = (function () {
6196	var writeStylesTimeouts = {};
6197	var DEBUG = false;
6198
6199	var diag = DEBUG && console && console.log ?
6200		function (msg) {
6201			console.log('[Debounced Stylesheet Update] ' + msg);
6202		}
6203		: function () { };
6204
6205
6206	// Original Function We are Debouncing to update stylesheet.
6207	var updateStylesheet = function (styleSheetID, styles, isEditor) {
6208		diag('Debounced Call');
6209		var styleSheet = document.getElementById(styleSheetID);
6210		isEditor = isEditor === undefined ? false : isEditor;
6211		if (!isEditor) {
6212			//Include misc styles from Theme properties.
6213			if ($('#hdnThemePropertiesMiscStyles').length > 0 && $('#hdnThemePropertiesMiscStyles').html() != '')
6214				styles += $('#hdnThemePropertiesMiscStyles').html();
6215		}
6216		if (styleSheet == null) {
6217			styleSheet = document.createElement('style');
6218			styleSheet.id = styleSheetID;
6219			styleSheet.setAttribute('type', 'text/css');
6220			var head = document.getElementsByTagName('head')[0];
6221			head.appendChild(styleSheet);
6222		}
6223		if (styleSheet.styleSheet) {
6224			styleSheet.styleSheet.cssText = styles; //IE only
6225		} else {
6226			styleSheet.innerHTML = styles;
6227		}
6228	};
6229
6230	return function (styleSheetID, styles) {
6231		diag('Bounce Call');
6232		if (writeStylesTimeouts[styleSheetID]) {
6233			clearTimeout(writeStylesTimeouts[styleSheetID]);
6234		}
6235		writeStylesTimeouts[styleSheetID] = setTimeout(function () { updateStylesheet(styleSheetID, styles); }, 100);
6236	};
6237}());
6238
6239LayoutClass.prototype.updateStylesheet = function (styleSheetID, styles) {
6240	this.debouncedStyleSheetUpdate(styleSheetID, styles);
6241};
6242
6243//Usage:  Core.Layout.toggleFeatureColumn();
6244LayoutClass.prototype.toggleFeatureColumn = function () {
6245	if ($('#pageShowFeatureColumn').val() == 'True') {
6246		$('body').addClass('withFeatureColumn');
6247		$('#featureColumn').show();
6248	} else {
6249		$('body').removeClass('withFeatureColumn');
6250		$('#featureColumn').hide();
6251	}
6252
6253	if (typeof SetHeights == 'function' && !window.isRemoveSetHeights) {
6254		SetHeights();
6255	}
6256};
6257
6258//Usage:  Core.Layout.stretchContainers(containerSelectors);
6259LayoutClass.prototype.stretchContainers = function (containerSelectors) {
6260	this.unstretchContainers(containerSelectors);
6261	$(containerSelectors).each(function () {
6262		var $container = $(this);
6263		var height = $container.outerHeight();
6264		$container.siblings().each(function () {
6265			var $sibling = $(this);
6266			if ($sibling.css('float') != 'none') {
6267				var siblingHeight = $sibling.outerHeight();
6268				height = siblingHeight > height ? siblingHeight : height;
6269			}
6270		});
6271		if (height >= ($container.outerHeight())) {
6272
6273			var desiredContainerHeight = height;
6274			var $innermostWrapper = $container;
6275
6276			//The paddings of the container itself needs to be considered as well since we allow for paddings on the structural containers too. 
6277			//This fixes the height issues we have been having with several sites(neighboring containers dont match he
6277ight) Vishal
6278			var $wrappers = $innermostWrapper;
6279
6280			while ($innermostWrapper.children('.inner').length) {
6281				$wrappers = $wrappers.add($innermostWrapper.children('.inner'));
6282				$innermostWrapper = $innermostWrapper.children('.inner');
6283			}
6284
6285			var paddingHeight = 0;
6286
6287			$wrappers.each(function () {
6288				$this = $(this);
6289				paddingHeight += parseFloat($this.css('paddingTop')) + parseFloat($this.css('paddingBottom')) + parseFloat($this.css('borderBottomWidth')) + parseFloat($this.css('borderTopWidth'));
6290			});
6291
6292			var calculatedHeight = desiredContainerHeight - paddingHeight;
6293			var heightString = calculatedHeight.toString() + 'px';
6294			$innermostWrapper.css('min-height', heightString);
6295		}
6296	});
6297
6298	setTimeout(function () {
6299		if (!window.isRemoveSetHeights)
6300			SetHeights();
6301	}, 8000);
6302};
6303
6304//Usage:  Core.Layout.unstretchContainers(containerSelectors);
6305LayoutClass.prototype.unstretchContainers = function (containerSelectors) {
6306	$(containerSelectors).each(function () {
6307		var $container = $(this);
6308		$container.css('min-height', '0');
6309		$('.inner', $container).css('min-height', '0');
6310	});
6311};
6312
6313//Usage:  Core.Layout.dynamicJavascript(javaScriptCode);
6314LayoutClass.prototype.dynamicJavascript = function (javaScriptCode) {
6315	var code = javaScriptCode.replace(/\\'/g, "'").replace(/\\\"/g, "\"").replace(/\\\t/g, "\t").replace(/\\\r/g, "\r").replace(/\\\n/g, "\n").replace(/\\\f/g, "\f").replace(/\\\\/g, "\\");
6316	var myFucn = new Function(code);
6317	myFucn();
6318};
6319
6320//Usage:  Core.Layout.setColumnWidth($widget);
6321LayoutClass.prototype.setColumnWidth = function ($widget) {
6322	var width = $('input.auto.update.widgetOption.common[name=WidgetWidth]').val();
6323	$widget.closest('div.outer.col').css('width', width ? width + '%' : "");
6324};
6325
6326function LayoutClass() {
6327	this.filter = null;
6328}
6329
6330if (!window.Core.Layout) {
6331	window.Core.Layout = new LayoutClass();
6332}
6333// Handles polling login status after ajax requests lazily, and notifying the user if they should be notified.
6334//  The whole intention of this block of code is to alert the user they aren't logged in after executing an AJAX request 
6335//  without colliding with other AJAX requests or affecting user experience. This is only done if the user is initially logged in.
6336$(function () {
6337	var DEBUG = false;
6338
6339	var diag = function (msg) {
6340		if (DEBUG) {
6341			console.log("[Send User Home If Logged Out] " + msg);
6342		}
6343	};
6344
6345	// We want to be able to start/load this at a specific time (after all of the initial ajax calls complete) so I wrapped it in a function.
6346	var isLoggedInModule = function () {
6347		"use strict";
6348		diag('Initializing Send User Home If Logged Out module.');
6349		var ns = this;
6350		var notLoggedInMessage = 'You are no longer logged in. Please login to continue.';
6351		var loginCheckPending = false;
6352
6353		ns.initiallyLoggedInWithLiveEdit = $('[href="#liveEditMenu"]').hasClass('on');
6354
6355		if (!ns.initiallyLoggedInWithLiveEdit) {
6356			diag('Initialization Stopped - Not initially logged in with Live Edit On.');
6357			return; // We don't need to notify them they aren't logged in, if they aren't logged in initially.
6358		}
6359
6360		$.ajaxSetup({
6361			beforeSend: function () {
6362				ns.isAjaxOccuring = true;
6363			},
6364			complete: function () {
6365				diag('Ajax Call Completed (hook) - ' + (loginCheckPending ? 'Login Check is Pending.' : 'Login Check is not already Pending.'));
6366				ns.isAjaxOccuring = false;
6367				// If an ajax call is already occuring wait until it is finished. We don't want to affect the user experience with normal AJAX calls.
6368				if (!loginCheckPending) {
6369					lazyExecute(
6370						alertIfUserNotLoggedIn,
6371						function () { return !ns.isAjaxOccuring; },
6372						2000
6373					);
6374				}
6375			}
6376		});
6377
6378		// Executes a function based on a condition lazily, checking a given predicate at a set interval. 
6379		var lazyExecute = function (fn, executeWhenPredicate, pollingTime) {
6380			diag('Lazy Execution Triggered.');
6381			loginCheckPending = true;
6382			var intervalExecuter = null;
6383			var internalHandler = function () {
6384				diag('Attempting to execute login check.');
6385				if (executeWhenPredicate()) {
6386					fn();
6387					clearInterval(intervalExecuter);
6388					diag('Login check is no longer pending. Login check invoked.');
6389					loginCheckPending = false;
6390				} else {
6391					diag('AJAX request in progress. Trying again in a short bit.');
6392				}
6393			};
6394
6395			intervalExecuter = setInterval(internalHandler, pollingTime);
6396		}
6397
6398		var alertIfUserNotLoggedIn = function () {
6399			if (!isUserLoggedIn()) {
6400				alert('You are no longer logged in. Please login to continue.');
6401				location.href = '/myaccount?from=url&url=' + window.location.pathname;
6402			}
6403		}
6404	}
6405
6406	// We don't need to start checking if the user is logged in until after everything is probably loaded. I went with 10 seconds
6407	setTimeout(isLoggedInModule, 6000);
6408});
6409
6410//Begin Authentication
6411if (!window.location.origin) {
6412	window.location.origin = window.location.protocol + "//" + window.location.host;
6413}
6414
6415function popupSignIn(redirectUrl, parameterSet, jsCallback) {
6416	var popupBasedAuthenticationJs = new PopupBasedAuthentication();
6417
6418	popupBasedAuthenticationJs.setupJsCallback(jsCallback);
6419	popupBasedAuthenticationJs.requireLoggedIn(redirectUrl, parameterSet);
6420};
6421
6422function internetExplorerMessagingHandlerForPopup(data) {
6423	var popupBasedAuthenticationJs = new PopupBasedAuthentication();
6424	popupBasedAuthenticationJs.internetExplorerMessageHandling(data);
6425};
6426
6427var internetExplorerVersion = (function () {
6428	var undef;
6429
6430	var agent = navigator.userAgent;
6431	var reg = /MSIE\s?(\d+)(?:\.(\d+))?/i;
6432	var matches = agent.match(reg);
6433	if (matches != null) {
6434		return matches[1];
6435	}
6436	return undef;
6437}());
6438//End authentication
6439
6440/********************************************************************************
6441Logic for moving mega menus in DOM and updating their attributes.
6442/*******************************************************************************/
6443function moveMegaMenusInDOM(data) {
6444	//Grab all the flyouts that are not moved yet and are not tooltips and not in WidgetManager
6445	var $megaMenus = $('.megaMenuContainer').not('.moved');
6446	var $megaMenusAlreadyMoved = $('.megaMenuContainer.moved');
6447
6448	var parentID;
6449	var marginLeft, marginTop;
6450	$megaMenus.each(function (e) {
6451		$(this).appendTo('body');
6452		$(this).addClass('moved').addClass('megaMenu');
6453		$(this).css('position', 'absolute');
6454		$(this).css('z-index', '100');
6455		updateMegaMenuAttributes($(this), data);
6456	});
6457	$megaMenusAlreadyMoved.each(function (e) {
6458		updateMegaMenuAttributes($(this), data);
6459	});
6460}
6461
6462function updateMegaMenusOnBrowserResize() {
6463	var $megaMenus = $('.megaMenuContainer');
6464	$megaMenus.each(function () {
6465		updateMegaMenuAttributes($(this));
6466	});
6467}
6468
6469function updateMegaMenuAttributes($this, data) {
6470	//Enums
6471	var MegaMenuWidthReferenceEnum = { MainNavigation: 0, SitesContent: 1 };
6472	var MegaMenuPopupDirectionEnum = { Below: 0, Above: 1 };
6473	var widthReference = $('#megaMenuWidthReference').val();
6474	var direction = $('#megaMenuPopupDirection').val();
6475
6476	//If data has been provded, use it!.
6477	if (data != null) {
6478		if (data.widthReference != null)
6479			widthReference = data.widthReference;
6480		if (data.direction != null)
6481			direction = data.direction;
6482	}
6483
6484	//Get the main nav.
6485	var $mainNav = $('.siteNav.mainNav');
6486	//Get the closest parent having a siteWrap class.
6487	var $siteWrap = $mainNav.closest('.siteWrap');
6488
6489	var $referenceElem = null;
6490	if (widthReference == MegaMenuWidthReferenceEnum.MainNavigation)
6491		$referenceElem = $mainNav;
6492	else
6493		$referenceElem = $siteWrap;
6494
6495	if ($referenceElem != null && $referenceElem.length > 0) {
6496		//Set left position of megamenu
6497		$this.css('left', $referenceElem.offset().left + parseFloat($referenceElem.css('padding-left')));
6498		//Set width of megamenu
6499		$this.css('width', $referenceElem.width());
6500	}
6501	if (direction == null || direction == MegaMenuPopupDirectionEnum.Below) {
6502		//Set top position of megamenu. 
6503		//NOTE: Even if the widthReference is set to SitesContent, the top position is calculated always using siteNav.mainNav since thats where the megamenu needs to be displayed. 
6504		//The siteWrap is some scenarios contains all the content pushing the megamnus to show even below the footer. Vishal
6505		$this.css('top', $mainNav.offset().top + $mainNav.height());
6506	}
6507	else {
6508		//Set top position of megamenu
6509		$this.css('top', '-' + ($this.height() - $('#divToolbars').height()) + 'px');
6510	}
6511}
6512
6513function adjustMegaMenuDisplay(widthReference, direction) {
6514	var $megaMenu = $('#sampleMegaMenu');
6515	updateMegaMenuAttributes($megaMenu, { widthReference: widthReference, direction: direction });
6516}
6517/********************************************************************************
6518Logic for moving mega menus in DOM and updating their attributes.
6519/*******************************************************************************/
6520
6521/***********************************************************************************************************
6522Common editor rendering functions used in multiple widgets(editor and InfoAdvanced so far)
6523/**********************************************************************************************************/
6524function renderSlideshowIfApplicable($element) {
6525	var $slideshow = $element.find('.cpSlideshowImages');
6526	$slideshow.each(function (e) {
6527		var $this = $(this);
6528		var imgWidth = $this.attr('data-width');
6529		var className = $this.attr('class');
6530		var id = $this.attr('id');
6531		var html = getSlideshowContent(id);
6532
6533		$this.replaceWith(html);
6534
6535		// Froala specific data
6536		//Add froala related classes and image attributes only after html is replaced.
6537		if (className.indexOf('fr-') > -1) {
6538			var inlineStyles = $this.attr("style");
6539			var $images = $('.cpSlideshowJS' + id + ' img[data-delayed-image]');
6540			$images.each(function (index) {
6541				var $image = $(this);
6542				$image.attr("style", inlineStyles);
6543			});
6544
6545			// In-line and block classes
6546			if (this.classList.contains('fr-dib'))
6547				$('.cpSlideshowJS' + id).addClass('fr-dib');
6548			else if (this.classList.contains('fr-dii'))
6549				$('.cpSlideshowJS' + id).addClass('fr-dii');
6550			// Alignment classes
6551			if (this.classList.contains('fr-fil'))
6552				$('.cpSlideshowJS' + id).addClass('fr-fil');
6553			else if (this.classList.contains('fr-fir'))
6554				$('.cpSlideshowJS' + id).addClass('fr-fir');
6555		}
6556
6557		//If the slideshow has an alignment set in the editor, that alignment needs to be applied to the ol surrounding the images in slideshow.
6558		if (className.indexOf('float') > 0) {
6559			var applyClass = '';
6560			switch (className) {
6561				case 'cpSlideshowImages floatRight':
6562					applyClass = 'floatRight';
6563					break;
6564				case 'cpSlideshowImages floatLeft':
6565					applyClass = 'floatLeft';
6566					break;
6567				case 'cpSlideshowImages floatCenter':
6568					applyClass = 'floatCenter';
6569					break;
6570				case 'cpSlideshowImages floatJustify':
6571					applyClass = 'floatJustify';
6572					break;
6573			}
6574			$('.cpSlideshowJS' + id).addClass(applyClass);
6575		}
6576
6577		// Changing the container size for an inline slideshow
6578		var $container = $('#divSlideshow' + id);
6579		var hasDii = $container.hasClass('fr-dii');
6580		var hasFil = $container.hasClass('fr-fil');
6581		var hasFir = $container.hasClass('fr-fir');
6582
6583		if (hasDii && (hasFil || hasFir || (!hasFil && !hasFir))) {
6584			$container.css('width', imgWidth);
6585			$container.css('margin-right', '5px 5px 5px 0px');
6586		}
6587	});
6588}
6589
6590function getSlideshowContent(slideshowID) {
6591	var slideshowHtml = '';
6592	$.ajax({
6593		url: location.protocol + '//' + window.location.hostname + '/Slideshow/Render/' + slideshowID,
6594		type: 'POST',
6595		cache: false,
6596		async: false,
6597		success: function (response) {
6598			slideshowHtml = response;
6599		},
6600		error: function (xhr, textStatus, exception) {
6601			alert("Error: " + xhr.statusText + "\nStatus: " + xhr.status);
6602		}
6603	});
6604	return slideshowHtml;
6605}
6606/*****************************************************************************************************************
6607Common editor rendering functions used in multiple widgets(editor and InfoAdvanced so far) Ends
6608/****************************************************************************************************************/
6609
6610///Gets absolute Url when given a relative Url. Useful for certain scenarios where http call is made under https hood and it fails.
6611function getAbsoluteUrl(relativeUrl) {
6612	var myAccount = $('#MyAccountLoginPage').val();
6613
6614	if (myAccount != null && myAccount.toLowerCase() == "true") {
6615		var basePath = location.protocol + '//' + location.hostname + (typeof (location.port) !== 'undefined' && location.port != '' && location.port != '80' ? ':' + location.port : '');
6616		return basePath + relativeUrl;
6617	}
6618
6619	return relativeUrl;
6620}
6621
6622function fireMediaQueriesIfNeeded($parent) {
6623	if (window.cpMedia) {
6624		fireMediaElementQueriesOfChildren($parent);
6625	}
6626}
6627
6628function loadMaps() {
6629	downloadGoogleMapsCustomScript();
6630}
6631
6632function googleMapsCustomScriptDownloaded() {
6633	$('.googleMap').each(function (index, item) {
6634		new CivicPlus.Maps().LoadMap(item);
6635	});
6636}
6637
6638function downloadGoogleMapsCustomScript() {
6639	if (typeof (CivicPlus) !== 'undefined')
6640		CivicPlus.Maps = {};
6641	var script = document.createElement('script');
6642	script.type = 'text/javascript';
6643	if (script.readyState) {  //IE
6644		script.onreadystatechange = function () {
6645			if (script.readyState === "loaded" || script.readyState === "complete") {
6646				script.onreadystatechange = null;
6647				if (window.googleMapsMode !== 2)//dynamic but lazy loaded
6648					googleMapsCustomScriptDownloaded();
6649			}
6650		};
6651	} else {  //Others
6652		script.onload = function () {
6653			if (window.googleMapsMode !== 2)//dynamic but lazy loaded
6654				googleMapsCustomScriptDownloaded();
6655		};
6656	}
6657
6658	script.src = '/Assets/Scripts/GoogleMaps.js';
6659	document.getElementsByTagName("head")[0].appendChild(script);
6660}
6661
6662function loadGoogleMapsScript(mode, callback) {
6663	var script;
6664	window.googleMapsMode = mode;
6665	if ($('div.widgetStaffDirectory').length > 0 || $('.DirectoryNormalText .mapWrap .googleMap').length > 0) {
6666		if ($('#GoogleMapsJS').length == 0) {
6667			script = document.createElement('script');
6668			var key = document.getElementById('GoogleMapsKey').value;
6669			script.id = 'GoogleMapsJS';
6670			script.type = 'text/javascript';
6671			if (key != null) {
6672				script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&key=' + encodeURIComponent(key) + '&callback=';
6673			}
6674			else {
6675				script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&callback=';
6676			}
6677			script.src += mode !== 2 ? callback : 'downloadGoogleMapsCustomScript';
6678			document.body.appendChild(script);
6679		} else {
6680			if (window.google && window.google.maps) {
6681				loadMaps();
6682			}
6683		}
6684	}
6685}
6686$(window).on("load", function () {
6687	if (typeof targetHash !== "undefined" && targetHash) {
6688		smoothScroll(targetHash);
6689	}
6690
6691	$("a[href*='#']:not(a[href^='/#'], [href='#'])").click(function () {
6692		var $this = $(this)[0];
6693		if (hashRegex.test($this.hash)) {
6694			if ($this.target !== '_blank') {
6695				if (location.pathname
6696					.replace(/^\//, '') ===
6697					this.pathname.replace(/^\//, '') &&
6698					location.hostname === this.hostname) {
6699					return smoothScroll(this.hash);
6700				}
6701			}
6702		}
6703	});
6704	if (window.location && window.location.hash && $(window.location.hash.replace('/', '\\/')).offset()) {
6705		setTimeout(function () {
6706			$('html, body').animate({
6707				scrollTop: $(window.location.hash).offset().top - calculateTotalFixedHeight()
6708			}, 300);
6709		}, 2000);
6710	}
6711});
6712//Calculates the total fixed length
6713function calculateTotalFixedHeight() {
6714	var totalHeight = 0;
6715
6716	if ($('.fixedTop_ts').height()) {
6717		totalHeight += $('.fixedTop_ts').height();
6718	}
6719	if ($('#divToolbars').height()) {
6720		totalHeight += $('#divToolbars').height();
6721	}
6722	if ($('div.cp-Toolbars').height()) {
6723		totalHeight += $('div.cp-Toolbars').height();
6724	}
6725	if ($('.stickyStructuralContainer').height()) {
6726		totalHeight += $('.stickyStructuralContainer').height();
6727	}
6728
6729	return totalHeight;
6730}
6731
6732function smoothScroll(hash) {
6733	var target = $(hash);
6734	target = target.length ? target : $('[name=' + hash.slice(1) + ']');
6735	if (!target.length) {
6736		return false;
6737	}
6738	var speed = target[0].getAttribute('data-smoothscrolling') ? 1333 : 1;
6739	var cpToolbarsHeight = $('div.cp-Toolbars').height() || 0;
6740	$('html, body').animate({
6741		scrollTop: target.offset().top - ($('#divToolbars').height() + cpToolbarsHeight)
6742	}, speed);
6743	window.location.hash = ''; // Fixes chrome focus bug
6744	window.location.hash = hash;
6745	return false;
6746}
6747
6748function hideLiveEditElement(target) {
6749	target.addClass('hide');
6750	setTimeout(function () {
6751		target.hide();
6752	}, 666);
6753}
6754
6755function showLiveEditElement(target) {
6756	target.show();
6757	setTimeout(function () {
6758		target.removeClass('hide');
6759	}, 1);
6760}
6761
6762function redrawContextualInnerToolbar(pageID, versionID) {
6763	if (versionID > 0) {
6764		var url = '/Pages/Toolbar/Contextual?pageID=' + pageID + '&versionID=' + versionID;
6765		$.ajax({
6766			url: url,
6767			type: 'GET',
6768			cache: false,
6769			success: function (response) {
6770				$('#informativeToolBar').remove();
6771				var $toolbar = $('#innerToolbar');
6772				if ($toolbar.length > 0) {
6773					$toolbar.replaceWith(response);
6774				} else {
6775					$('#divToolbars').append(response);
6776				}
6777				var toolbarHeight = $('#divToolbars').height() + 'px';
6778				$('#bodyWrapper').css('padding-top', toolbarHeight);
6779				if (window.liveEditTabs != null && typeof (window.liveEditTabs.updateMaxHeightTabs) == "function")
6780					window.liveEditTabs.updateMaxHeightTabs();
6781				InitializeToolbar();
6782				if (window.Toolbars && window.Toolbars.ContextualToolbar) {
6783					$(window.Toolbars.ContextualToolbar).trigger('Loaded');
6784				}
6785				$('.widgetSpacer').each(function () {
6786					var $this = $(this);
6787					if (!$this.hasClass('adminWrap')) {
6788						$this.addClass('adminWrap');
6789					}
6790				});
6791			},
6792			error: function (xhr, textStatus, exception) {
6793				if (xhr.status !== 0 && xhr.readyState !== 0)
6794					alert('Error: ' + xhr.statusText + '\nStatus: ' + xhr.status);
6795			}
6796		});
6797	}
6798}
6799
6800function InitializeToolbar() {
6801	$('#lnkVersionSaveAsCopy', '#ulVersionToolBar').unbind('click').click(function (e) {
6802		e.preventDefault();
6803		if (!$(this).hasClass('inactive')) {
6804			SaveAsCopy();
6805		}
6806	});
6807	$('#lnkVersionCancel', '#ulVersionToolBar').unbind('click').click(function (e) {
6808		e.preventDefault();
6809		if (!$(this).hasClass('inactive')) {
6810			AbandonWorkingCopy();
6811		}
6812	});
6813	$('#layoutPageSelector', "#LayoutToolBar").unbind('change').change(function () {
6814		var pageId = parseInt($(this).val(), 10);
6815		if (!isNaN(pageId))
6816			window.location.href = "/" + pageId;
6817	});
6818}
6819
6820function triggerStickyStructuralInitLogic() {
6821	setTimeout(function () {
6822		new StickyStructuralContainers().init();
6823	}, 666);
6824}
6825
6826//Function to toggle for widget link.
6827function toggleWidgetsLink(isEnabled) {
6828	var widgetLink = $('#innerLnkwidgets');
6829
6830	if (widgetLink) {
6831		if (isEnabled) {
6832			widgetLink.prop('disabled', false).removeClass('cp-modificationProhibited');
6833			widgetLink[0].href = '#liveEditTab_widgets';
6834			addClassToWidgets(true);
6835		}
6836		else {
6837			widgetLink.prop('disabled', true).addClass('cp-modificationProhibited');
6838			widgetLink[0].href = '#';
6839			addClassToWidgets(false);
6840		}
6841	}
6842}
6843
6844//Function to show/hide widget disabled popup.
6845function showWidgetDisabledPopUp() {
6846	var options = {
6847		title: 'Widget Edit',
6848		elementID: 'widgetDisabledPopup',
6849		autoAdjust: false,
6850		className: 'adminWrap accountActivation widgetPopUp popup-position',
6851		isFrontEnd: false,
6852		htmlContent: '<div class="modalScreen socialSignIn"><p>To modify this content, you\'ll have to create a copy of the page first.</p><p><a class="widget-disable socialButton twitter toTwitterPageSelect pageCopyEditWidgetModal cursor-pointer"><span class="socialButton-override">Copy Page</span></a><a class="widget-disable socialButton twitter toTwitterPageSelect closeEditWidgetModal cursor-pointer" style="padding-left:20px;"><span class="socialButton-override">Cancel</span></a></p></div>',
6853		draggable: true
6854	}
6855
6856	openCpModal(options);
6857}
6858
6859//Function to save page copy.
6860function savePageCopy() {
6861	SaveAsCopy();
6862	closeModal();
6863}
6864
6865//Function to close the modal
6866function closeModal() {
6867	hideModal('.modalContainer.modalContainerCP');
6868}
6869
6870//Function to add class to widgets
6871function addClassToWidgets(isEnabled) {
6872	var pageContent = $('.pageContent div');
6873	$.each(pageContent, function (index, item) {
6874		if (isEnabled) {
6875			$(item).removeClass('cp-modificationProhibited');
6876		}
6877		else {
6878			$(item).addClass('cp-modificationProhibited');
6879		}
6880	});
6881}
6882
6883function initializeSkipLinkHandlers() {
6884	var skipLinks = document.querySelectorAll('#skipToContentLinks a');
6885	if (!skipLinks.length)
6886		return;
6887
6888	skipLinks.forEach(function (link) {
6889		link.addEventListener('touchstart', handleSkipLinkActivation, { passive: false });
6890		link.addEventListener('click', handleSkipLinkActivation);
6891		link.addEventListener('keydown', function (e) {
6892			if (e.key === 'Enter' || e.key === ' ') {
6893				handleSkipLinkActivation.call(link, e);
6894			}
6895		});
6896	});
6897}
6898
6899function handleSkipLinkActivation(e) {
6900	e.preventDefault();
6901	e.stopPropagation();
6902
6903	// Prevent duplicate execution on mobile (touchstart + click)
6904	if (e.type === 'click' && e.isTrusted === false) {
6905		return;
6906	}
6907
6908	// handle rapid touches (300ms threshold)
6909	var now = Date.now();
6910	var lastActivation = this.dataset.lastActivation || 0;
6911	if (now - lastActivation < 300) {
6912		return;
6913	}
6914
6915	this.dataset.lastActivation = now;
6916	var href = this.getAttribute('href');
6917	if (!href || href[0] !== '#' || href.length < 2)
6918		return;
6919
6920	var target = document.querySelector(href);
6921	if (!target) return;
6922
6923	var previousTabIndex = target.getAttribute('tabindex');
6924	if (previousTabIndex === null) {
6925		target.setAttribute('tabindex', '-1');
6926	}
6927
6928	void document.body.offsetHeight;
6929
6930	// Get toolbar elements
6931	var $divToolbars = $('#divToolbars');
6932	var $cpToolbars = $('div.cp-Toolbars');
6933
6934	var divToolbarsHeight = $divToolbars.length && $divToolbars.is(':visible') ? ($divToolbars.outerHeight(true) || 0) : 0;
6935	var cpToolbarsHeight = $cpToolbars.length && $cpToolbars.is(':visible') ? ($cpToolbars.outerHeight(true) || 0) : 0;
6936
6937	var toolbarHeight = divToolbarsHeight + cpToolbarsHeight;
6938	var $target = $(target);
6939	var targetOffsetTop = $target.offset().top;
6940	var targetTop = targetOffsetTop - toolbarHeight;
6941
6942	$('html, body').animate({scrollTop: targetTop}, 300, function () {
6943        try {
6944            target.focus({ preventScroll: true });
6945		} catch (focusErr) {
6946            target.focus();
6947        }
6948	});
6949}
6950;
6951//Usage:  Core.Layout.attachTabbedWidgetTabHandlers();
6952LayoutClass.prototype.attachTabbedWidgetTabHandlers = function () {
6953	window.Pages.tabChangeHandlers = window.Pages.tabChangeHandlers || [];
6954
6955	storePanelScripts();
6956
6957	// Hiding all panels, then showing the first one
6958	$('.tabbedWidget.cpTabPanel').hide();
6959	$('.tabbedWidget.cpTabPanel.showing').show();
6960
6961	$('.tabbedWidget.cpTabs, .tabbedWidgetNarrow.cpTabs').each(function (e) {
6962		var $tabs = $(this);
6963		var activateTab = function ($tab) {
6964			$tab.trigger('click');
6965		};
6966
6967		// Keyboard navigation for tabs (WCAG 2.1 AA)
6968		$tabs.find('li:not(.newTab) > a[role="tab"]').unbind('keydown.tabWidget').bind('keydown.tabWidget', function (e) {
6969			var $currentTab = $(this);
6970			var $tabList = $currentTab.closest('ol');
6971			var $allTabs = $tabList.find('li:not(.newTab) > a[role="tab"]');
6972			var currentIndex = $allTabs.index($currentTab);
6973			var newIndex = -1;
6974
6975			switch (e.key) {
6976				case 'ArrowRight':
6977				case 'Right':
6978					e.preventDefault();
6979					newIndex = (currentIndex + 1) % $allTabs.length;
6980					break;
6981				case 'ArrowLeft':
6982				case 'Left':
6983					e.preventDefault();
6984					newIndex = (currentIndex - 1 + $allTabs.length) % $allTabs.length;
6985					break;
6986				case 'Home':
6987					e.preventDefault();
6988					newIndex = 0;
6989					break;
6990				case 'End':
6991					e.preventDefault();
6992					newIndex = $allTabs.length - 1;
6993					break;
6994				case 'Enter':
6995				case ' ':
6996					e.preventDefault();
6997					$currentTab.click();
6998					return;
6999				default:
7000					return;
7001			}
7002
7003			if (newIndex >= 0) {
7004				// Roving tabindex: set all tabs to -1, focused tab to 0
7005				$allTabs.attr('tabindex', '-1');
7006				var $newTab = $allTabs.eq(newIndex);
7007				$newTab.attr('tabindex', '0').focus();
7008				activateTab($newTab);
7009			}
7010		});
7011
7012		// Keyboard navigation for accordion buttons
7013		$tabs.find('li:not(.newTab) > a[role="button"]').unbind('keydown.tabWidget').bind('keydown.tabWidget', function (e) {
7014			if (e.key === 'Enter' || e.key === ' ') {
7015				e.preventDefault();
7016				$(this).click();
7017			}
7018		});
7019
7020		// When a tab is clicked
7021		$tabs.find('li:not(.newTab) > a').unbind('click').click(function (e) {
7022			e.preventDefault();
7023			var $selectedTab = $(this);
7024			var selectedTabHref = attrOrProps($selectedTab, 'href');
7025			var hashTabOffset = selectedTabHref.indexOf('#');
7026			var target = selectedTabHref.slice(hashTabOffset);
7027			var anchor = this;
7028			var $target = $('div' + target);
7029			var $targetli = $selectedTab.parent();
7030			var isNarrow = $selectedTab.parent().parent().hasClass('tabbedWidgetNarrow');
7031			var isAccordion = $selectedTab.parent().parent().hasClass('accordion');
7032			var $parentTab = $selectedTab.parent().parent().parent();
7033			var tabAriaAttribute = isAccordion ? "aria-expanded" : "aria-selected";
7034
7035			var showTab = function () {
7036				$target.addClass('showing').slideDown(function () {
7037					doAfterSwitchingTabs($target);
7038					if (document.body.classList.contains("narrow")) {
7039						anchor.scrollIntoView({behavior: "smooth", block: "start", inline: "nearest"});
7040					}
7041				}).css({'overflow': ''});
7042			}
7043			// Checking to see if it's showing already
7044			if (!$target.hasClass('showing') || isAccordion === true) {
7045				// Making the current tab inactive, and the new one active
7046				var $widget = $selectedTab.parents('.widget.widgetTabbed');
7047				
7048				if (isAccordion === false) {
7049					if ($widget.hasClass('narrow')) {
7050						$selectedTab.parent().parent().siblings('ol').find('li.active').removeClass('active');
7051						$selectedTab.parent().parent().siblings('ol').find('a[' + tabAriaAttribute + '="true"]').attr(tabAriaAttribute, "false");
7052						// Update roving tabindex on sibling tab lists
7053						$selectedTab.parent().parent().siblings('ol').find('a[role="tab"]').attr('tabindex', '-1');
7054					} else {
7055						$parentTab.children().first().find('li.active').removeClass('active');
7056						$parentTab.children().first().find('a[' + tabAriaAttribute + '="true"]').attr(tabAriaAttribute, "false");
7057						// Update roving tabindex on the primary tab list
7058						$parentTab.children().first().find('a[role="tab"]').attr('tabindex', '-1');
7059					}
7060				}
7061
7062				var tabButton = $widget.find('a[href="' + target + '"]');
7063
7064				if (isNarrow && isAccordion === false) {
7065					tabButton.attr(tabAriaAttribute, "true");
7066					tabButton.attr('tabindex', '0');
7067					tabButton.parent().addClass('active');
7068				}
7069				// Hiding the current panel, showing the new one
7070				if (!isNarrow) {
7071					tabButton.attr(tabAriaAttribute, "true");
7072					tabButton.attr('tabindex', '0');
7073					tabButton.parent().addClass('active');
7074					$target.siblings('.showing').removeClass('showing').hide();
7075					$target.addClass('showing').show();
7076					doAfterSwitchingTabs($target);
7077				} else {
7078					if(isAccordion === false)
7079					{
7080						$target.siblings('.showing').removeClass('showing').slideUp();
7081						
7082						showTab();
7083					}
7084					else
7085					{
7086						if ($targetli.hasClass('active')) { 
7087							$targetli.removeClass('active');
7088							$targetli.find("a").attr(tabAriaAttribute, "false");
7089						} else {
7090							$targetli.addClass('active');
7091							$targetli.find("a").attr(tabAriaAttribute, "true");
7092						}
7093						$target.hasClass('showing') ? $target.removeClass('showing').slideUp() : showTab();
7094					}
7095				}
7096
7097				var $arr = ($target).contents().find('.videoPlayer');
7098				if ($arr.length > 0) {
7099					($target).contents().find('.videoPlayer').children('iframe').trigger('onload');
7100				}
7101			}
7102			//Checking any on tab change handlers were added
7103			if (window.Pages.tabChangeHandlers.length > 0) {
7104				window.Pages.tabChangeHandlers.forEach(function (car) { car(); });
7105			}
7106		});
7107	});
7108
7109	$('.nextAction.tabName').unbind('click').click(function (e) {
7110		e.preventDefault();
7111	});
7112
7113	$.fn.hasData = function (prop) {
7114		return this.filter(
7115			function () { return $(this).data(prop) != null; }
7116		);
7117	};
7118
7119	var updateChildWidgetClasses = function ($target) {
7120		// Apply wide/narrow classes based on parent tabbed widget state
7121		var liveEditEnabled = getCookieValue("enableLiveEdit") === "true";
7122		if (liveEditEnabled)
7123			return;
7124
7125		var $parentTabbedWidget = $target.closest('.widget.widgetTabbed');
7126		var isParentNarrow = $parentTabbedWidget.hasClass('narrow');
7127		var $childWidgets = $target.find('.widget').not('[data-elementqueryclasses]');
7128
7129		if (isParentNarrow) {
7130			$childWidgets.addClass('narrow').removeClass('wide');
7131			$target.find('[data-event-list-row="true"]').addClass('narrow').removeClass('wide');
7132		} else {
7133			$childWidgets.addClass('wide').removeClass('narrow');
7134			$target.find('[data-event-list-row="true"]').addClass('wide').removeClass('narrow');
7135		}
7136	};
7137
7138	var doAfterSwitchingTabs = function ($target) {
7139		fireMediaQueriesIfNeeded($target);
7140
7141		updateChildWidgetClasses($target);
7142
7143		if (!window.isRemoveSetHeights)
7144			SetHeights();
7145
7146		reloadPanelScripts($target[0]);
7147	};
7148};
7149
7150///Matches the rest of the tab's height with the highest tab in a tabbed widget.
7151function setTabbedWidgetsTabHeight(tabWrapperID) {
7152	if (tabWrapperID == null || typeof tabWrapperID == 'undefined') {
7153		$('.tabbedWidget.cpTabs').not('.left,.right').each(function (e) {
7154			var $this = $(this);
7155			$this.find('li').each(function () {
7156				var $thisLi = $(this);
7157				if ($thisLi.css('height') != '0px')
7158					$thisLi.find('a').css('height', $thisLi.css('height'));
7159			})
7160		});
7161	}
7162	else {
7163		var $wrapper = $('#' + tabWrapperID);
7164		$wrapper.find('ol.tabbedWidget.cpTabs').not('.left,.right').find('li').each(function () {
7165			var $thisLi = $(this);
7166			if (!$thisLi.is(':hidden')) {
7167				if ($thisLi.css('height') != '0px')
7168					$thisLi.find('a').css('height', $thisLi.css('height'));
7169			}
7170		});
7171	}
7172}
7173
7174function storePanelScripts() {
7175	var panels = document.querySelectorAll('.tabbedWidget.cpTabPanel');
7176	for (var i = 0; i < panels.length; i++) {
7177		var panel = panels[i];
7178		if (panel.style.display === 'none') {
7179			var containers = panel.querySelectorAll('[id^="customHtml"]');
7180			for (var j = 0; j < containers.length; j++) {
7181				var container = containers[j];
7182				if (!container.getAttribute('data-original-html')) {
7183					var scripts = container.getElementsByTagName('script');
7184					if (scripts.length > 0) {
7185						container.setAttribute('data-original-html', container.innerHTML);
7186					}
7187				}
7188			}
7189		}
7190	}
7191}
7192
7193function reloadPanelScripts(panelElement) {
7194	if (!panelElement)
7195		return;
7196
7197	var containers = panelElement.querySelectorAll('[id^="customHtml"]');
7198	if (!containers || containers.length === 0)
7199		return;
7200
7201	for (var i = 0; i < containers.length; i++) {
7202		var container = containers[i];
7203		var originalHtml = container.getAttribute('data-original-html');
7204		if (!originalHtml)
7205			continue;
7206
7207		container.innerHTML = originalHtml;
7208
7209		var scripts = container.getElementsByTagName('script');
7210		var scriptsArray = Array.prototype.slice.call(scripts);
7211		for (var j = 0; j < scriptsArray.length; j++) {
7212			var oldScript = scriptsArray[j];
7213			var newScript = document.createElement('script');
7214			if (oldScript.src) {
7215				newScript.src = oldScript.src;
7216			} else {
7217				newScript.textContent = oldScript.textContent || oldScript.innerText;
7218			}
7219			oldScript.parentNode.replaceChild(newScript, oldScript);
7220		}
7221	}
7222}
7223;
7224/**** Functions to handle Main/Left Menu on Front-end. *****/
7225//Global variables
7226var MAIN_MENU = 2;
7227var SIDE_MENU = 1;
7228var menuManager = new MenuManager();
7229var accessibleMenuToggleEnabled = window.FeatureToggles.isActive("CMS.Pages.AccessibleMainMenuWithIndicators");
7230//setup RWD menu
7231window.Pages = window.Pages || {};
7232$.when(window.Pages.rwdReady, menuManager.mainMenuReady).done(function () {
7233	menuManager.initRWD();
7234	var isLoggedBackendUser = $('#helpMenu').length == 1;
7235	var mql = matchMedia(window.mainMenuMediaQuery);
7236	var isFirstTimeRun = true;
7237	var executeOnce = function () {
7238		fireAllMediaElementQueries();
7239		if (typeof rearrangeFlyouts === 'function')
7240			rearrangeFlyouts(false);
7241		window.Pages.onResizeHandlersExecute();
7242		window.Pages.toolBarDeferred.resolve();
7243	};
7244	if (!mql.matches) {
7245		executeOnce();
7246		isFirstTimeRun = false;
7247	}
7248	cpMedia.register(window.mainMenuMediaQuery, {
7249		setup: function () {
7250			if (isLoggedBackendUser)
7251				$('div.cpToolbar.user').removeClass('public').addClass('admin adminWrap');
7252		},
7253		match: function () {
7254			$('body').addClass('narrow').removeClass('wide');
7255			if (isLoggedBackendUser)
7256				$('div.cpToolbar.user').removeClass('admin adminWrap').addClass('public');
7257			menuManager.moveToMobile();
7258			resetBodyPadding && resetBodyPadding();
7259			if (isFirstTimeRun) {
7260				executeOnce();
7261			}
7262			isFirstTimeRun = false;
7263		},
7264		unmatch: function () {
7265			$('body').addClass('wide').removeClass('narrow');
7266			if (isLoggedBackendUser)
7267				$('div.cpToolbar.user').removeClass('public').addClass('admin adminWrap');
7268			menuManager.moveToDesktop();
7269		}
7270	});
7271});
7272
7273//Defines menu class to handle Main/Left Menu on Front-end.
7274function MenuManager() {
7275	//object variables
7276	this.$divListSubMenus = null; //hide div where submenus are be placed.
7277	//this.$containerSubMenus = $('#containerSubMenus'); ; //no hidden div to hold the submenus of main menu being displayed. Workaround to solve z-index issues. could be removed along with its related code after redo layout project!
7278	this.menuTimeoutID = null;
7279	this.mainMenuMaxSubMenuLevels = 0;
7280	this.sideMenuMaxSubMenuLevels = 0;
7281	this.popdownDelaySideMenu = 500;
7282	this.popdownDelayTopMenu = 500;
7283	this.popupDelaySideMenu = 300;
7284	this.popupDelayTopMenu = 300;
7285	this.isMainMenuEditable = false;
7286	this.isMainMenuBeingDragged = false;
7287	this.isSideMenuEditable = false;
7288	this.isSideMenuBeingDragged = false;
7289	this.sideMenuHasCustomLinks = false;
7290	this.bouncing = true;
7291	this.initialized = false;
7292	this.setupDraggable = false;
7293	this.mobileMainNav = false;
7294	this.mainMenuInit = false;
7295	this.mainMenuReady = $.Deferred();
7296	this.$mainNavHolderMobile = null;
7297	this.$mainNav = null;
7298	this.$mainNavMenu = null;
7299	this.rwdInitNavOpenButton = false;
7300	this.mainMenuTextResizer = false;
7301	this.mainMenuTextResizerRatio = 0.5;
7302	this.isAdjustingMainMenuItemsWidth = false;
7303
7304	//Initialize menu manger after document was load
7305	this.init = function () {
7306		var self = this; // Reference to current object
7307		if (!self.initialized) {
7308			self.initialized = true;
7309			this.resetSubMenus();
7310
7311			// Hide all submenus after clicking any menu item
7312			$('li.subMenuItem > a.navMenuItem, li.topMenuItem > a.navMainItem').on("click", function () {
7313				menuManager.hideAllSubMenus(MAIN_MENU);
7314				menuManager.hideAllSubMenus(SIDE_MENU);
7315			});
7316
7317			// Hide submenu/s when the Escape key is pressed
7318			document.addEventListener('keydown', function (event) {
7319				if (event.key === "Escape") {
7320					// Only handle if focus is inside a menu or submenu
7321					if (!document.activeElement.closest('#secondaryNav, #mainNav, .mainNavMegaMenu, .secondarySubMenu, .mainSubMenu')) {
7322						return;
7323					}
7324
7325					let menuButton = null;
7326					const previouslyFocusedElement = document.activeElement;
7327					
7328					const subMenuContainer = previouslyFocusedElement.closest("ol[id^='ParentMainItem']");
7329					if (subMenuContainer) {
7330						// Get the parent menu item id (e.g., MainItem2151 for ParentMainItem2151)
7331						const parentItemId = subMenuContainer.id.replace('Parent', '');
7332						const parentMenuItem = document.getElementById(parentItemId);
7333						if (parentMenuItem) {
7334
7335							var liElement = parentMenuItem;
7336							const currentLi = previouslyFocusedElement.closest('li');
7337							const currentLiAnchor = currentLi ? currentLi.querySelector('a') : null;
7338							if (currentLi && currentLi['ariaHasPopup'] === "true" && currentLiAnchor.getAttribute('aria-expanded') === "true") {
7339								liElement = currentLi;
7340							}
7341
7342							menuManager.hideSubMenu($(liElement));
7343
7344							// Find the anchor inside the parent menu item
7345							const anchor = liElement.querySelector('a');
7346							menuButton = anchor;
7347						}
7348					} else {
7349						// Logic for mega menus
7350						const menuContainer = previouslyFocusedElement.closest("aside[id^='mainNavMegaMenu'], ol[id^='ParentMainItem']");
7351						if (menuContainer) {
7352							const itemID = menuContainer.id.match(/\d+$/)?.[0];
7353							menuButton = findMainNavButton(itemID);
7354						}
7355
7356						// Hide all submenus
7357						menuManager.hideAllSubMenus(MAIN_MENU);
7358						menuManager.hideAllSubMenus(SIDE_MENU);
7359					}
7360
7361					// Return focus to the parent menu item if applicable
7362					if (menuButton) {
7363						menuButton.focus();
7364						self.toggleIndicator($(menuButton));
7365						return;
7366					} else {
7367						self.toggleIndicator($(previouslyFocusedElement));
7368					}
7369				}
7370			});
7371
7372			/*
7373				Recursively traverses the menu hierarchy to find the main navigation button corresponding to a given menu item ID.
7374
7375				@param {string} itemID - The ID of the menu item to find the button for.
7376				@returns {HTMLElement|null} - The main navigation button element, or null if not found.
7377			*/
7378			function findMainNavButton(itemID) {
7379				const menuItem = document.querySelector(`#MainItem${itemID}`);
7380				const parent = menuItem && menuItem.closest("ol[id^='ParentMainItem']");
7381				const parentID = parent && parent.id.match(/\d+$/)?.[0];
7382
7383				if (parentID) {
7384					return findMainNavButton(parentID);
7385				} else {
7386					return menuItem.querySelector('a');
7387				}
7388			}
7389		}
7390		if (self.setupDraggable)
7391			self.attachDragAndDropHandlers();
7392	};
7393
7394	this.initRWD = function () {
7395		var self = this; // Reference to current object
7396		self.$mainNavHolderMobile = $("#mainNavHolderMobile");
7397		self.$mainNav = $("#mainNav");
7398		self.$mainNavMenu = $("#mainNavMenu");
7399		if (self.isAdjustingMainMenuItemsWidth) {
7400			self.resetMainItemsWidth("#mainNavMenu");
7401			self.adjustMainItemsWidth("#mainNavMenu");
7402		}
7403		if (self.mainMenuTextResizer)
7404			self.$mainNavMenu.responsiveMenuText({ ratio: self.mainMenuTextResizerRatio });
7405	};
7406
7407	this.resetSubMenus = function () {
7408		var self = this; // Reference to current object
7409		if (self.$divListSubMenus != null)
7410			self.$divListSubMenus.remove();
7411		var $divListSubMenus = $('<div id="divListSubMenus" style="display:block; visibility:hidden; position:absolute; left:-9999px; top:-9999px;" class="siteNav"></div>');
7412		//Trick to get width from hidden elements needed to calculate bouncing. If above styles creates problems use hack from http://stackoverflow.com/questions/1472303/jquery-get-width-of-element-when-not-visible-display-none
7413		var docFrag = $(document.createDocumentFragment());
7414		docFrag[0].appendChild($divListSubMenus[0].cloneNode(true));
7415		self.$divListSubMenus = docFrag.children();
7416		$divListSubMenus.remove();
7417	};
7418
7419	/*var $body = $("body");
7420	this.isNarrowSite = function () {
7421		//return $body.hasClass("narrow");
7422		return true;
7423	};*/
7424}
7425
7426MenuManager.prototype.moveToMobile = function () {
7427	var menusToClose = document.getElementsByClassName("megaMenuContainer");
7428	for (i = 0; i < menusToClose.length; i++) {
7429		menusToClose[i].style.display = "none";
7430	}
7431
7432	var self = this; // Reference to current object
7433	if (!self.mobileMainNav) {
7434		self.mobileMainNav = true;
7435		if (self.mainMenuTextResizer && self.$mainNavMenu.data('responsiveMenuText'))
7436			self.$mainNavMenu.responsiveMenuText('dispose');
7437		if ($("#nav-open-btn").length === 0) {
7438			$('#divToolbars').append($('<a class="nav-btn" id="nav-open-btn" href="#nav" aria-haspopup="true" role="menu">Menu</a>'));
7439			self.applyResponsiveMenuSettings();
7440			self.initNavOpenButton();
7441		}
7442		self.$mainNav.before($('<div id="mainNavOriginalPosition" style="display:none;"></div>'));
7443		self.$mainNavHolderMobile.append(self.$mainNav);
7444		self.$mainNavMenu.wrap('<div id="rwd-menu" class="rwd-menuwrapper">');
7445		self.$mainNavMenu.attr('aria-hidden', 'true');
7446		var $menu = $('#rwd-menu');
7447
7448		$menu.rwdmenu();
7449
7450		$menu.onclick = function () { };
7451
7452		if (self.isAdjustingMainMenuItemsWidth)
7453			self.resetMainItemsWidth("#mainNavMenu");
7454	}
7455};
7456
7457MenuManager.prototype.applyResponsiveMenuSettings = function () {
7458	var signInBar = $('.cpToolbar.user.public');
7459	var adminToolbar = $('.cp-Admin-Legacy-Toolbar');
7460	var alertBar = $('.alertToolbar');
7461	var navButton = $("#nav-open-btn");
7462	var fullWidth = window.fullWidthResponsiveMenu;
7463	var fixedMenu = window.fixedResponsiveMenu;
7464
7465	var responsiveMenuButtonHeight = window.responsiveMenuHeight !== '' ? window.responsiveMenuHeight : "34";
7466	var responsiveMenuButtonHeightWithPx = "";
7467	if (responsiveMenuButtonHeight.indexOf('px') === -1) responsiveMenuButtonHeightWithPx = responsiveMenuButtonHeight + 'px';
7468
7469	if (responsiveMenuButtonHeight > 34) //dont assign any inline styles if height < 34
7470	{
7471		responsiveMenuButtonHeight -= (signInBar.length && 8);
7472		var responsiveMenuButtonHeightNavbtnWithpx = "";
7473		if (responsiveMenuButtonHeight.toString().indexOf('px') === -1) responsiveMenuButtonHeightNavbtnWithpx = responsiveMenuButtonHeight + 'px';
7474
7475		// Set the button height
7476		if (responsiveMenuButtonHeight !== "px") navButton.css("height", responsiveMenuButtonHeightNavbtnWithpx).css("line-height", responsiveMenuButtonHeightNavbtnWithpx);
7477	}
7478
7479	var responsiveMenuFontSize = window.responsiveMenuFontSize;
7480	if (responsiveMenuFontSize.indexOf('px') === -1) responsiveMenuFontSize += 'px';
7481	// Set the button font-size
7482	if (responsiveMenuFontSize !== 'px') navButton.css('font-size', responsiveMenuFontSize);
7483
7484	if ((fullWidth || alertBar.length) && !signInBar.length) {
7485		// Apply styles for the full-width button
7486		navButton.css("right", "0");
7487		navButton.css("bottom", "auto");
7488	}
7489
7490	// Special case: Forces full-width in order to avoid empty gap on right side of hamburger menu - see bug https://civicplus.tpondemand.com/entity/77390-an-extra-spacing-appears-below-the
7491	if (!fixedMenu && !fullWidth && !alertBar.length && !signInBar.length) {
7492		// Apply styles for the full-width button
7493		navButton.css("right", "0");
7494		navButton.css("bottom", "auto");
7495	}
7496	if (adminToolbar && adminToolbar.length != 0) {
7497		navButton.css("margin-top", "71px");
7498	}
7499	if (signInBar.length) {
7500		// Fix sign in bar height
7501		signInBar.css("height", responsiveMenuButtonHeightWithPx);
7502
7503		// Fix sign in button height
7504		signInBar.find(".button").css("height", responsiveMenuButtonHeightWithPx).css("line-height", responsiveMenuButtonHeightWithPx);
7505
7506		if (window.fixedResponsiveMenu && $('#nav-open-btn').length) {
7507			$('.cpToolbar.user.public').css("z-index" , "101");
7508		}
7509	}
7510
7511	if (fixedMenu) {
7512		// Move the menu button and menu to #outer-wrap (outside of transform)
7513		$("#nav-open-btn, #mainNavHolderMobile").appendTo("#outer-wrap");
7514
7515		// Make fixed
7516		navButton.css("position", "fixed");
7517
7518		// Prevent overlapping in the menu
7519		$("#mainNavHolderMobile").css("position", "fixed").css("top", responsiveMenuButtonHeightWithPx).css("left", "0").css("right", "0").css("bottom", "0");
7520
7521		// Remove main nav transform, fix z-index issues
7522		$("<style>.js-navopen #mainNav { transform: none; } .mainNavHolderMobile{ z-index: -1;}.js-navopen .mainNavHolderMobile{z-index: 1;}</style>").appendTo("body");
7523
7524		// Prevent overflow of the menu
7525		$("#mainNav").css("overflow-y", "auto");
7526
7527		if (signInBar.length) {
7528			// Move the sign in bar to #outer-wrap (outside of transform)
7529			signInBar.appendTo("#outer-wrap");
7530			signInBar.css("top", "0").css("left", "0").css("right", "0").css("position", "fixed");
7531		}
7532
7533		if (fullWidth || signInBar.length || alertBar.length) {
7534			// Add padding-top to #outer-wrap (prevent the button/sign in bar from overlapping stuff)
7535			$("#outer-wrap").css("padding-top", responsiveMenuButtonHeightWithPx);
7536		}
7537	}
7538};
7539
7540MenuManager.prototype.moveToDesktop = function () {
7541	var self = this; // Reference to current object
7542	if (self.mobileMainNav) {
7543		self.mobileMainNav = false;
7544		$("#mainNavOriginalPosition").replaceWith(self.$mainNav);
7545		self.$mainNavMenu.unwrap().rwdmenu('destroy');
7546		if (self.isAdjustingMainMenuItemsWidth)
7547			self.adjustMainItemsWidth("#mainNavMenu");
7548		if (self.mainMenuTextResizer)
7549			self.$mainNavMenu.responsiveMenuText({ ratio: self.mainMenuTextResizerRatio });
7550		self.$mainNavMenu.attr('aria-hidden', 'false');
7551		self.$mainNav.css("overflow-y", "");
7552	}
7553};
7554
7555MenuManager.prototype.initNavOpenButton = function () {
7556	var self = this; // Reference to current object
7557	if (self.rwdInitNavOpenButton)
7558		return;
7559	self.rwdInitNavOpenButton = true;
7560
7561	var trim = function (str) {
7562		return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
7563	};
7564
7565	var hasClass = function (el, cn) {
7566		return (' ' + el.className + ' ').indexOf(' ' + cn + ' ') !== -1;
7567	};
7568
7569	var addClass = function (el, cn) {
7570		if (!hasClass(el, cn)) {
7571			el.className = (el.className === '') ? cn : el.className + ' ' + cn;
7572		}
7573	};
7574
7575	var removeClass = function (el, cn) {
7576		el.className = trim((' ' + el.className + ' ').replace(' ' + cn + ' ', ' '));
7577	};
7578
7579	var hasParent = function (el, id) {
7580		if (el) {
7581			do {
7582				if (el.id === id) {
7583					return true;
7584				}
7585				if (el.nodeType === 9) {
7586					break;
7587				}
7588			}
7589			while ((el = el.parentNode));
7590		}
7591		return false;
7592	};
7593
7594	var doc = document.documentElement;
7595
7596	var transform_prop = window.Modernizr.prefixed('transform'),
7597		transition_prop = window.Modernizr.prefixed('transition'),
7598		transition_end = (function () {
7599			var props = {
7600				'WebkitTransition': 'webkitTransitionEnd',
7601				'MozTransition': 'transitionend',
7602				'OTransition': 'oTransitionEnd otransitionend',
7603				'msTransition': 'MSTransitionEnd',
7604				'transition': 'transitionend'
7605			};
7606			return props.hasOwnProperty(transition_prop) ? props[transition_prop] : false;
7607		})();
7608
7609	var inner = $("#inner-wrap")[0];
7610	var nav_open = false;
7611	var nav_class = 'js-navopen';
7612
7613	var closeNavEnd = function (e) {
7614		if (e && e.target === inner) {
7615			document.removeEventListener(transition_end, closeNavEnd, false);
7616		}
7617		nav_open = false;
7618	};
7619
7620	var closeNav = function () {
7621		if (nav_open) {
7622			// close navigation after transition or immediately
7623			var duration = (transition_end && transition_prop) ? parseFloat(window.getComputedStyle(inner, '')[transition_prop + 'Duration']) : 0;
7624			if (duration > 0) {
7625				document.addEventListener(transition_end, closeNavEnd, false);
7626			} else {
7627				closeNavEnd(null);
7628			}
7629		}
7630		removeClass(doc, nav_class);
7631		$('ol#mainNavMenu').find('li.rwd-close').remove();
7632		$('ol#mainNavMenu').attr('aria-hidden', 'true');
7633		nav_open = false;
7634	};
7635
7636	var openNav = function () {
7637		if (nav_open) {
7638			return;
7639		}
7640		addClass(doc, nav_class);
7641		$('ol#mainNavMenu').attr('aria-hidden', 'false');
7642		var $firstItem = $('ol#mainNavMenu').find('li > a').first();
7643		if (!$firstItem.hasClass('backMenuLink') && !$firstItem.hasClass('closeMenuLink')) {
7644			var $close = $('<li class="rwd-close"><a href="#" style="z-index:2;" class="navMenuItem closeMenuLink" aria-haspopup="false" role="menuitem">Close Menu</a></li>');
7645			$('#mainNavMenu').prepend($close);
7646			$firstItem = $('ol#mainNavMenu').find('li > a').first();
7647			$firstItem.bind('click', function (e) {
7648				e.preventDefault();
7649				closeNav();
7650			});
7651		}
7652		$firstItem.focus();
7653		nav_open = true;
7654	};
7655
7656	var toggleNav = function (e) {
7657		if (nav_open && hasClass(doc, nav_class)) {
7658			closeNav();
7659		} else {
7660			openNav();
7661		}
7662		if (e) {
7663			e.preventDefault();
7664		}
7665	};
7666
7667	// open nav with main "nav" button
7668	document.getElementById('nav-open-btn').addEventListener('click', toggleNav, false);
7669
7670	/* close nav with main "close" button
7671	document.getElementById('nav-close-btn').addEventListener('click', toggleNav, false);
7672	*/
7673
7674	// close nav by touching the partial off-screen content
7675	document.addEventListener('click', function (e) {
7676			if (nav_open && !hasParent(e.target, 'mainNav') && !hasClass(e.target, 'nav-btn')) {
7677				e.preventDefault();
7678				closeNav();
7679			}
7680		},
7681		true);
7682};
7683
7684//Configure a menu. This function should be call only inside $(document).ready
7685MenuManager.prototype.setupMenu = function (menuID, menuContainerID, menuType, setupDraggable, urlToGetHiddenMenus) {
7686	var self = this; // Reference to current object
7687	self.setupDraggable = setupDraggable;
7688
7689	//Initialize menu manger after DOM elements are loaded
7690	self.init();
7691
7692	$('#' + menuID).data('menu', { type: menuType, level: 1, parentID: null });
7693
7694	//mouse over on menu items from first level
7695	$("li.topMenuItem", '#' + menuID).mouseover(function (e) {
7696		e.stopPropagation();
7697	});
7698
7699	//mouse enter on menu items from first level
7700	$("li.topMenuItem", '#' + menuID).mouseenter(function () {
7701		var $li = $(this);
7702		self.menuMouseOver($li);
7703		
7704		//return false; //do not bubble mouse over events on other nested li tags
7705	});
7706
7707
7708
7709	//mouse out on menu items from first level
7710	$("li.topMenuItem", '#' + menuID).mouseleave(function () {
7711		var $li = $(this);
7712		self.menuMouseOut($li);
7713	});
7714
7715	$.ajax({
7716		url: urlToGetHiddenMenus,
7717		type: 'get',
7718		async: true, //let the page continue loading/processing meanwhile submenus are loaded
7719		cache: false,
7720		dataType: 'html',
7721		success: function (response) {
7722			if (response.ErrorMessage)
7723				alert(response.ErrorMessage);
7724			else {
7725				//Append submenus into divListSubMenus and bind menuMouseOut function on mouseleave event for all <li>.
7726				//create temporary container.
7727				var tempContainerID = 'dummyDivTemp' + menuID;
7728				var $tempContainer = $('<div id="' + tempContainerID + '" style="display:block;"></div>').append(response);
7729
7730				//set up hasChildren class on top level items
7731				$('#' + menuID + ' li').each(function () {
7732					var $this = $(this);
7733					var id = $this.attr('id'); //.replace(/item|leftItem/i, '');
7734					if (id != null) {
7735						var $olSubMenu = $tempContainer.find('#Parent' + id).find('li').not(".addPage");
7736						if ($olSubMenu.length > 0) {
7737							var $targetElement = $this.children('a').length ? $this.children('a') : $this;
7738							$targetElement.attr('aria-haspopup', 'true');
7739							$targetElement.attr('aria-expanded', 'false');
7740							//for secondary menus, set up withChildren class on top level items
7741							if (menuType === SIDE_MENU && $this.data("displayMainItemSubMenuIndicators") == "True") {
7742								$this.children('a.secondaryNavItem').addClass('withChildren');
7743							}
7744						}
7745					}
7746				});
7747
7748				//This needs to be executed once to bind draggable to main and side menu's root elements.
7749				if (setupDraggable) {
7750					//init drag and drop for menu items
7751					$('#' + menuID).find("li").each(function () {
7752						//set as droppable all submenu items on main menu
7753						self.setupDroppableElement($(this), menuType);
7754					});
7755
7756					$('#' + menuID).find(".grippy").each(function () {
7757						//setup grip icons as draggable elements for main menu sub items.
7758						self.setupDraggableElement($(this), menuType, '#' + menuContainerID);
7759					});
7760				}
7761
7762				//move submenus to main submenus container.
7763				self.$divListSubMenus.append($tempContainer.children()/*$('#' + tempContainerID + ' ol')*/);
7764				$tempContainer.remove();
7765			}
7766		},
7767		error: function (xhr, textStatus, exception) {
7768			if (xhr.status != 0)
7769				alert("Error retrieving sub-menus for menuID '" + menuID + "' : " + xhr.statusText + "\ntextStatus: " + xhr.status);
7770		}
7771	});
7772};
7773
7774//Handles mouse over event on menu items
7775MenuManager.prototype.menuMouseOver = function ($li) {
7776	var self = this; // Reference to current object
7777	if (self.mobileMainNav || ($('.pageContent.cpGrid.dragging').length > 0) || ($('.pageContent.cpGrid.pinned').length > 0)) {
7778		return;
7779	}
7780	this.resetMouseOvers();
7781	$li.addClass('mouseover');
7782	$li.parentsUntil('#mainNavMenu').children('a').addClass('mouseover');
7783	clearTimeout(self.menuTimeoutID);
7784
7785	var $parent = $li.parent();
7786	var menuData = $parent.data('menu');
7787
7788	
7789	//bail when is currently dragging an item to a different type of menu only if there is not custom links on side menu
7790	if (!self.sideMenuHasCustomLinks && self.isMainMenuBeingDragged && menuData.type === SIDE_MENU)
7791		return;
7792	if (!self.sideMenuHasCustomLinks && self.isSideMenuBeingDragged && menuData.type === MAIN_MENU)
7793		return;
7794
7795	if ((menuData.type === MAIN_MENU && self.isMainMenuEditable && (self.isMainMenuBeingDragged || self.isSideMenuBeingDragged) && $li.hasClass('liDropabble') && !$li.hasClass('beingDragged'))
7796		|| (menuData.type === SIDE_MENU && self.isSideMenuEditable && (self.isMainMenuBeingDragged || self.isSideMenuBeingDragged) && $li.hasClass('liDropabble') && !$li.hasClass('beingDragged'))) {
7797		//set elements settings when element is over
7798		$li.addClass('hover');
7799	}
7800
7801	$('#mainNav').css('z-index', '10');
7802
7803	//hide if needed submenus from siblings
7804	if ($li.hasClass('topMenuItem')) {
7805		//for top level menu items hide all the submenus before displaying another level
7806		self.hideAllSubMenus(menuData.type, $li);
7807	} else {
7808		//for all other submenus which are naturally inside DOM elements
7809		$parent.children().each(function () {
7810			if ($(this) != $li)
7811				self.hideSubMenu($(this));
7812		});
7813	}
7814
7815	//When opening different type of menu, hide submenus from the other types menu
7816	if (menuData.type === MAIN_MENU) {
7817		self.hideAllSubMenus(SIDE_MENU);
7818	} else if (menuData.type === SIDE_MENU) {
7819		self.hideAllSubMenus(MAIN_MENU);
7820	}
7821
7822	// As the sub-menu is displayed, we let the screen reader know the menu has expanded.
7823	var $anchor = $li.find('a');
7824	if ($anchor.length && $anchor.attr('aria-haspopup') === 'true') {
7825		$anchor.attr('aria-expanded', 'true');
7826		self.toggleIndicator($anchor);
7827	}
7828	else if ($anchor.length && $anchor.attr('aria-haspopup') != 'true') {
7829		return;
7830	}
7831	
7832
7833	if (!$li.hasClass('beingDragged')) {
7834		var id = $li.attr('id'); //.replace(/item|leftItem/i, '');
7835		var pageID = $li.data('pageid');
7836		var displayMegaMenu = $li.data('displaymegamenu');
7837		var delay = $li.hasClass('topMenuItem') ? self.popupDelayTopMenu : self.popupDelaySideMenu;
7838
7839		//This is to pick the list with with the most sub menus and remove the rest. Prevents issue with not displaying all submenus when there is more than one of the same
7840		//submenu being rendered, since the first rendered sub menu will be used for all submenu duplicates even though it may not have all the submenus included.
7841		//https://civicplus.tpondemand.com/entity/22126
7842		var maxSubMenus = 0;
7843		var maxResult;
7844		if (self.$divListSubMenus.find('#Parent' + id).length > 1) {
7845			$(self.$divListSubMenus.find('#Parent' + id)).each(function () {
7846				if ($(this).children().length > maxSubMenus) {
7847					maxSubMenus = $(this).children().length;
7848					maxResult = this;
7849				}
7850				$(this).addClass('removal');
7851			});
7852		}
7853		$(maxResult).removeClass('removal');
7854		self.$divListSubMenus.remove(".removal");
7855		self.$divListSubMenus.children().append(maxResult);
7856
7857		var $olSubMenu = self.$divListSubMenus.find('#Parent' + id);
7858		$('.megaMenuContainer.hover').hide().removeClass('hover');
7859		if (displayMegaMenu == 'True') {
7860			if (menuData.type === MAIN_MENU) {
7861				//Hack to get the heights of the megaMenu elements correctly, in state of display none, incorrect height is being returned. Vishal
7862				var $megaMenuContainer = $('.mainNavMegaMenu.megaMenuContainer.pageID_' + pageID);
7863				$megaMenuContainer.css('visibility', 'hidden');
7864				$megaMenuContainer.css("overflow", "hidden");
7865				$megaMenuContainer.css("height", "0");
7866				$megaMenuContainer.css("padding", "0");
7867				$megaMenuContainer.show();
7868
7869
7870				//Apply menu animation's start state
7871				var applyAnimation = function ($megaMenuContainer, timeout) {
7872					if (typeof (Animations) === 'function') {
7873						var animations = new Animations();
7874						animations.applyAnimationClassToMegaMenuContainer($megaMenuContainer, timeout);
7875					}
7876				}
7877
7878				var timeout = delay ? delay : 0;
7879				self.menuTimeoutID = window.setTimeout(function () {
7880					updateMegaMenuAttributes($megaMenuContainer);
7881					fireMediaQueriesIfNeeded($megaMenuContainer);
7882					$megaMenuContainer.show();
7883					$megaMenuContainer.css("visibility", "");
7884					$megaMenuContainer.css("overflow", "");
7885					$megaMenuContainer.css("height", "");
7886					$megaMenuContainer.css("padding", "");
7887					applyAnimation($megaMenuContainer, timeout);
7888					if (!window.isRemoveSetHeights)
7889						SetHeights();
7890				}, timeout);
7891			}
7892			else {
7893				delay ? self.menuTimeoutID = setTimeout(function () {
7894					$('.secondaryNavMegaMenu.megaMenuContainer.pageID_' + pageID).show();
7895					if (!window.isRemoveSetHeights)
7896						SetHeights();
7897				}, delay) : $('.secondaryNavMegaMenu.megaMenuContainer.pageID_' + pageID).show();
7898			}
7899		}
7900
7901		//For side menu, there isnt a mega menu, so render regular sub menu irrespective of displayMegaMenu setting.
7902		if (displayMegaMenu != 'True' || menuData.type === SIDE_MENU) {
7903			if ($olSubMenu.length > 1) {
7904				//remove duplicates. they might have been added by different menu (main/side)
7905				$olSubMenu.slice(1).remove();
7906				$olSubMenu = self.$divListSubMenus.find('#Parent' + id);
7907				$olSubMenu.removeClass('takenIntoAccount');
7908			}
7909			if ($olSubMenu.length == 1) {
7910				$olSubMenu.removeClass('takenIntoAccount');
7911				$olSubMenu.data('menu', { type: menuData.type, level: menuData.level + 1, parentID: $parent.attr('id') });
7912				var allowedToShow = ($olSubMenu.data('menu').type === MAIN_MENU) ? $olSubMenu.data('menu').level <= self.mainMenuMaxSubMenuLevels : $olSubMenu.data('menu').level <= self.sideMenuMaxSubMenuLevels;
7913				if (allowedToShow) {
7914					delay ? self.menuTimeoutID = setTimeout(function () { self.showSubMenu($li, $olSubMenu); }, delay) : self.showSubMenu($li, $olSubMenu);
7915				}
7916			}
7917		}
7918
7919		if (displayMegaMenu == 'True' && !window.isRemoveSetHeights) {
7920			SetHeights();
7921		}
7922	}
7923};
7924
7925//Display submenu items
7926MenuManager.prototype.showSubMenu = function ($li, $olSubMenu) {
7927	var self = this; // Reference to current object
7928	var menuType = $olSubMenu.data('menu').type;
7929	var animations = null;
7930
7931	//Apply menu animation's start state
7932	if (typeof (Animations) === 'function') {
7933		animations = new Animations();
7934		animations.applyInitial($olSubMenu, menuType);
7935	}
7936
7937	//Bind mouseenter for second level submenus
7938	//Also set the tab index for each <li>
7939	$olSubMenu.children().each(function () {
7940		if (self.type != "hidden") {
7941			var $input = $(this);
7942		}
7943		//mouse over on menu items from second and subsequent levels.
7944		$(this).bind("mouseenter.menu", function () {
7945			var $li = $(this);
7946			self.menuMouseOver($li);
7947			return false; //do not bubble mouse over events on other nested li tags
7948		});
7949	});
7950
7951	//Bind mouseleave for second level submenus
7952	$olSubMenu.children().each(function () {
7953		//mouse over on menu items from second and subsequent levels.
7954		$(this).bind("mouseleave.menu", function () {
7955			var $li = $(this);
7956			if (!$olSubMenu.is(":hover")) {
7957				self.menuMouseOut($li);
7958			}
7959		});
7960	});
7961
7962	var bouncing = self.bouncing &&
7963		((menuType === MAIN_MENU && $olSubMenu.data('menu').level > 2)
7964			|| (menuType === SIDE_MENU));
7965
7966	var $parentOl = $li.parent();
7967	var parentLeftLi = $li.offset().left;
7968
7969	self.moveSubMenuInDOM($olSubMenu, menuType);
7970
7971	if (bouncing) {
7972		//logic to bounce submenu to be opened if needed.
7973		var subMenuWidth = $olSubMenu.outerWidth(); //get width from submenu which is hidden (required to add extra styles on divListSubMenus)
7974
7975		var isOpeningToRight = !$parentOl.hasClass('flipLeft');
7976		if (isOpeningToRight) {
7977			var winWidth = $(window).width();
7978			var parentWidthLi = $parentOl.outerWidth();
7979
7980			if ((winWidth - parentLeftLi - parentWidthLi) <= (subMenuWidth + 3)) {
7981				$olSubMenu.addClass('flipLeft');
7982			}
7983		} else {
7984			if ((parentLeftLi) <= (subMenuWidth + 3)) {
7985				$olSubMenu.addClass('flipRight');
7986			} else {
7987				$olSubMenu.addClass('flipLeft');
7988			}
7989		}
7990	}
7991	self.positionSubMenuInDOM($olSubMenu, $li, menuType);
7992
7993	if (self.setupDraggable) {
7994		//init drag and drop for menu items
7995		$olSubMenu.find("li").each(function () {
7996			//set as droppable all submenu items on main menu
7997			self.setupDroppableElement($(this), menuType);
7998		});
7999
8000		$olSubMenu.find(".grippy").each(function () {
8001			//setup grip icons as draggable elements for main menu sub items.
8002			self.setupDraggableElement($(this), menuType, menuType == MAIN_MENU ? '#mainNav' : '#secondaryNav');
8003		});
8004	}
8005
8006	//If Animation manager toggled on, implement the menu animations
8007	if (animations != null) {
8008		animations.applyAnimationClassToNavContainers($olSubMenu, menuType);
8009	}
8010};
8011
8012//Handles mouse out event on menu items
8013MenuManager.prototype.menuMouseOut = function ($li) {
8014	var self = this; // Reference to current object
8015
8016	if (self.mobileMainNav) return;
8017	var parentMenuID = $li.parents('ol').attr('id') || '';
8018	var menuType = $li.attr('id') != null ? ($li.attr('id').match(/MainItem/) != null ? MAIN_MENU : SIDE_MENU) : (($li.hasClass('secondaryNavItem') || parentMenuID.match(/SideItem/) != null) ? SIDE_MENU : MAIN_MENU);
8019	//log("popdownDelaySideMenu" + popdownDelaySideMenu);
8020	var delay = $li.hasClass('topMenuItem') ? self.popdownDelayTopMenu : self.popdownDelaySideMenu;
8021	if (self.isMainMenuBeingDragged || self.isSideMenuBeingDragged) {
8022		//reset elements settings
8023		$li.removeClass('hover');
8024	}
8025
8026	$('#mainNav').css('z-index', '');
8027
8028	clearTimeout(self.menuTimeoutID);
8029	self.menuTimeoutID = setTimeout(function () {
8030		/*if ($li.parent().data('menu').type == MAIN_MENU)
8031		self.hideAllSubMenus(MAIN_MENU); //workaround related with containerSubMenus
8032		else*/
8033		$('#bodyWrapper').animate({ 'padding-bottom': 0 }, 'fast');
8034		$('#bodyWrapper').data('maxPaddingBottom', '0');
8035		$('.takenIntoAccount').removeClass('takenIntoAccount');
8036		if (!$li.hasClass('topMenuItem'))
8037			self.hideAllSubMenus(menuType, $li);
8038		else
8039			self.hideSubMenu($li);
8040	}, delay);
8041};
8042
8043MenuManager.prototype.hideAllSubMenus = function (menuType, $currentLi) {
8044	var self = this; // Reference to current object
8045	switch (menuType) {
8046		case SIDE_MENU: //hide sub menus for left menu
8047			$("li.topMenuItem", ".secondaryNav ol.rootNavMenu").each(function () {
8048				if ($currentLi && $(this).attr('id') === $currentLi.attr('id'))
8049					return true; //continue. don't hide current top menu item opened if provided
8050				self.hideSubMenu($(this));
8051			});
8052			break;
8053		case MAIN_MENU: //hide sub menus for main menu
8054			/*var openMenuID = self.$containerSubMenus.find('ol:first').attr('id');
8055			if ($currentLi && openMenuID === ('Parent' + $currentLi.attr('id')))
8056			return true; //continue. don't hide current top menu item opened if provided
8057			self.hideSubMenu(self.$containerSubMenus);*/
8058			$("li.topMenuItem", "#mainNavMenu").each(function () {
8059				if ($currentLi && $(this).attr('id') === $currentLi.attr('id'))
8060					return true; //continue. don't hide current top menu item opened if provided
8061				self.hideSubMenu($(this));
8062			});
8063			break;
8064		default: //hide submenus for all type of menus
8065			//self.hideSubMenu(self.$containerSubMenus);
8066			$("li.topMenuItem", "#mainNavMenu").each(function () {
8067				self.hideSubMenu($(this));
8068			});
8069			$("li.topMenuItem", "#sideNavMenu").each(function () {
8070				self.hideSubMenu($(this));
8071			});
8072			break;
8073	}
8074};
8075
8076MenuManager.prototype.isSubMenuTrigger = function ($elem) {
8077	return $elem.closest(".rwd-menu").length === 0 && $elem.attr("aria-haspopup") === "true";
8078};
8079
8080MenuManager.prototype.toggleSubMenu = function ($elem) {
8081	var expanded = $elem.attr("aria-expanded") === "true";
8082	var $li = $elem.closest("li");
8083	if (expanded) {
8084		menuManager.hideSubMenu($li);
8085	} else {
8086		menuManager.menuMouseOver($li);
8087	}
8088};
8089
8090MenuManager.prototype.getFirstSubmenuItem = function ($elem) {
8091	var $parentLi = $elem.parent('li');
8092	var pageId = $parentLi.data('pageid');
8093	var displayMegaMenu = $parentLi.data('displaymegamenu');
8094	
8095	if (displayMegaMenu === 'True') {
8096		var $megaMenuContainer = $('.mainNavMegaMenu.megaMenuContainer.pageID_' + pageId);
8097		if ($megaMenuContainer.length > 0) {
8098			return $megaMenuContainer.find('a[role="menuitem"]').first();
8099		}
8100	}
8101	
8102	var firstAnchorId = "pagelink" + pageId;
8103	return $('#' + firstAnchorId);
8104};
8105
8106MenuManager.prototype.setFocusToFirstSubmenuitem = function ($elem) {
8107	var $firstAnchor = menuManager.getFirstSubmenuItem($elem);
8108	if ($firstAnchor.length) {
8109		$firstAnchor[0].focus();
8110		return true;
8111	}
8112	return false;
8113};
8114
8115MenuManager.prototype.setFocusToLastTopLevelItem = function () {
8116	// Close any open submenus when tabbing out, but do not move focus.
8117	// Let the browser preserve the natural tab order so Shift+Tab re-enters
8118	// the menubar on the first top-level item rather than the last focused item.
8119	if (accessibleMenuToggleEnabled) {
8120		menuManager.hideAllSubMenus(MAIN_MENU);
8121	}
8122};
8123
8124MenuManager.prototype.getLastSubmenuItem = function ($elem) {
8125	var $parentLi = $elem.parent('li');
8126	var pageId = $parentLi.data('pageid');
8127	var displayMegaMenu = $parentLi.data('displaymegamenu');
8128	
8129	if (displayMegaMenu === 'True' || displayMegaMenu === true) {
8130		var $megaMenuContainer = $('.mainNavMegaMenu.megaMenuContainer.pageID_' + pageId);
8131		if ($megaMenuContainer.length > 0) {
8132			return $megaMenuContainer.find('a[role="menuitem"]').last();
8133		}
8134	}
8135	
8136	var parentOlId = $parentLi.attr('id');
8137	var $submenu = $('#Parent' + parentOlId);
8138	if ($submenu.length > 0) {
8139		return $submenu.find('a[role="menuitem"]').last();
8140	}
8141	return $();
8142};
8143
8144MenuManager.prototype.setFocusToLastSubmenuitem = function ($elem) {
8145	var $lastAnchor = menuManager.getLastSubmenuItem($elem);
8146	if ($lastAnchor.length) {
8147		$lastAnchor[0].focus();
8148		return true;
8149	}
8150	return false;
8151};
8152
8153MenuManager.prototype.toggleIndicator = function ($anchor) {
8154	if (window.FeatureToggles.isActive("CMS.Pages.AccessibleMainMenuWithIndicators")) {
8155		if ($anchor.attr('aria-expanded') === 'true') {
8156			if ($anchor.hasClass("arrowDown"))
8157				$anchor.removeClass("arrowDown").addClass("arrowUp");
8158			else if ($anchor.hasClass("arrowRight"))
8159				$anchor.removeClass("arrowRight").addClass("arrowDownSubMenu");
8160		} else {
8161			if ($anchor.hasClass("arrowUp"))
8162				$anchor.removeClass("arrowUp").addClass("arrowDown");
8163			else if ($anchor.hasClass("arrowDownSubMenu"))
8164				$anchor.removeClass("arrowDownSubMenu").addClass("arrowRight");
8165		}
8166	}
8167}
8168
8169MenuManager.prototype.hideSubMenu = function ($li) {
8170	var self = this; // Reference to current object
8171
8172	// As the sub-menu is closed, we let the screen reader know that the menu is no longer expanded.
8173	var $anchor = $li.find('a');
8174	if ($anchor.length && $anchor.attr('aria-haspopup') === 'true') {
8175		$anchor.attr('aria-expanded', 'false');
8176		self.toggleIndicator($anchor);
8177	}
8178
8179	var displayMegaMenu = $li.data('displaymegamenu');
8180	var mainMenu = $li.parents('nav').hasClass('mainNav') | $li.parents('ol').hasClass('mainSubMenu');
8181	//When a menu item is set to display as mega menu, we still display regular sub menu for secondary nav, since it doesnt have a megamenu. So while hiding, hide the regular submenu for side navigation.
8182	if (displayMegaMenu != 'True' || !mainMenu) {
8183		if ($('#mainNavMenu').find('.navMenu').length == 0) {
8184			$('#mainNavMenu li a.mouseover').removeClass('mouseover');
8185		}
8186		var id = $li.attr('id');
8187		var $olSubMenu = $('#Parent' + id);
8188		if ($olSubMenu.length == 1) {
8189			//moves sub menu to hidden div
8190			$olSubMenu.appendTo(self.$divListSubMenus);
8191			//reset data of the menu
8192			$olSubMenu.removeData('menu');
8193			if (self.bouncing) {
8194				//remove bouncing classes
8195				$olSubMenu.removeClass('flipLeft flipRight');
8196			}
8197			$olSubMenu.css({ position: '', top: '', left: '', zIndex: '' });
8198			//moves recursively its children if needed
8199			$olSubMenu.children().each(function () {
8200				self.hideSubMenu($(this));
8201				$(this).unbind("mouseenter.menu");
8202			});
8203
8204			//Remove animation trigger class
8205			$olSubMenu.removeClass('animation-triggered');
8206		}
8207	} else {
8208		var pageID = $li.data('pageid');
8209		var megaMenuContainer = $('.mainNavMegaMenu.megaMenuContainer.pageID_' + pageID);
8210		if (!megaMenuContainer.hasClass('hover') && $('.megaMenuContainer .handle.pin.pinned').length === 0) {
8211			//$('#megaMenu').hide();
8212			megaMenuContainer.hide();
8213			$('#mainNav').css('z-index', '');
8214			$('.megaMenuContainer').css("display", "none");
8215			$('.megaMenuContainer').removeClass('animation-triggered');
8216		}
8217		if (!$('.secondaryNavMegaMenu.megaMenuContainer.pageID_' + pageID).hasClass('hover')) {
8218			$('.secondaryNavMegaMenu.megaMenuContainer.pageID_' + pageID).hide();
8219		}
8220	}
8221};
8222
8223//Supports legacy code to set delays when opening/close submenus
8224MenuManager.prototype.setMOMMode = function (mommode, menuType) {
8225	//support legacy code
8226	if (menuType === MAIN_MENU) {
8227		switch (mommode) {
8228			case 0:
8229				self.popdownDelayTopMenu = 3;
8230				self.popupDelayTopMenu = false;
8231				self.mainMenuMaxSubMenuLevels = 0;
8232				break;
8233			case 2:
8234				self.popdownDelayTopMenu = 500;
8235				self.popupDelayTopMenu = 500;
8236				break;
8237			case 3:
8238				self.popdownDelayTopMenu = 500;
8239				self.popupDelayTopMenu = false;
8240				break;
8241		}
8242	} else if (menuType === SIDE_MENU) {
8243		switch (mommode) {
8244			case 0:
8245				self.popdownDelaySideMenu = 3;
8246				self.popupDelaySideMenu = false;
8247				self.sideMenuMaxSubMenuLevels = 0;
8248				break;
8249			case 2:
8250				self.popdownDelaySideMenu = 500;
8251				self.popupDelaySideMenu = 500;
8252				break;
8253			case 3:
8254				self.popdownDelaySideMenu = 500;
8255				self.popupDelaySideMenu = false;
8256				break;
8257		}
8258	}
8259};
8260
8261MenuManager.prototype.adjustMainItemsWidth = function (menuSelector) {
8262	this.isAdjustingMainMenuItemsWidth = true;
8263	return adjustMainItemsWidth(menuSelector);
8264};
8265
8266MenuManager.prototype.isMegaMenuItem = function ($elem) {
8267	var $parent = $elem.parent('li');
8268	if ($parent != null && $parent.data('displaymegamenu') == 'True') {
8269		return true;
8270	}
8271
8272	var $megaMenuContainer = $elem.closest('.mainNavMegaMenu');
8273	if ($megaMenuContainer.length > 0) {
8274		return true;
8275	}
8276
8277	return false;
8278};
8279
8280MenuManager.prototype.isFirstSubmenuItem = function ($elem) {
8281	var $submenu = $elem.closest('.mainSubMenu, .mainNavMegaMenu');
8282	if ($submenu.length === 0) return false;
8283	
8284	var $allItems = $submenu.find('a[role="menuitem"]');
8285	return $allItems.index($elem) === 0;
8286};
8287
8288MenuManager.prototype.isLastSubmenuItem = function ($elem) {
8289	var $submenu = $elem.closest('.mainSubMenu, .mainNavMegaMenu');
8290	if ($submenu.length === 0) return false;
8291	
8292	var $allItems = $submenu.find('a[role="menuitem"]');
8293	return $allItems.index($elem) === $allItems.length - 1;
8294};
8295
8296MenuManager.prototype.focusPrevSubmenuItem = function ($elem) {
8297	var $prev = $elem.parent('li').prev('li').find('a:first');
8298	if ($prev.length > 0) {
8299		$prev.focus();
8300	}
8301};
8302
8303MenuManager.prototype.focusNextSubmenuItem = function ($elem) {
8304	var $next = $elem.parent('li').next('li').find('a:first');
8305	if ($next.length > 0) {
8306		$next.focus();
8307	}
8308};
8309
8310MenuManager.prototype.findTopLevelParentId = function ($elem) {
8311	// For mega menus
8312	var $megaMenu = $elem.closest('.mainNavMegaMenu');
8313	if ($megaMenu.length > 0) {
8314		var pageId = $megaMenu.attr('id').replace('mainNavMegaMenu', '');
8315		return 'MainItem' + pageId;
8316	}
8317
8318	// For regular submenus - find the submenu that contains the current element
8319	var $submenu = $elem.closest('ol[id^="ParentMainItem"]');
8320	if ($submenu.length === 0) {
8321		return null;
8322	}
8323
8324	// Get the ID of the menu item that OWNS this submenu
8325	var ownerId = $submenu.attr('id').replace('ParentMainItem', ''); // e.g., "27" from "ParentMainItem27"
8326
8327	// Recursive helper to find the top-level parent
8328	var findTopLevel = function (id) {
8329		var $item = document.querySelector('#MainItem' + id);
8330		if (!$item) return null;
8331
8332		var $parentSubmenu = $item.closest("ol[id^='ParentMainItem']");
8333
8334		if (!$parentSubmenu) {
8335			// This item is not inside any submenu, so it's top-level
8336			return 'MainItem' + id;
8337		}
8338
8339		// Get the parent's owner ID and recurse
8340		var parentOwnerId = $parentSubmenu.id.match(/\d+$/)?.[0];
8341		return parentOwnerId ? findTopLevel(parentOwnerId) : 'MainItem' + id;
8342	};
8343
8344	return findTopLevel(ownerId);
8345};
8346
8347MenuManager.prototype.getSubmenuParentId = function ($elem) {
8348	var $submenu = $elem.closest('.mainSubMenu');
8349	if ($submenu.length > 0) {
8350		// For regular submenus, extract parent ID from submenu's id (e.g., "ParentMainItem123")
8351		return $submenu.attr('id').replace('Parent', '');
8352	}
8353	
8354	var $megaMenu = $elem.closest('.mainNavMegaMenu');
8355	if ($megaMenu.length > 0) {
8356		// For mega menus, extract from mega menu container id (e.g., "mainNavMegaMenu123")
8357		return 'MainItem' + $megaMenu.attr('id').replace('mainNavMegaMenu', '');
8358	}
8359	
8360	return null;
8361};
8362
8363MenuManager.prototype.handleUpKeyOnTopLevelItem = function ($elem) {
8364	if (!accessibleMenuToggleEnabled || !this.isSubMenuTrigger($elem)) {
8365		return false;
8366	}
8367	
8368	var isExpanded = $elem.attr('aria-expanded') === 'true';
8369	if (!isExpanded) {
8370		this.toggleSubMenu($elem);
8371	}
8372	
8373	var self = this;
8374	setTimeout(function () {
8375		self.setFocusToLastSubmenuitem($elem);
8376	}, isExpanded ? 0 : 300);
8377	
8378	return true;
8379};
8380
8381MenuManager.prototype.handleDownKeyOnTopLevelItem = function ($elem) {
8382	if (!accessibleMenuToggleEnabled || !this.isSubMenuTrigger($elem)) {
8383		return false;
8384	}
8385	
8386	var isExpanded = $elem.attr('aria-expanded') === 'true';
8387	if (!isExpanded) {
8388		this.toggleSubMenu($elem);
8389	}
8390	
8391	var self = this;
8392	setTimeout(function () {
8393		self.setFocusToFirstSubmenuitem($elem);
8394	}, isExpanded ? 0 : 300);
8395	
8396	return true;
8397};
8398
8399MenuManager.prototype.handleUpKeyInSubmenu = function ($elem, options) {
8400	options = options || {};
8401
8402	// Existing behavior for non-toggle mode	
8403	if (!accessibleMenuToggleEnabled) {
8404		if (this.isFirstSubmenuItem($elem) && options.onFirstItem) {
8405			options.onFirstItem($elem);
8406		} else {
8407			this.focusPrevSubmenuItem($elem);
8408		}
8409		return;
8410	}
8411
8412	// New behavior with toggle enabled
8413	if (this.isFirstSubmenuItem($elem)) {
8414		var parentId = this.getSubmenuParentId($elem);
8415		if (parentId) {
8416			this.setFocusToLastSubmenuitem($('#' + parentId).find('a:first'));
8417		}
8418	} else {
8419		this.focusPrevSubmenuItem($elem);
8420	}
8421};
8422
8423MenuManager.prototype.handleDownKeyInSubmenu = function ($elem) {
8424	// Existing behavior for non-toggle mode	
8425	if (!accessibleMenuToggleEnabled) {
8426		this.focusNextSubmenuItem($elem);
8427		return;
8428	}
8429
8430	// New behavior with toggle enabled
8431	if (this.isLastSubmenuItem($elem)) {
8432		var parentId = this.getSubmenuParentId($elem);
8433		if (parentId) {
8434			this.setFocusToFirstSubmenuitem($('#' + parentId).find('a:first'));
8435		}
8436	} else {
8437		this.focusNextSubmenuItem($elem);
8438	}
8439};
8440
8441MenuManager.prototype.getAdjacentTopLevelItem = function ($currentLi, direction) {
8442	var $targetLi = direction === 'prev' ? $currentLi.prev('li.topMenuItem') : $currentLi.next('li.topMenuItem');
8443
8444	if ($targetLi.length === 0) {
8445		var $siblings = $currentLi.parent().children('li.topMenuItem');
8446		$targetLi = direction === 'prev' ? $siblings.last() : $siblings.first();
8447	}
8448
8449	return $targetLi;
8450};
8451
8452MenuManager.prototype.handleLeftKeyOnTopLevelItem = function ($anchor, openSubmenu) {
8453	var $currentLi = $anchor.parent('li.topMenuItem');
8454	var $prevLi = this.getAdjacentTopLevelItem($currentLi, 'prev');
8455	var $targetAnchor = $prevLi.find('a:first');
8456	$targetAnchor.focus();
8457
8458	if (openSubmenu && this.isSubMenuTrigger($targetAnchor)) {
8459		clearTimeout(this.menuTimeoutID);
8460		this.openSubmenuImmediately($prevLi);
8461	}
8462};
8463
8464MenuManager.prototype.handleRightKeyOnTopLevelItem = function ($anchor, openSubmenu) {
8465	var $currentLi = $anchor.parent('li.topMenuItem');
8466	var $nextLi = this.getAdjacentTopLevelItem($currentLi, 'next');
8467	var $targetAnchor = $nextLi.find('a:first');
8468	$targetAnchor.focus();
8469
8470	if (openSubmenu && this.isSubMenuTrigger($targetAnchor)) {
8471		clearTimeout(this.menuTimeoutID);
8472		this.openSubmenuImmediately($nextLi);
8473	}
8474};
8475
8476MenuManager.prototype.handleLeftKeyInSubmenu = function ($elem, shouldOpenSubmenu) {
8477	var self = this;
8478	// Check if current item has a parent submenu item
8479	var $currentSubmenu = $elem.closest('ol.mainSubMenu');
8480	if ($currentSubmenu.length === 0) {
8481		return;
8482	}
8483
8484	var parentItemId = $currentSubmenu.attr('id').replace('Parent', '');
8485	var $parentItem = $('#' + parentItemId);
8486	var $parentAnchor = $parentItem.find('a:first');
8487
8488	// Check if the parent item is a submenu item
8489	var $parentSubmenu = $parentItem.closest('ol.mainSubMenu');
8490	var parentIsSubmenuItem = $parentSubmenu.length > 0;
8491
8492	if (parentIsSubmenuItem) {
8493		this.hideSubMenu($parentItem);
8494		$parentAnchor.focus();
8495		return;
8496	}
8497
8498	var parentId = this.getSubmenuParentId($elem);
8499	if (!parentId)
8500		return;
8501
8502	var $parentLi = $('#' + parentId);
8503
8504	this.hideSubMenu($parentLi);
8505
8506	var $prevLi = $parentLi.prev('li.topMenuItem');
8507	if ($prevLi.length === 0) {
8508		$prevLi = $parentLi.parent().children('li.topMenuItem').last();
8509	}
8510
8511	var $prevAnchor = $prevLi.find('a:first');
8512	$prevAnchor.focus();
8513
8514	if (shouldOpenSubmenu && this.isSubMenuTrigger($prevAnchor)) {
8515		this.openSubmenuImmediately($prevLi);
8516		var isExpanded = $prevAnchor.attr('aria-expanded') === 'true';
8517
8518		if (isExpanded) {
8519			setTimeout(function () {
8520				self.setFocusToFirstSubmenuitem($prevAnchor);
8521			}, 300);
8522		}
8523	}
8524};
8525
8526MenuManager.prototype.handleRightKeyInSubmenu = function ($elem, shouldOpenSubmenu) {
8527	var self = this;
8528
8529	// Check if current item has child submenu
8530	if (this.isSubMenuTrigger($elem)) {
8531		var isExpanded = $elem.attr('aria-expanded') === 'true';
8532		if (!isExpanded) {
8533			var $parentLi = $elem.parent('li');
8534			this.openSubmenuImmediately($parentLi);
8535			setTimeout(function () {
8536				self.setFocusToFirstSubmenuitem($elem);
8537			}, 300);
8538			return;
8539		}
8540	}
8541
8542	var topLevelParentId = this.findTopLevelParentId($elem);
8543	if (!topLevelParentId) {
8544		return;
8545	}
8546
8547	this.hideAllSubMenus(MAIN_MENU);
8548
8549	var $topLevelParent = $('#' + topLevelParentId);
8550	var $nextLi = $topLevelParent.next('li.topMenuItem');
8551	if ($nextLi.length === 0) {
8552		$nextLi = $('#mainNavMenu > li.topMenuItem').first();
8553	}
8554
8555	var $nextAnchor = $nextLi.children('a:first');
8556	if ($nextAnchor.length > 0) {
8557		$nextAnchor.focus();
8558		if (shouldOpenSubmenu) {
8559			// Check if target is a mega menu OR regular submenu
8560			var isMegaMenu = $nextLi.attr('data-displaymegamenu') === 'True';
8561			var hasSubmenu = this.isSubMenuTrigger($nextAnchor);
8562
8563			if (isMegaMenu || hasSubmenu) {
8564				self.menuMouseOver($nextLi);
8565
8566				setTimeout(function () {
8567					self.setFocusToFirstSubmenuitem($nextAnchor);
8568				}, 300);
8569			}
8570		}
8571	}
8572};
8573
8574MenuManager.prototype.openSubmenuImmediately = function ($li) {
8575	var self = this;
8576	var savedDelay = self.popupDelayTopMenu;
8577	self.popupDelayTopMenu = 0; // Disable delay temporarily
8578	self.menuMouseOver($li);
8579	self.popupDelayTopMenu = savedDelay; // Restore delay
8580};
8581
8582MenuManager.prototype.shouldOpenSubmenuOnNavigation = function ($elem) {
8583	// Find if current element is in a submenu
8584	var $currentSubmenu = $elem.closest('ol.mainSubMenu');
8585	if ($currentSubmenu.length === 0) {
8586		return false;
8587	}
8588
8589	// Get the parent menu item of this submenu
8590	var parentItemId = $currentSubmenu.attr('id').replace('Parent', '');
8591	var $parentItem = $('#' + parentItemId);
8592
8593	// Check if parent is a top-level item or nested submenu item
8594	var $parentSubmenu = $parentItem.closest('ol.mainSubMenu');
8595
8596	if ($parentSubmenu.length === 0) {
8597		// Parent is top-level,so we should open next submenu
8598		return true;
8599	} else {
8600		// Parent is in a nested submenu, check its aria-expanded
8601		var $parentAnchor = $parentItem.find('a:first');
8602		return $parentAnchor.attr('aria-expanded') === 'true';
8603	}
8604};
8605
8606MenuManager.prototype.isTopLevelMenuItem = function ($elem) {
8607	return $elem.hasClass('navMainItem') || $elem.closest('li').hasClass('topMenuItem');
8608};
8609
8610MenuManager.prototype.setActiveTopLevelItem = function ($elem) {
8611	if (!accessibleMenuToggleEnabled || !this.isTopLevelMenuItem($elem)) {
8612		return;
8613	}
8614
8615	// Roving tabindex pattern
8616	let $topLevelAnchor = $elem.hasClass('navMainItem') ? $elem : $elem.closest('li.topMenuItem').find('a.navMainItem').first();
8617	if ($topLevelAnchor.length === 0) {
8618		return;
8619	}
8620	
8621	$('#mainNavMenu > li.topMenuItem > a.navMainItem').attr('tabindex', '-1');
8622	$topLevelAnchor.attr('tabindex', '0');
8623};
8624
8625MenuManager.prototype.handleUpKeyOnAnyTopLevelItem = function ($elem) {
8626	if (this.isMegaMenuItem($elem)) {
8627		return false;
8628	}
8629
8630	return this.handleUpKeyOnTopLevelItem($elem);
8631};
8632
8633MenuManager.prototype.handleLeftKeyOnAnyTopLevelItem = function ($elem) {
8634	if (accessibleMenuToggleEnabled) {
8635		var shouldOpenSubmenu = $elem.attr('aria-expanded') === 'true';
8636		this.handleLeftKeyOnTopLevelItem($elem, shouldOpenSubmenu);
8637		return;
8638	}
8639
8640	this.navigateToSiblingTopLevelItem($elem, 'prev');
8641};
8642
8643MenuManager.prototype.handleRightKeyOnAnyTopLevelItem = function ($elem) {
8644	if (accessibleMenuToggleEnabled) {
8645		var shouldOpenSubmenu = $elem.attr('aria-expanded') === 'true';
8646		this.handleRightKeyOnTopLevelItem($elem, shouldOpenSubmenu);
8647		return;
8648	}
8649
8650	this.navigateToSiblingTopLevelItem($elem, 'next');
8651};
8652
8653MenuManager.prototype.navigateToSiblingTopLevelItem = function ($elem, direction) {
8654	var $currentLi = $elem.parent('li.topMenuItem');
8655	var $targetLi = this.getAdjacentTopLevelItem($currentLi, direction);
8656	$targetLi.find('a:first').focus();
8657};
8658
8659function adjustMainItemsWidth(menuSelector) {
8660	var widths = [];
8661	var $items = [];
8662	$(menuSelector).data('autowidth', true).find(".topMenuItem").each(function () {
8663		widths.push($(this).outerWidth());
8664		$items.push($(this));
8665	});
8666	if (widths.length > 0) {
8667		var totalWidth = 0;
8668		var i;
8669		for (i = 0; i < widths.length; i++) {
8670			totalWidth += widths[i];
8671		}
8672		var menuWidth = $(menuSelector).outerWidth();
8673		var availableWidth = menuWidth - totalWidth;
8674		var paddingPerItem = availableWidth / $items.length;
8675		for (i = 0; i < $items.length; i++) {
8676			var width = (100 * (widths[i] + paddingPerItem) / menuWidth);
8677			//This is to account for the anomoly of the last menu item wrapping for one client (Anoka County) only in Mac Safari
8678			//A site-specific solution was sought but none found that was acceptable
8679			if (navigator.userAgent.indexOf("Safari") > -1 && navigator.userAgent.indexOf('Chrome') == -1 && i == $items.length - 1) {
8680				width = width - 1;
8681			}
8682			$items[i].outerWidth(width + "%");
8683		}
8684	}
8685}
8686
8687MenuManager.prototype.resetMainItemsWidth = function (menuSelector) {
8688	$(menuSelector).find(".topMenuItem").each(function () {
8689		$(this).css("width", "auto");
8690	});
8691};
8692
8693function log(text) {
8694	console.log(text);
8695}
8696
8697/**** End-Functions to handle Main/Left Menu on Front-end. *****/
8698
8699/***** Drag and Drop functions to handle main/side menus  ********/
8700
8701//Handles when an element was dropped
8702MenuManager.prototype.dragHandler = function ($element, dragInfo) {
8703	var self = this; // Reference to current object
8704
8705	//var miLeave = 0;
8706	var menuItemLeave = function ($menuItemOver) {
8707		$menuItemOver.removeClass('hover');
8708		//miLeave++;
8709		//log("Leave event " + (miLeave) + ", liID=" + $menuItemOver.attr('id') + ", class=" + $menuItemOver.attr('class'));
8710		//$('#log3').val("Leave event " + (miLeave) + ", liID=" + $menuItemOver.attr('id') + ", class=" + $menuItemOver.attr('class'));
8711	};
8712
8713	if ($element.length != 0 && !$element.hasClass('thingToDrag')) { //workaround to avoid executing drag handler when mouse pointer is over drag helper
8714		//resetElementOver();
8715		//dragInfo.currentElementOver = { $element: null, $li: null, isAddPage: null, $ol: null };
8716		dragInfo.resetCurrentElementOver();
8717		// This element will hold info to keep track of the current element that the mouse pointer is over.
8718		dragInfo.currentElementOver.$element = $element;
8719		//$('#log1').val('element  ID:' + $element.attr('id') + ', class=' + $element.attr('class') + ", tag=" + $element.get(0).nodeName + "html=" + $element.html());
8720
8721		if ($element.hasClass('inside')) {
8722			//when mouse is over any DOM element inside an LI MenuItem
8723			var $li = $element.closest('li');
8724
8725			dragInfo.currentElementOver.$li = $li;
8726		} else if ($element.hasClass('liDropabble')) {
8727			//when mouse is over LI form field element
8728			dragInfo.currentElementOver.$li = $element;
8729		}
8730
8731		if (dragInfo.currentElementOver.$li != null && dragInfo.currentElementOver.$li.hasClass('liDropabble')) {
8732			//Over a valid droppable li
8733			dragInfo.currentElementOver.$ol = dragInfo.currentElementOver.$li.parent();
8734			//$('#log2').val("inside.. . currentLI=" + dragInfo.currentElementOver.$li.attr('id'));
8735		}
8736
8737		// Logic to determines if mouse pointer is out of a menu item.
8738		if (dragInfo.$prevMenuItemOver != null && (dragInfo.currentElementOver.$li == null || dragInfo.currentElementOver.$li[0] != dragInfo.$prevMenuItemOver[0])) {
8739			//fire menu item leave event
8740			menuItemLeave(dragInfo.$prevMenuItemOver);
8741		}
8742		dragInfo.$prevMenuItemOver = dragInfo.currentElementOver.$li;
8743
8744		//mouse is over a valid form field to resize.??
8745	}
8746};
8747
8748///Handles when an element was dropped
8749MenuManager.prototype.dropHandler = function (dragInfo) {
8750	var self = this; // Reference to current object
8751
8752	var validPosition = false;
8753	if (dragInfo.currentElementOver != null && dragInfo.currentElementOver.$li != null && dragInfo.currentElementOver.$li.hasClass('liDropabble') && !dragInfo.currentElementOver.$li.hasClass('beingDragged')) {
8754		var $liTarget = dragInfo.currentElementOver.$li;
8755		$liTarget.removeClass('hover');
8756
8757		if (self.sideMenuHasCustomLinks || dragInfo.$draggedElement.data('drag').menuType === $liTarget.data('drag').menuType) {
8758			validPosition = true;
8759			//var msgSource = "ID=" + dragInfo.$draggedElement.data('drag').itemID + ",parentID=" + dragInfo.$draggedElement.data('drag').parentID + ",prevItemID=" + dragInfo.$draggedElement.data('drag').prevItemID + ",isAddPage=" + dragInfo.$draggedElement.data('drag').isAddPage;
8760			//var msgTarget = "ID=" + $liTarget.data('drag').itemID + ",parentID=" + $liTarget.data('drag').parentID + ",prevItemID=" + $liTarget.data('drag').prevItemID + ",isAddPage=" + $liTarget.data('drag').isAddPage;
8761			//alert("dropped source=" + msgSource + "\nOn target=" + msgTarget);
8762			var url = '';
8763			var addingPage = false;
8764			if (dragInfo.$draggedElement.data('drag').isAddPage) {
8765				//Creating a new page in a specific menu position
8766				addingPage = true;
8767				url = "/Pages/Page/Add";
8768			} else {
8769				//Moving an existing menu item on different position
8770				url = "/Pages/PageStatus/Move/" + dragInfo.$draggedElement.data('drag').itemID;
8771			}
8772			//logic to build position where menu item was dropped
8773			url += "?parentID=" + $liTarget.data('drag').parentID;
8774			if ($liTarget.data('drag').isAddPage) {
8775				if ($liTarget.data('drag').prevItemID != null)
8776					url += "&refPageID={1}&position=Next".replace("{1}", $liTarget.data('drag').prevItemID);
8777				else
8778					url += "&position=Child";
8779			} else {
8780				url += "&refPageID={1}&position=Previous".replace("{1}", $liTarget.data('drag').itemID);
8781				if ($liTarget.hasClass('topMenuItem') && $liTarget.data('drag').menuType == MAIN_MENU) {
8782					//Check whether or not is possible to copy layout from top sibling page
8783					var message = '';
8784					$.ajax({
8785						url: '/Layout/CopyAssociation/CheckTopPages?copyLayoutFrom={0}'
8786							.replace('{0}', $liTarget.data('drag').itemID),
8787						type: 'POST',
8788						async: false, //Needs to be a sync request
8789						success: function (response) {
8790							if (response.ErrorMessage) {
8791								alert(response.ErrorMessage);
8792							} else if (response.Message) {
8793								message = response.Message;
8794							}
8795						},
8796						error: function (xhr, textStatus, exception) {
8797							alert("Error: " + xhr.statusText + "\nStatus: " + xhr.status);
8798						}
8799					});
8800					if (message.length > 0 && confirm(message)) {
8801						url += "&copyLayoutFrom=" + $liTarget.data('drag').itemID;
8802					}
8803				}
8804			}
8805
8806			if (addingPage) {
8807				window.location.href = url;
8808			} else {
8809				$.ajax({
8810					url: url,
8811					type: 'POST',
8812					success: function (response) {
8813						if (response.ErrorMessage) {
8814							alert(response.ErrorMessage);
8815							ajaxPostBackEnd();
8816						} else if (response.RedirectURL && response.RedirectURL !== location.href) {
8817							location.href = response.RedirectURL;
8818						} else {
8819							location.reload(true);
8820						}
8821					},
8822					beforeSend: function () {
8823						ajaxPostBackStart('Loading');
8824					},
8825					error: function (xhr, textStatus, exception) {
8826						alert("Error: " + xhr.statusText + "\nStatus: " + xhr.status);
8827						ajaxPostBackEnd();
8828					}
8829				});
8830			}
8831		}
8832	}
8833};
8834
8835MenuManager.prototype.setupDraggableElement = function ($element, menuType, containerSelectorToAppend) {
8836	var self = this; // Reference to current object
8837
8838	//Unbind the event before binding it again. Both solutions below work.
8839	$element.unbind('draginit dragstart drag dragend');
8840	//$element.drag('destroy');
8841	// Prevents IE from selecting text while starting a drag.
8842	$element.bind('selectstart', function (event) {
8843		event.preventDefault();
8844		return false;
8845	});
8846
8847	var dragInfo = null;
8848
8849	var relativeContainerOffSet = { top: 0, left: 0 };
8850	var draggedRelativeElementOffset = { top: 0, left: 0 };
8851	var isAddPageElem = $element.hasClass('addPage');
8852
8853	//jquery event drag 2.0 plugin.
8854	$element.drag("start", function () {
8855		if (self.mobileMainNav) return false;
8856		self.isMainMenuBeingDragged = (menuType == MAIN_MENU);
8857		self.isSideMenuBeingDragged = (menuType == SIDE_MENU);
8858
8859		var $draggedElement = null;
8860		if ($(this).hasClass('grippy'))
8861			$draggedElement = $(this).parent('li'); //page menu items
8862		else if ($(this).hasClass('addPage'))
8863			$draggedElement = $(this); //Add Page menu items
8864
8865		$draggedElement.addClass('beingDragged');
8866
8867		/*if ($draggedElement.hasClass('topMenuItem') && (menuType == MAIN_MENU)) {
8868		//workaround to hide top level menu items on main menu. (hideMenu don't work since submenus are not naturally on DOM)
8869		self.hideAllSubMenus(MAIN_MENU);
8870		}
8871		else*/
8872		self.hideSubMenu($draggedElement);
8873
8874		dragInfo = {
8875			$draggedElement: $draggedElement,
8876			currentElementOver: { $element: null, $li: null, isAddPage: null, $ol: null },
8877			$prevMenuItemOver: null,
8878			resetCurrentElementOver: function () {
8879				this.currentElementOver.$element = null;
8880				this.currentElementOver.$li = null;
8881				this.currentElementOver.$ol = null;
8882				this.currentElementOver.isAddPage = null;
8883			}
8884		};
8885
8886		//If container for thing to drag has relative position, gets its offset to subtract coordinates while dragging.
8887		relativeContainerOffSet = ($(containerSelectorToAppend).css("position") == "relative") ? $(containerSelectorToAppend).offset() : { top: 0, left: 0 };
8888
8889		var hasChildren = $draggedElement.hasClass('hasChildren');
8890		var menuText = $draggedElement.children('a.navMenuItem, a.navMainItem').text();
8891		if (menuText == '') {
8892			menuText = $draggedElement.children('div.accordionNavItem').children('a.navMenuItem').text();
8893		}
8894		var $dragHelper = $('<a/>', {
8895			'class': 'thingToDrag navMenuItem' + (hasChildren ? ' withChildren' : '')
8896		}).css('z-index', 1002).text(menuText);
8897		return $dragHelper.appendTo(containerSelectorToAppend);
8898	}).drag(function (e, dd) {
8899		//if draggable element has relative position, gets the offset where the mouse was clicked to add coordinates while dragging.
8900		draggedRelativeElementOffset = (isAddPageElem) ? { top: dd.startY - dd.originalY, left: dd.startX - dd.originalX } : { top: 0, left: 0 };
8901
8902		$(dd.proxy).css({
8903			top: (dd.offsetY + draggedRelativeElementOffset.top - relativeContainerOffSet.top) + 15,
8904			left: (dd.offsetX + draggedRelativeElementOffset.left - relativeContainerOffSet.left) - 10
8905		});
8906		//$('#log4').val('dd.offsetX=' + dd.offsetX + ',dd.offsetY=' + dd.offsetY + ',e.clientX=' + e.clientX + ',e.clientY=' + e.clientY + ',e.pageX=' + e.pageX + ',e.pageY=' + e.pageY);
8907		var $elementOver = $(document.elementFromPoint(e.originalEvent.clientX, e.originalEvent.clientY));
8908		// Execute drag handler
8909		if (dragInfo != null)
8910			self.dragHandler($elementOver, dragInfo);
8911	}, { relative: false })
8912		.drag("end", function (ev, dd) {
8913			if (self.mobileMainNav) return false;
8914			$(dd.proxy).remove();
8915
8916			if (dragInfo != null) {
8917				self.dropHandler(dragInfo);
8918				dragInfo.$draggedElement.removeClass('beingDragged');
8919				dragInfo.$draggedElement = null;
8920				dragInfo.$prevMenuItemOver = null;
8921				dragInfo = null;
8922			}
8923			self.isMainMenuBeingDragged = false;
8924			self.isSideMenuBeingDragged = false;
8925		});
8926};
8927
8928MenuManager.prototype.setupDroppableElement = function ($element, menuType) {
8929	var self = this; // Reference to current object
8930	if (!self.mobileMainNav && $element.find('div.indicator').length == 1 && !$element.hasClass('liDropabble')) {
8931		$element.addClass('liDropabble');
8932
8933		//initialize drag jquery data for droppable elements
8934		var isAddPage = $element.hasClass('addPage');
8935		var itemID = !isAddPage ? $element.attr('id').replace(/MainItem|SideItem/i, '') : '';
8936		var prevItemID = ($element.prev().length == 1) ? $element.prev().attr('id').replace(/MainItem|SideItem/i, '') : null;
8937		var parentID = $element.parent().attr('id').replace(/ParentMainItem|ParentSideItem/i, '');
8938		if (isNaN(parentID)) //for top level menu items
8939			parentID = $element.parent().data('parent');
8940
8941		$element.data('drag', { itemID: itemID, parentID: parentID, prevItemID: prevItemID, isAddPage: isAddPage, menuType: menuType });
8942
8943		/// Setups recursively all children DOM elements with class needed by drag algorithm to recognize which element mouse pointer is
8944		var setUpChildren = function ($children) {
8945			if ($children.length > 0) {
8946				$children.each(function () {
8947					$children.addClass('inside');
8948					setUpChildren($(this).children());
8949				});
8950			}
8951		};
8952
8953		setUpChildren($element.children());
8954	}
8955};
8956
8957MenuManager.prototype.setupDroppableAccordionElement = function ($element) {
8958	var self = this;
8959	if (!self.mobileMainNav && $element.find('div.indicator').length > 0 && !$element.hasClass('liDropabble')) {
8960		$element.addClass('liDropabble');
8961
8962		//initialize drag jquery data for droppable elements
8963		var isAddPage = $element.hasClass('addPage');
8964		var itemID = !isAddPage ? $element.attr('id').replace(/MainItem|SideItem/i, '') : '';
8965		var prevItemID = ($element.prev().length == 1) ? $element.prev().attr('id').replace(/MainItem|SideItem/i, '') : null;
8966		var $parent = $element.parents('li:first');
8967		if ($parent.length == 0) {
8968			$parent = $element.parents('ol:first');
8969		}
8970		var parentID = $parent.attr('id').replace(/ParentMainItem|ParentSideItem/i, '');
8971		if (isNaN(parentID)) //for top level menu items
8972			parentID = $element.parent().data('parent');
8973
8974		$element.data('drag', { itemID: itemID, parentID: parentID, prevItemID: prevItemID, isAddPage: isAddPage, menuType: SIDE_MENU });
8975
8976		/// Setups recursively all children DOM elements with class needed by drag algorithm to recognize which element mouse pointer is
8977		var setUpChildren = function ($children) {
8978			$children.each(function () {
8979				$children.addClass('inside');
8980				setUpChildren($(this).children());
8981			});
8982		};
8983
8984		setUpChildren($element.children());
8985	}
8986
8987	$element.unbind('mouseenter').mouseenter(function (e) {
8988		e.stopPropagation();
8989		if (self.isSideMenuBeingDragged) {
8990			$element.addClass('hover');
8991		}
8992	});
8993
8994	$element.unbind('mouseleave').mouseleave(function (e) {
8995		$element.removeClass('hover');
8996	});
8997};
8998
8999///Moves the submenu to be displayed at the bottom of the DOM.
9000MenuManager.prototype.moveSubMenuInDOM = function ($submenu, menuType) {
9001
9002	//Remove any old .pop elements from the DOM to reload the new one.
9003	if ($('body').find($submenu).length > 0)
9004		$('body').find($submenu).remove();
9005
9006	//$submenu is the ol, $parent is the li.
9007	$submenu.addClass('subMenuMoved').appendTo('body');
9008
9009	var className = menuType == MAIN_MENU ? 'mainSubMenu' : 'secondarySubMenu';
9010	$submenu.addClass(className);
9011	$submenu.addClass('moved');
9012
9013	$submenu.css('position', 'absolute');
9014	$submenu.css('z-index', '100');
9015}
9016
9017///Updates the position of submenus in the DOM.
9018MenuManager.prototype.positionSubMenuInDOM = function ($submenu, $li, menuType) {
9019	var topMainNavigationLink = menuType == MAIN_MENU && $li.hasClass('topMenuItem');
9020	var self = this;
9021	self.updateSubMenuPositionAttributes($submenu, topMainNavigationLink, menuType);
9022	//If after the submenu is positioned, it has a class of flipLeft, remove it since that causes some display issues on the front-end. Vishal
9023	if ($submenu.hasClass('flipLeft'))
9024		$submenu.removeClass('flipLeft').addClass('flippedLeft');
9025};
9026
9027MenuManager.prototype.updateSubMenuPositionAttributes = function ($submenu, topMainNavigationLink, menuType) {
9028	//Get the main nav.
9029	var parentID = $submenu.attr('id').replace(/Parent/, '');
9030	var $parent = $('#' + parentID);
9031
9032	$submenu.removeClass('flippedLeft');
9033
9034	if ($('#bodyWrapper').data('maxPaddingBottom') == undefined)
9035		$('#bodyWrapper').data('maxPaddingBottom', 0);
9036
9037	//Reset bottom-padding on body wrapper to allow accurate calculation
9038	$('#bodyWrapper').css('padding-bottom', $('#bodyWrapper').data('maxPaddingBottom'));
9039
9040	var docHeight = $(document).height();
9041	var menuVisibleSpaceAvailable = docHeight - $parent.offset().top;
9042	var submenuHeight = $submenu.height();
9043
9044	//If the parent submenu opened in towards left, let all the subsequent submenus open in the same flow.
9045	if ($parent.length > 0 && $parent.parents('ol.subMenuMoved').hasClass('flippedLeft'))
9046		$submenu.addClass('flipLeft');
9047
9048	if (menuVisibleSpaceAvailable < submenuHeight && !$submenu.hasClass('takenIntoAccount')) {
9049		//20 is just a default safe padding apart from the calculations.
9050		$('#bodyWrapper').css('padding-bottom', (submenuHeight - menuVisibleSpaceAvailable + parseFloat($('#bodyWrapper').data('maxPaddingBottom')) + 20));
9051		$('#bodyWrapper').data('maxPaddingBottom', $('#bodyWrapper').css('padding-bottom'));
9052		$submenu.addClass('takenIntoAccount');
9053		if (!$submenu.hasClass('safePaddingApplied')) {
9054			//Add a padding-bottom of 10px to the submenu to be more presentable
9055			$submenu.css('padding-bottom', '10px');
9056			$submenu.addClass('safePaddingApplied');
9057		}
9058	}
9059	if (menuType == MAIN_MENU) {
9060		//Set top position of main submenu
9061		$submenu.css('top', $parent.offset().top + (topMainNavigationLink ? $parent.height() : 0));
9062
9063		if ($submenu.hasClass('flipLeft')) {
9064			var width = $submenu.find('li:first').width();
9065			//Set left position of side submenu
9066			$submenu.css('left', $parent.offset().left - width);
9067		}
9068		else {
9069			//Set left position of main submenu
9070			$submenu.css('left', $parent.offset().left + (topMainNavigationLink ? 0 : $parent.width()));
9071		}
9072	}
9073	else {
9074		//Set top position of side submenu
9075		$submenu.css('top', $parent.offset().top);
9076
9077		if ($submenu.hasClass('flipLeft')) {
9078			var width = $submenu.find('li:first').width();
9079			//Set left position of side submenu
9080			$submenu.css('left', $parent.offset().left - width);
9081		}
9082		else {
9083			//Set left position of side submenu
9084			$submenu.css('left', $parent.offset().left + $parent.width());
9085		}
9086	}
9087};
9088/***** End - Drag and Drop functions to handle main/side menus  ********/
9089
9090/***** Start - Mega Menu methods  ********/
9091MenuManager.prototype.pinMegaMenuOpen = function ($this) {
9092	var $megaMenuGrid = $this.parents('.megaMenuContainer').children('.pageContent.cpGrid');
9093	if ($megaMenuGrid.is(':visible')) {
9094		$('#mainNav').css('z-index', '10');
9095		$megaMenuGrid.addClass('pinned');
9096		$megaMenuGrid.find('.handle.pin').addClass('pinned');
9097		if (typeof PageEditLocalization != 'undefined') {
9098			$megaMenuGrid.find('.handle.pin').attr('title', pageEditLocalization.UnpinMegaMenu);
9099		}
9100	}
9101};
9102
9103MenuManager.prototype.resetMouseOvers = function () {
9104	$('#mainNav').css('z-index', '').find('*').removeClass('mouseover');
9105	$('#secondaryNav').find('*').removeClass('mouseover');
9106};
9107
9108/// Setup
9109MenuManager.prototype.initializeMegaMenus = function () {
9110	var self = this;
9111	if (typeof window.DesignCenter === 'undefined' || typeof window.DesignCenter.themeJSON === 'undefined') { // If we aren't in design center....
9112		$('#megaMenu,.megaMenuContainer').unbind('mouseenter').mouseenter(function (e) {
9113			e.stopPropagation();
9114			var $megaMenuContainer = $(this).attr('id') == 'megaMenu' ? $('.megaMenuContainer:visible') : $(this);
9115			var pageID = $megaMenuContainer.attr('id').match(/\d+$/)[0];
9116			$('#mainNav [data-pageid=' + pageID + ']  a').addClass('mouseover');
9117
9118			$megaMenuContainer.addClass('hover');
9119		});
9120
9121		$('.megaMenuContainer').unbind('mouseleave').mouseleave(function (e) {
9122			var $megaMenuContainer = $(this);
9123			var visible = $(this).is(':visible');
9124			if (visible) {
9125				if ($megaMenuContainer.hasClass('optionOpen') && !$('.cpPopOver.common').is(':visible')) {
9126					$megaMenuContainer.removeClass('optionOpen');
9127				}
9128				if (!$megaMenuContainer.hasClass('handleHover') && !$megaMenuContainer.hasClass('optionOpen') && !$megaMenuContainer.find('.pageContent.cpGrid').hasClass('dragging') && !$megaMenuContainer.find('.pageContent.cpGrid').hasClass('pinned')) {
9129					$megaMenuContainer.hide().removeClass('hover');
9130					//$('#megaMenu').hide();
9131					$('.megaMenu').hide();
9132
9133					//While mousing out of mega menu, if it contains any flyout widgets, hide them.
9134					$('.flyOut.moved.forMegaMenu').hide();
9135
9136					self.resetMouseOvers();
9137				}
9138			}
9139		});
9140
9141		$('.megaMenuContainer .handle.remove, .megaMenuContainer .handle.move, .megaMenuContainer .handle.inheritance').unbind('mouseenter').mouseenter(function (e) {
9142			e.stopPropagation();
9143			$(this).parents('.megaMenuContainer').addClass('handleHover');
9144		});
9145
9146		$('.megaMenuContainer .handle.remove, .megaMenuContainer .handle.move, .megaMenuContainer .handle.inheritance').unbind('mouseleave').mouseleave(function (e) {
9147			$(this).parents('.megaMenuContainer').removeClass('handleHover');
9148		});
9149
9150		$('.megaMenuContainer .handle.pin').unbind('click').click(function (e) {
9151			$(this).toggleClass('pinned');
9152			$(this).parent().toggleClass('pinned');
9153			if (typeof PageEditLocalization != 'undefined') {
9154				$(this).attr('title', $(this).hasClass('pinned') ? pageEditLocalization.UnpinMegaMenu : pageEditLocalization.PinMegaMenu);
9155			}
9156		});
9157	}
9158};
9159
9160MenuManager.prototype.attachDragAndDropHandlers = function () {
9161	//Make mega menu items draggable
9162	var $currentDraggables = $('.megaMenuContainer').find('li.level1.ui-draggable, li.level2.ui-draggable');
9163	if ($currentDraggables.length) {
9164		$currentDraggables.draggable('destroy');
9165	}
9166
9167	$('.megaMenuContainer').find('li.level1, li.level2').draggable({
9168		helper: function (event) {
9169			var html = '<ol class="semeanticList" style="white-space: nowrap">';
9170			html += $('<div>').append($(this).clone()).html() + '</ol>';
9171			return $(html);
9172		},
9173		start: function (event, ui) {
9174			$('.megaMenuContainer .pageContent').addClass('megaMenudragging');
9175		},
9176		stop: function (event, ui) {
9177			$('.megaMenuContainer .pageContent').removeClass('megaMenudragging');
9178		},
9179		cursorAt: { top: 5, right: 5 },
9180		cursor: 'move',
9181		handle: '.grippy'
9182	});
9183
9184	//Attach drop target handlers
9185	var $currentDroppables = $('.megaMenuTarget.ui-droppable', '.megaMenuContainer.ui-droppable');
9186	if ($currentDroppables.length) {
9187		$currentDroppables.droppable('destroy');
9188	}
9189	$('.megaMenuTarget', '.megaMenuContainer').droppable({
9190		over: function (event, ui) {
9191			$(this).parent().addClass('hover');
9192		},
9193		out: function (event, ui) {
9194			$(this).parent().removeClass('hover');
9195		},
9196		drop: function (event, ui) {
9197			var $target = $(this),
9198				targetPageID = $target.data('pageid'),
9199				targetPosition = $target.data('position'),
9200				parentID = $target.data('parentid'),
9201				pageID = $(ui.helper).children('li').data('pageid');
9202
9203			$target.parent().removeClass('hover');
9204
9205			var url = "/Pages/PageStatus/Move/" + pageID;
9206			url += "?parentID=" + parentID;
9207			url += "&refPageID={0}&position={1}".replace("{0}", targetPageID).replace("{1}", targetPosition);
9208
9209			$.ajax({
9210				url: url,
9211				type: 'POST',
9212				success: function (response) {
9213					if (response.ErrorMessage) {
9214						alert(response.ErrorMessage);
9215						ajaxPostBackEnd();
9216					} else {
9217						location.href = response.RedirectURL;
9218					}
9219				},
9220				beforeSend: function () {
9221					ajaxPostBackStart('Loading');
9222				},
9223				error: function (xhr, textStatus, exception) {
9224					alert("Error: " + xhr.statusText + "\nStatus: " + xhr.status);
9225					ajaxPostBackEnd();
9226				}
9227			});
9228		},
9229		tolerance: 'pointer'
9230	});
9231};
9232
9233/***** End - Mega Menu methods  ********/
9234
9235/***** Start - Class/functions to handle custom links ********/
9236function MenuCustomLinksManager(confirmCustomLinksDeletion, pageID, moduleID) {
9237	this.pageID = pageID;
9238	this.moduleID = moduleID;
9239	this.checkOrphanFeatureLinks = function () {
9240		if (confirmCustomLinksDeletion && confirmCustomLinksDeletion.length > 0) {
9241			return confirm(confirmCustomLinksDeletion);
9242		}
9243		return true;
9244	};
9245
9246	this.updateSideMenu = function (actionUrl) {
9247		$.ajax({
9248			url: actionUrl,
9249			type: 'post',
9250			cache: false,
9251			success: function (response) {
9252				if (response.ErrorMessage) {
9253					alert(response.ErrorMessage);
9254					ajaxPostBackEnd();
9255				} else if (response.RedirectURL)
9256					window.location.href = response.RedirectURL;
9257				else {
9258					//update side menu UI.
9259					window.location.reload(true);
9260				}
9261			},
9262			beforeSend: function () {
9263				ajaxPostBackStart('Loading');
9264			},
9265			error: function (xhr, textStatus, exception) {
9266				ajaxPostBackEnd();
9267				alert("Error choosing default side menu: " + xhr.statusText + "\nStatus: " + xhr.status);
9268			}
9269		});
9270	};
9271}
9272
9273/// open modal to chose page to associate with current page/module as custom link
9274MenuCustomLinksManager.prototype.chosePage = function () {
9275	var self = this; // Reference to current object
9276	if (self.checkOrphanFeatureLinks()) {
9277		openCpModal({
9278			title: 'Choose Page',
9279			className: 'notContent choosePageForLinks',
9280			isFrontEnd: false,
9281			url: '/Pages/CustomLinks/ChoosePage/?pageID=' + self.pageID + '&moduleID=' + self.moduleID
9282		});
9283	}
9284};
9285
9286/// Call back to execute after choosing a page on modal.
9287MenuCustomLinksManager.prototype.chosePageExecute = function (chosenPageID) {
9288	var self = this; // Reference to current object
9289	closeCpModal();
9290	//Update side nav.
9291	self.updateSideMenu('/Pages/CustomLinks/ChangeSideMenu/?pageID=' + self.pageID + '&moduleID=' + self.moduleID + '&chosenPageID=' + chosenPageID);
9292};
9293
9294/// Creates a new empty root feature link for specific page/module
9295MenuCustomLinksManager.prototype.createNewCustomLink = function () {
9296	var self = this; // Reference to current object
9297	if (self.checkOrphanFeatureLinks()) {
9298		self.updateSideMenu('/Pages/CustomLinks/CreateCustomFeatureLinks/?pageID=' + self.pageID + '&moduleID=' + self.moduleID);
9299	}
9300};
9301
9302/// Make default side menu for current page/module (remove custom link previously assigned).
9303MenuCustomLinksManager.prototype.choseDefaultSideMenu = function () {
9304	var self = this; // Reference to current object
9305	if (self.checkOrphanFeatureLinks()) {
9306		self.updateSideMenu('/Pages/CustomLinks/ChoseDefaultSideMenu/?pageID=' + self.pageID + '&moduleID=' + self.moduleID);
9307	}
9308};
9309
9310/***** End - Class/functions to handle feature links on Secondary menus ********/
9311
9312/***** Start - Class/functions to handle Main Menu Options ********/
9313function MainMenuOptions(pageID, mainMenuRootID) {
9314	var wasCheckBoxChanged = function ($checkbox) {
9315		if ($checkbox.is(":checked"))
9316			return $checkbox.data('original') != 'True';
9317		else
9318			return $checkbox.data('original') == 'True';
9319	};
9320
9321	var closeMainMenuPopover = function ($handler, doNotResetCheckboxes) {
9322		$handler.data("cpPopover").hide();
9323		if (doNotResetCheckboxes)
9324			return;
9325
9326		//reset checkbox selections
9327		$('div.menuOptions input[type=checkbox]').each(function () {
9328			if ($(this).data("original") == "True")
9329				$(this).prop("checked", true);
9330			else
9331				$(this).prop("checked", false);
9332		});
9333	};
9334
9335	var initializeMainMenuPopup = function ($handler) {
9336		$('#cancelMainNavOptions', "#modalMainNavOptions")
9337			.unbind('click.mainMenuOptions').bind("click.mainMenuOptions", function (e) {
9338			e.preventDefault();
9339			closeMainMenuPopover($handler, false);
9340		});
9341
9342		$('#saveMainNavOptions', "#modalMainNavOptions")
9343			.unbind('click.mainMenuOptions').bind("click.mainMenuOptions", function (e) {
9344			e.preventDefault();
9345
9346			var useThisPageAsMainMenu = null;
9347			var displayMegaMenu = [];
9348
9349			$('div.menuOptions input.DisplayMegaMenu').each(function () {
9350				if (wasCheckBoxChanged($(this)))
9351					displayMegaMenu.push({ PageID: $(this).data('pageid'), DisplayMegaMenu: $(this).is(':checked') });
9352			});
9353
9354			if ($('#ysnUseThisPagesSubpages', 'div.menuOptions').length == 1 && wasCheckBoxChanged($('#ysnUseThisPagesSubpages'), 'div.menuOptions'))
9355				useThisPageAsMainMenu = $('#ysnUseThisPagesSubpages', 'div.menuOptions').is(':checked');
9356
9357			var data = JSON.stringify({ pageID: pageID, versionID: $('#hdnVersionID').val(), useThisPageAsMainMenu: useThisPageAsMainMenu, displayMegaMenu: displayMegaMenu, structureID: $('#hdnStru
9357ctureID').val() });
9358
9359			AJAX("/Pages/Menu/MainMenuOptionsSave", 'POST', data, function (response) {
9360				window.location.reload(true);
9361			}, true, 'application/json');
9362
9363			closeMainMenuPopover($handler, true);
9364		});
9365	};
9366
9367	var $handlerMainMenu = $('#mainNavMenuHandleOptions');
9368	if ($('#hdnIsLayoutPage').val() === "True" || $('#hdnVersionID').length === 0 || $('#hdnVersionID').val() == "0") {
9369		$handlerMainMenu.remove();
9370	} else {
9371		$handlerMainMenu.cpPopover({
9372			url: '/Pages/Menu/MainMenuOptions',
9373			type: 'POST',
9374			contentType: 'application/json',
9375			data: JSON.stringify({ pageID: pageID, mainMenuRootID: mainMenuRootID }),
9376			className: 'options adminWrap admin menuOptions',
9377			onInit: function () {
9378				initializeMainMenuPopup($handlerMainMenu);
9379			},
9380			onClose: function (e) {
9381				e.preventDefault();
9382				closeMainMenuPopover($handlerMainMenu, false);
9383			}
9384		});
9385	}
9386}
9387
9388/***** End - Class/functions to handle Main Menu Options ********/
9389
9390function showHideAccordionMenuForSecondaryNav($elem) {
9391	var secondaryMenu = 1;
9392	var hasAccordionSubmenu = $elem.next('a.openAccordionNav').length > 0;
9393	if (hasAccordionSubmenu)
9394		$elem = $elem.next('a.openAccordionNav');
9395	var $container = $elem.parent().siblings('.accordionNavContainer');
9396	var $secondaryNavHiddenElement = $('#secondaryNav').children('[class*="hiddenAnimations"]');
9397	var animations = null;
9398	//Apply initial animation state before the sliding happens to open the accordion submenu
9399	if (!$elem.hasClass('accordionNavOpened')) {
9400		if (typeof (Animations) === 'function') {
9401			animations = new Animations();
9402			animations.applyInitial($container, secondaryMenu);
9403		}
9404	} else {//reset the container by removing animation classes.
9405		if ($secondaryNavHiddenElement.length > 0 && $secondaryNavHiddenElement.data('animationClass') !== undefined)
9406			$container.removeClass($secondaryNavHiddenElement.data('animationclass'));
9407		$container.removeClass('animation-triggered');
9408	}
9409
9410	$elem.toggleClass('accordionNavOpened');
9411	$elem.attr('aria-expanded', $elem.attr('aria-expanded') === 'true' ? 'false' : 'true');
9412	$container.css('overflow', 'hidden');
9413	$container.slideToggle("333ms");
9414
9415	if ($container.attr('aria-hidden') === 'true') {
9416		$container.attr('aria-hidden', 'false');
9417	} else {
9418		$container.attr('aria-hidden', 'true');
9419	}
9420
9421	setTimeout(function () {
9422		$container.css('overflow', '');
9423		if ($elem.hasClass('accordionNavOpened')) {
9424			//If Animation manager toggled on, implement the menu animations
9425			if (animations != null)
9426				animations.applyAnimationClassToNavContainers($container, 1);
9427		}
9428
9429	}, 400);
9430
9431	if (typeof dynamicStretchContainers === 'function') {
9432		setTimeout(dynamicStretchContainers, 400);
9433	}
9434}
9435
9436$(document).ready(function () {
9437	//Mega menus handlers
9438	$('.megaMenuContainer')
9439		.hide()
9440		.removeClass('hidden')
9441		.find('.handle.inheritance').remove();
9442	menuManager.initializeMegaMenus();
9443});
9444;
9445/*Strategy pattern
9446AccessibleMenu: Abstract class with default implementation for bindHandlers, initialize
9447MainAccessibleMenu: Concrete implementation of Accessible menu
9448SecondaryAccessibleMenu: Concrete implementation of Accessible menu
9449Note: AccordionAccessibleMenu has been moved to AccessibleAccordionMenu.js*/
9450var stack = [];
9451var AccessibleMenu = function () {
9452	this.menuItem = "";
9453};
9454var accessibleMenuToggleEnabled = window.FeatureToggles.isActive("CMS.Pages.AccessibleMainMenuWithIndicators");
9455
9456AccessibleMenu.prototype = {
9457	initialize: function (mainMenuItem, accordionMenu) {
9458		if (mainMenuItem)
9459			this.setStrategy(new MainAccessibleMenu());
9460		else {
9461			this.setStrategy(new SecondaryAccessibleMenu());
9462		}
9463	},
9464	setStrategy: function (menuItem) {
9465		this.menuItem = menuItem;
9466	},
9467	bindHandlers: function ($elem) {
9468		var self = this;
9469
9470		$elem.off('keydown.Menu').on('keydown.Menu', function (e) {
9471			if (e.which == 37) {//left
9472				self.left($elem);
9473				e.preventDefault();
9474			}
9475			if (e.which == 38) {//up
9476				self.up($elem);
9477				e.preventDefault();
9478			}
9479			if (e.which == 39) {//right
9480				self.right($elem);
9481				e.preventDefault();
9482			}
9483			if (e.which == 40) {//down
9484				self.down($elem);
9485				e.preventDefault();
9486			}
9487			if (e.which === 13 || e.which === 32) {//enter or space
9488				if (self.enter($elem)) {
9489					e.preventDefault();
9490				}
9491			}
9492			if (e.which === 9) {//tab
9493				if (self.tab($elem)) {
9494					e.preventDefault();
9495				}
9496			}
9497		});
9498	},
9499	left: function ($elem) {
9500		this.menuItem.left($elem);
9501	},
9502	up: function ($elem) {
9503		this.menuItem.up($elem);
9504	},
9505	right: function ($elem) {
9506		this.menuItem.right($elem);
9507	},
9508	down: function ($elem) {
9509		this.menuItem.down($elem);
9510	},
9511	enter: function ($elem) {
9512		return this.menuItem.enter($elem);
9513	},
9514	tab: function ($elem) {
9515		return this.menuItem.tab($elem);
9516	}
9517};
9518
9519//MainAccessibleMenu concrete class
9520var MainAccessibleMenu = function () {
9521
9522	// Get parent menu item from submenu
9523	var getParentMenuItem = function ($elem) {
9524		var parentOlId = $elem.parents('ol').attr('id');
9525		var parentMenuItemId = parentOlId.slice('Parent'.length);
9526		return $('#' + parentMenuItemId).find('a:first');
9527	};
9528
9529	// Get first anchor in child submenu
9530	var getFirstChildSubmenuAnchor = function ($elem) {
9531		var $parentLi = $elem.parent('li');
9532		var $parentId = "Parent" + $parentLi.attr('id');
9533		return $('ol[id=' + $parentId + '] a:first');
9534	};
9535
9536	this.left = function ($elem) {
9537		if (menuManager.isTopLevelMenuItem($elem)) {
9538			menuManager.handleLeftKeyOnAnyTopLevelItem($elem);
9539			return;
9540		}
9541
9542		// Submenu item handling
9543		if (!accessibleMenuToggleEnabled) {
9544			getParentMenuItem($elem).focus();
9545			return;
9546		}
9547
9548		var shouldOpenSubmenu = menuManager.shouldOpenSubmenuOnNavigation($elem);
9549		menuManager.handleLeftKeyInSubmenu($elem, shouldOpenSubmenu);
9550	};
9551
9552	this.up = function ($elem) {
9553		if (menuManager.isTopLevelMenuItem($elem)) {
9554			if (menuManager.isMegaMenuItem($elem)) {
9555				return;
9556			}
9557			menuManager.handleUpKeyOnTopLevelItem($elem);
9558			return;
9559		}
9560
9561		// Submenu item handling - use MenuManager handler
9562		menuManager.handleUpKeyInSubmenu($elem, {
9563			onFirstItem: function ($elem) {
9564				getParentMenuItem($elem).focus();
9565			}
9566		});
9567	};
9568
9569	this.right = function ($elem) {
9570		if (menuManager.isTopLevelMenuItem($elem)) {
9571			menuManager.handleRightKeyOnAnyTopLevelItem($elem);
9572			return;
9573		}
9574
9575		// Submenu item handling
9576		if (!accessibleMenuToggleEnabled) {
9577			getFirstChildSubmenuAnchor($elem).focus();
9578			return;
9579		}
9580
9581		var shouldOpenSubmenu = menuManager.shouldOpenSubmenuOnNavigation($elem);
9582		menuManager.handleRightKeyInSubmenu($elem, shouldOpenSubmenu);
9583	};
9584
9585	this.down = function ($elem) {
9586		if (menuManager.isTopLevelMenuItem($elem)) {
9587			if (menuManager.isMegaMenuItem($elem)) {
9588				return;
9589			}
9590
9591			if (!menuManager.handleDownKeyOnTopLevelItem($elem)) {
9592				getFirstChildSubmenuAnchor($elem).focus();
9593			}
9594			return;
9595		}
9596
9597		// Submenu item handling - use MenuManager handler
9598		menuManager.handleDownKeyInSubmenu($elem);
9599	};
9600
9601	this.enter = function ($elem) {
9602		if (!menuManager.isSubMenuTrigger($elem)) {
9603			$elem[0].click();
9604			return true;
9605		}
9606
9607		if (accessibleMenuToggleEnabled) {
9608			menuManager.toggleSubMenu($elem);
9609			menuManager.toggleIndicator($elem);
9610			setTimeout(function () {
9611				menuManager.setFocusToFirstSubmenuitem($elem);
9612			}, 300);
9613			return true;
9614		} else if ($elem.hasClass("mainNavItem")) {
9615			menuManager.toggleSubMenu($elem);
9616			return true;
9617		}
9618
9619		return false;
9620	};
9621
9622    this.tab = function ($elem) {
9623        menuManager.setFocusToLastTopLevelItem();
9624
9625        // Return false to allow default tab behavior (focus moves to next focusable element outside menu)
9626        return false;
9627	};
9628};
9629
9630//SecondaryAccessibleMenu concrete class
9631var SecondaryAccessibleMenu = function () {
9632	this.left = function ($elem) {
9633		var parentOlId = $elem.parents('ol').attr('id');
9634		var parentMenuItemId = parentOlId.slice('Parent'.length);
9635		$('#' + parentMenuItemId).find('a:first').focus();
9636	};
9637
9638	this.up = function ($elem) {
9639		var $prev = $elem.parent('li').prev('li').find('a:first');
9640		if ($prev != null)
9641			$prev.focus();
9642	};
9643
9644	this.right = function ($elem) {
9645		var $parentLi = $elem.parent('li');
9646		var $parentId = "Parent" + $parentLi.attr('id');
9647		var $firstAnchorOfSubmenu = $('ol[id=' + $parentId + '] a:first');
9648		$firstAnchorOfSubmenu.focus();
9649	};
9650
9651	this.down = function ($elem) {
9652		var $next = $elem.parent('li').next('li').find('a:first');
9653		if ($next != null)
9654			$next.focus();
9655	};
9656
9657	this.enter = function ($elem) {
9658		return false;
9659	};
9660
9661	this.tab = function ($elem) {
9662		return false;
9663	};
9664};
9665
9666//Self invoked function
9667(function () {
9668	var isClick = false;
9669	$("a.navMainItem, a.navMenuItem").on("mousedown", function () {
9670		//Set isClick true if clicked on secondary nav menu item.
9671		isClick = true;
9672	});
9673
9674	function menuHandler(e) {
9675		var $this = $(this);
9676
9677		var focusSource = $this.data('focus-source');
9678		if (focusSource) {
9679			$this.removeData('focus-source');
9680			if (accessibleMenuToggleEnabled) {
9681				menuManager.hideSubMenu($this.parent('li'));
9682			}
9683		}
9684
9685		var isAccordionToggle = $this.hasClass('openAccordionNav');
9686		var isAccordionNavItem = $this.parent('div').hasClass('accordionNavItem');
9687		var isInAccordionNav = $this.closest('.accordionNav').length > 0;
9688
9689		if (isAccordionToggle || isAccordionNavItem || isInAccordionNav) {
9690			return;
9691		}
9692
9693		var accessibleMenu = new AccessibleMenu();
9694		var mainMenuItem = $this.parents('nav').hasClass('mainNav') | $this.parents('ol').hasClass('mainSubMenu');
9695
9696		accessibleMenu.initialize(mainMenuItem, false);
9697
9698		if (!mainMenuItem) {
9699			if (!accessibleMenuToggleEnabled)
9700				menuManager.menuMouseOver($this.parent('li'));
9701		} else {
9702			if (accessibleMenuToggleEnabled)
9703				menuManager.setActiveTopLevelItem($this);
9704			if (!accessibleMenuToggleEnabled || !mainMenuItem)
9705				menuManager.menuMouseOver($this.parent('li'));
9706
9707			window.lastMegaMenuOpen = $this.parent('li');
9708		}
9709		accessibleMenu.bindHandlers($this);
9710	}
9711
9712	$(document).on("focusin", "a.navMainItem, a.navMenuItem", menuHandler);
9713
9714	//hide last main menu item on tabbing through the menu item.
9715	$(".siteWrap").on("focusin", function (e) {
9716		menuManager.hideAllSubMenus(MAIN_MENU);
9717	});
9718}());
9719;
9720/*Strategy pattern
9721AccessibleMegaMenu: Abstract class with default implementation for bindHandlers, initialize
9722FormattedMegaMenu: Concrete implementation of Accessible mega menu*/
9723var AccessibleMegaMenu = function () {
9724	this.megaMenuItem = "";
9725	this.depth = 1;
9726	this.cols = 1;
9727};
9728
9729AccessibleMegaMenu.prototype = {
9730	initialize: function (format) {
9731		this.setStrategy(new FormatedMegaMenu());
9732	},
9733	setStrategy: function (megaMenuItem) {
9734		this.megaMenuItem = megaMenuItem;
9735	},
9736	bindHandlers: function ($elem) {
9737		var self = this;
9738		var LEFT = 37;
9739		var UP = 38;
9740		var RIGHT = 39;
9741		var DOWN = 40;		
9742        var SPACE = 32;
9743        var TAB = 9;
9744		$elem.off('keydown.MegaMenu').on('keydown.MegaMenu', function (e) {
9745			if (e.which == LEFT) {
9746				self.left($elem);
9747				e.preventDefault();
9748			}
9749			if (e.which == UP) {
9750				self.up($elem);
9751				e.preventDefault();
9752			}
9753			if (e.which == RIGHT) {
9754				self.right($elem);
9755				e.preventDefault();
9756			}
9757			if (e.which == DOWN) {
9758				self.down($elem);
9759				e.preventDefault();
9760			}
9761			if (e.which == SPACE) {
9762				self.space($elem)
9763				e.preventDefault();
9764            }
9765            if (e.which == TAB) {
9766                if (self.tab($elem)) {
9767                    e.preventDefault();
9768                }
9769            }
9770		});
9771	},
9772	exitMegaMenu: function ($elem) {
9773		this.megaMenuItem.exitMegaMenu($elem);
9774	},
9775	left: function ($elem) {
9776		this.megaMenuItem.left($elem);
9777	},
9778	up: function ($elem) {
9779		this.megaMenuItem.up($elem);
9780	},
9781	right: function ($elem) {
9782		this.megaMenuItem.right($elem);
9783	},
9784	down: function ($elem) {
9785		this.megaMenuItem.down($elem);
9786	},
9787	space: function ($elem) {
9788		return this.megaMenuItem.space($elem);
9789    },
9790    tab: function ($elem) {
9791        return this.megaMenuItem.tab($elem);
9792    }
9793};
9794
9795//Format 1,2,3,4 concrete implementation
9796var FormatedMegaMenu = function () {
9797	// Navigate to root mega menu item
9798	var focusRootMegaMenuItem = function ($elem) {
9799		var closestMenu = $elem.closest('.mainNavMegaMenu');
9800		if (closestMenu.length > 0) {
9801			var rootItem = closestMenu.attr('id');
9802			if (rootItem && rootItem.startsWith('mainNavMegaMenu')) {
9803				rootItem = rootItem.slice('mainNavMegaMenu'.length);
9804				if (!isNaN(parseInt(rootItem))) {
9805					var $rootAnchor = $('#MainItem' + rootItem + ' a');
9806					if ($rootAnchor.length > 0) {
9807						$rootAnchor.focus();
9808						return true;
9809					}
9810				}
9811			}
9812		}
9813		return false;
9814	};
9815
9816	// Check if element is in mega menu header
9817	var isMegaMenuHeader = function ($elem) {
9818		return $elem.closest("header").length > 0;
9819	};
9820
9821	var getWidgetRoot = function ($elem) {
9822		return accessibleMenuToggleEnabled ? $elem.closest('.widgetPages') : $elem.closest('section');
9823	};
9824
9825	// Focus element if it exists
9826	var focusIfExists = function ($target) {
9827		if ($target && $target.length > 0) {
9828			$target.focus();
9829			return true;
9830		}
9831		return false;
9832	};
9833
9834	// Find previous widget item for up navigation
9835	var findPreviousWidgetItem = function ($elem) {
9836		var $prevLi = $elem.closest('li').prev('li');
9837		if (!$prevLi.hasClass('widgetItem')) {
9838			return $prevLi.find('a:first');
9839		}
9840		
9841		// If previous has children, go to last child, otherwise go to previous item
9842		if ($prevLi.children('ol').length > 0) {
9843			return $prevLi.children('ol').children('li:last').find('a:first');
9844		}
9845		return $prevLi.find('a:first');
9846	};
9847
9848	// Find next widget item for down navigation
9849	var findNextWidgetItem = function ($elem, isWidgetItemElement) {
9850		if (isWidgetItemElement) {
9851			// If has children, go to first child, otherwise go to next sibling
9852			var $children = $elem.closest('li').children('ol');
9853			if ($children.length > 0) {
9854				return $children.children('li:first').children('a');
9855			}
9856			return $elem.closest('li').next('li').find('a:first');
9857		}
9858		
9859		// Try next sibling first
9860		var $target = $elem.closest('li').next('li').find('a:first');
9861		// If no sibling, try next widget item
9862		if ($target.length === 0) {
9863			$target = $elem.parents('li.widgetItem').next('li').find('a:first');
9864		}
9865		return $target;
9866	};
9867
9868	// Check if element is at a specific position in the mega menu
9869	var isItemAtPosition = function ($elem, position) {
9870		var $megaMenuContainer = $elem.closest('.mainNavMegaMenu');
9871		if ($megaMenuContainer.length === 0)
9872			return false;
9873
9874		// Find the link at the specified position (first or last)
9875		var $targetLink = $megaMenuContainer.find('a[role="menuitem"]')[position]();
9876		return $targetLink.length > 0 && $targetLink[0] === $elem[0];
9877	};
9878
9879	var isFirstItemInFirstColumn = function ($elem) {
9880		return isItemAtPosition($elem, 'first');
9881	};
9882
9883	var isLastItemInLastColumn = function ($elem) {
9884		return isItemAtPosition($elem, 'last');
9885	};
9886
9887	// Navigate to adjacent top-level menu item (mega menu or normal menu)
9888	var navigateToAdjacentMegaMenu = function ($elem, direction) {
9889		var topLevelParentId = menuManager.findTopLevelParentId($elem);
9890		if (!topLevelParentId) return false;
9891
9892		var $currentTopLevelItem = $('#' + topLevelParentId);
9893		if ($currentTopLevelItem.length === 0) return false;
9894
9895		var menuDirection = direction === 'left' ? 'prev' : 'next';
9896		var $targetTopLevelItem = menuManager.getAdjacentTopLevelItem($currentTopLevelItem, menuDirection);
9897		if ($targetTopLevelItem.length === 0) return false;
9898
9899		var $targetAnchor = $targetTopLevelItem.find('a:first');
9900		if ($targetAnchor.length === 0) return false;
9901
9902		// Close current mega menu
9903		var $currentMegaMenu = $elem.closest('.mainNavMegaMenu');
9904		if ($currentMegaMenu.length > 0) {
9905			$currentMegaMenu.removeClass('hover');
9906			menuManager.menuMouseOut($currentTopLevelItem);
9907		}
9908
9909		var isMegaMenu = $targetTopLevelItem.attr('data-displaymegamenu') === 'True';
9910		menuManager.menuMouseOver($targetTopLevelItem);
9911
9912		setTimeout(function () {
9913			if (isMegaMenu || menuManager.isSubMenuTrigger($targetAnchor)) {
9914				menuManager.setFocusToFirstSubmenuitem($targetAnchor);
9915			}
9916		}, 300);
9917
9918		return true;
9919	};
9920
9921	this.left = function ($elem) {
9922		if (menuManager.isTopLevelMenuItem($elem)) {
9923			menuManager.handleLeftKeyOnAnyTopLevelItem($elem);
9924			return;
9925		}
9926
9927		// Check if we're at the first item in the first column
9928		if (accessibleMenuToggleEnabled && isFirstItemInFirstColumn($elem)) {
9929			navigateToAdjacentMegaMenu($elem, 'left');
9930			return;
9931		}
9932
9933		// Navigate within mega menu columns
9934		var $prev = $elem.closest('div.col').prev().find('li.widgetItem:first').find('a:first');
9935		if ($prev.length > 0) {
9936			$prev.focus();
9937		} else {
9938			focusRootMegaMenuItem($elem);
9939		}
9940	};
9941
9942	this.up = function ($elem) {
9943		if (menuManager.isTopLevelMenuItem($elem)) {
9944			if (!menuManager.handleUpKeyOnTopLevelItem($elem)) {
9945				var id = $elem.closest('li').attr('id');
9946				$('#mainNavMegaMenu' + id).removeClass('hover');
9947				menuManager.menuMouseOut($elem.closest('li'));
9948			}
9949			return;
9950		}
9951
9952		// Check if this is the first item in a widget list
9953		var isWidgetItemElement = $elem.closest('li').hasClass('widgetItem');
9954		var isFirstInWidgetList = isWidgetItemElement && 
9955			$elem[0] == $elem.closest('li').parent('ol').children('li:first').find('a:first')[0];
9956
9957		if (isFirstInWidgetList) {
9958			if (accessibleMenuToggleEnabled) {
9959				focusRootMegaMenuItem($elem);
9960			} else {
9961				var $headerLink = getWidgetRoot($elem).find("header a");
9962				focusIfExists($headerLink);
9963			}
9964			return;
9965		}
9966
9967		// Check if first item in parent list
9968		var $parentOl = $elem.closest('li').parent('ol');
9969		if ($parentOl.length > 0 && $parentOl.children('li:first').children('a')[0] == $elem[0]) {
9970			var $parentLink = $parentOl.parent('li').find('a:first');
9971			focusIfExists($parentLink);
9972			return;
9973		}
9974
9975		// Navigate to previous widget item
9976		var $target = findPreviousWidgetItem($elem);
9977		focusIfExists($target);
9978	};
9979
9980	this.right = function ($elem) {
9981		if (menuManager.isTopLevelMenuItem($elem)) {
9982			menuManager.handleRightKeyOnAnyTopLevelItem($elem);
9983			return;
9984		}
9985
9986		// Check if we're at the last item in the last column
9987		if (accessibleMenuToggleEnabled && isLastItemInLastColumn($elem)) {
9988			navigateToAdjacentMegaMenu($elem, 'right');
9989			return;
9990		}
9991
9992		// In mega menu content - navigate to next column
9993		var $next = $elem.closest('div.col').next().find('li.widgetItem:first').find('a:first');
9994		if ($next.length > 0) {
9995			$next.focus();
9996		}
9997	};
9998
9999	this.down = function ($elem) {
10000		// Handle top-level menu items
10001		if ($elem.hasClass('navMainItem')) {
10002			if (!menuManager.handleDownKeyOnTopLevelItem($elem)) {
10003				// Legacy behavior - find first link in mega menu
10004				var $parentLi = $elem.parent('li');
10005				var $parentId = "mainNavMegaMenu" + $parentLi.attr('data-pageid');
10006				var $firstLink = accessibleMenuToggleEnabled
10007					? $('aside[id=' + $parentId + '] a[role="menuitem"]').first()
10008					: $('aside[id=' + $parentId + '] header a[role="menuitem"]').first();
10009				focusIfExists($firstLink);
10010			}
10011			return;
10012		}
10013
10014		// Navigate down in mega menu content
10015		var isWidgetItemElement = $elem.closest('li').hasClass('widgetItem');
10016		var $target = findNextWidgetItem($elem, isWidgetItemElement);
10017		focusIfExists($target);
10018	};
10019
10020	this.exitMegaMenu = function ($elem) {
10021		var asideContainerId = $elem.parents('.megaMenuContainer.megaMenu').attr('id').slice('mainNavMegaMenu'.length);
10022		var $li = $('#MainItem' + asideContainerId);
10023		$elem.parents('.megaMenuContainer.megaMenu').removeClass('hover');
10024		menuManager.menuMouseOut($li);
10025		$elem.focus();
10026	};
10027	this.space = function ($elem) {
10028		if (accessibleMenuToggleEnabled && !menuManager.isSubMenuTrigger($elem)) {
10029			$elem[0].click();
10030			return true;
10031		}
10032    };
10033    this.tab = function ($elem) {
10034        menuManager.setFocusToLastTopLevelItem();
10035
10036        // Return false to allow default tab behavior (focus moves to next focusable element outside menu)
10037        return false;
10038    };
10039};
10040
10041//Self invloked function
10042(function () {
10043	$(document).on('focusin', '.megaMenuContainer div.widgetTitle, .megaMenuContainer header a, #mainNav a.navMainItem , li.megaMenuItem a[role]', function (e) {
10044		var $this = $(this);
10045		var execute = true;
10046		var topMenuItem = $this.hasClass('navMainItem');
10047		if (topMenuItem) {
10048			var $parent = $this.parent('li');
10049			if ($parent != null) {
10050				//Logic for flyout menu is in AccessibleMenu.js, so do not execute the logic below for the same
10051				if ($parent.data('displaymegamenu') == 'False')
10052					execute = false;
10053			}
10054		}
10055		if (execute) {
10056			var depth = $this.parents('.widgetPages').find('.depth').html();
10057			var cols = $this.parents('.widgetPages').find('.cols').html();
10058			var accessibleMegaMenu = new AccessibleMegaMenu();
10059			var mainMenuItem = true;
10060			//If top menu item(and has megamenu which is already checked above), replicate the logic for "mouse near" to load the mega menus
10061			if (topMenuItem) {
10062				var megaMenuContentContainers = $('[data-displaymegamenu="True"]')
10063					.map(function () {
10064						$('#mainNavMegaMenu' + $(this).data('pageid') + ' div.pageContent').html('Loading...');
10065						return $('#mainNavMegaMenu' + $(this).data('pageid') + ' div.pageContent').data('containerid');
10066					}).toArray();
10067				reloadSharedContentContainers(megaMenuContentContainers);
10068			}
10069			accessibleMegaMenu.initialize(depth, cols);
10070			accessibleMegaMenu.bindHandlers($this);
10071		}
10072	});
10073}());
10074;
10075/*Strategy pattern
10076AccessibleAccordionMenu: Self-contained module for handling accordion menu keyboard navigation
10077Moved from AccessibleMenu.js for better maintainability
10078*/
10079
10080var AccessibleAccordionMenu = function () {
10081	this.accordionMenuItem = "";
10082};
10083
10084//Static field for accordion menu navigation stack
10085AccessibleAccordionMenu.accordionMenuStack = [];
10086
10087AccessibleAccordionMenu.prototype = {
10088	initialize: function () {
10089		this.setStrategy(new AccordionMenu());
10090	},
10091	setStrategy: function (accordionMenuItem) {
10092		this.accordionMenuItem = accordionMenuItem;
10093	},
10094	bindHandlers: function ($elem) {
10095		var self = this;
10096		var LEFT = 37;
10097		var UP = 38;
10098		var RIGHT = 39;
10099		var DOWN = 40;
10100		var ENTER = 13;
10101		var SPACE = 32;
10102		var TAB = 9;
10103
10104		$elem.off('keydown.AccordionMenu').on('keydown.AccordionMenu', function (e) {
10105			if (e.which === LEFT) {
10106				self.left($elem);
10107				e.preventDefault();
10108			}
10109			if (e.which === UP) {
10110				self.up($elem);
10111				e.preventDefault();
10112			}
10113			if (e.which === RIGHT) {
10114				self.right($elem);
10115				e.preventDefault();
10116			}
10117			if (e.which === DOWN) {
10118				self.down($elem);
10119				e.preventDefault();
10120			}
10121			if (e.which === ENTER || e.which === SPACE) {
10122				if (self.enter($elem)) {
10123					e.preventDefault();
10124				}
10125			}
10126			if (e.which === TAB) {
10127				if (self.tab($elem)) {
10128					e.preventDefault();
10129				}
10130			}
10131		});
10132	},
10133	left: function ($elem) {
10134		this.accordionMenuItem.left($elem);
10135	},
10136	up: function ($elem) {
10137		this.accordionMenuItem.up($elem);
10138	},
10139	right: function ($elem) {
10140		this.accordionMenuItem.right($elem);
10141	},
10142	down: function ($elem) {
10143		this.accordionMenuItem.down($elem);
10144	},
10145	enter: function ($elem) {
10146		return this.accordionMenuItem.enter($elem);
10147	},
10148	tab: function ($elem) {
10149		return this.accordionMenuItem.tab($elem);
10150	}
10151};
10152
10153//AccordionMenu concrete implementation
10154var AccordionMenu = function () {
10155
10156	var getAdjacentAccordionTopLevelItem = function ($currentLi, direction) {
10157		var $targetLi = direction === 'prev' ? $currentLi.prev('.topMenuItem') : $currentLi.next('.topMenuItem');
10158
10159		// If no adjacent sibling found, wrap around
10160		if ($targetLi.length === 0) {
10161			var $siblings = $currentLi.parent().children('.topMenuItem');
10162			$targetLi = direction === 'prev' ? $siblings.last() : $siblings.first();
10163		}
10164
10165		return $targetLi;
10166	};
10167
10168	var isMainLevelAccordionItem = function ($elem) {
10169		return $elem.hasClass('navMainItem') && $elem.hasClass('secondaryNavItem');
10170	};
10171
10172	var isTopLevelToggle = function ($elem) {
10173		return $elem.hasClass('accordionSecondaryNavItem');
10174	};
10175
10176	var isNestedToggle = function ($elem) {
10177		return $elem.hasClass('accordionNavMenuItem');
10178	};
10179
10180	var isSubmenuLink = function ($elem) {
10181		return $elem.hasClass('navMenuItem');
10182	};
10183
10184	var focusElement = function ($elem) {
10185		if ($elem && $elem.length > 0) {
10186			$elem.focus();
10187			return true;
10188		}
10189		return false;
10190	};
10191
10192    var hasOpenedSubmenuInCurrentContext = function ($elem) {
10193        // Check if the currently focused main-level item has an opened submenu directly under it
10194        if (!isMainLevelAccordionItem($elem)) {
10195            return false;
10196        }
10197        
10198        var $parentTopMenuItem = $elem.closest('.topMenuItem');
10199        if ($parentTopMenuItem.length > 0) {
10200            var $openedSubmenu = $parentTopMenuItem.children('.accordionNavContainer:visible');
10201            return $openedSubmenu.length > 0;
10202        }
10203        return false;
10204    };
10205
10206    var getParentToggleButton = function ($parentSubmenu) {
10207        var $parentNavItemDiv = $parentSubmenu.siblings('.accordionNavItem');
10208        return $parentNavItemDiv.find('a.openAccordionNav');
10209    };
10210
10211    var navigateToAdjacentSibling = function ($currentMenuItem, direction, shouldPushToStack, $currentElem) {
10212        var $siblingLi = direction === 'next' 
10213            ? $currentMenuItem.next('li[role=menuitem]')
10214            : $currentMenuItem.prev('li[role=menuitem]');
10215
10216        if ($siblingLi.length > 0) {
10217            if (shouldPushToStack && $currentElem) {
10218                AccessibleAccordionMenu.accordionMenuStack.push($currentElem);
10219            }
10220            focusElement($siblingLi.find('a:first'));
10221            return true;
10222        }
10223        return false;
10224    };
10225
10226    // Helper: Navigate to parent level when no sibling exists
10227    var navigateToParentLevel = function ($currentMenuItem, direction, shouldPushToStack, $currentElem) {
10228        var $parentSubmenu = $currentMenuItem.parent('.accordionNavContainer');
10229        if ($parentSubmenu.length === 0) {
10230            return false;
10231        }
10232
10233        var $grandParentMenuItem = $parentSubmenu.parent('[role=menuitem]');
10234        if ($grandParentMenuItem.length === 0) {
10235            return false;
10236        }
10237
10238        if (direction === 'next') {
10239            // Moving down - go to parent's next sibling
10240            var $parentNextSibling = $grandParentMenuItem.next('li[role=menuitem]');
10241            if ($parentNextSibling.length > 0) {
10242                if (shouldPushToStack && $currentElem) {
10243                    AccessibleAccordionMenu.accordionMenuStack.push($currentElem);
10244                }
10245                focusElement($parentNextSibling.find('a:first'));
10246                return true;
10247            }
10248
10249            // No parent sibling - move to top-level's next item
10250            var $topMenuItem = $grandParentMenuItem.closest('.topMenuItem');
10251            if ($topMenuItem.length > 0) {
10252                var $nextTopMenuItem = getAdjacentAccordionTopLevelItem($topMenuItem, 'next');
10253                if (shouldPushToStack && $currentElem) {
10254                    AccessibleAccordionMenu.accordionMenuStack.push($currentElem);
10255                }
10256                focusElement($nextTopMenuItem.find('a.navMainItem:first'));
10257                return true;
10258            }
10259        } else {
10260            // Moving up - go to parent's toggle button
10261            var $parentToggleButton = getParentToggleButton($parentSubmenu);
10262            if ($parentToggleButton.length > 0 && $parentToggleButton.hasClass('accordionNavOpened')) {
10263                focusElement($parentToggleButton);
10264                return true;
10265            }
10266        }
10267
10268        return false;
10269    };
10270
10271    var closeSiblingSubmenus = function ($currentMenuItem) {
10272        var $siblings = $currentMenuItem.siblings('li[role=menuitem]');
10273        
10274        $siblings.each(function() {
10275            var $siblingToggle = $(this).find('> .accordionNavItem > a.openAccordionNav');
10276            if ($siblingToggle.length > 0 && $siblingToggle.hasClass('accordionNavOpened')) {
10277                $siblingToggle[0].click();
10278            }
10279        });
10280    };
10281
10282    // Top-level toggle (accordionSecondaryNavItem) arrow handling
10283    var handleTopLevelToggleUp = function ($elem) {
10284        var $currentTopMenuItem = $elem.closest('.topMenuItem');
10285
10286        // If submenu is open, close it first
10287        if ($elem.hasClass('accordionNavOpened')) {
10288            $elem[0].click();
10289        }
10290
10291        var $prevTopMenuItem = getAdjacentAccordionTopLevelItem($currentTopMenuItem, 'prev');
10292        focusElement($prevTopMenuItem.find('a.navMainItem:first'));
10293    };
10294
10295    var handleTopLevelToggleDown = function ($elem) {
10296        var $parentMenuItem = $elem.closest('[role=menuitem]');
10297
10298        // If submenu is open, move INTO the submenu (don't close)
10299        if ($elem.hasClass('accordionNavOpened')) {
10300            var $submenu = $parentMenuItem.children('.accordionNavContainer');
10301            if ($submenu.length > 0 && $submenu.is(':visible')) {
10302                var $firstSubmenuItem = $submenu.children('[role=menuitem]:first').find('a:first');
10303                if ($firstSubmenuItem.length > 0) {
10304                    AccessibleAccordionMenu.accordionMenuStack.push($elem);
10305                    focusElement($firstSubmenuItem);
10306                    return;
10307                }
10308            }
10309        }
10310
10311        // Submenu not open or no children: go to next top-level
10312        var $nextTopMenuItem = getAdjacentAccordionTopLevelItem($parentMenuItem, 'next');
10313        focusElement($nextTopMenuItem.find('a.navMainItem:first'));
10314    };
10315
10316    // Nested toggle (accordionNavMenuItem) arrow handling
10317    var handleNestedToggleUp = function ($elem) {
10318        var $parentMenuItem = $elem.closest('[role=menuitem]');
10319
10320        // If submenu is open, close it first
10321        if ($elem.hasClass('accordionNavOpened')) {
10322            $elem[0].click();
10323        }
10324
10325        // Try previous sibling first; if none, go to parent level
10326        if (navigateToAdjacentSibling($parentMenuItem, 'prev', false, null)) {
10327            return;
10328        }
10329        navigateToParentLevel($parentMenuItem, 'prev', false, null);
10330    };
10331
10332    var handleNestedToggleDown = function ($elem) {
10333        var $parentMenuItem = $elem.closest('[role=menuitem]');
10334
10335        // If submenu is open, move INTO the submenu (don't close)
10336        if ($elem.hasClass('accordionNavOpened')) {
10337            var $submenu = $parentMenuItem.children('.accordionNavContainer');
10338            if ($submenu.length > 0 && $submenu.is(':visible')) {
10339                var $firstSubmenuItem = $submenu.children('[role=menuitem]:first').find('a:first');
10340                if ($firstSubmenuItem.length > 0) {
10341                    AccessibleAccordionMenu.accordionMenuStack.push($elem);
10342                    focusElement($firstSubmenuItem);
10343                    return;
10344                }
10345            }
10346        }
10347
10348        // Submenu not open - try next sibling; else parent level
10349        if (navigateToAdjacentSibling($parentMenuItem, 'next', false, null)) {
10350            return;
10351        }
10352        navigateToParentLevel($parentMenuItem, 'next', false, null);
10353    };
10354
10355    // Submenu link (navMenuItem) arrow handling
10356    var handleSubmenuItemUp = function ($elem) {
10357        var $currentMenuItem = $elem.closest('[role=menuitem]');
10358        var $parentSubmenu = $currentMenuItem.parent('.accordionNavContainer');
10359
10360        if ($parentSubmenu.length === 0) return;
10361
10362        // If this is first item, go to its toggle
10363        var $firstItem = $parentSubmenu.children('[role=menuitem]:first');
10364        if ($firstItem.length > 0 && $currentMenuItem[0] === $firstItem[0]) {
10365            var $parentToggleButton = getParentToggleButton($parentSubmenu);
10366            if ($parentToggleButton.length > 0 && $parentToggleButton.hasClass('accordionNavOpened')) {
10367                focusElement($parentToggleButton);
10368                return;
10369            }
10370        }
10371
10372        // Otherwise go to previous sibling
10373        navigateToAdjacentSibling($currentMenuItem, 'prev', false, null);
10374    };
10375
10376    var handleSubmenuItemDown = function ($elem) {
10377        var $currentMenuItem = $elem.closest('[role=menuitem]');
10378
10379        // Try next sibling first
10380        if (navigateToAdjacentSibling($currentMenuItem, 'next', true, $elem)) {
10381            return;
10382        }
10383
10384        // No sibling - go to parent level
10385        navigateToParentLevel($currentMenuItem, 'next', true, $elem);
10386    };
10387
10388    this.left = function ($elem) {
10389        //do nothing
10390    };
10391
10392    this.up = function ($elem) {
10393        // Top-level toggle
10394        if (isTopLevelToggle($elem)) {
10395            handleTopLevelToggleUp($elem);
10396            return;
10397        }
10398
10399        // Nested toggle
10400        if (isNestedToggle($elem)) {
10401            handleNestedToggleUp($elem);
10402            return;
10403        }
10404
10405        // Submenu link
10406        if (isSubmenuLink($elem)) {
10407            handleSubmenuItemUp($elem);
10408            return;
10409        }
10410
10411        // Main-level text links (navMainItem)
10412        if (isMainLevelAccordionItem($elem)) {
10413            if (AccessibleAccordionMenu.accordionMenuStack.length > 0) {
10414                var $popped = AccessibleAccordionMenu.accordionMenuStack.pop();
10415                if ($popped) {
10416                    $popped.focus();
10417                }
10418                return;
10419            }
10420            var $currentTopMenuItem = $elem.parents('.topMenuItem:first');
10421            var $prevTopMenuItem = getAdjacentAccordionTopLevelItem($currentTopMenuItem, 'prev');
10422            focusElement($prevTopMenuItem.find('a.navMainItem:first'));
10423            return;
10424        }
10425
10426        // Fallback to stack for any other element
10427        var $poppedFallback = AccessibleAccordionMenu.accordionMenuStack.pop();
10428        if ($poppedFallback) {
10429            $poppedFallback.focus();
10430        }
10431    };
10432
10433    this.right = function ($elem) {
10434        //do nothing
10435    };
10436
10437    this.down = function ($elem) {
10438        // Top-level toggle
10439        if (isTopLevelToggle($elem)) {
10440            handleTopLevelToggleDown($elem);
10441            return;
10442        }
10443
10444        // Nested toggle
10445        if (isNestedToggle($elem)) {
10446            handleNestedToggleDown($elem);
10447            return;
10448        }
10449
10450        // Submenu link
10451        if (isSubmenuLink($elem)) {
10452            handleSubmenuItemDown($elem);
10453            return;
10454        }
10455
10456        // Main-level text links (navMainItem) when no submenu is open
10457        if (isMainLevelAccordionItem($elem) && !hasOpenedSubmenuInCurrentContext($elem)) {
10458            var $currentTopMenuItem = $elem.parents('.topMenuItem:first');
10459            var $nextTopMenuItem = getAdjacentAccordionTopLevelItem($currentTopMenuItem, 'next');
10460            focusElement($nextTopMenuItem.find('a.navMainItem:first'));
10461            return;
10462        }
10463
10464        // Original behavior for nested/other items
10465        AccessibleAccordionMenu.accordionMenuStack.push($elem);
10466        var hasAccordionSubmenu = $elem.next('a.openAccordionNav').length > 0;
10467        var accordionSubmenuAlreadyOpen = $elem.next('a.openAccordionNav').hasClass('accordionNavOpened');
10468        var $nextElementToFocus = '';
10469
10470        if (hasAccordionSubmenu && !accordionSubmenuAlreadyOpen) {
10471            $nextElementToFocus = $elem.parents('.topMenuItem').next('li').find('a:first');
10472            if ($nextElementToFocus.length > 0) {
10473                $nextElementToFocus.focus();
10474            }
10475            return;
10476        }
10477
10478        if (hasAccordionSubmenu) {
10479            $nextElementToFocus = $elem.parents('[role=menuitem]:first').children('ol.accordionNavContainer').find('a:first');
10480            if ($nextElementToFocus.length > 0) {
10481                $nextElementToFocus.focus();
10482            }
10483        } else {
10484            var $nextSiblingLi = $elem.parents('[role=menuitem]').next('li:first');
10485            if ($nextSiblingLi && $nextSiblingLi.length > 0) {
10486                $nextElementToFocus = $nextSiblingLi.find('a:first');
10487                if ($nextElementToFocus.length > 0) {
10488                    $nextElementToFocus.focus();
10489                }
10490            } else {
10491                $nextElementToFocus = $elem.parents('.topMenuItem').next('li').find('a:first');
10492                if ($nextElementToFocus.length > 0) {
10493                    $nextElementToFocus.focus();
10494                }
10495            }
10496        }
10497    };
10498
10499    this.enter = function ($elem) {
10500        // Focus is on accordion toggle button (+/- or arrow)
10501        if ($elem.hasClass('openAccordionNav')) {
10502            var $parentMenuItem = $elem.closest('[role=menuitem]');
10503            
10504            // If toggle is currently closed (will be opened), close sibling submenus first
10505            if (!$elem.hasClass('accordionNavOpened')) {
10506                closeSiblingSubmenus($parentMenuItem);
10507            }
10508            
10509            $elem[0].click();
10510            return true;
10511        }
10512
10513        if (isMainLevelAccordionItem($elem)) {
10514            $elem[0].click();
10515            return true;
10516        }
10517
10518        if (isSubmenuLink($elem)) {
10519            $elem[0].click();
10520            return true;
10521        }
10522
10523        return false;
10524    };
10525
10526    this.tab = function ($elem) {
10527        return false;
10528    };
10529};
10530
10531//Self invoked function
10532(function () {
10533	function accordionMenuHandler(e) {
10534		var $this = $(this);
10535
10536		var accessibleAccordionMenu = new AccessibleAccordionMenu();
10537		var $topmostAccordionMenuItem = $this.parents('nav').find('a:first');
10538
10539		if ($this[0] === $topmostAccordionMenuItem[0]) {
10540			AccessibleAccordionMenu.accordionMenuStack = [];
10541		}
10542
10543		accessibleAccordionMenu.initialize();
10544		accessibleAccordionMenu.bindHandlers($this);
10545	}
10546
10547	$(document).on("focusin", ".accordionNav a.navMainItem, .accordionNav a.navMenuItem, .accordionNav a.openAccordionNav", accordionMenuHandler);
10548}());
10549var AccessibleAnchors = function () {
10550	
10551};
10552
10553AccessibleAnchors.prototype =
10554{
10555	configure: function (config) {
10556		var self = this;
10557		self.OPEN_IN_NEW_WINDOW_TEXT = ' Opens in new window';
10558		if (config.type === 'popup') {
10559			this.bindPopupHandlers(self);
10560		}
10561		if (config.type === 'extend') {
10562			this.bindExtendHandlers(self);
10563		}
10564		if (config.type === 'both') {
10565			this.bindPopupHandlers(self);
10566			this.bindExtendHandlers(self);
10567		}
10568		$(document).ready(function () {
10569			var anchors_TargetBlank = $('a[target=_blank]');
10570			$.each(anchors_TargetBlank, function () {
10571				var $this = $(this);
10572				self.setAriaLabelAndAlt($this);
10573			});
10574		});
10575	},
10576	bindExtendHandlers: function (self) {
10577		$('a[target=_blank]').on("focusin mouseenter", function (e) {
10578			var $this = $(this);
10579			self.setAriaLabelAndAlt($this);
10580		});		
10581	},
10582	setAriaLabelAndAlt: function ($this) {
10583		//If anchor has an image inside it
10584		if (this.hasImage($this)) {
10585			var $img = $this.children('img');
10586			if ($img.length == 0)
10587				$img = $this.children('span').children('img');
10588			var alt = $img.attr('alt');
10589			if (alt) {
10590				if (alt.indexOf(this.OPEN_IN_NEW_WINDOW_TEXT) === -1)
10591					$img.attr('alt', alt + this.OPEN_IN_NEW_WINDOW_TEXT);
10592			}
10593			else {
10594				$img.attr('alt', $img.attr('title') + this.OPEN_IN_NEW_WINDOW_TEXT);
10595			}
10596			this.setAriaLabel($this, $img.attr('alt'));
10597		}
10598		else {
10599			this.setAriaLabel($this, $this.text() + this.OPEN_IN_NEW_WINDOW_TEXT);
10600		}
10601	},
10602	bindPopupHandlers: function (self) {
10603		$('a[target=_blank]').on("focusin mouseenter", function (e) {
10604			var $this = $(this);
10605			$this.trigger('focusout');
10606			$this.append($('<span aria-hidden="false" aria-label="opens in new window" title="opens in new window" class="newWindowIndicator"></span>'));
10607		});	
10608
10609		$('a[target=_blank]').on("focusout mouseleave", function (e) {
10610			$('.newWindowIndicator').remove();
10611		});		
10612	},
10613	setAriaLabel: function($anchor, ariaLabelText){
10614		var ariaLabel = $anchor.attr('aria-label');
10615		if (ariaLabel) {
10616			if (ariaLabel.indexOf(this.OPEN_IN_NEW_WINDOW_TEXT) == -1)
10617				$anchor.attr('aria-label', ariaLabelText);
10618		}
10619		else {
10620			$anchor.attr('aria-label', ariaLabelText);
10621		}
10622	},
10623	hasImage: function ($anchor) {
10624		var hasImage = false;
10625		if ($anchor.children('img') != null && $anchor.children('img').length > 0)
10626			return true;
10627		else if ($anchor.children('span') != null && $anchor.children('span').length > 0) {
10628			return $anchor.children('span').children('img') != null && $anchor.children('span').children('img').length > 0;
10629		}
10630	}
10631
10632};
10633
10634//Self invloked function
10635(function () {
10636	//Add a warning span to body for anchors that open in new window
10637	$(
10638		new AccessibleAnchors().configure({ type: 'extend' })
10639	);
10640}());
10641
10642
10643
10644;
10645/* File Created: February 11, 2013 by Vishal Bhatia*/
10646
10647function rearrangeFlyouts(clearDOM) {
10648    if (clearDOM) {
10649        //Remove any old .pop elements from the DOM to reload the new one.
10650        $('.flyOut.moved').remove();
10651    }
10652    //Grab all the flyouts that are not moved yet and are not tooltips and not in WidgetManager
10653    var $flyOutDivs = $('.flyOut').not('.moved').not('.helpTip').not('.widgetManager');
10654    var parentID;
10655    var marginLeft, marginTop;
10656    $flyOutDivs.each(function (e) {
10657        parentID = $(this).parent('.flyOutParent').attr('id');
10658
10659        //If the element does not have a flyOutParent, display it on the center of the screen.
10660        if (parentID == undefined) {
10661            marginLeft = '-' + $(this).outerWidth() / 2 + 'px';
10662            marginTop = '-' + $(this).outerHeight() / 2 + 'px';
10663
10664            $(this).css('left', '50%');
10665            $(this).css('margin-left', marginLeft);
10666            $(this).css('top', '50%');
10667            $(this).css('margin-top', marginTop);
10668
10669            $(this).appendTo('body');
10670            $(this).addClass('moved');
10671            //TODO: Confirm from Kyle and remove 2 lines below since they are being done through css.
10672            $(this).css('position', 'absolute');
10673            $(this).css('z-index', '100');
10674        }
10675        else {
10676            //Remove any pre existing copies of this element from the DOM.
10677        	$('[data-parentID=' + parentID + ']').remove();
10678			//Remove margin styles if the element has a flyOutParent.
10679            $(this).css({ 'margin-left': '', 'margin-top': '' });
10680            $(this).appendTo('body');
10681            $(this).addClass('moved');
10682            //TODO: Confirm from Kyle and remove 2 lines below since they are being done through css.
10683            $(this).css('position', 'absolute');
10684            $(this).css('z-index', '100');
10685            $(this).attr('data-parentID', parentID);
10686            adjustFlyoutPosition($('#' + parentID), $(this));
10687        }
10688    });
10689}
10690
10691///Executes when the browser is being resized or the screen orientation changes(portrait/landscape).
10692function rearrangeFlyoutsOnResizeEvents() {
10693	//Grab all the flyouts that are not moved yet and are not tooltips and not in WidgetManager
10694	var $flyOutDivs = $('.flyOut').not('.helpTip').not('.widgetManager').not('.mainNavMegaMenu.megaMenuContainer');;
10695	var parentID;
10696	var marginLeft, marginTop;
10697	$flyOutDivs.each(function (e) {
10698		parentID = $(this).data('parentid');
10699		//If the element does not have a flyOutParent, display it on the center of the screen.
10700		if (parentID == undefined) {
10701			marginLeft = '-' + $(this).outerWidth() / 2 + 'px';
10702			marginTop = '-' + $(this).outerHeight() / 2 + 'px';
10703			$(this).css('margin-left', marginLeft);
10704			$(this).css('margin-top', marginTop);
10705		}
10706		else {			
10707			adjustFlyoutPosition($('#' + parentID), $(this));
10708		}
10709	});
10710}
10711
10712///Checks if any ancestor of a flyout element is fixed positioned.
10713function anyAncestorFixedPositioned($parent) {
10714	var anyAncestorFixedPosition = false;
10715	if ($parent.css('position') === 'fixed')
10716		anyAncestorFixedPosition = true;
10717	if (!anyAncestorFixedPosition) {
10718		$parent.parents().each(function () {
10719			if (!anyAncestorFixedPosition) {
10720				if ($(this).css('position') === 'fixed')
10721					anyAncestorFixedPosition = true;
10722			}
10723		});
10724	}
10725	return anyAncestorFixedPosition;
10726}
10727
10728function adjustFlyoutPosition($parent, $this) {
10729    var $parentElem = $parent;    
10730    if ($parentElem != null) {        
10731        var parentWidth = $parent.outerWidth(false);
10732        var parentHeight = $parent.outerHeight(false);
10733        var offset = $parent.offset();        
10734        if (offset != null) {
10735            var offsetLeft = offset.left;
10736            //Take into account scroll height if the document has been scrolled, to compute the top distance from viewport. VB
10737            var offsetTop = $this.css('position') === 'fixed' ? offset.top - $(document).scrollTop() : offset.top; // Take into account if the item is fixed or absolutely positioned.                        
10738                        
10739			if (anyAncestorFixedPositioned($parent))
10740				$this.css('position', 'fixed');
10741
10742            var offsetRight;
10743            var offsetBottom;
10744
10745            if ($this.hasClass('left') || $this.hasClass('leftCorner')) {
10746                offsetLeft = offsetLeft - $this.outerWidth(false);
10747                $this.css('left', offsetLeft);
10748            }
10749
10750            if ($this.hasClass('right') || $this.hasClass('rightCorner')) {
10751                offsetLeft = offsetLeft + parentWidth;
10752                $this.css('left', offsetLeft);
10753            }
10754
10755            if ($this.hasClass('top') || $this.hasClass('topCorner')) {
10756                offsetBottom = offsetTop - $this.outerHeight(false);
10757                $this.css('top', offsetBottom);
10758            }
10759
10760            if ($this.hasClass('bottom') || $this.hasClass('bottomCorner')) {
10761                offsetTop = offsetTop + parentHeight;
10762                $this.css('top', offsetTop);                
10763            }
10764
10765            if ($this.hasClass('leftEdge')) {
10766                $this.css('left', offsetLeft);
10767
10768                if ($this.hasClass('rightEdge')) {
10769                    $this.css('width', parentWidth);
10770                }                
10771            }
10772
10773            if ($this.hasClass('rightEdge')) {
10774                offsetLeft = offsetLeft + parentWidth - $this.outerWidth(false);
10775                $this.css('left', offsetLeft);
10776            }
10777
10778            if ($this.hasClass('topEdge')) {
10779                $this.css('top', offsetTop);
10780
10781                if ($this.hasClass('bottomEdge')) {
10782                    $this.css('height', parentHeight);
10783                }
10784            }
10785
10786            if ($this.hasClass('bottomEdge')) {
10787                offsetTop = offsetTop + parentHeight - $this.outerHeight(false);                
10788                $this.css('top', offsetTop);
10789            }
10790
10791            if ($this.hasClass('center') && ($this.hasClass('top') || $this.hasClass('bottom'))) {
10792                offsetLeft = offsetLeft + (parentWidth / 2) - ($this.outerWidth(false) / 2);
10793                $this.css('left', offsetLeft);
10794            }
10795
10796            if ($this.hasClass('center') && ($this.hasClass('left') || $this.hasClass('right'))) {
10797                offsetTop = offsetTop + (parentHeight / 2) - ($this.outerHeight(false) / 2);
10798                $this.css('top', offsetTop);
10799            }
10800        }
10801    }
10802};
10803// Note some of this functionality is in Menu.js as well
10804
10805// Deferred Loading for mega menus
10806$(function () {
10807	"use strict";
10808
10809	var thisRef = {};
10810
10811	thisRef.initialized = false;
10812
10813	var LOAD_TRIGGER_DISTANCE = 200; // in px
10814	var $megaMenus = $('[data-displaymegamenu="True"]');
10815	function isNear(element, distance, event) {
10816		var left = element.offset().left - distance,
10817			top = element.offset().top - distance,
10818			right = left + element.width() + 2 * distance,
10819			bottom = top + element.height() + 2 * distance,
10820			x = event.pageX,
10821			y = event.pageY;
10822
10823		return (x > left && x < right && y > top && y < bottom);
10824	};
10825
10826	$('body:not(.mobile)').bind('mousemove.megaMenuLazyLoad', function (e) {
10827		$megaMenus.each(function (index) {
10828			var mouseIsNear = isNear($(this), LOAD_TRIGGER_DISTANCE, e);
10829			if (mouseIsNear) {
10830				if (!thisRef.initialized) {
10831					$('body').unbind('.megaMenuLazyLoad');
10832					thisRef.initialized = true;
10833					var megaMenuContentContainers = $('[data-displaymegamenu="True"]')
10834					.map(function () {
10835						$('#mainNavMegaMenu' + $(this).data('pageid') + ' div.pageContent').html('Loading...');
10836						return $('#mainNavMegaMenu' + $(this).data('pageid') + ' div.pageContent').data('containerid');
10837					}).toArray();
10838
10839					window.Pages.megaMenuLoaded.resolve();
10840					reloadSharedContentContainers(megaMenuContentContainers);
10841				}
10842			} 
10843		});
10844	});
10845});
10846
10847var reloadSharedContentContainers = function (containerIDs) {
10848	if (containerIDs.length > 0) {
10849		// Reload all mega menus?
10850		var url = getAbsoluteUrl('/Content/Load?contentCollectionID=' + $('#hdnContentCollectionID').val() + "&StructureID=" + $('#hdnStructureID').val() + "&themeID=" + $('#hdnThemeID').val());
10851		if ($('body').hasClass('preview'))
10852			url += "&preview=true";
10853		$.ajax({
10854			url: url,
10855			type: 'POST',
10856			data: JSON.stringify({ "contentContainerIDs": containerIDs }),
10857			contentType: 'application/json',
10858			cache: false,
10859			async: true,
10860			ignoreEditor: true, //prevent for executing global editor event
10861			error: function (xhr, textStatus, exception) {
10862				if (xhr.status != 0) {
10863					alert("Error: " + xhr.statusText + "\nStatus: " + xhr.status);
10864				}
10865			},
10866			success: function (response) {
10867				if (response.PageModified !== undefined && response.PageModified === true && response.PageModifiedMessage) {
10868					if (confirm(response.PageModifiedMessage)) {
10869						document.cookie = "refresh=true; max-age=5";
10870						location.reload();
10871					}
10872				}
10873				else if (response.ErrorMessage)
10874					alert(response.ErrorMessage);
10875				else {
10876					//Replace content containers HTML
10877					var root = document.createElement("div");
10878					root.innerHTML = response;
10879					$(root).find('#fb-root').remove();
10880					$('head').append($(root).find('.bundledStyles'));
10881					var allChilds = root.childNodes;
10882					for (var i = 0; i < containerIDs.length; i++) {
10883						var contentContainerID = containerIDs[i];
10884						//Grab Content Container HTML from response
10885						var contentContainerHtml = null;
10886						for (var j = 0; j < allChilds.length; j++) {
10887							if (allChilds[j].id && allChilds[j].id == 'cc' + contentContainerID) {
10888								contentContainerHtml = allChilds[j].outerHTML;
10889								break;
10890							}
10891						}
10892						if (contentContainerHtml != null) {
10893							var $contentContainer = $('#cc' + contentContainerID);
10894							$contentContainer.empty().replaceWith(contentContainerHtml);
10895						} else {
10896							//ContentContainer Html was not found. This might happen when we have a html version and switch (Refresh containers) to a linked version on the same page.
10897						}
10898					}
10899
10900					if (window.cpMedia) {
10901						$('.mainNavMegaMenu.megaMenuContainer').each(function () {
10902							applyElementQueryToChildren($(this));
10903						});
10904					}
10905
10906					//TODO: unbind/destroy events/drag/drop on elements before initialize containers
10907					if (typeof InitializeContainers == 'function' && getCookieValue("enableLiveEdit") === "true") {
10908						InitializeContainers({ hidePopover: false });
10909						$('.mainNavMegaMenu.megaMenuContainer').find('.pinned').removeClass('pinned');
10910						setTimeout(function () { // It is unfortunate to use  timeout here, but there is a very difficult to reproduce race condition in FF where it is still getting unpinned by something
10911							$('.mainNavMegaMenu.megaMenuContainer').find('.pinned').removeClass('pinned');
10912						},300);
10913					}
10914					if (menuManager && typeof menuManager.attachDragAndDropHandlers == 'function') {
10915						menuManager.attachDragAndDropHandlers();
10916					}
10917
10918					//Execute this function or else the click event wont be registered for tabbed widgets inside megamenus.
10919					Core.Layout.attachTabbedWidgetTabHandlers();
10920				}
10921			}
10922		});
10923	}
10924};
10925
10926// Handle touchstart event for touch devices. First click will load the megamenus if they haven't been loaded and show the mega menu. Second click will navigate to the menu link itself.
10927$('[data-displaymegamenu="True"]').bind('touchstart', function (e) {
10928	e.stopPropagation(); // prevent this event from bubbling up and triggering the handler on document below!
10929	if (($(this).closest('.mainNavHolderMobile')[0] !== undefined) || ($('body:not(.mobile)').length === 0)) { // Return if mobile menu is being shown
10930		return;
10931	}
10932	if (window.lastMegaMenuOpen === this) { // Used to do the second click navigation if the same menu is clicked twice.
10933		return;
10934	}
10935	e.preventDefault();
10936	if (!window.megaMenuInitializedForTouch) {
10937		$('body').unbind('.megaMenuLazyLoad');
10938		window.megaMenuInitializedForTouch = true;
10939		var megaMenuContentContainers = $('[data-displaymegamenu="True"]')
10940		.map(function () {
10941			$('#mainNavMegaMenu' + $(this).data('pageid') + ' div.pageContent').html('Loading...');
10942			return $('#mainNavMegaMenu' + $(this).data('pageid') + ' div.pageContent').data('containerid');
10943		}).toArray();
10944
10945		window.Pages.megaMenuLoaded.resolve();
10946		reloadSharedContentContainers(megaMenuContentContainers);
10947	}
10948
10949	menuManager.menuMouseOver($(this)); 
10950	window.lastMegaMenuOpen = this;
10951});
10952
10953$(document).bind('touchstart click', function (e) {
10954	if (window.lastMegaMenuOpen === undefined || window.lastMegaMenuOpen === this || !isResolvedOrState(window.Pages.megaMenuLoaded)) {
10955		return;
10956	}
10957	//Skip menumouseout method if user slide up the expanded mega menu to scroll
10958	if (!e.target.id.startsWith("mainNavMegaMenu")) {
10959		if (!$(e.target).parents("aside[id^='mainNavMegaMenu']").length) {
10960			menuManager.menuMouseOut($(window.lastMegaMenuOpen));
10961		}
10962	}
10963});
10964(function () {
10965	const focusableSelector = 'a:not([disabled]):not([aria-hidden="true"]),input:not([disabled]):not([type="hidden"])';
10966	const toggleEl = (target, toggleable) => {
10967		const display = target.getAttribute("aria-expanded") === "false";
10968		toggleable.style.display = display ? "block" : "none";
10969		target.setAttribute("aria-expanded", display);
10970
10971		if (display) {
10972			target.classList.add("active");
10973		} else {
10974			target.classList.remove("active");
10975		}
10976	};
10977
10978	const repositionPopover = (target) => {
10979		const elId = target.getAttribute("aria-controls");
10980		if (!elId) {
10981			return;
10982		}
10983
10984		const popover = document.getElementById(elId);
10985		if (!popover) {
10986			return;
10987		}
10988
10989		const popoverWidth = popover.offsetWidth;
10990		const rect = target.getBoundingClientRect();
10991		const targetHeight = target.offsetHeight;
10992		const distanceFromRight = window.innerWidth - rect.left;
10993		const parent = target.parentElement;
10994		const parentWidth = parent.offsetWidth;
10995
10996		if (distanceFromRight < popoverWidth && parentWidth < popoverWidth) {
10997			popover.classList.add("flip");
10998			const shift = parentWidth - popoverWidth;
10999			popover.style.left = `${shift}px`;
11000		} else {
11001			popover.classList.remove("flip");
11002			popover.style.left = `0px`;
11003		}
11004
11005		const parentRect = parent.getBoundingClientRect();
11006		const distanceFromParentBottom = parentRect.bottom - rect.bottom;
11007		popover.style.bottom = `${distanceFromParentBottom + targetHeight}px`;
11008		popover.style.zIndex = 1;
11009		popover.scrollIntoView({ behavior: "smooth", block: "center", inline: "nearest"});
11010	};
11011
11012	const handleCpNavKeydown = (event, focusables) => {
11013		if (focusables.length < 1) {
11014			return;
11015		}
11016
11017		const currentFocusedIndex = focusables.findIndex(element => element === document.activeElement);
11018		let nextFocusIndex = -1;
11019		switch (event.key) {
11020			case 'ArrowLeft':
11021			case 'ArrowUp':
11022				event.preventDefault();
11023				if (currentFocusedIndex > 0) {
11024					nextFocusIndex = currentFocusedIndex - 1;
11025				} else {
11026					nextFocusIndex = focusables.length - 1;
11027				}
11028				break;
11029			case 'ArrowRight':
11030			case 'ArrowDown':
11031				event.preventDefault();
11032				if (currentFocusedIndex < focusables.length - 1) {
11033					nextFocusIndex = currentFocusedIndex + 1;
11034				} else {
11035					nextFocusIndex = 0;
11036				}
11037				break;
11038			case 'Home':
11039				event.preventDefault();
11040				nextFocusIndex = 0;
11041				break;
11042			case 'End':
11043				event.preventDefault();
11044				nextFocusIndex = focusables.length - 1;
11045				break;
11046			default:
11047				break;
11048		}
11049
11050		if (nextFocusIndex > -1) {
11051			focusables[currentFocusedIndex].setAttribute('tabindex', '-1');
11052			focusables[nextFocusIndex].setAttribute('tabindex', '0');
11053			focusables[nextFocusIndex].focus();
11054		}
11055	};
11056
11057	const handleCpNav2DKeydown = (e, focusables) => {
11058		const map = {
11059			"ArrowLeft": { pos: "left", sign: 1, finder: "findLast", ctrl: false },
11060			"ArrowRight": { pos: "left", sign: -1, finder: "find", ctrl: false },
11061			"ArrowUp": { pos: "top", sign: 1, finder: "findLast", ctrl: false },
11062			"ArrowDown": { pos: "top", sign: -1, finder: "find", ctrl: false },
11063			"Home": { pos: "left", sign: 1, finder: "find", ctrl: e.ctrlKey },
11064			"End": { pos: "left", sign: -1, finder: "findLast", ctrl: e.ctrlKey }
11065		};
11066
11067		const settings = map[e.key];
11068
11069		if (!settings) {
11070			return;
11071		}
11072
11073		const current = e.target.closest(focusableSelector);
11074
11075		if (!current) {
11076			return;
11077		}
11078
11079		e.preventDefault();
11080
11081		const pos = settings.pos;
11082		const offsetConst = pos === "top" ? "left" : "top";
11083		const sign = settings.sign;
11084		const ctrlKey = settings.ctrl;
11085		const rectCurrent = current.getBoundingClientRect();
11086		const tolerance = pos === "top" ? current.offsetHeight / 3 : current.offsetWidth / 3;
11087
11088		const finder = settings.finder;
11089
11090		const elFound = focusables[finder](el => {
11091			const rect = el.getBoundingClientRect();
11092			const currentDistance = sign * (rectCurrent[pos] - rect[pos]);
11093			const offset = Math.abs(rectCurrent[offsetConst] - rect[offsetConst]);
11094			return (offset < tolerance && currentDistance > 0) || ctrlKey;
11095		});
11096
11097		if (!elFound) {
11098			return;
11099		}
11100
11101		current.setAttribute("tabindex", "-1");
11102		elFound.setAttribute("tabindex", "0");
11103		elFound.focus();
11104		return elFound;
11105	}
11106
11107	const handleEl = (target) => {
11108		const elId = target.getAttribute("aria-controls");
11109		if (!elId) {
11110			return;
11111		}
11112
11113		const toggleable = document.getElementById(elId);
11114		if (!toggleable) {
11115			return;
11116		}
11117
11118		toggleEl(target, toggleable);
11119
11120		const handleFocusout = (e) => {
11121			if (toggleable.contains(e.relatedTarget) || target.getAttribute("aria-expanded") !== "true") {
11122				return;
11123			}
11124
11125			if (toggleable.contains(e.currentTarget) && target.contains(e.relatedTarget)) {
11126				// Exclude the case where the focus is moving from popup back to button (e.g. when closing the currently focused popup with a left-mouse click on the button)
11127				// The popup will be closed within the keydown handleEl(); failure to exclude this case will cause a bug where toggleEl() is called twice, making it difficult to close the popup.
11128				// https://civicplus.tpondemand.com/entity/182413-211-calendar-month-view-remove-menu
11129				return;
11130			}
11131
11132			toggleEl(target, toggleable);
11133		};
11134
11135		if (!target["data-cp-toggle"]) {
11136			target["data-cp-toggle"] = true;
11137			toggleable.addEventListener("focusout", handleFocusout);
11138			target.addEventListener("focusout", handleFocusout);
11139		}
11140
11141		const closeActionEl = toggleable.querySelector(".close");
11142
11143		if (!closeActionEl) {
11144			return toggleable;
11145		}
11146
11147		const handleClose = (e) => {
11148			if (e.type === "click" || (e.type === "keydown" && (e.key === "Enter" || e.key === " "))) {
11149				e.preventDefault();
11150				toggleEl(target, toggleable);
11151				target.focus();
11152			}
11153		};
11154
11155		if (!closeActionEl["data-cp-toggle"]) {
11156			closeActionEl["data-cp-toggle"] = true;
11157			closeActionEl.addEventListener("click", handleClose);
11158			closeActionEl.addEventListener("keydown", handleClose);
11159		}
11160
11161		return toggleable;
11162	};
11163
11164	const handleDropdown = (target, func) => {
11165		const toggleable = handleEl(target);
11166		if (!toggleable) {
11167			return;
11168		}
11169		const focusables = Array.from(toggleable.querySelectorAll(focusableSelector));
11170		if (focusables.length === 0) {
11171			return;
11172		}
11173		focusables.forEach( (item, index) => {
11174			item.setAttribute("tabindex", -!!index|0);
11175		});
11176		if (!target["data-cp-toggle-navkeys"]) {
11177			target["data-cp-toggle-navkeys"] = true;
11178			target.addEventListener("keydown", e => {
11179				if (e.key === "ArrowDown" && target.getAttribute("aria-expanded") === "true") {
11180					focusables[0].focus();
11181				}
11182			});
11183			toggleable.addEventListener("keydown", e => {
11184				func(e, focusables);
11185			});
11186		}
11187	}
11188
11189	const handleDropdown1D = (target) => {
11190		return handleDropdown(target, handleCpNavKeydown);
11191	}
11192
11193	const handleDropdown2D = (target) => {
11194		return handleDropdown(target, handleCpNav2DKeydown);
11195	}
11196
11197	const handlePopover = (target) => {
11198		handleEl(target);
11199		repositionPopover(target);
11200	};
11201
11202	/**
11203	 * From the given toggle button's aria-controls elements returns active and total panel count
11204	 * @target  {Element} foo [description]
11205	 */
11206	const getPanels = (target) => {
11207		const elIds = target.getAttribute("aria-controls");
11208		const panelIds = elIds.split(' ');
11209		let activePanels = 0;
11210		let totalPanels = 0;
11211		for (const panelId of panelIds) {
11212			const panel = document.getElementById(panelId);
11213			if (!panel) {
11214				continue
11215			}
11216			totalPanels += 1
11217			activePanels += Number(!!( panel.offsetWidth || panel.offsetHeight || panel.getClientRects().length ))
11218		}
11219
11220		return [activePanels, totalPanels];
11221	}
11222
11223	/**
11224	 * Get total height of the given element's children
11225	 * @collapsable  {Element} foo [description]
11226	 */
11227	const collapsableHeight = (collapsable) => {
11228		const totalHeight = Array.from(collapsable.children).reduce((acc, child) => acc + child.offsetHeight, 0);
11229		return `calc(${totalHeight}px + 2px)`
11230	}
11231
11232	const handleCollapsar = (target) => {
11233		const elIds = target.getAttribute("aria-controls");
11234		if (!elIds) {
11235			return;
11236		}
11237
11238		const collapsables = elIds.split(' ').filter(x => document.getElementById(x));
11239
11240		const expand = target.getAttribute("aria-expanded") === "false";
11241
11242		for (const collapsableId of collapsables) {
11243
11244			const collapsable = document.getElementById(collapsableId);
11245			collapsable.style.overflow = "hidden";
11246			collapsable.style.transition = "all 300ms ease-in";
11247
11248			// get all the buttons those are responsible for the given panel
11249			const controllers = document.querySelectorAll(`[aria-controls^="${collapsableId}"],[aria-controls*=" ${collapsableId} "],[aria-controls$="${collapsableId}"]`);
11250
11251			if (expand) {
11252				collapsable.style.height = "0";
11253				collapsable.style.display = "block";
11254				collapsable.style.height = collapsableHeight(collapsable);
11255				let nextFocus = null;
11256				for (const controller of controllers) {
11257					const [activePanels, totalPanels] = getPanels(controller);
11258					if (activePanels !== totalPanels) {
11259						continue;
11260					}
11261					nextFocus = document.getElementById(controller.dataset.cpToggleFocus);
11262					controller.setAttribute("aria-expanded", "true");
11263					controller.classList.add("active");
11264					if (controller.dataset.cpToggleActiveTitle) {
11265						controller.innerHTML = controller.dataset.cpToggleActiveTitle;
11266					}
11267				}
11268
11269				window.setTimeout(() => {
11270					collapsable.style.removeProperty("height");
11271					collapsable.style.removeProperty("overflow");
11272					nextFocus && nextFocus.focus();
11273				}, 300);
11274				continue;
11275			}
11276
11277			collapsable.style.height = collapsableHeight(collapsable);
11278			collapsable.style.overflow = "hidden";
11279			window.setTimeout(() => {
11280				collapsable.style.height = "0";
11281			}, 0);
11282
11283			window.setTimeout(function () {
11284				collapsable.style.display = "none";
11285				for (const controller of controllers) {
11286					const [activePanels, _] = getPanels(controller);
11287					if (activePanels !== 0) {
11288						continue;
11289					}
11290					controller.setAttribute("aria-expanded", "false");
11291					controller.classList.remove("active");
11292					if (controller.dataset.cpToggleInactiveTitle) {
11293						controller.innerHTML = controller.dataset.cpToggleInactiveTitle;
11294					}
11295				}
11296			}, 300);
11297		}
11298	};
11299
11300	const handleCpToggles = (e) => {
11301		if (e.type === "click" || (e.type === "keydown" && (e.key === "Enter" || e.key === " "))) {
11302			const target = e.target.closest("[data-cp-toggle]");
11303			if (!target) {
11304				return;
11305			}
11306			e.preventDefault();
11307			// target.focus(); // focus element so that focusout is fired to close other open menus.
11308
11309			const actionDescriptor = target.dataset.cpToggle;
11310			switch (actionDescriptor) {
11311				case "popover":
11312					handlePopover(target);
11313					break;
11314				case "collapse":
11315					handleCollapsar(target);
11316					break;
11317				case "dropdown":
11318					handleDropdown1D(target);
11319					break
11320				case "dropdown-2d":
11321					handleDropdown2D(target);
11322					break
11323				default:
11324					handleEl(target);
11325			}
11326		}
11327
11328		const escTargets = new Set(["dropdown", "dropdown-2d"]);
11329
11330		if (e.type === "keydown" && e.key === "Escape") {
11331			const toggles = document.querySelectorAll('[data-cp-toggle][aria-expanded="true"]');
11332			for (const target of toggles) {
11333				const toggleType = target.dataset.cpToggle;
11334				if (escTargets.has(toggleType)) {
11335					const elId = target.getAttribute("aria-controls");
11336					if (!elId) {
11337						continue;
11338					}
11339
11340					const toggleable = document.getElementById(elId);
11341					if (!toggleable) {
11342						continue;
11343					}
11344
11345					const refocus = toggleable.contains(document.activeElement);
11346
11347					toggleEl(target, toggleable);
11348
11349					if (refocus) {
11350						target.focus();
11351					}
11352				}
11353			}
11354		}
11355	};
11356
11357	document.addEventListener("click", handleCpToggles);
11358	document.addEventListener("keydown", handleCpToggles);
11359})();
11360;
11361/* Responsive Menu Font Sizing
11362 * Joshua Enfield
11363 *  -------------
11364 * This resizes menus responsively. It takes into account the original font size.
11365 * If auto widths are on font sizes are adjusted based on the size left in menu items. 
11366 * If auto widths are off font sizes are adjusted based on the size left in the main nav.
11367 * ---------------
11368 * Common Usage: $('menuOLSelector').responsiveMenuText();
11369 * jQuery Usage expects markup in the form of ol > li > a
11370 */
11371(function ($, window, undefined) {
11372
11373	'use strict';
11374
11375	var DEBUG = false;
11376	var diag = function (msg) {
11377		if (DEBUG) {
11378			window.console.log('[ Responsive Menus ] ' + msg);
11379		}
11380	};
11381	
11382	$.MenuTextResizer = function (options, element) {
11383		this.$mainNavMenu = $(element);
11384		this.$topLevelMenuItems = this.$mainNavMenu.find('a');
11385		this._init(options);
11386	};
11387
11388	// the options
11389	$.MenuTextResizer.defaults = {
11390		ratio: 0.5,
11391		timeout: 120,
11392		numberOfFontSizes: 20,
11393		tolerance: 0.00
11394	};
11395
11396	$.MenuTextResizer.prototype = {
11397		_init: function (options) {
11398			// options
11399			this.options = $.extend(true, {}, $.MenuTextResizer.defaults, options);
11400
11401			// local variables
11402			var self = this;
11403			this.timer = null;
11404			this.autoCreatedWrapper = false;
11405			createInnerWrappersIfWrappersDoNotExist();
11406			var desktopFontSize = parseFloat(this.$topLevelMenuItems.css('font-size')); // Initial Font Size. When at maximum size font-size should be this.
11407			var numberOfFontSizes = this.options.numberOfFontSizes;
11408			var fontSizes = getFontSizes();
11409			var currentFontIndex = fontSizes.length - 1;
11410			var tolerance = this.options.tolerance;
11411			var autoWidths = this.$mainNavMenu.data('autowidth') == true;
11412
11413			var ratioToTriggerResize = autoWidths ? { menuRatio: 1.00, itemRatio: self.options.ratio } : { menuRatio: self.options.ratio, itemRatio: 1.00 };
11414			//var ratioToTriggerResize = { menuRatio: 0.68, itemRatio: 1.00 };
11415			//var ratioToTriggerResize = { menuRatio: 1.00, itemRatio: 0.70 };
11416
11417			if (autoWidths)
11418				diag('Auto Widths Detected.');
11419			else {
11420				diag('Auto Widths Turned Off.');
11421			}
11422
11423			diag('Font Sizes: ' + fontSizes);
11424
11425			// Gets list of font sizes to resize amongst
11426
11427			function getFontSizes () {
11428				var fontSizes = [];
11429
11430				// Linear Scale
11431				for (var i = 0; i < numberOfFontSizes; i++) {
11432					fontSizes[i] = Math.floor(desktopFontSize / numberOfFontSizes * (i + 1));
11433				}
11434
11435				// Exponential Decay
11436				/*
11437				fontSizes[numberOfFontSizes - 1] = desktopFontSize;
11438				for (var i = (numberOfFontSizes-2); i > 0; i--) {
11439					fontSizes[i] = Math.floor(0.95 * fontSizes[i+1]);
11440				}*/
11441
11442				return fontSizes;
11443			}
11444
11445			// Increases font size.
11446			var increaseFontSize = function () {
11447				var wasFontSizeIncreased = false;
11448
11449				if (currentFontIndex < (fontSizes.length - 1)) {
11450					currentFontIndex++;
11451					wasFontSizeIncreased = true;
11452					// ratioToTriggerResize.itemRatio -= 0.1;
11453				}
11454
11455				self.$topLevelMenuItems.css('font-size', fontSizes[currentFontIndex]);
11456				diag('INCREASE IN SIZE TRIGGERED (sizeIndex: ' + currentFontIndex + (currentFontIndex == (numberOfFontSizes - 1) ? '(MAX)' : '') + ' ,' + fontSizes[currentFontIndex] + ')');
11457				return wasFontSizeIncreased;
11458			};
11459
11460			// Decreases font size.
11461			var decreaseFontSize = function () {
11462				var wasFontSizeDecreased = false;
11463
11464				if (currentFontIndex > 0) {
11465					currentFontIndex--;
11466					wasFontSizeDecreased = true;
11467					//  ratioToTriggerResize.itemRatio += 0.1;
11468				}
11469
11470				self.$topLevelMenuItems.css('font-size', fontSizes[currentFontIndex]);
11471
11472				diag('DECREASE IN SIZE TRIGGERED (sizeIndex: ' + currentFontIndex + ',' + fontSizes[currentFontIndex] + ')');
11473				return wasFontSizeDecreased;
11474			};
11475
11476			// Wraps menu Items with a span if spans are not already wrapping them.
11477			function createInnerWrappersIfWrappersDoNotExist () {
11478				if (self.$topLevelMenuItems.find('span').length === 0) {
11479					self.$topLevelMenuItems.removeAttr('style').wrapInner('<span/>').find('span').css('display', 'inline');
11480					self.autoCreatedWrapper = true;
11481				}
11482			}
11483
11484			// Get the ratios of space taken to space available for menu items and the menu itself
11485			function getRatio () {
11486				var getItemRatio = function ($item) { return $item.find('span').width() / $item.width(); };
11487				var itemRatio = getItemRatio(self.$topLevelMenuItems.first());
11488
11489				var widthConsumedByMenuItems = 0;
11490				self.$topLevelMenuItems.each(function () {
11491					widthConsumedByMenuItems += $(this).outerWidth(true);
11492
11493					var currentItemRatio = getItemRatio($(this));
11494					if (currentItemRatio > itemRatio) {
11495						itemRatio = currentItemRatio;
11496					}
11497
11498				});
11499
11500				var menuRatio = widthConsumedByMenuItems / self.$mainNavMenu.width();
11501				var result = {
11502					menuRatio: menuRatio.toFixed(2),
11503					itemRatio: itemRatio.toFixed(2)
11504				};
11505
11506				return result;
11507			}
11508
11509			// Conditions
11510			var predicates = (function () {
11511				// Should return true when an increase in size should occur.
11512				var shouldIncreaseInSize = function () {
11513					var currentRatio = getRatio();
11514					diag(JSON.stringify(currentRatio));
11515					if (autoWidths) {
11516						return currentRatio.itemRatio < (ratioToTriggerResize.itemRatio - tolerance);
11517					} else {
11518						return currentRatio.menuRatio < (ratioToTriggerResize.menuRatio - tolerance);
11519					}
11520				};
11521
11522				// Should return true when a decrease in size should occur.
11523				var shouldDescreaseInSize = function () {
11524					var currentRatio = getRatio();
11525					diag(JSON.stringify(currentRatio));
11526					if (autoWidths) {
11527						return currentRatio.itemRatio > (ratioToTriggerResize.itemRatio - tolerance);
11528					} else {
11529						return currentRatio.menuRatio > (ratioToTriggerResize.menuRatio - tolerance);
11530					}
11531				};
11532
11533				return {
11534					shouldIncreaseInSize: shouldIncreaseInSize,
11535					shouldDescreaseInSize: shouldDescreaseInSize
11536				};
11537
11538			}());
11539
11540			// Function that actually adjusts menu font sizes.
11541			this.adjustMenuFontSize = function () {
11542				while (predicates.shouldIncreaseInSize() && increaseFontSize()) ;
11543				while (predicates.shouldDescreaseInSize() && decreaseFontSize()) ;
11544			};
11545
11546			this._initDefault();
11547		},
11548		_initDefault : function () {
11549			// Setup and bind menu resizing logic
11550			var self = this;
11551			var timeout = self.options.timeout || 100; //debouncing
11552			$(window).bind('resize.responsiveMenuText', function () {
11553				self.timer && clearTimeout(self.timer);
11554				
11555				self.timer = setTimeout(function () {
11556					self.adjustMenuFontSize();
11557				}, timeout);
11558			});
11559			self.adjustMenuFontSize();
11560		},
11561		dispose: function () {
11562			var self = this;
11563			clearTimeout(self.timer);
11564			$(window).unbind('.responsiveMenuText');
11565			if (self.autoCreatedWrapper) {
11566				self.$topLevelMenuItems.find('span').contents().unwrap();
11567				setTimeout(function () { self.$topLevelMenuItems.removeAttr('style'); }, 200);
11568			}
11569		}
11570	};
11571
11572	/* jQuery Plugin Support
11573	   Expected Markup structure: ol > li > a
11574	   Menu Text is dynamically wrapped by a span if it isn't already.
11575	*/
11576	$.fn.responsiveMenuText = function (options) {
11577		if (typeof options === 'string') {
11578			var args = Array.prototype.slice.call(arguments, 1);
11579			this.each(function () {
11580				var instance = $.data(this, 'responsiveMenuText');
11581				if (!instance) {
11582					diag("cannot call methods on responsiveMenuText prior to initialization; " +
11583					"attempted to call method '" + options + "'");
11584					return;
11585				}
11586				if (!$.isFunction(instance[options]) || options.charAt(0) === "_") {
11587					diag("no such method '" + options + "' for responsiveMenuText instance");
11588					return;
11589				}
11590				instance[options].apply(instance, args);
11591			});
11592		}
11593		else {
11594			this.each(function () {
11595				var instance = $.data(this, 'responsiveMenuText');
11596				if (instance) {
11597					instance._init(options);
11598				}
11599				else {
11600					instance = $.data(this, 'responsiveMenuText', new $.MenuTextResizer(options, this));
11601				}
11602			});
11603		}
11604
11605		return this;
11606	};
11607
11608})(jQuery, window);
11609/**
11610 * Based on  jquery.rwdmenu.js v1.0.1
11611 * http://www.codrops.com
11612 *
11613 */
11614; (function ($, window, undefined) {
11615
11616	'use strict';
11617
11618	// global
11619	var Modernizr = window.Modernizr, $body = $('body');
11620
11621	$.RWDMenu = function (options, element) {
11622		this.$el = $(element);
11623		this._init(options);
11624	};
11625
11626	// the options
11627	$.RWDMenu.defaults = {
11628		// classes for the animation effects
11629		animationClasses: { classin: 'rwd-animate-in', classout: 'rwd-animate-out' },
11630		// callback: click a link that has a sub menu
11631		// el is the link element (li); name is the level name
11632		onLevelClick: function (el, name) { return false; },
11633		// callback: click a link that does not have a sub menu
11634		// el is the link element (li); ev is the event obj
11635		onLinkClick: function (el, ev) { return false; }
11636	};
11637
11638	$.RWDMenu.prototype = {
11639		_init: function (options) {
11640
11641			// options
11642			this.options = $.extend(true, {}, $.RWDMenu.defaults, options);
11643			// cache some elements and initialize some variables
11644			this._config();
11645
11646			var animEndEventNames = {
11647				'WebkitAnimation': 'webkitAnimationEnd',
11648				'OAnimation': 'oAnimationEnd',
11649				'msAnimation': 'MSAnimationEnd',
11650				'animation': 'animationend'
11651			},
11652				transEndEventNames = {
11653					'WebkitTransition': 'webkitTransitionEnd',
11654					'MozTransition': 'transitionend',
11655					'OTransition': 'oTransitionEnd',
11656					'msTransition': 'MSTransitionEnd',
11657					'transition': 'transitionend'
11658				};
11659			// animation end event name
11660			this.animEndEventName = animEndEventNames[Modernizr.prefixed('animation')] + '.rwdmenu';
11661			// transition end event name
11662			this.transEndEventName = transEndEventNames[Modernizr.prefixed('transition')] + '.rwdmenu',
11663			// support for css animations and css transitions
11664			this.supportAnimations = Modernizr.cssanimations,
11665			this.supportTransitions = Modernizr.csstransitions;
11666
11667			var self = this;
11668			this.clickMenuItem = function (event) {
11669				//if (!menuManager.mobileMainNav) return true;
11670
11671				event.stopPropagation();
11672
11673				var $li = $(this),
11674					$submenu = $li.children('ol.rwd-submenu');
11675
11676				if ($submenu.length == 0) {
11677					var id = $li.attr('id'); //.replace(/item|leftItem/i, '');
11678					var $olSubMenu = menuManager.$divListSubMenus.find('#Parent' + id);
11679					if ($olSubMenu.length > 1) {
11680						//remove duplicates. they might have been added by different menu (main/side)
11681						$olSubMenu.slice(1).remove();
11682						$olSubMenu = menuManager.$divListSubMenus.find('#Parent' + id);
11683					}
11684					if ($olSubMenu.length == 1) {
11685						var $back = $('<li class="rwd-back"><a href="#" style="z-index:2;" class="navMenuItem backMenuLink" aria-haspopup="true" role="menuitem">Back</a></li>');
11686						$back.bind('click.rwdmenu', self.clickBack);
11687						$olSubMenu.prepend($back);
11688						$olSubMenu.addClass('rwd-submenu');
11689						$olSubMenu.find('li:not(.rwd-back)').bind('click.rwdmenu', self.clickMenuItem);
11690						$li.append($olSubMenu);
11691						$submenu = $olSubMenu;
11692					}
11693				}
11694
11695				if ($submenu.length > 0) {
11696
11697					var $flyin = $submenu.clone().css('opacity', 0).insertAfter(self.$menu),
11698						onAnimationEndFn = function () {
11699							self.$menu.unbind(self.animEndEventName).removeClass(self.options.animationClasses.classout).addClass('rwd-subview');
11700							$('.rwd-subviewopen').children('ol').attr('aria-hidden', 'true');
11701							$li.addClass('rwd-subviewopen').parents('.rwd-subviewopen:first').removeClass('rwd-subviewopen').addClass('rwd-subview');
11702							$li.children('ol').attr('aria-hidden', 'false');
11703							$flyin.remove();
11704							$li.find('.openThePageLink').focus();
11705						};
11706
11707					setTimeout(function () {
11708						$flyin.addClass(self.options.animationClasses.classin);
11709						self.$menu.addClass(self.options.animationClasses.classout);
11710						if (self.supportAnimations) {
11711							self.$menu.bind(self.animEndEventName, onAnimationEndFn);
11712						} else {
11713							onAnimationEndFn.call();
11714						}
11715
11716						self.options.onLevelClick($li, $li.children('a:first').text());
11717					});
11718
11719					return false;
11720
11721				} else {
11722					self.options.onLinkClick($li, event);
11723				}
11724
11725			};
11726
11727			this.clickBack = function (event) {
11728
11729				var $this = $(this),
11730					$submenu = $this.parents('ol.rwd-submenu:first'),
11731					$item = $submenu.parent(),
11732					$flyin = $submenu.clone().insertAfter(self.$menu);
11733
11734				var onAnimationEndFn = function () {
11735					self.$menu.unbind(self.animEndEventName).removeClass(self.options.animationClasses.classin);
11736					$flyin.remove();
11737				};
11738
11739				setTimeout(function () {
11740					$flyin.addClass(self.options.animationClasses.classout);
11741					self.$menu.addClass(self.options.animationClasses.classin);
11742					if (self.supportAnimations) {
11743						self.$menu.bind(self.animEndEventName, onAnimationEndFn);
11744					} else {
11745						onAnimationEndFn.call();
11746					}
11747
11748					$item.removeClass('rwd-subviewopen').children('ol').attr('aria-hidden', 'true');
11749
11750					var $subview = $this.parents('.rwd-subview:first');
11751					if ($subview.is('li')) {
11752						$subview.addClass('rwd-subviewopen').children('ol').attr('aria-hidden', 'false');
11753					}
11754					$subview.removeClass('rwd-subview');
11755					$('ol#mainNavMenu').find('li > a').first().focus();
11756				});
11757
11758				return false;
11759			};
11760
11761			this._initEvents();
11762
11763		},
11764		_config: function () {
11765			this.$menu = this.$el;// this.$el.children('ol.rwd-menu');
11766			this.$menuitems = this.$menu.find('li.topMenuItem');
11767			this.$menu.addClass('rwd-menu');
11768		},
11769		_initEvents: function () {
11770
11771			var self = this;
11772
11773			this.$menuitems.bind('click.rwdmenu', self.clickMenuItem);
11774		},
11775		destroy: function () {
11776			//Remove classes, other events, not needed lis (back, to parent) and place back into hidden div.
11777			this.$menu.removeClass('rwd-menu rwd-subview');
11778			this.$menu.find('li').removeClass('rwd-subviewopen rwd-subview').unbind('.rwdmenu');
11779			this.$menu.find('li.rwd-back').remove();
11780			this.$menu.find('li.toParent').remove();
11781			this.$menu.find('ol').removeClass('rwd-submenu').each(function () {
11782				menuManager.$divListSubMenus.append($(this));
11783			});
11784		}
11785	};
11786
11787	var logError = function (message) {
11788		if (window.console) {
11789			window.console.error(message);
11790		}
11791	};
11792
11793	$.fn.rwdmenu = function (options) {
11794		if (typeof options === 'string') {
11795			var args = Array.prototype.slice.call(arguments, 1);
11796			this.each(function () {
11797				var instance = $.data(this, 'rwdmenu');
11798				if (!instance) {
11799					logError("cannot call methods on rwdmenu prior to initialization; " +
11800					"attempted to call method '" + options + "'");
11801					return;
11802				}
11803				if (!$.isFunction(instance[options]) || options.charAt(0) === "_") {
11804					logError("no such method '" + options + "' for rwdmenu instance");
11805					return;
11806				}
11807				instance[options].apply(instance, args);
11808			});
11809		}
11810		else {
11811			this.each(function () {
11812				var instance = $.data(this, 'rwdmenu');
11813				if (instance) {
11814					instance._init();
11815				}
11816				else {
11817					instance = $.data(this, 'rwdmenu', new $.RWDMenu(options, this));
11818				}
11819			});
11820		}
11821		return this;
11822	};
11823
11824})(jQuery, window);
11825/*global jQuery:false, alert:false */
11826
11827/*
11828 * Default text - jQuery plugin for html5 dragging files from desktop to browser
11829 *
11830 * Author: Weixi Yen
11831 *
11832 * Email: [Firstname][Lastname]@gmail.com
11833 *
11834 * Copyright (c) 2010 Resopollution
11835 *
11836 * Licensed under the MIT license:
11837 *   http://www.opensource.org/licenses/mit-license.php
11838 *
11839 * Project home:
11840 *   http://www.github.com/weixiyen/jquery-filedrop
11841 *
11842 * Version:  0.1.0
11843 *
11844 * Features:
11845 *      Allows sending of extra parameters with file.
11846 *      Works with Firefox 3.6+
11847 *      Future-compliant with HTML5 spec (will work with Webkit browsers and IE9)
11848 * Usage:
11849 *  See README at project homepage
11850 *
11851 */
11852;(function($) {
11853
11854  var default_opts = {
11855        fallback_id: '',
11856        fallback_dropzoneClick : true,
11857        url: '',
11858        refresh: 1000,
11859        paramname: 'userfile',
11860        requestType: 'POST',    // just in case you want to use another HTTP verb
11861        allowedfileextensions:[],
11862        allowedfiletypes:[],
11863        maxfiles: 25,           // Ignored if queuefiles is set > 0
11864        maxfilesize: 1,         // MB file size limit
11865        queuefiles: 0,          // Max files before queueing (for large volume uploads)
11866        queuewait: 200,         // Queue wait time if full
11867        data: {},
11868        headers: {},
11869        drop: empty,
11870        dragStart: empty,
11871        dragEnter: empty,
11872        dragOver: empty,
11873        dragLeave: empty,
11874        docEnter: empty,
11875        docOver: empty,
11876        docLeave: empty,
11877        beforeEach: empty,
11878        afterAll: empty,
11879        rename: empty,
11880        error: function(err, file, i, status) {
11881          alert(err);
11882        },
11883        uploadStarted: empty,
11884        uploadFinished: empty,
11885        progressUpdated: empty,
11886        globalProgressUpdated: empty,
11887        speedUpdated: empty
11888      },
11889      errors = ["BrowserNotSupported", "TooManyFiles", "FileTooLarge", "FileTypeNotAllowed", "NotFound", "NotReadable", "AbortError", "ReadError", "FileExtensionNotAllowed"];
11890
11891  $.fn.filedrop = function(options) {
11892    var opts = $.extend({}, default_opts, options),
11893        global_progress = [],
11894        doc_leave_timer, stop_loop = false,
11895        files_count = 0,
11896        files;
11897
11898    if ( opts.fallback_id )
11899    {
11900      if ( opts.fallback_dropzoneClick === true )
11901      {
11902        $('#' + opts.fallback_id).css({
11903          display: 'none',
11904          width: 0,
11905          height: 0
11906        });
11907      }
11908
11909
11910
11911
11912      if ( opts.fallback_dropzoneClick === true )
11913      {
11914        if ( this.find('#' + opts.fallback_id).length > 0 )
11915        {
11916          throw "Fallback element ["+opts.fallback_id+"] cannot be inside dropzone, unless option fallback_dropzoneClick is false";
11917        }
11918        else
11919        {
11920          this.on('click', function(e){
11921            $('#' + opts.fallback_id).trigger(e);
11922          });
11923        }
11924      }
11925
11926      $('#' + opts.fallback_id).change(function(e) {
11927        opts.drop(e);
11928        files = e.target.files;
11929        files_count = files.length;
11930        upload();
11931      });
11932    }
11933
11934    this.on('drop', drop).on('dragstart', opts.dragStart).on('dragenter', dragEnter).on('dragover', dragOver).on('dragleave', dragLeave);
11935    $(document).on('drop', docDrop).on('dragenter', docEnter).on('dragover', docOver).on('dragleave', docLeave);
11936
11937    function drop(e) {
11938      if( opts.drop.call(this, e) === false ) return false;
11939      if(!e.originalEvent.dataTransfer)
11940        return;
11941      files = e.originalEvent.dataTransfer.files;
11942      if (files === null || files === undefined || files.length === 0) {
11943        opts.error(errors[0]);
11944        return false;
11945      }
11946      files_count = files.length;
11947      upload();
11948      e.preventDefault();
11949      return false;
11950    }
11951
11952    function getBuilder(filename, filedata, mime, boundary) {
11953      var dashdash = '--',
11954          crlf = '\r\n',
11955          builder = '',
11956          paramname = opts.paramname;
11957
11958      if (opts.data) {
11959        var params = $.param(opts.data).replace(/\+/g, '%20').split(/&/);
11960
11961        $.each(params, function() {
11962          var pair = this.split("=", 2),
11963              name = decodeURIComponent(pair[0]),
11964              val  = decodeURIComponent(pair[1]);
11965
11966          if (pair.length !== 2) {
11967            return;
11968          }
11969
11970          builder += dashdash;
11971          builder += boundary;
11972          builder += crlf;
11973          builder += 'Content-Disposition: form-data; name="' + name + '"';
11974          builder += crlf;
11975          builder += crlf;
11976          builder += val;
11977          builder += crlf;
11978        });
11979      }
11980
11981      if (jQuery.isFunction(paramname)){
11982        paramname = paramname(filename);
11983      }
11984
11985      builder += dashdash;
11986      builder += boundary;
11987      builder += crlf;
11988      builder += 'Content-Disposition: form-data; name="' + (paramname||"") + '"';
11989      builder += '; filename="' + encodeURIComponent(filename) + '"';
11990      builder += crlf;
11991
11992      builder += 'Content-Type: ' + mime;
11993      builder += crlf;
11994      builder += crlf;
11995
11996      builder += filedata;
11997      builder += crlf;
11998
11999      builder += dashdash;
12000      builder += boundary;
12001      builder += dashdash;
12002      builder += crlf;
12003      return builder;
12004    }
12005
12006    function progress(e) {
12007      if (e.lengthComputable) {
12008        var percentage = Math.round((e.loaded * 100) / e.total);
12009        if (this.currentProgress !== percentage) {
12010
12011          this.currentProgress = percentage;
12012          opts.progressUpdated(this.index, this.file, this.currentProgress);
12013
12014          global_progress[this.global_progress_index] = this.currentProgress;
12015          globalProgress();
12016
12017          var elapsed = new Date().getTime();
12018          var diffTime = elapsed - this.currentStart;
12019          if (diffTime >= opts.refresh) {
12020            var diffData = e.loaded - this.startData;
12021            var speed = diffData / diffTime; // KB per second
12022            opts.speedUpdated(this.index, this.file, speed);
12023            this.startData = e.loaded;
12024            this.currentStart = elapsed;
12025          }
12026        }
12027      }
12028    }
12029
12030    function globalProgress() {
12031      if (global_progress.length === 0) {
12032        return;
12033      }
12034
12035      var total = 0, index;
12036      for (index in global_progress) {
12037        if(global_progress.hasOwnProperty(index)) {
12038          total = total + global_progress[index];
12039        }
12040      }
12041
12042      opts.globalProgressUpdated(Math.round(total / global_progress.length));
12043    }
12044
12045    // Respond to an upload
12046    function upload() {
12047      stop_loop = false;
12048
12049      if (!files) {
12050        opts.error(errors[0]);
12051        return false;
12052      }
12053
12054      if (opts.allowedfiletypes.push && opts.allowedfiletypes.length) {
12055        for(var fileIndex = files.length;fileIndex--;) {
12056          if(!files[fileIndex].type || $.inArray(files[fileIndex].type, opts.allowedfiletypes) < 0) {
12057            opts.error(errors[3], files[fileIndex]);
12058            return false;
12059          }
12060        }
12061      }
12062
12063      if (opts.allowedfileextensions.push && opts.allowedfileextensions.length) {
12064        for(var fileIndex = files.length;fileIndex--;) {
12065          var allowedextension = false;
12066          for (i=0;i<opts.allowedfileextensions.length;i++){
12067            if (files[fileIndex].name.substr(files[fileIndex].name.length-opts.allowedfileextensions[i].length).toLowerCase()
12068                == opts.allowedfileextensions[i].toLowerCase()
12069            ) {
12070              allowedextension = true;
12071            }
12072          }
12073          if (!allowedextension){
12074            opts.error(errors[8], files[fileIndex]);
12075            return false;
12076          }
12077        }
12078      }
12079
12080      var filesDone = 0,
12081          filesRejected = 0;
12082
12083      if (files_count > opts.maxfiles && opts.queuefiles === 0) {
12084        opts.error(errors[1]);
12085        return false;
12086      }
12087
12088      // Define queues to manage upload process
12089      var workQueue = [];
12090      var processingQueue = [];
12091      var doneQueue = [];
12092
12093      // Add everything to the workQueue
12094      for (var i = 0; i < files_count; i++) {
12095        workQueue.push(i);
12096      }
12097
12098      // Helper function to enable pause of processing to wait
12099      // for in process queue to complete
12100      var pause = function(timeout) {
12101        setTimeout(process, timeout);
12102        return;
12103      };
12104
12105      // Process an upload, recursive
12106      var process = function() {
12107
12108        var fileIndex;
12109
12110        if (stop_loop) {
12111          return false;
12112        }
12113
12114        // Check to see if are in queue mode
12115        if (opts.queuefiles > 0 && processingQueue.length >= opts.queuefiles) {
12116          return pause(opts.queuewait);
12117        } else {
12118          // Take first thing off work queue
12119          fileIndex = workQueue[0];
12120          workQueue.splice(0, 1);
12121
12122          // Add to processing queue
12123          processingQueue.push(fileIndex);
12124        }
12125
12126        try {
12127          if (beforeEach(files[fileIndex]) !== false) {
12128            if (fileIndex === files_count) {
12129              return;
12130            }
12131            var reader = new FileReader(),
12132                max_file_size = 1048576 * opts.maxfilesize;
12133
12134            reader.index = fileIndex;
12135            if (files[fileIndex].size > max_file_size) {
12136              opts.error(errors[2], files[fileIndex], fileIndex);
12137              // Remove from queue
12138              processingQueue.forEach(function(value, key) {
12139                if (value === fileIndex) {
12140                  processingQueue.splice(key, 1);
12141                }
12142              });
12143              filesRejected++;
12144              return true;
12145            }
12146
12147            reader.onerror = function(e) {
12148              switch(e.target.error.code) {
12149                case e.target.error.NOT_FOUND_ERR:
12150                  opts.error(errors[4]);
12151                  return false;
12152                case e.target.error.NOT_READABLE_ERR:
12153                  opts.error(errors[5]);
12154                  return false;
12155                case e.target.error.ABORT_ERR:
12156                  opts.error(errors[6]);
12157                  return false;
12158                default:
12159                  opts.error(errors[7]);
12160                  return false;
12161              };
12162            };
12163
12164            reader.onloadend = !opts.beforeSend ? send : function (e) {
12165              opts.beforeSend(files[fileIndex], fileIndex, function () { send(e); });
12166            };
12167
12168            reader.readAsDataURL(files[fileIndex]);
12169
12170          } else {
12171            filesRejected++;
12172          }
12173        } catch (err) {
12174          // Remove from queue
12175          processingQueue.forEach(function(value, key) {
12176            if (value === fileIndex) {
12177              processingQueue.splice(key, 1);
12178            }
12179          });
12180          opts.error(errors[0]);
12181          return false;
12182        }
12183
12184        // If we still have work to do,
12185        if (workQueue.length > 0) {
12186          process();
12187        }
12188      };
12189
12190      var send = function(e) {
12191
12192        var fileIndex = (e.srcElement || e.target).index;
12193
12194        // Sometimes the index is not attached to the
12195        // event object. Find it by size. Hack for sure.
12196        if (e.target.index === undefined) {
12197          e.target.index = getIndexBySize(e.total);
12198        }
12199
12200        var xhr = new XMLHttpRequest(),
12201            upload = xhr.upload,
12202            file = files[e.target.index],
12203            index = e.target.index,
12204            start_time = new Date().getTime(),
12205            boundary = '------multipartformboundary' + (new Date()).getTime(),
12206            global_progress_index = global_progress.length,
12207            builder,
12208            newName = rename(file.name),
12209            mime = file.type;
12210
12211        if (opts.withCredentials) {
12212          xhr.withCredentials = opts.withCredentials;
12213        }
12214
12215        var encodedString = e.target.result.split(',')[1];
12216        var data = encodedString === undefined ? '' : atob(encodedString);
12217        if (typeof newName === "string") {
12218          builder = getBuilder(newName, data, mime, boundary);
12219        } else {
12220          builder = getBuilder(file.name, data, mime, boundary);
12221        }
12222
12223        upload.index = index;
12224        upload.file = file;
12225        upload.downloadStartTime = start_time;
12226        upload.currentStart = start_time;
12227        upload.currentProgress = 0;
12228        upload.global_progress_index = global_progress_index;
12229        upload.startData = 0;
12230        upload.addEventListener("progress", progress, false);
12231
12232        // Allow url to be a method
12233        if (jQuery.isFunction(opts.url)) {
12234          xhr.open(opts.requestType, opts.url(upload), true);
12235        } else {
12236          xhr.open(opts.requestType, opts.url, true);
12237        }
12238
12239        xhr.setRequestHeader('content-type', 'multipart/form-data; boundary=' + boundary);
12240        xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
12241
12242        // Add headers
12243        $.each(opts.headers, function(k, v) {
12244          xhr.setRequestHeader(k, v);
12245        });
12246
12247        if(!xhr.sendAsBinary){
12248          xhr.sendAsBinary = function(datastr) {
12249            function byteValue(x) {
12250              return x.charCodeAt(0) & 0xff;
12251            }
12252            var ords = Array.prototype.map.call(datastr, byteValue);
12253            var ui8a = new Uint8Array(ords);
12254            this.send(ui8a.buffer);
12255          }
12256        }
12257
12258        xhr.sendAsBinary(builder);
12259
12260        global_progress[global_progress_index] = 0;
12261        globalProgress();
12262
12263        opts.uploadStarted(index, file, files_count);
12264
12265        xhr.onload = function() {
12266          var serverResponse = null;
12267
12268          if (xhr.responseText) {
12269            try {
12270              serverResponse = jQuery.parseJSON(xhr.responseText);
12271            }
12272            catch (e) {
12273              serverResponse = xhr.responseText;
12274            }
12275          }
12276
12277          var now = new Date().getTime(),
12278              timeDiff = now - start_time,
12279              result = opts.uploadFinished(index, file, serverResponse, timeDiff, xhr);
12280          filesDone++;
12281
12282          // Remove from processing queue
12283          processingQueue.forEach(function(value, key) {
12284            if (value === fileIndex) {
12285              processingQueue.splice(key, 1);
12286            }
12287          });
12288
12289          // Add to donequeue
12290          doneQueue.push(fileIndex);
12291
12292          // Make sure the global progress is updated
12293          global_progress[global_progress_index] = 100;
12294          globalProgress();
12295
12296          if (filesDone === (files_count - filesRejected)) {
12297            afterAll();
12298          }
12299          if (result === false) {
12300            stop_loop = true;
12301          }
12302
12303
12304          // Pass any errors to the error option
12305          if (xhr.status < 200 || xhr.status > 299) {
12306            opts.error(xhr.statusText, file, fileIndex, xhr.status);
12307          }
12308        };
12309      };
12310
12311      // Initiate the processing loop
12312      process();
12313    }
12314
12315    function getIndexBySize(size) {
12316      for (var i = 0; i < files_count; i++) {
12317        if (files[i].size === size) {
12318          return i;
12319        }
12320      }
12321
12322      return undefined;
12323    }
12324
12325    function rename(name) {
12326      return opts.rename(name);
12327    }
12328
12329    function beforeEach(file) {
12330      return opts.beforeEach(file);
12331    }
12332
12333    function afterAll() {
12334      return opts.afterAll();
12335    }
12336
12337    function dragEnter(e) {
12338      clearTimeout(doc_leave_timer);
12339      e.preventDefault();
12340      opts.dragEnter.call(this, e);
12341    }
12342
12343    function dragOver(e) {
12344      clearTimeout(doc_leave_timer);
12345      e.preventDefault();
12346      opts.docOver.call(this, e);
12347      opts.dragOver.call(this, e);
12348    }
12349
12350    function dragLeave(e) {
12351      clearTimeout(doc_leave_timer);
12352      opts.dragLeave.call(this, e);
12353      e.stopPropagation();
12354    }
12355
12356    function docDrop(e) {
12357      e.preventDefault();
12358      opts.docLeave.call(this, e);
12359      return false;
12360    }
12361
12362    function docEnter(e) {
12363      clearTimeout(doc_leave_timer);
12364      e.preventDefault();
12365      opts.docEnter.call(this, e);
12366      return false;
12367    }
12368
12369    function docOver(e) {
12370      clearTimeout(doc_leave_timer);
12371      e.preventDefault();
12372      opts.docOver.call(this, e);
12373      return false;
12374    }
12375
12376    function docLeave(e) {
12377      doc_leave_timer = setTimeout((function(_this) {
12378        return function() {
12379          opts.docLeave.call(_this, e);
12380        };
12381      })(this), 200);
12382    }
12383
12384    return this;
12385  };
12386
12387  function empty() {}
12388
12389  try {
12390    if (XMLHttpRequest.prototype.sendAsBinary) {
12391      return;
12392    }
12393    XMLHttpRequest.prototype.sendAsBinary = function(datastr) {
12394      function byteValue(x) {
12395        return x.charCodeAt(0) & 0xff;
12396      }
12397      var ords = Array.prototype.map.call(datastr, byteValue);
12398      var ui8a = new Uint8Array(ords);
12399
12400      // Not pretty: Chrome 22 deprecated sending ArrayBuffer, moving instead
12401      // to sending ArrayBufferView.  Sadly, no proper way to detect this
12402      // functionality has been discovered.  Happily, Chrome 22 also introduced
12403      // the base ArrayBufferView class, not present in Chrome 21.
12404      if ('ArrayBufferView' in window)
12405        this.send(ui8a);
12406      else
12407        this.send(ui8a.buffer);
12408    };
12409  } catch (e) {}
12410
12411})(jQuery);
12412;
12413/*!
12414 * Javascript Cookie v1.5.1
12415 * https://github.com/js-cookie/js-cookie
12416 *
12417 * Copyright 2006, 2014 Klaus Hartl
12418 * Released under the MIT license
12419 */
12420(function(n){var i,r,t;if(typeof define=="function"&&define.amd)define(["jquery"],n);else if(typeof exports=="object"){try{i=require("jquery")}catch(u){}module.exports=n(i)}else r=window.Cookies,t=window.Cookies=n(window.jQuery),t.noConflict=function(){return window.Cookies=r,t}})(function(n){function i(n){return t.raw?n:encodeURIComponent(n)}function o(n){return t.raw?n:decodeURIComponent(n)}function s(n){return i(t.json?JSON.stringify(n):String(n))}function h(n){n.indexOf('"')===0&&(n=n.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\"));try{return n=decodeURIComponent(n.replace(e," ")),t.json?JSON.parse(n):n}catch(i){}}function r(n,i){var r=t.raw?n:h(n);return f(i)?i(r):r}function u(){for(var n,t,i=0,r={};i<arguments.length;i++){t=arguments[i];for(n in t)r[n]=t[n]}return r}function f(n){return Object.prototype.toString.call(n)==="[object Function]"}var e=/\+/g,t=function(n,e,h){var y,l;if(arguments.length>1&&!f(e))return h=u(t.defaults,h),typeof h.expires=="number"&&(y=h.expires,l=h.expires=new Date,l.setMilliseconds(l.getMilliseconds()+y*864e5)),document.cookie=[i(n),"=",s(e),h.expires?"; expires="+h.expires.toUTCString():"",h.path?"; path="+h.path:"",h.domain?"; domain="+h.domain:"",h.secure?"; secure":""].join("");for(var a=n?undefined:{},p=document.cookie?document.cookie.split("; "):[],v=0,k=p.length;v<k;v++){var w=p[v].split("="),b=o(w.shift()),c=w.join("=");if(n===b){a=r(c,e);break}n||(c=r(c))===undefined||(a[b]=c)}return a};return t.get=t.set=t,t.defaults={},t.remove=function(n,i){return t(n,"",u(i,{expires:-1})),!t(n)},n&&(n.cookie=t,n.removeCookie=t.remove),t});
12421/*! jQuery UI - v1.14.2 - 2026-01-29
vendor: 32,915 bytes, lines 12421-12426
12421
12422* https://jqueryui.com
12423* Includes: widget.js, position.js, data.js, disable-selection.js, effect.js, effects/effect-blind.js, effects/effect-bounce.js, effects/effect-clip.js, effects/effect-drop.js, effects/effect-explode.js, effects/effect-fade.js, effects/effect-fold.js, effects/effect-highlight.js, effects/effect-puff.js, effects/effect-pulsate.js, effects/effect-scale.js, effects/effect-shake.js, effects/effect-size.js, effects/effect-slide.js, effects/effect-transfer.js, focusable.js, form-reset-mixin.js, jquery-patch.js, keycode.js, labels.js, scroll-parent.js, tabbable.js, unique-id.js, widgets/accordion.js, widgets/autocomplete.js, widgets/button.js, widgets/checkboxradio.js, widgets/controlgroup.js, widgets/datepicker.js, widgets/dialog.js, widgets/draggable.js, widgets/droppable.js, widgets/menu.js, widgets/mouse.js, widgets/progressbar.js, widgets/resizable.js, widgets/selectable.js, widgets/selectmenu.js, widgets/slider.js, widgets/sortable.js, widgets/spinner.js, widgets/tabs.js, widgets/tooltip.js
12424* Copyright OpenJS Foundation and other contributors; Licensed MIT */
12425
12426!function(t){"use strict";"function"==typeof define&&define.amd?define(["jquery"],t):t(jQuery)}(function(t){"use strict";t.ui=t.ui||{},t.ui.version="1.14.2";var e,i,s,n,o,a=0,r=Array.prototype.hasOwnProperty,l=Array.prototype.slice;h=t.cleanData,t.cleanData=function(e){var i,s,n;for(n=0;null!=(s=e[n]);n++)(i=t._data(s,"events"))&&i.remove&&t(s).triggerHandler("remove");h(e)},t.widget=function(e,i,s){var n,o,a,r={},l=e.split(".")[0];if("__proto__"===(e=e.split(".")[1])||"constructor"===e)return t.error("Invalid widget name: "+e);var h=l+"-"+e;return s||(s=i,i=t.Widget),Array.isArray(s)&&(s=t.extend.apply(null,[{}].concat(s))),t.expr.pseudos[h.toLowerCase()]=function(e){return!!t.data(e,h)},t[l]=t[l]||{},n=t[l][e],o=t[l][e]=function(t,e){if(!this||!this._createWidget)return new o(t,e);arguments.length&&this._createWidget(t,e)},t.extend(o,n,{version:s.version,_proto:t.extend({},s),_childConstructors:[]}),(a=new i).options=t.widget.extend({},a.options),t.each(s,function(t,e){if("function"!=typeof e){r[t]=e;return}r[t]=function(){function s(){return i.prototype[t].apply(this,arguments)}function n(e){return i.prototype[t].apply(this,e)}return function(){var t,i=this._super,o=this._superApply;return this._super=s,this._superApply=n,t=e.apply(this,arguments),this._super=i,this._superApply=o,t}}()}),o.prototype=t.widget.extend(a,{widgetEventPrefix:n&&a.widgetEventPrefix||e},r,{constructor:o,namespace:l,widgetName:e,widgetFullName:h}),n?(t.each(n._childConstructors,function(e,i){var s=i.prototype;t.widget(s.namespace+"."+s.widgetName,o,i._proto)}),delete n._childConstructors):i._childConstructors.push(o),t.widget.bridge(e,o),o},t.widget.extend=function(e){for(var i,s,n=l.call(arguments,1),o=0,a=n.length;o<a;o++)for(i in n[o])s=n[o][i],r.call(n[o],i)&&void 0!==s&&(t.isPlainObject(s)?e[i]=t.isPlainObject(e[i])?t.widget.extend({},e[i],s):t.widget.extend({},s):e[i]=s);return e},t.widget.bridge=function(e,i){var s=i.prototype.widgetFullName||e;t.fn[e]=function(n){var o="string"==typeof n,a=l.call(arguments,1),r=this;return o?this.length||"instance"!==n?this.each(function(){var i,o=t.data(this,s);return"instance"===n?(r=o,!1):o?"function"!=typeof o[n]||"_"===n.charAt(0)?t.error("no such method '"+n+"' for "+e+" widget instance"):(i=o[n].apply(o,a))!==o&&void 0!==i?(r=i&&i.jquery?r.pushStack(i.get()):i,!1):void 0:t.error("cannot call methods on "+e+" prior to initialization; attempted to call method '"+n+"'")}):r=void 0:(a.length&&(n=t.widget.extend.apply(null,[n].concat(a))),this.each(function(){var e=t.data(this,s);e?(e.option(n||{}),e._init&&e._init()):t.data(this,s,new i(n,this))})),r}},t.Widget=function(){},t.Widget._childConstructors=[],t.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{classes:{},disabled:!1,create:null},_createWidget:function(e,i){i=t(i||this.defaultElement||this)[0],this.element=t(i),this.uuid=a++,this.eventNamespace="."+this.widgetName+this.uuid,this.bindings=t(),this.hoverable=t(),this.focusable=t(),this.classesElementLookup={},i!==this&&(t.data(i,this.widgetFullName,this),this._on(!0,this.element,{remove:function(t){t.target===i&&this.destroy()}}),this.document=t(i.style?i.ownerDocument:i.document||i),this.window=t(this.document[0].defaultView||this.document[0].parentWindow)),this.options=t.widget.extend({},this.options,this._getCreateOptions(),e),this._create(),this.options.disabled&&this._setOptionDisabled(this.options.disabled),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:function(){return{}},_getCreateEventData:t.noop,_create:t.noop,_init:t.noop,destroy:function(){var e=this;this._destroy(),t.each(this.classesElementLookup,function(t,i){e._removeClass(i,t)}),this.element.off(this.eventNamespace).removeData(this.widgetFullName),this.widget().off(this.eventNamespace).removeAttr("aria-disabled"),this.bindings.off(this.eventNamespace)},_destroy:t.noop,widget:function(){return this.element},option:function(e,i){var s,n,o,a=e;if(0==arguments.length)return t.widget.extend({},this.options);if("string"==typeof e){if(a={},e=(s=e.split(".")).shift(),s.length){for(o=0,n=a[e]=t.widget.extend({},this.options[e]);o<s.length-1;o++)n[s[o]]=n[s[o]]||{},n=n[s[o]];if(e=s.pop(),1==arguments.length)return void 0===n[e]?null:n[e];n[e]=i}else{if(1==arguments.length)return void 0===this.options[e]?null:this.options[e];a[e]=i}}return this._setOptions(a),this},_setOptions:function(t){var e;for(e in t)this._setOption(e,t[e]);return this},_setOption:function(t,e){return"classes"===t&&this._setOptionClasses(e),this.options[t]=e,"disabled"===t&&this._setOptionDisabled(e),this},_setOptionClasses:function(e){var i,s,n;for(i in e)n=this.classesElementLookup[i],e[i]!==this.options.classes[i]&&n&&n.length&&(s=t(n.get()),this._removeClass(n,i),s.addClass(this._classes({element:s,keys:i,classes:e,add:!0})))},_setOptionDisabled:function(t){this._toggleClass(this.widget(),this.widgetFullName+"-disabled",null,!!t),t&&(this._removeClass(this.hoverable,null,"ui-state-hover"),this._removeClass(this.focusable,null,"ui-state-focus"))},enable:function(){return this._setOptions({disabled:!1})},disable:function(){return this._setOptions({disabled:!0})},_classes:function(e){var i=[],s=this;function n(n,o){var a,r;for(r=0;r<n.length;r++)a=s.classesElementLookup[n[r]]||t(),e.add?(function(){var i=[];e.element.each(function(e,n){t.map(s.classesElementLookup,function(t){return t}).some(function(t){return t.is(n)})||i.push(n)}),s._on(t(i),{remove:"_untrackClassesElement"})}(),a=t(t.uniqueSort(a.get().concat(e.element.get())))):a=t(a.not(e.element).get()),s.classesElementLookup[n[r]]=a,i.push(n[r]),o&&e.classes[n[r]]&&i.push(e.classes[n[r]])}return(e=t.extend({element:this.element,classes:this.options.classes||{}},e)).keys&&n(e.keys.match(/\S+/g)||[],!0),e.extra&&n(e.extra.match(/\S+/g)||[]),i.join(" ")},_untrackClassesElement:function(e){var i=this;t.each(i.classesElementLookup,function(s,n){-1!==t.inArray(e.target,n)&&(i.classesElementLookup[s]=t(n.not(e.target).get()))}),this._off(t(e.target))},_removeClass:function(t,e,i){return this._toggleClass(t,e,i,!1)},_addClass:function(t,e,i){return this._toggleClass(t,e,i,!0)},_toggleClass:function(t,e,i,s){s="boolean"==typeof s?s:i;var n="string"==typeof t||null===t,o={extra:n?e:i,keys:n?t:e,element:n?this.element:t,add:s};return o.element.toggleClass(this._classes(o),s),this},_on:function(e,i,s){var n,o=this;"boolean"!=typeof e&&(s=i,i=e,e=!1),s?(i=n=t(i),this.bindings=this.bindings.add(i)):(s=i,i=this.element,n=this.widget()),t.each(s,function(s,a){function r(){if(!(!e&&(!0===o.options.disabled||t(this).hasClass("ui-state-disabled"))))return("string"==typeof a?o[a]:a).apply(o,arguments)}"string"!=typeof a&&(r.guid=a.guid=a.guid||r.guid||t.guid++);var l=s.match(/^([\w:-]*)\s*(.*)$/),h=l[1]+o.eventNamespace,c=l[2];c?n.on(h,c,r):i.on(h,r)})},_off:function(e,i){i=(i||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,e.off(i),this.bindings=t(this.bindings.not(e).get()),this.focusable=t(this.focusable.not(e).get()),this.hoverable=t(this.hoverable.not(e).get())},_delay:function(t,e){var i=this;return setTimeout(function(){return("string"==typeof t?i[t]:t).apply(i,arguments)},e||0)},_hoverable:function(e){this.hoverable=this.hoverable.add(e),this._on(e,{mouseenter:function(e){this._addClass(t(e.currentTarget),null,"ui-state-hover")},mouseleave:function(e){this._removeClass(t(e.currentTarget),null,"ui-state-hover")}})},_focusable:function(e){this.focusable=this.focusable.add(e),this._on(e,{focusin:function(e){this._addClass(t(e.currentTarget),null,"ui-state-focus")},focusout:function(e){this._removeClass(t(e.currentTarget),null,"ui-state-focus")}})},_trigger:function(e,i,s){var n,o,a=this.options[e];if(s=s||{},(i=t.Event(i)).type=(e===this.widgetEventPrefix?e:this.widgetEventPrefix+e).toLowerCase(),i.target=this.element[0],o=i.originalEvent)for(n in o)n in i||(i[n]=o[n]);return this.element.trigger(i,s),!("function"==typeof a&&!1===a.apply(this.element[0],[i].concat(s))||i.isDefaultPrevented())}},t.each({show:"fadeIn",hide:"fadeOut"},function(e,i){t.Widget.prototype["_"+e]=function(s,n,o){"string"==typeof n&&(n={effect:n});var a,r=n?!0===n||"number"==typeof n?i:n.effect||i:e;"number"==typeof(n=n||{})?n={duration:n}:!0===n&&(n={}),a=!t.isEmptyObject(n),n.complete=o,n.delay&&s.delay(n.delay),a&&t.effects&&t.effects.effect[r]?s[e](n):r!==e&&s[r]?s[r](n.duration,n.easing,o):s.queue(function(i){t(this)[e](),o&&o.call(s[0]),i()})}}),t.widget,function(){var e,i=Math.max,s=Math.abs,n=/left|center|right/,o=/top|center|bottom/,a=/[\+\-]\d+(\.[\d]+)?%?/,r=/^\w+/,l=/%$/,h=t.fn.position;function c(t,e,i){return[parseFloat(t[0])*(l.test(t[0])?e/100:1),parseFloat(t[1])*(l.test(t[1])?i/100:1)]}function u(e,i){return parseInt(t.css(e,i),10)||0}function d(t){return null!=t&&t===t.window}t.position={scrollbarWidth:function(){if(void 0!==e)return e;var i,s,n=t("<div style='display:block;position:absolute;width:200px;height:200px;overflow:hidden;'><div style='height:300px;width:auto;'></div></div>"),o=n.children()[0];return t("body").append(n),i=o.offsetWidth,n.css("overflow","scroll"),i===(s=o.offsetWidth)&&(s=n[0].clientWidth),n.remove(),e=i-s},getScrollInfo:function(e){var i=e.isWindow||e.isDocument?"":e.element.css("overflow-x"),s=e.isWindow||e.isDocument?"":e.element.css("overflow-y"),n="scroll"===i||"auto"===i&&e.width<e.element[0].scrollWidth;return{width:"scroll"===s||"auto"===s&&e.height<e.element[0].scrollHeight?t.position.scrollbarWidth():0,height:n?t.position.scrollbarWidth():0}},getWithinInfo:function(e){var i=t(e||window),s=d(i[0]),n=!!i[0]&&9===i[0].nodeType;return{element:i,isWindow:s,isDocument:n,offset:s||n?{left:0,top:0}:t(e).offset(),scrollLeft:i.scrollLeft(),scrollTop:i.scrollTop(),width:i.outerWidth(),height:i.outerHeight()}}},t.fn.position=function(e){if(!e||!e.of)return h.apply(this,arguments);var l,p,f,g,m,_,v,b="string"==typeof(e=t.extend({},e)).of?t(document).find(e.of):t(e.of),y=t.position.getWithinInfo(e.within),w=t.position.getScrollInfo(y),x=(e.collision||"flip").split(" "),k={};return v=9===(l=b[0]).nodeType?{width:b.width(),height:b.height(),offset:{top:0,left:0}}:d(l)?{width:b.width(),height:b.height(),offset:{top:b.scrollTop(),left:b.scrollLeft()}}:l.preventDefault?{width:0,height:0,offset:{top:l.pageY,left:l.pageX}}:{width:b.outerWidth(),height:b.outerHeight(),offset:b.offset()},b[0].preventDefault&&(e.at="left top"),f=v.width,g=v.height,m=v.offset,_=t.extend({},m),t.each(["my","at"],function(){var t,i,s=(e[this]||"").split(" ");1===s.length&&(s=n.test(s[0])?s.concat(["center"]):o.test(s[0])?["center"].concat(s):["center","center"]),s[0]=n.test(s[0])?s[0]:"center",s[1]=o.test(s[1])?s[1]:"center",t=a.exec(s[0]),i=a.exec(s[1]),k[this]=[t?t[0]:0,i?i[0]:0],e[this]=[r.exec(s[0])[0],r.exec(s[1])[0]]}),1===x.length&&(x[1]=x[0]),"right"===e.at[0]?_.left+=f:"center"===e.at[0]&&(_.left+=f/2),"bottom"===e.at[1]?_.top+=g:"center"===e.at[1]&&(_.top+=g/2),p=c(k.at,f,g),_.left+=p[0],_.top+=p[1],this.each(function(){var n,o,a=t(this),r=a.outerWidth(),l=a.outerHeight(),h=u(this,"marginLeft"),d=u(this,"marginTop"),v=r+h+u(this,"marginRight")+w.width,C=l+d+u(this,"marginBottom")+w.height,D=t.extend({},_),I=c(k.my,a.outerWidth(),a.outerHeight());"right"===e.my[0]?D.left-=r:"center"===e.my[0]&&(D.left-=r/2),"bottom"===e.my[1]?D.top-=l:"center"===e.my[1]&&(D.top-=l/2),D.left+=I[0],D.top+=I[1],n={marginLeft:h,marginTop:d},t.each(["left","top"],function(i,s){t.ui.position[x[i]]&&t.ui.position[x[i]][s](D,{targetWidth:f,targetHeight:g,elemWidth:r,elemHeight:l,collisionPosition:n,collisionWidth:v,collisionHeight:C,offset:[p[0]+I[0],p[1]+I[1]],my:e.my,at:e.at,within:y,elem:a})}),e.using&&(o=function(t){var n=m.left-D.left,o=n+f-r,h=m.top-D.top,c=h+g-l,u={target:{element:b,left:m.left,top:m.top,width:f,height:g},element:{element:a,left:D.left,top:D.top,width:r,height:l},horizontal:o<0?"left":n>0?"right":"center",vertical:c<0?"top":h>0?"bottom":"middle"};f<r&&s(n+o)<f&&(u.horizontal="center"),g<l&&s(h+c)<g&&(u.vertical="middle"),i(s(n),s(o))>i(s(h),s(c))?u.important="horizontal":u.important="vertical",e.using.call(this,t,u)}),a.offset(t.extend(D,{using:o}))})},t.ui.position={fit:{left:function(t,e){var s,n=e.within,o=n.isWindow?n.scrollLeft:n.offset.left,a=n.width,r=t.left-e.collisionPosition.marginLeft,l=o-r,h=r+e.collisionWidth-a-o;e.collisionWidth>a?l>0&&h<=0?(s=t.left+l+e.collisionWidth-a-o,t.left+=l-s):h>0&&l<=0?t.left=o:l>h?t.left=o+a-e.collisionWidth:t.left=o:l>0?t.left+=l:h>0?t.left-=h:t.left=i(t.left-r,t.left)},top:function(t,e){var s,n=e.within,o=n.isWindow?n.scrollTop:n.offset.top,a=e.within.height,r=t.top-e.collisionPosition.marginTop,l=o-r,h=r+e.collisionHeight-a-o;e.collisionHeight>a?l>0&&h<=0?(s=t.top+l+e.collisionHeight-a-o,t.top+=l-s):h>0&&l<=0?t.top=o:l>h?t.top=o+a-e.collisionHeight:t.top=o:l>0?t.top+=l:h>0?t.top-=h:t.top=i(t.top-r,t.top)}},flip:{left:function(t,e){var i,n,o=e.within,a=o.offset.left+o.scrollLeft,r=o.width,l=o.isWindow?o.scrollLeft:o.offset.left,h=t.left-e.collisionPosition.marginLeft,c=h-l,u=h+e.collisionWidth-r-l,d="left"===e.my[0]?-e.elemWidth:"right"===e.my[0]?e.elemWidth:0,p="left"===e.at[0]?e.targetWidth:"right"===e.at[0]?-e.targetWidth:0,f=-2*e.offset[0];c<0?((i=t.left+d+p+f+e.collisionWidth-r-a)<0||i<s(c))&&(t.left+=d+p+f):u>0&&((n=t.left-e.collisionPosition.marginLeft+d+p+f-l)>0||s(n)<u)&&(t.left+=d+p+f)},top:function(t,e){var i,n,o=e.within,a=o.offset.top+o.scrollTop,r=o.height,l=o.isWindow?o.scrollTop:o.offset.top,h=t.top-e.collisionPosition.marginTop,c=h-l,u=h+e.collisionHeight-r-l,d="top"===e.my[1]?-e.elemHeight:"bottom"===e.my[1]?e.elemHeight:0,p="top"===e.at[1]?e.targetHeight:"bottom"===e.at[1]?-e.targetHeight:0,f=-2*e.offset[1];c<0?((n=t.top+d+p+f+e.collisionHeight-r-a)<0||n<s(c))&&(t.top+=d+p+f):u>0&&((i=t.top-e.collisionPosition.marginTop+d+p+f-l)>0||s(i)<u)&&(t.top+=d+p+f)}},flipfit:{left:function(){t.ui.position.flip.left.apply(this,arguments),t.ui.position.fit.left.apply(this,arguments)},top:function(){t.ui.position.flip.top.apply(this,arguments),t.ui.position.fit.top.apply(this,arguments)}}}}(),t.ui.position,t.extend(t.expr.pseudos,{data:t.expr.createPseudo(function(e){return function(i){return!!t.data(i,e)}})}),t.fn.extend({disableSelection:(c="onselectstart"in document.createElement("div")?"selectstart":"mousedown",function(){return this.on(c+".ui-disableSelection",function(t){t.preventDefault()})}),enableSelection:function(){return this.off(".ui-disableSelection")}});var h,c,u,d={},p=d.toString,f=/^([\-+])=\s*(\d+\.?\d*)/,g=[{re:/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(t){return[t[1],t[2],t[3],t[4]]}},{re:/rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(t){return[2.55*t[1],2.55*t[2],2.55*t[3],t[4]]}},{re:/#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})?/,parse:function(t){return[parseInt(t[1],16),parseInt(t[2],16),parseInt(t[3],16),t[4]?(parseInt(t[4],16)/255).toFixed(2):1]}},{re:/#([a-f0-9])([a-f0-9])([a-f0-9])([a-f0-9])?/,parse:function(t){return[parseInt(t[1]+t[1],16),parseInt(t[2]+t[2],16),parseInt(t[3]+t[3],16),t[4]?(parseInt(t[4]+t[4],16)/255).toFixed(2):1]}},{re:/hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,space:"hsla",parse:function(t){return[t[1],t[2]/100,t[3]/100,t[4]]}}],m=t.Color=function(e,i,s,n){return new t.Color.fn.parse(e,i,s,n)},_={rgba:{props:{red:{idx:0,type:"byte"},green:{idx:1,type:"byte"},blue:{idx:2,type:"byte"}}},hsla:{props:{hue:{idx:0,type:"degrees"},saturation:{idx:1,type:"percent"},lightness:{idx:2,type:"percent"}}}},v={byte:{floor:!0,max:255},percent:{max:1},degrees:{mod:360,floor:!0}},b=t.each;function y(t){return null==t?t+"":"object"==typeof t?d[p.call(t)]||"object":typeof t}function w(t,e,i){var s=v[e.type]||{};return null==t?i||!e.def?null:e.def:(t=s.floor?~~t:parseFloat(t),s.mod)?(t+s.mod)%s.mod:Math.min(s.max,Math.max(0,t))}function x(e){var i=m(),s=i._rgba=[];return(e=e.toLowerCase(),b(g,function(t,n){var o,a=n.re.exec(e),r=a&&n.parse(a),l=n.space||"rgba";if(r)return o=i[l](r),i[_[l].cache]=o[_[l].cache],s=i._rgba=o._rgba,!1}),s.length)?("0,0,0,0"===s.join()&&t.extend(s,u.transparent),i):u[e]}function k(t,e,i){return 6*(i=(i+1)%1)<1?t+(e-t)*i*6:2*i<1?e:3*i<2?t+(e-t)*(2/3-i)*6:t}b(_,function(t,e){e.cache="_"+t,e.props.alpha={idx:3,type:"percent",def:1}}),t.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(t,e){d["[object "+e+"]"]=e.toLowerCase()}),m.fn=t.extend(m.prototype,{parse:function(e,i,s,n){if(void 0===e)return this._rgba=[null,null,null,null],this;(e.jquery||e.nodeType)&&(e=t(e).css(i),i=void 0);var o=this,a=y(e),r=this._rgba=[];return(void 0!==i&&(e=[e,i,s,n],a="array"),"string"===a)?this.parse(x(e)||u._default):"array"===a?(b(_.rgba.props,function(t,i){r[i.idx]=w(e[i.idx],i)}),this):"object"===a?(e instanceof m?b(_,function(t,i){e[i.cache]&&(o[i.cache]=e[i.cache].slice())}):b(_,function(i,s){var n=s.cache;b(s.props,function(t,i){if(!o[n]&&s.to){if("alpha"===t||null==e[t])return;o[n]=s.to(o._rgba)}o[n][i.idx]=w(e[t],i,!0)}),o[n]&&0>t.inArray(null,o[n].slice(0,3))&&(null==o[n][3]&&(o[n][3]=1),s.from&&(o._rgba=s.from(o[n])))}),this):void 0},is:function(t){var e=m(t),i=!0,s=this;return b(_,function(t,n){var o,a=e[n.cache];return a&&(o=s[n.cache]||n.to&&n.to(s._rgba)||[],b(n.props,function(t,e){if(null!=a[e.idx])return i=a[e.idx]===o[e.idx]})),i}),i},_space:function(){var t=[],e=this;return b(_,function(i,s){e[s.cache]&&t.push(i)}),t.pop()},transition:function(t,e){var i=m(t),s=i._space(),n=_[s],o=0===this.alpha()?m("transparent"):this,a=o[n.cache]||n.to(o._rgba),r=a.slice();return i=i[n.cache],b(n.props,function(t,s){var n=s.idx,o=a[n],l=i[n],h=v[s.type]||{};null!==l&&(null===o?r[n]=l:(h.mod&&(l-o>h.mod/2?o+=h.mod:o-l>h.mod/2&&(o-=h.mod)),r[n]=w((l-o)*e+o,s)))}),this[s](r)},blend:function(e){if(1===this._rgba[3])return this;var i=this._rgba.slice(),s=i.pop(),n=m(e)._rgba;return m(t.map(i,function(t,e){return(1-s)*n[e]+s*t}))},toRgbaString:function(){var e="rgba(",i=t.map(this._rgba,function(t,e){return null!=t?t:+(e>2)});return 1===i[3]&&(i.pop(),e="rgb("),e+i.join(", ")+")"},toHslaString:function(){var e="hsla(",i=t.map(this.hsla(),function(t,e){return null==t&&(t=+(e>2)),e&&e<3&&(t=Math.round(100*t)+"%"),t});return 1===i[3]&&(i.pop(),e="hsl("),e+i.join(", ")+")"},toHexString:function(e){var i=this._rgba.slice(),s=i.pop();return e&&i.push(~~(255*s)),"#"+t.map(i,function(t){return("0"+(t||0).toString(16)).substr(-2)}).join("")},toString:function(){return this.toRgbaString()}}),m.fn.parse.prototype=m.fn,_.hsla.to=function(t){if(null==t[0]||null==t[1]||null==t[2])return[null,null,null,t[3]];var e,i=t[0]/255,s=t[1]/255,n=t[2]/255,o=t[3],a=Math.max(i,s,n),r=Math.min(i,s,n),l=a-r,h=a+r,c=.5*h;return[Math.round(r===a?0:i===a?60*(s-n)/l+360:s===a?60*(n-i)/l+120:60*(i-s)/l+240)%360,0===l?0:c<=.5?l/h:l/(2-h),c,null==o?1:o]},_.hsla.from=function(t){if(null==t[0]||null==t[1]||null==t[2])return[null,null,null,t[3]];var e=t[0]/360,i=t[1],s=t[2],n=t[3],o=s<=.5?s*(1+i):s+i-s*i,a=2*s-o;return[Math.round(255*k(a,o,e+1/3)),Math.round(255*k(a,o,e)),Math.round(255*k(a,o,e-1/3)),n]},b(_,function(t,e){var i=e.props,s=e.cache,n=e.to,o=e.from;m.fn[t]=function(t){if(n&&!this[s]&&(this[s]=n(this._rgba)),void 0===t)return this[s].slice();var e,a=y(t),r="array"===a||"object"===a?t:arguments,l=this[s].slice();return(b(i,function(t,e){var i=r["object"===a?t:e.idx];null==i&&(i=l[e.idx]),l[e.idx]=w(i,e)}),o)?((e=m(o(l)))[s]=l,e):m(l)},b(i,function(e,i){!m.fn[e]&&(m.fn[e]=function(s){var n,o,a,r,l=y(s);return(o=(n=this[r="alpha"===e?this._hsla?"hsla":"rgba":t]())[i.idx],"undefined"===l)?o:("function"===l&&(l=y(s=s.call(this,o))),null==s&&i.empty)?this:("string"===l&&(a=f.exec(s))&&(s=o+parseFloat(a[2])*("+"===a[1]?1:-1)),n[i.idx]=s,this[r](n))})})}),m.hook=function(e){b(e.split(" "),function(e,i){t.cssHooks[i]={set:function(t,e){var s;"transparent"!==e&&("string"!==y(e)||(s=x(e)))&&(e=(e=m(s||e)).toRgbaString()),t.style[i]=e}},t.fx.step[i]=function(e){e.colorInit||(e.start=m(e.elem,i),e.end=m(e.end),e.colorInit=!0),t.cssHooks[i].set(e.elem,e.start.transition(e.end,e.pos))}})},m.hook("backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor"),t.cssHooks.borderColor={expand:function(t){var e={};return b(["Top","Right","Bottom","Left"],function(i,s){e["border"+s+"Color"]=t}),e}},u=t.Color.names={aqua:"#00ffff",black:"#000000",blue:"#0000ff",fuchsia:"#ff00ff",gray:"#808080",green:"#008000",lime:"#00ff00",maroon:"#800000",navy:"#000080",olive:"#808000",purple:"#800080",red:"#ff0000",silver:"#c0c0c0",teal:"#008080",white:"#ffffff",yellow:"#ffff00",transparent:[null,null,null,0],_default:"#ffffff"};var C="ui-effects-",D="ui-effects-style",I="ui-effects-animated";t.effects={effect:{}},function(){var e,i,s,n=["add","remove","toggle"],o={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};function a(t){var e,i,s=t.ownerDocument.defaultView.getComputedStyle(t),n={};i=s.length;while(i--)e=s[i],"string"==typeof s[e]&&(n[e.replace(/-([\da-z])/gi,function(t,e){return e.toUpperCase()})]=s[e]);return n}t.each(["borderLeftStyle","borderRightStyle","borderBottomStyle","borderTopStyle"],function(e,i){t.fx.step[i]=function(e){("none"===e.end||e.setAttr)&&(1!==e.pos||e.setAttr)||(t.style(e.elem,i,e.end),e.setAttr=!0)}}),t.effects.animateClass=function(e,i,s,r){var l=t.speed(i,s,r);return this.queue(function(){var i,s=t(this),r=s.attr("class")||"",h=l.children?s.find("*").addBack():s;h=h.map(function(){return{el:t(this),start:a(this)}}),(i=function(){t.each(n,function(t,i){e[i]&&s[i+"Class"](e[i])})})(),h=h.map(function(){return this.end=a(this.el[0]),this.diff=function(e,i){var s,n,a={};for(s in i)n=i[s],e[s]===n||o[s]||!t.fx.step[s]&&isNaN(parseFloat(n))||(a[s]=n);return a}(this.start,this.end),this}),s.attr("class",r),h=h.map(function(){var e=this,i=t.Deferred(),s=t.extend({},l,{queue:!1,complete:function(){i.resolve(e)}});return this.el.animate(this.diff,s),i.promise()}),t.when.apply(t,h.get()).done(function(){i(),t.each(arguments,function(){var e=this.el;t.each(this.diff,function(t){e.css(t,"")})}),l.complete.call(s[0])})})},t.fn.extend({addClass:(e=t.fn.addClass,function(i,s,n,o){return s?t.effects.animateClass.call(this,{add:i},s,n,o):e.apply(this,arguments)}),removeClass:(i=t.fn.removeClass,function(e,s,n,o){return arguments.length>1?t.effects.animateClass.call(this,{remove:e},s,n,o):i.apply(this,arguments)}),toggleClass:(s=t.fn.toggleClass,function(e,i,n,o,a){return"boolean"!=typeof i&&void 0!==i?t.effects.animateClass.call(this,{toggle:e},i,n,o):n?t.effects.animateClass.call(this,i?{add:e}:{remove:e},n,o,a):s.apply(this,arguments)}),switchClass:function(e,i,s,n,o){return t.effects.animateClass.call(this,{add:i,remove:e},s,n,o)}})}(),function(){var e,i,s,n;function o(e,i,s,n){return t.isPlainObject(e)&&(i=e,e=e.effect),e={effect:e},null==i&&(i={}),"function"==typeof i&&(n=i,s=null,i={}),("number"==typeof i||t.fx.speeds[i])&&(n=s,s=i,i={}),"function"==typeof s&&(n=s,s=null),i&&t.extend(e,i),s=s||i.duration,e.duration=t.fx.off?0:"number"==typeof s?s:s in t.fx.speeds?t.fx.speeds[s]:t.fx.speeds._default,e.complete=n||i.complete,e}function a(e){return!e||"number"==typeof e||!!t.fx.speeds[e]||"string"==typeof e&&!t.effects.effect[e]||"function"==typeof e||"object"==typeof e&&!e.effect}function r(t,e){var i=e.outerWidth(),s=e.outerHeight(),n=/^rect\((-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto)\)$/.exec(t)||["",0,i,s,0];return{top:parseFloat(n[1])||0,right:"auto"===n[2]?i:parseFloat(n[2]),bottom:"auto"===n[3]?s:parseFloat(n[3]),left:parseFloat(n[4])||0}}t.expr&&t.expr.pseudos&&t.expr.pseudos.animated&&(t.expr.pseudos.animated=(e=t.expr.pseudos.animated,function(i){return!!t(i).data(I)||e(i)})),!0===t.uiBackCompat&&t.extend(t.effects,{save:function(t,e){for(var i=0,s=e.length;i<s;i++)null!==e[i]&&t.data(C+e[i],t[0].style[e[i]])},restore:function(t,e){for(var i,s=0,n=e.length;s<n;s++)null!==e[s]&&(i=t.data(C+e[s]),t.css(e[s],i))},setMode:function(t,e){return"toggle"===e&&(e=t.is(":hidden")?"show":"hide"),e},createWrapper:function(e){if(e.parent().is(".ui-effects-wrapper"))return e.parent();var i={width:e.outerWidth(!0),height:e.outerHeight(!0),float:e.css("float")},s=t("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0}),n={width:e.width(),height:e.height()},o=document.activeElement;try{o.id}catch(t){o=document.body}return e.wrap(s),(e[0]===o||t.contains(e[0],o))&&t(o).trigger("focus"),s=e.parent(),"static"===e.css("position")?(s.css({position:"relative"}),e.css({position:"relative"})):(t.extend(i,{position:e.css("position"),zIndex:e.css("z-index")}),t.each(["top","left","bottom","right"],function(t,s){i[s]=e.css(s),isNaN(parseInt(i[s],10))&&(i[s]="auto")}),e.css({position:"relative",top:0,left:0,right:"auto",bottom:"auto"})),e.css(n),s.css(i).show()},removeWrapper:function(e){var i=document.activeElement;return e.parent().is(".ui-effects-wrapper")&&(e.parent().replaceWith(e),(e[0]===i||t.contains(e[0],i))&&t(i).trigger("focus")),e}}),t.extend(t.effects,{version:"1.14.2",define:function(e,i,s){return s||(s=i,i="effect"),t.effects.effect[e]=s,t.effects.effect[e].mode=i,s},scaledDimensions:function(t,e,i){if(0===e)return{height:0,width:0,outerHeight:0,outerWidth:0};var s="horizontal"!==i?(e||100)/100:1,n="vertical"!==i?(e||100)/100:1;return{height:t.height()*n,width:t.width()*s,outerHeight:t.outerHeight()*n,outerWidth:t.outerWidth()*s}},clipToBox:function(t){return{width:t.clip.right-t.clip.left,height:t.clip.bottom-t.clip.top,left:t.clip.left,top:t.clip.top}},unshift:function(t,e,i){var s=t.queue();e>1&&s.splice.apply(s,[1,0].concat(s.splice(e,i))),t.dequeue()},saveStyle:function(t){t.data(D,t[0].style.cssText)},restoreStyle:function(t){t[0].style.cssText=t.data(D)||"",t.removeData(D)},mode:function(t,e){var i=t.is(":hidden");return"toggle"===e&&(e=i?"show":"hide"),(i?"hide"===e:"show"===e)&&(e="none"),e},getBaseline:function(t,e){var i,s;switch(t[0]){case"top":i=0;break;case"middle":i=.5;break;case"bottom":i=1;break;default:i=t[0]/e.height}switch(t[1]){case"left":s=0;break;case"center":s=.5;break;case"right":s=1;break;default:s=t[1]/e.width}return{x:s,y:i}},createPlaceholder:function(e){var i,s=e.css("position"),n=e.position();return e.css({marginTop:e.css("marginTop"),marginBottom:e.css("marginBottom"),marginLeft:e.css("marginLeft"),marginRight:e.css("marginRight")}).outerWidth(e.outerWidth()).outerHeight(e.outerHeight()),/^(static|relative)/.test(s)&&(s="absolute",i=t("<"+e[0].nodeName+">").insertAfter(e).css({display:/^(inline|ruby)/.test(e.css("display"))?"inline-block":"block",visibility:"hidden",marginTop:e.css("marginTop"),marginBottom:e.css("marginBottom"),marginLeft:e.css("marginLeft"),marginRight:e.css("marginRight"),float:e.css("float")}).outerWidth(e.outerWidth()).outerHeight(e.outerHeight()).addClass("ui-effects-placeholder"),e.data(C+"placeholder",i)),e.css({position:s,left:n.left,top:n.top}),i},removePlaceholder:function(t){var e=C+"placeholder",i=t.data(e);i&&(i.remove(),t.removeData(e))},cleanUp:function(e){t.effects.restoreStyle(e),t.effects.removePlaceholder(e)},setTransition:function(e,i,s,n){return n=n||{},t.each(i,function(t,i){var o=e.cssUnit(i);o[0]>0&&(n[i]=o[0]*s+o[1])}),n}}),t.fn.extend({effect:function(){var e=o.apply(this,arguments),i=t.effects.effect[e.effect],s=i.mode,n=e.queue,a=n||"fx",r=e.complete,l=e.mode,h=[],c=function(e){var i=t(this),n=t.effects.mode(i,l)||s;i.data(I,!0),h.push(n),s&&("show"===n||n===s&&"hide"===n)&&i.show(),s&&"none"===n||t.effects.saveStyle(i),"function"==typeof e&&e()};if(t.fx.off||!i)return l?this[l](e.duration,r):this.each(function(){r&&r.call(this)});function u(n){var o=t(this);function a(){"function"==typeof r&&r.call(o[0]),"function"==typeof n&&n()}e.mode=h.shift(),!0!==t.uiBackCompat||s?"none"===e.mode?(o[l](),a()):i.call(o[0],e,function(){o.removeData(I),t.effects.cleanUp(o),"hide"===e.mode&&o.hide(),a()}):(o.is(":hidden")?"hide"===l:"show"===l)?(o[l](),a()):i.call(o[0],e,a)}return!1===n?this.each(c).each(u):this.queue(a,c).queue(a,u)},show:(i=t.fn.show,function(t){if(a(t))return i.apply(this,arguments);var e=o.apply(this,arguments);return e.mode="show",this.effect.call(this,e)}),hide:(s=t.fn.hide,function(t){if(a(t))return s.apply(this,arguments);var e=o.apply(this,arguments);return e.mode="hide",this.effect.call(this,e)}),toggle:(n=t.fn.toggle,function(t){if(a(t)||"boolean"==typeof t)return n.apply(this,arguments);var e=o.apply(this,arguments);return e.mode="toggle",this.effect.call(this,e)}),cssUnit:function(e){var i=this.css(e),s=[];return t.each(["em","px","%","pt"],function(t,e){i.indexOf(e)>0&&(s=[parseFloat(i),e])}),s},cssClip:function(t){return t?this.css("clip","rect("+t.top+"px "+t.right+"px "+t.bottom+"px "+t.left+"px)"):r(this.css("clip"),this)},transfer:function(e,i){var s=t(this),n=t(e.to),o="fixed"===n.css("position"),a=t("body"),r=o?a.scrollTop():0,l=o?a.scrollLeft():0,h=n.offset(),c={top:h.top-r,left:h.left-l,height:n.innerHeight(),width:n.innerWidth()},u=s.offset(),d=t("<div class='ui-effects-transfer'></div>");d.appendTo("body").addClass(e.className).css({top:u.top-r,left:u.left-l,height:s.innerHeight(),width:s.innerWidth(),position:o?"fixed":"absolute"}).animate(c,e.duration,e.easing,function(){d.remove(),"function"==typeof i&&i()})}}),t.fx.step.clip=function(e){e.clipInit||(e.start=t(e.elem).cssClip(),"string"==typeof e.end&&(e.end=r(e.end,e.elem)),e.clipInit=!0),t(e.elem).cssClip({top:e.pos*(e.end.top-e.start.top)+e.start.top,right:e.pos*(e.end.right-e.start.right)+e.start.right,bottom:e.pos*(e.end.bottom-e.start.bottom)+e.start.bottom,left:e.pos*(e.end.left-e.start.left)+e.start.left})}}(),e={},t.each(["Quad","Cubic","Quart","Quint","Expo"],function(t,i){e[i]=function(e){return Math.pow(e,t+2)}}),t.extend(e,{Sine:function(t){return 1-Math.cos(t*Math.PI/2)},Circ:function(t){return 1-Math.sqrt(1-t*t)},Elastic:function(t){return 0===t||1===t?t:-Math.pow(2,8*(t-1))*Math.sin(((t-1)*80-7.5)*Math.PI/15)},Back:function(t){return t*t*(3*t-2)},Bounce:function(t){var e,i=4;while(t<((e=Math.pow(2,--i))-1)/11);return 1/Math.pow(4,3-i)-7.5625*Math.pow((3*e-2)/22-t,2)}}),t.each(e,function(e,i){t.easing["easeIn"+e]=i,t.easing["easeOut"+e]=function(t){return 1-i(1-t)},t.easing["easeInOut"+e]=function(t){return t<.5?i(2*t)/2:1-i(-2*t+2)/2}});var n=t.effects;t.effects.define("blind","hide",function(e,i){var s={up:["bottom","top"],vertical:["bottom","top"],down:["top","bottom"],left:["right","left"],horizontal:["right","left"],right:["left","right"]},n=t(this),o=e.direction||"up",a=n.cssClip(),r={clip:t.extend({},a)},l=t.effects.createPlaceholder(n);r.clip[s[o][0]]=r.clip[s[o][1]],"show"===e.mode&&(n.cssClip(r.clip),l&&l.css(t.effects.clipToBox(r)),r.clip=a),l&&l.animate(t.effects.clipToBox(r),e.duration,e.easing),n.animate(r,{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("bounce",function(e,i){var s,n,o,a=t(this),r=e.mode,l="hide"===r,h="show"===r,c=e.direction||"up",u=e.distance,d=e.times||5,p=2*d+(h||l?1:0),f=e.duration/p,g=e.easing,m="up"===c||"down"===c?"top":"left",_="up"===c||"left"===c,v=0,b=a.queue().length;for(t.effects.createPlaceholder(a),o=a.css(m),u||(u=a["top"===m?"outerHeight":"outerWidth"]()/3),h&&((n={opacity:1})[m]=o,a.css("opacity",0).css(m,_?-(2*u):2*u).animate(n,f,g)),l&&(u/=Math.pow(2,d-1)),(n={})[m]=o;v<d;v++)(s={})[m]=(_?"-=":"+=")+u,a.animate(s,f,g).animate(n,f,g),u=l?2*u:u/2;l&&((s={opacity:0}
vendor: 4,374 bytes, line 12426
12426)[m]=(_?"-=":"+=")+u,a.animate(s,f,g)),a.queue(i),t.effects.unshift(a,b,p+1)}),t.effects.define("clip","hide",function(e,i){var s,n={},o=t(this),a=e.direction||"vertical",r="both"===a,l=r||"horizontal"===a,h=r||"vertical"===a;s=o.cssClip(),n.clip={top:h?(s.bottom-s.top)/2:s.top,right:l?(s.right-s.left)/2:s.right,bottom:h?(s.bottom-s.top)/2:s.bottom,left:l?(s.right-s.left)/2:s.left},t.effects.createPlaceholder(o),"show"===e.mode&&(o.cssClip(n.clip),n.clip=s),o.animate(n,{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("drop","hide",function(e,i){var s,n=t(this),o=e.mode,a=e.direction||"left",r="up"===a||"down"===a?"top":"left",l="up"===a||"left"===a?"-=":"+=",h={opacity:0};t.effects.createPlaceholder(n),s=e.distance||n["top"===r?"outerHeight":"outerWidth"](!0)/2,h[r]=l+s,"show"===o&&(n.css(h),h[r]=("+="===l?"-=":"+=")+s,h.opacity=1),n.animate(h,{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("explode","hide",function(e,i){var s,n,o,a,r,l,h=e.pieces?Math.round(Math.sqrt(e.pieces)):3,c=t(this),u="show"===e.mode,d=c.show().css("visibility","hidden").offset(),p=Math.ceil(c.outerWidth()/h),f=Math.ceil(c.outerHeight()/h),g=[];function m(){g.push(this),g.length===h*h&&(c.css({visibility:"visible"}),t(g).remove(),i())}for(s=0;s<h;s++)for(n=0,a=d.top+s*f,l=s-(h-1)/2;n<h;n++)o=d.left+n*p,r=n-(h-1)/2,c.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-n*p,top:-s*f}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:p,height:f,left:o+(u?r*p:0),top:a+(u?l*f:0),opacity:+!u}).animate({left:o+(u?0:r*p),top:a+(u?0:l*f),opacity:+!!u},e.duration||500,e.easing,m)}),t.effects.define("fade","toggle",function(e,i){var s="show"===e.mode;t(this).css("opacity",+!s).animate({opacity:+!!s},{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("fold","hide",function(e,i){var s=t(this),n=e.mode,o=e.size||15,a=/([0-9]+)%/.exec(o),r=e.horizFirst?["right","bottom"]:["bottom","right"],l=e.duration/2,h=t.effects.createPlaceholder(s),c=s.cssClip(),u={clip:t.extend({},c)},d={clip:t.extend({},c)},p=[c[r[0]],c[r[1]]],f=s.queue().length;a&&(o=parseInt(a[1],10)/100*p[+("hide"!==n)]),u.clip[r[0]]=o,d.clip[r[0]]=o,d.clip[r[1]]=0,"show"===n&&(s.cssClip(d.clip),h&&h.css(t.effects.clipToBox(d)),d.clip=c),s.queue(function(i){h&&h.animate(t.effects.clipToBox(u),l,e.easing).animate(t.effects.clipToBox(d),l,e.easing),i()}).animate(u,l,e.easing).animate(d,l,e.easing).queue(i),t.effects.unshift(s,f,4)}),t.effects.define("highlight","show",function(e,i){var s=t(this),n={backgroundColor:s.css("backgroundColor")};"hide"===e.mode&&(n.opacity=0),t.effects.saveStyle(s),s.css({backgroundImage:"none",backgroundColor:e.color||"#ffff99"}).animate(n,{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("size",function(e,i){var s,n,o,a=t(this),r=["fontSize"],l=["borderTopWidth","borderBottomWidth","paddingTop","paddingBottom"],h=["borderLeftWidth","borderRightWidth","paddingLeft","paddingRight"],c=e.mode,u="effect"!==c,d=e.scale||"both",p=e.origin||["middle","center"],f=a.css("position"),g=a.position(),m=t.effects.scaledDimensions(a),_=e.from||m,v=e.to||t.effects.scaledDimensions(a,0);t.effects.createPlaceholder(a),"show"===c&&(o=_,_=v,v=o),n={from:{y:_.height/m.height,x:_.width/m.width},to:{y:v.height/m.height,x:v.width/m.width}},("box"===d||"both"===d)&&(n.from.y!==n.to.y&&(_=t.effects.setTransition(a,l,n.from.y,_),v=t.effects.setTransition(a,l,n.to.y,v)),n.from.x!==n.to.x&&(_=t.effects.setTransition(a,h,n.from.x,_),v=t.effects.setTransition(a,h,n.to.x,v))),("content"===d||"both"===d)&&n.from.y!==n.to.y&&(_=t.effects.setTransition(a,r,n.from.y,_),v=t.effects.setTransition(a,r,n.to.y,v)),p&&(s=t.effects.getBaseline(p,m),_.top=(m.outerHeight-_.outerHeight)*s.y+g.top,_.left=(m.outerWidth-_.outerWidth)*s.x+g.left,v.top=(m.outerHeight-v.outerHeight)*s.y+g.top,v.left=(m.outerWidth-v.outerWidth)*s.x+g.left),delete _.outerHeight,delete _.outerWidth,a.css(_),("content"===d||"both"===d)&&(l=l.concat(["marginTop","marginBottom"]).concat(r),h=h.concat(["marginLeft","marginRight"]),a.find("*[width]").each(function(){var i=t(this),s=t.effects.scaledDimensions(i),o={height:s.height*n.from.y,width:s.width*n.from.x,outerHeight:s.outerHeight*n.from.y,outerWidth:s.outerWidth*n.from.x}
vendor: 10,317 bytes, line 12426
12426,a={height:s.height*n.to.y,width:s.width*n.to.x,outerHeight:s.height*n.to.y,outerWidth:s.width*n.to.x};n.from.y!==n.to.y&&(o=t.effects.setTransition(i,l,n.from.y,o),a=t.effects.setTransition(i,l,n.to.y,a)),n.from.x!==n.to.x&&(o=t.effects.setTransition(i,h,n.from.x,o),a=t.effects.setTransition(i,h,n.to.x,a)),u&&t.effects.saveStyle(i),i.css(o),i.animate(a,e.duration,e.easing,function(){u&&t.effects.restoreStyle(i)})})),a.animate(v,{queue:!1,duration:e.duration,easing:e.easing,complete:function(){var e=a.offset();0===v.opacity&&a.css("opacity",_.opacity),u||(a.css("position","static"===f?"relative":f).offset(e),t.effects.saveStyle(a)),i()}})}),t.effects.define("scale",function(e,i){var s=t(this),n=e.mode,o=parseInt(e.percent,10)||(0===parseInt(e.percent,10)?0:100*("effect"===n)),a=t.extend(!0,{from:t.effects.scaledDimensions(s),to:t.effects.scaledDimensions(s,o,e.direction||"both"),origin:e.origin||["middle","center"]},e);e.fade&&(a.from.opacity=1,a.to.opacity=0),t.effects.effect.size.call(this,a,i)}),t.effects.define("puff","hide",function(e,i){var s=t.extend(!0,{},e,{fade:!0,percent:parseInt(e.percent,10)||150});t.effects.effect.scale.call(this,s,i)}),t.effects.define("pulsate","show",function(e,i){var s=t(this),n=e.mode,o="show"===n,a=2*(e.times||5)+ +!!(o||"hide"===n),r=e.duration/a,l=0,h=1,c=s.queue().length;for((o||!s.is(":visible"))&&(s.css("opacity",0).show(),l=1);h<a;h++)s.animate({opacity:l},r,e.easing),l=1-l;s.animate({opacity:l},r,e.easing),s.queue(i),t.effects.unshift(s,c,a+1)}),t.effects.define("shake",function(e,i){var s=1,n=t(this),o=e.direction||"left",a=e.distance||20,r=e.times||3,l=2*r+1,h=Math.round(e.duration/l),c="up"===o||"down"===o?"top":"left",u="up"===o||"left"===o,d={},p={},f={},g=n.queue().length;for(t.effects.createPlaceholder(n),d[c]=(u?"-=":"+=")+a,p[c]=(u?"+=":"-=")+2*a,f[c]=(u?"-=":"+=")+2*a,n.animate(d,h,e.easing);s<r;s++)n.animate(p,h,e.easing).animate(f,h,e.easing);n.animate(p,h,e.easing).animate(d,h/2,e.easing).queue(i),t.effects.unshift(n,g,l+1)}),t.effects.define("slide","show",function(e,i){var s,n,o=t(this),a={up:["bottom","top"],down:["top","bottom"],left:["right","left"],right:["left","right"]},r=e.mode,l=e.direction||"left",h="up"===l||"down"===l?"top":"left",c=e.distance||o["top"===h?"outerHeight":"outerWidth"](!0),u={};t.effects.createPlaceholder(o),s=o.cssClip(),n=o.position()[h],u[h]=("up"===l||"left"===l?-1:1)*c+n,u.clip=o.cssClip(),u.clip[a[l][1]]=u.clip[a[l][0]],"show"===r&&(o.cssClip(u.clip),o.css(h,u[h]),u.clip=s,u[h]=n),o.animate(u,{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),!0===t.uiBackCompat&&t.effects.define("transfer",function(e,i){t(this).transfer(e,i)}),t.ui.focusable=function(e,i){var s,n,o,a,r,l=e.nodeName.toLowerCase();return"area"===l?(n=(s=e.parentNode).name,!!e.href&&!!n&&"map"===s.nodeName.toLowerCase()&&(o=t("img[usemap='#"+n+"']")).length>0&&o.is(":visible")):(/^(input|select|textarea|button|object)$/.test(l)?(a=!e.disabled)&&(r=t(e).closest("fieldset")[0])&&(a=!r.disabled):a="a"===l&&e.href||i,a&&t(e).is(":visible")&&"visible"===t(e).css("visibility"))},t.extend(t.expr.pseudos,{focusable:function(e){return t.ui.focusable(e,null!=t.attr(e,"tabindex"))}}),t.ui.focusable,t.ui.formResetMixin={_formResetHandler:function(){var e=t(this);setTimeout(function(){var i=e.data("ui-form-reset-instances");t.each(i,function(){this.refresh()})})},_bindFormResetHandler:function(){if(this.form=t(this.element.prop("form")),this.form.length){var e=this.form.data("ui-form-reset-instances")||[];e.length||this.form.on("reset.ui-form-reset",this._formResetHandler),e.push(this),this.form.data("ui-form-reset-instances",e)}},_unbindFormResetHandler:function(){if(this.form.length){var e=this.form.data("ui-form-reset-instances");e.splice(t.inArray(this,e),1),e.length?this.form.data("ui-form-reset-instances",e):this.form.removeData("ui-form-reset-instances").off("reset.ui-form-reset")}}},t.escapeSelector||(t.escapeSelector=function(t){return CSS.escape(t+"")}),t.fn.even&&t.fn.odd||t.fn.extend({even:function(){return this.filter(function(t){return t%2==0})},odd:function(){return this.filter(function(t){return t%2==1})}}),t.ui.keyCode={BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38},t.fn.labels=function(){var t,e,i,s,n;return this.length?this[0].labels&&this[0].labels.length?this.pushStack(this[0].labels):(s=this.eq(0).parents("label"),(i=this.attr("id"))&&(n=(t=this.eq(0).parents().last()).add(t.length?t.siblings():this.siblings()),e="label[for='"+CSS.escape(i)+"']",s=s.add(n.find(e).addBack(e))),this.pushStack(s)):this.pushStack([])},t.fn.scrollParent=function(e){var i=this.css("position"),s="absolute"===i,n=e?/(auto|scroll|hidden)/:/(auto|scroll)/,o=this.parents().filter(function(){var e=t(this);return(!s||"static"!==e.css("position"))&&n.test(e.css("overflow")+e.css("overflow-y")+e.css("overflow-x"))}).eq(0);return"fixed"!==i&&o.length?o:t(this[0].ownerDocument||document)},t.extend(t.expr.pseudos,{tabbable:function(e){var i=t.attr(e,"tabindex"),s=null!=i;return(!s||i>=0)&&t.ui.focusable(e,s)}}),t.fn.extend({uniqueId:(i=0,function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++i)})}),removeUniqueId:function(){return this.each(function(){/^ui-id-\d+$/.test(this.id)&&t(this).removeAttr("id")})}}),t.widget("ui.accordion",{version:"1.14.2",options:{active:0,animate:{},classes:{"ui-accordion-header":"ui-corner-top","ui-accordion-header-collapsed":"ui-corner-all","ui-accordion-content":"ui-corner-bottom"},collapsible:!1,event:"click",header:function(t){return t.find("> li > :first-child").add(t.find("> :not(li)").filter(function(t){return t%2==0}))},heightStyle:"auto",icons:{activeHeader:"ui-icon-triangle-1-s",header:"ui-icon-triangle-1-e"},activate:null,beforeActivate:null},hideProps:{borderTopWidth:"hide",borderBottomWidth:"hide",paddingTop:"hide",paddingBottom:"hide",height:"hide"},showProps:{borderTopWidth:"show",borderBottomWidth:"show",paddingTop:"show",paddingBottom:"show",height:"show"},_create:function(){var e=this.options;this.prevShow=this.prevHide=t(),this._addClass("ui-accordion","ui-widget ui-helper-reset"),this.element.attr("role","tablist"),e.collapsible||!1!==e.active&&null!=e.active||(e.active=0),this._processPanels(),e.active<0&&(e.active+=this.headers.length),this._refresh()},_getCreateEventData:function(){return{header:this.active,panel:this.active.length?this.active.next():t()}},_createIcons:function(){var e,i,s=this.options.icons;s&&(e=t("<span>"),this._addClass(e,"ui-accordion-header-icon","ui-icon "+s.header),e.prependTo(this.headers),i=this.active.children(".ui-accordion-header-icon"),this._removeClass(i,s.header)._addClass(i,null,s.activeHeader)._addClass(this.headers,"ui-accordion-icons"))},_destroyIcons:function(){this._removeClass(this.headers,"ui-accordion-icons"),this.headers.children(".ui-accordion-header-icon").remove()},_destroy:function(){var t;this.element.removeAttr("role"),this.headers.removeAttr("role aria-expanded aria-selected aria-controls tabIndex").removeUniqueId(),this._destroyIcons(),t=this.headers.next().css("display","").removeAttr("role aria-hidden aria-labelledby").removeUniqueId(),"content"!==this.options.heightStyle&&t.css("height","")},_setOption:function(t,e){if("active"===t){this._activate(e);return}"event"===t&&(this.options.event&&this._off(this.headers,this.options.event),this._setupEvents(e)),this._super(t,e),"collapsible"!==t||e||!1!==this.options.active||this._activate(0),"icons"===t&&(this._destroyIcons(),e&&this._createIcons())},_setOptionDisabled:function(t){this._super(t),this.element.attr("aria-disabled",t),this._toggleClass(null,"ui-state-disabled",!!t)},_keydown:function(e){if(!e.altKey&&!e.ctrlKey){var i=t.ui.keyCode,s=this.headers.length,n=this.headers.index(e.target),o=!1;switch(e.keyCode){case i.RIGHT:case i.DOWN:o=this.headers[(n+1)%s];break;case i.LEFT:case i.UP:o=this.headers[(n-1+s)%s];break;case i.SPACE:case i.ENTER:this._eventHandler(e);break;case i.HOME:o=this.headers[0];break;case i.END:o=this.headers[s-1]}o&&(t(e.target).attr("tabIndex",-1),t(o).attr("tabIndex",0),t(o).trigger("focus"),e.preventDefault())}},_panelKeyDown:function(e){e.keyCode===t.ui.keyCode.UP&&e.ctrlKey&&t(e.currentTarget).prev().trigger("focus")},refresh:function(){var e=this.options;this._processPanels(),(!1!==e.active||!0!==e.collapsible)&&this.headers.length?!1===e.active?this._activate(0):this.active.length&&!t.contains(this.element[0],this.active[0])?this.headers.length===this.headers.find(".ui-state-disabled").length?(e.active=!1,this.active=t()):this._activate(Math.max(0,e.active-1)):e.active=this.headers.index(this.active):(e.active=!1,this.active=t()),this._destroyIcons(),this._refresh()},_processPanels:function(){var t=this.headers,e=this.panels;"function"==typeof this.options.header?this.headers=this.options.header(this.element):this.headers=this.element.find(this.options.header),this._addClass(this.headers,"ui-accordion-header ui-accordion-header-collapsed","ui-state-default"),this.panels=this.headers.next().filter(":not(.ui-accordion-content-active)").hide(),this._addClass(this.panels,"ui-accordion-content","ui-helper-reset ui-widget-content"),e&&(this._off(t.not(this.headers)),this._off(e.not(this.panels)))},_refresh:function(){var e,i=this.options,s=i.heightStyle,n=this.element.parent();this.active=this._findActive(i.active),this._addClass(this.active,"ui-accordion-header-active","ui-state-active")._removeClass(this.active,"ui-accordion-header-collapsed"),this._addClass(this.active.next(),"ui-accordion-content-active"),this.active.next().show(),this.headers.attr("role","tab").each(function(){var e=t(this),i=e.uniqueId().attr("id"),s=e.next(),n=s.uniqueId().attr("id");e.attr("aria-controls",n),s.attr("aria-labelledby",i)}).next().attr("role","tabpanel"),this.headers.not(this.active).attr({"aria-selected":"false","aria-expanded":"false",tabIndex:-1}).next().attr({"aria-hidden":"true"}).hide(),this.active.length?this.active.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0}).next().attr({"aria-hidden":"false"}):this.headers.eq(0).attr("tabIndex",0),this._createIcons(),this._setupEvents(i.event),"fill"===s?(e=n.height(),this.element.siblings(":visible").each(function(){var i=t(this),s=i.
vendor: 4,770 bytes, line 12426
12426css("position");"absolute"!==s&&"fixed"!==s&&(e-=i.outerHeight(!0))}),this.headers.each(function(){e-=t(this).outerHeight(!0)}),this.headers.next().each(function(){t(this).height(Math.max(0,e-t(this).innerHeight()+t(this).height()))}).css("overflow","auto")):"auto"===s&&(e=0,this.headers.next().each(function(){var i=t(this).is(":visible");i||t(this).show(),e=Math.max(e,t(this).css("height","").height()),i||t(this).hide()}).height(e))},_activate:function(e){var i=this._findActive(e)[0];i!==this.active[0]&&(i=i||this.active[0],this._eventHandler({target:i,currentTarget:i,preventDefault:t.noop}))},_findActive:function(e){return"number"==typeof e?this.headers.eq(e):t()},_setupEvents:function(e){var i={keydown:"_keydown"};e&&t.each(e.split(" "),function(t,e){i[e]="_eventHandler"}),this._off(this.headers.add(this.headers.next())),this._on(this.headers,i),this._on(this.headers.next(),{keydown:"_panelKeyDown"}),this._hoverable(this.headers),this._focusable(this.headers)},_eventHandler:function(e){var i,s,n=this.options,o=this.active,a=t(e.currentTarget),r=a[0]===o[0],l=r&&n.collapsible,h=l?t():a.next(),c=o.next(),u={oldHeader:o,oldPanel:c,newHeader:l?t():a,newPanel:h};e.preventDefault(),(!r||n.collapsible)&&!1!==this._trigger("beforeActivate",e,u)&&(n.active=!l&&this.headers.index(a),this.active=r?t():a,this._toggle(u),this._removeClass(o,"ui-accordion-header-active","ui-state-active"),n.icons&&(i=o.children(".ui-accordion-header-icon"),this._removeClass(i,null,n.icons.activeHeader)._addClass(i,null,n.icons.header)),r||(this._removeClass(a,"ui-accordion-header-collapsed")._addClass(a,"ui-accordion-header-active","ui-state-active"),n.icons&&(s=a.children(".ui-accordion-header-icon"),this._removeClass(s,null,n.icons.header)._addClass(s,null,n.icons.activeHeader)),this._addClass(a.next(),"ui-accordion-content-active")))},_toggle:function(e){var i=e.newPanel,s=this.prevShow.length?this.prevShow:e.oldPanel;this.prevShow.add(this.prevHide).stop(!0,!0),this.prevShow=i,this.prevHide=s,this.options.animate?this._animate(i,s,e):(s.hide(),i.show(),this._toggleComplete(e)),s.attr({"aria-hidden":"true"}),s.prev().attr({"aria-selected":"false","aria-expanded":"false"}),i.length&&s.length?s.prev().attr({tabIndex:-1,"aria-expanded":"false"}):i.length&&this.headers.filter(function(){return 0===parseInt(t(this).attr("tabIndex"),10)}).attr("tabIndex",-1),i.attr("aria-hidden","false").prev().attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0})},_animate:function(t,e,i){var s,n,o,a=this,r=0,l=t.css("box-sizing"),h=t.length&&(!e.length||t.index()<e.index()),c=this.options.animate||{},u=h&&c.down||c,d=function(){a._toggleComplete(i)};return("number"==typeof u&&(o=u),"string"==typeof u&&(n=u),n=n||u.easing||c.easing,o=o||u.duration||c.duration,e.length)?t.length?void(s=t.show().outerHeight(),e.animate(this.hideProps,{duration:o,easing:n,step:function(t,e){e.now=Math.round(t)}}),t.hide().animate(this.showProps,{duration:o,easing:n,complete:d,step:function(t,i){i.now=Math.round(t),"height"!==i.prop?"content-box"===l&&(r+=i.now):"content"!==a.options.heightStyle&&(i.now=Math.round(s-e.outerHeight()-r),r=0)}})):e.animate(this.hideProps,o,n,d):t.animate(this.showProps,o,n,d)},_toggleComplete:function(t){var e=t.oldPanel,i=e.prev();this._removeClass(e,"ui-accordion-content-active"),this._removeClass(i,"ui-accordion-header-active")._addClass(i,"ui-accordion-header-collapsed"),this._trigger("activate",null,t)}}),t.widget("ui.menu",{version:"1.14.2",defaultElement:"<ul>",delay:300,options:{icons:{submenu:"ui-icon-caret-1-e"},items:"> *",menus:"ul",position:{my:"left top",at:"right top"},role:"menu",blur:null,focus:null,select:null},_create:function(){this.activeMenu=this.element,this.mouseHandled=!1,this.lastMousePosition={x:null,y:null},this.element.uniqueId().attr({role:this.options.role,tabIndex:0}),this._addClass("ui-menu","ui-widget ui-widget-content"),this._on({"mousedown .ui-menu-item":function(t){t.preventDefault(),this._activateItem(t)},"click .ui-menu-item":function(e){var i=t(e.target),s=t(this.document[0].activeElement);!this.mouseHandled&&i.not(".ui-state-disabled").length&&(this.select(e),e.isPropagationStopped()||(this.mouseHandled=!0),i.has(".ui-menu").length?this.expand(e):!this.element.is(":focus")&&s.closest(".ui-menu").length&&(this.element.trigger("focus",[!0]),this.active&&1===this.active.parents(".ui-menu").length&&clearTimeout(this.timer)))},"mouseenter .ui-menu-item":"_activateItem","mousemove .ui-menu-item":"_activateItem",mouseleave:"collapseAll","mouseleave .ui-menu":"collapseAll",focus:function(t,e){var i=this.active||this._menuItems().first();e||this.focus(t,i)},blur:function(e){this._delay(function(){t.contains(this.element[0],this.document[0].activeElement)||this.collapseAll(e)}
vendor: 26,610 bytes, line 12426
12426)},keydown:"_keydown"}),this.refresh(),this._on(this.document,{click:function(t){this._closeOnDocumentClick(t)&&this.collapseAll(t,!0),this.mouseHandled=!1}})},_activateItem:function(e){if(!this.previousFilter&&(e.clientX!==this.lastMousePosition.x||e.clientY!==this.lastMousePosition.y)){this.lastMousePosition={x:e.clientX,y:e.clientY};var i=t(e.target).closest(".ui-menu-item"),s=t(e.currentTarget);!(i[0]!==s[0]||s.is(".ui-state-active"))&&(this._removeClass(s.siblings().children(".ui-state-active"),null,"ui-state-active"),this.focus(e,s))}},_destroy:function(){var e=this.element.find(".ui-menu-item").removeAttr("role aria-disabled").children(".ui-menu-item-wrapper").removeUniqueId().removeAttr("tabIndex role aria-haspopup");this.element.removeAttr("aria-activedescendant").find(".ui-menu").addBack().removeAttr("role aria-labelledby aria-expanded aria-hidden aria-disabled tabIndex").removeUniqueId().show(),e.children().each(function(){var e=t(this);e.data("ui-menu-submenu-caret")&&e.remove()})},_keydown:function(e){var i,s,n,o,a=!0;switch(e.keyCode){case t.ui.keyCode.PAGE_UP:this.previousPage(e);break;case t.ui.keyCode.PAGE_DOWN:this.nextPage(e);break;case t.ui.keyCode.HOME:this._move("first","first",e);break;case t.ui.keyCode.END:this._move("last","last",e);break;case t.ui.keyCode.UP:this.previous(e);break;case t.ui.keyCode.DOWN:this.next(e);break;case t.ui.keyCode.LEFT:this.collapse(e);break;case t.ui.keyCode.RIGHT:this.active&&!this.active.is(".ui-state-disabled")&&this.expand(e);break;case t.ui.keyCode.ENTER:case t.ui.keyCode.SPACE:this._activate(e);break;case t.ui.keyCode.ESCAPE:this.collapse(e);break;default:a=!1,s=this.previousFilter||"",o=!1,n=e.keyCode>=96&&e.keyCode<=105?(e.keyCode-96).toString():String.fromCharCode(e.keyCode),clearTimeout(this.filterTimer),n===s?o=!0:n=s+n,i=this._filterMenuItems(n),(i=o&&-1!==i.index(this.active.next())?this.active.nextAll(".ui-menu-item"):i).length||(n=String.fromCharCode(e.keyCode),i=this._filterMenuItems(n)),i.length?(this.focus(e,i),this.previousFilter=n,this.filterTimer=this._delay(function(){delete this.previousFilter},1e3)):delete this.previousFilter}a&&e.preventDefault()},_activate:function(t){this.active&&!this.active.is(".ui-state-disabled")&&(this.active.children("[aria-haspopup='true']").length?this.expand(t):this.select(t))},refresh:function(){var e,i,s,n,o=this,a=this.options.icons.submenu,r=this.element.find(this.options.menus);this._toggleClass("ui-menu-icons",null,!!this.element.find(".ui-icon").length),i=r.filter(":not(.ui-menu)").hide().attr({role:this.options.role,"aria-hidden":"true","aria-expanded":"false"}).each(function(){var e=t(this),i=e.prev(),s=t("<span>").data("ui-menu-submenu-caret",!0);o._addClass(s,"ui-menu-icon","ui-icon "+a),i.attr("aria-haspopup","true").prepend(s),e.attr("aria-labelledby",i.attr("id"))}),this._addClass(i,"ui-menu","ui-widget ui-widget-content ui-front"),(e=r.add(this.element).find(this.options.items)).not(".ui-menu-item").each(function(){var e=t(this);o._isDivider(e)&&o._addClass(e,"ui-menu-divider","ui-widget-content")}),n=(s=e.not(".ui-menu-item, .ui-menu-divider")).children().not(".ui-menu").uniqueId().attr({tabIndex:-1,role:this._itemRole()}),this._addClass(s,"ui-menu-item")._addClass(n,"ui-menu-item-wrapper"),e.filter(".ui-state-disabled").attr("aria-disabled","true"),this.active&&!t.contains(this.element[0],this.active[0])&&this.blur()},_itemRole:function(){return({menu:"menuitem",listbox:"option"})[this.options.role]},_setOption:function(t,e){if("icons"===t){var i=this.element.find(".ui-menu-icon");this._removeClass(i,null,this.options.icons.submenu)._addClass(i,null,e.submenu)}this._super(t,e)},_setOptionDisabled:function(t){this._super(t),this.element.attr("aria-disabled",String(t)),this._toggleClass(null,"ui-state-disabled",!!t)},focus:function(t,e){var i,s,n;this.blur(t,t&&"focus"===t.type),this._scrollIntoView(e),this.active=e.first(),s=this.active.children(".ui-menu-item-wrapper"),this._addClass(s,null,"ui-state-active"),this.options.role&&this.element.attr("aria-activedescendant",s.attr("id")),n=this.active.parent().closest(".ui-menu-item").children(".ui-menu-item-wrapper"),this._addClass(n,null,"ui-state-active"),t&&"keydown"===t.type?this._close():this.timer=this._delay(function(){this._close()},this.delay),(i=e.children(".ui-menu")).length&&t&&/^mouse/.test(t.type)&&this._startOpening(i),this.activeMenu=e.parent(),this._trigger("focus",t,{item:e})},_scrollIntoView:function(e){var i,s,n,o,a,r;this._hasScroll()&&(i=parseFloat(t.css(this.activeMenu[0],"borderTopWidth"))||0,s=parseFloat(t.css(this.activeMenu[0],"paddingTop"))||0,n=e.offset().top-this.activeMenu.offset().top-i-s,o=this.activeMenu.scrollTop(),a=this.activeMenu.height(),r=e.outerHeight(),n<0?this.activeMenu.scrollTop(o+n):n+r>a&&this.activeMenu.scrollTop(o+n-a+r))},blur:function(t,e){e||clearTimeout(this.timer),this.active&&(this._removeClass(this.active.children(".ui-menu-item-wrapper"),null,"ui-state-active"),this._trigger("blur",t,{item:this.active}),this.active=null)},_startOpening:function(t){clearTimeout(this.timer),"true"===t.attr("aria-hidden")&&(this.timer=this._delay(function(){this._close(),this._open(t)},this.delay))},_open:function(e){var i=t.extend({of:this.active},this.options.position);clearTimeout(this.timer),this.element.find(".ui-menu").not(e.parents(".ui-menu")).hide().attr("aria-hidden","true"),e.show().removeAttr("aria-hidden").attr("aria-expanded","true").position(i)},collapseAll:function(e,i){clearTimeout(this.timer),this.timer=this._delay(function(){var s=i?this.element:t(e&&e.target).closest(this.element.find(".ui-menu"));s.length||(s=this.element),this._close(s),this.blur(e),this._removeClass(s.find(".ui-state-active"),null,"ui-state-active"),this.activeMenu=s},i?0:this.delay)},_close:function(t){t||(t=this.active?this.active.parent():this.element),t.find(".ui-menu").hide().attr("aria-hidden","true").attr("aria-expanded","false")},_closeOnDocumentClick:function(e){return!t(e.target).closest(".ui-menu").length},_isDivider:function(t){return!/[^\-\u2014\u2013\s]/.test(t.text())},collapse:function(t){var e=this.active&&this.active.parent().closest(".ui-menu-item",this.element);e&&e.length&&(this._close(),this.focus(t,e))},expand:function(t){var e=this.active&&this._menuItems(this.active.children(".ui-menu")).first();e&&e.length&&(this._open(e.parent()),this._delay(function(){this.focus(t,e)}))},next:function(t){this._move("next","first",t)},previous:function(t){this._move("prev","last",t)},isFirstItem:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},isLastItem:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},_menuItems:function(t){return(t||this.element).find(this.options.items).filter(".ui-menu-item")},_move:function(t,e,i){var s;this.active&&(s="first"===t||"last"===t?this.active["first"===t?"prevAll":"nextAll"](".ui-menu-item").last():this.active[t+"All"](".ui-menu-item").first()),s&&s.length&&this.active||(s=this._menuItems(this.activeMenu)[e]()),this.focus(i,s)},nextPage:function(e){var i,s,n;if(!this.active){this.next(e);return}!this.isLastItem()&&(this._hasScroll()?(s=this.active.offset().top,n=this.element.innerHeight(),0===t.fn.jquery.indexOf("3.2.")&&(n+=this.element[0].offsetHeight-this.element.outerHeight()),this.active.nextAll(".ui-menu-item").each(function(){return(i=t(this)).offset().top-s-n<0}),this.focus(e,i)):this.focus(e,this._menuItems(this.activeMenu)[this.active?"last":"first"]()))},previousPage:function(e){var i,s,n;if(!this.active){this.next(e);return}!this.isFirstItem()&&(this._hasScroll()?(s=this.active.offset().top,n=this.element.innerHeight(),0===t.fn.jquery.indexOf("3.2.")&&(n+=this.element[0].offsetHeight-this.element.outerHeight()),this.active.prevAll(".ui-menu-item").each(function(){return(i=t(this)).offset().top-s+n>0}),this.focus(e,i)):this.focus(e,this._menuItems(this.activeMenu).first()))},_hasScroll:function(){return this.element.outerHeight()<this.element.prop("scrollHeight")},select:function(e){this.active=this.active||t(e.target).closest(".ui-menu-item");var i={item:this.active};this.active.has(".ui-menu").length||this.collapseAll(e,!0),this._trigger("select",e,i)},_filterMenuItems:function(e){var i=RegExp("^"+e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&"),"i");return this.activeMenu.find(this.options.items).filter(".ui-menu-item").filter(function(){return i.test(String.prototype.trim.call(t(this).children(".ui-menu-item-wrapper").text()))})}}),t.widget("ui.autocomplete",{version:"1.14.2",defaultElement:"<input>",options:{appendTo:null,autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null,change:null,close:null,focus:null,open:null,response:null,search:null,select:null},requestIndex:0,pending:0,liveRegionTimer:null,_create:function(){var e,i,s,n=this.element[0].nodeName.toLowerCase(),o="textarea"===n,a="input"===n;this.isMultiLine=o||!a&&"true"===this.element.prop("contentEditable"),this.valueMethod=this.element[o||a?"val":"text"],this.isNewMenu=!0,this._addClass("ui-autocomplete-input"),this.element.attr("autocomplete","off"),this._on(this.element,{keydown:function(n){if(this.element.prop("readOnly")){e=!0,s=!0,i=!0;return}e=!1,s=!1,i=!1;var o=t.ui.keyCode;switch(n.keyCode){case o.PAGE_UP:e=!0,this._move("previousPage",n);break;case o.PAGE_DOWN:e=!0,this._move("nextPage",n);break;case o.UP:e=!0,this._keyEvent("previous",n);break;case o.DOWN:e=!0,this._keyEvent("next",n);break;case o.ENTER:this.menu.active&&(e=!0,n.preventDefault(),this.menu.select(n));break;case o.TAB:this.menu.active&&this.menu.select(n);break;case o.ESCAPE:this.menu.element.is(":visible")&&(this.isMultiLine||this._value(this.term),this.close(n),n.preventDefault());break;default:i=!0,this._searchTimeout(n)}},keypress:function(s){if(e){e=!1,(!this.isMultiLine||this.menu.element.is(":visible"))&&s.preventDefault();return}if(!i){var n=t.ui.keyCode;switch(s.keyCode){case n.PAGE_UP:this._move("previousPage",s);break;case n.PAGE_DOWN:this._move("nextPage",s);break;case n.UP:this._keyEvent("previous",s);break;case n.DOWN:this._keyEvent("next",s)}}},input:function(t){if(s){s=!1,t.preventDefault();return}this._searchTimeout(t)},focus:function(){this.selectedItem=null,this.previous=this._value()},blur:function(t){clearTimeout(this.searching),this.close(t),this._change(t)}}),this._initSource(),this.menu=t("<ul>").appendTo(this._appendTo()).menu({role:null}).hide().menu("instance"),this._addClass(this.menu.element,"ui-autocomplete","ui-front"),this._on(this.menu.element,{mousedown:function(t){t.preventDefault()},menufocus:function(e,i){var s,n;if(this.isNewMenu&&(this.isNewMenu=!1,e.originalEvent&&/^mouse/.test(e.originalEvent.type))){this.menu.blur(),this.document.one("mousemove",function(){t(e.target).trigger(e.originalEvent)});return}n=i.item.data("ui-autocomplete-item"),!1!==this._trigger("focus",e,{item:n})&&e.originalEvent&&/^key/.test(e.originalEvent.type)&&this._value(n.value),(s=i.item.attr("aria-label")||n.value)&&String.prototype.trim.call(s).length&&(clearTimeout(this.liveRegionTimer),this.liveRegionTimer=this._delay(function(){this.liveRegion.html(t("<div>").text(s))},100))},menuselect:function(t,e){var i=e.item.data("ui-autocomplete-item"),s=this.previous;this.element[0]!==this.document[0].activeElement&&(this.element.trigger("focus"),this.previous=s),!1!==this._trigger("select",t,{item:i})&&this._value(i.value),this.term=this._value(),this.close(t),this.selectedItem=i}}),this.liveRegion=t("<div>",{role:"status","aria-live":"assertive","aria-relevant":"additions"}).appendTo(this.document[0].body),this._addClass(this.liveRegion,null,"ui-helper-hidden-accessible"),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_destroy:function(){clearTimeout(this.searching),this.element.removeAttr("autocomplete"),this.menu.element.remove(),this.liveRegion.remove()},_setOption:function(t,e){this._super(t,e),"source"===t&&this._initSource(),"appendTo"===t&&this.menu.element.appendTo(this._appendTo()),"disabled"===t&&e&&this.xhr&&this.xhr.abort()},_isEventTargetInWidget:function(e){var i=this.menu.element[0];return e.target===this.element[0]||e.target===i||t.contains(i,e.target)},_closeOnClickOutside:function(t){this._isEventTargetInWidget(t)||this.close()},_appendTo:function(){var e=this.options.appendTo;return e&&(e=e.jquery||e.nodeType?t(e):this.document.find(e).eq(0)),e&&e[0]||(e=this.element.closest(".ui-front, dialog")),e.length||(e=this.document[0].body),e},_initSource:function(){var e,i,s=this;Array.isArray(this.options.source)?(e=this.options.source,this.source=function(i,s){s(t.ui.autocomplete.filter(e,i.term))}):"string"==typeof this.options.source?(i=this.options.source,this.source=function(e,n){s.xhr&&s.xhr.abort(),s.xhr=t.ajax({url:i,data:e,dataType:"json",success:function(t){n(t)},error:function(){n([])}})}):this.source=this.options.source},_searchTimeout:function(t){clearTimeout(this.searching),this.searching=this._delay(function(){var e=this.term===this._value(),i=this.menu.element.is(":visible"),s=t.altKey||t.ctrlKey||t.metaKey||t.shiftKey;e&&(!e||i||s)||(this.selectedItem=null,this.search(null,t))},this.options.delay)},search:function(t,e){return(t=null!=t?t:this._value(),this.term=this._value(),t.length<this.options.minLength)?this.close(e):!1!==this._trigger("search",e)?this._search(t):void 0},_search:function(t){this.pending++,this._addClass("ui-autocomplete-loading"),this.cancelSearch=!1,this.source({term:t},this._response())},_response:function(){var t=++this.requestIndex;return(function(e){t===this.requestIndex&&this.__response(e),this.pending--,this.pending||this._removeClass("ui-autocomplete-loading")}).bind(this)},__response:function(t){t&&(t=this._normalize(t)),this._trigger("response",null,{content:t}),!this.options.disabled&&t&&t.length&&!this.cancelSearch?(this._suggest(t),this._trigger("open")):this._close()},close:function(t){this.cancelSearch=!0,this._close(t)},_close:function(t){this._off(this.document,"mousedown"),this.menu.element.is(":visible")&&(this.menu.element.hide(),this.menu.blur(),this.isNewMenu=!0,this._trigger("close",t))},_change:function(t){this.previous!==this._value()&&this._trigger("change",t,{item:this.selectedItem})},_normalize:function(e){return e.length&&e[0].label&&e[0].value?e:t.map(e,function(e){return"string"==typeof e?{label:e,value:e}:t.extend({},e,{label:e.label||e.value,value:e.value||e.label})})},_suggest:function(e){var i=this.menu.element.empty();this._renderMenu(i,e),this.isNewMenu=!0,this.menu.refresh(),i.show(),this._resizeMenu(),i.position(t.extend({of:this.element},this.options.position)),this.options.autoFocus&&this.menu.next(),this._on(this.document,{mousedown:"_closeOnClickOutside"})},_resizeMenu:function(){var t=this.menu.element;t.outerWidth(Math.max(t.width("").outerWidth()+1,this.element.outerWidth()))},_renderMenu:function(e,i){var s=this;t.each(i,function(t,i){s._renderItemData(e,i)})},_renderItemData:function(t,e){return this._renderItem(t,e).data("ui-autocomplete-item",e)},_renderItem:function(e,i){return t("<li>").append(t("<div>").text(i.label)).appendTo(e)},_move:function(t,e){if(!this.menu.element.is(":visible")){this.search(null,e);return}if(this.menu.isFirstItem()&&/^previous/.test(t)||this.menu.isLastItem()&&/^next/.test(t)){this.isMultiLine||this._value(this.term),this.menu.blur();return}this.menu[t](e)},widget:function(){return this.menu.element},_value:function(){return this.valueMethod.apply(this.element,arguments)},_keyEvent:function(t,e){(!this.isMultiLine||this.menu.element.is(":visible"))&&(this._move(t,e),e.preventDefault())}}),t.extend(t.ui.autocomplete,{escapeRegex:function(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")},filter:function(e,i){var s=RegExp(t.ui.autocomplete.escapeRegex(i),"i");return t.grep(e,function(t){return s.test(t.label||t.value||t)})}}),t.widget("ui.autocomplete",t.ui.autocomplete,{options:{messages:{noResults:"No search results.",results:function(t){return t+(t>1?" results are":" result is")+" available, use up and down arrow keys to navigate."}}},__response:function(e){var i;this._superApply(arguments),!this.options.disabled&&!this.cancelSearch&&(i=e&&e.length?this.options.messages.results(e.length):this.options.messages.noResults,clearTimeout(this.liveRegionTimer),this.liveRegionTimer=this._delay(function(){this.liveRegion.html(t("<div>").text(i))},100))}}),t.ui.autocomplete;var T=/ui-corner-([a-z]){2,6}/g;function P(){this._curInst=null,this._keyEvent=!1,this._disabledInputs=[],this._datepickerShowing=!1,this._inDialog=!1,this._mainDivId="ui-datepicker-div",this._inlineClass="ui-datepicker-inline",this._appendClass="ui-datepicker-append",this._triggerClass="ui-datepicker-trigger",this._dialogClass="ui-datepicker-dialog",this._disableClass="ui-datepicker-disabled",this._unselectableClass="ui-datepicker-unselectable",this._currentClass="ui-datepicker-current-day",this._dayOverClass="ui-datepicker-days-cell-over",this.regional=[],this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:!1,showMonthAfterYear:!1,yearSuffix:"",selectMonthLabel:"Select month",selectYearLabel:"Select year"},this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:!1,hideIfNoPrevNext:!1,navigationAsDateFormat:!1,gotoCurrent:!1,changeMonth:!1,changeYear:!1,yearRange:"c-10:c+10",showOtherMonths:!1,selectOtherMonths:!1,showWeek:!1,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,onUpdateDatepicker:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:!0,showButtonPanel:!1,autoSize:!1,disabled:!1},t.extend(this._defaults,this.regional[""]),this.regional.en=t.extend(!0,{},this.regional[""]),this.regional["en-US"]=t.extend(!0,{},this.regional.en),this.dpDiv=M(t("<div id='"+this._mainDivId+"' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"))}function M(e){var i="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return e.on("mouseout",i,function(){t(this).removeClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&t(this).removeClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&t(this).removeClass("ui-datepicker-next-hover")}).on("mouseover",i,S)}function S(){t.datepicker._isDisabledDatepicker(o.inline?o.dpDiv.parent()[0]:o.input[0])||(t(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"),t(this).addClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&t(this).addClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&t(this).addClass("ui-datepicker-next-hover"))}function H(e,i){for(var s in t.extend(e,i),i)null==i[s]&&(e[s]=i[s]);return e}t.widget("ui.controlgroup",{version:"1.14.2",defaultElement:"<div>",options:{direction:"horizontal",disabled:null,onlyVisible:!0,items:{button:"input[type=button], input[type=submit], input[type=reset], button, a",controlgroupLabel:".ui-controlgroup-label",checkboxradio:"input[type='checkbox'], input[type='radio']",selectmenu:"select",spinner:".ui-spinner-input"}},_create:function(){this._enhance()},_enhance:function(){this.element.attr("role","toolbar"),this.refresh()},_destroy:function(){this._callChildMethod("destroy"),this.childWidgets.removeData("ui-controlgroup-data"),this.element.removeAttr("role"),this.options.items.controlgroupLabel&&this.element.find(this.options.items.controlgroupLabel).find(".ui-controlgroup-label-contents").contents().unwrap()},_initWidgets:function(){var e=this,i=[];t.each(this.options.items,function(s,n){var o,a={};if(n){if("controlgroupLabel"===s){(o=e.element.find(n)).each(function(){var e=t(this);!e.children(".ui-controlgroup-label-contents").length&&e.contents().wrapAll("<span class='ui-controlgroup-label-contents'></span>")}),e._addClass(o,null,"ui-widget ui-widget-content ui-state-default"),i=i.concat(o.get());return}t.fn[s]&&(a=e["_"+s+"Options"]?e["_"+s+"Options"]("middle"):{classes:{}},e.element.find(n).each(function(){var n=t(this),o=n[s]("instance"),r=t.widget.extend({},a);if("button"!==s||!n.parent(".ui-spinner").length){o||(o=n[s]()[s]("instance")),o&&(r.classes=e._resolveClassesValues(r.classes,o)),n[s](r);var l=n[s]("widget");t.data(l[0],"ui-controlgroup-data",o||n[s]("instance")),i.push(l[0])}}))}}),this.childWidgets=t(t.uniqueSort(i)),this._addClass(this.childWidgets,"ui-controlgroup-item")},_callChildMethod:function(e){this.childWidgets.each(function(){var i=t(this).data("ui-controlgroup-data");i&&i[e]&&i[e]()})},_updateCornerClass:function(t,e){var i=this._buildSimpleOptions(e,"label").classes.label;this._removeClass(t,null,"ui-corner-top ui-corner-bottom ui-corner-left ui-corner-right ui-corner-all"),this._addClass(t,null,i)},_buildSimpleOptions:function(t,e){var i="vertical"===this.options.direction,s={classes:{}};return s.classes[e]=({middle:"",first:"ui-corner-"+(i?"top":"left"),last:"ui-corner-"+(i?"bottom":"right"),only:"ui-corner-all"})[t],s},_spinnerOptions:function(t){var e=this._buildSimpleOptions(t,"ui-spinner");return e.classes["ui-spinner-up"]="",e.classes["ui-spinner-down"]="",e},_buttonOptions:function(t){return this._buildSimpleOptions(t,"ui-button")},_checkboxradioOptions:function(t){return this._buildSimpleOptions(t,"ui-checkboxradio-label")},_selectmenuOptions:function(t){var e="vertical"===this.options.direction;return{width:!!e&&"auto",classes:({middle:{"ui-selectmenu-button-open":"","ui-selectmenu-button-closed":""},first:{"ui-selectmenu-button-open":"ui-corner-"+(e?"top":"tl"),"ui-selectmenu-button-closed":"ui-corner-"+(e?"top":"left")},last:{"ui-selectmenu-button-open":e?"":"ui-corner-tr","ui-selectmenu-button-closed":"ui-corner-"+(e?"bottom":"right")},only:{"ui-selectmenu-button-open":"ui-corner-top","ui-selectmenu-button-closed":"ui-corner-all"}})[t]}},_resolveClassesValues:function(e,i){var s={};return t.each(e,function(t){var n=i.options.classes[t]||"";n=String.prototype.trim.call(n.replace(T,"")),s[t]=(n+" "+e[t]).replace(/\s+/g," ")}),s},_setOption:function(t,e){if("direction"===t&&this._removeClass("ui-controlgroup-"+this.options.direction),this._super(t,e),"disabled"===t){this._callChildMethod(e?"disable":"enable");return}this.refresh()},refresh:function(){var e,i=this;this._addClass("ui-controlgroup ui-controlgroup-"+this.options.direction),"horizontal"===this.options.direction&&this._addClass(null,"ui-helper-clearfix"),this._initWidgets(),e=this.childWidgets,this.options.onlyVisible&&(e=e.filter(":visible")),e.length&&(t.each(["first","last"],function(t,s){var n=e[s]().data("ui-controlgroup-data");if(n&&i["_"+n.widgetName+"Options"]){var o=i["_"+n.widgetName+"Options"](1===e.length?"only":s);o.classes=i._resolveClassesValues(o.classes,n),n.element[n.widgetName](o)}else i._updateCornerClass(e[s](),s)}),this._callChildMethod("refresh"))}}),t.widget("ui.checkboxradio",[t.ui.formResetMixin,{version:"1.14.2",options:{disabled:null,label:null,icon:!0,classes:{"ui-checkboxradio-label":"ui-corner-all","ui-checkboxradio-icon":"ui-corner-all"}},_getCreateOptions:function(){var e,i,s,n=this._super()||{};return this._readType(),i=this.element.labels(),this.label=t(i[i.length-1]),this.label.length||t.error("No label found for checkboxradio widget"),this.originalLabel="",(s=this.label.contents().not(this.element[0])).length&&(this.originalLabel+=s.clone().wrapAll("<div></div>").parent().html()),this.originalLabel&&(n.label=this.originalLabel),null!=(e=this.element[0].disabled)&&(n.disabled=e),n},_create:function(){var t=this.element[0].checked;this._bindFormResetHandler(),null==this.options.disabled&&(this.options.disabled=this.element[0].disabled),this._setOption("disabled",this.options.disabled),this._addClass("ui-checkboxradio","ui-helper-hidden-accessible"),this._addClass(this.label,"ui-checkboxradio-label","ui-button ui-widget"),"radio"===this.type&&this._addClass(this.label,"ui-checkboxradio-radio-label"),this.options.label&&this.options.label!==this.originalLabel?this._updateLabel():this.originalLabel&&(this.options.label=this.originalLabel),this._enhance(),t&&this._addClass(this.label,"ui-checkboxradio-checked","ui-state-active"),this._on({change:"_toggleClasses",focus:function(){this._addClass(this.label,null,"ui-state-focus ui-visual-focus")},blur:function(){this._removeClass(this.label,null,"ui-state-focus ui-visual-focus")}})},_readType:function(){var e=this.element[0].nodeName.toLowerCase();this.type=this.element[0].type,"input"===e&&/radio|checkbox/.test(this.type)||t.error("Can't create checkboxradio on element.nodeName="+e+" and element.type="+this.type)},_enhance:function(){this._updateIcon(this.element[0].checked)},widget:function(){return this.label},_getRadioGroup:function(){var e,i=this.element[0].name,s="input[name='"+CSS.escape(i)+"']";return i?(this.form.length?t(this.form[0].elements).filter(s):t(s).filter(function(){return 0===t(t(this).prop("form")).length})).not(this.element):t([])},_toggleClasses:function(){var e=this.element[0].checked;this._toggleClass(this.label,"ui-checkboxradio-checked","ui-state-active",e),this.options.icon&&"checkbox"===this.type&&this._toggleClass(this.icon,null,"ui-icon-check ui-state-checked",e)._toggleClass(this.icon,null,"ui-icon-blank",!e),"radio"===this.type&&this._getRadioGroup().each(function(){var e=t(this).checkboxradio("instance");e&&e._removeClass(e.label,"ui-checkboxradio-checked","ui-state-active")})},_destroy:function(){this._unbindFormResetHandler(),this.icon&&(this.icon.remove(),this.iconSpace.remove())},_setOption:function(t,e){if("label"!==t||e){if(this._super(t,e),"disabled"===t){this._toggleClass(this.label,null,"ui-state-disabled",e),this.element[0].disabled=e;return}this.refresh()}},_updateIcon:function(e){var i="ui-icon ui-icon-background ";this.options.icon?(this.icon||(this.icon=t("<span>"),this.iconSpace=t("<span> </span>
vendor: 2,904 bytes, line 12426
12426"),this._addClass(this.iconSpace,"ui-checkboxradio-icon-space")),"checkbox"===this.type?(i+=e?"ui-icon-check ui-state-checked":"ui-icon-blank",this._removeClass(this.icon,null,e?"ui-icon-blank":"ui-icon-check")):i+="ui-icon-blank",this._addClass(this.icon,"ui-checkboxradio-icon",i),e||this._removeClass(this.icon,null,"ui-icon-check ui-state-checked"),this.icon.prependTo(this.label).after(this.iconSpace)):void 0!==this.icon&&(this.icon.remove(),this.iconSpace.remove(),delete this.icon)},_updateLabel:function(){var t=this.label.contents().not(this.element[0]);this.icon&&(t=t.not(this.icon[0])),this.iconSpace&&(t=t.not(this.iconSpace[0])),t.remove(),this.label.append(this.options.label)},refresh:function(){var t=this.element[0].checked,e=this.element[0].disabled;this._updateIcon(t),this._toggleClass(this.label,"ui-checkboxradio-checked","ui-state-active",t),null!==this.options.label&&this._updateLabel(),e!==this.options.disabled&&this._setOptions({disabled:e})}}]),t.ui.checkboxradio,t.widget("ui.button",{version:"1.14.2",defaultElement:"<button>",options:{classes:{"ui-button":"ui-corner-all"},disabled:null,icon:null,iconPosition:"beginning",label:null,showLabel:!0},_getCreateOptions:function(){var t,e=this._super()||{};return this.isInput=this.element.is("input"),null!=(t=this.element[0].disabled)&&(e.disabled=t),this.originalLabel=this.isInput?this.element.val():this.element.html(),this.originalLabel&&(e.label=this.originalLabel),e},_create:function(){!this.option.showLabel&!this.options.icon&&(this.options.showLabel=!0),null==this.options.disabled&&(this.options.disabled=this.element[0].disabled||!1),this.hasTitle=!!this.element.attr("title"),this.options.label&&this.options.label!==this.originalLabel&&(this.isInput?this.element.val(this.options.label):this.element.html(this.options.label)),this._addClass("ui-button","ui-widget"),this._setOption("disabled",this.options.disabled),this._enhance(),this.element.is("a")&&this._on({keyup:function(e){e.keyCode===t.ui.keyCode.SPACE&&(e.preventDefault(),this.element[0].click?this.element[0].click():this.element.trigger("click"))}})},_enhance:function(){this.element.is("button")||this.element.attr("role","button"),this.options.icon&&(this._updateIcon("icon",this.options.icon),this._updateTooltip())},_updateTooltip:function(){this.title=this.element.attr("title"),this.options.showLabel||this.title||this.element.attr("title",this.options.label)},_updateIcon:function(e,i){var s="iconPosition"!==e,n=s?this.options.iconPosition:i,o="top"===n||"bottom"===n;this.icon?s&&this._removeClass(this.icon,null,this.options.icon):(this.icon=t("<span>"),this._addClass(this.icon,"ui-button-icon","ui-icon"),this.options.showLabel||this._addClass("ui-button-icon-only")),s&&this._addClass(this.icon,null,i),this._attachIcon(n),o?(this._addClass(this.icon,null,"ui-widget-icon-block"),this.iconSpace&&this.iconSpace.remove()):(this.iconS
vendor: 7,045 bytes, line 12426
12426pace||(this.iconSpace=t("<span> </span>"),this._addClass(this.iconSpace,"ui-button-icon-space")),this._removeClass(this.icon,null,"ui-wiget-icon-block"),this._attachIconSpace(n))},_destroy:function(){this.element.removeAttr("role"),this.icon&&this.icon.remove(),this.iconSpace&&this.iconSpace.remove(),this.hasTitle||this.element.removeAttr("title")},_attachIconSpace:function(t){this.icon[/^(?:end|bottom)/.test(t)?"before":"after"](this.iconSpace)},_attachIcon:function(t){this.element[/^(?:end|bottom)/.test(t)?"append":"prepend"](this.icon)},_setOptions:function(t){var e=void 0===t.showLabel?this.options.showLabel:t.showLabel,i=void 0===t.icon?this.options.icon:t.icon;e||i||(t.showLabel=!0),this._super(t)},_setOption:function(t,e){"icon"===t&&(e?this._updateIcon(t,e):this.icon&&(this.icon.remove(),this.iconSpace&&this.iconSpace.remove())),"iconPosition"===t&&this._updateIcon(t,e),"showLabel"===t&&(this._toggleClass("ui-button-icon-only",null,!e),this._updateTooltip()),"label"===t&&(this.isInput?this.element.val(e):(this.element.html(e),this.icon&&(this._attachIcon(this.options.iconPosition),this._attachIconSpace(this.options.iconPosition)))),this._super(t,e),"disabled"===t&&(this._toggleClass(null,"ui-state-disabled",e),this.element[0].disabled=e,e&&this.element.trigger("blur"))},refresh:function(){var t=this.element.is("input, button")?this.element[0].disabled:this.element.hasClass("ui-button-disabled");t!==this.options.disabled&&this._setOptions({disabled:t}),this._updateTooltip()}}),!0===t.uiBackCompat&&(t.widget("ui.button",t.ui.button,{options:{text:!0,icons:{primary:null,secondary:null}},_create:function(){this.options.showLabel&&!this.options.text&&(this.options.showLabel=this.options.text),!this.options.showLabel&&this.options.text&&(this.options.text=this.options.showLabel),!this.options.icon&&(this.options.icons.primary||this.options.icons.secondary)?this.options.icons.primary?this.options.icon=this.options.icons.primary:(this.options.icon=this.options.icons.secondary,this.options.iconPosition="end"):this.options.icon&&(this.options.icons.primary=this.options.icon),this._super()},_setOption:function(t,e){if("text"===t){this._super("showLabel",e);return}"showLabel"===t&&(this.options.text=e),"icon"===t&&(this.options.icons.primary=e),"icons"===t&&(e.primary?(this._super("icon",e.primary),this._super("iconPosition","beginning")):e.secondary&&(this._super("icon",e.secondary),this._super("iconPosition","end"))),this._superApply(arguments)}}),t.fn.button=(s=t.fn.button,function(e){var i="string"==typeof e,n=Array.prototype.slice.call(arguments,1),o=this;return i?this.length||"instance"!==e?this.each(function(){var i,s=t(this).attr("type"),a=t.data(this,"ui-"+("checkbox"!==s&&"radio"!==s?"button":"checkboxradio"));return"instance"===e?(o=a,!1):a?"function"!=typeof a[e]||"_"===e.charAt(0)?t.error("no such method '"+e+"' for button widget instance"):(i=a[e].apply(a,n))!==a&&void 0!==i?(o=i&&i.jquery?o.pushStack(i.get()):i,!1):void 0:t.error("cannot call methods on button prior to initialization; attempted to call method '"+e+"'")}):o=void 0:(n.length&&(e=t.widget.extend.apply(null,[e].concat(n))),this.each(function(){var i=t(this).attr("type"),n="checkbox"!==i&&"radio"!==i?"button":"checkboxradio",o=t.data(this,"ui-"+n);if(o)o.option(e||{}),o._init&&o._init();else{if("button"===n){s.call(t(this),e);return}t(this).checkboxradio(t.extend({icon:!1},e))}})),o}),t.fn.buttonset=function(){return(t.ui.controlgroup||t.error("Controlgroup widget missing"),"option"===arguments[0]&&"items"===arguments[1]&&arguments[2])?this.controlgroup.apply(this,[arguments[0],"items.button",arguments[2]]):"option"===arguments[0]&&"items"===arguments[1]?this.controlgroup.apply(this,[arguments[0],"items.button"]):("object"==typeof arguments[0]&&arguments[0].items&&(arguments[0].items={button:arguments[0].items}),this.controlgroup.apply(this,arguments))}),t.ui.button,t.extend(t.ui,{datepicker:{version:"1.14.2"}}),t.extend(P.prototype,{markerClassName:"hasDatepicker",maxRows:4,_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(t){return H(this._defaults,t||{}),this},_attachDatepicker:function(e,i){var s,n,o;n="div"===(s=e.nodeName.toLowerCase())||"span"===s,e.id||(this.uuid+=1,e.id="dp"+this.uuid),(o=this._newInst(t(e),n)).settings=t.extend({},i||{}),"input"===s?this._connectDatepicker(e,o):n&&this._inlineDatepicker(e,o)},_newInst:function(e,i){return{id:e[0].id.replace(/([^A-Za-z0-9_\-])/g,"\\\\$1"),input:e,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:i,dpDiv:i?M(t("<div class='"+this._inlineClass+" ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")):this.dpDiv}},_connectDatepicker:function(e,i){var s=t(e);i.append=t([]),i.trigger=t([]),!s.hasClass(this.markerClassName)&&(this._attachments(s,i),s.addClass(this.markerClassName).on("keydown",this._doKeyDown).on("keypress",this._doKeyPress).on("keyup",this._doKeyUp),this._autoSize(i),t.data(e,"datepicker",i),i.settings.disabled&&this._disableDatepicker(e))},_attachments:function(e,i){var s,n,o,a=this._get(i,"appendText"),r=this._get(i,"isRTL");i.append&&i.append.remove(),a&&(i.append=t("<span>").addClass(this._appendClass).text(a),e[r?"before":"after"](i.append)),e.off("focus",this._showDatepicker),i.trigger&&i.trigger.remove(),("focus"===(s=this._get(i,"showOn"))||"both"===s)&&e.on("focus",this._showDatepicker),("button"===s||"both"===s)&&(n=this._get(i,"buttonText"),o=this._get(i,"buttonImage"),this._get(i,"buttonImageOnly")?i.trigger=t("<img>").addClass(this._triggerClass).attr({src:o,alt:n,title:n}):(i.trigger=t("<button type='button'>").addClass(this._triggerClass),o?i.trigger.html(t("<img>").attr({src:o,alt:n,title:n})):i.trigger.text(n)),e[r?"before":"after"](i.trigger),i.trigger.on("click",function(){return t.datepicker._datepickerShowing&&t.datepicker._lastInput===e[0]?t.datepicker._hideDatepicker():(t.datepicker._datepickerShowing&&t.datepicker._lastInput!==e[0]&&t.datepicker._hideDatepicker(),t.datepicker._showDatepicker(e[0])),!1}))},_autoSize:function(t){if(this._get(t,"autoSize")&&!t.inline){var e,i,s,n,o=new Date(2009,11,20),a=this._get(t,"dateFormat");a.match(/[DM]/)&&(e=function(t){for(n=0,i=0,s=0;n<t.length;n++)t[n].length>i&&(i=t[n].length,s=n);return s},o.setMonth(e(this._get(t,a.match(/MM/)?"monthNames":"monthNamesShort"))),o.setDate(e(this._get(t,a.match(/DD/)?"dayNames":"dayNamesShort"))+20-o.getDay())),t.input.attr("size",this._formatDate(t,o).length)}},_inlineDatepicker:function(e,i){var s=t(e);!s.hasClass(this.markerClassName)&&(s.addClass(this.markerClassName).append(i.dpDiv),t.data(e,"datepicker",i),this._setDate(i,this._getDefaultDate(i),!0),this._updateDatepicker(i),this._updateAlternate(i),i.settings.disabled&&this._disableDatepicker(e),i.dpDiv.css("display","block"))},_dialogDatepicker:function(e,i,s,n,o){var a,r,l,h,c,u=this._dialogInst;return u||(this.uuid+=1,a="dp"+this.uuid,this._dialogInput=t("<input type='text' id='"+a+"' style='position: absolute; top: -100px; width: 0px;'/>
vendor: 12,691 bytes, line 12426
12426"),this._dialogInput.on("keydown",this._doKeyDown),t("body").append(this._dialogInput),(u=this._dialogInst=this._newInst(this._dialogInput,!1)).settings={},t.data(this._dialogInput[0],"datepicker",u)),H(u.settings,n||{}),i=i&&i.constructor===Date?this._formatDate(u,i):i,this._dialogInput.val(i),this._pos=o?o.length?o:[o.pageX,o.pageY]:null,this._pos||(r=document.documentElement.clientWidth,l=document.documentElement.clientHeight,h=document.documentElement.scrollLeft||document.body.scrollLeft,c=document.documentElement.scrollTop||document.body.scrollTop,this._pos=[r/2-100+h,l/2-150+c]),this._dialogInput.css("left",this._pos[0]+20+"px").css("top",this._pos[1]+"px"),u.settings.onSelect=s,this._inDialog=!0,this.dpDiv.addClass(this._dialogClass),this._showDatepicker(this._dialogInput[0]),t.blockUI&&t.blockUI(this.dpDiv),t.data(this._dialogInput[0],"datepicker",u),this},_destroyDatepicker:function(e){var i,s=t(e),n=t.data(e,"datepicker");s.hasClass(this.markerClassName)&&(i=e.nodeName.toLowerCase(),t.removeData(e,"datepicker"),"input"===i?(n.append.remove(),n.trigger.remove(),s.removeClass(this.markerClassName).off("focus",this._showDatepicker).off("keydown",this._doKeyDown).off("keypress",this._doKeyPress).off("keyup",this._doKeyUp)):("div"===i||"span"===i)&&s.removeClass(this.markerClassName).empty(),t.datepicker._hideDatepicker(),o===n&&(o=null,this._curInst=null))},_enableDatepicker:function(e){var i,s,n=t(e),o=t.data(e,"datepicker");n.hasClass(this.markerClassName)&&("input"===(i=e.nodeName.toLowerCase())?(e.disabled=!1,o.trigger.filter("button").each(function(){this.disabled=!1}).end().filter("img").css({opacity:"1.0",cursor:""})):("div"===i||"span"===i)&&((s=n.children("."+this._inlineClass)).children().removeClass("ui-state-disabled"),s.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!1)),this._disabledInputs=t.map(this._disabledInputs,function(t){return t===e?null:t}))},_disableDatepicker:function(e){var i,s,n=t(e),o=t.data(e,"datepicker");n.hasClass(this.markerClassName)&&("input"===(i=e.nodeName.toLowerCase())?(e.disabled=!0,o.trigger.filter("button").each(function(){this.disabled=!0}).end().filter("img").css({opacity:"0.5",cursor:"default"})):("div"===i||"span"===i)&&((s=n.children("."+this._inlineClass)).children().addClass("ui-state-disabled"),s.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!0)),this._disabledInputs=t.map(this._disabledInputs,function(t){return t===e?null:t}),this._disabledInputs[this._disabledInputs.length]=e)},_isDisabledDatepicker:function(t){if(!t)return!1;for(var e=0;e<this._disabledInputs.length;e++)if(this._disabledInputs[e]===t)return!0;return!1},_getInst:function(e){try{return t.data(e,"datepicker")}catch(t){throw"Missing instance data for this datepicker"}},_optionDatepicker:function(e,i,s){var n,o,a,r,l=this._getInst(e);if(2==arguments.length&&"string"==typeof i)return"defaults"===i?t.extend({},t.datepicker._defaults):l?"all"===i?t.extend({},l.settings):this._get(l,i):null;n=i||{},"string"==typeof i&&((n={})[i]=s),l&&(this._curInst===l&&this._hideDatepicker(),o=this._getDateDatepicker(e,!0),a=this._getMinMaxDate(l,"min"),r=this._getMinMaxDate(l,"max"),H(l.settings,n),null!==a&&void 0!==n.dateFormat&&void 0===n.minDate&&(l.settings.minDate=this._formatDate(l,a)),null!==r&&void 0!==n.dateFormat&&void 0===n.maxDate&&(l.settings.maxDate=this._formatDate(l,r)),"disabled"in n&&(n.disabled?this._disableDatepicker(e):this._enableDatepicker(e)),this._attachments(t(e),l),this._autoSize(l),this._setDate(l,o),this._updateAlternate(l),this._updateDatepicker(l))},_changeDatepicker:function(t,e,i){this._optionDatepicker(t,e,i)},_refreshDatepicker:function(t){var e=this._getInst(t);e&&this._updateDatepicker(e)},_setDateDatepicker:function(t,e){var i=this._getInst(t);i&&(this._setDate(i,e),this._updateDatepicker(i),this._updateAlternate(i))},_getDateDatepicker:function(t,e){var i=this._getInst(t);return i&&!i.inline&&this._setDateFromField(i,e),i?this._getDate(i):null},_doKeyDown:function(e){var i,s,n,o=t.datepicker._getInst(e.target),a=!0,r=o.dpDiv.is(".ui-datepicker-rtl");if(o._keyEvent=!0,t.datepicker._datepickerShowing)switch(e.keyCode){case 9:t.datepicker._hideDatepicker(),a=!1;break;case 13:return(n=t("td."+t.datepicker._dayOverClass+":not(."+t.datepicker._currentClass+")",o.dpDiv))[0]&&t.datepicker._selectDay(e.target,o.selectedMonth,o.selectedYear,n[0]),(i=t.datepicker._get(o,"onSelect"))?(s=t.datepicker._formatDate(o),i.apply(o.input?o.input[0]:null,[s,o])):t.datepicker._hideDatepicker(),!1;case 27:t.datepicker._hideDatepicker();break;case 33:t.datepicker._adjustDate(e.target,e.ctrlKey?-t.datepicker._get(o,"stepBigMonths"):-t.datepicker._get(o,"stepMonths"),"M");break;case 34:t.datepicker._adjustDate(e.target,e.ctrlKey?+t.datepicker._get(o,"stepBigMonths"):+t.datepicker._get(o,"stepMonths"),"M");break;case 35:(e.ctrlKey||e.metaKey)&&t.datepicker._clearDate(e.target),a=e.ctrlKey||e.metaKey;break;case 36:(e.ctrlKey||e.metaKey)&&t.datepicker._gotoToday(e.target),a=e.ctrlKey||e.metaKey;break;case 37:(e.ctrlKey||e.metaKey)&&t.datepicker._adjustDate(e.target,r?1:-1,"D"),a=e.ctrlKey||e.metaKey,e.originalEvent.altKey&&t.datepicker._adjustDate(e.target,e.ctrlKey?-t.datepicker._get(o,"stepBigMonths"):-t.datepicker._get(o,"stepMonths"),"M");break;case 38:(e.ctrlKey||e.metaKey)&&t.datepicker._adjustDate(e.target,-7,"D"),a=e.ctrlKey||e.metaKey;break;case 39:(e.ctrlKey||e.metaKey)&&t.datepicker._adjustDate(e.target,r?-1:1,"D"),a=e.ctrlKey||e.metaKey,e.originalEvent.altKey&&t.datepicker._adjustDate(e.target,e.ctrlKey?+t.datepicker._get(o,"stepBigMonths"):+t.datepicker._get(o,"stepMonths"),"M");break;case 40:(e.ctrlKey||e.metaKey)&&t.datepicker._adjustDate(e.target,7,"D"),a=e.ctrlKey||e.metaKey;break;default:a=!1}else 36===e.keyCode&&e.ctrlKey?t.datepicker._showDatepicker(this):a=!1;a&&(e.preventDefault(),e.stopPropagation())},_doKeyPress:function(e){var i,s,n=t.datepicker._getInst(e.target);if(t.datepicker._get(n,"constrainInput"))return i=t.datepicker._possibleChars(t.datepicker._get(n,"dateFormat")),s=String.fromCharCode(null==e.charCode?e.keyCode:e.charCode),e.ctrlKey||e.metaKey||s<" "||!i||i.indexOf(s)>-1},_doKeyUp:function(e){var i=t.datepicker._getInst(e.target);if(i.input.val()!==i.lastVal)try{t.datepicker.parseDate(t.datepicker._get(i,"dateFormat"),i.input?i.input.val():null,t.datepicker._getFormatConfig(i))&&(t.datepicker._setDateFromField(i),t.datepicker._updateAlternate(i),t.datepicker._updateDatepicker(i))}catch(t){}return!0},_showDatepicker:function(e){var i,s,n,o,a,r,l;if("input"!==(e=e.target||e).nodeName.toLowerCase()&&(e=t("input",e.parentNode)[0]),!t.datepicker._isDisabledDatepicker(e)&&t.datepicker._lastInput!==e)i=t.datepicker._getInst(e),t.datepicker._curInst&&t.datepicker._curInst!==i&&(t.datepicker._curInst.dpDiv.stop(!0,!0),i&&t.datepicker._datepickerShowing&&t.datepicker._hideDatepicker(t.datepicker._curInst.input[0])),!1!==(n=(s=t.datepicker._get(i,"beforeShow"))?s.apply(e,[e,i]):{})&&(H(i.settings,n),i.lastVal=null,t.datepicker._lastInput=e,t.datepicker._setDateFromField(i),t.datepicker._inDialog&&(e.value=""),t.datepicker._pos||(t.datepicker._pos=t.datepicker._findPos(e),t.datepicker._pos[1]+=e.offsetHeight),o=!1,t(e).parents().each(function(){return!(o|="fixed"===t(this).css("position"))}),a={left:t.datepicker._pos[0],top:t.datepicker._pos[1]},t.datepicker._pos=null,i.dpDiv.empty(),i.dpDiv.css({position:"absolute",display:"block",top:"-1000px"}),t.datepicker._updateDatepicker(i),a=t.datepicker._checkOffset(i,a,o),i.dpDiv.css({position:t.datepicker._inDialog&&t.blockUI?"static":o?"fixed":"absolute",display:"none",left:a.left+"px",top:a.top+"px"}),i.inline||(r=t.datepicker._get(i,"showAnim"),l=t.datepicker._get(i,"duration"),i.dpDiv.css("z-index",function(t){var e,i;while(t.length&&t[0]!==document){if(("absolute"===(e=t.css("position"))||"relative"===e||"fixed"===e)&&!isNaN(i=parseInt(t.css("zIndex"),10))&&0!==i)return i;t=t.parent()}return 0}(t(e))+1),t.datepicker._datepickerShowing=!0,t.effects&&t.effects.effect[r]?i.dpDiv.show(r,t.datepicker._get(i,"showOptions"),l):i.dpDiv[r||"show"](r?l:null),t.datepicker._shouldFocusInput(i)&&i.input.trigger("focus"),t.datepicker._curInst=i))},_updateDatepicker:function(e){this.maxRows=4,o=e,e.dpDiv.empty().append(this._generateHTML(e)),this._attachHandlers(e);var i,s=this._getNumberOfMonths(e),n=s[1],a=e.dpDiv.find("."+this._dayOverClass+" a"),r=t.datepicker._get(e,"onUpdateDatepicker");a.length>0&&S.apply(a.get(0)),e.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""),n>1&&e.dpDiv.addClass("ui-datepicker-multi-"+n).css("width",17*n+"em"),e.dpDiv[(1!==s[0]||1!==s[1]?"add":"remove")+"Class"]("ui-datepicker-multi"),e.dpDiv[(this._get(e,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl"),e===t.datepicker._curInst&&t.datepicker._datepickerShowing&&t.datepicker._shouldFocusInput(e)&&e.input.trigger("focus"),e.yearshtml&&(i=e.yearshtml,setTimeout(function(){i===e.yearshtml&&e.yearshtml&&e.dpDiv.find("select.ui-datepicker-year").first().replaceWith(e.yearshtml),i=e.yearshtml=null},0)),r&&r.apply(e.input?e.input[0]:null,[e])},_shouldFocusInput:function(t){return t.input&&t.input.is(":visible")&&!t.input.is(":disabled")},_checkOffset:function(e,i,s){var n=e.dpDiv.outerWidth(),o=e.dpDiv.outerHeight(),a=e.input?e.input.outerWidth():0,r=e.input?e.input.outerHeight():0,l=document.documentElement.clientWidth+(s?0:t(document).scrollLeft()),h=document.documentElement.clientHeight+(s?0:t(document).scrollTop());return i.left-=this._get(e,"isRTL")?n-a:0,i.left-=s&&i.left===e.input.offset().left?t(document).scrollLeft():0,i.top-=s&&i.top===e.input.offset().top+r?t(document).scrollTop():0,i.left-=Math.min(i.left,i.left+n>l&&l>n?Math.abs(i.left+n-l):0),i.top-=Math.min(i.top,i.top+o>h&&h>o?Math.abs(o+r):0),i},_findPos:function(e){var i,s=this._getInst(e),n=this._get(s,"isRTL");while(e&&("hidden"===e.type||1!==e.nodeType||t.expr.pseudos.hidden(e)))e=e[n?"previousSibling":"nextSibling"];return[(i=t(e).offset()).left,i.top]},_hideDatepicker:function(e){var i,s,n,o,a=this._curInst;a&&(!e||a===t.data(e,"datepicker"))&&this._datepickerShowing&&(i=this._get(a,"showAnim"),s=this._get(a,"duration"),n=function(){t.datepicker._tidyDialog(a)},t.effects&&t.effects.effect[i]?a.dpDiv.hide(i,t.datepicker._get(a,"showOptions"),s,n):a.dpDiv["slideDown"===i?"slideUp":"fadeIn"===i?"fadeOut":"hide"](i?s:null,n),i||n(),this._datepickerShowing=!1,(o=this._get(a,"onClose"))&&o.apply(a.input?a.input[0]:null,[a.input?a.input.val():"",a]),this._lastInput=null,this._inDialog&&(this._dialogInput.css({position:"absolute",left:"0",top:"-100px"}),t.blockUI&&(t.unblockUI(),t("body").append(this.dpDiv))),this._inDialog=!1)},_tidyDialog:function(t){t.dpDiv.removeClass(this._dialogClass).off(".ui-datepicker-calendar")},_checkExternalClick:function(e){if(t.datepicker._curInst){var i=t(e.target),s=t.datepicker._getInst(i[0]);(i[0].id!==t.datepicker._mainDivId&&0===i.parents("#"+t.datepicker._mainDivId).length&&!i.hasClass(t.datepicker.markerClassName)&&!i.closest("."+t.datepicker._triggerClass).length&&t.datepicker._datepickerShowing&&!(t.datepicker._inDialog&&t.blockUI)||i.hasClass(t.datepicker.markerClassName)&&t.datepicker._curInst!==s)&&t.datepicker._hideDatepicker()}},_adjustDate:function(e,i,s){var n=t(e),o=this._getInst(n[0]);!this._isDisabledDatepicker(n[0])&&(this._adjustInstDate(o,i,s),this._updateDatepicker(o))},_gotoToday:function(e){var i,s=t(e),n=this._getInst(s[0]);this._get(n,"gotoCurrent")&&n.currentDay?(n.selectedDay=n.currentDay,n.drawMonth=n.selectedMonth=n.currentMonth,n.drawYear=n.selectedYear=n.currentYear):(n.selectedDay=(i=new Date).getDate(),n.drawMonth=n.selectedMonth=i.getMonth(),n.drawYear=n.selectedYear=i.getFullYear()),this._notifyChange(n),this._adjustDate(s)},_selectMonthYear:function(e,i,s){var n=t(e),o=this._getInst(n[0]);o["selected"+("M"===s?"Month":"Year")]=o["draw"+("M"===s?"Month":"Year")]=parseInt(i.options[i.selectedIndex].value,10),this._notifyChange(o),this._adjustDate(n)},_selectDay:function(e,i,s,n){var o,a=t(e);!(t(n).hasClass(this._unselectableClass)||this._isDisabledDatepicker(a[0]))&&((o=this._getInst(a[0])).selectedDay=o.currentDay=parseInt(t("a",n).attr("data-date")),o.selectedMonth=o.currentMonth=i,o.selectedYear=o.currentYear=s,this._selectDate(e,this._formatDate(o,o.currentDay,o.currentMonth,o.currentYear)))},_clearDate:function(e){var i=t(e);this._selectDate(i,"")},_selectDate:function(e,i){var s,n=t(e),o=this._getInst(n[0]);i=null!=i?i:this._formatDate(o),o.input&&o.input.val(i),this._updateAlternate(o),(s=this._get(o,"onSelect"))?s.apply(o.input?o.input[0]:null,[
vendor: 21,003 bytes, line 12426
12426i,o]):o.input&&o.input.trigger("change"),o.inline?this._updateDatepicker(o):(this._hideDatepicker(),this._lastInput=o.input[0],"object"!=typeof o.input[0]&&o.input.trigger("focus"),this._lastInput=null)},_updateAlternate:function(e){var i,s,n,o=this._get(e,"altField");o&&(i=this._get(e,"altFormat")||this._get(e,"dateFormat"),s=this._getDate(e),n=this.formatDate(i,s,this._getFormatConfig(e)),t(document).find(o).val(n))},noWeekends:function(t){var e=t.getDay();return[e>0&&e<6,""]},iso8601Week:function(t){var e,i=new Date(t.getTime());return i.setDate(i.getDate()+4-(i.getDay()||7)),e=i.getTime(),i.setMonth(0),i.setDate(1),Math.floor(Math.round((e-i)/864e5)/7)+1},parseDate:function(e,i,s){if(null==e||null==i)throw"Invalid arguments";if(""===(i="object"==typeof i?i.toString():i+""))return null;var n,o,a,r,l=0,h=(s?s.shortYearCutoff:null)||this._defaults.shortYearCutoff,c="string"!=typeof h?h:new Date().getFullYear()%100+parseInt(h,10),u=(s?s.dayNamesShort:null)||this._defaults.dayNamesShort,d=(s?s.dayNames:null)||this._defaults.dayNames,p=(s?s.monthNamesShort:null)||this._defaults.monthNamesShort,f=(s?s.monthNames:null)||this._defaults.monthNames,g=-1,m=-1,_=-1,v=-1,b=!1,y=function(t){var i=n+1<e.length&&e.charAt(n+1)===t;return i&&n++,i},w=function(t){var e=y(t),s="@"===t?14:"!"===t?20:"y"===t&&e?4:"o"===t?3:2,n=RegExp("^\\d{"+("y"===t?s:1)+","+s+"}"),o=i.substring(l).match(n);if(!o)throw"Missing number at position "+l;return l+=o[0].length,parseInt(o[0],10)},x=function(e,s,n){var o=-1,a=t.map(y(e)?n:s,function(t,e){return[[e,t]]}).sort(function(t,e){return-(t[1].length-e[1].length)});if(t.each(a,function(t,e){var s=e[1];if(i.substr(l,s.length).toLowerCase()===s.toLowerCase())return o=e[0],l+=s.length,!1}),-1!==o)return o+1;throw"Unknown name at position "+l},k=function(){if(i.charAt(l)!==e.charAt(n))throw"Unexpected literal at position "+l;l++};for(n=0;n<e.length;n++)if(b)"'"!==e.charAt(n)||y("'")?k():b=!1;else switch(e.charAt(n)){case"d":_=w("d");break;case"D":x("D",u,d);break;case"o":v=w("o");break;case"m":m=w("m");break;case"M":m=x("M",p,f);break;case"y":g=w("y");break;case"@":g=(r=new Date(w("@"))).getFullYear(),m=r.getMonth()+1,_=r.getDate();break;case"!":g=(r=new Date((w("!")-this._ticksTo1970)/1e4)).getFullYear(),m=r.getMonth()+1,_=r.getDate();break;case"'":y("'")?k():b=!0;break;default:k()}if(l<i.length&&(a=i.substr(l),!/^\s+/.test(a)))throw"Extra/unparsed characters found in date: "+a;if(-1===g?g=new Date().getFullYear():g<100&&(g+=new Date().getFullYear()-new Date().getFullYear()%100+(g<=c?0:-100)),v>-1){m=1,_=v;do{if(_<=(o=this._getDaysInMonth(g,m-1)))break;m++,_-=o}while(!0)}if((r=this._daylightSavingAdjust(new Date(g,m-1,_))).getFullYear()!==g||r.getMonth()+1!==m||r.getDate()!==_)throw"Invalid date";return r},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:(718685+Math.floor(492.5)-Math.floor(19.7)+Math.floor(4.925))*864e9,formatDate:function(t,e,i){if(!e)return"";var s,n=(i?i.dayNamesShort:null)||this._defaults.dayNamesShort,o=(i?i.dayNames:null)||this._defaults.dayNames,a=(i?i.monthNamesShort:null)||this._defaults.monthNamesShort,r=(i?i.monthNames:null)||this._defaults.monthNames,l=function(e){var i=s+1<t.length&&t.charAt(s+1)===e;return i&&s++,i},h=function(t,e,i){var s=""+e;if(l(t))while(s.length<i)s="0"+s;return s},c=function(t,e,i,s){return l(t)?s[e]:i[e]},u="",d=!1;if(e)for(s=0;s<t.length;s++)if(d)"'"!==t.charAt(s)||l("'")?u+=t.charAt(s):d=!1;else switch(t.charAt(s)){case"d":u+=h("d",e.getDate(),2);break;case"D":u+=c("D",e.getDay(),n,o);break;case"o":u+=h("o",Math.round((new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()-new Date(e.getFullYear(),0,0).getTime())/864e5),3);break;case"m":u+=h("m",e.getMonth()+1,2);break;case"M":u+=c("M",e.getMonth(),a,r);break;case"y":u+=l("y")?e.getFullYear():(e.getFullYear()%100<10?"0":"")+e.getFullYear()%100;break;case"@":u+=e.getTime();break;case"!":u+=1e4*e.getTime()+this._ticksTo1970;break;case"'":l("'")?u+="'":d=!0;break;default:u+=t.charAt(s)}return u},_possibleChars:function(t){var e,i="",s=!1,n=function(i){var s=e+1<t.length&&t.charAt(e+1)===i;return s&&e++,s};for(e=0;e<t.length;e++)if(s)"'"!==t.charAt(e)||n("'")?i+=t.charAt(e):s=!1;else switch(t.charAt(e)){case"d":case"m":case"y":case"@":i+="0123456789";break;case"D":case"M":return null;case"'":n("'")?i+="'":s=!0;break;default:i+=t.charAt(e)}return i},_get:function(t,e){return void 0!==t.settings[e]?t.settings[e]:this._defaults[e]},_setDateFromField:function(t,e){if(t.input.val()!==t.lastVal){var i=this._get(t,"dateFormat"),s=t.lastVal=t.input?t.input.val():null,n=this._getDefaultDate(t),o=n,a=this._getFormatConfig(t);try{o=this.parseDate(i,s,a)||n}catch(t){s=e?"":s}t.selectedDay=o.getDate(),t.drawMonth=t.selectedMonth=o.getMonth(),t.drawYear=t.selectedYear=o.getFullYear(),t.currentDay=s?o.getDate():0,t.currentMonth=s?o.getMonth():0,t.currentYear=s?o.getFullYear():0,this._adjustInstDate(t)}},_getDefaultDate:function(t){return this._restrictMinMax(t,this._determineDate(t,this._get(t,"defaultDate"),new Date))},_determineDate:function(e,i,s){var n,o=null==i||""===i?s:"string"==typeof i?function(i){try{return t.datepicker.parseDate(t.datepicker._get(e,"dateFormat"),i,t.datepicker._getFormatConfig(e))}catch(t){}var s=(i.toLowerCase().match(/^c/)?t.datepicker._getDate(e):null)||new Date,n=s.getFullYear(),o=s.getMonth(),a=s.getDate(),r=/([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,l=r.exec(i);while(l){switch(l[2]||"d"){case"d":case"D":a+=parseInt(l[1],10);break;case"w":case"W":a+=7*parseInt(l[1],10);break;case"m":case"M":o+=parseInt(l[1],10),a=Math.min(a,t.datepicker._getDaysInMonth(n,o));break;case"y":case"Y":n+=parseInt(l[1],10),a=Math.min(a,t.datepicker._getDaysInMonth(n,o))}l=r.exec(i)}return new Date(n,o,a)}(i):"number"==typeof i?isNaN(i)?s:((n=new Date).setDate(n.getDate()+i),n):new Date(i.getTime());return(o=o&&"Invalid Date"===o.toString()?s:o)&&(o.setHours(0),o.setMinutes(0),o.setSeconds(0),o.setMilliseconds(0)),this._daylightSavingAdjust(o)},_daylightSavingAdjust:function(t){return t?(t.setHours(t.getHours()>12?t.getHours()+2:0),t):null},_setDate:function(t,e,i){var s=!e,n=t.selectedMonth,o=t.selectedYear,a=this._restrictMinMax(t,this._determineDate(t,e,new Date));t.selectedDay=t.currentDay=a.getDate(),t.drawMonth=t.selectedMonth=t.currentMonth=a.getMonth(),t.drawYear=t.selectedYear=t.currentYear=a.getFullYear(),n===t.selectedMonth&&o===t.selectedYear||i||this._notifyChange(t),this._adjustInstDate(t),t.input&&t.input.val(s?"":this._formatDate(t))},_getDate:function(t){return!t.currentYear||t.input&&""===t.input.val()?null:this._daylightSavingAdjust(new Date(t.currentYear,t.currentMonth,t.currentDay))},_attachHandlers:function(e){var i=this._get(e,"stepMonths"),s="#"+e.id.replace(/\\\\/g,"\\");e.dpDiv.find("[data-handler]").map(function(){t(this).on(this.getAttribute("data-event"),{prev:function(){t.datepicker._adjustDate(s,-i,"M")},next:function(){t.datepicker._adjustDate(s,+i,"M")},hide:function(){t.datepicker._hideDatepicker()},today:function(){t.datepicker._gotoToday(s)},selectDay:function(){return t.datepicker._selectDay(s,+this.getAttribute("data-month"),+this.getAttribute("data-year"),this),!1},selectMonth:function(){return t.datepicker._selectMonthYear(s,this,"M"),!1},selectYear:function(){return t.datepicker._selectMonthYear(s,this,"Y"),!1}}[this.getAttribute("data-handler")])})},_generateHTML:function(e){var i,s,n,o,a,r,l,h,c,u,d,p,f,g,m,_,v,b,y,w,x,k,C,D,I,T,P,M,S,H,z,O,A,E,N,W,F,L,R,Y=new Date,B=this._daylightSavingAdjust(new Date(Y.getFullYear(),Y.getMonth(),Y.getDate())),j=this._get(e,"isRTL"),q=this._get(e,"showButtonPanel"),K=this._get(e,"hideIfNoPrevNext"),U=this._get(e,"navigationAsDateFormat"),V=this._getNumberOfMonths(e),X=this._get(e,"showCurrentAtPos"),$=this._get(e,"stepMonths"),G=1!==V[0]||1!==V[1],Q=this._daylightSavingAdjust(e.currentDay?new Date(e.currentYear,e.currentMonth,e.currentDay):new Date(9999,9,9)),J=this._getMinMaxDate(e,"min"),Z=this._getMinMaxDate(e,"max"),tt=e.drawMonth-X,te=e.drawYear;if(tt<0&&(tt+=12,te--),Z){i=this._daylightSavingAdjust(new Date(Z.getFullYear(),Z.getMonth()-V[0]*V[1]+1,Z.getDate())),i=J&&i<J?J:i;while(this._daylightSavingAdjust(new Date(te,tt,1))>i)--tt<0&&(tt=11,te--)}for(e.drawMonth=tt,e.drawYear=te,s=this._get(e,"prevText"),s=U?this.formatDate(s,this._daylightSavingAdjust(new Date(te,tt-$,1)),this._getFormatConfig(e)):s,n=this._canAdjustMonth(e,-1,te,tt)?t("<a>").attr({class:"ui-datepicker-prev ui-corner-all","data-handler":"prev","data-event":"click",title:s}).append(t("<span>").addClass("ui-icon ui-icon-circle-triangle-"+(j?"e":"w")).text(s))[0].outerHTML:K?"":t("<a>").attr({class:"ui-datepicker-prev ui-corner-all ui-state-disabled",title:s}).append(t("<span>").addClass("ui-icon ui-icon-circle-triangle-"+(j?"e":"w")).text(s))[0].outerHTML,o=this._get(e,"nextText"),o=U?this.formatDate(o,this._daylightSavingAdjust(new Date(te,tt+$,1)),this._getFormatConfig(e)):o,a=this._canAdjustMonth(e,1,te,tt)?t("<a>").attr({class:"ui-datepicker-next ui-corner-all","data-handler":"next","data-event":"click",title:o}).append(t("<span>").addClass("ui-icon ui-icon-circle-triangle-"+(j?"w":"e")).text(o))[0].outerHTML:K?"":t("<a>").attr({class:"ui-datepicker-next ui-corner-all ui-state-disabled",title:o}).append(t("<span>").attr("class","ui-icon ui-icon-circle-triangle-"+(j?"w":"e")).text(o))[0].outerHTML,r=this._get(e,"currentText"),l=this._get(e,"gotoCurrent")&&e.currentDay?Q:B,r=U?this.formatDate(r,l,this._getFormatConfig(e)):r,h="",e.inline||(h=t("<button>").attr({type:"button",class:"ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all","data-handler":"hide","data-event":"click"}).text(this._get(e,"closeText"))[0].outerHTML),c="",q&&(c=t("<div class='ui-datepicker-buttonpane ui-widget-content'>").append(j?h:"").append(this._isInRange(e,l)?t("<button>").attr({type:"button",class:"ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all","data-handler":"today","data-event":"click"}).text(r):"").append(j?"":h)[0].outerHTML),u=isNaN(u=parseInt(this._get(e,"firstDay"),10))?0:u,d=this._get(e,"showWeek"),p=this._get(e,"dayNames"),f=this._get(e,"dayNamesMin"),g=this._get(e,"monthNames"),m=this._get(e,"monthNamesShort"),_=this._get(e,"beforeShowDay"),v=this._get(e,"showOtherMonths"),b=this._get(e,"selectOtherMonths"),y=this._getDefaultDate(e),w="",k=0;k<V[0];k++){for(D=0,C="",this.maxRows=4;D<V[1];D++){if(I=this._daylightSavingAdjust(new Date(te,tt,e.selectedDay)),T=" ui-corner-all",P="",G){if(P+="<div class='ui-datepicker-group",V[1]>1)switch(D){case 0:P+=" ui-datepicker-group-first",T=" ui-corner-"+(j?"right":"left");break;case V[1]-1:P+=" ui-datepicker-group-last",T=" ui-corner-"+(j?"left":"right");break;default:P+=" ui-datepicker-group-middle",T=""}P+="'>"}for(P+="<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix"+T+"'>"+(/all|left/.test(T)&&0===k?j?a:n:"")+(/all|right/.test(T)&&0===k?j?n:a:"")+this._generateMonthYearHeader(e,tt,te,J,Z,k>0||D>0,g,m)+"</div><table class='ui-datepicker-calendar'><thead><tr>",M=d?"<th class='ui-datepicker-week-col'>"+this._get(e,"weekHeader")+"</th>":"",x=0;x<7;x++)S=(x+u)%7,M+="<th scope='col'"+((x+u+6)%7>=5?" class='ui-datepicker-week-end'":"")+"><span title='"+p[S]+"'>"+f[S]+"</span></th>";for(P+=M+"</tr></thead><tbody>",H=this._getDaysInMonth(te,tt),te===e.selectedYear&&tt===e.selectedMonth&&(e.selectedDay=Math.min(e.selectedDay,H)),O=Math.ceil(((z=(this._getFirstDayOfMonth(te,tt)-u+7)%7)+H)/7),A=G&&this.maxRows>O?this.maxRows:O,this.maxRows=A,E=this._daylightSavingAdjust(new Date(te,tt,1-z)),N=0;N<A;N++){for(P+="<tr>",W=d?"<td class='ui-datepicker-week-col'>"+this._get(e,"calculateWeek")(E)+"</td>":"",x=0;x<7;x++)F=_?_.apply(e.input?e.input[0]:null,[E]):[!0,""],R=(L=E.getMonth()!==tt)&&!b||!F[0]||J&&E<J||Z&&E>Z,W+="<td class='"+((x+u+6)%7>=5?" ui-datepicker-week-end":"")+(L?" ui-datepicker-other-month":"")+(E.getTime()===I.getTime()&&tt===e.selectedMonth&&e._keyEvent||y.getTime()===E.getTime()&&y.getTime()===I.getTime()?" "+this._dayOverClass:"")+(R?" "+this._unselectableClass+" ui-state-disabled":"")+(L&&!v?"":" "+F[1]+(E.getTime()===Q.getTime()?" "+this._currentClass:"")+(E.getTime()===B.getTime()?" ui-datepicker-today":""))+"'"+((!L||v)&&F[2]?" title='"+F[2].replace(/'/g,"&#39;")+"'":"")+(R?"":" data-handler='selectDay' data-event='click' data-month='"+E.getMonth()+"' data-year='"+E.getFullYear()+"'")+">"+(L&&!v?"&#xa0;":R?"<span class='ui-state-default'>"+E.getDate()+"</span>":"<a class='ui-state-default"+(E.getTime()===B.getTime()?" ui-state-highlight":"")+(E.getTime()===Q.getTime()?" ui-state-active":"")+(L?" ui-priority-secondary":"")+"' href='#' aria-current='"+(E.getTime()===Q.getTime()?"true":"false")+"' data-date='"+E.getDate()+"'>"+E.getDate()+"</a>")+"</td>",E.setDate(E.getDate()+1),E=this._daylightSavingAdjust(E);P+=W+"</tr>"}++tt>11&&(tt=0,te++),P+="</tbody></table>"+(G?"</div>"+(V[0]>0&&D===V[1]-1?"<div class='ui-datepicker-row-break'></div>":""):""),C+=P}w+=C}return w+=c,e._keyEvent=!1,w},_generateMonthYearHeader:function(t,e,i,s,n,o,a,r){var l,h,c,u,d,p,f,g,m=this._get(t,"changeMonth"),_=this._get(t,"changeYear"),v=this._get(t,"showMonthAfterYear"),b=this._get(t,"selectMonthLabel"),y=this._get(t,"selectYearLabel"),w="<div class='ui-datepicker-title'>",x="";if(o||!m)x+="<span class='ui-datepicker-month'>"+a[e]+"</span>";else{for(l=s&&s.getFullYear()===i,h=n&&n.getFullYear()===i,x+="<select class='ui-datepicker-month' aria-label='"+b+"' data-handler='selectMonth' data-event='change'>",c=0;c<12;c++)(!l||c>=s.getMonth())&&(!h||c<=n.getMonth())&&(x+="<option value='"+c+"'"+(c===e?" selected='selected'":"")+">"+r[c]+"</option>");x+="</select>"}if(v||(w+=x+(o||!(m&&_)?"&#xa0;":"")),!t.yearshtml){if(t.yearshtml="",o||!_)w+="<span class='ui-datepicker-year'>"+i+"</span>";else{for(u=this._get(t,"yearRange").split(":"),d=new Date().getFullYear(),g=Math.max(f=(p=function(t){var e=t.match(/c[+\-].*/)?i+parseInt(t.substring(1),10):t.match(/[+\-].*/)?d+parseInt(t,10):parseInt(t,10);return isNaN(e)?d:e})(u[0]),p(u[1]||"")),f=s?Math.max(f,s.getFullYear()):f,g=n?Math.min(g,n.getFullYear()):g,t.yearshtml+="<select class='ui-datepicker-year' aria-label='"+y+"' data-handler='selectYear' data-event='change'>";f<=g;f++)t.yearshtml+="<option value='"+f+"'"+(f===i?" selected='selected'":"")+">"+f+"</option>";t.yearshtml+="</select>",w+=t.yearshtml,t.yearshtml=null}}return w+=this._get(t,"yearSuffix"),v&&(w+=(o||!(m&&_)?"&#xa0;":"")+x),w+="</div>"},_adjustInstDate:function(t,e,i){var s=t.selectedYear+("Y"===i?e:0),n=t.selectedMonth+("M"===i?e:0),o=Math.min(t.selectedDay,this._getDaysInMonth(s,n))+("D"===i?e:0),a=this._restrictMinMax(t,this._daylightSavingAdjust(new Date(s,n,o)));t.selectedDay=a.getDate(),t.drawMonth=t.selectedMonth=a.getMonth(),t.drawYear=t.selectedYear=a.getFullYear(),("M"===i||"Y"===i)&&this._notifyChange(t)},_restrictMinMax:function(t,e){var i=this._getMinMaxDate(t,"min"),s=this._getMinMaxDate(t,"max"),n=i&&e<i?i:e;return s&&n>s?s:n},_notifyChange:function(t){var e=this._get(t,"onChangeMonthYear");e&&e.apply(t.input?t.input[0]:null,[t.selectedYear,t.selectedMonth+1,t])},_getNumberOfMonths:function(t){var e=this._get(t,"numberOfMonths");return null==e?[1,1]:"number"==typeof e?[1,e]:e},_getMinMaxDate:function(t,e){return this._determineDate(t,this._get(t,e+"Date"),null)},_getDaysInMonth:function(t,e){return 32-this._daylightSavingAdjust(new Date(t,e,32)).getDate()},_getFirstDayOfMonth:function(t,e){return new Date(t,e,1).getDay()},_canAdjustMonth:function(t,e,i,s){var n=this._getNumberOfMonths(t),o=this._daylightSavingAdjust(new Date(i,s+(e<0?e:n[0]*n[1]),1));return e<0&&o.setDate(this._getDaysInMonth(o.getFullYear(),o.getMonth())),this._isInRange(t,o)},_isInRange:function(t,e){var i,s,n=this._getMinMaxDate(t,"min"),o=this._getMinMaxDate(t,"max"),a=null,r=null,l=this._get(t,"yearRange");return l&&(i=l.split(":"),s=new Date().getFullYear(),a=parseInt(i[0],10),r=parseInt(i[1],10),i[0].match(/[+\-].*/)&&(a+=s),i[1].match(/[+\-].*/)&&(r+=s)),(!n||e.getTime()>=n.getTime())&&(!o||e.getTime()<=o.getTime())&&(!a||e.getFullYear()>=a)&&(!r||e.getFullYear()<=r)},_getFormatConfig:function(t){var e=this._get(t,"shortYearCutoff");return{shortYearCutoff:e="string"!=typeof e?e:new Date().getFullYear()%100+parseInt(e,10),dayNamesShort:this._get(t,"dayNamesShort"),dayNames:this._get(t,"dayNames"),monthNamesShort:this._get(t,"monthNamesShort"),monthNames:this._get(t,"monthNames")}},_formatDate:function(t,e,i,s){e||(t.currentDay=t.selectedDay,t.currentMonth=t.selectedMonth,t.currentYear=t.selectedYear);var n=e?"object"==typeof e?e:this._daylightSavingAdjust(new Date(s,i,e)):this._daylightSavingAdjust(new Date(t.currentYear,t.currentMonth,t.currentDay));return this.formatDate(this._get(t,"dateFormat"),n,this._getFormatConfig(t))}}),t.fn.datepicker=function(e){if(!this.length)return this;t.datepicker.initialized||(t(document).on("mousedown",t.datepicker._checkExternalClick),t.datepicker.initialized=!0),0===t("#"+t.datepicker._mainDivId).length&&t("body").append(t.datepicker.dpDiv);var i=Array.prototype.slice.call(arguments,1);return"string"==typeof e&&("isDisabled"===e||"getDate"===e||"widget"===e)||"option"===e&&2==arguments.length&&"string"==typeof arguments[1]?t.datepicker["_"+e+"Datepicker"].apply(t.datepicker,[this[0]].concat(i)):this.each(function(){"string"==typeof e?t.datepicker["_"+e+"Datepicker"].apply(t.datepicker,[this].concat(i)):t.datepicker._attachDatepicker(this,e)})},t.datepicker=new P,t.datepicker.initialized=!1,t.datepicker.uuid=new Date().getTime(),t.datepicker.version="1.14.2",t.datepicker;var z=!1;function O(t){return function(){var e=this.element.val();t.apply(this,arguments),this._refresh(),e!==this.element.val()&&this._trigger("change")}}t(document).on("mouseup",function(){z=!1}),t.widget("ui.mouse",{version:"1.14.2",options:{cancel:"input, textarea, button, select, option",distance:1,delay:0},_mouseInit:function(){var e=this;this.element.on("mousedown."+this.widgetName,function(t){return e._mouseDown(t)}).on("click."+this.widgetName,function(i){if(!0===t.data(i.target,e.widgetName+".preventClickEvent"))return t.removeData(i.target,e.widgetName+".preventClickEvent"),i.stopImmediatePropagation(),!1}),this.started=!1},_mouseDestroy:function(){this.element.off("."+this.widgetName),this._mouseMoveDelegate&&this.document.off("mousemove."+this.widgetName,this._mouseMoveDelegate).off("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(e){if(!z){this._mouseMoved=!1,this._mouseStarted&&this._mouseUp(e),this._mouseDownEvent=e;var i=this,s=1===e.which,n="string"==typeof this.options.cancel&&t(e.target).closest(this.options.cancel).length;return!(s&&!n&&this._mouseCapture(e))||((this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){i.mouseDelayMet=!0},this.options.delay)),this._mouseDistanceMet(e)&&this._mouseDelayMet(e)&&(this._mouseStarted=!1!==this._mouseStart(e),!this._mouseStarted))?e.preventDefault():(!0===t.data(e.target,this.widgetName+".preventClickEvent")&&t.removeData(e.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(t){return i._mouseMove(t)},this._mouseUpDelegate=function(t){return i._mouseUp(t)},this.document.on("mousemove."+this.widgetName,this._mouseMoveDelegate).on("mouseup."+this.widgetName,this._mouseUpDelegate),e.preventDefault(),z=!0),!0)}},_mouseMove:function(t){if(this._mouseMoved&&!t.which){if(t.originalEvent.altKey||t.originalEvent.ctrlKey||t.originalEvent.metaKey||t.originalEvent.shiftKey)this.ignoreMissingWhich=!0;else if(!this.ignoreMissingWhich)return this._mouseUp(t)}return((t.which||t.button)&&(this._mouseMoved=!0),this._mouseStarted)?(this._mouseDrag(t),t.preventDefault()):(this._mouseDistanceMet(t)&&this._mouseDelayMet(t)&&(this._mouseStarted=!1!==this._mouseStart(this._mouseDownEvent,t),this._mouseStarted?this._mouseDrag(t):this._mouseUp(t)),!this._mouseStarted)},_mouseUp:function(e){this.document.off("mousemove."+this.widgetName,this._mouseMoveDelegate).off("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,e.target===this._mouseDownEvent.target&&t.data(e.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(e)),this._mouseDelayTimer&&(clearTimeout(this._mouseDelayTimer),delete this._mouseDelayTimer),this.ignoreMissingWhich=!1,z=!1,e.preventDefault()},_mouseDistanceMet:function(t){return Math.max(Math.abs(this._mouseDownEvent.pageX-t.pageX),Math.abs(this._mouseDownEvent.pageY-t.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}}),t.ui.plugin={add:function(e,i,s){var n,o=t.ui[e].prototype;for(n in s)o.plugins[n]=o.plugins[n]||[],o.plugins[n].push([i,s[n]])}
vendor: 14,241 bytes, line 12426
12426,call:function(t,e,i,s){var n,o=t.plugins[e];if(o&&(s||t.element[0].parentNode&&11!==t.element[0].parentNode.nodeType))for(n=0;n<o.length;n++)t.options[o[n][0]]&&o[n][1].apply(t.element,i)}},t.widget("ui.draggable",t.ui.mouse,{version:"1.14.2",widgetEventPrefix:"drag",options:{addClasses:!0,appendTo:"parent",axis:!1,connectToSortable:!1,containment:!1,cursor:"auto",cursorAt:!1,grid:!1,handle:!1,helper:"original",iframeFix:!1,opacity:!1,refreshPositions:!1,revert:!1,revertDuration:500,scope:"default",scroll:!0,scrollSensitivity:20,scrollSpeed:20,snap:!1,snapMode:"both",snapTolerance:20,stack:!1,zIndex:!1,drag:null,start:null,stop:null},_create:function(){"original"===this.options.helper&&this._setPositionRelative(),this.options.addClasses&&this._addClass("ui-draggable"),this._setHandleClassName(),this._mouseInit()},_setOption:function(t,e){this._super(t,e),"handle"===t&&(this._removeHandleClassName(),this._setHandleClassName())},_destroy:function(){if((this.helper||this.element).is(".ui-draggable-dragging")){this.destroyOnClear=!0;return}this._removeHandleClassName(),this._mouseDestroy()},_mouseCapture:function(e){var i=this.options;return!this.helper&&!i.disabled&&!(t(e.target).closest(".ui-resizable-handle").length>0)&&(this.handle=this._getHandle(e),!!this.handle&&(this._blurActiveElement(e),this._blockFrames(!0===i.iframeFix?"iframe":i.iframeFix),!0))},_blockFrames:function(e){this.iframeBlocks=this.document.find(e).map(function(){var e=t(this);return t("<div>").css("position","absolute").appendTo(e.parent()).outerWidth(e.outerWidth()).outerHeight(e.outerHeight()).offset(e.offset())[0]})},_unblockFrames:function(){this.iframeBlocks&&(this.iframeBlocks.remove(),delete this.iframeBlocks)},_blurActiveElement:function(e){var i=this.document[0].activeElement;!t(e.target).closest(i).length&&t(i).trigger("blur")},_mouseStart:function(e){var i=this.options;return(this.helper=this._createHelper(e),this._addClass(this.helper,"ui-draggable-dragging"),this._cacheHelperProportions(),t.ui.ddmanager&&(t.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(!0),this.offsetParent=this.helper.offsetParent(),this.hasFixedAncestor=this.helper.parents().filter(function(){return"fixed"===t(this).css("position")}).length>0,this.positionAbs=this.element.offset(),this._refreshOffsets(e),this.originalPosition=this.position=this._generatePosition(e,!1),this.originalPageX=e.pageX,this.originalPageY=e.pageY,i.cursorAt&&this._adjustOffsetFromHelper(i.cursorAt),this._setContainment(),!1===this._trigger("start",e))?(this._clear(),!1):(this._cacheHelperProportions(),t.ui.ddmanager&&!i.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e),this._mouseDrag(e,!0),t.ui.ddmanager&&t.ui.ddmanager.dragStart(this,e),!0)},_refreshOffsets:function(t){this.offset={top:this.positionAbs.top-this.margins.top,left:this.positionAbs.left-this.margins.left,scroll:!1,parent:this._getParentOffset(),relative:this._getRelativeOffset()},this.offset.click={left:t.pageX-this.offset.left,top:t.pageY-this.offset.top}},_mouseDrag:function(e,i){if(this.hasFixedAncestor&&(this.offset.parent=this._getParentOffset()),this.position=this._generatePosition(e,!0),this.positionAbs=this._convertPositionTo("absolute"),!i){var s=this._uiHash();if(!1===this._trigger("drag",e,s))return this._mouseUp(new t.Event("mouseup",e)),!1;this.position=s.position}return this.helper[0].style.left=this.position.left+"px",this.helper[0].style.top=this.position.top+"px",t.ui.ddmanager&&t.ui.ddmanager.drag(this,e),!1},_mouseStop:function(e){var i=this,s=!1;return t.ui.ddmanager&&!this.options.dropBehaviour&&(s=t.ui.ddmanager.drop(this,e)),this.dropped&&(s=this.dropped,this.dropped=!1),"invalid"===this.options.revert&&!s||"valid"===this.options.revert&&s||!0===this.options.revert||"function"==typeof this.options.revert&&this.options.revert.call(this.element,s)?t(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){!1!==i._trigger("stop",e)&&i._clear()}):!1!==this._trigger("stop",e)&&this._clear(),!1},_mouseUp:function(e){return this._unblockFrames(),t.ui.ddmanager&&t.ui.ddmanager.dragStop(this,e),this.handleElement.is(e.target)&&this.element.trigger("focus"),t.ui.mouse.prototype._mouseUp.call(this,e)},cancel:function(){return this.helper.is(".ui-draggable-dragging")?this._mouseUp(new t.Event("mouseup",{target:this.element[0]})):this._clear(),this},_getHandle:function(e){return!this.options.handle||!!t(e.target).closest(this.element.find(this.options.handle)).length},_setHandleClassName:function(){this.handleElement=this.options.handle?this.element.find(this.options.handle):this.element,this._addClass(this.handleElement,"ui-draggable-handle")},_removeHandleClassName:function(){this._removeClass(this.handleElement,"ui-draggable-handle")},_createHelper:function(e){var i=this.options,s="function"==typeof i.helper,n=s?t(i.helper.apply(this.element[0],[e])):"clone"===i.helper?this.element.clone().removeAttr("id"):this.element;return n.parents("body").length||n.appendTo("parent"===i.appendTo?this.element[0].parentNode:i.appendTo),s&&n[0]===this.element[0]&&this._setPositionRelative(),n[0]===this.element[0]||/(fixed|absolute)/.test(n.css("position"))||n.css("position","absolute"),n},_setPositionRelative:function(){/^(?:r|a|f)/.test(this.element.css("position"))||(this.element[0].style.position="relative")},_adjustOffsetFromHelper:function(t){"string"==typeof t&&(t=t.split(" ")),Array.isArray(t)&&(t={left:+t[0],top:+t[1]||0}),"left"in t&&(this.offset.click.left=t.left+this.margins.left),"right"in t&&(this.offset.click.left=this.helperProportions.width-t.right+this.margins.left),"top"in t&&(this.offset.click.top=t.top+this.margins.top),"bottom"in t&&(this.offset.click.top=this.helperProportions.height-t.bottom+this.margins.top)},_isRootNode:function(t){return/(html|body)/i.test(t.tagName)||t===this.document[0]},_getParentOffset:function(){var e=this.offsetParent.offset(),i=this.document[0];return"absolute"===this.cssPosition&&this.scrollParent[0]!==i&&t.contains(this.scrollParent[0],this.offsetParent[0])&&(e.left+=this.scrollParent.scrollLeft(),e.top+=this.scrollParent.scrollTop()),this._isRootNode(this.offsetParent[0])&&(e={top:0,left:0}),{top:e.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:e.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"!==this.cssPosition)return{top:0,left:0};var t=this.element.position(),e=this._isRootNode(this.scrollParent[0]);return{top:t.top-(parseInt(this.helper.css("top"),10)||0)+(e?0:this.scrollParent.scrollTop()),left:t.left-(parseInt(this.helper.css("left"),10)||0)+(e?0:this.scrollParent.scrollLeft())}},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e,i,s,n=this.options,o=this.document[0];if(this.relativeContainer=null,!n.containment){this.containment=null;return}if("window"===n.containment){this.containment=[t(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,t(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,t(window).scrollLeft()+t(window).width()-this.helperProportions.width-this.margins.left,t(window).scrollTop()+(t(window).height()||o.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];return}if("document"===n.containment){this.containment=[0,0,t(o).width()-this.helperProportions.width-this.margins.left,(t(o).height()||o.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];return}if(n.containment.constructor===Array){this.containment=n.containment;return}"parent"===n.containment&&(n.containment=this.helper[0].parentNode),(s=(i=t(n.containment))[0])&&(e=/(scroll|auto)/.test(i.css("overflow")),this.containment=[(parseInt(i.css("borderLeftWidth"),10)||0)+(parseInt(i.css("paddingLeft"),10)||0),(parseInt(i.css("borderTopWidth"),10)||0)+(parseInt(i.css("paddingTop"),10)||0),(e?Math.max(s.scrollWidth,s.offsetWidth):s.offsetWidth)-(parseInt(i.css("borderRightWidth"),10)||0)-(parseInt(i.css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(e?Math.max(s.scrollHeight,s.offsetHeight):s.offsetHeight)-(parseInt(i.css("borderBottomWidth"),10)||0)-(parseInt(i.css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relativeContainer=i)},_convertPositionTo:function(t,e){e||(e=this.position);var i="absolute"===t?1:-1,s=this._isRootNode(this.scrollParent[0]);return{top:e.top+this.offset.relative.top*i+this.offset.parent.top*i-("fixed"===this.cssPosition?-this.offset.scroll.top:s?0:this.offset.scroll.top)*i,left:e.left+this.offset.relative.left*i+this.offset.parent.left*i-("fixed"===this.cssPosition?-this.offset.scroll.left:s?0:this.offset.scroll.left)*i}},_generatePosition:function(t,e){var i,s,n,o,a=this.options,r=this._isRootNode(this.scrollParent[0]),l=t.pageX,h=t.pageY;return r&&this.offset.scroll||(this.offset.scroll={top:this.scrollParent.scrollTop(),left:this.scrollParent.scrollLeft()}),e&&(this.containment&&(this.relativeContainer?(s=this.relativeContainer.offset(),i=[this.containment[0]+s.left,this.containment[1]+s.top,this.containment[2]+s.left,this.containment[3]+s.top]):i=this.containment,t.pageX-this.offset.click.left<i[0]&&(l=i[0]+this.offset.click.left),t.pageY-this.offset.click.top<i[1]&&(h=i[1]+this.offset.click.top),t.pageX-this.offset.click.left>i[2]&&(l=i[2]+this.offset.click.left),t.pageY-this.offset.click.top>i[3]&&(h=i[3]+this.offset.click.top)),a.grid&&(n=a.grid[1]?this.originalPageY+Math.round((h-this.originalPageY)/a.grid[1])*a.grid[1]:this.originalPageY,h=i?n-this.offset.click.top>=i[1]||n-this.offset.click.top>i[3]?n:n-this.offset.click.top>=i[1]?n-a.grid[1]:n+a.grid[1]:n,o=a.grid[0]?this.originalPageX+Math.round((l-this.originalPageX)/a.grid[0])*a.grid[0]:this.originalPageX,l=i?o-this.offset.click.left>=i[0]||o-this.offset.click.left>i[2]?o:o-this.offset.click.left>=i[0]?o-a.grid[0]:o+a.grid[0]:o),"y"===a.axis&&(l=this.originalPageX),"x"===a.axis&&(h=this.originalPageY)),{top:h-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.offset.scroll.top:r?0:this.offset.scroll.top),left:l-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.offset.scroll.left:r?0:this.offset.scroll.left)}},_clear:function(){this._removeClass(this.helper,"ui-draggable-dragging"),this.helper[0]===this.element[0]||this.cancelHelperRemoval||this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1,this.destroyOnClear&&this.destroy()},_trigger:function(e,i,s){return s=s||this._uiHash(),t.ui.plugin.call(this,e,[i,s,this],!0),/^(drag|start|stop)/.test(e)&&(this.positionAbs=this._convertPositionTo("absolute"),s.offset=this.positionAbs),t.Widget.prototype._trigger.call(this,e,i,s)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),t.ui.plugin.add("draggable","connectToSortable",{start:function(e,i,s){var n=t.extend({},i,{item:s.element});s.sortables=[],t(s.options.connectToSortable).each(function(){var i=t(this).sortable("instance");i&&!i.options.disabled&&(s.sortables.push(i),i.refreshPositions(),i._trigger("activate",e,n))})},stop:function(e,i,s){var n=t.extend({},i,{item:s.element});s.cancelHelperRemoval=!1,t.each(s.sortables,function(){this.isOver?(this.isOver=0,s.cancelHelperRemoval=!0,this.cancelHelperRemoval=!1,this._storedCSS={position:this.placeholder.css("position"),top:this.placeholder.css("top"),left:this.placeholder.css("left")},this._mouseStop(e),this.options.helper=this.options._helper):(this.cancelHelperRemoval=!0,this._trigger("deactivate",e,n))})},drag:function(e,i,s){t.each(s.sortables,function(){var n=!1,o=this;o.positionAbs=s.positionAbs,o.helperProportions=s.helperProportions,o.offset.click=s.offset.click,o._intersectsWith(o.containerCache)&&(n=!0,t.each(s.sortables,function(){return this.positionAbs=s.positionAbs,this.helperProportions=s.helperProportions,this.offset.click=s.offset.click,this!==o&&this._intersectsWith(this.containerCache)&&t.contains(o.element[0],this.element[0])&&(n=!1),n})),n?(o.isOver||(o.isOver=1,s._parent=i.helper.parent(),o.currentItem=i.helper.appendTo(o.element).data("ui-sortable-item",!0),o.options._helper=o.options.helper,o.options.helper=function(){return i.helper[0]},e.target=o.currentItem[0],o._mouseCapture(e,!0),o._mouseStart(e,!0,!0),o.offset.click.top=s.offset.click.top,o.offset.click.left=s.offset.click.left,o.offset.parent.left-=s.offset.parent.left-o.offset.parent.left,o.offset.parent.top-=s.offset.parent.top-o.offset.parent.top,s._trigger("toSortable",e),s.dropped=o.element,t.each(s.sortables,function(){this.refreshPositions()}),s.currentItem=s.element,o.fromOutside=s),o.currentItem&&(o._mouseDrag(e),i.position=o.position)):o.isOver&&(o.isOver=0,o.cancelHelperRemoval=!0,o.options._revert=o.options.revert,o.options.revert=!1,o._trigger("out",e,o._uiHash(o)),o._mouseStop(e,!0),o.options.revert=o.options._revert,o.options.helper=o.options._helper,o.placeholder&&o.placeholder.remove(),i.helper.appendTo(s._parent),s._refreshOffsets(e),i.position=s._generatePosition(e,!0),s._trigger("fromSortable",e),s.dropped=!1,t.each(s.sortables,function(){this.refreshPositions()}))})}}),t.ui.plugin.add("draggable","cursor",{start:function(e,i,s){var n=t("body"),o=s.options;n.css("cursor")&&(o._cursor=n.css("cursor")),n.css("cursor",o.cursor)},stop:function(e,i,s){var n=s.options;n._cursor&&t("body").css("cursor",n._cursor)}}),t.ui.plugin.add("draggable","opacity",{start:function(e,i,s){var n=t(i.helper),o=s.options;n.css("opacity")&&(o._opacity=n.css("opacity")),n.css("opacity",o.opacity)},stop:function(e,i,s){var n=s.options;n._opacity&&t(i.helper).css("opacity",n._opacity)}}
vendor: 7,485 bytes, line 12426
12426),t.ui.plugin.add("draggable","scroll",{start:function(t,e,i){i.scrollParentNotHidden||(i.scrollParentNotHidden=i.helper.scrollParent(!1)),i.scrollParentNotHidden[0]!==i.document[0]&&"HTML"!==i.scrollParentNotHidden[0].tagName&&(i.overflowOffset=i.scrollParentNotHidden.offset())},drag:function(e,i,s){var n=s.options,o=!1,a=s.scrollParentNotHidden[0],r=s.document[0];a!==r&&"HTML"!==a.tagName?((!n.axis||"x"!==n.axis)&&(s.overflowOffset.top+a.offsetHeight-e.pageY<n.scrollSensitivity?a.scrollTop=o=a.scrollTop+n.scrollSpeed:e.pageY-s.overflowOffset.top<n.scrollSensitivity&&(a.scrollTop=o=a.scrollTop-n.scrollSpeed)),(!n.axis||"y"!==n.axis)&&(s.overflowOffset.left+a.offsetWidth-e.pageX<n.scrollSensitivity?a.scrollLeft=o=a.scrollLeft+n.scrollSpeed:e.pageX-s.overflowOffset.left<n.scrollSensitivity&&(a.scrollLeft=o=a.scrollLeft-n.scrollSpeed))):((!n.axis||"x"!==n.axis)&&(e.pageY-t(r).scrollTop()<n.scrollSensitivity?o=t(r).scrollTop(t(r).scrollTop()-n.scrollSpeed):t(window).height()-(e.pageY-t(r).scrollTop())<n.scrollSensitivity&&(o=t(r).scrollTop(t(r).scrollTop()+n.scrollSpeed))),(!n.axis||"y"!==n.axis)&&(e.pageX-t(r).scrollLeft()<n.scrollSensitivity?o=t(r).scrollLeft(t(r).scrollLeft()-n.scrollSpeed):t(window).width()-(e.pageX-t(r).scrollLeft())<n.scrollSensitivity&&(o=t(r).scrollLeft(t(r).scrollLeft()+n.scrollSpeed)))),!1!==o&&t.ui.ddmanager&&!n.dropBehaviour&&t.ui.ddmanager.prepareOffsets(s,e)}}),t.ui.plugin.add("draggable","snap",{start:function(e,i,s){var n=s.options;s.snapElements=[],t(n.snap.constructor!==String?n.snap.items||":data(ui-draggable)":n.snap).each(function(){var e=t(this),i=e.offset();this!==s.element[0]&&s.snapElements.push({item:this,width:e.outerWidth(),height:e.outerHeight(),top:i.top,left:i.left})})},drag:function(e,i,s){var n,o,a,r,l,h,c,u,d,p,f=s.options,g=f.snapTolerance,m=i.offset.left,_=m+s.helperProportions.width,v=i.offset.top,b=v+s.helperProportions.height;for(d=s.snapElements.length-1;d>=0;d--){if(h=(l=s.snapElements[d].left-s.margins.left)+s.snapElements[d].width,u=(c=s.snapElements[d].top-s.margins.top)+s.snapElements[d].height,_<l-g||m>h+g||b<c-g||v>u+g||!t.contains(s.snapElements[d].item.ownerDocument,s.snapElements[d].item)){s.snapElements[d].snapping&&s.options.snap.release&&s.options.snap.release.call(s.element,e,t.extend(s._uiHash(),{snapItem:s.snapElements[d].item})),s.snapElements[d].snapping=!1;continue}"inner"!==f.snapMode&&(n=Math.abs(c-b)<=g,o=Math.abs(u-v)<=g,a=Math.abs(l-_)<=g,r=Math.abs(h-m)<=g,n&&(i.position.top=s._convertPositionTo("relative",{top:c-s.helperProportions.height,left:0}).top),o&&(i.position.top=s._convertPositionTo("relative",{top:u,left:0}).top),a&&(i.position.left=s._convertPositionTo("relative",{top:0,left:l-s.helperProportions.width}).left),r&&(i.position.left=s._convertPositionTo("relative",{top:0,left:h}).left)),p=n||o||a||r,"outer"!==f.snapMode&&(n=Math.abs(c-v)<=g,o=Math.abs(u-b)<=g,a=Math.abs(l-m)<=g,r=Math.abs(h-_)<=g,n&&(i.position.top=s._convertPositionTo("relative",{top:c,left:0}).top),o&&(i.position.top=s._convertPositionTo("relative",{top:u-s.helperProportions.height,left:0}).top),a&&(i.position.left=s._convertPositionTo("relative",{top:0,left:l}).left),r&&(i.position.left=s._convertPositionTo("relative",{top:0,left:h-s.helperProportions.width}).left)),!s.snapElements[d].snapping&&(n||o||a||r||p)&&s.options.snap.snap&&s.options.snap.snap.call(s.element,e,t.extend(s._uiHash(),{snapItem:s.snapElements[d].item})),s.snapElements[d].snapping=n||o||a||r||p}}}),t.ui.plugin.add("draggable","stack",{start:function(e,i,s){var n,o=s.options,a=t.makeArray(t(o.stack)).sort(function(e,i){return(parseInt(t(e).css("zIndex"),10)||0)-(parseInt(t(i).css("zIndex"),10)||0)});a.length&&(n=parseInt(t(a[0]).css("zIndex"),10)||0,t(a).each(function(e){t(this).css("zIndex",n+e)}),this.css("zIndex",n+a.length))}}),t.ui.plugin.add("draggable","zIndex",{start:function(e,i,s){var n=t(i.helper),o=s.options;n.css("zIndex")&&(o._zIndex=n.css("zIndex")),n.css("zIndex",o.zIndex)},stop:function(e,i,s){var n=s.options;n._zIndex&&t(i.helper).css("zIndex",n._zIndex)}}),t.ui.draggable,t.widget("ui.resizable",t.ui.mouse,{version:"1.14.2",widgetEventPrefix:"resize",options:{alsoResize:!1,animate:!1,animateDuration:"slow",animateEasing:"swing",aspectRatio:!1,autoHide:!1,classes:{"ui-resizable-se":"ui-icon ui-icon-gripsmall-diagonal-se"},containment:!1,ghost:!1,grid:!1,handles:"e,s,se",helper:!1,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:90,resize:null,start:null,stop:null},_num:function(t){return parseFloat(t)||0},_isNumber:function(t){return!isNaN(parseFloat(t))},_hasScroll:function(e,i){var s,n=!1,o=t(e).css("overflow");if("hidden"===o)return!1;if("scroll"===o||e[s=i&&"left"===i?"scrollLeft":"scrollTop"]>0)return!0;try{e[s]=1,n=e[s]>0,e[s]=0}catch(t){}return n},_create:function(){var e,i=this.options,s=this;this._addClass("ui-resizable"),t.extend(this,{_aspectRatio:!!i.aspectRatio,aspectRatio:i.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:i.helper||i.ghost||i.animate?i.helper||"ui-resizable-helper":null}),this.element[0].nodeName.match(/^(canvas|textarea|input|select|button|img)$/i)&&(this.element.wrap(t("<div class='ui-wrapper'></div>").css({overflow:"hidden",position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")})),this.element=this.element.parent().data("ui-resizable",this.element.resizable("instance")),this.elementIsWrapper=!0,e={marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom"),marginLeft:this.originalElement.css("marginLeft")},this.element.css(e),this.originalResizeStyle=this.originalElement.css("resize"),this.originalElement.css("resize","none"),this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"})),this._proportionallyResize()),this._setupHandles(),i.autoHide&&t(this.element).on("mouseenter",function(){!i.disabled&&(s._removeClass("ui-resizable-autohide"),s._handles.show())}).on("mouseleave",function(){!i.disabled&&(s.resizing||(s._addClass("ui-resizable-autohide"),s._handles.hide()))}),this._mouseInit()},_destroy:function(){this._mouseDestroy(),this._addedHandles.remove();var e,i=function(e){t(e).removeData("resizable").removeData("ui-resizable").off(".resizable")};return this.elementIsWrapper&&(i(this.element),e=this.element,this.originalElement.css({position:e.css("position"),width:e.outerWidth(),height:e.outerHeight(),top:e.css("top"),left:e.css("left")}).insertAfter(e),e.remove()),this.originalElement.css("resize",this.originalResizeStyle),i(this.originalElement),this},_setOption:function(t,e){switch(this._super(t,e),t){case"handles":this._removeHandles(),this._setupHandles();break;case"aspectRatio":this._aspectRatio=!!e}},_setupHandles:function(){var e,i,s,n,o,a=this.options,r=this;if(this.handles=a.handles||(t(".ui-resizable-handle",this.element).length?{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"}:"e,s,se"),this._handles=t(),this._addedHandles=t(),this.handles.constructor===String)for("all"===this.handles&&(this.handles="n,e,s,w,se,sw,ne,nw"),s=this.handles.split(","),this.handles={},i=0;i<s.length;i++)n="ui-resizable-"+(e=String.prototype.trim.call(s[i])),o=t("<
vendor: 13,711 bytes, line 12426
12426div>"),this._addClass(o,"ui-resizable-handle "+n),o.css({zIndex:a.zIndex}),this.handles[e]=".ui-resizable-"+e,this.element.children(this.handles[e]).length||(this.element.append(o),this._addedHandles=this._addedHandles.add(o));this._renderAxis=function(e){var i,s,n,o;for(i in e=e||this.element,this.handles)this.handles[i].constructor===String?this.handles[i]=this.element.children(this.handles[i]).first().show():(this.handles[i].jquery||this.handles[i].nodeType)&&(this.handles[i]=t(this.handles[i]),this._on(this.handles[i],{mousedown:r._mouseDown})),this.elementIsWrapper&&this.originalElement[0].nodeName.match(/^(textarea|input|select|button)$/i)&&(s=t(this.handles[i],this.element),o=/sw|ne|nw|se|n|s/.test(i)?s.outerHeight():s.outerWidth(),n=["padding",/ne|nw|n/.test(i)?"Top":/se|sw|s/.test(i)?"Bottom":/^e$/.test(i)?"Right":"Left"].join(""),e.css(n,o),this._proportionallyResize()),this._handles=this._handles.add(this.handles[i])},this._renderAxis(this.element),this._handles=this._handles.add(this.element.find(".ui-resizable-handle")),this._handles.disableSelection(),this._handles.on("mouseover",function(){r.resizing||(this.className&&(o=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)),r.axis=o&&o[1]?o[1]:"se")}),a.autoHide&&(this._handles.hide(),this._addClass("ui-resizable-autohide"))},_removeHandles:function(){this._addedHandles.remove()},_mouseCapture:function(e){var i,s,n=!1;for(i in this.handles)((s=t(this.handles[i])[0])===e.target||t.contains(s,e.target))&&(n=!0);return!this.options.disabled&&n},_mouseStart:function(e){var i,s,n,o,a=this.options,r=this.element;return this.resizing=!0,this._renderProxy(),i=this._num(this.helper.css("left")),s=this._num(this.helper.css("top")),a.containment&&(i+=t(a.containment).scrollLeft()||0,s+=t(a.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:i,top:s},this._helper||(o=this._calculateAdjustedElementDimensions(r)),this.size=this._helper?{width:this.helper.width(),height:this.helper.height()}:{width:o.width,height:o.height},this.originalSize=this._helper?{width:r.outerWidth(),height:r.outerHeight()}:{width:o.width,height:o.height},this.sizeDiff={width:r.outerWidth()-r.width(),height:r.outerHeight()-r.height()},this.originalPosition={left:i,top:s},this.originalMousePosition={left:e.pageX,top:e.pageY},this.aspectRatio="number"==typeof a.aspectRatio?a.aspectRatio:this.originalSize.width/this.originalSize.height||1,n=t(".ui-resizable-"+this.axis).css("cursor"),t("body").css("cursor","auto"===n?this.axis+"-resize":n),this._addClass("ui-resizable-resizing"),this._propagate("start",e),!0},_mouseDrag:function(e){var i,s,n=this.originalMousePosition,o=this.axis,a=e.pageX-n.left||0,r=e.pageY-n.top||0,l=this._change[o];return this._updatePrevProperties(),!!l&&(i=l.apply(this,[e,a,r]),this._updateVirtualBoundaries(e.shiftKey),(this._aspectRatio||e.shiftKey)&&(i=this._updateRatio(i,e)),i=this._respectSize(i,e),this._updateCache(i),this._propagate("resize",e),s=this._applyChanges(),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),t.isEmptyObject(s)||(this._updatePrevProperties(),this._trigger("resize",e,this.ui()),this._applyChanges()),!1)},_mouseStop:function(e){this.resizing=!1;var i,s,n,o,a,r,l,h=this.options;return this._helper&&(n=(s=(i=this._proportionallyResizeElements).length&&/textarea/i.test(i[0].nodeName))&&this._hasScroll(i[0],"left")?0:this.sizeDiff.height,o=s?0:this.sizeDiff.width,a={width:this.helper.width()-o,height:this.helper.height()-n},r=parseFloat(this.element.css("left"))+(this.position.left-this.originalPosition.left)||null,l=parseFloat(this.element.css("top"))+(this.position.top-this.originalPosition.top)||null,h.animate||this.element.css(t.extend(a,{top:l,left:r})),this.helper.height(this.size.height),this.helper.width(this.size.width),this._helper&&!h.animate&&this._proportionallyResize()),t("body").css("cursor","auto"),this._removeClass("ui-resizable-resizing"),this._propagate("stop",e),this._helper&&this.helper.remove(),!1},_updatePrevProperties:function(){this.prevPosition={top:this.position.top,left:this.position.left},this.prevSize={width:this.size.width,height:this.size.height}},_applyChanges:function(){var t={};return this.position.top!==this.prevPosition.top&&(t.top=this.position.top+"px"),this.position.left!==this.prevPosition.left&&(t.left=this.position.left+"px"),this.helper.css(t),this.size.width!==this.prevSize.width&&(t.width=this.size.width+"px",this.helper.width(t.width)),this.size.height!==this.prevSize.height&&(t.height=this.size.height+"px",this.helper.height(t.height)),t},_updateVirtualBoundaries:function(t){var e,i,s,n,o,a=this.options;o={minWidth:this._isNumber(a.minWidth)?a.minWidth:0,maxWidth:this._isNumber(a.maxWidth)?a.maxWidth:1/0,minHeight:this._isNumber(a.minHeight)?a.minHeight:0,maxHeight:this._isNumber(a.maxHeight)?a.maxHeight:1/0},(this._aspectRatio||t)&&(e=o.minHeight*this.aspectRatio,s=o.minWidth/this.aspectRatio,i=o.maxHeight*this.aspectRatio,n=o.maxWidth/this.aspectRatio,e>o.minWidth&&(o.minWidth=e),s>o.minHeight&&(o.minHeight=s),i<o.maxWidth&&(o.maxWidth=i),n<o.maxHeight&&(o.maxHeight=n)),this._vBoundaries=o},_updateCache:function(t){this.offset=this.helper.offset(),this._isNumber(t.left)&&(this.position.left=t.left),this._isNumber(t.top)&&(this.position.top=t.top),this._isNumber(t.height)&&(this.size.height=t.height),this._isNumber(t.width)&&(this.size.width=t.width)},_updateRatio:function(t){var e=this.position,i=this.size,s=this.axis;return this._isNumber(t.height)?t.width=t.height*this.aspectRatio:this._isNumber(t.width)&&(t.height=t.width/this.aspectRatio),"sw"===s&&(t.left=e.left+(i.width-t.width),t.top=null),"nw"===s&&(t.top=e.top+(i.height-t.height),t.left=e.left+(i.width-t.width)),t},_respectSize:function(t){var e=this._vBoundaries,i=this.axis,s=this._isNumber(t.width)&&e.maxWidth&&e.maxWidth<t.width,n=this._isNumber(t.height)&&e.maxHeight&&e.maxHeight<t.height,o=this._isNumber(t.width)&&e.minWidth&&e.minWidth>t.width,a=this._isNumber(t.height)&&e.minHeight&&e.minHeight>t.height,r=this.originalPosition.left+this.originalSize.width,l=this.originalPosition.top+this.originalSize.height,h=/sw|nw|w/.test(i),c=/nw|ne|n/.test(i);return o&&(t.width=e.minWidth),a&&(t.height=e.minHeight),s&&(t.width=e.maxWidth),n&&(t.height=e.maxHeight),o&&h&&(t.left=r-e.minWidth),s&&h&&(t.left=r-e.maxWidth),a&&c&&(t.top=l-e.minHeight),n&&c&&(t.top=l-e.maxHeight),t.width||t.height||t.left||!t.top?t.width||t.height||t.top||!t.left||(t.left=null):t.top=null,t},_getPaddingPlusBorderDimensions:function(t){for(var e=0,i=[],s=[t.css("borderTopWidth"),t.css("borderRightWidth"),t.css("borderBottomWidth"),t.css("borderLeftWidth")],n=[t.css("paddingTop"),t.css("paddingRight"),t.css("paddingBottom"),t.css("paddingLeft")];e<4;e++)i[e]=parseFloat(s[e])||0,i[e]+=parseFloat(n[e])||0;return{height:i[0]+i[2],width:i[1]+i[3]}},_calculateAdjustedElementDimensions:function(t){var e,i,s,n=t.get(0);return"content-box"===t.css("box-sizing")&&(this._hasScroll(n)||this._hasScroll(n,"left"))?(e=parseFloat(n.style.width),i=parseFloat(n.style.height),s=this._getPaddingPlusBorderDimensions(t),e=isNaN(e)?this._getElementTheoreticalSize(t,s,"width"):e,{height:i=isNaN(i)?this._getElementTheoreticalSize(t,s,"height"):i,width:e}):{height:parseFloat(t.css("height")),width:parseFloat(t.css("width"))}},_getElementTheoreticalSize:function(t,e,i){return Math.max(0,Math.ceil(t.get(0)["offset"+i[0].toUpperCase()+i.slice(1)]-e[i]-.5))||0},_proportionallyResize:function(){if(this._proportionallyResizeElements.length)for(var t,e=0,i=this.helper||this.element;e<this._proportionallyResizeElements.length;e++)t=this._proportionallyResizeElements[e],this.outerDimensions||(this.outerDimensions=this._getPaddingPlusBorderDimensions(t)),t.css({height:i.height()-this.outerDimensions.height||0,width:i.width()-this.outerDimensions.width||0})},_renderProxy:function(){var e=this.element,i=this.options;this.elementOffset=e.offset(),this._helper?(this.helper=this.helper||t("<div></div>").css({overflow:"hidden"}),this._addClass(this.helper,this._helper),this.helper.css({width:this.element.outerWidth(),height:this.element.outerHeight(),position:"absolute",left:this.elementOffset.left+"px",top:this.elementOffset.top+"px",zIndex:++i.zIndex}),this.helper.appendTo("body").disableSelection()):this.helper=this.element},_change:{e:function(t,e){return{width:this.originalSize.width+e}},w:function(t,e){var i=this.originalSize;return{left:this.originalPosition.left+e,width:i.width-e}},n:function(t,e,i){var s=this.originalSize;return{top:this.originalPosition.top+i,height:s.height-i}},s:function(t,e,i){return{height:this.originalSize.height+i}},se:function(e,i,s){return t.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[e,i,s]))},sw:function(e,i,s){return t.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[e,i,s]))},ne:function(e,i,s){return t.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[e,i,s]))},nw:function(e,i,s){return t.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[e,i,s]))}},_propagate:function(e,i){t.ui.plugin.call(this,e,[i,this.ui()]),"resize"!==e&&this._trigger(e,i,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}}),t.ui.plugin.add("resizable","animate",{stop:function(e){var i=t(this).resizable("instance"),s=i.options,n=i._proportionallyResizeElements,o=n.length&&/textarea/i.test(n[0].nodeName),a=o&&i._hasScroll(n[0],"left")?0:i.sizeDiff.height,r=o?0:i.sizeDiff.width,l={width:i.size.width-r,height:i.size.height-a},h=parseFloat(i.element.css("left"))+(i.position.left-i.originalPosition.left)||null,c=parseFloat(i.element.css("top"))+(i.position.top-i.originalPosition.top)||null;i.element.animate(t.extend(l,c&&h?{top:c,left:h}:{}),{duration:s.animateDuration,easing:s.animateEasing,step:function(){var s={width:parseFloat(i.element.css("width")),height:parseFloat(i.element.css("height")),top:parseFloat(i.element.css("top")),left:parseFloat(i.element.css("left"))};n&&n.length&&t(n[0]).css({width:s.width,height:s.height}),i._updateCache(s),i._propagate("resize",e)}})}}),t.ui.plugin.add("resizable","containment",{start:function(){var e,i,s,n,o,a,r,l=t(this).resizable("instance"),h=l.options,c=l.element,u=h.containment,d=u instanceof t?u.get(0):/parent/.test(u)?c.parent().get(0):u;d&&(l.containerElement=t(d),/document/.test(u)||u===document?(l.containerOffset={left:0,top:0},l.containerPosition={left:0,top:0},l.parentData={element:t(document),left:0,top:0,width:t(document).width(),height:t(document).height()||document.body.parentNode.scrollHeight}):(e=t(d),i=[],t(["Top","Right","Left","Bottom"]).each(function(t,s){i[t]=l._num(e.css("padding"+s))}),l.containerOffset=e.offset(),l.containerPosition=e.position(),l.containerSize={height:e.innerHeight()-i[3],width:e.innerWidth()-i[1]},s=l.containerOffset,n=l.containerSize.height,o=l.containerSize.width,a=l._hasScroll(d,"left")?d.scrollWidth:o,r=l._hasScroll(d)?d.scrollHeight:n,l.parentData={element:d,left:s.left,top:s.top,width:a,height:r}))},resize:function(e){var i,s,n,o,a=t(this).resizable("instance"),r=a.options,l=a.containerOffset,h=a.position,c=a._aspectRatio||e.shiftKey,u={top:0,left:0},d=a.containerElement,p=!0;d[0]!==document&&/static/.test(d.css("position"))&&(u=l),h.left<(a._helper?l.left:0)&&(a.size.width=a.size.width+(a._helper?a.position.left-l.left:a.position.left-u.left),c&&(a.size.height=a.size.width/a.aspectRatio,p=!1),a.position.left=r.helper?l.left:0),h.top<(a._helper?l.top:0)&&(a.size.height=a.size.height+(a._helper?a.position.top-l.top:a.position.top),c&&(a.size.width=a.size.height*a.aspectRatio,p=!1),a.position.top=a._helper?l.top:0),n=a.containerElement.get(0)===a.element.parent().get(0),o=/relative|absolute/.test(a.containerElement.css("position")),n&&o?(a.offset.left=a.parentData.left+a.position.left,a.offset.top=a.parentData.top+a.position.top):(a.offset.left=a.element.offset().left,a.offset.top=a.element.offset().top),i=Math.abs(a.sizeDiff.width+(a._helper?a.offset.left-u.left:a.offset.left-l.left)),s=Math.abs(a.sizeDiff.height+(a._helper?a.offset.top-u.top:a.offset.top-l.top)),i+a.size.width>=a.parentData.width&&(a.size.width=a.parentData.width-i,c&&(a.size.height=a.size.width/a.aspectRatio,p=!1)),s+a.size.height>=a.parentData.height&&(a.size.height=a.parentData.height-s,c&&(a.size.width=a.size.height*a.aspectRatio,p=!1)),p||(a.position.left=a.prevPosition.left,a.position.top=a.prevPosition.top,a.size.width=a.prevSize.width,a.size.height=a.prevSize.height)},stop:function(){var e=t(this).resizable("instance"),i=e.options,s=e.containerOffset,n=e.containerPosition,o=e.containerElement,a=t(e.helper),r=a.offset(),l=a.outerWidth()-e.sizeDiff.width,h=a.outerHeight()-e.sizeDiff.height;e._helper&&!i.animate&&/relative/.test(o.css("position"))&&t(this).css({left:r.left-n.left-s.left,width:l,height:h}),e._helper&&!i.animate&&/static/.test(o.css("position"))&&t(this).css({left:r.left-n.left-s.left,width:l,height:h})}}),t.ui.plugin.add("resizable","alsoResize",{start:function(){var e=t(this).resizable("instance");t(e.options.alsoResize).each(function(){var i=t(this),s=e._calculateAdjustedElementDimensions(i);i.data("ui-resizable-alsoresize",{width:s.width,height:s.height,left:parseFloat(i.css("left")),top:parseFloat(i.css("top"))})})},resize:function(e,i){var s=t(this).resizable("instance"),n=s.options,o=s.originalSize,a=s.originalPosition,r={height:s.size.height-o.height||0,width:s.size.width-o.width||0,top:s.position.top-a.top||0,left
vendor: 8,009 bytes, line 12426
12426:s.position.left-a.left||0};t(n.alsoResize).each(function(){var e=t(this),s=t(this).data("ui-resizable-alsoresize"),n={},o=e.parents(i.originalElement[0]).length?["width","height"]:["width","height","top","left"];t.each(o,function(t,e){var i=(s[e]||0)+(r[e]||0);i&&i>=0&&(n[e]=i||null)}),e.css(n)})},stop:function(){t(this).removeData("ui-resizable-alsoresize")}}),t.ui.plugin.add("resizable","ghost",{start:function(){var e=t(this).resizable("instance"),i=e.size;e.ghost=e.originalElement.clone(),e.ghost.css({opacity:.25,display:"block",position:"relative",height:i.height,width:i.width,margin:0,left:0,top:0}),e._addClass(e.ghost,"ui-resizable-ghost"),!0===t.uiBackCompat&&"string"==typeof e.options.ghost&&e.ghost.addClass(this.options.ghost),e.ghost.appendTo(e.helper)},resize:function(){var e=t(this).resizable("instance");e.ghost&&e.ghost.css({position:"relative",height:e.size.height,width:e.size.width})},stop:function(){var e=t(this).resizable("instance");e.ghost&&e.helper&&e.helper.get(0).removeChild(e.ghost.get(0))}}),t.ui.plugin.add("resizable","grid",{resize:function(){var e,i=t(this).resizable("instance"),s=i.options,n=i.size,o=i.originalSize,a=i.originalPosition,r=i.axis,l="number"==typeof s.grid?[s.grid,s.grid]:s.grid,h=l[0]||1,c=l[1]||1,u=Math.round((n.width-o.width)/h)*h,d=Math.round((n.height-o.height)/c)*c,p=o.width+u,f=o.height+d,g=s.maxWidth&&s.maxWidth<p,m=s.maxHeight&&s.maxHeight<f,_=s.minWidth&&s.minWidth>p,v=s.minHeight&&s.minHeight>f;s.grid=l,_&&(p+=h),v&&(f+=c),g&&(p-=h),m&&(f-=c),/^(se|s|e)$/.test(r)?(i.size.width=p,i.size.height=f):/^(ne)$/.test(r)?(i.size.width=p,i.size.height=f,i.position.top=a.top-d):/^(sw)$/.test(r)?(i.size.width=p,i.size.height=f,i.position.left=a.left-u):((f-c<=0||p-h<=0)&&(e=i._getPaddingPlusBorderDimensions(this)),f-c>0?(i.size.height=f,i.position.top=a.top-d):(f=c-e.height,i.size.height=f,i.position.top=a.top+o.height-f),p-h>0?(i.size.width=p,i.position.left=a.left-u):(p=h-e.width,i.size.width=p,i.position.left=a.left+o.width-p))}}),t.ui.resizable,t.widget("ui.dialog",{version:"1.14.2",options:{appendTo:"body",autoOpen:!0,buttons:[],classes:{"ui-dialog":"ui-corner-all","ui-dialog-titlebar":"ui-corner-all"},closeOnEscape:!0,closeText:"Close",draggable:!0,hide:null,height:"auto",maxHeight:null,maxWidth:null,minHeight:150,minWidth:150,modal:!1,position:{my:"center",at:"center",of:window,collision:"fit",using:function(e){var i=t(this).css(e).offset().top;i<0&&t(this).css("top",e.top-i)}},resizable:!0,show:null,title:null,uiDialogTitleHeadingLevel:0,width:300,beforeClose:null,close:null,drag:null,dragStart:null,dragStop:null,focus:null,open:null,resize:null,resizeStart:null,resizeStop:null},sizeRelatedOptions:{buttons:!0,height:!0,maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0,width:!0},resizableRelatedOptions:{maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0},_create:function(){this.originalCss={display:this.element[0].style.display,width:this.element[0].style.width,minHeight:this.element[0].style.minHeight,maxHeight:this.element[0].style.maxHeight,height:this.element[0].style.height},this.originalPosition={parent:this.element.parent(),index:this.element.parent().children().index(this.element)},this.originalTitle=this.element.attr("title"),null==this.options.title&&null!=this.originalTitle&&(this.options.title=this.originalTitle),this.options.disabled&&(this.options.disabled=!1),this._createWrapper(),this.element.show().removeAttr("title").appendTo(this.uiDialog),this._addClass("ui-dialog-content","ui-widget-content"),this._createTitlebar(),this._createButtonPane(),this.options.draggable&&t.fn.draggable&&this._makeDraggable(),this.options.resizable&&t.fn.resizable&&this._makeResizable(),this._isOpen=!1,this._trackFocus()},_init:function(){this.options.autoOpen&&this.open()},_appendTo:function(){var e=this.options.appendTo;return e&&(e.jquery||e.nodeType)?t(e):this.document.find(e||"body").eq(0)},_destroy:function(){var t,e=this.originalPosition;this._untrackInstance(),this._destroyOverlay(),this.element.removeUniqueId().css(this.originalCss).detach(),this.uiDialog.remove(),this.originalTitle&&this.element.attr("title",this.originalTitle),(t=e.parent.children().eq(e.index)).length&&t[0]!==this.element[0]?t.before(this.element):e.parent.append(this.element)},widget:function(){return this.uiDialog},disable:t.noop,enable:t.noop,close:function(e){var i=this;this._isOpen&&!1!==this._trigger("beforeClose",e)&&(this._isOpen=!1,this._focusedElement=null,this._destroyOverlay(),this._untrackInstance(),this.opener.filter(":focusable").trigger("focus").length||t(this.document[0].activeElement).trigger("blur"),this._hide(this.uiDialog,this.options.hide,function(){i._trigger("close",e)}))},isOpen:function(){return this._isOpen},moveToTop:function(){this._moveToTop()},_moveToTop:function(e,i){var s=!1,n=this.uiDialog.siblings(".ui-front:visible").map(function(){return+t(this).css("z-index")}).get(),o=Math.max.apply(null,n);return o>=+this.uiDialog.css("z-index")&&(this.uiDialog.css("z-index",o+1),s=!0),s&&!i&&this._trigger("focus",e),s},open:function(){var e=this;if(this._isOpen){this._moveToTop()&&this._focusTabbable();return}this._isOpen=!0,this.opener=t(this.document[0].activeElement),this._size(),this._position(),this._createOverlay(),this._moveToTop(null,!0),this.overlay&&this.overlay.css("z-index",this.uiDialog.css("z-index")-1),this._show(this.uiDialog,this.options.show,function(){e._focusTabbable(),e._trigger("focus")}),this._makeFocusTarget(),this._trigger("open")},_focusTabbable:function(){var t=this._focusedElement;t||(t=this.element.find("[autofocus]")),t.length||(t=this.element.find(":tabbable")),t.length||(t=this.uiDialogButtonPane.find(":tabbable")),t.length||(t=this.uiDialogTitlebarClose.filter(":tabbable")),t.length||(t=this.uiDialog),t.eq(0).trigger("focus")},_restoreTabbableFocus:function(){var e=this.document[0].activeElement;this.uiDialog[0]===e||t.contains(this.uiDialog[0],e)||this._focusTabbable()},_keepFocus:function(t){t.preventDefault(),this._restoreTabbableFocus()},_createWrapper:function(){this.uiDialog=t("<div>").hide().attr({tabIndex:-1,role:"dialog","aria-modal":this.options.modal?"true":null}).appendTo(this._appendTo()),this._addClass(this.uiDialog,"ui-dialog","ui-widget ui-widget-content ui-front"),this._on(this.uiDialog,{keydown:function(e){if(this.options.closeOnEscape&&!e.isDefaultPrevented()&&e.keyCode&&e.keyCode===t.ui.keyCode.ESCAPE){e.preventDefault(),this.close(e);return}if(!(e.keyCode!==t.ui.keyCode.TAB||e.isDefaultPrevented())){var i=this.uiDialog.find(":tabbable"),s=i.first(),n=i.last();e.target!==n[0]&&e.target!==this.uiDialog[0]||e.shiftKey?(e.target===s[0]||e.target===this.uiDialog[0])&&e.shiftKey&&(this._delay(function(){n.trigger("focus")}),e.preventDefault()):(this._delay(function(){s.trigger("focus")}),e.preventDefault())}},mousedown:function(t){this._moveToTop(t)&&this._focusTabbable()}}),this.element.find("[aria-describedby]").length||this.uiDialog.attr({"aria-describedby":this.element.uniqueId().attr("id")})},_createTitlebar:function(){var e;this.uiDialogTitlebar=t("<div>"),this._addClass(this.uiDialogTitlebar,"ui-dialog-titlebar","ui-widget-header ui-helper-clearfix"),this._on(this.uiDialogTitlebar,{mousedown:function(e){t(e.target).closest(".ui-dialog-titlebar-close")||this.uiDialog.trigger("focus")}}),this.uiDialogTitlebarClose=t("<button type='button'></button>").button({label:t("<a>").text(this.options.closeText).html(),icon:"ui-icon-closethick",showLabel:!1}).appendTo(this.uiDialogTitlebar),this._addClass(this.uiDialogTitlebarClose,"ui-dialog-titlebar-close"),this._on(this.uiDialogTitlebarClose,{click:function(t){t.preventDefault(),this.close(t)}}),e=t("<"+(Number.isInteger(this.options.uiDialogTitleHeadingLevel)&&this.options.uiDialogTitleHeadingLevel>0&&this.options.uiDialogTitleHeadingLevel<=6?"h"+this.options.uiDialogTitleHeadingLevel:"span")+">").uniqueId().prependTo(this.uiDialogTitlebar),this._addClass(e,"ui-dialog-title"),this._title(e),this.uiDialogTitlebar.prepe
vendor: 28,777 bytes, line 12426
12426ndTo(this.uiDialog),this.uiDialog.attr({"aria-labelledby":e.attr("id")})},_title:function(t){this.options.title?t.text(this.options.title):t.html("&#160;")},_createButtonPane:function(){this.uiDialogButtonPane=t("<div>"),this._addClass(this.uiDialogButtonPane,"ui-dialog-buttonpane","ui-widget-content ui-helper-clearfix"),this.uiButtonSet=t("<div>").appendTo(this.uiDialogButtonPane),this._addClass(this.uiButtonSet,"ui-dialog-buttonset"),this._createButtons()},_createButtons:function(){var e=this,i=this.options.buttons;if(this.uiDialogButtonPane.remove(),this.uiButtonSet.empty(),t.isEmptyObject(i)||Array.isArray(i)&&!i.length){this._removeClass(this.uiDialog,"ui-dialog-buttons");return}t.each(i,function(i,s){var n,o;s="function"==typeof s?{click:s,text:i}:s,n=(s=t.extend({type:"button"},s)).click,o={icon:s.icon,iconPosition:s.iconPosition,showLabel:s.showLabel,icons:s.icons,text:s.text},delete s.click,delete s.icon,delete s.iconPosition,delete s.showLabel,delete s.icons,"boolean"==typeof s.text&&delete s.text,t("<button></button>",s).button(o).appendTo(e.uiButtonSet).on("click",function(){n.apply(e.element[0],arguments)})}),this._addClass(this.uiDialog,"ui-dialog-buttons"),this.uiDialogButtonPane.appendTo(this.uiDialog)},_makeDraggable:function(){var e=this,i=this.options;function s(t){return{position:t.position,offset:t.offset}}this.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(i,n){e._addClass(t(this),"ui-dialog-dragging"),e._blockFrames(),e._trigger("dragStart",i,s(n))},drag:function(t,i){e._trigger("drag",t,s(i))},stop:function(n,o){var a=o.offset.left-e.document.scrollLeft(),r=o.offset.top-e.document.scrollTop();i.position={my:"left top",at:"left"+(a>=0?"+":"")+a+" top"+(r>=0?"+":"")+r,of:e.window},e._removeClass(t(this),"ui-dialog-dragging"),e._unblockFrames(),e._trigger("dragStop",n,s(o))}})},_makeResizable:function(){var e=this,i=this.options,s=i.resizable,n=this.uiDialog.css("position");function o(t){return{originalPosition:t.originalPosition,originalSize:t.originalSize,position:t.position,size:t.size}}this.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:this.element,maxWidth:i.maxWidth,maxHeight:i.maxHeight,minWidth:i.minWidth,minHeight:this._minHeight(),handles:"string"==typeof s?s:"n,e,s,w,se,sw,ne,nw",start:function(i,s){e._addClass(t(this),"ui-dialog-resizing"),e._blockFrames(),e._trigger("resizeStart",i,o(s))},resize:function(t,i){e._trigger("resize",t,o(i))},stop:function(s,n){var a=e.uiDialog.offset(),r=a.left-e.document.scrollLeft(),l=a.top-e.document.scrollTop();i.height=e.uiDialog.height(),i.width=e.uiDialog.width(),i.position={my:"left top",at:"left"+(r>=0?"+":"")+r+" top"+(l>=0?"+":"")+l,of:e.window},e._removeClass(t(this),"ui-dialog-resizing"),e._unblockFrames(),e._trigger("resizeStop",s,o(n))}}).css("position",n)},_trackFocus:function(){this._on(this.widget(),{focusin:function(e){this._makeFocusTarget(),this._focusedElement=t(e.target)}})},_makeFocusTarget:function(){this._untrackInstance(),this._trackingInstances().unshift(this)},_untrackInstance:function(){var e=this._trackingInstances(),i=t.inArray(this,e);-1!==i&&e.splice(i,1)},_trackingInstances:function(){var t=this.document.data("ui-dialog-instances");return t||(t=[],this.document.data("ui-dialog-instances",t)),t},_minHeight:function(){var t=this.options;return"auto"===t.height?t.minHeight:Math.min(t.minHeight,t.height)},_position:function(){var t=this.uiDialog.is(":visible");t||this.uiDialog.show(),this.uiDialog.position(this.options.position),t||this.uiDialog.hide()},_setOptions:function(e){var i=this,s=!1,n={};t.each(e,function(t,e){i._setOption(t,e),t in i.sizeRelatedOptions&&(s=!0),t in i.resizableRelatedOptions&&(n[t]=e)}),s&&(this._size(),this._position()),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option",n)},_setOption:function(e,i){var s,n,o=this.uiDialog;"disabled"!==e&&(this._super(e,i),"appendTo"===e&&this.uiDialog.appendTo(this._appendTo()),"buttons"===e&&this._createButtons(),"closeText"===e&&this.uiDialogTitlebarClose.button({label:t("<a>").text(""+this.options.closeText).html()}),"draggable"===e&&((s=o.is(":data(ui-draggable)"))&&!i&&o.draggable("destroy"),!s&&i&&this._makeDraggable()),"position"===e&&this._position(),"resizable"!==e||((n=o.is(":data(ui-resizable)"))&&!i&&o.resizable("destroy"),n&&"string"==typeof i&&o.resizable("option","handles",i),n||!1===i||this._makeResizable()),"title"===e&&this._title(this.uiDialogTitlebar.find(".ui-dialog-title")),"modal"===e&&o.attr("aria-modal",i?"true":null))},_size:function(){var t,e,i,s=this.options;this.element.show().css({width:"auto",minHeight:0,maxHeight:"none",height:0}),s.minWidth>s.width&&(s.width=s.minWidth),t=this.uiDialog.css({height:"auto",width:s.width}).outerHeight(),e=Math.max(0,s.minHeight-t),i="number"==typeof s.maxHeight?Math.max(0,s.maxHeight-t):"none","auto"===s.height?this.element.css({minHeight:e,maxHeight:i,height:"auto"}):this.element.height(Math.max(0,s.height-t)),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option","minHeight",this._minHeight())},_blockFrames:function(){this.iframeBlocks=this.document.find("iframe").map(function(){var e=t(this);return t("<div>").css({position:"absolute",width:e.outerWidth(),height:e.outerHeight()}).appendTo(e.parent()).offset(e.offset())[0]})},_unblockFrames:function(){this.iframeBlocks&&(this.iframeBlocks.remove(),delete this.iframeBlocks)},_allowInteraction:function(e){return!!t(e.target).closest(".ui-dialog").length||!!t(e.target).closest(".ui-datepicker").length},_createOverlay:function(){if(this.options.modal){var e=!0;this._delay(function(){e=!1}),this.document.data("ui-dialog-overlays")||this.document.on("focusin.ui-dialog",(function(t){if(!e){var i=this._trackingInstances()[0];i._allowInteraction(t)||(t.preventDefault(),i._focusTabbable())}}).bind(this)),this.overlay=t("<div>").appendTo(this._appendTo()),this._addClass(this.overlay,null,"ui-widget-overlay ui-front"),this._on(this.overlay,{mousedown:"_keepFocus"}),this.document.data("ui-dialog-overlays",(this.document.data("ui-dialog-overlays")||0)+1)}},_destroyOverlay:function(){if(this.options.modal&&this.overlay){var t=this.document.data("ui-dialog-overlays")-1;t?this.document.data("ui-dialog-overlays",t):(this.document.off("focusin.ui-dialog"),this.document.removeData("ui-dialog-overlays")),this.overlay.remove(),this.overlay=null}}}),!0===t.uiBackCompat&&t.widget("ui.dialog",t.ui.dialog,{options:{dialogClass:""},_createWrapper:function(){this._super(),this.uiDialog.addClass(this.options.dialogClass)},_setOption:function(t,e){"dialogClass"===t&&this.uiDialog.removeClass(this.options.dialogClass).addClass(e),this._superApply(arguments)}}),t.ui.dialog,t.widget("ui.droppable",{version:"1.14.2",widgetEventPrefix:"drop",options:{accept:"*",addClasses:!0,greedy:!1,scope:"default",tolerance:"intersect",activate:null,deactivate:null,drop:null,out:null,over:null},_create:function(){var t,e=this.options,i=e.accept;this.isover=!1,this.isout=!0,this.accept="function"==typeof i?i:function(t){return t.is(i)},this.proportions=function(){if(!arguments.length)return t||(t={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight});t=arguments[0]},this._addToManager(e.scope),e.addClasses&&this._addClass("ui-droppable")},_addToManager:function(e){t.ui.ddmanager.droppables[e]=t.ui.ddmanager.droppables[e]||[],t.ui.ddmanager.droppables[e].push(this)},_splice:function(t){for(var e=0;e<t.length;e++)t[e]===this&&t.splice(e,1)},_destroy:function(){var e=t.ui.ddmanager.droppables[this.options.scope];this._splice(e)},_setOption:function(e,i){if("accept"===e)this.accept="function"==typeof i?i:function(t){return t.is(i)};else if("scope"===e){var s=t.ui.ddmanager.droppables[this.options.scope];this._splice(s),this._addToManager(i)}this._super(e,i)},_activate:function(e){var i=t.ui.ddmanager.current;this._addActiveClass(),i&&this._trigger("activate",e,this.ui(i))},_deactivate:function(e){var i=t.ui.ddmanager.current;this._removeActiveClass(),i&&this._trigger("deactivate",e,this.ui(i))},_over:function(e){var i=t.ui.ddmanager.current;i&&(i.currentItem||i.element)[0]!==this.element[0]&&this.accept.call(this.element[0],i.currentItem||i.element)&&(this._addHoverClass(),this._trigger("over",e,this.ui(i)))},_out:function(e){var i=t.ui.ddmanager.current;i&&(i.currentItem||i.element)[0]!==this.element[0]&&this.accept.call(this.element[0],i.currentItem||i.element)&&(this._removeHoverClass(),this._trigger("out",e,this.ui(i)))},_drop:function(e,i){var s=i||t.ui.ddmanager.current,n=!1;return!!s&&(s.currentItem||s.element)[0]!==this.element[0]&&(this.element.find(":data(ui-droppable)").not(".ui-draggable-dragging").each(function(){var i=t(this).droppable("instance");if(i.options.greedy&&!i.options.disabled&&i.options.scope===s.options.scope&&i.accept.call(i.element[0],s.currentItem||s.element)&&t.ui.intersect(s,t.extend(i,{offset:i.element.offset()}),i.options.tolerance,e))return n=!0,!1}),!n&&!!this.accept.call(this.element[0],s.currentItem||s.element)&&(this._removeActiveClass(),this._removeHoverClass(),this._trigger("drop",e,this.ui(s)),this.element))},ui:function(t){return{draggable:t.currentItem||t.element,helper:t.helper,position:t.position,offset:t.positionAbs}},_addHoverClass:function(){this._addClass("ui-droppable-hover")},_removeHoverClass:function(){this._removeClass("ui-droppable-hover")},_addActiveClass:function(){this._addClass("ui-droppable-active")},_removeActiveClass:function(){this._removeClass("ui-droppable-active")}}),t.ui.intersect=function(t,e,i,s){if(!e.offset)return!1;var n,o,a,r,l=(t.positionAbs||t.position.absolute).left+t.margins.left,h=(t.positionAbs||t.position.absolute).top+t.margins.top,c=l+t.helperProportions.width,u=h+t.helperProportions.height,d=e.offset.left,p=e.offset.top,f=d+e.proportions().width,g=p+e.proportions().height;switch(i){case"fit":return d<=l&&c<=f&&p<=h&&u<=g;case"intersect":return d<l+t.helperProportions.width/2&&c-t.helperProportions.width/2<f&&p<h+t.helperProportions.height/2&&u-t.helperProportions.height/2<g;case"pointer":return n=s.pageY,o=e.proportions().height,n>=p&&n<p+o&&(a=s.pageX,r=e.proportions().width,a>=d&&a<d+r);case"touch":return(h>=p&&h<=g||u>=p&&u<=g||h<p&&u>g)&&(l>=d&&l<=f||c>=d&&c<=f||l<d&&c>f);default:return!1}},t.ui.ddmanager={current:null,droppables:{default:[]},prepareOffsets:function(e,i){var s,n,o=t.ui.ddmanager.droppables[e.options.scope]||[],a=i?i.type:null,r=(e.currentItem||e.element).find(":data(ui-droppable)").addBack();t:for(s=0;s<o.length;s++){if(!o[s].options.disabled&&(!e||o[s].accept.call(o[s].element[0],e.currentItem||e.element))){for(n=0;n<r.length;n++)if(r[n]===o[s].element[0]){o[s].proportions().height=0;continue t}o[s].visible="none"!==o[s].element.css("display"),o[s].visible&&("mousedown"===a&&o[s]._activate.call(o[s],i),o[s].offset=o[s].element.offset(),o[s].proportions({width:o[s].element[0].offsetWidth,height:o[s].element[0].offsetHeight}))}}},drop:function(e,i){var s=!1;return t.each((t.ui.ddmanager.droppables[e.options.scope]||[]).slice(),function(){this.options&&(!this.options.disabled&&this.visible&&t.ui.intersect(e,this,this.options.tolerance,i)&&(s=this._drop.call(this,i)||s),!this.options.disabled&&this.visible&&this.accept.call(this.element[0],e.currentItem||e.element)&&(this.isout=!0,this.isover=!1,this._deactivate.call(this,i)))}),s},dragStart:function(e,i){e.element.parentsUntil("body").on("scroll.droppable",function(){e.options.refreshPositions||t.ui.ddmanager.prepareOffsets(e,i)})},drag:function(e,i){e.options.refreshPositions&&t.ui.ddmanager.prepareOffsets(e,i),t.each(t.ui.ddmanager.droppables[e.options.scope]||[],function(){if(!this.options.disabled&&!this.greedyChild&&this.visible){var s,n,o,a=t.ui.intersect(e,this,this.options.tolerance,i),r=!a&&this.isover?"isout":a&&!this.isover?"isover":null;r&&(this.options.greedy&&(n=this.options.scope,(o=this.element.parents(":data(ui-droppable)").filter(function(){return t(this).droppable("instance").options.scope===n})).length&&((s=t(o[0]).droppable("instance")).greedyChild="isover"===r)),s&&"isover"===r&&(s.isover=!1,s.isout=!0,s._out.call(s,i)),this[r]=!0,this["isout"===r?"isover":"isout"]=!1,this["isover"===r?"_over":"_out"].call(this,i),s&&"isout"===r&&(s.isout=!1,s.isover=!0,s._over.call(s,i)))}})},dragStop:function(e,i){e.element.parentsUntil("body").off("scroll.droppable"),e.options.refreshPositions||t.ui.ddmanager.prepareOffsets(e,i)}},!0===t.uiBackCompat&&t.widget("ui.droppable",t.ui.droppable,{options:{hoverClass:!1,activeClass:!1},_addActiveClass:function(){this._super(),this.options.activeClass&&this.element.addClass(this.options.activeClass)},_removeActiveClass:function(){this._super(),this.options.activeClass&&this.element.removeClass(this.options.activeClass)},_addHoverClass:function(){this._super(),this.options.hoverClass&&this.element.addClass(this.options.hoverClass)},_removeHoverClass:function(){this._super(),this.options.hoverClass&&this.element.removeClass(this.options.hoverClass)}}),t.ui.droppable,t.widget("ui.progressbar",{version:"1.14.2",options:{classes:{"ui-progressbar":"ui-corner-all","ui-progressbar-value":"ui-corner-left","ui-progressbar-complete":"ui-corner-right"},max:100,value:0,change:null,complete:null},min:0,_create:function(){this.oldValue=this.options.value=this._constrainedValue(),this.element.attr({role:"progressbar","aria-valuemin":this.min}),this._addClass("ui-progressbar","ui-widget ui-widget-content"),this.valueDiv=t("<div>").appendTo(this.element),this._addClass(this.valueDiv,"ui-progressbar-value","ui-widget-header"),this._refreshValue()},_destroy:function(){this.element.removeAttr("role aria-valuemin aria-valuemax aria-valuenow"),this.valueDiv.remove()},value:function(t){if(void 0===t)return this.options.value;this.options.value=this._constrainedValue(t),this._refreshValue()},_constrainedValue:function(t){return void 0===t&&(t=this.options.value),this.indeterminate=!1===t,"number"!=typeof t&&(t=0),!this.indeterminate&&Math.min(this.options.max,Math.max(this.min,t))},_setOptions:function(t){var e=t.value;delete t.value,this._super(t),this.options.value=this._constrainedValue(e),this._refreshValue()},_setOption:function(t,e){"max"===t&&(e=Math.max(this.min,e)),this._super(t,e)},_setOptionDisabled:function(t){this._super(t),this.element.attr("aria-disabled",t),this._toggleClass(null,"ui-state-disabled",!!t)},_percentage:function(){return this.indeterminate?100:100*(this.options.value-this.min)/(this.options.max-this.min)},_refreshValue:function(){var e=this.options.value,i=this._percentage();this.valueDiv.toggle(this.indeterminate||e>this.min).width(i.toFixed(0)+"%"),this._toggleClass(this.valueDiv,"ui-progressbar-complete",null,e===this.options.max)._toggleClass("ui-progressbar-indeterminate",null,this.indeterminate),this.indeterminate?(this.element.removeAttr("aria-valuenow"),this.overlayDiv||(this.overlayDiv=t("<div>").appendTo(this.valueDiv),this._addClass(this.overlayDiv,"ui-progressbar-overlay"))):(this.element.attr({"aria-valuemax":this.options.max,"aria-valuenow":e}),this.overlayDiv&&(this.overlayDiv.remove(),this.overlayDiv=null)),this.oldValue!==e&&(this.oldValue=e,this._trigger("change")),e===this.options.max&&this._trigger("complete")}}),t.widget("ui.selectable",t.ui.mouse,{version:"1.14.2",options:{appendTo:"body",autoRefresh:!0,distance:0,filter:"*",tolerance:"touch",selected:null,selecting:null,start:null,stop:null,unselected:null,unselecting:null},_create:function(){var e=this;this._addClass("ui-selectable"),this.dragged=!1,this.refresh=function(){e.elementPos=t(e.element[0]).offset(),e.selectees=t(e.options.filter,e.element[0]),e._addClass(e.selectees,"ui-selectee"),e.selectees.each(function(){var i=t(this),s=i.offset(),n={left:s.left-e.elementPos.left,top:s.top-e.elementPos.top};t.data(this,"selectable-item",{element:this,$element:i,left:n.left,top:n.top,right:n.left+i.outerWidth(),bottom:n.top+i.outerHeight(),startselected:!1,selected:i.hasClass("ui-selected"),selecting:i.hasClass("ui-selecting"),unselecting:i.hasClass("ui-unselecting")})})},this.refresh(),this._mouseInit(),this.helper=t("<div>"),this._addClass(this.helper,"ui-selectable-helper")},_destroy:function(){this.selectees.removeData("selectable-item"),this._mouseDestroy()},_mouseStart:function(e){var i=this,s=this.options;this.opos=[e.pageX,e.pageY],this.elementPos=t(this.element[0]).offset(),!this.options.disabled&&(this.selectees=t(s.filter,this.element[0]),this._trigger("start",e),t(s.appendTo).append(this.helper),this.helper.css({left:e.pageX,top:e.pageY,width:0,height:0}),s.autoRefresh&&this.refresh(),this.selectees.filter(".ui-selected").each(function(){var s=t.data(this,"selectable-item");s.startselected=!0,e.metaKey||e.ctrlKey||(i._removeClass(s.$element,"ui-selected"),s.selected=!1,i._addClass(s.$element,"ui-unselecting"),s.unselecting=!0,i._trigger("unselecting",e,{unselecting:s.element}))}),t(e.target).parents().addBack().each(function(){var s,n=t.data(this,"selectable-item");if(n)return s=!e.metaKey&&!e.ctrlKey||!n.$element.hasClass("ui-selected"),i._removeClass(n.$element,s?"ui-unselecting":"ui-selected")._addClass(n.$element,s?"ui-selecting":"ui-unselecting"),n.unselecting=!s,n.selecting=s,n.selected=s,s?i._trigger("selecting",e,{selecting:n.element}):i._trigger("unselecting",e,{unselecting:n.element}),!1}))},_mouseDrag:function(e){if(this.dragged=!0,!this.options.disabled){var i,s=this,n=this.options,o=this.opos[0],a=this.opos[1],r=e.pageX,l=e.pageY;return o>r&&(i=r,r=o,o=i),a>l&&(i=l,l=a,a=i),this.helper.css({left:o,top:a,width:r-o,height:l-a}),this.selectees.each(function(){var i=t.data(this,"selectable-item"),h=!1,c={};i&&i.element!==s.element[0]&&(c.left=i.left+s.elementPos.left,c.right=i.right+s.elementPos.left,c.top=i.top+s.elementPos.top,c.bottom=i.bottom+s.elementPos.top,"touch"===n.tolerance?h=!(c.left>r||c.right<o||c.top>l||c.bottom<a):"fit"===n.tolerance&&(h=c.left>o&&c.right<r&&c.top>a&&c.bottom<l),h?(i.selected&&(s._removeClass(i.$element,"ui-selected"),i.selected=!1),i.unselecting&&(s._removeClass(i.$element,"ui-unselecting"),i.unselecting=!1),i.selecting||(s._addClass(i.$element,"ui-selecting"),i.selecting=!0,s._trigger("selecting",e,{selecting:i.element}))):(i.selecting&&((e.metaKey||e.ctrlKey)&&i.startselected?(s._removeClass(i.$element,"ui-selecting"),i.selecting=!1,s._addClass(i.$element,"ui-selected"),i.selected=!0):(s._removeClass(i.$element,"ui-selecting"),i.selecting=!1,i.startselected&&(s._addClass(i.$element,"ui-unselecting"),i.unselecting=!0),s._trigger("unselecting",e,{unselecting:i.element}))),!i.selected||e.metaKey||e.ctrlKey||i.startselected||(s._removeClass(i.$element,"ui-selected"),i.selected=!1,s._addClass(i.$element,"ui-unselecting"),i.unselecting=!0,s._trigger("unselecting",e,{unselecting:i.element}))))}),!1}},_mouseStop:function(e){var i=this;return this.dragged=!1,t(".ui-unselecting",this.element[0]).each(function(){var s=t.data(this,"selectable-item");i._removeClass(s.$element,"ui-unselecting"),s.unselecting=!1,s.startselected=!1,i._trigger("unselected",e,{unselected:s.element})}),t(".ui-selecting",this.element[0]).each(function(){var s=t.data(this,"selectable-item");i._removeClass(s.$element,"ui-selecting")._addClass(s.$element,"ui-selected"),s.selecting=!1,s.selected=!0,s.startselected=!0,i._trigger("selected",e,{selected:s.element})}),this._trigger("stop",e),this.helper.remove(),!1}}),t.widget("ui.selectmenu",[t.ui.formResetMixin,{version:"1.14.2",defaultElement:"<select>",options:{appendTo:null,classes:{"ui-selectmenu-button-open":"ui-corner-top","ui-selectmenu-button-closed":"ui-corner-all"},disabled:null,icons:{button:"ui-icon-triangle-1-s"},position:{my:"left top",at:"left bottom",collision:"none"},width:!1,change:null,close:null,focus:null,open:null,select:null},_create:function(){var e=this.element.uniqueId().attr("id");this.ids={element:e,button:e+"-button",menu:e+"-menu"},this._drawButton(),this._drawMenu(),this._bindFormResetHandler(),this._rendered=!1,this.menuItems=t()},_drawButton:function(){var e,i=this,s=this._parseOption(this.element.find("option:selected"),this.element[0].selectedIndex);this.labels=this.element.labels().attr("for",this.ids.button),this._on(this.labels,{click:function(t){this.button.trigger("focus"),t.preventDefault()}}),this.element.hide(),this.button=t("<span>",{tabindex:this.options.disabled?-1:0,id:this.ids.button,role:"combobox","aria-expanded":"false","aria-autocomplete":"list","aria-owns":this.ids.menu,"aria-haspopup":"true",title:this.element.attr("title")}).insertAfter(this.element),this._addClass(this.button,"ui-selectmenu-button ui-selectmenu-button-closed","ui-button ui-widget"),e=t("<span>").appendTo(this.button),this._addClass(e,"ui-selectmenu-icon","ui-icon "+this.options.icons.button),this.buttonItem=this._renderButtonItem(s).appendTo(this.button),!1!==this.options.width&&this._resizeButton(),this._on(this.button,this._buttonEvents),this.button.one("focusin",function(){i._rendered||i._refreshMenu()})},_drawMenu:function(){var e=this;this.menu=t("<ul>",{"aria-hidden":"true","aria-labelledby":this.ids.button,id:this.ids.menu}),this.menuWrap=t("<div>").append(this.menu),this._addClass(this.menuWrap,"ui-selectmenu-menu","ui-front"),this.menuWrap.appendTo(this._appendTo()),this.menuInstance=this.menu.menu({classes:{"ui-menu":"ui-corner-bottom"},role:"listbox",select:function(t,i){t.preventDefault(),e._select(i.item.data("ui-selectmenu-item"),t)},focus:function(t,i){var s=i.item.data("ui-selectmenu-item");null==e.focusIndex||s.index===e.focusIndex||(e._trigger("focus",t,{item:s}),e.isOpen||e._select(s,t)),e.focusIndex=s.index,e.button.attr("aria-activedescendant",e.menuItems.eq(s.index).attr("id"))}}).menu("instance"),this.menuInstance._off(this.menu,"mouseleave"),this.menuInstance._closeOnDocumentClick=function(){return!1},this.menuInstance._isDivider=function(){return!1}},refresh:function(){this._refreshMenu(),this.buttonItem.replaceWith(this.buttonItem=this._renderButtonItem(this._getSelectedItem().data("ui-selectmenu-item")||{})),null===this.options.width&&this._resizeButton()},_refreshMenu:function(){var t,e=this.element.find("option");this.menu.empty(),this._parseOptions(e),this._renderMenu(this.menu,this.items),this.menuInstance.refresh(),this.menuItems=this.menu.find("li").not(".ui-selectmenu-optgroup").find(".ui-menu-item-wrapper"),this._rendered=!0,e.length&&(t=this._getSelectedItem(),this.menuInstance.focus(null,t),this._setAria(t.data("ui-selectmenu-item")),this._setOption("disabled",this.element.prop("disabled")))},open:function(t){if(!this.options.disabled)this._rendered?(this._removeClass(this.menu.find(".ui-state-active"),null,"ui-state-active"),this.menuInstance.focus(null,this._getSelectedItem())):this._refreshMenu(),this.menuItems.length&&(this.isOpen=!0,this._toggleAttr(),this._resizeMenu(),this._position(),this._on(this.document,this._documentClick),this._trigger("open",t))},_position:function(){this.menuWrap.position(t.extend({of:this.button},this.options.position))},close:function(t){this.isOpen&&(this.isOpen=!1,this._toggleAttr(),this.range=null,this._off(this.document),this._trigger("close",t))},widget:function(){return this.button},menuWidget:function(){return this.menu},_renderButtonItem:function(e){var i=t("<span>");return this._setText(i,e.label),this._addClass(i,"ui-selectmenu-text"),i},_renderMenu:function(e,i){var s=this,n="";t.each(i,function(i,o){var a;o.optgroup!==n&&(a=t("<li>",{text:o.optgroup}),s._addClass(a,"ui-selectmenu-optgroup","ui-menu-divider"+(o.element.parent("optgroup").prop("disabled")?" ui-state-disabled":"")),a.appendTo(e),n=o.optgroup),s._renderItemData(e,o)})},_renderItemData:function(t,e){return this._renderItem(t,e).data("ui-selectmenu-item",e)},_renderItem:function(e,i){var s=t("<li>"),n=t("<div>",{title:i.element.attr("title")});return i.disabled&&this._addClass(s,null,"ui-state-disabled"),i.hidden?s.prop("hidden",!0):this._setText(n,i.label),s.append(n).appendTo(e)},_setText:function(t,e){e?t.text(e):t.html("&#160;")},_move:function(t,e){var i,s,n=".ui-menu-item";this.isOpen?i=this.menuItems.eq(this.focusIndex).parent("li"):(i=this.menuItems.eq(this.element[0].selectedIndex).parent("li"),n+=":not(.ui-state-disabled)"),(s="first"===t||"last"===t?i["first"===t?"prevAll":"nextAll"](n).eq(-1):i[t+"All"](n).eq(0)).length&&this.menuInstance.focus(e,s)},_getSelectedItem:function(){return this.menuItems.eq(this.element[0].selectedIndex).parent("li")},_toggle:function(t){this[this.isOpen?"close":"open"](t)},_setSelection:function(){var t;this.range&&((t=window.getSelection()).removeAllRanges(),t.addRange(this.range))},_documentClick:{mousedown:function(e){this.isOpen&&(t(e.target).closest(".ui-selectmenu-menu, #"+CSS.escape(this.ids.button)).length||this.close(e))}},_buttonEvents:{mousedown:function(){var t=window.getSelection();t.rangeCount&&(this.range=t.getRangeAt(0))},click:function(t){this._setSelection(),this._toggle(t)},keydown:function(e){var i=!0;switch(e.keyCode){case t.ui.keyCode.TAB:case t.ui.keyCode.ESCAPE:this.close(e),i=!1;break;case t.ui.keyCode.ENTER:this.isOpen&&this._selectFocusedItem(e);break;case t.ui.keyCode.UP:e.altKey?this._toggle(e):this._move("prev",e);break;case t.ui.keyCode.DOWN:e.altKey?this._toggle(e):this._move("next",e);break;case t.ui.keyCode.SPACE:this.isOpen?this._selectFocusedItem(e):this._toggle(e);break;case t.ui.keyCode.LEFT:this._move("prev",e);break;case t.ui.keyCode.RIGHT:this._move("next",e);break;case t.ui.keyCode.HOME:case t.ui.keyCode.PAGE_UP:this._move("first",e);break;case t.ui.keyCode.END:case t.ui.keyCode.PAGE_DOWN:this._move("last",e);break;default:this.menu.trigger(e),i=!1}i&&e.preventDefault()}},_selectFocusedItem:function(t){var e=this.menuItems.eq(this.focusIndex).parent("li");e.hasClass("ui-state-disabled")||this._select(e.data("ui-selectmenu-item"),t)},_select:function(t,e){var i=this.element[0].selectedIndex;this.element[0].selectedIndex=t.index,this.buttonItem.replaceWith(this.buttonItem=this._renderButtonItem(t)),this._setAria(t),this._trigger("select",e,{item:t}),t.index!==i&&this._trigger("change",e,{item:t}),this.close(e)},_setAria:function(t){var e=this.menuItems.eq(t.index).attr("id");this.button.attr({"aria-labelledby":e,"aria-activedescendant":e}),this.menu.attr("aria-activedescendant",e)},_setOption:function(t,e){if("icons"===t){var i=this.button.find("span.ui-icon");this._removeClass(i,null,this.options.icons.button)._addClass(i,null,e.button)}this._super(t,e),"appendTo"===t&&this.menuWrap.appendTo(this._appendTo()),"width"===t&&this._resizeButton()},_setOptionDisabled:function(t){this._super(t),this.menuInstance.option("disabled",t),this.button.attr("aria-disabled",t),this._toggleClass(this.button,null,"ui-state-disabled",t),this.element.prop("disabled",t),t?(this.button.attr("tabindex",-1),this.close()):this.button.attr("tabindex",0)},_appendTo:function(){var e=this.options.appendTo;return e&&(e=e.jquery||e.nodeType?t(e):this.document.find(e).eq(0)),e&&e[0]||(e=this.element.closest(".ui-front, dialog")),e.length||(e=this.document[0].body),e},_toggleAttr:function(){this.button.attr("aria-expanded",this.isOpen),this._removeClass(this.button,"ui-selectmenu-button-"+(this.isOpen?"closed":"open"))._addClass(this.button,"ui-selectmenu-button-"+(this.isOpen?"open":"closed"))._toggleClass(this.menuWrap,"ui-selectmenu-open",null,this.isOpen),this.menu.attr("aria-hidden",!this.isOpen)},_resizeButton:function(){var t=this.options.width;if(!1===t){this.button.css("width","");return}null===t&&(t=this.element.show().outerWidth(),this.element.hide()),this.button.outerWidth(t)},_resizeMenu:function(){this.menu.outerWidth(Math.max(this.button.outerWidth(),this.menu.width("").outerWidth()))},_getCreateOptions:function(){var t=this._super();return t.disabled=this.element.prop("disabled"),t},_parseOptions:function(e){var i=this,s=[];e.each(function(e,n){s.push(i._parseOption(t(n),e))}),this.items=s},_parseOption:function(t,e){var i=t.parent("optgroup");return{element:t,index:e,value:t.val(),label:t.text(),hidden:i.prop("hidden")||t.prop("hidden"),optgroup:i.attr("label")||"",disabled:i.prop("disabled")||t.prop("disabled")}},_destroy:function(){this._unbindFormResetHandler(),this.menuWrap.remove(),this.button.remove(),this.element.show(),this.element.removeUniqueId(),this.labels.attr("for",this.ids.element)}}]),t.widget("ui.slider",t.ui.mouse,{version:"1.14.2",widgetEventPrefix:"slide",options:{animate:!1,classes:{"ui-slider":"ui-corner-all","ui-slider-handle":"ui-corner-all","ui-slider-range":"ui-corner-all ui-widget-header"},distance:0,max:100,min:0,orientation:"horizontal",range:!1,step:1,value:0,values:null,change:null,slide:null,start:null,stop:null}
vendor: 4,695 bytes, line 12426
12426,numPages:5,_create:function(){this._keySliding=!1,this._mouseSliding=!1,this._animateOff=!0,this._handleIndex=null,this._detectOrientation(),this._mouseInit(),this._calculateNewMax(),this._addClass("ui-slider ui-slider-"+this.orientation,"ui-widget ui-widget-content"),this._refresh(),this._animateOff=!1},_refresh:function(){this._createRange(),this._createHandles(),this._setupEvents(),this._refreshValue()},_createHandles:function(){var e,i,s=this.options,n=this.element.find(".ui-slider-handle"),o=[];for(i=s.values&&s.values.length||1,n.length>i&&(n.slice(i).remove(),n=n.slice(0,i)),e=n.length;e<i;e++)o.push("<span tabindex='0'></span>");this.handles=n.add(t(o.join("")).appendTo(this.element)),this._addClass(this.handles,"ui-slider-handle","ui-state-default"),this.handle=this.handles.eq(0),this.handles.each(function(e){t(this).data("ui-slider-handle-index",e).attr("tabIndex",0)})},_createRange:function(){var e=this.options;e.range?(!0===e.range&&(e.values?e.values.length&&2!==e.values.length?e.values=[e.values[0],e.values[0]]:Array.isArray(e.values)&&(e.values=e.values.slice(0)):e.values=[this._valueMin(),this._valueMin()]),this.range&&this.range.length?(this._removeClass(this.range,"ui-slider-range-min ui-slider-range-max"),this.range.css({left:"",bottom:""})):(this.range=t("<div>").appendTo(this.element),this._addClass(this.range,"ui-slider-range")),("min"===e.range||"max"===e.range)&&this._addClass(this.range,"ui-slider-range-"+e.range)):(this.range&&this.range.remove(),this.range=null)},_setupEvents:function(){this._off(this.handles),this._on(this.handles,this._handleEvents),this._hoverable(this.handles),this._focusable(this.handles)},_destroy:function(){this.handles.remove(),this.range&&this.range.remove(),this._mouseDestroy()},_mouseCapture:function(e){var i,s,n,o,a,r,l,h=this,c=this.options;return!c.disabled&&(this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()},this.elementOffset=this.element.offset(),i={x:e.pageX,y:e.pageY},s=this._normValueFromMouse(i),n=this._valueMax()-this._valueMin()+1,this.handles.each(function(e){var i=Math.abs(s-h.values(e));(n>i||n===i&&(e===h._lastChangedValue||h.values(e)===c.min))&&(n=i,o=t(this),a=e)}),!1!==this._start(e,a)&&(this._mouseSliding=!0,this._handleIndex=a,this._addClass(o,null,"ui-state-active"),o.trigger("focus"),r=o.offset(),l=!t(e.target).parents().addBack().is(".ui-slider-handle"),this._clickOffset=l?{left:0,top:0}:{left:e.pageX-r.left-o.width()/2,top:e.pageY-r.top-o.height()/2-(parseInt(o.css("borderTopWidth"),10)||0)-(parseInt(o.css("borderBottomWidth"),10)||0)+(parseInt(o.css("marginTop"),10)||0)},this.handles.hasClass("ui-state-hover")||this._slide(e,a,s),this._animateOff=!0,!0))},_mouseStart:function(){return!0},_mouseDrag:function(t){var e={x:t.pageX,y:t.pageY},i=this._normValueFromMouse(e);return this._slide(t,this._handleIndex,i),!1},_mouseStop:function(t){return this._removeClass(this.handles,null,"ui-state-active"),this._mouseSliding=!1,this._stop(t,this._handleIndex),this._change(t,this._handleIndex),this._handleIndex=null,this._clickOffset=null,this._animateOff=!1,!1},_detectOrientation:function(){this.orientation="vertical"===this.options.orientation?"vertical":"horizontal"},_normValueFromMouse:function(t){var e,i,s,n,o;return"horizontal"===this.orientation?(e=this.elementSize.width,i=t.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)):(e=this.elementSize.height,i=t.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)),(s=i/e)>1&&(s=1),s<0&&(s=0),"vertical"===this.orientation&&(s=1-s),n=this._valueMax()-this._valueMin(),o=this._valueMin()+s*n,this._trimAlignValue(o)},_uiHash:function(t,e,i){var s={handle:this.handles[t],handleIndex:t,value:void 0!==e?e:this.value()};return this._hasMultipleValues()&&(s.value=void 0!==e?e:this.values(t),s.values=i||this.values()),s},_hasMultipleValues:function(){return this.options.values&&this.options.values.length},_start:function(t,e){return this._trigger("start",t,this._uiHash(e))},_slide:function(t,e,i){var s,n=this.value(),o=this.values();this._hasMultipleValues()&&(s=this.values(+!e),n=this.values(e),2===this.options.values.length&&!0===this.options.range&&(i=0===e?Math.min(s,i):Math.max(s,i)),o[e]=i),i!==n&&!1!==this._trigger("slide",t,this._uiHash(e,i,o))&&(this._hasMultipleValues()?this.values(e,i):this.value(i))},_stop:function(t,e){this._trigger("stop",t,this._uiHash(e))},_change:function(t,e){this._keySliding||this._mouseSliding||(this._lastChangedValue=e,this._trigger("change",t,this._uiHash(e)))},value:function(t){if(arguments.length){this.options.value=this._trimAlignValue(t),this._refreshValue(),this._change(null,0);return}
vendor: 5,983 bytes, line 12426
12426return this._value()},values:function(t,e){var i,s,n;if(arguments.length>1){this.options.values[t]=this._trimAlignValue(e),this._refreshValue(),this._change(null,t);return}if(!arguments.length)return this._values();if(!Array.isArray(arguments[0]))return this._hasMultipleValues()?this._values(t):this.value();for(n=0,i=this.options.values,s=arguments[0];n<i.length;n+=1)i[n]=this._trimAlignValue(s[n]),this._change(null,n);this._refreshValue()},_setOption:function(t,e){var i,s=0;switch("range"===t&&!0===this.options.range&&("min"===e?(this.options.value=this._values(0),this.options.values=null):"max"===e&&(this.options.value=this._values(this.options.values.length-1),this.options.values=null)),Array.isArray(this.options.values)&&(s=this.options.values.length),this._super(t,e),t){case"orientation":this._detectOrientation(),this._removeClass("ui-slider-horizontal ui-slider-vertical")._addClass("ui-slider-"+this.orientation),this._refreshValue(),this.options.range&&this._refreshRange(e),this.handles.css("horizontal"===e?"bottom":"left","");break;case"value":this._animateOff=!0,this._refreshValue(),this._change(null,0),this._animateOff=!1;break;case"values":for(this._animateOff=!0,this._refreshValue(),i=s-1;i>=0;i--)this._change(null,i);this._animateOff=!1;break;case"step":case"min":case"max":this._animateOff=!0,this._calculateNewMax(),this._refreshValue(),this._animateOff=!1;break;case"range":this._animateOff=!0,this._refresh(),this._animateOff=!1}},_setOptionDisabled:function(t){this._super(t),this._toggleClass(null,"ui-state-disabled",!!t)},_value:function(){var t=this.options.value;return this._trimAlignValue(t)},_values:function(t){var e,i,s;if(arguments.length)return e=this.options.values[t],e=this._trimAlignValue(e);if(!this._hasMultipleValues())return[];for(s=0,i=this.options.values.slice();s<i.length;s+=1)i[s]=this._trimAlignValue(i[s]);return i},_trimAlignValue:function(t){if(t<=this._valueMin())return this._valueMin();if(t>=this._valueMax())return this._valueMax();var e=this.options.step>0?this.options.step:1,i=(t-this._valueMin())%e,s=t-i;return 2*Math.abs(i)>=e&&(s+=i>0?e:-e),parseFloat(s.toFixed(5))},_calculateNewMax:function(){var t=this.options.max,e=this._valueMin(),i=this.options.step;(t=Math.round((t-e)/i)*i+e)>this.options.max&&(t-=i),this.max=parseFloat(t.toFixed(this._precision()))},_precision:function(){var t=this._precisionOf(this.options.step);return null!==this.options.min&&(t=Math.max(t,this._precisionOf(this.options.min))),t},_precisionOf:function(t){var e=t.toString(),i=e.indexOf(".");return -1===i?0:e.length-i-1},_valueMin:function(){return this.options.min},_valueMax:function(){return this.max},_refreshRange:function(t){"vertical"===t&&this.range.css({width:"",left:""}),"horizontal"===t&&this.range.css({height:"",bottom:""})},_refreshValue:function(){var e,i,s,n,o,a=this.options.range,r=this.options,l=this,h=!this._animateOff&&r.animate,c={};this._hasMultipleValues()?this.handles.each(function(s){i=(l.values(s)-l._valueMin())/(l._valueMax()-l._valueMin())*100,c["horizontal"===l.orientation?"left":"bottom"]=i+"%",t(this).stop(1,1)[h?"animate":"css"](c,r.animate),!0===l.options.range&&("horizontal"===l.orientation?(0===s&&l.range.stop(1,1)[h?"animate":"css"]({left:i+"%"},r.animate),1===s&&l.range[h?"animate":"css"]({width:i-e+"%"},{queue:!1,duration:r.animate})):(0===s&&l.range.stop(1,1)[h?"animate":"css"]({bottom:i+"%"},r.animate),1===s&&l.range[h?"animate":"css"]({height:i-e+"%"},{queue:!1,duration:r.animate}))),e=i}):(s=this.value(),n=this._valueMin(),i=(o=this._valueMax())!==n?(s-n)/(o-n)*100:0,c["horizontal"===this.orientation?"left":"bottom"]=i+"%",this.handle.stop(1,1)[h?"animate":"css"](c,r.animate),"min"===a&&"horizontal"===this.orientation&&this.range.stop(1,1)[h?"animate":"css"]({width:i+"%"},r.animate),"max"===a&&"horizontal"===this.orientation&&this.range.stop(1,1)[h?"animate":"css"]({width:100-i+"%"},r.animate),"min"===a&&"vertical"===this.orientation&&this.range.stop(1,1)[h?"animate":"css"]({height:i+"%"},r.animate),"max"===a&&"vertical"===this.orientation&&this.range.stop(1,1)[h?"animate":"css"]({height:100-i+"%"},r.animate))},_handleEvents:{keydown:function(e){var i,s,n,o=t(e.target).data("ui-slider-handle-index");switch(e.keyCode){case t.ui.keyCode.HOME:case t.ui.keyCode.END:case t.ui.keyCode.PAGE_UP:case t.ui.keyCode.PAGE_DOWN:case t.ui.keyCode.UP:case t.ui.keyCode.RIGHT:case t.ui.keyCode.DOWN:case t.ui.keyCode.LEFT:if(e.preventDefault(),!this._keySliding&&(this._keySliding=!0,this._addClass(t(e.target),null,"ui-state-active"),!1===this._start(e,o)))return}switch(n=this.options.step,i=s=this._hasMultipleValues()?this.values(o):this.value(),e.keyCode){case t.ui.keyCode.HOME:s=this._valueMin();break;case t.ui.keyCode.END:s=this._valueMax();break;case t.ui.keyCode.PAGE_UP:s=this._trimAlignValue(i+(this._valueMax()-this._valueMin())/this.numPages);break;case t.ui.keyCode.PAGE_DOWN:s=this._trimAlignValue(i-(this._valueMax()-this._valueMin())/this.numPages);break;case t.ui.keyCode.UP:case t.ui.keyCode.RIGHT:if(i===this._valueMax())return;s=this._trimAlignValue(i+n);break;case t.ui.keyCode.DOWN:case t.ui.keyCode.LEFT:if(i===this._valueMin())return;s=this._trimAlignValue(i-n)}this._slide(e,o,s)},keyup:function(e){var i=t(e.target).data("ui-slider-handle-index");this._keySliding&&(this._keySliding=!1,this._stop(e,i),this._change(e,i),this._removeClass(t(e.target),null,"ui-state-active"))}}}),t.widget("ui.sortable",t.ui.mouse,{version:"1.14.2",widgetEventPrefix:"sort",ready:!1,options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"> *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3,activate:null,beforeStop:null,change:null,deactivate:null,out:null,over:null,receive:null,remove:null,sort:null,start:null,stop:null,update:null}
vendor: 9,954 bytes, line 12426
12426,_isOverAxis:function(t,e,i){return t>=e&&t<e+i},_isFloating:function(t){return/left|right/.test(t.css("float"))||/inline|table-cell/.test(t.css("display"))},_create:function(){this.containerCache={},this._addClass("ui-sortable"),this.refresh(),this.offset=this.element.offset(),this._mouseInit(),this._setHandleClassName(),this.ready=!0},_setOption:function(t,e){this._super(t,e),"handle"===t&&this._setHandleClassName()},_setHandleClassName:function(){var e=this;this._removeClass(this.element.find(".ui-sortable-handle"),"ui-sortable-handle"),t.each(this.items,function(){e._addClass(this.instance.options.handle?this.item.find(this.instance.options.handle):this.item,"ui-sortable-handle")})},_destroy:function(){this._mouseDestroy();for(var t=this.items.length-1;t>=0;t--)this.items[t].item.removeData(this.widgetName+"-item");return this},_mouseCapture:function(e,i){var s=null,n=!1,o=this;return!this.reverting&&!this.options.disabled&&"static"!==this.options.type&&(this._refreshItems(e),t(e.target).parents().each(function(){if(t.data(this,o.widgetName+"-item")===o)return s=t(this),!1}),t.data(e.target,o.widgetName+"-item")===o&&(s=t(e.target)),!!s&&(!this.options.handle||!!i||(t(this.options.handle,s).find("*").addBack().each(function(){this===e.target&&(n=!0)}),!!n))&&(this.currentItem=s,this._removeCurrentsFromItems(),!0))},_mouseStart:function(e,i,s){var n,o,a=this.options;if(this.currentContainer=this,this.refreshPositions(),this.appendTo=t("parent"!==a.appendTo?a.appendTo:this.currentItem.parent()),this.helper=this._createHelper(e),this._cacheHelperProportions(),this._cacheMargins(),this.offset=this.currentItem.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},t.extend(this.offset,{click:{left:e.pageX-this.offset.left,top:e.pageY-this.offset.top},relative:this._getRelativeOffset()}),this.helper.css("position","absolute"),this.cssPosition=this.helper.css("position"),a.cursorAt&&this._adjustOffsetFromHelper(a.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!==this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),this.scrollParent=this.placeholder.scrollParent(),t.extend(this.offset,{parent:this._getParentOffset()}),a.containment&&this._setContainment(),a.cursor&&"auto"!==a.cursor&&(o=this.document.find("body"),this._storedStylesheet=t("<style>*{ cursor: "+a.cursor+" !important; }</style>").appendTo(o)),a.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",a.zIndex)),a.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",a.opacity)),this.scrollParent[0]!==this.document[0]&&"HTML"!==this.scrollParent[0].tagName&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",e,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions(),!s)for(n=this.containers.length-1;n>=0;n--)this.containers[n]._trigger("activate",e,this._uiHash(this));return t.ui.ddmanager&&(t.ui.ddmanager.current=this),t.ui.ddmanager&&!a.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e),this.dragging=!0,this._addClass(this.helper,"ui-sortable-helper"),this.helper.parent().is(this.appendTo)||(this.helper.detach().appendTo(this.appendTo),this.offset.parent=this._getParentOffset()),this.position=this.originalPosition=this._generatePosition(e),this.originalPageX=e.pageX,this.originalPageY=e.pageY,this.lastPositionAbs=this.positionAbs=this._convertPositionTo("absolute"),this._mouseDrag(e),!0},_scroll:function(t){var e=this.options,i=!1;return this.scrollParent[0]!==this.document[0]&&"HTML"!==this.scrollParent[0].tagName?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-t.pageY<e.scrollSensitivity?this.scrollParent[0].scrollTop=i=this.scrollParent[0].scrollTop+e.scrollSpeed:t.pageY-this.overflowOffset.top<e.scrollSensitivity&&(this.scrollParent[0].scrollTop=i=this.scrollParent[0].scrollTop-e.scrollSpeed),this.overflowOffset.left+this.scrollParent[0].offsetWidth-t.pageX<e.scrollSensitivity?this.scrollParent[0].scrollLeft=i=this.scrollParent[0].scrollLeft+e.scrollSpeed:t.pageX-this.overflowOffset.left<e.scrollSensitivity&&(this.scrollParent[0].scrollLeft=i=this.scrollParent[0].scrollLeft-e.scrollSpeed)):(t.pageY-this.document.scrollTop()<e.scrollSensitivity?i=this.document.scrollTop(this.document.scrollTop()-e.scrollSpeed):this.window.height()-(t.pageY-this.document.scrollTop())<e.scrollSensitivity&&(i=this.document.scrollTop(this.document.scrollTop()+e.scrollSpeed)),t.pageX-this.document.scrollLeft()<e.scrollSensitivity?i=this.document.scrollLeft(this.document.scrollLeft()-e.scrollSpeed):this.window.width()-(t.pageX-this.document.scrollLeft())<e.scrollSensitivity&&(i=this.document.scrollLeft(this.document.scrollLeft()+e.scrollSpeed))),i},_mouseDrag:function(e){var i,s,n,o,a=this.options;for(this.position=this._generatePosition(e),this.positionAbs=this._convertPositionTo("absolute"),this.options.axis&&"y"===this.options.axis||(this.helper[0].style.left=this.position.left+"px"),this.options.axis&&"x"===this.options.axis||(this.helper[0].style.top=this.position.top+"px"),a.scroll&&!1!==this._scroll(e)&&(this._refreshItemPositions(!0),t.ui.ddmanager&&!a.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e)),this.dragDirection={vertical:this._getDragVerticalDirection(),horizontal:this._getDragHorizontalDirection()},i=this.items.length-1;i>=0;i--)if(n=(s=this.items[i]).item[0],(o=this._intersectsWithPointer(s))&&s.instance===this.currentContainer&&n!==this.currentItem[0]&&this.placeholder[1===o?"next":"prev"]()[0]!==n&&!t.contains(this.placeholder[0],n)&&("semi-dynamic"!==this.options.type||!t.contains(this.element[0],n))){if(this.direction=1===o?"down":"up","pointer"===this.options.tolerance||this._intersectsWithSides(s))this._rearrange(e,s);else break;this._trigger("change",e,this._uiHash());break}return this._contactContainers(e),t.ui.ddmanager&&t.ui.ddmanager.drag(this,e),this._trigger("sort",e,this._uiHash()),this.lastPositionAbs=this.positionAbs,!1},_mouseStop:function(e,i){if(e){if(t.ui.ddmanager&&!this.options.dropBehaviour&&t.ui.ddmanager.drop(this,e),this.options.revert){var s=this,n=this.placeholder.offset(),o=this.options.axis,a={};o&&"x"!==o||(a.left=n.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]===this.document[0].body?0:this.offsetParent[0].scrollLeft)),o&&"y"!==o||(a.top=n.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]===this.document[0].body?0:this.offsetParent[0].scrollTop)),this.reverting=!0,t(this.helper).animate(a,parseInt(this.options.revert,10)||500,function(){s._clear(e)})}else this._clear(e,i);return!1}},cancel:function(){if(this.dragging){this._mouseUp(new t.Event("mouseup",{target:null})),"original"===this.options.helper?(this.currentItem.css(this._storedCSS),this._removeClass(this.currentItem,"ui-sortable-helper")):this.currentItem.show();for(var e=this.containers.length-1;e>=0;e--)this.containers[e]._trigger("deactivate",null,this._uiHash(this)),this.containers[e].containerCache.over&&(this.containers[e]._trigger("out",null,this._uiHash(this)),this.containers[e].containerCache.over=0)}return this.placeholder&&(this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]),"original"!==this.options.helper&&this.helper&&this.helper[0].parentNode&&this.helper.remove(),t.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?t(this.domPosition.prev).after(this.currentItem):t(this.domPosition.parent).prepend(this.currentItem)),this},serialize:function(e){var i=this._getItemsAsjQuery(e&&e.connected),s=[];return e=e||{},t(i).each(function(){var i=(t(e.item||this).attr(e.attribute||"id")||"").match(e.expression||/(.+)[\-=_](.+)/);i&&s.push((e.key||i[1]+"[]")+"="+(e.key&&e.expression?i[1]:i[2]))}),!s.length&&e.key&&s.push(e.key+"="),s.join("&")},toArray:function(e){var i=this._getItemsAsjQuery(e&&e.connected),s=[];return e=e||{},i.each(function(){s.push(t(e.item||this).attr(e.attribute||"id")||"")}),s},_intersectsWith:function(t){var e=this.positionAbs.left,i=e+this.helperProportions.width,s=this.positionAbs.top,n=s+this.helperProportions.height,o=t.left,a=o+t.width,r=t.top,l=r+t.height,h=this.offset.click.top,c=this.offset.click.left,u="x"===this.options.axis||s+h>r&&s+h<l,d="y"===this.options.axis||e+c>o&&e+c<a;return"pointer"===this.options.tolerance||this.options.forcePointerForContainers||"pointer"!==this.options.tolerance&&this.helperProportions[this.floating?"width":"height"]>t[this.floating?"width":"height"]?u&&d:o<e+this.helperProportions.width/2&&i-this.helperProportions.width/2<a&&r<s+this.helperProportions.height/2&&n-this.helperProportions.height/2<l},_intersectsWithPointer:function(t){var e,i,s="x"===this.options.axis||this._isOverAxis(this.positionAbs.top+this.offset.click.top,t.top,t.height),n="y"===this.options.axis||this._isOverAxis(this.positionAbs.left+this.offset.click.left,t.left,t.width);return!!s&&!!n&&(e=this.dragDirection.vertical,i=this.dragDirection.horizontal,this.floating?"right"===i||"down"===e?2:1:e&&("down"===e?2:1))},_intersectsWithSides:function(t){var e=this._isOverAxis(this.positionAbs.top+this.offset.click.top,t.top+t.height/2,t.height),i=this._isOverAxis(this.positionAbs.left+this.offset.click.left,t.left+t.width/2,t.width),s=this.dragDirection.vertical,n=this.dragDirection.horizontal;return this.floating&&n?"right"===n&&i||"left"===n&&!i:s&&("down"===s&&e||"up"===s&&!e)},_getDragVerticalDirection:function(){var t=this.positionAbs.top-this.lastPositionAbs.top;return 0!==t&&(t>0?"down":"up")},_getDragHorizontalDirection:function(){var t=this.positionAbs.left-this.lastPositionAbs.left;return 0!==t&&(t>0?"right":"left")},refresh:function(t){return this._refreshItems(t),this._setHandleClassName(),this.refreshPositions(),this},_connectWith:function(){var t=this.options;
vendor: 27,623 bytes, line 12426
12426return t.connectWith.constructor===String?[t.connectWith]:t.connectWith},_getItemsAsjQuery:function(e){var i,s,n,o,a=[],r=[],l=this._connectWith();if(l&&e)for(i=l.length-1;i>=0;i--)for(s=(n=t(l[i],this.document[0])).length-1;s>=0;s--)(o=t.data(n[s],this.widgetFullName))&&o!==this&&!o.options.disabled&&r.push(["function"==typeof o.options.items?o.options.items.call(o.element):t(o.options.items,o.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),o]);function h(){a.push(this)}for(r.push(["function"==typeof this.options.items?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):t(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]),i=r.length-1;i>=0;i--)r[i][0].each(h);return t(a)},_removeCurrentsFromItems:function(){var e=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=t.grep(this.items,function(t){for(var i=0;i<e.length;i++)if(e[i]===t.item[0])return!1;return!0})},_refreshItems:function(e){this.items=[],this.containers=[this];var i,s,n,o,a,r,l,h,c=this.items,u=[["function"==typeof this.options.items?this.options.items.call(this.element[0],e,{item:this.currentItem}):t(this.options.items,this.element),this]],d=this._connectWith();if(d&&this.ready)for(i=d.length-1;i>=0;i--)for(s=(n=t(d[i],this.document[0])).length-1;s>=0;s--)(o=t.data(n[s],this.widgetFullName))&&o!==this&&!o.options.disabled&&(u.push(["function"==typeof o.options.items?o.options.items.call(o.element[0],e,{item:this.currentItem}):t(o.options.items,o.element),o]),this.containers.push(o));for(i=u.length-1;i>=0;i--)for(s=0,a=u[i][1],h=(r=u[i][0]).length;s<h;s++)(l=t(r[s])).data(this.widgetName+"-item",a),c.push({item:l,instance:a,width:0,height:0,left:0,top:0})},_refreshItemPositions:function(e){var i,s,n,o;for(i=this.items.length-1;i>=0;i--)s=this.items[i],(!this.currentContainer||s.instance===this.currentContainer||s.item[0]===this.currentItem[0])&&(n=this.options.toleranceElement?t(this.options.toleranceElement,s.item):s.item,e||(s.width=n.outerWidth(),s.height=n.outerHeight()),s.left=(o=n.offset()).left,s.top=o.top)},refreshPositions:function(t){var e,i;if(this.floating=!!this.items.length&&("x"===this.options.axis||this._isFloating(this.items[0].item)),this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset()),this._refreshItemPositions(t),this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(e=this.containers.length-1;e>=0;e--)i=this.containers[e].element.offset(),this.containers[e].containerCache.left=i.left,this.containers[e].containerCache.top=i.top,this.containers[e].containerCache.width=this.containers[e].element.outerWidth(),this.containers[e].containerCache.height=this.containers[e].element.outerHeight();return this},_createPlaceholder:function(e){var i,s,n=(e=e||this).options;n.placeholder&&n.placeholder.constructor!==String||(i=n.placeholder,s=e.currentItem[0].nodeName.toLowerCase(),n.placeholder={element:function(){var n=t("<"+s+">",e.document[0]);return e._addClass(n,"ui-sortable-placeholder",i||e.currentItem[0].className)._removeClass(n,"ui-sortable-helper"),"tbody"===s?e._createTrPlaceholder(e.currentItem.find("tr").eq(0),t("<tr>",e.document[0]).appendTo(n)):"tr"===s?e._createTrPlaceholder(e.currentItem,n):"img"===s&&n.attr("src",e.currentItem.attr("src")),i||n.css("visibility","hidden"),n},update:function(t,o){(!i||n.forcePlaceholderSize)&&((!o.height()||n.forcePlaceholderSize&&("tbody"===s||"tr"===s))&&o.height(e.currentItem.innerHeight()-parseInt(e.currentItem.css("paddingTop")||0,10)-parseInt(e.currentItem.css("paddingBottom")||0,10)),o.width()||o.width(e.currentItem.innerWidth()-parseInt(e.currentItem.css("paddingLeft")||0,10)-parseInt(e.currentItem.css("paddingRight")||0,10)))}}),e.placeholder=t(n.placeholder.element.call(e.element,e.currentItem)),e.currentItem.after(e.placeholder),n.placeholder.update(e,e.placeholder)},_createTrPlaceholder:function(e,i){var s=this;e.children().each(function(){t("<td>&#160;</td>",s.document[0]).attr("colspan",t(this).attr("colspan")||1).appendTo(i)})},_contactContainers:function(e){var i,s,n,o,a,r,l,h,c,u,d=null,p=null;for(i=this.containers.length-1;i>=0;i--)if(!t.contains(this.currentItem[0],this.containers[i].element[0])){if(this._intersectsWith(this.containers[i].containerCache)){if(d&&t.contains(this.containers[i].element[0],d.element[0]))continue;d=this.containers[i],p=i}else this.containers[i].containerCache.over&&(this.containers[i]._trigger("out",e,this._uiHash(this)),this.containers[i].containerCache.over=0)}if(d){if(1===this.containers.length)this.containers[p].containerCache.over||(this.containers[p]._trigger("over",e,this._uiHash(this)),this.containers[p].containerCache.over=1);else{for(n=1e4,o=null,a=(c=d.floating||this._isFloating(this.currentItem))?"left":"top",r=c?"width":"height",u=c?"pageX":"pageY",s=this.items.length-1;s>=0;s--)t.contains(this.containers[p].element[0],this.items[s].item[0])&&this.items[s].item[0]!==this.currentItem[0]&&(l=this.items[s].item.offset()[a],h=!1,e[u]-l>this.items[s][r]/2&&(h=!0),Math.abs(e[u]-l)<n&&(n=Math.abs(e[u]-l),o=this.items[s],this.direction=h?"up":"down"));if(!o&&!this.options.dropOnEmpty)return;if(this.currentContainer===this.containers[p]){this.currentContainer.containerCache.over||(this.containers[p]._trigger("over",e,this._uiHash()),this.currentContainer.containerCache.over=1);return}o?this._rearrange(e,o,null,!0):this._rearrange(e,null,this.containers[p].element,!0),this._trigger("change",e,this._uiHash()),this.containers[p]._trigger("change",e,this._uiHash(this)),this.currentContainer=this.containers[p],this.options.placeholder.update(this.currentContainer,this.placeholder),this.scrollParent=this.placeholder.scrollParent(),this.scrollParent[0]!==this.document[0]&&"HTML"!==this.scrollParent[0].tagName&&(this.overflowOffset=this.scrollParent.offset()),this.containers[p]._trigger("over",e,this._uiHash(this)),this.containers[p].containerCache.over=1}}},_createHelper:function(e){var i=this.options,s="function"==typeof i.helper?t(i.helper.apply(this.element[0],[e,this.currentItem])):"clone"===i.helper?this.currentItem.clone():this.currentItem;return s.parents("body").length||this.appendTo[0].appendChild(s[0]),s[0]===this.currentItem[0]&&(this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}),(!s[0].style.width||i.forceHelperSize)&&s.width(this.currentItem.width()),(!s[0].style.height||i.forceHelperSize)&&s.height(this.currentItem.height()),s},_adjustOffsetFromHelper:function(t){"string"==typeof t&&(t=t.split(" ")),Array.isArray(t)&&(t={left:+t[0],top:+t[1]||0}),"left"in t&&(this.offset.click.left=t.left+this.margins.left),"right"in t&&(this.offset.click.left=this.helperProportions.width-t.right+this.margins.left),"top"in t&&(this.offset.click.top=t.top+this.margins.top),"bottom"in t&&(this.offset.click.top=this.helperProportions.height-t.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var e=this.offsetParent.offset();return"absolute"===this.cssPosition&&this.scrollParent[0]!==this.document[0]&&t.contains(this.scrollParent[0],this.offsetParent[0])&&(e.left+=this.scrollParent.scrollLeft(),e.top+=this.scrollParent.scrollTop()),this.offsetParent[0]===this.document[0].body&&(e={top:0,left:0}),{top:e.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:e.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"!==this.cssPosition)return{top:0,left:0};var t=this.currentItem.position();return{top:t.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:t.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e,i,s,n=this.options;"parent"===n.containment&&(n.containment=this.helper[0].parentNode),("document"===n.containment||"window"===n.containment)&&(this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,"document"===n.containment?this.document.width():this.window.width()-this.helperProportions.width-this.margins.left,("document"===n.containment?this.document.height()||document.body.parentNode.scrollHeight:this.window.height()||this.document[0].body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]),/^(document|window|parent)$/.test(n.containment)||(e=t(n.containment)[0],i=t(n.containment).offset(),s="hidden"!==t(e).css("overflow"),this.containment=[i.left+(parseInt(t(e).css("borderLeftWidth"),10)||0)+(parseInt(t(e).css("paddingLeft"),10)||0)-this.margins.left,i.top+(parseInt(t(e).css("borderTopWidth"),10)||0)+(parseInt(t(e).css("paddingTop"),10)||0)-this.margins.top,i.left+(s?Math.max(e.scrollWidth,e.offsetWidth):e.offsetWidth)-(parseInt(t(e).css("borderLeftWidth"),10)||0)-(parseInt(t(e).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,i.top+(s?Math.max(e.scrollHeight,e.offsetHeight):e.offsetHeight)-(parseInt(t(e).css("borderTopWidth"),10)||0)-(parseInt(t(e).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top])},_convertPositionTo:function(e,i){i||(i=this.position);var s="absolute"===e?1:-1,n="absolute"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&t.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,o=/(html|body)/i.test(n[0].tagName);return{top:i.top+this.offset.relative.top*s+this.offset.parent.top*s-("fixed"===this.cssPosition?-this.scrollParent.scrollTop():o?0:n.scrollTop())*s,left:i.left+this.offset.relative.left*s+this.offset.parent.left*s-("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():o?0:n.scrollLeft())*s}},_generatePosition:function(e){var i,s,n=this.options,o=e.pageX,a=e.pageY,r="absolute"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&t.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,l=/(html|body)/i.test(r[0].tagName);return"relative"===this.cssPosition&&(this.scrollParent[0]===this.document[0]||this.scrollParent[0]===this.offsetParent[0])&&(this.offset.relative=this._getRelativeOffset()),this.originalPosition&&(this.containment&&(e.pageX-this.offset.click.left<this.containment[0]&&(o=this.containment[0]+this.offset.click.left),e.pageY-this.offset.click.top<this.containment[1]&&(a=this.containment[1]+this.offset.click.top),e.pageX-this.offset.click.left>this.containment[2]&&(o=this.containment[2]+this.offset.click.left),e.pageY-this.offset.click.top>this.containment[3]&&(a=this.containment[3]+this.offset.click.top)),n.grid&&(i=this.originalPageY+Math.round((a-this.originalPageY)/n.grid[1])*n.grid[1],a=this.containment?i-this.offset.click.top>=this.containment[1]&&i-this.offset.click.top<=this.containment[3]?i:i-this.offset.click.top>=this.containment[1]?i-n.grid[1]:i+n.grid[1]:i,s=this.originalPageX+Math.round((o-this.originalPageX)/n.grid[0])*n.grid[0],o=this.containment?s-this.offset.click.left>=this.containment[0]&&s-this.offset.click.left<=this.containment[2]?s:s-this.offset.click.left>=this.containment[0]?s-n.grid[0]:s+n.grid[0]:s)),{top:a-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():l?0:r.scrollTop()),left:o-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():l?0:r.scrollLeft())}},_rearrange:function(t,e,i,s){i?i[0].appendChild(this.placeholder[0]):e.item[0].parentNode.insertBefore(this.placeholder[0],"down"===this.direction?e.item[0]:e.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var n=this.counter;this._delay(function(){n===this.counter&&this.refreshPositions(!s)})},_clear:function(t,e){this.reverting=!1;var i,s=[];if(!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null,this.helper[0]===this.currentItem[0]){for(i in this._storedCSS)("auto"===this._storedCSS[i]||"static"===this._storedCSS[i])&&(this._storedCSS[i]="");this.currentItem.css(this._storedCSS),this._removeClass(this.currentItem,"ui-sortable-helper")}else this.currentItem.show();function n(t,e,i){return function(s){i._trigger(t,s,e._uiHash(e))}}for(this.fromOutside&&!e&&s.push(function(t){this._trigger("receive",t,this._uiHash(this.fromOutside))}),(this.fromOutside||this.domPosition.prev!==this.currentItem.prev().not(".ui-sortable-helper")[0]||this.domPosition.parent!==this.currentItem.parent()[0])&&!e&&s.push(function(t){this._trigger("update",t,this._uiHash())}),this===this.currentContainer||e||(s.push(function(t){this._trigger("remove",t,this._uiHash())}),s.push((function(t){return function(e){t._trigger("receive",e,this._uiHash(this))}}).call(this,this.currentContainer)),s.push((function(t){return function(e){t._trigger("update",e,this._uiHash(this))}}).call(this,this.currentContainer))),i=this.containers.length-1;i>=0;i--)e||s.push(n("deactivate",this,this.containers[i])),this.containers[i].containerCache.over&&(s.push(n("out",this,this.containers[i])),this.containers[i].containerCache.over=0);if(this._storedStylesheet&&(this._storedStylesheet.remove(),this._storedStylesheet=null),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex","auto"===this._storedZIndex?"":this._storedZIndex),this.dragging=!1,e||this._trigger("beforeStop",t,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.cancelHelperRemoval||(this.helper[0]!==this.currentItem[0]&&this.helper.remove(),this.helper=null),!e){for(i=0;i<s.length;i++)s[i].call(this,t);this._trigger("stop",t,this._uiHash())}return this.fromOutside=!1,!this.cancelHelperRemoval},_trigger:function(){!1===t.Widget.prototype._trigger.apply(this,arguments)&&this.cancel()},_uiHash:function(e){var i=e||this;return{helper:i.helper,placeholder:i.placeholder||t([]),position:i.position,originalPosition:i.originalPosition,offset:i.positionAbs,item:i.currentItem,sender:e?e.element:null}}}),t.widget("ui.spinner",{version:"1.14.2",defaultElement:"<input>",widgetEventPrefix:"spin",options:{classes:{"ui-spinner":"ui-corner-all","ui-spinner-down":"ui-corner-br","ui-spinner-up":"ui-corner-tr"},culture:null,icons:{down:"ui-icon-triangle-1-s",up:"ui-icon-triangle-1-n"},incremental:!0,max:null,min:null,numberFormat:null,page:10,step:1,change:null,spin:null,start:null,stop:null},_create:function(){this._setOption("max",this.options.max),this._setOption("min",this.options.min),this._setOption("step",this.options.step),""!==this.value()&&this._value(this.element.val(),!0),this._draw(),this._on(this._events),this._refresh(),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_getCreateOptions:function(){var e=this._super(),i=this.element;return t.each(["min","max","step"],function(t,s){var n=i.attr(s);null!=n&&n.length&&(e[s]=n)}),e},_events:{keydown:function(t){this._start(t)&&this._keydown(t)&&t.preventDefault()},keyup:"_stop",focus:function(){this.previous=this.element.val()},blur:function(t){this._stop(),this._refresh(),this.previous!==this.element.val()&&this._trigger("change",t)},wheel:function(t){var e=this.document[0].activeElement,i=this.element[0]===e,s=t.deltaY||t.originalEvent&&t.originalEvent.deltaY;if(i&&s){if(!this.spinning&&!this._start(t))return!1;this._spin((s>0?-1:1)*this.options.step,t),clearTimeout(this.mousewheelTimer),this.mousewheelTimer=this._delay(function(){this.spinning&&this._stop(t)},100),t.preventDefault()}},mousewheel:function(e,i){if(e.isTrigger){var s=t.Event(e);return s.type="wheel",i&&(s.deltaY=-i),this._events.wheel.call(this,s)}},"mousedown .ui-spinner-button":function(e){var i;i=this.element[0]===this.document[0].activeElement?this.previous:this.element.val(),e.preventDefault(),(function(){this.element[0]!==this.document[0].activeElement&&(this.element.trigger("focus"),this.previous=i)}).call(this),!1!==this._start(e)&&this._repeat(null,t(e.currentTarget).hasClass("ui-spinner-up")?1:-1,e)},"mouseup .ui-spinner-button":"_stop","mouseenter .ui-spinner-button":function(e){if(t(e.currentTarget).hasClass("ui-state-active")){if(!1===this._start(e))return!1;this._repeat(null,t(e.currentTarget).hasClass("ui-spinner-up")?1:-1,e)}},"mouseleave .ui-spinner-button":"_stop"},_enhance:function(){this.uiSpinner=this.element.attr("autocomplete","off").wrap("<span>").parent().append("<a></a><a></a>")},_draw:function(){this._enhance(),this._addClass(this.uiSpinner,"ui-spinner","ui-widget ui-widget-content"),this._addClass("ui-spinner-input"),this.element.attr("role","spinbutton"),this.buttons=this.uiSpinner.children("a").attr("tabIndex",-1).attr("aria-hidden",!0).button({classes:{"ui-button":""}}),this._removeClass(this.buttons,"ui-corner-all"),this._addClass(this.buttons.first(),"ui-spinner-button ui-spinner-up"),this._addClass(this.buttons.last(),"ui-spinner-button ui-spinner-down"),this.buttons.first().button({icon:this.options.icons.up,showLabel:!1}),this.buttons.last().button({icon:this.options.icons.down,showLabel:!1}),this.buttons.height()>Math.ceil(.5*this.uiSpinner.height())&&this.uiSpinner.height()>0&&this.uiSpinner.height(this.uiSpinner.height())},_keydown:function(e){var i=this.options,s=t.ui.keyCode;switch(e.keyCode){case s.UP:return this._repeat(null,1,e),!0;case s.DOWN:return this._repeat(null,-1,e),!0;case s.PAGE_UP:return this._repeat(null,i.page,e),!0;case s.PAGE_DOWN:return this._repeat(null,-i.page,e),!0}return!1},_start:function(t){return(!!this.spinning||!1!==this._trigger("start",t))&&(this.counter||(this.counter=1),this.spinning=!0,!0)},_repeat:function(t,e,i){t=t||500,clearTimeout(this.timer),this.timer=this._delay(function(){this._repeat(40,e,i)},t),this._spin(e*this.options.step,i)},_spin:function(t,e){var i=this.value()||0;this.counter||(this.counter=1),i=this._adjustValue(i+t*this._increment(this.counter)),(!this.spinning||!1!==this._trigger("spin",e,{value:i}))&&(this._value(i),this.counter++)},_increment:function(t){var e=this.options.incremental;return e?"function"==typeof e?e(t):Math.floor(t*t*t/5e4-t*t/500+17*t/200+1):1},_precision:function(){var t=this._precisionOf(this.options.step);return null!==this.options.min&&(t=Math.max(t,this._precisionOf(this.options.min))),t},_precisionOf:function(t){var e=t.toString(),i=e.indexOf(".");return -1===i?0:e.length-i-1},_adjustValue:function(t){var e,i,s=this.options;return(i=Math.round((i=t-(e=null!==s.min?s.min:0))/s.step)*s.step,t=parseFloat((t=e+i).toFixed(this._precision())),null!==s.max&&t>s.max)?s.max:null!==s.min&&t<s.min?s.min:t},_stop:function(t){this.spinning&&(clearTimeout(this.timer),clearTimeout(this.mousewheelTimer),this.counter=0,this.spinning=!1,this._trigger("stop",t))},_setOption:function(t,e){var i,s,n;if("culture"===t||"numberFormat"===t){i=this._parse(this.element.val()),this.options[t]=e,this.element.val(this._format(i));return}("max"===t||"min"===t||"step"===t)&&"string"==typeof e&&(e=this._parse(e)),"icons"===t&&(s=this.buttons.first().find(".ui-icon"),this._removeClass(s,null,this.options.icons.up),this._addClass(s,null,e.up),n=this.buttons.last().find(".ui-icon"),this._removeClass(n,null,this.options.icons.down),this._addClass(n,null,e.down)),this._super(t,e)},_setOptionDisabled:function(t){this._super(t),this._toggleClass(this.uiSpinner,null,"ui-state-disabled",!!t),this.element.prop("disabled",!!t),this.buttons.button(t?"disable":"enable")},_setOptions:O(function(t){this._super(t)}),_parse:function(t){return"string"==typeof t&&""!==t&&(t=window.Globalize&&this.options.numberFormat?Globalize.parseFloat(t,10,this.options.culture):+t),""===t||isNaN(t)?null:t},_format:function(t){return""===t?"":window.Globalize&&this.options.numberFormat?Globalize.format(t,this.options.numberFormat,this.options.culture):t},_refresh:function(){this.element.attr({"aria-valuemin":this.options.min,"aria-valuemax":this.options.max,"aria-valuenow":this._parse(this.element.val())})},isValid:function(){var t=this.value();return null!==t&&t===this._adjustValue(t)},_value:function(t,e){var i;""!==t&&null!==(i=this._parse(t))&&(e||(i=this._adjustValue(i)),t=this._format(i)),this.element.val(t),this._refresh()},_destroy:function(){this.element.prop("disabled",!1).removeAttr("autocomplete role aria-valuemin aria-valuemax aria-valuenow"),this.uiSpinner.replaceWith(this.element)},stepUp:O(function(t){this._stepUp(t)}),_stepUp:function(t){this._start()&&(this._spin((t||1)*this.options.step),this._stop())},stepDown:O(function(t){this._stepDown(t)}),_stepDown:function(t){this._start()&&(this._spin(-((t||1)*this.options.step)),this._stop())},pageUp:O(function(t){this._stepUp((t||1)*this.options.page)}),pageDown:O(function(t){this._stepDown((t||1)*this.options.page)}),value:function(t){if(!arguments.length)return this._parse(this.element.val());O(this._value).call(this,t)},widget:function(){return this.uiSpinner}}),!0===t.uiBackCompat&&t.widget("ui.spinner",t.ui.spinner,{_enhance:function(){this.uiSpinner=this.element.attr("autocomplete","off").wrap(this._uiSpinnerHtml()).parent().append(this._buttonHtml())},_uiSpinnerHtml:function(){return"<span>"},_buttonHtml:function(){return"<a></a><a></a>"}}),t.ui.spinner,t.widget("ui.tabs",{version:"1.14.2",delay:300,options:{active:null,classes:{"ui-tabs":"ui-corner-all","ui-tabs-nav":"ui-corner-all","ui-tabs-panel":"ui-corner-bottom","ui-tabs-tab":"ui-corner-top"},collapsible:!1,event:"click",heightStyle:"content",hide:null,show:null,activate:null,beforeActivate:null,beforeLoad:null,load:null},_isLocal:function(t){var e=new URL(t.href),i=new URL(location.href);return t.hash.length>1&&e.origin===i.origin&&e.pathname===i.pathname&&e.search===i.search},_create:function(){var e=this,i=this.options;this.running=!1,this._addClass("ui-tabs","ui-widget ui-widget-content"),this._toggleClass("ui-tabs-collapsible",null,i.collapsible),this._processTabs(),i.active=this._initialActive(),Array.isArray(i.disabled)&&(i.disabled=t.uniqueSort(i.disabled.concat(t.map(this.tabs.filter(".ui-state-disabled"),function(t){return e.tabs.index(t)}))).sort()),!1!==this.options.active&&this.anchors.length?this.active=this._findActive(i.active):this.active=t(),this._refresh(),this.active.length&&this.load(i.active)},_initialActive:function(){var e=this.options.active,i=this.options.collapsible,s=location.hash.substring(1),n=decodeURIComponent(s);return null===e&&(s&&(this.tabs.each(function(i,n){if(t(n).attr("aria-controls")===s)return e=i,!1}),null===e&&this.tabs.each(function(i,s){if(t(s).attr("aria-controls")===n)return e=i,!1})),null===e&&(e=this.tabs.index(this.tabs.filter(".ui-tabs-active"))),(null===e||-1===e)&&(e=!!this.tabs.length&&0)),!1!==e&&-1===(e=this.tabs.index(this.tabs.eq(e)))&&(e=!i&&0),!i&&!1===e&&this.anchors.length&&(e=0),e},_getCreateEventData:function(){return{tab:this.active,panel:this.active.length?this._getPanelForTab(this.active):t()}},_tabKeydown:function(e){var i=t(this.document[0].activeElement).closest("li"),s=this.tabs.index(i),n=!0;if(!this._handlePageNav(e)){switch(e.keyCode){case t.ui.keyCode.RIGHT:case t.ui.keyCode.DOWN:s++;break;case t.ui.keyCode.UP:case t.ui.keyCode.LEFT:n=!1,s--;break;case t.ui.keyCode.END:s=this.anchors.length-1;break;case t.ui.keyCode.HOME:s=0;break;case t.ui.keyCode.SPACE:e.preventDefault(),clearTimeout(this.activating),this._activate(s);return;case t.ui.keyCode.ENTER:e.preventDefault(),clearTimeout(this.activating),this._activate(s!==this.options.active&&s);return;default:return}e.preventDefault(),clearTimeout(this.activating),s=this._focusNextTab(s,n),e.ctrlKey||e.metaKey||(i.attr("aria-selected","false"),this.tabs.eq(s).attr("aria-selected","true"),this.activating=this._delay(function(){this.option("active",s)},this.delay))}},_panelKeydown:function(e){!this._handlePageNav(e)&&e.ctrlKey&&e.keyCode===t.ui.keyCode.UP&&(e.preventDefault(),this.active.trigger("focus"))},_handlePageNav:function(e){return e.altKey&&e.keyCode===t.ui.keyCode.PAGE_UP?(this._activate(this._focusNextTab(this.options.active-1,!1)),!0):e.altKey&&e.keyCode===t.ui.keyCode.PAGE_DOWN?(this._activate(this._focusNextTab(this.options.active+1,!0)),!0):void 0},_findNextTab:function(e,i){var s=this.tabs.length-1;while(-1!==t.inArray((e>s&&(e=0),e<0&&(e=s),e),this.options.disabled))e=i?e+1:e-1;return e},_focusNextTab:function(t,e){return t=this._findNextTab(t,e),this.tabs.eq(t).trigger("focus"),t},_setOption:function(t,e){if("active"===t){this._activate(e);return}this._super(t,e),"collapsible"!==t||(this._toggleClass("ui-tabs-collapsible",null,e),e||!1!==this.options.active||this._activate(0)),"event"===t&&this._setupEvents(e),"heightStyle"===t&&this._setupHeightStyle(e)},refresh:function(){var e=this.options,i=this.tablist.children(":has(a[href])");e.disabled=t.map(i.filter(".ui-state-disabled"),function(t){return i.index(t)}),this._processTabs(),!1!==e.active&&this.anchors.length?this.active.length&&!t.contains(this.tablist[0],this.active[0])?this.tabs.length===e.disabled.length?(e.active=!1,this.active=t()):this._activate(this._findNextTab(Math.max(0,e.active-1),!1)):e.active=this.tabs.index(this.active):(e.active=!1,this.active=t()),this._refresh()},_refresh:function(){this._setOptionDisabled(this.options.disabled),this._setupEvents(this.options.event),this._setupHeightStyle(this.options.heightStyle),this.tabs.not(this.active).attr({"aria-selected":"false","aria-expanded":"false",tabIndex:-1}),this.panels.not(this._getPanelForTab(this.active)).hide().attr({"aria-hidden":"true"}),this.active.length?(this.active.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0}),this._addClass(this.active,"ui-tabs-active","ui-state-active"),this._getPanelForTab(this.active).show().attr({"aria-hidden":"false"})):this.tabs.eq(0).attr("tabIndex",0)},_processTabs:function(){var e=this,i=this.tabs,s=this.anchors,n=this.panels;this.tablist=this._getList().attr("role","tablist"),this._addClass(this.tablist,"ui-tabs-nav","ui-helper-reset ui-helper-clearfix ui-widget-header"),this.tablist.on("mousedown"+this.eventNamespace,"> li",function(e){t(this).is(".ui-state-disabled")&&e.preventDefault()}),this.tabs=this.tablist.find("> li:has(a[href])").attr({role:"tab",tabIndex:-1}),this._addClass(this.tabs,"ui-tabs-tab","ui-state-default"),this.anchors=this.tabs.map(function(){return t("a",this)[0]}).attr({tabIndex:-1}),this._addClass(this.anchors,"ui-tabs-anchor"),this.panels=t(),this.anchors.each(function(i,s){var n,o,a,r=t(s).uniqueId().attr("id"),l=t(s).closest("li"),h=l.attr("aria-controls");e._isLocal(s)?(a=(n=s.hash).substring(1),(o=e.element.find("#"+CSS.escape(a))).length||(a=decodeURIComponent(a),o=e.element.find("#"+CSS.escape(a)))):(n="#"+(a=l.attr("aria-controls")||t({}).uniqueId()[0].id),(o=e.element.find(n)).length||(o=e._createPanel(a)).insertAfter(e.panels[i-1]||e.tablist),o.attr("aria-live","polite")),o.length&&(e.panels=e.panels.add(o)),h&&l.data("ui-tabs-aria-controls",h),l.attr({"aria-controls":a,"aria-labelledby":r}),o.attr("aria-labelledby",r)}),this.panels.attr("role","tabpanel"),this._addClass(this.panels,"ui-tabs-panel","ui-widget-content"),i&&(this._off(i.not(this.tabs)
vendor: 11,437 bytes, line 12426
12426),this._off(s.not(this.anchors)),this._off(n.not(this.panels)))},_getList:function(){return this.tablist||this.element.find("ol, ul").eq(0)},_createPanel:function(e){return t("<div>").attr("id",e).data("ui-tabs-destroy",!0)},_setOptionDisabled:function(e){var i,s,n;for(Array.isArray(e)&&(e.length?e.length===this.anchors.length&&(e=!0):e=!1),n=0;s=this.tabs[n];n++)i=t(s),!0===e||-1!==t.inArray(n,e)?(i.attr("aria-disabled","true"),this._addClass(i,null,"ui-state-disabled")):(i.removeAttr("aria-disabled"),this._removeClass(i,null,"ui-state-disabled"));this.options.disabled=e,this._toggleClass(this.widget(),this.widgetFullName+"-disabled",null,!0===e)},_setupEvents:function(e){var i={};e&&t.each(e.split(" "),function(t,e){i[e]="_eventHandler"}),this._off(this.anchors.add(this.tabs).add(this.panels)),this._on(!0,this.anchors,{click:function(t){t.preventDefault()}}),this._on(this.anchors,i),this._on(this.tabs,{keydown:"_tabKeydown"}),this._on(this.panels,{keydown:"_panelKeydown"}),this._focusable(this.tabs),this._hoverable(this.tabs)},_setupHeightStyle:function(e){var i,s=this.element.parent();"fill"===e?(i=s.height()-(this.element.outerHeight()-this.element.height()),this.element.siblings(":visible").each(function(){var e=t(this),s=e.css("position");"absolute"!==s&&"fixed"!==s&&(i-=e.outerHeight(!0))}),this.element.children().not(this.panels).each(function(){i-=t(this).outerHeight(!0)}),this.panels.each(function(){t(this).height(Math.max(0,i-t(this).innerHeight()+t(this).height()))}).css("overflow","auto")):"auto"===e&&(i=0,this.panels.each(function(){i=Math.max(i,t(this).height("").height())}).height(i))},_eventHandler:function(e){var i=this.options,s=this.active,n=t(e.currentTarget).closest("li"),o=n[0]===s[0],a=o&&i.collapsible,r=a?t():this._getPanelForTab(n),l=s.length?this._getPanelForTab(s):t(),h={oldTab:s,oldPanel:l,newTab:a?t():n,newPanel:r};e.preventDefault(),!(n.hasClass("ui-state-disabled")||n.hasClass("ui-tabs-loading"))&&!this.running&&(!o||i.collapsible)&&!1!==this._trigger("beforeActivate",e,h)&&(i.active=!a&&this.tabs.index(n),this.active=o?t():n,this.xhr&&this.xhr.abort(),l.length||r.length||t.error("jQuery UI Tabs: Mismatching fragment identifier."),r.length&&this.load(this.tabs.index(n),e),this._toggle(e,h))},_toggle:function(e,i){var s=this,n=i.newPanel,o=i.oldPanel;function a(){s.running=!1,s._trigger("activate",e,i)}function r(){s._addClass(i.newTab.closest("li"),"ui-tabs-active","ui-state-active"),n.length&&s.options.show?s._show(n,s.options.show,a):(n.show(),a())}this.running=!0,o.length&&this.options.hide?this._hide(o,this.options.hide,function(){s._removeClass(i.oldTab.closest("li"),"ui-tabs-active","ui-state-active"),r()}):(this._removeClass(i.oldTab.closest("li"),"ui-tabs-active","ui-state-active"),o.hide(),r()),o.attr("aria-hidden","true"),i.oldTab.attr({"aria-selected":"false","aria-expanded":"false"}),n.length&&o.length?i.oldTab.attr("tabIndex",-1):n.length&&this.tabs.filter(function(){return 0===t(this).attr("tabIndex")}).attr("tabIndex",-1),n.attr("aria-hidden","false"),i.newTab.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0})},_activate:function(e){var i,s=this._findActive(e);s[0]!==this.active[0]&&(s.length||(s=this.active),i=s.find(".ui-tabs-anchor")[0],this._eventHandler({target:i,currentTarget:i,preventDefault:t.noop}))},_findActive:function(e){return!1===e?t():this.tabs.eq(e)},_getIndex:function(t){return"string"==typeof t&&(t=this.anchors.index(this.anchors.filter("[href$='"+CSS.escape(t)+"']"))),t},_destroy:function(){this.xhr&&this.xhr.abort(),this.tablist.removeAttr("role").off(this.eventNamespace),this.anchors.removeAttr("role tabIndex").removeUniqueId(),this.tabs.add(this.panels).each(function(){t.data(this,"ui-tabs-destroy")?t(this).remove():t(this).removeAttr("role tabIndex aria-live aria-busy aria-selected aria-labelledby aria-hidden aria-expanded")}),this.tabs.each(function(){var e=t(this),i=e.data("ui-tabs-aria-controls");i?e.attr("aria-controls",i).removeData("ui-tabs-aria-controls"):e.removeAttr("aria-controls")}),this.panels.show(),"content"!==this.options.heightStyle&&this.panels.css("height","")},enable:function(e){var i=this.options.disabled;!1!==i&&(void 0===e?i=!1:(e=this._getIndex(e),i=Array.isArray(i)?t.map(i,function(t){return t!==e?t:null}):t.map(this.tabs,function(t,i){return i!==e?i:null})),this._setOptionDisabled(i))},disable:function(e){var i=this.options.disabled;if(!0!==i){if(void 0===e)i=!0;else{if(e=this._getIndex(e),-1!==t.inArray(e,i))return;i=Array.isArray(i)?t.merge([e],i).sort():[e]}this._setOptionDisabled(i)}},load:function(e,i){e=this._getIndex(e);var s=this,n=this.tabs.eq(e),o=n.find(".ui-tabs-anchor"),a=this._getPanelForTab(n),r={tab:n,panel:a},l=function(t,e){"abort"===e&&s.panels.stop(!1,!0),s._removeClass(n,"ui-tabs-loading"),a.removeAttr("aria-busy"),t===s.xhr&&delete s.xhr};!this._isLocal(o[0])&&(this.xhr=t.ajax(this._ajaxSettings(o,i,r)),"canceled"!==this.xhr.statusText&&(this._addClass(n,"ui-tabs-loading"),a.attr("aria-busy","true"),this.xhr.done(function(t,e,n){a.html(t),s._trigger("load",i,r),l(n,e)}).fail(function(t,e){l(t,e)})))},_ajaxSettings:function(e,i,s){var n=this;return{url:e.attr("href"),beforeSend:function(e,o){return n._trigger("beforeLoad",i,t.extend({jqXHR:e,ajaxSettings:o},s))}}},_getPanelForTab:function(e){var i=t(e).attr("aria-controls");return this.element.find("#"+CSS.escape(i))}}),!0===t.uiBackCompat&&t.widget("ui.tabs",t.ui.tabs,{_processTabs:function(){this._superApply(arguments),this._addClass(this.tabs,"ui-tab")}}),t.ui.tabs,t.widget("ui.tooltip",{version:"1.14.2",options:{classes:{"ui-tooltip":"ui-corner-all ui-widget-shadow"},content:function(){var e=t(this).attr("title");return t("<a>").text(e).html()},hide:!0,items:"[title]:not([disabled])",position:{my:"left top+15",at:"left bottom",collision:"flipfit flip"},show:!0,track:!1,close:null,open:null},_addDescribedBy:function(t,e){var i=(t.attr("aria-describedby")||"").split(/\s+/);i.push(e),t.data("ui-tooltip-id",e).attr("aria-describedby",String.prototype.trim.call(i.join(" ")))},_removeDescribedBy:function(e){var i=e.data("ui-tooltip-id"),s=(e.attr("aria-describedby")||"").split(/\s+/),n=t.inArray(i,s);-1!==n&&s.splice(n,1),e.removeData("ui-tooltip-id"),(s=String.prototype.trim.call(s.join(" ")))?e.attr("aria-describedby",s):e.removeAttr("aria-describedby")},_create:function(){this._on({mouseover:"open",focusin:"open"}),this.tooltips={},this.parents={},this.liveRegion=t("<div>").attr({role:"log","aria-live":"assertive","aria-relevant":"additions"}).appendTo(this.document[0].body),this._addClass(this.liveRegion,null,"ui-helper-hidden-accessible"),this.disabledTitles=t([])},_setOption:function(e,i){var s=this;this._super(e,i),"content"===e&&t.each(this.tooltips,function(t,e){s._updateContent(e.element)})},_setOptionDisabled:function(t){this[t?"_disable":"_enable"]()},_disable:function(){var e=this;t.each(this.tooltips,function(i,s){var n=t.Event("blur");n.target=n.currentTarget=s.element[0],e.close(n,!0)}),this.disabledTitles=this.disabledTitles.add(this.element.find(this.options.items).addBack().filter(function(){var e=t(this);if(e.is("[title]"))return e.data("ui-tooltip-title",e.attr("title")).removeAttr("title")}))},_enable:function(){this.disabledTitles.each(function(){var e=t(this);e.data("ui-tooltip-title")&&e.attr("title",e.data("ui-tooltip-title"))}),this.disabledTitles=t([])},open:function(e){var i=this,s=t(e?e.target:this.element).closest(this.options.items);!(!s.length||s.data("ui-tooltip-id"))&&(s.attr("title")&&s.data("ui-tooltip-title",s.attr("title")),s.data("ui-tooltip-open",!0),e&&"mouseover"===e.type&&s.parents().each(function(){var e,s=t(this);s.data("ui-tooltip-open")&&((e=t.Event("blur")).target=e.currentTarget=this,i.close(e,!0)),s.attr("title")&&(s.uniqueId(),i.parents[this.id]={element:this,title:s.attr("title")},s.attr("title",""))}),this._registerCloseHandlers(e,s),this._updateContent(s,e))},_updateContent:function(t,e){var i,s=this.options.content,n=this,o=e?e.type:null;if("string"==typeof s||s.nodeType||s.jquery)return this._open(e,t,s);(i=s.call(t[0],function(i){t.data("ui-tooltip-open")&&(e&&(e.type=o),n._open(e,t,i))}))&&this._open(e,t,i)},_open:function(e,i,s){var n,o,a,r,l=t.extend({},this.options.position);if(s){if(n=this._find(i)){n.tooltip.find(".ui-tooltip-content").html(s);return}i.is("[title]")&&(e&&"mouseover"===e.type?i.attr("title",""):i.removeAttr("title")),o=(n=this._tooltip(i)).tooltip,this._addDescribedBy(i,o.attr("id")),o.find(".ui-tooltip-content").html(s),this.liveRegion.children().hide(),(r=t("<div>").html(o.find(".ui-tooltip-content").html())).removeAttr("name").find("[name]").removeAttr("name"),r.removeAttr("id").find("[id]").removeAttr("id"),r.appendTo(this.liveRegion),this.options.track&&e&&/^mouse/.test(e.type)?(this._on(this.document,{mousemove:h}),h(e)):o.position(t.extend({of:i},this.options.position)),o.hide(),this._show(o,this.options.show),this.options.track&&this.options.show&&this.options.show.delay&&(a=this.delayedShow=setInterval(function(){o.is(":visible")&&(h(l.of),clearInterval(a))},13)),this._trigger("open",e,{tooltip:o})}function h(t){l.of=t,!o.is(":hidden")&&o.position(l)}},_registerCloseHandlers:function(e,i){var s={keyup:function(e){if(e.keyCode===t.ui.keyCode.ESCAPE){var s=t.Event(e);s.currentTarget=i[0],this.close(s,!0)}}};i[0]!==this.element[0]&&(s.remove=function(){var t=this._find(i);t&&this._removeTooltip(t.tooltip)}),e&&"mouseover"!==e.type||(s.mouseleave="close"),e&&"focusin"!==e.type||(s.focusout="close"),this._on(!0,i,s)},close:function(e){var i,s=this,n=t(e?e.currentTarget:this.element),o=this._find(n);if(!o){n.removeData("ui-tooltip-open");return}i=o.tooltip,!o.closing&&(clearInterval(this.delayedShow),n.data("ui-tooltip-title")&&!n.attr("title")&&n.attr("title",n.data("ui-tooltip-title")),this._removeDescribedBy(n),o.hiding=!0,i.stop(!0),this._hide(i,this.options.hide,function(){s._removeTooltip(t(this))}),n.removeData("ui-tooltip-open"),this._off(n,"mouseleave focusout keyup"),n[0]!==this.element[0]&&this._off(n,"remove"),this._off(this.document,"mousemove"),e&&"mouseleave"===e.type&&t.each(this.parents,function(e,i){t(i.element).attr("title",i.title),delete s.parents[e]}),o.closing=!0,this._trigger("close",e,{tooltip:i}),o.hiding||(o.closing=!1))},_tooltip:function(e){var i=t("<div>").attr("role","tooltip"),s=t("<div>").appendTo(i),n=i.uniqueId().attr("id");return this._addClass(s,"ui-tooltip-content"),this._addClass(i,"ui-tooltip","ui-widget ui-widget-content"),i.appendTo(this._appendTo(e)),this.tooltips[n]={element:e,tooltip:i}},_find:function(t){var e=t.data("ui-tooltip-id");return e?this.tooltips[e]:null},_removeTooltip:function(t){clearInterval(this.delayedShow),t.remove(),delete this.tooltips[t.attr("id")]},_appendTo:function(t){var e=t.closest(".ui-front, dialog");return e.length||(e=this.document[0].body),e},_destroy:function(){var e=this;t.each(this.tooltips,function(i,s){var n=t.Event("blur"),o=s.element;n.target=n.currentTarget=o[0],e.close(n,!0),t("#"+i).remove(),o.data("ui-tooltip-title")&&(o.attr("title")||o.attr("title",o.data("ui-tooltip-title")),o.removeData("ui-tooltip-title"))}),this.liveRegion.remove()}}),!0===t.uiBackCompat&&t.widget("ui.tooltip",t.ui.tooltip,{options:{tooltipClass:null},_tooltip:function(){var t=this._superApply(arguments);return this.options.tooltipClass&&t.tooltip.addClass(this.options.tooltipClass),t}}),t.ui.tooltip});
12426
12427$(document).ready(function () {
12428    var $body = $('body');
12429    var expiryDate = new Date('12/31/2999');    
12430    var size = Math.floor($('body').css('font-size').replace('px', ''));    
12431
12432    //Append a class of cpTextResizeOn on body to get right styles for text resizer.
12433    $body.addClass('cpTextResizeOn');
12434
12435    var factor = 1;
12436    if ($.cookie('sizeFactor') == null || $.cookie('sizeFactor') == '0') {
12437        //Do nothing.
12438    }
12439    else {
12440        factor = parseFloat($.cookie('sizeFactor'));
12441        size = size + factor;
12442        $body.css('font-size', '' + size + 'px');
12443}
12444
12445    $('.cpTextResizer').find('a').click(function (e) {
12446        e.preventDefault();
12447        resizePageText(size, $(this));
12448    });
12449});
12450
12451//Resize the text based on cookie value set.
12452function resizePageText(originalFontSize, $anchor) {
12453    var $body = $('body');
12454    var expiryDate = new Date('12/31/2999');
12455    var currentFontSize = $body.css('font-size');
12456    var bigOrSmall = $anchor.attr('id');
12457    var multiplier = 1;
12458    var fontSize;
12459    if (bigOrSmall == "makeTextSmaller") {        
12460        $.cookie('sizeFactor', parseInt($.cookie('sizeFactor') == null ? 0 : $.cookie('sizeFactor')) - 1, { path: '/', expires: expiryDate });
12461        fontSize = parseInt(currentFontSize.replace('px', '')) - 1;
12462    } else if (bigOrSmall == "makeTextBigger") {        
12463        $.cookie('sizeFactor', parseInt($.cookie('sizeFactor') == null ? 0 : $.cookie('sizeFactor')) + 1, { path: '/', expires: expiryDate });
12464        fontSize = parseInt(currentFontSize.replace('px', '')) +1;
12465    }    
12466     $body.css('font-size', '' + fontSize + 'px');
12467
12468     if (!window.isRemoveSetHeights)
12469     	SetHeights();//Adjust heights of the containers.
12470};
12471var PopupBasedAuthentication = function () {
12472    var self = this;
12473    var popupWindow;
12474    var url;
12475    var paramSet;
12476    var jsCallback;
12477    var popupOrigin;
12478
12479    self.requireLoggedIn = function (redirectUri, parameterSet) {
12480        if (redirectUri == null || redirectUri == '') {
12481            redirectUri = (window.location.pathname + window.location.search).split('#')[0];
12482        }
12483        self.setupParameters(redirectUri, parameterSet);
12484        self.checkLoggedIn();
12485    };
12486
12487    self.setupParameters = function (redirectUri, parameterSet) {
12488        url = redirectUri;
12489        paramSet = parameterSet;
12490    };
12491
12492    self.setupJsCallback = function (callback) {
12493    	jsCallback = callback;
12494    };
12495
12496    self.checkLoggedIn = function () {
12497        $.ajax({
12498            url: '/Authentication/IsLoggedIn',
12499            type: 'GET',
12500            success: self.processCheckLoggedInResponse,
12501            async: false
12502        })
12503    };
12504
12505    self.processCheckLoggedInResponse = function (loggedInResponse) {
12506    	if (loggedInResponse.loggedIn == true) {
12507    		if (jsCallback == null) {
12508    			window.location.href = url;
12509    		}
12510    		else {
12511    			jsCallback();
12512    		}
12513    	}
12514    	else if (loggedInResponse.UseIdentityServer) {
12515    		window.location.href = '/MyAccount?from=url&url=' + encodeURIComponent(url);
12516	    } else {
12517		    self.authenticate(loggedInResponse.domain);
12518	    }
12519    };
12520
12521    self.authenticate = function (domain) {
12522        var popupUrl = document.createElement('a');
12523        popupUrl.href = 'https://' + domain;
12524        popupOrigin = popupUrl.protocol + '//' + popupUrl.host;
12525        if (internetExplorerVersion == undefined) {
12526            self.setupEventToListenFromChildWindow();
12527        }
12528
12529        self.disableScreen();
12530
12531        var width = 500;
12532        var height = 420;
12533
12534        var left = (screen.width / 2) - (width / 2);
12535        var top = (screen.height / 2) - (height / 2);
12536		
12537        if (navigator.appName == 'Microsoft Internet Explorer' || !!(navigator.userAgent.match(/Trident/) || navigator.userAgent.match(/rv:11/)) || (typeof $.browser !== "undefined" && $.browser.msie == 1)) {
12538			window.location = "/MyAccount?from=url&url=" + window.location.pathname + window.location.search;
12539			return;
12540		}
12541
12542        popupWindow = window.open(
12543                popupOrigin + '/Authentication/Popup?'
12544				+ 'redirectUri=' + encodeURIComponent(url)
12545				+ '&parameterSet=' + paramSet
12546				+ self.getUsernameFromCookie()
12547                + '&callingHost=' + window.location.protocol + '//' + window.location.hostname,
12548            'SignIn',
12549            'height=420,width=500,toolbar=no,menubar=no,left=' + left + ',top=' + top);
12550
12551        self.checkBlockedPopup(popupWindow);
12552        self.attachOnCloseEvent(popupWindow);
12553    };
12554
12555    self.getUsernameFromCookie = function () {
12556        var usernameCookieValue = cookieGet("CP");
12557        if (usernameCookieValue != null && usernameCookieValue.indexOf('uname=') == 0) {
12558            return '&prePopulatedUsername=' + usernameCookieValue.substring(6);
12559        } else {
12560            return '';
12561        }
12562    };
12563
12564    self.attachOnCloseEvent = function (win) {
12565        var intervalId;
12566        function checkWindow() {
12567            if (win && win.closed) {
12568                window.clearInterval(intervalId);
12569                self.enableScreen();
12570            }
12571        }
12572        intervalId = window.setInterval(checkWindow, 500);
12573    };
12574
12575    self.disableScreen = function () {
12576        $('#editItemBehavior_backgroundElement').show();
12577    };
12578
12579    self.enableScreen = function () {
12580        $('#editItemBehavior_backgroundElement').hide();
12581    };
12582
12583    self.checkBlockedPopup = function (popup) {
12584        setTimeout(function () {
12585        	if (!popup || popup.closed || popup.closed == 'undefined' || (popup.outerHeight && popup.outerHeight === 0)) {
12586                alert('Popup blocked');
12587                self.enableScreen();
12588            }
12589        }, 25);
12590    };
12591
12592    self.setupEventToListenFromChildWindow = function () {
12593        window.addEventListener('message', function (msg) {
12594            if (msg.source === popupWindow && msg.origin === popupOrigin && msg.data.Type == 'Redirect') {
12595                self.handleResponseFromChild(msg.data);
12596            }
12597        }, true);
12598    };
12599
12600    self.internetExplorerMessageHandling = function (data) {
12601        self.handleResponseFromChild(data);
12602    };
12603
12604    self.handleResponseFromChild = function (data) {
12605        if (data.Type == 'Redirect') {
12606            var redirectUrl = document.createElement('a');
12607            redirectUrl.href = data.Url.replace(/&amp;/g, '&');
12608            if (redirectUrl.protocol === window.location.protocol && redirectUrl.host === window.location.host) {
12609                window.location.href = redirectUrl.href;
12610            }
12611        }
12612    };
12613};
12614;
12615/**
12616 * http://www.openjs.com/scripts/events/keyboard_shortcuts/
12617 * Version : 2.01.B
12618 * By Binny V A
12619 * License : BSD
12620 */
12621
12622var pressCount = 0; //this is used to track button presses for a specific table widget IE hack
12623
12624shortcut = {
12625	'all_shortcuts':{},//All the shortcuts are stored in this array
12626	'add': function(shortcut_combination,callback,opt) {
12627		//Provide a set of default options
12628		var default_options = {
12629			'type':'keydown',
12630			'propagate':false,
12631			'disable_in_input':false,
12632			'target':document,
12633			'keycode':false
12634		}
12635		if(!opt) opt = default_options;
12636		else {
12637			for(var dfo in default_options) {
12638				if(typeof opt[dfo] == 'undefined') opt[dfo] = default_options[dfo];
12639			}
12640		}
12641
12642		var ele = opt.target;
12643		if(typeof opt.target == 'string') ele = document.getElementById(opt.target);
12644		var ths = this;
12645		shortcut_combination = shortcut_combination.toLowerCase();
12646
12647		//The function to be called at keypress
12648		var func = function(e) {
12649			e = e || window.event;
12650			var character = null;
12651			
12652		    //this is an IE only hack that will fix double (<p>) vs single line (<br>) breaks in the table widget (<div contenteditable=true)
12653			if (detectIE() && e.keyCode == 13 && e.target.tagName == 'DIV' && e.target.contentEditable == "true") {
12654			    if ((pressCount) % 4 == 0) {
12655			        var node = document.createElement('br')
12656			        var positionNode = document.createTextNode('\u200B'); //used as a fake node to advance the cursor
12657			        node.appendChild(positionNode);
12658			        var selection = window.getSelection();
12659			        var range = selection.getRangeAt(0);
12660			        range.insertNode(node);
12661			        range.setStartAfter(node);
12662			        range.setEndAfter(node);
12663			        selection.removeAllRanges();
12664			        selection.addRange(range);
12665			    }
12666			    else {
12667			        e.preventDefault();
12668			    }
12669
12670			    pressCount++;
12671			    return false;
12672			}
12673
12674			if(opt['disable_in_input']) { //Don't enable shortcut keys in Input, Textarea fields
12675				var element;
12676				if(e.target) element=e.target;
12677				else if(e.srcElement) element=e.srcElement;
12678				if(element.nodeType==3) element=element.parentNode;
12679
12680				if(element.tagName == 'INPUT' || element.tagName == 'TEXTAREA') return;
12681			}
12682	
12683			//Find Which key is pressed
12684			if (e.keyCode) code = e.keyCode;
12685			else if (e.which) code = e.which;
12686			if (typeof (code) !== "undefined")
12687			{
12688				character = String.fromCharCode(code).toLowerCase();
12689				if (code == 188) character = ","; //If the user presses , when the type is onkeydown
12690				if (code == 190) character = "."; //If the user presses , when the type is onkeydown
12691			}
12692
12693			var keys = shortcut_combination.split("+");
12694			//Key Pressed - counts the number of valid keypresses - if it is same as the number of keys, the shortcut function is invoked
12695			var kp = 0;
12696			
12697			//Work around for stupid Shift key bug created by using lowercase - as a result the shift+num combination was broken
12698			var shift_nums = {
12699				"`":"~",
12700				"1":"!",
12701				"2":"@",
12702				"3":"#",
12703				"4":"$",
12704				"5":"%",
12705				"6":"^",
12706				"7":"&",
12707				"8":"*",
12708				"9":"(",
12709				"0":")",
12710				"-":"_",
12711				"=":"+",
12712				";":":",
12713				"'":"\"",
12714				",":"<",
12715				".":">",
12716				"/":"?",
12717				"\\":"|"
12718			}
12719			//Special Keys - and their codes
12720			var special_keys = {
12721				'esc':27,
12722				'escape':27,
12723				'tab':9,
12724				'space':32,
12725				'return':13,
12726				'enter':13,
12727				'backspace':8,
12728	
12729				'scrolllock':145,
12730				'scroll_lock':145,
12731				'scroll':145,
12732				'capslock':20,
12733				'caps_lock':20,
12734				'caps':20,
12735				'numlock':144,
12736				'num_lock':144,
12737				'num':144,
12738				
12739				'pause':19,
12740				'break':19,
12741				
12742				'insert':45,
12743				'home':36,
12744				'delete':46,
12745				'end':35,
12746				
12747				'pageup':33,
12748				'page_up':33,
12749				'pu':33,
12750	
12751				'pagedown':34,
12752				'page_down':34,
12753				'pd':34,
12754	
12755				'left':37,
12756				'up':38,
12757				'right':39,
12758				'down':40,
12759	
12760				'f1':112,
12761				'f2':113,
12762				'f3':114,
12763				'f4':115,
12764				'f5':116,
12765				'f6':117,
12766				'f7':118,
12767				'f8':119,
12768				'f9':120,
12769				'f10':121,
12770				'f11':122,
12771				'f12':123
12772			}
12773	
12774			var modifiers = { 
12775				shift: { wanted:false, pressed:false},
12776				ctrl : { wanted:false, pressed:false},
12777				alt  : { wanted:false, pressed:false},
12778				meta : { wanted:false, pressed:false}	//Meta is Mac specific
12779			};
12780                        
12781			if(e.ctrlKey)	modifiers.ctrl.pressed = true;
12782			if(e.shiftKey)	modifiers.shift.pressed = true;
12783			if(e.altKey)	modifiers.alt.pressed = true;
12784			if(e.metaKey)   modifiers.meta.pressed = true;
12785                        
12786			for(var i=0; k=keys[i],i<keys.length; i++) {
12787				//Modifiers
12788				if(k == 'ctrl' || k == 'control') {
12789					kp++;
12790					modifiers.ctrl.wanted = true;
12791
12792				} else if(k == 'shift') {
12793					kp++;
12794					modifiers.shift.wanted = true;
12795
12796				} else if(k == 'alt') {
12797					kp++;
12798					modifiers.alt.wanted = true;
12799				} else if(k == 'meta') {
12800					kp++;
12801					modifiers.meta.wanted = true;
12802				} else if(k.length > 1) { //If it is a special key
12803					if(special_keys[k] == code) kp++;
12804					
12805				} else if(opt['keycode']) {
12806					if(opt['keycode'] == code) kp++;
12807
12808				} else { //The special keys did not match
12809					if(character == k) kp++;
12810					else {
12811						if(shift_nums[character] && e.shiftKey) { //Stupid Shift key bug created by using lowercase
12812							character = shift_nums[character]; 
12813							if(character == k) kp++;
12814						}
12815					}
12816				}
12817			}
12818			
12819			if(kp == keys.length && 
12820						modifiers.ctrl.pressed == modifiers.ctrl.wanted &&
12821						modifiers.shift.pressed == modifiers.shift.wanted &&
12822						modifiers.alt.pressed == modifiers.alt.wanted &&
12823						modifiers.meta.pressed == modifiers.meta.wanted) {
12824				callback(e);
12825	
12826				if(!opt['propagate']) { //Stop the event
12827					//e.cancelBubble is supported by IE - this will kill the bubbling process.
12828					e.cancelBubble = true;
12829					e.returnValue = false;
12830	
12831					//e.stopPropagation works in Firefox.
12832					if (e.stopPropagation) {
12833						e.stopPropagation();
12834						e.preventDefault();
12835					}
12836					return false;
12837				}
12838			}
12839		}
12840		this.all_shortcuts[shortcut_combination] = {
12841			'callback':func, 
12842			'target':ele, 
12843			'event': opt['type']
12844		};
12845		//Attach the function with the event
12846		if(ele.addEventListener) ele.addEventListener(opt['type'], func, false);
12847		else if(ele.attachEvent) ele.attachEvent('on'+opt['type'], func);
12848		else ele['on'+opt['type']] = func;
12849	},
12850
12851	//Remove the shortcut - just specify the shortcut and I will remove the binding
12852	'remove':function(shortcut_combination) {
12853		shortcut_combination = shortcut_combination.toLowerCase();
12854		var binding = this.all_shortcuts[shortcut_combination];
12855		delete(this.all_shortcuts[shortcut_combination])
12856		if(!binding) return;
12857		var type = binding['event'];
12858		var ele = binding['target'];
12859		var callback = binding['callback'];
12860
12861		if(ele.detachEvent) ele.detachEvent('on'+type, callback);
12862		else if(ele.removeEventListener) ele.removeEventListener(type, callback, false);
12863		else ele['on'+type] = false;
12864	}
12865}
12866
12867/**
12868 * detect IE
12869 * returns version of IE or false, if browser is not Internet Explorer
12870 */
12871function detectIE() {
12872    var ua = window.navigator.userAgent;
12873
12874    var msie = ua.indexOf('MSIE ');
12875    if (msie > 0) {
12876        // IE 10 or older => return version number
12877        return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
12878    }
12879
12880    var trident = ua.indexOf('Trident/');
12881    if (trident > 0) {
12882        // IE 11 => return version number
12883        var rv = ua.indexOf('rv:');
12884        return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
12885    }
12886
12887    var edge = ua.indexOf('Edge/');
12888    if (edge > 0) {
12889        // Edge (IE 12+) => return version number
12890        return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
12891    }
12892
12893    // other browser
12894    return false;
12895}
12896;
12897// http://www.codinghorror.com/blog/2006/02/standard-browser-keyboard-shortcuts.html
12898// NOTE: Ctrl+Shift+T is used by browsers to reopen the last closed tab
12899// NOTE: Ctrl+Shift+B is used by several browsers for various functions
12900
12901//Toggle live edit
12902shortcut.add("Ctrl+Shift+L", function () {
12903	enableLiveEdit($.cookie("enableLiveEdit") === "false");
12904});
12905
12906//Toggle set heights
12907shortcut.add("Ctrl+Shift+S", function () {
12908	window.Core.performSetHeights = !window.Core.performSetHeights;
12909});
12910
12911//Toggle bundling
12912shortcut.add("Ctrl+Shift+A", function () {
12913	if (window.location.href.indexOf('bundle=on') > -1) {
12914		window.location.href = window.location.href.replace('bundle=on', 'bundle=off');
12915	} else if (window.location.href.indexOf('bundle=off') > -1) {
12916		window.location.href = window.location.href.replace('bundle=off', 'bundle=on');
12917	} else {
12918		var value = $('script[src="/Assets/Scripts/Shared.js"]').length == 0 ? 'off' : 'on';
12919		var connector = window.location.href.indexOf('?') > -1 ? '&' : '?';
12920		window.location.href = window.location.href + connector + 'bundle=' + value;
12921	}
12922});
12923
12924//Toggle mobile
12925shortcut.add("Ctrl+Shift+M", function () {
12926	if (window.location.href.indexOf('mobile=on') > -1) {
12927		window.location.href = window.location.href.replace('mobile=on', 'mobile=off');
12928	} else if (window.location.href.indexOf('mobile=off') > -1) {
12929		window.location.href = window.location.href.replace('mobile=off', 'mobile=on');
12930	} else {
12931		var value = $('body').hasClass('mobile') ? 'off' : 'on';
12932		var connector = window.location.href.indexOf('?') > -1 ? '&' : '?';
12933		window.location.href = window.location.href + connector + 'mobile=' + value;
12934	}
12935});
12936;
12937var needRegisterH5Exts = true;
12938var isAlreadyInitialized = false;
12939
12940// Only register the placeholder attachment code once, regardless of include count.
12941// File shouldn't be included more than once, but it could happen.
12942if (needRegisterH5Exts) {
12943	$(document).ready(function () {
12944		// Register placeholder shims, if needed.
12945		if (needPlaceHoldersShim() && !isAlreadyInitialized) {
12946		    isAlreadyInitialized = true;
12947
12948		    // Not all INPUTs/TEXTAREAs are automatically hooked into this,
12949			// since we have older implementations of placeholders and
12950			// overridding them would cause wierd behavior. Plus, it
12951			// would not make sense to hook to image/checkbox/radio/etc.
12952
12953			// The attribute cp5ph (CivicPlus HTML5 PlaceHolder) is automatically placed on inputs
12954			// with placeholders through the CPHtml5TextInput() HTML extension.
12955			registerPlaceHoldersShim($('input[cp5ph]'));
12956			registerPlaceHoldersShim($('textarea[cp5ph]'));
12957		}
12958	});
12959
12960	needRegisterH5Exts = false;
12961}
12962
12963// Registers placeholders on fields inside a specific context.
12964function registerPlaceHoldersShimOnContainer($container) {
12965	registerPlaceHoldersShim($('input[cp5ph]', $container));
12966	registerPlaceHoldersShim($('textarea[cp5ph]', $container));
12967}
12968
12969// Unregisters placeholders on fields inside a specific context.
12970function unregisterPlaceHoldersShimOnContainer($container) {
12971	unregisterPlaceHolderShim($('input[cp5ph]', $container));
12972	unregisterPlaceHolderShim($('textarea[cp5ph]', $container));
12973}
12974
12975// Determines if placeholder shim is necessary.
12976function needPlaceHoldersShim() {
12977	var tmpElem = document.createElement('input');
12978	return !('placeholder' in tmpElem);
12979}
12980
12981// Added due to a bug with IE 10's IE 7 document standards mode.  The elem.getAttribute('placeholder')
12982// always returns NULL if IE 10 in IE 7 document standards mode, but elem.attributes['placeholder'] 
12983// works.
12984function getPlaceholder(elem) {
12985    var placeholder = elem.getAttribute('placeholder')
12986    if (placeholder == null) {
12987        placeholder = elem.attributes['placeholder'];
12988        if (placeholder == null)
12989            return '';
12990        else
12991            return placeholder.value;
12992    }
12993    return placeholder;
12994}
12995
12996// Unregisters placeholder shim hooks. Destroys event hooks and spawned placeholder element.
12997function unregisterPlaceHolderShim($elemsToHack) {
12998	// Get hooks.
12999	var hookData = $elemsToHack.data('cp5ph_hooks');
13000
13001	if (hookData) {
13002		// Destroy all the hooks present.
13003		var attachedMSIE = hookData.ie == null ? [] : hookData.ie;
13004		var attachedSTD = hookData.std == null ? [] : hookData.std;
13005		var attachedJQR = hookData.jqr == null ? [] : hookData.jqr;
13006		var spawnedPHs = hookData.spawns == null ? [] : hookData.spawns;
13007		
13008		// Remove MSIE style events.
13009		for (var i = 0, len = attachedMSIE.length; i < len; i++) {
13010			if (attachedMSIE[i].element)
13011				attachedMSIE[i].element.detachEvent(attachedMSIE[i].event, attachedMSIE[i].method);
13012		}
13013
13014		// Remove DOM standard (STD) events.
13015		for (var i = 0, len = attachedSTD.length; i < len; i++) {
13016			if (attachedSTD[i].element)
13017				attachedSTD[i].element.removeEventListener(attachedSTD[i].event, attachedSTD[i].method, false);
13018		}
13019
13020		// Remove jQuery bindings.
13021		for (var i = 0, len = attachedJQR.length; i < len; i++) {
13022			if (attachedJQR[i].instance)
13023				attachedJQR[i].instance.unbind(attachedJQR[i].event, attachedJQR[i].method);
13024		}
13025		
13026		// Destroy placeholder spawned elements.
13027		for (var i = 0, len = spawnedPHs.length; i < len; i++) {
13028			if (spawnedPHs[i]) {
13029				spawnedPHs[i].innerHTML = "";
13030				spawnedPHs[i].style.display = "none";
13031
13032				if (spawnedPHs[i].parentNode)
13033					spawnedPHs[i].parentNode.removeChild(spawnedPHs[i]);
13034			}
13035		}
13036
13037		// Destroy hook data now that hooks have been cleaned.
13038		$elemsToHack.removeData('cp5ph_hooks');
13039	}
13040}
13041
13042// Registers placeholder shims for jQuery element group specified.
13043// The shim is by no means perfect (won't catch things like attribute selectors causing changes).
13044
13045function registerPlaceHoldersShim($elemsToHack) {
13046	// Track standard, MSIE, and jQuery event assignments so they can be cancelled/destroyed.
13047	// Also track any spawned placeholder elements since they too need to be cleaned up.
13048	var attachedMSIE = [];
13049	var attachedSTD = [];
13050	var attachedJQR = [];
13051	var spawnedPHs = [];
13052
13053	// Hooks programmatic changes to the value property for browsers without 
13054	// placeholder support. jQuery did not seem to have a way to do this.
13055	var hookProgrammaticValueChange = function(elem, callback) {
13056		// Note: Browsers are buggy at this time with DOMControlValueChanged.
13057
13058		// Handle Firefox Prior to 4 (which has built-in placeholder support).
13059		if (elem.__defineSetter__) {
13060			var oldSetter = elem.__lookupSetter__('value');
13061
13062			if (oldSetter) {
13063				elem.__defineSetter__('value', function(v) {
13064					oldSetter.call(elem, v);
13065					callback();
13066				});
13067			}
13068		}
13069
13070		// Handle IE, even up to IE 9.
13071		if (elem.attachEvent) {
13072			attachedMSIE.push({ element: elem, event: 'onpropertychange', method: callback });
13073			elem.attachEvent('onpropertychange', callback);
13074		}
13075	};
13076
13077	var displayAttrMatch = new RegExp('^(class|value|className|placeholder|id|style|style\\..*)$');
13078
13079	// Hooks display changes for an element (placeholder may need to update itself).
13080	var hookDisplayUpdates = function(elem, callback) {
13081		if (elem.addEventListener) {
13082			var domAttrModifiedHook = function(event) {
13083				// Prevents an infinite loop due to bubbling.
13084				event.stopPropagation();
13085
13086				// Another necessary escape hatch.
13087				if (event.target.className == '_ph_shim')
13088					return;
13089
13090				if (displayAttrMatch.test(event.attrName))
13091					callback(event.attrName);
13092			};
13093
13094			attachedSTD.push({ element: elem, event: 'DOMAttrModified', method: domAttrModifiedHook });
13095			elem.addEventListener('DOMAttrModified', domAttrModifiedHook, false);
13096		} else if (elem.attachEvent) {
13097			var propertyChangeHook = function(event) {
13098				if (displayAttrMatch.test(event.propertyName))
13099					callback(event.propertyName);
13100			};
13101
13102			attachedMSIE.push({ element: elem, event: 'onpropertychange', method: propertyChangeHook });
13103			elem.attachEvent('onpropertychange', propertyChangeHook);
13104		}
13105	};
13106
13107	// Hooks display changes for an element or its parents.
13108	var hookDisplayUpdatesAndParents = function(elem, callback) {
13109		var node = elem;
13110
13111		while (node && node != document.body) {
13112			hookDisplayUpdates(node, callback);
13113
13114			node = node.parentNode;
13115		}
13116	};
13117
13118	// Debouncer used to prevent the same placeholder updates from ocuring over and over again within a short time (30 ms).
13119	var debouncer = [];
13120	var isBouncy = function(element) {
13121		var now = function() {
13122			return new Date().getTime();
13123		};
13124		var getIndexOf = function(elem) {
13125			for (var i = 0; i < debouncer.length; i++) {
13126				if (debouncer[i].object === element) {
13127					return i;
13128				}
13129			}
13130			return -1;
13131		};
13132		var index = getIndexOf(element);
13133		if (index === -1) {
13134			var obj = { object: element, recentlyOccured: true };
13135			debouncer.push(obj);
13136			setTimeout(function () {
13137				obj.recentlyOccured = false;
13138			}
13139			,30);
13140			return false;
13141		} else if (debouncer[index].recentlyOccured) {
13142			return true;
13143		} else {
13144			debouncer[index].recentlyOccured = true;
13145			setTimeout(function () {
13146				debouncer[index].recentlyOccured = false;
13147			}
13148			, 30);
13149			return false;
13150		}
13151	};
13152
13153	// Updates position/style of pseudo-element that acts as placeholder message.
13154	// Called when necessary to ensure placeholder looks right (e.g. styles changed).
13155	var updatePlaceHolderMessageElement = function (phElem, elem) {
13156		var $elem = $(elem);
13157		if (isBouncy(elem)) {
13158			return;
13159		}
13160
13161		// TODO: Does $elem.is() not work if the element is not in the document?
13162		if (elem.parentNode != null && !elem._focus && $elem.is(':visible'))
13163			phElem.style.display = (elem.value == '' || elem.value == null ? 'block' : 'none');
13164		else {
13165			phElem.style.display = 'none';
13166			return;
13167		}
13168
13169		// Determine where placeholder element should go.
13170		var shouldParent = $elem.offsetParent().get(0);
13171
13172		// Placeholder element cannot go inside table rows, use cell instead.
13173		if (shouldParent.tagName == 'TR') {
13174			shouldParent = elem;
13175
13176			while (shouldParent.tagName != 'TD')
13177				shouldParent = shouldParent.parentNode;
13178		}
13179
13180		var phChanged = (phElem.getAttribute('_ph_val') != getPlaceholder(elem));
13181
13182		if ((shouldParent != phElem.parentNode) || phChanged) {
13183			// Remove from old parent (or existing, if phChanged).
13184			// Necessary for phChanged since element may be inside a table,
13185			// and trying to set innerHTML in a table with IE causes trouble.
13186			phElem.parentNode.removeChild(phElem);
13187
13188			// If placeholder changed, update innerHTML.
13189			if (phChanged)
13190			    $(phElem).text(getPlaceholder(elem));
13191
13192			// Ensure pseudo-placeholder is placed in same offsetParent
13193			// that element resides within (positioning), and add it to
13194			// the end (resolves some possible z-index issues).
13195			shouldParent.appendChild(phElem);
13196		}
13197
13198		phElem.style.width = elem.clientWidth + 'px';
13199		phElem.style.height = elem.clientHeight + 'px';
13200		phElem.style.verticalAlign = elem.style.verticalAlign;
13201		phElem.style.lineHeight = elem.style.lineHeight;
13202		phElem.style.textAlign = elem.style.textAlign;
13203		phElem.style.fontSize = elem.style.fontSize;
13204		phElem.style.fontFamily = elem.style.fontFamily;
13205
13206		var compStyle = (window.getComputedStyle ? window.getComputedStyle(elem, null) : elem.currentStyle);
13207		var elemPaddingLeft = parseInt(compStyle.paddingLeft.replace(/px$/g, ''), 10);
13208		var elemPaddingTop = parseInt(compStyle.paddingTop.replace(/px$/g, ''), 10);
13209		var pos = $elem.position();
13210
13211		phElem.style.top = (pos.top + elem.clientTop + elemPaddingTop 
13211- 2) + 'px';
13212		phElem.style.left = (pos.left + elem.clientLeft + elemPaddingLeft) + 'px';
13213	}
13214
13215	// Creates pseudo-element that acts as placeholder message.
13216	var createPlaceHolderMessageElement = function(elem) {
13217		// Create pseudo-placeholder that will appear over the top of the control.
13218		var phElem = document.createElement('div');
13219
13220		// Attach to element for reference.
13221		elem._ph_shim = phElem;
13222
13223		// Ensure pseudo-placeholder is placed in same offsetParent
13224		// that element resides within (positioning), and add it to
13225		// the end (resolves some possible z-index issues).
13226		var phValue = getPlaceholder(elem);
13227		$(phElem).text(phValue == null ? '' : phValue);
13228		phElem.setAttribute('_ph_val', 'phValue');
13229
13230		phElem.setAttribute('id', 'ph_' + elem.id);
13231		phElem.setAttribute('name', 'ph_' + elem.id);
13232
13233		var shouldParent = $(elem).offsetParent().get(0);
13234		shouldParent.appendChild(phElem);
13235
13236		// Configure the pseudo-placeholder.
13237		phElem.className = '_ph_shim';
13238		phElem.style.position = 'absolute';
13239		phElem.style.color = '#aaa'; // Placeholder Text Color.
13240		phElem.style.backgroundColor = 'transparent';
13241		phElem.style.cssFloat = 'none';
13242
13243		// Update appearance.
13244		updatePlaceHolderMessageElement(phElem, elem);
13245
13246		// Set up events for pseudo-placeholder and element.
13247		var $phElem = $(phElem);
13248
13249		var mouseDownHook = function(event) {
13250			phElem.style.display = 'none';
13251
13252			// Mouse down is passed to the input control
13253			// the placeholder is shown on top of.
13254			$(elem).trigger('mousedown', event);
13255
13256			// Hack: IE needs setTimeout to actually do this properly for TEXTAREA.
13257			setTimeout(function() {
13258				try {
13259					elem.focus()
13260				} catch(err) {
13261					//When the text box is readonly then the above focus code would throw error
13262					//so that error is only handled only for Center, if u happen to get this error please do ur implemntation below
13263					//NOTE: here we have checked only for /formcenter and so if there is any other place which uses readonly textbox and trys to focus also will get the same alert - This is known bug 
13264					//for DEtails talk to Akila or Robin - AK
13265
13266					//**Please note the use of lowercase here**
13267					var url = (location.href).toLowerCase();
13268
13269					if (url.indexOf("/admin/formcenter") > -1) {
13270						alert('You have selected the field input. Please select the field label or instructions.');
13271					}
13272				}
13273			}, 15);
13274		};
13275
13276		$phElem.mousedown(mouseDownHook);
13277
13278		attachedJQR.push({ instance: $phElem, event: 'mousedown', method: mouseDownHook });
13279
13280		return phElem;
13281	};
13282
13283	// Registers a shim placeholder for an element (private helper method).
13284	var registerPlaceHolder = function (elem) {
13285		// Create jQuery wrapper.
13286		var $elem = $(elem);
13287
13288		// Create placeholder.
13289		var phElem = createPlaceHolderMessageElement(elem);
13290
13291		// Track creation.
13292		spawnedPHs.push(phElem);
13293
13294		var focusHook = function () {
13295			// Older firefox does not support document.activeElement.
13296			elem._focus = true;
13297
13298			phElem.style.display = 'none';
13299		};
13300
13301		var blurHook = function () {
13302			// Older firefox does not support document.activeElement.
13303			elem._focus = false;
13304
13305			if ((elem.value == '' || elem.value == null) && $(elem).is(':visible'))
13306				phElem.style.display = 'block';
13307		};
13308
13309		$elem.focus(focusHook);
13310		$elem.blur(blurHook);
13311
13312		attachedJQR.push({ instance: $elem, event: 'focus', method: focusHook });
13313		attachedJQR.push({ instance: $elem, event: 'blur', method: blurHook });
13314
13315		// Ensure placeholder state is updated when the value
13316		// is changed programmatically.
13317		hookProgrammaticValueChange(elem, function () {
13318			if (elem._focus)
13319				phElem.style.display = 'none';
13320			else {
13321				if ((elem.value == '' || elem.value == null) && $(elem).is(':visible'))
13322					phElem.style.display = 'block';
13323				else
13324					phElem.style.display = 'none';
13325			}
13326		});
13327
13328		// Ensure placeholder UI updates correctly when display changes are made.
13329		hookDisplayUpdatesAndParents(elem, function () {
13330			updatePlaceHolderMessageElement(phElem, elem);
13331		});
13332	};
13333
13334	// Attach shim to each wrapped element passed to the method.
13335	$elemsToHack.each(function () {
13336		registerPlaceHolder(this);
13337	});
13338
13339	// Keep track of hooks so they can be destroyed.
13340	$elemsToHack.data('cp5ph_hooks', {
13341		ie: attachedMSIE,
13342		std: attachedSTD,
13343		jqr: attachedJQR,
13344		spawns: spawnedPHs 
13345	});
13346}
13347
13348
13349// Unregisters placeholder shim hooks. Destroys event hooks and spawned placeholder element.
13350function unregisterPlaceHoldersShimForEach($elemsToHack) {
13351	// Get hooks.
13352	$elemsToHack.each(function () {
13353		var hookData = $(this).data('cp5ph_hooks');
13354
13355		if (hookData) {
13356			// Destroy all the hooks present.
13357			var attachedMSIE = hookData.ie == null ? [] : hookData.ie;
13358			var attachedSTD = hookData.std == null ? [] : hookData.std;
13359			var attachedJQR = hookData.jqr == null ? [] : hookData.jqr;
13360			var spawnedPHs = hookData.spawns == null ? [] : hookData.spawns;
13361
13362			// Remove MSIE style events.
13363			for (var i = 0, len = attachedMSIE.length; i < len; i++) {
13364				if (attachedMSIE[i].element)
13365					attachedMSIE[i].element.detachEvent(attachedMSIE[i].event, attachedMSIE[i].method);
13366			}
13367
13368			// Remove DOM standard (STD) events.
13369			for (var i = 0, len = attachedSTD.length; i < len; i++) {
13370				if (attachedSTD[i].element)
13371					attachedSTD[i].element.removeEventListener(attachedSTD[i].event, attachedSTD[i].method, false);
13372			}
13373
13374			// Remove jQuery bindings.
13375			for (var i = 0, len = attachedJQR.length; i < len; i++) {
13376				if (attachedJQR[i].instance)
13377					attachedJQR[i].instance.unbind(attachedJQR[i].event, attachedJQR[i].method);
13378			}
13379
13380			// Destroy placeholder spawned elements.
13381			for (var i = 0, len = spawnedPHs.length; i < len; i++) {
13382				if (spawnedPHs[i]) {
13383					spawnedPHs[i].innerHTML = "";
13384					spawnedPHs[i].style.display = "none";
13385
13386					if (spawnedPHs[i].parentNode)
13387						spawnedPHs[i].parentNode.removeChild(spawnedPHs[i]);
13388				}
13389			}
13390
13391			// Destroy hook data now that hooks have been cleaned.
13392			$(this).removeData('cp5ph_hooks');
13393		}
13394	});
13395}
13396
13397// Registers placeholder shims for jQuery element group specified.
13398// The shim is by no means perfect (won't catch things like attribute selectors causing changes).
13399function registerPlaceHoldersShimForEach($elemsToHack) {
13400	// Track standard, MSIE, and jQuery event assignments so they can be cancelled/destroyed.
13401	// Also track any spawned placeholder elements since they too need to be cleaned up.
13402	var attachedMSIE = [];
13403	var attachedSTD = [];
13404	var attachedJQR = [];
13405	var spawnedPHs = [];
13406
13407	// Hooks programmatic changes to the value property for browsers without 
13408	// placeholder support. jQuery did not seem to have a way to do this.
13409	var hookProgrammaticValueChange = function (elem, callback) {
13410		// Note: Browsers are buggy at this time with DOMControlValueChanged.
13411
13412		// Handle Firefox Prior to 4 (which has built-in placeholder support).
13413		if (elem.__defineSetter__) {
13414			var oldSetter = elem.__lookupSetter__('value');
13415
13416			if (oldSetter) {
13417				elem.__defineSetter__('value', function (v) {
13418					oldSetter.call(elem, v);
13419					callback();
13420				});
13421			}
13422		}
13423
13424		// Handle IE, even up to IE 9.
13425		if (elem.attachEvent) {
13426			attachedMSIE.push({ element: elem, event: 'onpropertychange', method: callback });
13427			elem.attachEvent('onpropertychange', callback);
13428		}
13429	};
13430
13431	var displayAttrMatch = new RegExp('^(class|value|className|placeholder|id|style|style\\..*)$');
13432
13433	// Hooks display changes for an element (placeholder may need to update itself).
13434	var hookDisplayUpdates = function (elem, callback) {
13435		if (elem.addEventListener) {
13436			var domAttrModifiedHook = function (event) {
13437				// Prevents an infinite loop due to bubbling.
13438				event.stopPropagation();
13439
13440				// Another necessary escape hatch.
13441				if (event.target.className == '_ph_shim')
13442					return;
13443
13444				if (displayAttrMatch.test(event.attrName))
13445					callback(event.attrName);
13446			};
13447
13448			attachedSTD.push({ element: elem, event: 'DOMAttrModified', method: domAttrModifiedHook });
13449			elem.addEventListener('DOMAttrModified', domAttrModifiedHook, false);
13450		}
13451		else if (elem.attachEvent) {
13452			var propertyChangeHook = function (event) {
13453				if (displayAttrMatch.test(event.propertyName))
13454					callback(event.propertyName);
13455			};
13456
13457			attachedMSIE.push({ element: elem, event: 'onpropertychange', method: propertyChangeHook });
13458			elem.attachEvent('onpropertychange', propertyChangeHook);
13459		}
13460	};
13461
13462	// Hooks display changes for an element or its parents.
13463	var hookDisplayUpdatesAndParents = function (elem, callback) {
13464		var node = elem;
13465
13466		while (node && node != document.body) {
13467			hookDisplayUpdates(node, callback);
13468
13469			node = node.parentNode;
13470		}
13471	};
13472
13473	// Updates position/style of pseudo-element that acts as placeholder message.
13474	// Called when necessary to ensure placeholder looks right (e.g. styles changed).
13475	var updatePlaceHolderMessageElement = function (phElem, elem) {
13476		var $elem = $(elem);
13477
13478		// TODO: Does $elem.is() not work if the element is not in the document?
13479		if (elem.parentNode != null && !elem._focus && $elem.is(':visible'))
13480			phElem.style.display = (elem.value == '' || elem.value == null ? 'block' : 'none');
13481		else {
13482			phElem.style.display = 'none';
13483			return;
13484		}
13485
13486		// Determine where placeholder element should go.
13487		var shouldParent = $elem.offsetParent().get(0);
13488
13489		// Placeholder element cannot go inside table rows, use cell instead.
13490		if (shouldParent.tagName == 'TR') {
13491			shouldParent = elem;
13492
13493			while (shouldParent.tagName != 'TD')
13494				shouldParent = shouldParent.parentNode;
13495		}
13496
13497		var phChanged = (phElem.getAttribute('_ph_val') != getPlaceholder(elem));
13498
13499		if ((shouldParent != phElem.parentNode) || phChanged) {
13500			// Remove from old parent (or existing, if phChanged).
13501			// Necessary for phChanged since element may be inside a table,
13502			// and trying to set innerHTML in a table with IE causes trouble.
13503			phElem.parentNode.removeChild(phElem);
13504
13505			// If placeholder changed, update innerHTML.
13506			if (phChanged)
13507				$(phElem).text(getPlaceholder(elem));
13508
13509			// Ensure pseudo-placeholder is placed in same offsetParent
13510			// that element resides within (positioning), and add it to
13511			// the end (resolves some possible z-index issues).
13512			shouldParent.appendChild(phElem);
13513		}
13514
13515		phElem.style.width = elem.clientWidth + 'px';
13516		phElem.style.height = elem.clientHeight + 'px';
13517		phElem.style.verticalAlign = elem.style.verticalAlign;
13518		phElem.style.lineHeight = elem.style.lineHeight;
13519		phElem.style.textAlign = elem.style.textAlign;
13520		phElem.style.fontSize = elem.style.fontSize;
13521		phElem.style.fontFamily = elem.style.fontFamily;
13522
13523		var compStyle = (window.getComputedStyle ? window.getComputedStyle(elem, null) : elem.currentStyle);
13524		var elemPaddingLeft = parseInt(compStyle.paddingLeft.replace(/px$/g, ''), 10);
13525		var elemPaddingTop = parseInt(compStyle.paddingTop.replace(/px$/g, ''), 10);
13526		var pos = $elem.position();
13527
13528		phElem.style.top = (pos.top + elem.clientTop + elemPaddingTop - 2) + 'px';
13529		phElem.style.left = (pos.left + elem.clientLeft + elemPaddingLeft) + 'px';
13530	}
13531
13532	// Creates pseudo-element that acts as placeholder message.
13533	var createPlaceHolderMessageElement = function (elem) {
13534		// Create pseudo-placeholder that will appear over the top of the control.
13535		var phElem = document.createElement('div');
13536
13537		// Attach to element for reference.
13538		elem._ph_shim = phElem;
13539
13540		// Ensure pseudo-placeholder is placed in same offsetParent
13541		// that element resides within (positioning), and add it to
13542		// the end (resolves some possible z-index issues).
13543		var phValue = getPlaceholder(elem);
13544		$(phElem).text(phValue == null ? '' : phValue);
13545		phElem.setAttribute('_ph_val', 'phValue');
13546
13547		phElem.setAttribute('id', 'ph_' + elem.id);
13548		phElem.setAttribute('name', 'ph_' + elem.id);
13549
13550		var shouldParent = $(elem).offsetParent().get(0);
13551		shouldParent.appendChild(phElem);
13552
13553		// Configure the pseudo-placeholder.
13554		phElem.className = '_ph_shim';
13555		phElem.style.position = 'absolute';
13556		phElem.style.color = '#aaa'; // Placeholder Text Color.
13557		phElem.style.backgroundColor = 'transparent';
13558		phElem.style.cssFloat = 'none';
13559
13560		// Update appearance.
13561		updatePlaceHolderMessageElement(phElem, elem);
13562
13563		// Set up events for pseudo-placeholder and element.
13564		var $phElem = $(phElem);
13565
13566		var mouseDownHook = function (event) {
13567			phElem.style.display = 'none';
13568
13569			// Mouse down is passed to the input control
13570			// the placeholder is shown on top of.
13571			$(elem).trigger('mousedown', event);
13572
13573			// Hack: IE needs setTimeout to actually do this properly for TEXTAREA.
13574			setTimeout(function () {
13575				try { elem.focus() } catch (err) {
13576					//When the text box is readonly then the above focus code would throw error
13577					//so that error is only handled only for Center, if u happen to get this error please do ur implemntation below
13578					//NOTE: here we have checked only for /formcenter and so if there is any other place which uses readonly textbox and trys to focus also will get the same alert - This is known bug 
13579					//for DEtails talk to Akila or Robin - AK
13580
13581					//**Please note the use of lowercase here**
13582					var url = (location.href).toLowerCase();
13583
13584					if (url.indexOf("/admin/formcenter") > -1) {
13585						alert('You have selected the field input. Please select the field label or instructions.');
13586					}
13587				}
13588			}, 15);
13589		};
13590
13591		$phElem.mousedown(mouseDownHook);
13592
13593		attachedJQR.push({ instance: $phElem, event: 'mousedown', method: mouseDownHook });
13594
13595		return phElem;
13596	}
13597
13598	// Registers a shim placeholder for an element (private helper method).
13599	var registerPlaceHolder = function (elem) {
13600		// Create jQuery wrapper.
13601		var $elem = $(elem);
13602
13603		// Create placeholder.
13604		var phElem = createPlaceHolderMessageElement(elem);
13605
13606		// Track creation.
13607		spawnedPHs.push(phElem);
13608
13609		var focusHook = function () {
13610			// Older firefox does not support document.activeElement.
13611			elem._focus = true;
13612
13613			phElem.style.display = 'none';
13614		};
13615
13616		var blurHook = function () {
13617			// Older firefox does not support document.activeElement.
13618			elem._focus = false;
13619
13620			if ((elem.value == '' || elem.value == null) && $(elem).is(':visible'))
13621				phElem.style.display = 'block';
13622		};
13623
13624		$elem.focus(focusHook);
13625		$elem.blur(blurHook);
13626
13627		attachedJQR.push({ instance: $elem, event: 'focus', method: focusHook });
13628		attachedJQR.push({ instance: $elem, event: 'blur', method: blurHook });
13629
13630		// Ensure placeholder state is updated when the value
13631		// is changed programmatically.
13632		hookProgrammaticValueChange(elem, function () {
13633			if (elem._focus)
13634				phElem.style.display = 'none';
13635			else {
13636				if ((elem.value == '' || elem.value == null) && $(elem).is(':visible'))
13637					phElem.style.display = 'block';
13638				else
13639					phElem.style.display = 'none';
13640			}
13641		});
13642
13643		// Ensure placeholder UI updates correctly when display changes are made.
13644		hookDisplayUpdatesAndParents(elem, function () {
13645			updatePlaceHolderMessageElement(phElem, elem);
13646		});
13647	};
13648
13649	// Attach shim to each wrapped element passed to the method.
13650	$elemsToHack.each(function () {
13651		registerPlaceHolder(this);
13652	});
13653
13654	// Keep track of hooks so they can be destroyed.
13655	$elemsToHack.each(function() {
13656		$(this).data('cp5ph_hooks', {
13657			ie: attachedMSIE,
13658			std: attachedSTD,
13659			jqr: attachedJQR,
13660			spawns: spawnedPHs
13661			});
13662	});
13663}
13664;
13665

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