/* Minification failed. Returning unminified contents.
(7144,733-734): run-time error JS1005: Expected '(': {
(7144,735-736): run-time error JS1006: Expected ')': }
(7144,735-736): run-time error JS1008: Expected '{': }
(7144,686-699): run-time error JS1301: End of file encountered before function is properly closed: function(n,t)
(17024,1): run-time error JS1107: Expecting more source characters
(7144,87-100): run-time error JS1301: End of file encountered before function is properly closed: function(n,t)
(17024,1): run-time error JS1107: Expecting more source characters
 */
window.CivicWeb=window.CivicWeb||{};window.CivicWeb.Common=window.CivicWeb.Common||{},function(n,t){var f="attachment-update",a=f+"-description",w=f+"-change",h=f+"-default-folder",b=h+"-label",v=f+"-attachments",nt=f+"-update",tt=f+"-cancel",y=f+"-update-notification",p=f+"-overlay",u="attachment-update",r,s,e,k=!1,o,c,l,d,i,it=function(n){var u=t(n.target).closest("button"),f=CivicWeb.Common.Button.update(u,r.buttonUpdatingAttachments,!0,!0),h;u.tooltip("destroy");h=CivicWeb.Common.Notification.hide(y);t.ajax({url:"/api/item/"+c+"/moveandupdateattachments",contentType:"application/json",dataType:"json",async:!0,type:"POST",data:JSON.stringify({pathId:i.defaultPathId,path:i.defaultPath})}).done(function(){CivicWeb.Common.Notification.show(h,CivicWeb.Common.Notification.types.success,r.notificationAttachmentUpdateSucceeded,!0);CivicWeb.Common.Button.update(u,f,!0,!1);"function"==typeof s&&s();setTimeout(function(){o.data("kendoWindow").close();CivicWeb.Common.Button.update(u,f,!1,!1);u.tooltip();typeof e=="function"&&e()},3e3)}).fail(function(){CivicWeb.Common.Notification.show(h,CivicWeb.Common.Notification.types.failure,r.notificationAttachmentUpdateFailed,!0);CivicWeb.Common.Button.update(u,f,!1,!1);u.tooltip()});n.preventDefault()},rt=function(n){o.data("kendoWindow").close();n.preventDefault();typeof e=="function"&&e()},ut=function(){return i=null,t.ajax({url:"/api/item/"+c+"/attachmentinformation?showattachments=true&showDefaultPath=true&closed="+l,contentType:"application/json",dataType:"json",async:!0,type:"GET"}).done(function(n){i=n})},g=function(){var s,n;i.updateAllowed&&i.attachments.length>0&&(i.defaultPathId===null||"undefined"!=typeof i.attachments.find(function(n){return n.parentId!==i.defaultPathId}))?CivicWeb.Common.loadKendoUi(g)?(t(document.getElementById(p)).remove(),o||(t("body").append(o=t("<div><\/div>").attr({id:f,"class":"hidden"}).append(t("<div><\/div>").addClass(u).append(t("<div><\/div>").addClass(u+"-section").append(t("<div><\/div>").append(t("<label><\/label>").attr({"for":a}).text(r.formFieldLabelItem))).append(t("<div><\/div>").attr({id:a,"class":u+"-description"}))).append(t("<div><\/div>").addClass(u+"-section").append(CivicWeb.Common.Notification.create(w,CivicWeb.Common.Notification.types.instruction,"",!1))).append(t("<div><\/div>").addClass(u+"-section").append(t("<div><\/div>").append(t("<label><\/label>").attr({id:b,"for":h}))).append(t("<div><\/div>").attr({id:h,"class":u+"-path"}))).append(t("<div><\/div>").addClass(u+"-section").append(t("<div><\/div>").append(t("<label><\/label>").attr({"for":v}).text(r.formFieldLabelAttachments))).append(t("<div><\/div>").append(t("<ol><\/ol>").attr({id:v,"class":u+"-attachments clean"})))).append(t("<div><\/div>").attr({"class":u+"-section button-row"}).append(CivicWeb.Common.Button.create(nt,r.buttonUpdateAttachmentsLocationAndPermissions,r.toolTipUpdateAttachmentsLocationAndPermissions,CivicWeb.Common.Button.types.important).on("click",it)).append(CivicWeb.Common.Button.create(tt,r.buttonMakeNoChanges,r.toolTipMakeNoChangesToAttachmentLocationAndPermissions).on("click",rt))).append(t("<div><\/div>").addClass(u+"-section").append(CivicWeb.Common.Notification.create(y,CivicWeb.Common.Notification.types.instruction,"",!0))))),o.kendoWindow({width:"800px",modal:!0,visible:!1,title:r.titleUpdateAttachments}),o.css({padding:"0",overflow:"initial"}),o.find("[title]").tooltip(),o.data("kendoWindow").center()),t(document.getElementById(a)).html(d),CivicWeb.Common.Notification.show(w,CivicWeb.Common.Notification.types.instruction,l?r.instructionNotClosedToClosedItemWithAttachments:r.instructionClosedToNotClosedItemWithAttachments,!0,!1),t(document.getElementById(b)).text(l?r.formFieldLabelClosedAttachmentsFolder:r.formFieldLabelOpenAttachmentsFolder),s=t(document.getElementById(h)).empty().append(t("<span><\/span>",{"class":"folder-image cw-icon-folder-lg",title:r.toolTipFolder})).append(i.defaultPathExistingPath?t("<a><\/a>").attr({href:"/filepro/documents/"+i.defaultPathExistingFolderId,target:"_blank"}).text(i.defaultPathExistingPath):null).append(i.defaultPathRemainingPath?t("<span><\/span>").text(i.defaultPathRemainingPath):null).append(t("<a><\/a>").attr({href:i.defaultPathExistingFolderId?"/filepro/document/"+i.defaultPathExistingFolderId+"?tab=security":"/filepro/document/ensureexists?path="+encodeURIComponent(i.defaultPath),target:"_blank","class":"undecorated"}).append(t("<span><\/span>").addClass(u+"-permission-label label label-"+(i.defaultPathIsPublic?"success":"danger")).append(t("<span><\/span>").addClass("cw-icon-folder-"+(i.defaultPathIsPublic?"permit":"forbid"))).append(t("<span><\/span>").text(i.defaultPathIsPublic?r.labelPublic:r.labelPrivate)))),s.find("[title]").tooltip(),n=t(document.getElementById(v)).empty(),i.attachments.forEach(function(i){var e=i.extension.replace(".",""),f=i.isPublic;n.append(t("<li><\/li>").addClass(u+"-path").append(t("<span><\/span>",{"class":CivicWeb.Common.getFileIconClass(e),title:e.toUpperCase()})).append(t("<a><\/a>").attr({href:"/filepro/documents/"+i.id,target:"_blank"}).text(i.name)).append(t("<a><\/a>").attr({href:"/filepro/document/"+i.id+"?tab=security",target:"_blank","class":"undecorated"}).append(t("<span><\/span>").addClass(u+"-permission-label label label-"+(f?"success":"danger")).append(t("<span><\/span>").addClass("cw-icon-folder-"+(f?"permit":"forbid"))).append(t("<span><\/span>").text(f?r.labelPublic:r.labelPrivate)))))}),n.find("[title]").tooltip(),CivicWeb.Common.Notification.hide(y),o.removeClass("hidden").css({visibility:""}).data("kendoWindow").open()):t("body").append(t("<div><\/div>").attr({id:p,"class":"overlay-all"}).append(t("<div><\/div>").addClass("overlay-content").append(t("<span><\/span>").attr({"class":"overlay-throbber"}).append(CivicWeb.Common.Button.getThrobber(p+"-throbber"))))):typeof e=="function"&&e()};n.load=function(n){r=n.localization;s=n.afterUpdate;e=n.afterUpdatePath;k=!0};n.show=function(n){k?(c=n.itemId,l=n.closed,d=n.description,s="undefined"!=typeof n.afterUpdate?n.afterUpdate:s,e="undefined"!=typeof n.afterUpdatePath?n.afterUpdatePath:e,c>0&&ut().then(g)):console.log("Attachment Update control not loaded.")}}(window.CivicWeb.Common.AttachmentUpdate=window.CivicWeb.Common.AttachmentUpdate||{},jQuery);;
window.CivicWeb = window.CivicWeb || {};
window.CivicWeb.Common = window.CivicWeb.Common || {};

(function (library, $)
{
	//Properties
	var instances = [];

	//Classes
	// ReSharper disable once InconsistentNaming
	var Control = function (id, args)
	{
		var clientId = id;
		var newAttachmentsClientId = clientId + '-new-attachments';
		var locationSummaryClientId = clientId + '-location-summary';
		var selectFromDocumentCenterClientId = clientId + '-select-from-document-center';
		var documentCenterSelectorClientId = clientId + '-document-center-location-selector';
		var locationDetailsClientId = clientId + '-location-details';
		var pathClientId = clientId + '-path';
		var locationDetailsPermissionLabelClientId = clientId + '-location-details-permission-label';
		var locationSelectClientId = clientId + '-location-select';
		var locationSelectorClientId = clientId + '-location-selector';
		var noAccessNotificationClientId = clientId + '-no-access-notification';
		var permissionsClientId = clientId + '-permissions';
		var itemPermissionLabelClientId = clientId + '-item-permission-label';
		var potentialRecordClientId = clientId + '-potential-record';
		var classifyRecordClientId = clientId + '-classify-record';
		var dropTargetClientId = clientId + '-drop-target';
		var fileClientId = clientId + '-file';
		var attachmentsListClientId = clientId + '-attachments-list';
		var includeAllClientId = clientId + '-include-all';
		var includeClientId = clientId + '-include-';
		var linkClientId = clientId + '-link-';
		var attachmentPermissionClientId = clientId + '-attachment-permission-';
		var nameClientId = clientId + '-name-';
		var updateClientId = clientId + '-update-';
		var renameClientId = clientId + '-rename-';

		var localization = args.localization;
		var confirmationPopupLocalization = args.confirmationPopupLocalization;
		var attachmentUpdateLocalization = args.attachmentUpdateLocalization;

		var editable = args.editable;
		var itemId = args.itemId;
		var changeSetId = args.changeSetId;
		var closed = args.closed;
		var description = args.description;
		var itemIsPublic = args.itemIsPublic;
		var documentSelectorArguments = args.documentSelectorArguments;
		var contactAdministratorArguments = args.contactAdministratorArguments;
		var jumpTo = !!args.jumpTo;

		var updateList = args.updateList;
		var change = args.change;

		var loadPromise = $.Deferred().resolve();
		var pathId;
		var path;
		var pathUpdateAllowed;
		var pathIsPublic;
		var existingPathId;
		var existingPath;
		var remainingPath;
		var useItemPermissions = false;
		var attachments = [];
		var newAttachments = [];
		var removedAttachments = [];
		var replacementId = 0;

		//Event Handlers
		var locationSummaryClick = function ()
		{
			$(document.getElementById(locationDetailsClientId)).toggleClass('hidden');
		};

		var documentCenterOpen = function (sender)
		{
			sender.setCustomNodes(attachments.map(function (attachment)
			{
				return attachment.id;
			}), 'cw-icon-attachment-check', localization.toolTipAttached);
		};

		var documentCenterSelect = function (e)
		{
			if (!e.folder)
			{
				var attachment = findAttachment(e.id);
				if (!attachment)
				{
					e.sender.startThrobber(e.node, localization.toolTipAttaching);

					addAttachment(e.id).then(function ()
					{
						e.sender.endThrobber(e.node);

						e.sender.addCustomNode({ id: e.id });
					});
				}
			}
		};

		var thirdPartyOpen = function (sender)
		{
			var provider = sender.getProvider().toLowerCase();
			sender.setCustomNodes(attachments.filter(function (attachment)
			{
				return attachment.thirdPartyType.toLowerCase() === provider;
			}).map(function (attachment)
			{
				return attachment.id;
			}), 'cw-icon-attachment-check', localization.toolTipAttached);
		};

		var thirdPartySelect = function (e)
		{
			if (!e.folder)
			{
				e.sender.startThrobber(e.node, localization.toolTipAttaching);

				addAttachment(e.id, e.title, e.provider).then(function ()
				{
					e.sender.close();

					e.sender.endThrobber(e.node);

					e.sender.addCustomNode({ id: e.id });
				});
			}
		};

		var locationSelect = function (e)
		{
			existingPathId = pathId = e.id;
			existingPath = path = e.path;
			pathIsPublic = e.itemData.IsPublic;
			pathUpdateAllowed = e.itemData.UpdateAllowed;

			generatePermissionLabel(locationSummaryClientId, !useItemPermissions ? pathIsPublic : itemIsPublic);
			generatePathLink();
			generatePermissionLabel(locationDetailsPermissionLabelClientId, pathIsPublic);
			checkPathAccess();

			e.close = true;
		};

		var permissionsContactAdministratorButtonClick = function (e)
		{
			CivicWeb.Common.ContactAdministrator.load({ isPermissions: contactAdministratorArguments.isPermissions, documentId: existingPathId, path: existingPath, localization: contactAdministratorArguments.localization, kendoEditorLocalization: contactAdministratorArguments.kendoEditorLocalization, reload: true });

			e.preventDefault();
		};

		var permissionsClick = function ()
		{
			useItemPermissions = CivicWeb.Common.toNumber($(document.getElementById(permissionsClientId)).find('input[type="radio"]:checked').val()) === 2;
			$(document.getElementById(itemPermissionLabelClientId)).toggleClass('hidden', !useItemPermissions);

			generatePermissionLabel(locationSummaryClientId, !useItemPermissions ? pathIsPublic : itemIsPublic);
		};

		var dropTargetClick = function ()
		{
			$(document.getElementById(fileClientId)).click();
		};

		var dropTargetDragOver = function (e)
		{
			e.preventDefault();
		};

		var dropTargetDrop = function (e)
		{
			e.preventDefault();

			if (e.originalEvent.dataTransfer.items)
			{
				// Use DataTransferItemList interface to access the file(s)
				var files = [];
				for (var i = 0; i < e.originalEvent.dataTransfer.items.length; i++)
				{
					// If dropped items aren't files, reject them
					if (e.originalEvent.dataTransfer.items[i].kind === 'file')
					{
						files.push(e.originalEvent.dataTransfer.items[i].getAsFile());
					}
				}

				uploadAttachments(files);
			}
			else
			{
				uploadAttachments(e.originalEvent.dataTransfer.files.length);
			}

			//Cleanup
			loadPromise.then(function ()
			{
				if (e.originalEvent.dataTransfer.items)
				{
					// Use DataTransferItemList interface to remove the drag data
					e.originalEvent.dataTransfer.items.clear();
				}
				else
				{
					// Use DataTransfer interface to remove the drag data
					e.originalEvent.dataTransfer.clearData();
				}
			});
		};

		var fileChange = function ()
		{
			uploadAttachments();
		};

		var includeAllClick = function (e)
		{
			var includeAll = $(e.target).prop('checked');
			$(document.getElementById(attachmentsListClientId)).find('input[id^="' + includeClientId + '"]').prop('checked', includeAll);

			attachments.forEach(function (attachment)
			{
				attachment.include = includeAll;
			});

			setChanged(true);
		};

		var attachmentDrag = function (e)
		{
			var dropTarget = $(document.elementsFromPoint(e.pageX, e.pageY)).filter(':not([data-drag])').first();
			dropTarget = dropTarget.closest('tr');
			var row = dropTarget.parent().children().index(dropTarget);
			var tbody = dropTarget.closest('tbody');
			var list = tbody.closest('div[id="' + attachmentsListClientId + '"');
			var overList = replacementId === 0 && row > 0 && tbody.length === 1 && list.length === 1;

			var target = $('.k-drag-clue[data-row]');
			target.find('.k-icon').attr({ 'class': 'k-icon ' + (overList ? 'k-i-add' : 'k-i-cancel') });

			if (overList)
			{
				var overTopHalf = e.pageY < (dropTarget.offset().top + (dropTarget.height() / 2));
				row = row + (overTopHalf ? -1 : 0);

				//Add placeholder row
				tbody.find('[data-placeholder]').remove();
				tbody.insertAt(row + 1, $('<tr></tr>').attr({ 'data-placeholder': true })
					.append($('<td></td>').attr({ 'colspan': editable ? 5 : 8 }).html('&nbsp;')));
			}
			else
			{
				list.find('[data-placeholder]').remove();
			}
		};

		var attachmentDragEnd = function (e)
		{
			var dropTarget = $(document.elementsFromPoint(e.pageX, e.pageY)).filter(':not([data-drag])').first();
			dropTarget = dropTarget.closest('tr');
			var row = dropTarget.parent().children().index(dropTarget);
			var tbody = dropTarget.closest('tbody');
			var list = tbody.closest('div[id="' + attachmentsListClientId + '"');
			var overList = row > 0 && tbody.length === 1 && list.length === 1;

			var target = $('.k-drag-clue[data-row]');
			var oldIndex = Math.max(CivicWeb.Common.toNumber(target.attr('data-row')) - 1, 0);

			var placeholder = tbody.find('tr[data-placeholder]');
			var newIndex = placeholder.parent().children().index(placeholder) - 1;
			if (newIndex > oldIndex)
			{
				newIndex--;
			}

			list.find('[data-placeholder]').remove();

			if (overList)
			{
				//Remove from current position
				var attachment = attachments.splice(oldIndex, 1);
				var movedRow = tbody.find('tr:eq(' + (oldIndex + 1) + ')').detach();

				//Add to new position
				attachments.splice(newIndex, 0, attachment[0]);
				tbody.find('tr:eq(' + newIndex + ')').after(movedRow);
			}

			setChanged(true);
		};

		var includeClick = function (e)
		{
			var checkBox = $(e.target);
			var attachmentId = CivicWeb.Common.toNumber(checkBox.attr('data-id'));
			var attachment = findAttachment(attachmentId);
			if (attachment)
			{
				attachment.include = checkBox.prop('checked');
			}

			$(document.getElementById(includeAllClientId)).prop('checked', attachments.every(function (attachment) { return attachment.include; }));

			setChanged(true);
		};

		var updateClick = function (e)
		{
			var attachmentId = CivicWeb.Common.toNumber($(e.target).attr('data-id'));

			var link = $(document.getElementById(linkClientId + attachmentId)).removeClass('hidden');
			$(document.getElementById(attachmentPermissionClientId + attachmentId)).removeClass('hidden');
			var nameInput = $(document.getElementById(nameClientId + attachmentId)).addClass('hidden');
			$(document.getElementById(updateClientId + attachmentId)).addClass('hidden');
			$(document.getElementById(renameClientId + attachmentId)).removeAttr('data-renaming').text(localization.buttonRename);

			var name = nameInput.val() || '';
			var attachment = findAttachment(attachmentId);
			if (attachment)
			{
				if (name.length > 0)
				{
					attachment.name = name;
					link.text(name);

					setChanged(true);
				}
				else
				{
					nameInput.val(attachment.name);
				}
			}
		};

		var renameClick = function (e)
		{
			var rename = $(e.target);
			var attachmentId = CivicWeb.Common.toNumber(rename.attr('data-id'));
			var renaming = rename.filter('[data-renaming]').length === 1;

			rename.text(renaming ? localization.buttonRename : localization.buttonUndo);
			$(document.getElementById(linkClientId + attachmentId)).toggleClass('hidden', !renaming);
			$(document.getElementById(attachmentPermissionClientId + attachmentId)).toggleClass('hidden', !renaming);
			var nameInput = $(document.getElementById(nameClientId + attachmentId)).toggleClass('hidden', renaming);
			$(document.getElementById(updateClientId + attachmentId)).toggleClass('hidden', renaming);

			if (renaming)
			{
				//Undo
				rename.removeAttr('data-renaming');

				var attachment = findAttachment(attachmentId);
				if (attachment)
				{
					nameInput.val(attachment.name);
				}
			}
			else
			{
				rename.attr({ 'data-renaming': true });
			}

			e.preventDefault();
		};

		var replaceClick = function (e)
		{
			var button = $(e.target);

			replacementId = replacementId > 0 ? 0 : CivicWeb.Common.toNumber(button.attr('data-id'));

			toggleReplacement(button);

			e.preventDefault();
		};

		var removeClick = function (e)
		{
			var button = $(e.target);
			var attachmentId = CivicWeb.Common.toNumber(button.attr('data-id'));
			var index = removedAttachments.findIndex(function (id)
			{
				return id === attachmentId;
			});
			var removed = index >= 0;
			var attachment = findAttachment(attachmentId);

			button.text(!removed ? localization.buttonUndoRemoval : localization.buttonRemove);
			button.closest('tr').find('td.attachments-document-name a').toggleClass('attachments-removed', !removed);

			var content;
			if (!removed)
			{
				removedAttachments.push(attachmentId);
				setChanged(true);

				if (attachment.deleteAllowed && attachment.itemsAttachedTo <= 1)
				{
					content = $('<div></div>')
						.append(CivicWeb.Common.Notification.create('attachment-delete-notification', CivicWeb.Common.Notification.types.instruction, localization.notificationDoYouWantToDeleteThisAttachment, false, false));

					window.CivicWeb.Common.Confirmation.open(content, true, { title: localization.titleDeleteThisAttachment, width: 500, height: 250, localization: confirmationPopupLocalization }, generateDeleteAttachmentCallback(attachment, false));
				}
			}
			else
			{
				removedAttachments.splice(index, 1);

				if (attachment.deleteAllowed && attachment.deleted)
				{
					content = $('<div></div>')
						.append(CivicWeb.Common.Notification.create('attachment-restore-notification', CivicWeb.Common.Notification.types.instruction, localization.notificationDoYouWantToRestoreThisAttachment, false, false));

					window.CivicWeb.Common.Confirmation.open(content, true, { title: localization.titleRestoreThisAttachment, width: 500, height: 250, localization: localization.confirmationPopupLocalization }, generateDeleteAttachmentCallback(attachment, true));
				}
			}

			setUpdateList();

			e.preventDefault();
		};

		//Methods
		this.getId = function ()
		{
			return clientId;
		};

		this.setOptions = function (options)
		{
			if (options)
			{
				var updatePath;
				var updateAttachments;

				var oldEditable = editable;
				editable = 'boolean' === typeof options.editable ? options.editable : editable;
				var updateEditable = updateAttachments = oldEditable !== editable;

				var oldItemId = itemId;
				itemId = options.itemId || itemId;
				var itemChanged = updatePath = updateAttachments = updateAttachments || oldItemId !== itemId;

				changeSetId = options.changeSetId || changeSetId;

				var oldClosed = closed;
				closed = 'boolean' === typeof options.closed ? options.closed : closed;
				updatePath = updatePath || oldClosed !== closed;

				var oldDescription = description;
				description = options.description || description;
				updatePath = updatePath || oldDescription !== description;

				updatePath = updatePath || options.updatePath;

				var oldItemIsPublic = itemIsPublic;
				itemIsPublic = 'boolean' === typeof options.itemIsPublic ? options.itemIsPublic : itemIsPublic;
				var updateItemPermissionLabel = oldItemIsPublic !== itemIsPublic;

				// Reset the attachment original name if they were saved
				if (options.saved) {
					attachments.forEach(function (attachment) {
						attachment.originalName = attachment.name;
					});
				}

				if (updateEditable)
				{
					showEditableLayout();
				}

				if (itemChanged)
				{
					useItemPermissions = false;
					attachments = [];
					newAttachments = [];
					removedAttachments = [];

					$(document.getElementById(permissionsClientId)).find('input[type="radio"]').prop('checked', false).filter('[value="1"]').prop('checked', true);
					$(document.getElementById(itemPermissionLabelClientId)).addClass('hidden');
				}

				if (updatePath || updateAttachments)
				{
					getAttachmentInformation(updatePath, updateAttachments).then(function ()
					{
						if (oldClosed !== closed)
						{
							//Ask to update attachments
							CivicWeb.Common.AttachmentUpdate.load({ localization: attachmentUpdateLocalization, afterUpdate: function () { getAttachmentInformation(false, true); }, afterUpdatePath: options.afterUpdatePath });
							CivicWeb.Common.AttachmentUpdate.show({ itemId: itemId, closed: closed, description: description });
						}
					});
				}

				if (updateItemPermissionLabel)
				{
					generatePermissionLabel(itemPermissionLabelClientId, itemIsPublic);
				}
			}
		};

		this.buildAttachmentsObject = function ()
		{
			return {
				existing: attachments.filter(function (attachment)
				{
					return !removedAttachments.includes(attachment.id);
				}).map(function (attachment)
				{
					return {
						id: attachment.id,
						name: attachment.name !== attachment.originalName ? attachment.name : '',
						include: attachment.include
					};
				}),
				removed: removedAttachments
			};
		};

		//Functions
		var load = function ()
		{
			getAttachmentInformation(true, true);
			generatePermissionLabel(itemPermissionLabelClientId, itemIsPublic);

			$(document.getElementById(locationSummaryClientId)).on('click', locationSummaryClick);
			$(document.getElementById(permissionsClientId)).find('input[type="radio"]').on('click', permissionsClick);
			$(document.getElementById(dropTargetClientId)).on('click', dropTargetClick).on('dragover', dropTargetDragOver).on('drop', dropTargetDrop);
			$(document.getElementById(fileClientId)).on('change', fileChange);

			CivicWeb.Common.DocumentSelector.create(documentCenterSelectorClientId, { options: documentSelectorArguments, searchFolders: false, includeDocuments: true, title: localization.titleDocumentCenter, openWindowButtonClientId: selectFromDocumentCenterClientId, open: documentCenterOpen, select: documentCenterSelect });
			CivicWeb.Common.DocumentSelector.create(locationSelectorClientId, { options: documentSelectorArguments, openWindowButtonClientId: locationSelectClientId, select: locationSelect });
			$(document.getElementById(clientId)).find('button[data-provider]').each(function ()
			{
				var button = $(this);
				var id = button.attr('id');
				CivicWeb.Common.DocumentSelector.create(id + '-selector', { options: documentSelectorArguments, searchFolders: false, includeDocuments: true, title: button.attr('data-title'), provider: button.attr('data-provider').toLowerCase(), openWindowButtonClientId: id, open: thirdPartyOpen, select: thirdPartySelect });
			});
		};

		var findAttachment = function (id)
		{
			return attachments.find(function (attachment)
			{
				return attachment.id === id;
			});
		};

		var showEditableLayout = function ()
		{
			$(document.getElementById(newAttachmentsClientId)).toggleClass('hidden', !editable);
		};

		var getAttachmentInformation = function (showPath, showAttachments)
		{
			return loadPromise
				.then(function ()
				{
					showAttachments = !!showAttachments;
					showPath = !!showPath;

					return $.ajax({
						url: '/api/item/' + itemId + '/attachmentinformation',
						contentType: 'application/json',
						dataType: 'json',
						async: true,
						type: 'POST',
						data: JSON.stringify({
							'closed': closed,
							'description': description,
							'showAttachments': showAttachments,
							'showCurrentPath': showPath,
							'showDefaultPath': showPath
						})
					}).done(function (data)
					{
						if (showPath)
						{
							pathId = data.currentPathId || data.defaultPathId;
							path = data.currentPath || data.defaultPath;
							pathUpdateAllowed = 'boolean' === typeof data.currentPathUpdateAllowed ? data.currentPathUpdateAllowed : !!data.defaultPathUpdateAllowed;
							pathIsPublic = 'boolean' === typeof data.currentPathIsPublic ? data.currentPathIsPublic : !!data.defaultPathIsPublic;
							existingPathId = data.currentPathId || data.defaultPathExistingFolderId;
							existingPath = data.currentPath || data.defaultPathExistingPath;
							remainingPath = !data.currentPath ? data.defaultPathRemainingPath : null;

							generatePermissionLabel(locationSummaryClientId, !useItemPermissions ? pathIsPublic : itemIsPublic);
							generatePathLink();
							generatePermissionLabel(locationDetailsPermissionLabelClientId, pathIsPublic);
							checkPathAccess();
						}

						if (showAttachments)
						{
							attachments = applyChangesToUpdatedAttachments(data.attachments);
							removedAttachments = [];

							showAttachmentList();

							if (jumpTo)
							{
								document.getElementById(clientId).scrollIntoView();

								jumpTo = false;
							}
						}
					});
				});
		};

		var applyChangesToUpdatedAttachments = function (newAttachments)
		{
			newAttachments = newAttachments || [];
			var reorderedAttachments = [];
			if (attachments.length > 0)
			{
				//Retain the current order
				attachments.forEach(function (oldAttachment)
				{
					var newAttachment = newAttachments.find(function (newAttachment)
					{
						return newAttachment.id === oldAttachment.id;
					});
					if (newAttachment)
					{
						reorderedAttachments.push(newAttachment);
					};
				});

				//Update fields
				newAttachments.forEach(function (newAttachment)
				{
					var oldAttachment = findAttachment(newAttachment.id);
					if (oldAttachment)
					{
						newAttachment.name = oldAttachment.name;
						newAttachment.originalName = oldAttachment.originalName;
						newAttachment.include = oldAttachment.include;
					}
					else
					{
						reorderedAttachments.push(newAttachment);
					}
				});
			}
			else
			{
				reorderedAttachments = newAttachments;
			}

			reorderedAttachments.forEach(function (attachment) {
				if (!attachment.originalName) {
					attachment.originalName = attachment.name;
				}
			});

			return reorderedAttachments;
		};

		var generatePermissionLabel = function (element, isPublic)
		{
			return library.generatePermissionLabel(element, isPublic, localization.labelPublic, localization.labelPrivate);
		};

		var generatePathLink = function ()
		{
			return library.generatePathLink(pathClientId,
				{
					existingPath: existingPath,
					existingPathId: existingPathId,
					remainingPath: remainingPath
				});
		};

		var checkPathAccess = function ()
		{
			if (pathUpdateAllowed)
			{
				CivicWeb.Common.Notification.hide(noAccessNotificationClientId);
			}
			else
			{
				var notification = CivicWeb.Common.Notification.show(noAccessNotificationClientId, CivicWeb.Common.Notification.types.warning, localization.warningLocationNoUploadAllowed, undefined, false);
				notification.find('button').off('click').on('click', permissionsContactAdministratorButtonClick);
				$(document.getElementById(locationDetailsClientId)).removeClass('hidden');
			}
			$(document.getElementById(dropTargetClientId)).toggleClass('hidden', !pathUpdateAllowed || !editable);
		};

		var showAttachmentList = function ()
		{
			var attachmentsList = $(document.getElementById(attachmentsListClientId)).toggleClass('hidden', attachments.length === 0);
			var tableBody = attachmentsList.find('tbody').empty();
			if (attachments.length > 0 && editable)
			{
				tableBody
					.append($('<tr></tr>')
						.append($('<td></td>').attr({ 'colspan': 3 }))
						.append($('<td></td>')
							.append($('<input />').attr({ 'id': includeAllClientId, 'type': 'checkbox' }).prop('checked', attachments.every(function (attachment) { return attachment.include; })).on('click', includeAllClick)))
						.append($('<td></td>').addClass('attachments-document-name')
							.append($('<label></label>').attr({ 'for': includeAllClientId }).text(localization.formFieldLabelPublishAll)))
						.append(!editable ? null : $('<td></td>').attr({ 'colspan': 3 })));
			}

			attachments.forEach(function (attachment)
			{
				tableBody
					.append(generateAttachmentRow(attachment));
			});

			setUpdateList();
		};

		var generateAttachmentRow = function (attachment)
		{
			var dragHandle;
			var row = $('<tr></tr>').attr({ 'class': 'attachments-document', 'data-id': attachment.id })
				.append(dragHandle = $('<td></td>').attr({ 'title': localization.toolTipDragAndDrop, 'data-drag': 'true' })
					.append(!editable ? null : $('<span></span>').addClass('fas fa-arrows-alt-v glyphbutton')))
				.append($('<td></td>')
					.append(!attachment.stitchable || attachment.passwordProtected ? $('<span></span>').attr({ 'class': 'cw-icon-warning attachment-unstitchable unstitchable', 'title': attachment.passwordProtected ? localization.warningMessagePasswordProtectedPdf : (attachment.extension === '.pdf' ? localization.toolTipNonStichablePdfDocument : localization.toolTipNonStichableDocument) }) : null))
				.append($('<td></td>')
					.append(!attachment.searchable ? (attachment.ocrStatus === 1 ? $('<img />').attr({ 'src': '/Global/Images/document_refresh.png', 'alt': localization.toolTipOcrInProgress, 'title': localization.toolTipOcrInProgress }) : $('<span></span>').attr({ 'class': 'cw-icon-document-notext attachment-unstitchable unsearchable', 'title': localization.toolTipNonSearchableDocument })) : null))
				.append(!editable ? null : $('<td></td>')
					.append($('<input />').attr({ 'id': includeClientId + attachment.id, 'type': 'checkbox', 'title': localization.toolTipIncludeInPublishedDocuments, 'data-id': attachment.id }).prop('checked', attachment.include).on('click', includeClick)))
				.append($('<td></td>').addClass('attachments-document-name')
					.append(newAttachments.includes(attachment.id) ? $('<span></span>').attr({ 'class': 'cw-icon-attachment', 'title': localization.toolTipAttached }) : null)
					.append($('<a></a>').attr({ 'id': linkClientId + attachment.id, 'href': '/filepro/document/' + attachment.id, 'target': '_blank' }).text(attachment.name))
					.append(generatePermissionLabel($('<span></span>').attr({ 'id': attachmentPermissionClientId + attachment.id, 'class': 'attachments-document-permissions' }), attachment.isPublic))
					.append($('<input />').attr({ 'id': nameClientId + attachment.id, 'type': 'text', 'class': 'hidden', 'value': attachment.name, 'spellcheck': true, 'data-id': attachment.id }))
					.append($('<a></a>').attr({ 'id': updateClientId + attachment.id, 'class': 'attachments-document-update hidden', 'href': '#', 'data-id': attachment.id }).text(localization.buttonUpdate).on('click', updateClick)))
				.append(!editable ? null : $('<td></td>').addClass('attachments-document-actions')
					.append(!attachment.updateAllowed ? null : $('<a></a>').attr({ 'id': renameClientId + attachment.id, 'href': '#', 'data-id': attachment.id }).text(localization.buttonRename).on('click', renameClick)))
				.append(!editable ? null : $('<td></td>').addClass('attachments-document-actions')
					.append(!attachment.updateAllowed ? null : $('<a></a>').attr({ 'href': '#', 'data-id': attachment.id, 'data-replace': 'true' }).text(localization.buttonReplace).on('click', replaceClick)))
				.append(!editable ? null : $('<td></td>').addClass('attachments-document-actions')
					.append($('<a></a>').attr({ 'href': '#', 'data-id': attachment.id }).text(localization.buttonRemove).on('click', removeClick)));

			if (editable)
			{
				dragHandle.kendoDraggable({
					hint: function (element)
					{
						var rowElement = element.closest('tr');
						var row = rowElement.parent().children().index(rowElement);

						return $('<div></div>').attr({ 'class': 'k-header k-drag-clue', 'data-row': row, 'data-drag': true })
							.append($('<span></span>').attr({ 'class': 'k-icon k-i-add', 'data-drag': true }))
							.append($('<span></span>').attr({ 'data-drag': true })
								.append(rowElement.find('a[id^="' + linkClientId + '"]').clone()));
					},
					drag: attachmentDrag,
					dragend: attachmentDragEnd
				});
			}

			return row;
		};

		var addOrUpdateAttachmentRow = function (newAttachment)
		{
			var tbody = $(document.getElementById(attachmentsListClientId)).find('tbody');

			var index = attachments.findIndex(function (attachment)
			{
				return attachment.id === newAttachment.id;
			});
			if (index >= 0)
			{
				//Replacement
				attachments[index] = newAttachment;

				tbody.find('tr:eq(' + (index + 1) + ')').remove();
				tbody.find('tr:eq(' + index + ')').after(generateAttachmentRow(newAttachment));
			}
			else
			{
				//New
				attachments.push(newAttachment);

				if (attachments.length === 1)
				{
					showAttachmentList();
				}
				else
				{
					tbody
						.append(generateAttachmentRow(newAttachment));
				}
			}

			setUpdateList();
		};

		var toggleReplacement = function (button)
		{
			var tbody = $(document.getElementById(attachmentsListClientId)).find('tbody');
			tbody.find('td[data-drag]').children().toggleClass('invisible', replacementId > 0);
			tbody.find('td.attachments-document-actions').children().toggleClass('invisible', replacementId > 0);
			tbody.find('td.attachments-document-actions [data-replace]').text(replacementId > 0 ? localization.buttonCancelReplacement : localization.buttonReplace);

			if (button)
			{
				button.removeClass('invisible');
			}

			if (replacementId > 0)
			{
				tbody.find('input').attr({ 'disabled': 'disabled' });
			}
			else
			{
				tbody.find('input').removeAttr('disabled');
			}
		};

		var uploadAttachments = function (files)
		{
			files = files || document.getElementById(fileClientId).files;
			files = Array.prototype.slice.call(files); //Convert to array

			return files.filter(function (file)
			{
				var extension = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();

				return !CivicWeb.Common.excludedFileTypes.includes(extension);
			}).reduce(function (promise, file, index)
			{
				//Upload each file in turn
				return promise.then(function ()
				{
					return uploadAttachment(file, index);
				});
			}, loadPromise);
		};

		var uploadAttachment = function (file, index)
		{
			//Add to list
			var extension = file.name.substring(file.name.lastIndexOf('.')).replace('.', '').toLowerCase();
			var title = file.name.substring(0, file.name.lastIndexOf('.'));

			var attachmentsList = $(document.getElementById(attachmentsListClientId)).removeClass('hidden');
			var nameCell = attachmentsList.find('td.attachments-document-name');
			var progressBar = $('<div></div>').attr({ 'class': 'progress-bar progress-bar-success progress-bar-striped active', 'role': 'progressbar', 'aria-valuenow': '0', 'aria-valuemin': '0', 'aria-valuemax': '100' }).css({ 'width': '3%' }).text('0%');
			var progressRow = $('<tr></tr>').attr({ 'class': 'attachments-document', 'data-name': file.name })
				.append($('<td></td>').attr({ 'colspan': editable ? 8 : 5 })
					.append($('<div></div>').css({ 'padding-left': ((nameCell.length > 0 ? nameCell.offset().left : 0) - attachmentsList.offset().left) + 'px' }).text(title)) //Match the name column position
					.append($('<div></div>').attr({ 'class': 'progress' })
						.append(progressBar)));

			attachmentsList.find('tfoot')
				.append(progressRow);

			//Build data object
			var documentData = buildAttachmentDocumentObject();
			documentData.fileNumber = index;

			var fileData = new FormData();
			fileData.append(file.name, file);
			fileData.append('data', JSON.stringify(documentData));

			return $.ajax({
				url: '/api/documents/upload' + (changeSetId > 0 ? '?changeSetId=' + changeSetId.toString() : ''),
				contentType: false,
				dataType: 'json',
				async: true,
				cache: false,
				type: 'POST',
				data: fileData,
				processData: false,
				xhr: function ()
				{
					var progressListener = function (e)
					{
						if (e.lengthComputable)
						{
							var percentage = Math.round((e.loaded / e.total) * 90);

							progressBar.attr({ 'aria-valuenow': percentage.toString() }).css({ 'width': percentage.toString() + '%' }).text(percentage.toString() + '%');
						}
					};

					// ReSharper disable once InconsistentNaming
					var xmlHttpRequest = new XMLHttpRequest();

					//Download progress
					if (xmlHttpRequest.addEventListener)
					{
						// ReSharper disable once Html.EventNotResolved
						xmlHttpRequest.addEventListener('progress', progressListener, false);
					}
					if (xmlHttpRequest.upload && xmlHttpRequest.upload.addEventListener)
					{
						// ReSharper disable once Html.EventNotResolved
						xmlHttpRequest.upload.addEventListener('progress', progressListener, false);
					}

					return xmlHttpRequest;
				}
			}).done(function (data)
			{
				progressBar.attr({ 'aria-valuenow': '100' }).css({ 'width': '100%' }).text('100% - ' + title);

				if (data.Result && data.Documents && data.Documents.filter(function (document) { return document.Id > 0; }).length > 0)
				{
					//Update global settings
					changeSetId = data.ChangeSetId;
					pathId = data.parentId;

					//Update the link
					progressRow.remove();

					var attachmentData = data.Documents.length > 0 ? data.Documents[0] : null;
					if (attachmentData)
					{
						var attachment = {};
						attachment.id = attachmentData.Id;
						attachment.name = attachmentData.Description;
						attachment.include = true;
						attachment.extension = '.' + extension;
						attachment.thirdPartyType = 'None';
						attachment.thirdPartyId = '0';
						attachment.searchable = attachmentData.Searchable;
						attachment.ocrStatus = attachmentData.OcrStatus;
						attachment.stitchable = attachmentData.Stitchable;
						attachment.passwordProtected = attachmentData.PasswordProtected;
						attachment.isPublic = attachmentData.IsPublic;
						attachment.parentId = pathId;
						attachment.itemsAttachedTo = attachmentData.ItemsAttachedTo;
						attachment.updateAllowed = attachmentData.UpdateAllowed;
						attachment.deleteAllowed = attachmentData.DeleteAllowed;
						attachment.deleted = false;

						addOrUpdateAttachmentRow(attachment);

						replacementId = 0;
						toggleReplacement();
					}

					setChanged(false);
				}
				else
				{
					progressBar.removeClass('progress-bar-success').addClass('progress-bar-danger').attr({ 'aria-valuenow': '100' }).css({ 'width': '100%' }).text(localization.labelUploadFailed + ' - ' + title);
				}
			}).fail(function (xhr, statusText, error)
			{
				var message = null;
				if (xhr.responseJSON) {
					message = xhr.responseJSON.Message;
				}

				progressBar.removeClass('progress-bar-success').addClass('progress-bar-danger').attr({ 'aria-valuenow': '100' }).css({ 'width': '100%' }).text(message || localization.labelUploadFailed);
				console.error('Error uploading file', xhr.responseJSON, statusText, error);
			}).always(function (xhr)
			{
				setTimeout(function ()
				{
					progressRow.remove();
				}, xhr.status === 200 ? 3000 : 10000);
			});
		};

		var addAttachment = function (documentId, title, provider)
		{
			return loadPromise
				.then(function ()
				{
					return $.ajax({
						url: '/api/item/' + itemId + '/attach',
						type: 'POST',
						dataType: 'json',
						contentType: 'application/json',
						cache: false,
						async: true,
						data: JSON.stringify({
							id: documentId,
							title: title,
							provider: provider,
							documentId: replacementId,
							useItemPermissions: useItemPermissions,
							parentId: pathId,
							parentPath: path,
							record: $(document.getElementById(potentialRecordClientId)).prop('checked') || $(document.getElementById(classifyRecordClientId)).prop('checked')
						})
					}).done(function (data)
					{
						if (data.valid)
						{
							//Update global settings
							changeSetId = data.ChangeSetId;

							if (data.attachment)
							{
								addOrUpdateAttachmentRow(data.attachment);

								setChanged(false);
							}

							replacementId = 0;
							toggleReplacement();
						}
					});
				});
		};

		var buildAttachmentDocumentObject = function ()
		{
			return {
				documentId: replacementId,
				attachedToItemId: itemId,
				attach: true,
				useItemPermissions: useItemPermissions,
				parentId: pathId,
				parentPath: path,
				record: $(document.getElementById(potentialRecordClientId)).prop('checked') || $(document.getElementById(classifyRecordClientId)).prop('checked'),
				uploading: true,
				postBack: false,
				refreshUrl: '',
				disableThreading: true
			};
		};

		var generateDeleteAttachmentCallback = function (attachment, restore)
		{
			return function (promise, password, validCallback)
			{
				return $.ajax({
					url: '/api/documents/' + (!restore ? 'delete' : 'restore'),
					contentType: 'application/json',
					dataType: 'json',
					async: true,
					cache: false,
					type: !restore ? 'DELETE' : 'POST',
					data: JSON.stringify({ 'documentIds': [attachment.id], 'userPassword': password })
				}).done(function (data)
				{
					attachment.deleted = !restore;
					
					if (data && data.Result)
					{
						window.CivicWeb.Common.Confirmation.setContent(window.CivicWeb.Common.Notification.create('', window.CivicWeb.Common.Notification.types.success, restore ? localization.notificationAttachmentRestored : localization.notificationAttachmentDeleted, false));
						window.CivicWeb.Common.Confirmation.setDisabled(true);

						setTimeout(function ()
						{
							validCallback(true);
							promise.resolve();
						}, 2000);
					}
					else
					{
						validCallback(false);
					}

					setUpdateList();
				}).fail(function ()
				{
					window.CivicWeb.Common.Confirmation.close();

					promise.reject();
				});
			};
		};

		var setUpdateList = function ()
		{
			if ('function' === typeof updateList)
			{
				updateList({
					count: attachments.filter(function (attachment)
					{
						return !attachment.deleted && !removedAttachments.includes(attachment.id);
					}).length
				});
			}
		};

		var setChanged = function (needsSave)
		{
			if ('function' === typeof change)
			{
				change({
					needsSave: !!needsSave,
					changeSetId: changeSetId
				});
			}
		};

		load();
	};

	//Methods
	library.create = function (id, args)
	{
		//Remove existing control
		var existingIndex = instances.findIndex(function (element)
		{
			return element.getId() === id;
		});
		if (existingIndex >= 0)
		{
			instances.splice(existingIndex, 1);
		}

		var control = new Control(id, args);
		instances.push(control);

		return control;
	};

	library.find = function (id)
	{
		return instances.find(function (element)
		{
			return element.getId() === id;
		});
	};

	library.generatePermissionLabel = function (element, isPublic, labelPublic, labelPrivate)
	{
		element = CivicWeb.Common.getJqueryObject(element);
		if (element.is('button'))
		{
			element.addClass('btn btn-xs ' + (isPublic ? ' btn-success' : ' btn-danger'));
		}

		return element
			.empty()
			.append($('<span></span>').attr({ 'class': !element.is('button') ? 'permission-label label' + (isPublic ? ' label-success' : ' label-danger') : '' })
				.append($('<span></span>', { 'class': (isPublic ? 'cw-icon-folder-permit' : 'cw-icon-folder-forbid') }))
				.append(' ')
				.append($('<span></span>').text((isPublic ? labelPublic : labelPrivate))));
	};

	library.generatePathLink = function (element, publishData)
	{
		var pathElement = CivicWeb.Common.getJqueryObject(element)
			.empty();

		if (publishData.existingPath)
		{
			pathElement
				.append($('<a></a>').attr({ 'href': '/filepro/documents/' + publishData.existingPathId }).text(publishData.existingPath));
		}
		if (publishData.remainingPath)
		{
			pathElement
				.append($('<span></span>').text(publishData.remainingPath));
		}

		return pathElement;
	};
})(window.CivicWeb.Common.Attachments = window.CivicWeb.Common.Attachments || {}, jQuery);
;
window.CivicWeb = window.CivicWeb || {};
window.CivicWeb.Common = window.CivicWeb.Common || {};

(function (library, $)
{
	//Properties
	var instances = [];

	//Classes
	// ReSharper disable once InconsistentNaming
	var Control = function (id, args)
	{
		var clientId = id;
		var countdownLabelClientId = clientId + '-countdown-label';
		var saveClientId = clientId + '-save';
		var cancelClientId = clientId + '-cancel';

		var localization = args.localization;

		var save = args.save;
		var container = args.container;
		var prepend = 'boolean' === typeof args.prepend ? args.prepend : true;
		var timeBeforesave = args.timeBeforesave || 1200000;
		var startImmediately = !!args.startImmediately;

		var element = null;
		var visibleTime = 60000;
		var finishTime = null;
		var timeoutHandle = null;

		//Event Handlers
		var saveClick = function (e)
		{
			if ('function' === typeof save)
			{
				save();
			}

			cancelTimerInternal();

			e.preventDefault();
		};

		var cancelClick = function (e)
		{
			cancelTimerInternal();

			e.preventDefault();
		};

		//Methods
		this.getId = function ()
		{
			return clientId;
		};

		var startTimerInternal = this.startTimer = function ()
		{
			if (!timeoutHandle)
			{
				var currentTime = new Date().getTime();
				finishTime = currentTime + timeBeforesave;

				timeoutHandle = setTimeout(updateTimer, Math.max(finishTime - currentTime - visibleTime, 0));
			}
		};

		var cancelTimerInternal = this.cancelTimer = function ()
		{
			element.addClass('hidden');

			finishTime = null;

			if (timeoutHandle)
			{
				clearTimeout(timeoutHandle);
				timeoutHandle = null;
			}
		};

		this.toggleTimer = function (start)
		{
			if (start)
			{
				startTimerInternal();
			}
			else
			{
				cancelTimerInternal();
			}
		};

		//Functions
		var load = function ()
		{
			ensureControlExists();

			if (startImmediately)
			{
				startTimerInternal();
			}
		};

		var ensureControlExists = function ()
		{
			element = $(document.getElementById(clientId));
			if (element.length === 0)
			{
				element = $('<div></div>').attr({ 'id': clientId, 'class': 'autosave hidden' })
					.append($('<span></span>').attr({ 'id': countdownLabelClientId, 'class': 'autosave-countdown' }))
					.append($('<div></div>').attr({ 'class': 'btn-group' })
						.append($('<button></button>').attr({ 'id': saveClientId, 'class': 'btn btn-default btn-xs' }).text(localization.buttonSave).on('click', saveClick))
						.append($('<button></button>').attr({ 'id': cancelClientId, 'class': 'btn btn-default btn-xs' }).text(localization.buttonCancel).on('click', cancelClick)));

				var elementContainer = CivicWeb.Common.getJqueryObject(container);
				if (prepend)
				{
					elementContainer.prepend(element);
				}
				else
				{
					elementContainer.append(element);
				}
			}
		};

		var updateTimer = function ()
		{
			var currentTime = new Date().getTime();
			var remainingTime = finishTime - currentTime;
			if (remainingTime > 0)
			{
				$(document.getElementById(countdownLabelClientId)).text(localization.labelAutoSaveCountDown.replace('{0}', Math.round(remainingTime / 1000)));
				element.toggleClass('hidden', finishTime - currentTime > 60000);

				timeoutHandle = setTimeout(updateTimer, 1000);
			}
			else
			{
				performSave();
			}
		};

		var performSave = function ()
		{
			cancelTimerInternal();

			if ('function' === typeof save)
			{
				save();
			}
		};

		load();
	};

	//Methods
	library.create = function (id, args)
	{
		//Remove existing control
		var existingIndex = instances.findIndex(function (element)
		{
			return element.getId() === id;
		});
		if (existingIndex >= 0)
		{
			instances.splice(existingIndex, 1);
		}

		var control = new Control(id, args);
		instances.push(control);

		return control;
	};

	library.find = function (id)
	{
		return instances.find(function (element)
		{
			return element.getId() === id;
		});
	};
})(window.CivicWeb.Common.AutoSave = window.CivicWeb.Common.AutoSave || {}, jQuery);
;
window.CivicWeb = window.CivicWeb || {};
window.CivicWeb.Common = window.CivicWeb.Common || {};

(function (library, $)
{
	//Methods
	library.create = function (id, text, toolTip, type, attributes, imageUrl)
	{
		var additionalClasses = '';
		if (type === this.types.short)
		{
			additionalClasses = 'button-short';
		}
		else if (type === this.types.wide)
		{
			additionalClasses = 'button-wide';
		}
		else if (type === this.types.important)
		{
			additionalClasses = 'button-important';
		}
		else if (type === this.types.negative)
		{
			additionalClasses = 'button-negative';
		}

		attributes = attributes || {};
		attributes.id = id;
		attributes['class'] = 'button' + (additionalClasses.length > 0 ? ' ' + additionalClasses : '') + ' background-color-hover' + (attributes['class'] && attributes['class'].length > 0 ? ' ' + attributes['class'] : '');
		if (toolTip && toolTip.length > 0)
		{
			attributes.title = toolTip;
		}

		var button = $('<button></button>').attr(attributes);
		if (imageUrl && imageUrl.length > 0)
		{
			button
				.append(imageUrl.indexOf('/') >= 0 ? $('<img />').attr({ 'src': imageUrl, 'alt': toolTip ? toolTip : '' }) : $('<span></span>').addClass(imageUrl))
				.append(' ')
				.append($('<span></span>').text(text));
		}
		else
		{
			button.text(text);
		}

		return button;
	};

	library.update = function (element, text, disabled, showThrobber)
	{
		return update(element, { text: text, disabled: disabled, showThrobber: showThrobber });
	};

	var update = library.updateOptions = function (element, options)
	{
		var button = CivicWeb.Common.getJqueryObject(element);
		var textSpan = button.find('span.text');
		var existingText = textSpan.length > 0 ? textSpan.first().text() : button.first().text();
		options = options || {};

		//Set text
		var text = options.text;
		if (typeof text === 'string' && text.length > 0)
		{
			if (textSpan.length > 0)
			{
				textSpan.text(text);
			}
			else
			{
				button.text(text);
			}
		}

		//Set tooltip
		var toolTip = options.toolTip;
		if (typeof toolTip === 'string')
		{
			var usingToolTip = button.data('bs.tooltip');
			if (usingToolTip)
			{
				button.tooltip('destroy');
			}
			button.attr({ 'title': toolTip });
			if (usingToolTip)
			{
				button.tooltip();
			}
		}

		//Enable or disable
		var disabled = options.disabled;
		if (typeof disabled === 'boolean')
		{
			button.toggleClass('background-color-hover', !disabled);
			if (disabled)
			{
				button.attr({ 'disabled': 'disabled' });
			}
			else
			{
				button.removeAttr('disabled');
			}
		}

		//Add throbber
		var showThrobber = options.showThrobber;
		if (typeof showThrobber === 'boolean')
		{
			if (showThrobber)
			{
				if (button.find('span.throbber').length === 0)
				{
					button.append(getThrobber());
				}
			}
			else
			{
				button.find('span.throbber').remove();
			}
		}

		return existingText;
	};

	var getThrobber = library.getThrobber = function (id)
	{
		return $('<span></span>').attr(id && id.length > 0 ? { 'id': id } : {}).addClass('throbber')
			.append($('<span></span>').addClass('fa fa-spinner fa-spin'));
	};

	//Properties
	library.types = {
		none: 0,
		short: 1,
		wide: 2,
		important: 3,
		negative: 5
	};
})(window.CivicWeb.Common.Button = window.CivicWeb.Common.Button || {}, jQuery);
;
window.CivicWeb = window.CivicWeb || {};
window.CivicWeb.Common = window.CivicWeb.Common || {};

(function (library, $)
{
	//Properties
	var instances = [];

	//Classes
	// ReSharper disable once InconsistentNaming
	var Control = function (id, args)
	{
		var clientId = id;

		var change = args.change;

		var control = this;
		var container;

		//Event Handlers
		var selectChange = function (e)
		{
			setNextDropDowns($(e.target).closest('select'));

			if ('function' === typeof change)
			{
				e.value = getValue();
				change(e);
			}
		};

		//Methods
		this.getId = function ()
		{
			return clientId;
		};

		var getValue = this.value = function (listValueId)
		{
			var selectedValue = 0;
			if ('undefined' !== typeof listValueId)
			{
				selectedValue = CivicWeb.Common.toNumber(listValueId);

				var option = container.find('option[value="' + selectedValue + '"]');
				var select = option.closest('select').val(selectedValue);
				if (option.length === 0)
				{
					selectedValue = 0;
				}

				//Set next drop downs
				setNextDropDowns(select, selectedValue);

				//Set previous drop downs
				var index = CivicWeb.Common.toNumber(select.attr('data-index'));
				var previousParentId = selectedValue;
				container.find('select').filter(function ()
				{
					return CivicWeb.Common.toNumber($(this).attr('data-index')) <= index;
				}).toArray().reverse().forEach(function (element)
				{
					var previousSelect = $(element).removeAttr('disabled');
					var previousIndex = CivicWeb.Common.toNumber(previousSelect.attr('data-index'));
					if (previousIndex > 0 && previousParentId === 0)
					{
						previousSelect.attr({ 'disabled': 'disabled' });
					}

					var parentId = CivicWeb.Common.toNumber(previousSelect.find('option[value="' + previousParentId + '"]').attr('data-parent-id'));

					previousSelect.find('option:not([value="0"])').addClass('hidden');
					previousSelect.find('option[data-parent-id="' + parentId + '"]').removeClass('hidden');
					previousSelect.val(previousParentId);

					previousParentId = parentId;
				});

				selectedValue = control;
			}
			else
			{
				//Get the currently selected value
				container.find('select').each(function ()
				{
					var currentValue = CivicWeb.Common.toNumber($(this).val());
					if (currentValue > 0)
					{
						selectedValue = currentValue;
					}

					return currentValue !== 0;
				});
			}

			return selectedValue;
		};

		//Functions
		var getNextDropDowns = function (index)
		{
			return container.find('select').filter(function ()
			{
				return CivicWeb.Common.toNumber($(this).attr('data-index')) > index;
			});
		};

		var setNextDropDowns = function (select, selectedValue)
		{
			var index = CivicWeb.Common.toNumber(select.attr('data-index'));
			var selectedValue = selectedValue || CivicWeb.Common.toNumber(select.val());

			getNextDropDowns(index).each(function (nextIndex)
			{
				var nextSelect = $(this);
				nextSelect.val('0').find('option:not([value="0"])').addClass('hidden');
				if (selectedValue === 0 || nextIndex > 0)
				{
					nextSelect.attr({ 'disabled': 'disabled' });
				}
				else
				{
					nextSelect.removeAttr('disabled').find('option[data-parent-id="' + selectedValue + '"]').removeClass('hidden');
				}
			});
		};

		var load = function ()
		{
			(container = $(document.getElementById(clientId))).find('select').off('change').on('change', selectChange);
		};

		load();
	};

	//Methods
	library.create = function (id, args)
	{
		//Remove existing control
		var existingIndex = instances.findIndex(function (element)
		{
			return element.getId() === id;
		});
		if (existingIndex >= 0)
		{
			instances.splice(existingIndex, 1);
		}

		var control = new Control(id, args);
		instances.push(control);

		return control;
	};

	library.find = function (id)
	{
		return instances.find(function (element)
		{
			return element.getId() === id;
		});
	};
})(window.CivicWeb.Common.CascadingDropDown = window.CivicWeb.Common.CascadingDropDown || {}, jQuery);
;
// Declare namespaces
var CivicWeb = CivicWeb || {};
CivicWeb.Common = CivicWeb.Common || {};

//Create classes
CivicWeb.Common.Classification = function (args)
{
	//Properties
	var classifyButtonClientId = '-classify';
	var valueTextBoxClientId = '-value';
	var validateButtonClientId = '-validate';
	var notificationClientId = '-notify';
	var popupClientId = 'classification-popup-';
	var searchTextBoxClientd = 'search-';
	var searchButtonClientd = 'search-button-';
	var searchResultsClientId = 'search-results-';
	var valueClientId = 'value-';
	var textClientId = 'text-';
	var descriptionClientd = 'description-';
	var retention1ClientId = 'retention1-';
	var retention2ClientId = 'retention2-';
	var retention3ClientId = 'retention3-';
	var retention4ClientId = 'retention4-';
	var retention5ClientId = 'retention5-';
	var primaryLocationClientId = 'primary-location-';
	var secondaryLocationClientId = 'secondary-location-';
	var classificationNumberClientId = 'classification-number-';
	var selectButtonClientd = 'select-';
	var cancelButtonClientId = 'cancel-';
	var loadingClientd = 'loading-';

	var localization = args.localization;

	var canUpdateClassification = args.canUpdateClassification;
	var separator = args.separator;
	var textFieldId = args.textFieldId;
	var recordDateFieldId = args.recordDateFieldId;
	var primaryLocationFieldId = args.primaryLocationFieldId;
	var secondaryLocationFieldId = args.secondaryLocationFieldId;
	var descriptionFieldId = args.descriptionFieldId;
	var retention1FieldId = args.retention1FieldId;
	var retention1DateFieldId = args.retention1DateFieldId;
	var retention2FieldId = args.retention2FieldId;
	var retention2DateFieldId = args.retention2DateFieldId;
	var retention3FieldId = args.retention3FieldId;
	var retention3DateFieldId = args.retention3DateFieldId;
	var retention4FieldId = args.retention4FieldId;
	var retention4DateFieldId = args.retention4DateFieldId;
	var retention5FieldId = args.retention5FieldId;
	var retention5DateFieldId = args.retention5DateFieldId;

	var controls = [];
	var popups = [];

	var controlSelect = 'div[data-field-type="classification"]';
	var popupSelect = 'div.classification-popup';

	var eventHandlers = {
		change: []
	};

	//Events
	var classifyButtonClick = function (e)
	{
		loadPopup(e.target);

		e.preventDefault();
	};

	var validateButtonClick = function (e)
	{
		validate(e.target);

		e.preventDefault();
	};

	var searchKeyDown = function (e)
	{
		if (e.which === 13)
		{
			search(e.target);

			e.preventDefault();
		}
	};

	var searchClick = function (e)
	{
		search(e.target);

		e.preventDefault();
	};

	var searchResultClick = function (e)
	{
		var link = $(e.target).closest('a');
		var control = findControl(e.target);
		var popup = findPopup(control);
		if (popup)
		{
			var listValueId = parseInt(link.attr('data-id'));
			for (var index = popup.lookupTables.length - 1; index >= 0; index--)
			{
				var lookupTable = popup.lookupTables[index];
				var listValue = findListValue(lookupTable.listValues, listValueId);
				control.selectedValues[index] = listValue ? listValue.id : 0;
				if (listValue)
				{
					listValueId = listValue.parentId;
				}
			}

			loadSearchResults(control, popup);
			displaySelection(control);
		}

		e.preventDefault();
	};

	var classificationSelectChange = function (e)
	{
		var select = $(e.target).closest('select');
		var control = findControl(select);
		var index = parseInt(select.attr('data-index'));
		var lookupTableId = select.attr('data-id');

		//Set selection
		var selectedValue = parseInt(select.val());
		control.selectedValues[index] = !isNaN(selectedValue) && selectedValue > 0 ? selectedValue : 0;
		for (var index2 = index + 1; index2 < control.selectedValues.length; index2++)
		{
			control.selectedValues[index2] = 0;
		}
		select.parent().find('select[data-id="' + lookupTableId + '"]').val(selectedValue.toString());

		//Update dropdowns
		displaySelection(control);
	};

	var selectButtonClick = function (e)
	{
		var control = findControl(e.target);
		if (control)
		{
			var controlElement = $(document.getElementById(control.id + valueTextBoxClientId));
			CivicWeb.Common.Forms.value(controlElement, control.fieldId, $(document.getElementById(formatPopupId(classificationNumberClientId, control.fieldId))).text());
			CivicWeb.Common.Notification.hide($(document.getElementById(control.id + notificationClientId)));

			setRetentionInformation(controlElement, findSelectedListValue(control, findPopup(control)));
		}

		closePopup(control);

		e.preventDefault();
	};

	var cancelButtonClick = function (e)
	{
		closePopup(findControl(e.target));

		e.preventDefault();
	};

	var recordDateChange = function (e)
	{
		var form = $(document.getElementById(e.formId));
		for (var index = 0; index < controls.length; index++)
		{
			var control = controls[index];
			var element = document.getElementById(control.id);
			if (form.has(element))
			{
				element = $(element);
				if (parseInt(element.attr('data-list-value-id')) > 0)
				{
					setRetentionDates(element, parseInt(element.attr('data-id')), parseInt(element.attr('data-list-value-id')));
				}
				else
				{
					$.ajax({
						url: '/api/fields/classification/' + parseInt(element.attr('data-id')) + '/validate?classification=' + ($(document.getElementById(control.id + valueTextBoxClientId)).val() || ''),
						contentType: 'application/json', dataType: 'json', async: true, cache: false, type: 'GET',
						success: function (results) {
							setRetentionDates(element, parseInt(element.attr('data-id')), results.value.id);
						}
					});
				}
				break;
			}
		}
	};

	//Methods
	var load = function ()
	{
		$(controlSelect).each(function ()
		{
			var control = $(this);
			var data = {
				id: control.attr('id'),
				fieldId: parseInt(control.attr('data-id')),
				selectedValues: []
			};

			$(document.getElementById(data.id + classifyButtonClientId)).off('click').on('click', classifyButtonClick);
			$(document.getElementById(data.id + validateButtonClientId)).off('click').on('click', validateButtonClick);

			controls.push(data);
		});
	};

	var findControl = function (element)
	{
		var control = null;
		var element = CivicWeb.Common.getJqueryObject(element);
		var id = element.closest(controlSelect).attr('id') || element.closest(popupSelect).attr('data-for');
		for (var index = 0; index < controls.length; index++)
		{
			if (controls[index].id === id)
			{
				control = controls[index];
				break;
			}
		}

		return control;
	};

	var findPopup = function (control)
	{
		var popup = null;
		if (control)
		{
			for (var index = 0; index < popups.length; index++)
			{
				if (popups[index].fieldId === control.fieldId)
				{
					popup = popups[index];
					break;
				}
			}

			if (!popup)
			{
				popup = createPopup(control);
			}
		}

		return popup;
	};

	var findListValue = function (listValues, id)
	{
		var listValue = null;
		if (listValues)
		{
			for (var index = 0; index < listValues.length; index++)
			{
				if (listValues[index].id === id)
				{
					listValue = listValues[index];
					break;
				}
			}
		}

		return listValue;
	};

	var findSelectedListValue = function (control, popup)
	{
		var found = null;
		if (control && popup)
		{
			for (var index = control.selectedValues.length - 1; index >= 0; index--)
			{
				if (control.selectedValues[index] > 0)
				{
					found = findListValue(popup.lookupTables[index].listValues, control.selectedValues[index]);
					var textValue = findListValue(popup.lookupTables[index].textListValues, control.selectedValues[index]);
					if (found && textValue)
					{
						found.text = textValue.text;
					}

					break;
				}
			};
		}

		return found;
	};

	var loadPopup = function (element)
	{
		var control = findControl(element);
		var popup = findPopup(control);
		if (popup)
		{
			if (!popup.loaded)
			{
				popup.element.children('div').addClass('invisible');
				popup.element
					.append($('<div></div>').attr({ 'class': 'classification-loading' })
						.append(CivicWeb.Common.Button.getThrobber(formatPopupId(loadingClientd, control.fieldId))));
			}
			popup.element.attr({ 'data-for': control.id }).removeClass('hidden').css({ 'visibility': '' }).data('kendoWindow').center().open();
			if (!popup.loaded)
			{
				$.ajax({
					url: '/api/fields/classification/' + popup.fieldId.toString() + '/values',
					contentType: 'application/json', dataType: 'json', async: true, cache: false, type: 'GET',
					success: function (results)
					{
						finishLoadingPopup(control, popup, results.lookupTables);
					},
					error: function ()
					{
						finishLoadingPopup(control, popup, []);
					}
				});
			}
			else
			{
				setSelection(control);
			}
		}
	};

	var finishLoadingPopup = function (control, popup, lookupTables)
	{
		if (popup)
		{
			popup.lookupTables = lookupTables;
			var container = popup.element.find('.classification-drop-downs');
			for (var index = 0; index < popup.lookupTables.length; index++)
			{
				var lookupTable = popup.lookupTables[index];

				var valueSelect = $('<select></select>').attr({ 'id': formatPopupId(valueClientId, control.fieldId, lookupTable.id), 'class': 'classification-value-list', 'data-id': lookupTable.id, 'data-parent-id': lookupTable.parentId, 'data-index': index }).on('change', classificationSelectChange);
				var textSelect = $('<select></select>').attr({ 'id': formatPopupId(textClientId, control.fieldId, lookupTable.id), 'class': 'classification-text-list', 'data-id': lookupTable.id, 'data-parent-id': lookupTable.parentId, 'data-index': index }).on('change', classificationSelectChange);
				valueSelect.add(textSelect)
					.append($('<option></option>').attr({ 'value': '0' }).text(localization.selectOptionText));

				//Populate first level
				if (index === 0)
				{
					for (var index2 = 0; index2 < lookupTable.listValues.length; index2++)
					{
						var listValue = lookupTable.listValues[index2];

						valueSelect
							.append($('<option></option>').attr({ 'value': listValue.id }).text(listValue.value));
					}

					for (var index2 = 0; index2 < lookupTable.textListValues.length; index2++)
					{
						var listValue = lookupTable.textListValues[index2];

						textSelect
							.append($('<option></option>').attr({ 'value': listValue.id }).text(listValue.text));
					}
				}

				container
					.append($('<div></div>')
						.append($('<label></label>').attr({ 'for': formatPopupId(valueClientId, control.fieldId, lookupTable.id) }).text(lookupTable.name + (lookupTable.name.indexOf(':') < 0 ? ':' : ''))))
					.append($('<div></div>')
						.append(valueSelect)
						.append(textSelect));

				control.selectedValues.push(0);
			}

			popup.loaded = true;
			popup.element.find('.classification-loading').remove();
			popup.element.children('div').removeClass('invisible');
		}

		setSelection(control);
	};

	var createPopup = function (control)
	{
		var data = null;
		if (control)
		{
			data = {
				fieldId: control.fieldId,
				loaded: false
			};

			var search = $('<div></div>').attr({ 'class': 'search' })
				.append($('<input />').attr({ 'id': formatPopupId(searchTextBoxClientd, control.fieldId), 'type': 'text', 'class': 'search-text-box', 'title': localization.searchToolTipText, 'placeholder': localization.searchToolTipText }).on('keydown', searchKeyDown))
				.append($('<input />').attr({ 'id': formatPopupId(searchButtonClientd, control.fieldId), 'type': 'image', 'class': 'search-button background-color', 'src': 'https://i.civicweb.net/Global/Images/portal/search.png', 'alt': localization.searchToolTipText, 'title': localization.searchToolTipText }).on('click', searchClick))
				.append($('<div></div>').attr({ 'id': formatPopupId(searchResultsClientId, control.fieldId), 'class': 'hidden classification-search-results' }));

			var dropDowns = $('<div></div>').attr({ 'class': 'classification-drop-downs' });

			//Information table
			var information = $('<div></div>').attr({ 'class': 'classification-information' })
				.append($('<div></div>')
					.append($('<label></label>').attr({ 'for': formatPopupId(descriptionClientd, control.fieldId) }).text(localization.descriptionLabelText)))
				.append($('<div></div>').attr({ 'id': formatPopupId(descriptionClientd, control.fieldId), 'class': 'classification-description' }).html('&nbsp;'))
				.append($('<table></table>').attr({ 'class': 'classification-retention' })
					.append($('<tbody></tbody>')
						.append($('<tr></tr>')
							.append($('<td></td>')
								.append($('<label></label>').attr({ 'for': formatPopupId(retention1ClientId, control.fieldId) }).text(localization.retention1LabelText)))
							.append($('<td></td>').attr({ 'id': formatPopupId(retention1ClientId, control.fieldId), 'class': 'classification-retention' }))
							.append($('<td></td>')
								.append($('<label></label>').attr({ 'for': formatPopupId(retention2ClientId, control.fieldId) }).text(localization.retention2LabelText)))
							.append($('<td></td>').attr({ 'id': formatPopupId(retention2ClientId, control.fieldId), 'class': 'classification-retention' })))
						.append($('<tr></tr>')
							.append($('<td></td>')
								.append($('<label></label>').attr({ 'for': formatPopupId(retention3ClientId, control.fieldId) }).text(localization.retention3LabelText)))
							.append($('<td></td>').attr({ 'id': formatPopupId(retention3ClientId, control.fieldId), 'class': 'classification-retention' }))
							.append($('<td></td>')
								.append($('<label></label>').attr({ 'for': formatPopupId(retention4ClientId, control.fieldId) }).text(localization.retention4LabelText)))
							.append($('<td></td>').attr({ 'id': formatPopupId(retention4ClientId, control.fieldId), 'class': 'classification-retention' })))
						.append($('<tr></tr>')
							.append($('<td></td>')
								.append($('<label></label>').attr({ 'for': formatPopupId(retention5ClientId, control.fieldId) }).text(localization.retention5LabelText)))
							.append($('<td></td>').attr({ 'id': formatPopupId(retention5ClientId, control.fieldId), 'class': 'classification-retention' }))
							.append($('<td></td>'))
							.append($('<td></td>')))
						.append($('<tr></tr>')
							.append($('<td></td>')
								.append($('<label></label>').attr({ 'for': formatPopupId(primaryLocationClientId, control.fieldId) }).text(localization.primaryLocationLabelText)))
							.append($('<td></td>').attr({ 'id': formatPopupId(primaryLocationClientId, control.fieldId), 'class': 'classification-retention' }))
							.append($('<td></td>')
								.append($('<label></label>').attr({ 'for': formatPopupId(secondaryLocationClientId, control.fieldId) }).text(localization.secondaryLocationLabelText)))
							.append($('<td></td>').attr({ 'id': formatPopupId(secondaryLocationClientId, control.fieldId), 'class': 'classification-retention' })))))
				.append($('<div></div>')
					.append($('<label></label>').attr({ 'for': formatPopupId(classificationNumberClientId, control.fieldId) }).text(localization.classificationNumberLabelText))
					.append($('<span></span>').attr({ 'id': formatPopupId(classificationNumberClientId, control.fieldId) })));

			var buttons = $('<div></div>').attr({ 'class': 'button-row' })
				.append(CivicWeb.Common.Button.create(formatPopupId(selectButtonClientd, control.fieldId), localization.selectText, localization.selectToolTipText, CivicWeb.Common.Button.types.short).on('click', selectButtonClick))
				.append(CivicWeb.Common.Button.create(formatPopupId(cancelButtonClientId, control.fieldId), localization.cancelText, localization.cancelToolTipText, CivicWeb.Common.Button.types.short).on('click', cancelButtonClick));

			var links = null;
			if (canUpdateClassification)
			{
				links = $('<div></div>').attr({ 'class': 'classification-edit-link' })
					.append($('<a></a>').attr({ 'href': '/Administration/FieldDetail.aspx?Id=' + data.fieldId.toString(), 'target': 'edit' }).text(localization.editClassificationText));
			}

			$('body')
				.append(data.element = $('<div></div>').attr({ 'id': formatPopupId('', control.fieldId), 'class': 'classification-popup hidden' })
					.append(search)
					.append(dropDowns)
					.append(information)
					.append(buttons)
					.append(links));

			data.element.kendoWindow({
				modal: true,
				visible: false,
				title: localization.selectClassificationTitleText
			});

			popups.push(data);
		}

		return data;
	};

	var closePopup = function (control)
	{
		var popup = findPopup(control);
		if (popup)
		{
			popup.element.attr({ 'data-for': '' }).data('kendoWindow').close();
		}
	};

	var formatPopupId = function (id, fieldId, lookupTableId)
	{
		return popupClientId + id + fieldId.toString() + (lookupTableId ? '-' + lookupTableId.toString() : '');
	};

	var setSelection = function (control)
	{
		var popup = findPopup(control);
		if (popup)
		{
			//Parse classification
			var classification = $(document.getElementById(control.id + valueTextBoxClientId)).val() || '';
			var valueParts = classification.split(separator);
			for (var index = 0; index < popup.lookupTables.length; index++)
			{
				var lookupTable = popup.lookupTables[index];
				var value = index < valueParts.length ? valueParts[index] : null;
				if (value)
				{
					var parentId = index > 0 ? control.selectedValues[index - 1] : 0;
					for (var index2 = 0; index2 < lookupTable.listValues.length; index2++)
					{
						var listValue = lookupTable.listValues[index2];
						if (listValue.parentId === parentId && listValue.value === value)
						{
							control.selectedValues[index] = listValue.id;
						}
					}
				}
				else
				{
					control.selectedValues[index] = 0;
				}
			}

			displaySelection(control);
		}
	};

	var displaySelection = function (control)
	{
		var popup = findPopup(control);
		if (popup)
		{
			//Set the drop-downs
			var classification = '';
			var selectedListValue = null;
			for (var index = 0; index < popup.lookupTables.length; index++)
			{
				var lookupTable = popup.lookupTables[index];
				var selects = popup.element.find('select[data-id="' + lookupTable.id.toString() + '"]');
				var selectedValue = control.selectedValues[index];
				if (index > 0) //Don't alter the root level
				{
					if (selectedValue <= 0 || selects.find('option[value="' + selectedValue.toString() + '"]').length === 0)
					{
						selects.find('option:not([value="0"])').remove();
						var parentId = control.selectedValues[index - 1];
						if (parentId > 0) //Popuplate drop-downs
						{
							var valueSelect = selects.filter('.classification-value-list');
							for (var index2 = 0; index2 < lookupTable.listValues.length; index2++)
							{
								var listValue = lookupTable.listValues[index2];
								if (listValue.parentId === parentId)
								{
									valueSelect
										.append($('<option></option>').attr({ 'value': listValue.id }).text(listValue.value));
								}
							}

							var textSelect = selects.filter('.classification-text-list');
							for (var index2 = 0; index2 < lookupTable.textListValues.length; index2++)
							{
								var listValue = lookupTable.textListValues[index2];
								if (listValue.parentId === parentId)
								{
									textSelect
										.append($('<option></option>').attr({ 'value': listValue.id }).text(listValue.text));
								}
							}
						}
					}
				}

				selects.val(selectedValue.toString());

				var listValue = findListValue(lookupTable.listValues, selectedValue);
				if (listValue)
				{
					classification += (classification.length > 0 ? separator : '') + listValue.value;
					selectedListValue = listValue;
				}
			}

			//Set details
			$(document.getElementById(formatPopupId(descriptionClientd, control.fieldId))).html(selectedListValue ? selectedListValue.description : '&nbsp;');
			$(document.getElementById(formatPopupId(retention1ClientId, control.fieldId))).text(selectedListValue ? selectedListValue.retention1 : '');
			$(document.getElementById(formatPopupId(retention2ClientId, control.fieldId))).text(selectedListValue ? selectedListValue.retention2 : '');
			$(document.getElementById(formatPopupId(retention3ClientId, control.fieldId))).text(selectedListValue ? selectedListValue.retention3 : '');
			$(document.getElementById(formatPopupId(retention4ClientId, control.fieldId))).text(selectedListValue ? selectedListValue.retention4 : '');
			$(document.getElementById(formatPopupId(retention5ClientId, control.fieldId))).text(selectedListValue ? selectedListValue.retention5 : '');
			$(document.getElementById(formatPopupId(primaryLocationClientId, control.fieldId))).text(selectedListValue ? selectedListValue.primaryLocation : '');
			$(document.getElementById(formatPopupId(secondaryLocationClientId, control.fieldId))).text(selectedListValue ? selectedListValue.secondaryLocation : '');
			$(document.getElementById(formatPopupId(classificationNumberClientId, control.fieldId))).text(selectedListValue ? classification : '');
		}
	};

	var search = function (element)
	{
		var control = findControl(element);
		var popup = findPopup(control);
		if (popup)
		{
			$(document.getElementById(formatPopupId(searchResultsClientId, control.fieldId))).removeClass('hidden').empty()
				.append($('<div></div>').attr({ 'class': 'classification-search-loading' })
					.append(CivicWeb.Common.Button.getThrobber(formatPopupId(loadingClientd, control.fieldId))));

			$.ajax({
				url: '/api/fields/classification/' + popup.fieldId.toString() + '/search?keywords=' + ($(document.getElementById(formatPopupId(searchTextBoxClientd, control.fieldId))).val() || ''),
				contentType: 'application/json', dataType: 'json', async: true, cache: false, type: 'GET',
				success: function (results)
				{
					loadSearchResults(control, popup, results.listValues);
				},
				error: function ()
				{
					loadSearchResults(control, popup);
				}
			});
		}
	};

	var loadSearchResults = function (control, popup, listValues)
	{
		if (control && popup)
		{
			var results = $(document.getElementById(formatPopupId(searchResultsClientId, control.fieldId)));
			results.empty();
			if (listValues)
			{
				if (listValues.length > 0)
				{
					for (var index = 0; index < listValues.length; index++)
					{
						var listValue = listValues[index];
						results
							.append($('<div></div>').attr({ 'class': 'classification-search-result-' + (listValue.parentId === 0 ? 'primary' : 'secondary') })
								.append($('<div></div>').attr({ 'class': 'classification-search-result-title' })
									.append($('<a></a>').attr({ 'href': '#', 'data-id': listValue.id.toString() }).text(listValue.value + ' ' + separator + ' ' + listValue.text).on('click', searchResultClick)))
								.append($('<div></div>').attr({ 'class': 'classification-search-result-description' }).html(listValue.description)));
					}
				}
				else
				{
					results.append($('<div></div>').text(localization.noSearchResultsText));
				}
			}
			else
			{
				results.addClass('hidden');
			}
		}
	};

	var validate = function (element)
	{
		var control = findControl(element);
		var popup = findPopup(control);
		if (popup)
		{
			var originalText = CivicWeb.Common.Button.update($(document.getElementById(control.id + validateButtonClientId)), localization.validatingText, true, true);

			$.ajax({
				url: '/api/fields/classification/' + popup.fieldId.toString() + '/validate?classification=' + ($(document.getElementById(control.id + valueTextBoxClientId)).val() || ''),
				contentType: 'application/json', dataType: 'json', async: true, cache: false, type: 'GET',
				success: function (results)
				{
					CivicWeb.Common.Notification.show($(document.getElementById(control.id + notificationClientId)), results.valid ? CivicWeb.Common.Notification.types.success : CivicWeb.Common.Notification.types.failure, results.message, false);
					CivicWeb.Common.Button.update($(document.getElementById(control.id + validateButtonClientId)), originalText, false, false);

					setRetentionInformation(element, results.value);
				},
				error: function ()
				{
					CivicWeb.Common.Notification.hide($(document.getElementById(control.id + notificationClientId)));
					CivicWeb.Common.Button.update($(document.getElementById(control.id + validateButtonClientId)), originalText, false, false);
				}
			});
		}
	};

	var setRetentionInformation = function (element, listValue)
	{
		if (element && listValue)
		{
			CivicWeb.Common.Forms.value(element, textFieldId, listValue.text);
			CivicWeb.Common.Forms.value(element, descriptionFieldId, listValue.description);
			CivicWeb.Common.Forms.value(element, retention1FieldId, listValue.retention1);
			CivicWeb.Common.Forms.value(element, retention2FieldId, listValue.retention2);
			CivicWeb.Common.Forms.value(element, retention3FieldId, listValue.retention3);
			CivicWeb.Common.Forms.value(element, retention4FieldId, listValue.retention4);
			CivicWeb.Common.Forms.value(element, retention5FieldId, listValue.retention5);
			CivicWeb.Common.Forms.value(element, primaryLocationFieldId, listValue.primaryLocation, true);
			CivicWeb.Common.Forms.value(element, secondaryLocationFieldId, listValue.secondaryLocation, true);

			var control = findControl(element);
			var popup = findPopup(control) || { fieldId: 0 };
			setRetentionDates(element, popup.fieldId, listValue.id);
		}
	};

	this.setRetentionInformationExternal = function (element, listValue)
	{
		if (element && listValue)
		{
			listValue.text = listValue.text || listValue.Text;
			listValue.description = listValue.description || listValue.Description;
			listValue.primaryLocation = listValue.primaryLocation || listValue.PrimaryLocation;
			listValue.secondaryLocation = listValue.secondaryLocation || listValue.SecondaryLocation;
			listValue.retention1 = listValue.retention1 || listValue.RetentionField1;
			listValue.retention2 = listValue.retention2 || listValue.RetentionField2;
			listValue.retention3 = listValue.retention3 || listValue.RetentionField3;
			listValue.retention4 = listValue.retention4 || listValue.RetentionField4;
			listValue.retention5 = listValue.retention5 || listValue.RetentionField5;

			setRetentionInformation(element, listValue);
		}
	};

	var setRetentionDates = function (element, fieldId, listValueId)
	{
		if (fieldId > 0 && listValueId > 0)
		{
			$.ajax({
				url: '/api/fields/classification/' + fieldId.toString() + '/retentiondate/' + listValueId.toString() + '?baseDate=' + CivicWeb.Common.Date.toDateStringForJson(CivicWeb.Common.Forms.value(element, recordDateFieldId) || ''),
				contentType: 'application/json', dataType: 'json', async: true, cache: false, type: 'GET',
				success: function (results)
				{
					CivicWeb.Common.Forms.value(element, retention1DateFieldId, results.retention1Date || '');
					CivicWeb.Common.Forms.value(element, retention2DateFieldId, results.retention2Date || '');
					CivicWeb.Common.Forms.value(element, retention3DateFieldId, results.retention3Date || '');
					CivicWeb.Common.Forms.value(element, retention4DateFieldId, results.retention4Date || '');
					CivicWeb.Common.Forms.value(element, retention5DateFieldId, results.retention5Date || '');
				}
			});
		}
	};

	this.on = function (event, handler)
	{
		CivicWeb.Common.addControlEventHandler(eventHandlers, event, handler);
	};

	this.off = function (event, handler)
	{
		CivicWeb.Common.addControlEventHandler(eventHandlers, event, handler);
	};

	this.initialize = (function ()
	{
		load();

		CivicWeb.Common.Forms.on('change', recordDateChange, recordDateFieldId);
	})(this);
};

//Objects
CivicWeb.Common.Classifications = {
	//Properties
	instance: null,

	createInstance: function (args)
	{
		if (this.instance)
		{
			delete this.instance;
		}
		this.instance = new CivicWeb.Common.Classification(args);
	},

	on: function (event, handler)
	{
		this.instance.on(event, handler);
	},

	off: function (event, handler)
	{
		this.instance.off(event, handler);
	},

	setRetentionInformation: function (element, classificationFieldId, classification)
	{
		var method = this.instance.setRetentionInformationExternal;

		$.ajax({
			url: '/api/fields/classification/' + classificationFieldId.toString() + '/value/matching?value=' + encodeURIComponent(classification),
			contentType: 'application/json', dataType: 'json', async: true, cache: false, type: 'GET',
			success: function (result)
			{
				method(element, result);
			}
		});
	}
};
;
// Declare namespaces
var CivicWeb = CivicWeb || {};
CivicWeb.Common = CivicWeb.Common || {};

//Create classes
CivicWeb.Common.Classify = function (args)
{
	//Properties
	var classifyWindowClientId = 'classify-window';
	var classifySaveClientId = 'classify-save';
	var classifyCancelClientId = 'classify-cancel';

	var localization = args.localization;

	var classificationFieldId = args.classificationFieldId;
	var destructionDateFieldId = args.destructionDateFieldId;
	var setDestructionDate = args.setDestructionDate;
	var dateFormat = args.dateFormat;

	var kendoUiLoaded = false;
	var classifyWindow = null;
	var saveCallback = null;

	//Events
	var editRecordClick = function ()
	{
		saveClassifications();
	};

	var classifySaveClick = function ()
	{
		saveClassifications();

		closeWindow(true);
	};

	var classifyCancelClick = function ()
	{
		closeWindow(true);
	};

	//Methods
	var loadKendoUi = function (callback)
	{
		kendoUiLoaded = kendoUiLoaded || !!$('<div></div>').kendoWindow;
		if (!kendoUiLoaded)
		{
			var body = $('body');

			//Load styles
			body.append($('<link />').attr({ 'rel': 'stylesheet', 'type': 'text/css', 'href': '/css/kendo/kendoui?t=' + new Date().getTime().toString() }));

			//Load scripts
			$.getScript('/js/kendo/kendoui?t=' + new Date().getTime().toString(), function () { kendoUiLoaded = true; if (typeof callback === 'function') { callback(); } });
		}

		return kendoUiLoaded;
	};

	var loadInternal = this.load = function (items, callback)
	{
		if (items && items.length > 0)
		{
			if (loadKendoUi(function () { loadInternal(items, callback) }))
			{
				saveCallback = callback;

				//Create window
				if (!classifyWindow)
				{
					classifyWindow = $('<div></div>').attr({ 'id': classifyWindowClientId, 'class': 'hidden' })
						.append($('<div></div>').attr({ 'class': 'classify-list' }))
						.append($('<div></div>').attr({ 'class': 'button-row' })
							.append(CivicWeb.Common.Button.create(classifySaveClientId, localization.buttonSaveAndClose, localization.toolTipSaveAndClose, CivicWeb.Common.Button.types.none).on('click', classifySaveClick))
							.append(CivicWeb.Common.Button.create(classifyCancelClientId, localization.buttonCancel, localization.toolTipCancel, CivicWeb.Common.Button.types.none).on('click', classifyCancelClick)));
					$('body').append(classifyWindow);

					classifyWindow.kendoWindow({
						width: '800px',
						height: '600px',
						modal: true,
						visible: false,
						title: localization.titleClassifyRecords,
						close: function ()
						{
							closeWindow(false);
						}
					});
				}

				//Grid
				var classifyChildrenTable = $('<table></table>');

				classifyWindow.find('.classify-list').empty()
					.append(classifyChildrenTable);

				var columns = [];
				columns.push({
					field: 'Title',
					filterable: false,
					title: localization.columnHeaderTitle,
					template: function (dataItem)
					{
						return '<span class="icon-file-' + (dataItem.type.length > 0 ? dataItem.type.replace('docx', 'doc') : 'blank') + '-24" title="' + dataItem.type + '"></span> ' + dataItem.title;
					}
				});
				columns.push({
					field: 'Classification',
					filterable: false,
					title: localization.columnHeaderClassification,
					template: function (dataItem)
					{
						return '<input type="text" data-id="' + dataItem.id.toString() + '" data-field-type="classification-simplified" value="' + (items.classification || '') + '" />';
					}
				});
				if (setDestructionDate)
				{
					columns.push({
						field: 'DestructionDate',
						filterable: false,
						title: localization.columnHeaderDestructionDate,
						template: function (dataItem)
						{
							return '<input type="text" data-id="' + dataItem.id.toString() + '" data-field-type="date" value="' + (items.destructionDate || '') + '" />';
						}
					});
				}
				else
				{
					columns.push({
						field: 'Edit',
						filterable: false,
						title: localization.columnHeaderEdit,
						template: function (dataItem)
						{
							return '<a class="edit-node-icon cw-fp-icon-edit-disabled" href="/filepro/document/' + dataItem.id.toString() + '?tab=record" target="_blank" data-id="' + dataItem.id.toString() + '" data-field-type="edit-record"></a>';
						}
					});
				}

				classifyChildrenTable.kendoGrid({
					dataSource: items,
					columns: columns
				});

				CivicWeb.Common.Forms.classificationAutoComplete(classifyChildrenTable.find('input[data-field-type="classification-simplified"]'), classificationFieldId);
				classifyChildrenTable.find('input[data-field-type="date"]').kendoDatePicker({
					format: dateFormat
				});
				classifyChildrenTable.find('a[data-field-type="edit-record"]').off('click').on('click', editRecordClick);

				classifyWindow.removeClass('hidden').data('kendoWindow').center().open();
			}
		}
		else if (typeof callback === 'function')
		{
			//Pass through to callback
			callback();
		}
	};

	var buildClassifyObject = function ()
	{
		var documents = [];

		classifyWindow.find('.classify-list').find('input[data-field-type="classification-simplified"]').each(function ()
		{
			var classificationTextBox = $(this);
			var document = { fields: [] };

			document.id = CivicWeb.Common.toNumber(parseInt(classificationTextBox.attr('data-id')));
			document.fields.push({ id: classificationFieldId, localization: '', valueType: 1, value: classificationTextBox.val() || '' });
			if (setDestructionDate)
			{
				document.fields.push({ id: destructionDateFieldId, localization: '', valueType: 1, value: classificationTextBox.closest('tr').find('input[data-field-type="date"]').data('kendoDatePicker').value() || '' });
			}

			documents.push(document);
		});

		return documents;
	};

	var saveClassifications = function ()
	{
		var documents = buildClassifyObject();
		if (documents.length > 0)
		{
			$.ajax({
				url: '/api/documents/classify',
				contentType: 'application/json', dataType: 'json', async: false, cache: false, type: 'POST', data: JSON.stringify(documents)
			});
		}
	};

	var closeWindow = function (close)
	{
		if (close)
		{
			classifyWindow.addClass('hidden').data('kendoWindow').close();
		}

		if (typeof saveCallback === 'function')
		{
			saveCallback();
			saveCallback = null;
		}
	};
};

//Objects
CivicWeb.Common.Classifies = {
	//Properties
	instance: null,

	createInstance: function (args)
	{
		if (this.instance)
		{
			delete this.instance;
		}
		this.instance = new CivicWeb.Common.Classify(args);
	},

	load: function (items, callback)
	{
		this.instance.load(items, callback);
	}
};
;
window.CivicWeb = window.CivicWeb || {};
window.CivicWeb.Common = window.CivicWeb.Common || {};

(function (library, $)
{
	//Properties
	var instances = [];

	//Classes
	// ReSharper disable once InconsistentNaming
	var Control = function (id, args)
	{
		var clientId = id;
		var windowClientId = clientId + '-window';
		var commentClientId = clientId + '-comment';
		var saveCommentClientId = clientId + '-save-comment';
		var cancelClientId = clientId + '-cancel';
		var commentsClientId = clientId + '-comments';

		var localization = args.localization;
		var deleteConfirmationYesNoLocalization = args.deleteConfirmationYesNoLocalization;

		var userId = args.userId;
		var name = args.name;
		var canDelete = args.canDelete;

		var change = args.change;

		var comments = [];
		var editable = false;
		var button;
		var popupWindowElement;
		var popupWindow;
		var editing;

		//Event Handlers
		var viewClick = function (e)
		{
			if (!popupWindow)
			{
				popupWindowElement = $(document.getElementById(windowClientId));
				if (popupWindowElement.length === 0)
				{
					$('body')
						.append(popupWindowElement = $('<div></div>').attr({ 'id': windowClientId, 'class': 'comment-list hidden' })
							.append($('<div></div>').addClass('layout layout-full')
								.append($('<div></div>').addClass('layout-section')
									.append($('<div></div>')
										.append($('<textarea></textarea>').attr({ 'id': commentClientId, 'class': 'comment-list-editor' }).on('keydown keyup change', commentChange)))
									.append(editable ? $('<div></div>').addClass('btn-group')
										.append($('<button></button>').attr({ 'id': saveCommentClientId, 'class': 'btn btn-default btn-xs' }).text(localization.buttonSaveComment).on('click', saveCommentClick))
										.append($('<button></button>').attr({ 'id': cancelClientId, 'class': 'btn btn-default btn-xs hidden' }).text(localization.buttonCancel).on('click', cancelClick)) : null))
								.append($('<div></div>').attr({ 'id': commentsClientId, 'class': 'layout-section layout-section-fill scrollable' }))));
				}

				popupWindow = popupWindowElement.kendoWindow({
					width: '60%',
					height: '60%',
					modal: true,
					visible: false,
					title: localization.titleComments
				}).removeClass('hidden').data('kendoWindow');
				popupWindow.center();

				displayComments();
			}

			popupWindow.open();

			e.preventDefault();
		};

		var commentChange = function ()
		{
			toggleUnsavedChanges(true);
		};

		var saveCommentClick = function (e)
		{
			saveComment().then(function ()
			{
				toggleUnsavedChanges(false);
				toggleCancelButton(false);

				displayComments();
				updateViewButton();

				onChange();
			});

			e.preventDefault();
		};

		var cancelClick = function (e)
		{
			toggleUnsavedChanges(false);
			toggleCancelButton(false);

			e.preventDefault();
		};

		var editClick = function (e)
		{
			var button = $(e.target).closest('[data-index]');
			editing = CivicWeb.Common.toNumber(button.attr('data-index'));
			var comment = findComment(editing);
			$(document.getElementById(commentClientId)).val(comment.comment);
			toggleCancelButton(true);

			e.preventDefault();
		};

		var deleteClick = function (e)
		{
			CivicWeb.Common.Confirmation.createYesNo(clientId + 'delete-confirmation',
				{
					localization: deleteConfirmationYesNoLocalization,
					content: localization.warningMessageConfirmDeleteItem,
					includeCancel: false,
					yes: function ()
					{
						var index = CivicWeb.Common.toNumber($(e.target).closest('[data-index]').attr('data-index'));
						var comment = findComment(index);
						comment.deleted = true;

						displayComments();
						updateViewButton();

						onChange();
					}
				}).open();

			e.preventDefault();
		};

		//Methods
		this.getId = function ()
		{
			return clientId;
		};

		var getValue = this.value = function (newComments)
		{
			if ('undefined' !== typeof newComments)
			{
				comments = newComments;
				displayComments();
			}

			return comments.map(function (comment)
			{
				return {
					comment: comment.comment,
					userId: comment.userId,
					dateRecorded: comment.dateRecorded,
					deleted: comment.deleted
				};
			});
		};

		//Functions
		var load = function ()
		{
			(button = $(document.getElementById(clientId))).off('click').on('click', viewClick);

			comments = JSON.parse(button.attr('data-comments'));
			button.removeAttr('data-comments');

			editable = (button.attr('data-edit') || '').toLowerCase() === 'true';
		};

		var displayComments = function ()
		{
			if (popupWindow)
			{
				$(document.getElementById(commentsClientId))
					.empty()
					.append(comments
						.map(function (comment, index)
						{
							comment.index = index;

							return comment;
						})
						.filter(function (comment)
						{
							return !comment.deleted;
						})
						.reduce(function (list, comment)
						{
							return list
								.append($('<li></li>')
									.append($('<div></div>').addClass('layout-column')
										.append($('<div></div>').addClass('layout-section comment-list-name').text(comment.name))
										.append($('<div></div>').addClass('layout-section layout-section-fill comment-list-date').text(comment.dateFormatted))
										.append($('<div></div>').addClass('layout-section comment-list-edit')
											.append(editable && comment.userId === userId ? $('<span></span>').attr({ 'class': 'glyphbutton text-action', 'role': 'button', 'title': localization.toolTipEditComment, 'data-index': comment.index }).on('click', editClick)
												.append($('<span></span>').addClass('fas fa-pencil-alt')) : null)
											.append(' ')
											.append(editable && (comment.userId === userId || canDelete) ? $('<span></span>').attr({ 'class': 'glyphbutton text-negative', 'role': 'button', 'title': localization.toolTipDeleteComment, 'data-index': comment.index }).on('click', deleteClick)
												.append($('<span></span>').addClass('fas fa-times')) : null)))
									.append($('<div></div>').addClass('comment-list-comment').text(comment.comment)));
						}, $('<ol></ol>').attr({ 'class': 'clean' })));
			}
		};

		var toggleCancelButton = function (show)
		{
			$(document.getElementById(cancelClientId)).toggleClass('hidden', !show);
		};

		var toggleUnsavedChanges = function (hasChanges)
		{
			$(document.getElementById(saveCommentClientId)).toggleClass('highlighted btn-success', hasChanges).toggleClass('btn-default', !hasChanges);
			if (!hasChanges)
			{
				$(document.getElementById(commentClientId)).val('');
				editing = undefined;
			}
		};

		var updateViewButton = function ()
		{
			var count = comments.filter(function (comment)
			{
				return !comment.deleted;
			}).length;

			button.toggleClass('highlighted', count > 0).text(localization.buttonViewComments.replace('{0}', count));
		};

		var findComment = function (index)
		{
			return 'number' === typeof index && index < comments.length && index >= 0 ? comments[index] : null;
		};

		var saveComment = function ()
		{
			var comment = findComment(editing);
			if (!comment)
			{
				comment = {
					comment: '',
					userId: userId,
					name: name,
					dateRecorded: 0,
					dateFormatted: '',
					deleted: false
				};

				comments.push(comment);
			}
			comment.comment = $(document.getElementById(commentClientId)).val() || '';

			return $.ajax({
				url: '/api/system/date',
				type: 'GET',
				dataType: 'json',
				contentType: 'application/json',
				cache: false,
				async: true
			}).done(function (data)
			{
				comment.dateRecorded = data.utc;
				comment.dateFormatted = data.localDateTimeFormatted;

				comments.sort(function (a, b)
				{
					return a.dateRecorded === b.dateRecorded ? 0 : (a.dateRecorded > b.dateRecorded ? -1 : 1);
				});
			});
		};

		var onChange = function ()
		{
			if ('function' === typeof change)
			{
				change({
					target: button,
					value: getValue()
				});
			}
		};

		load();
	};

	//Methods
	library.create = function (id, args)
	{
		//Remove existing control
		var existingIndex = instances.findIndex(function (element)
		{
			return element.getId() === id;
		});
		if (existingIndex >= 0)
		{
			instances.splice(existingIndex, 1);
		}

		var control = new Control(id, args);
		instances.push(control);

		return control;
	};

	library.find = function (id)
	{
		return instances.find(function (element)
		{
			return element.getId() === id;
		});
	};
})(window.CivicWeb.Common.CommentList = window.CivicWeb.Common.CommentList || {}, jQuery);
;
window.CivicWeb = window.CivicWeb || {};
window.CivicWeb.Common = window.CivicWeb.Common || {};

(function (library, $)
{
	//Properties
	var instances = [];
	var concurrentEditorsHub;

	//Classes
	// ReSharper disable once InconsistentNaming
	var Control = function (id, args)
	{
		var clientId = id;
		var editorsClientId = clientId + '-editors';
		var editorsListClientId = clientId + '-editors-list';
		var openChatContainerClientId = clientId + '-open-chat-container';
		var openChatClientId = clientId + '-open-chat';
		var chatLoadingClientId = clientId + '-chat-loading';
		var chatWindowClientId = clientId + '-chat-window';
		var chatContentClientId = clientId + '-chat-content';
		var chatTextBoxClientId = clientId + '-chat-text-box';

		var localization = args.localization;

		var editGroupId = args.editGroupId;
		var enableChat = !!args.enableChat;
		var userId = args.userId;
		var userViewAllowed = args.userViewAllowed;

		var editors = [];
		var queuedMessages = [];
		var chatWindowElement = null;
		var chatWindow = null;
		var chatOpen = false;

		//Event Handlers
		var openChatClick = function (e)
		{
			displayChat();

			e.preventDefault();
		};

		var chatTextBoxKeyDown = function (e)
		{
			if (e.which === 13)
			{
				var textarea = $(e.target);
				var message = textarea.val();
				textarea.val('');

				displayMessageInternal(userId, localization.labelYou, message);

				concurrentEditorsHub.server.sendMessage(editGroupId, message);

				e.preventDefault();
			}
		};

		//Methods
		this.getId = function ()
		{
			return clientId;
		};

		this.getEditGroupId = function ()
		{
			return editGroupId;
		};

		this.getUserId = function ()
		{
			return userId;
		};

		this.addEditor = function (editorId, name)
		{
			var found = false;
			for (var index = 0; index < editors.length; index++)
			{
				if (found = (editors[index].editorId === editorId))
				{
					break;
				}
			}

			if (!found)
			{
				editors.push({ editorId: editorId, name: name, added: Date.now() });
			}
		};		

		this.removeEditor = function (editorId)
		{
			for (var index = 0; index < editors.length; index++)
			{
				if (editors[index].editorId === editorId)
				{
					editors.splice(index, 1);
					index--;
				}
			}
		};

		this.displayEditors = function ()
		{
			editors.sort(function (a, b)
			{
				var nameA = a ? a.name.toLowerCase() : '';
				var nameB = b ? b.name.toLowerCase() : '';

				return a.editorId === userId || nameA < nameB ? -1 : (nameA > nameB ? 1 : 0);
			});

			var currentTime = Date.now();
			var editorList = $(document.getElementById(editorsListClientId)).toggleClass('hidden', editors.length === 0).empty();
			for (var index = 0; index < editors.length; index++)
			{
				var editor = editors[index];
				var currentUser = editor.editorId === userId;

				var listItem = $('<li></li>').attr({ 'data-id': editor.editorId.toString() });
				if (currentUser)
				{
					listItem.addClass('editor-list-self');
				}

				var text = currentUser ? localization.labelYou : editor.name;
				if (userViewAllowed && !currentUser)
				{
					listItem
						.append($('<a></a>').attr({ 'href': '/user/' + editor.editorId.toString(), 'target': '_blank' }).text(text));
				}
				else
				{
					listItem.text(text);
				}

				if ((editor.added + 1500) >= currentTime && !currentUser)
				{
					listItem
						.append($('<span></span>').attr({ 'class': 'editor-list-signing-in', 'data-timeout': (editor.added + 1500).toString() })
							.append(CivicWeb.Common.Button.getThrobber()));
				}

				editorList
					.append(listItem);
			}

			setTimeout(function ()
			{
				var currentTime = Date.now();

				$(document.getElementById(editorsListClientId)).find('span.editor-list-signing-in').each(function ()
				{
					var span = $(this);
					if (CivicWeb.Common.toNumber(span.attr('data-timeout')) < currentTime)
					{
						span.remove();
					}
				});

				if (editors.length > 1)
				{
					$(document.getElementById(editorsClientId)).find('.editor-list-content').popover({ sanitize: false, trigger: 'hover', placement: 'bottom', container: 'body' }).popover('show');

					if (enableChat && !chatOpen)
					{
						$(document.getElementById(openChatContainerClientId)).removeClass('hidden');
						$(document.getElementById(openChatClientId)).off('click').on('click', openChatClick);
					}
				}
				else
				{
					$(document.getElementById(editorsClientId)).find('.editor-list-content').popover('destroy');

					$(document.getElementById(openChatContainerClientId)).addClass('hidden');
				}
			}, 2000);

			if (enableChat && chatWindow)
			{
				chatWindow.title(getChatTitle());
			}
		};

		var displayMessageInternal = this.displayMessage = function (senderId, name, message)
		{
			if (enableChat)
			{
				if (chatOpen)
				{
					var thisUser = senderId === userId;

					var content = $(document.getElementById(chatContentClientId))
						.append($('<div></div>').addClass('chat-message ' + (thisUser ? 'chat-current' : 'chat-other'))
							.append($('<div></div>').addClass('chat-text' + (!thisUser ? ' background-color' : '')).text(message))
							.append($('<div></div>').addClass('chat-information')
								.append($('<span></span>').addClass('chat-user').text(name))
								.append($('<span></span>').addClass('chat-timestamp').text(new Date().toLocaleTimeString()))));

					content.scrollTop(content[0].scrollHeight);
				}
				else
				{
					queuedMessages.push({ senderId: senderId, name: name, message: message });

					displayChat();
				}
			}
		};

		this.removeConcurrentEditor = function () {
			concurrentEditorsHub.server.removeEditor(editGroupId);
		};

		//Functions
		var load = function ()
		{
			if (Function.prototype.bind && !(window.callPhantom || window._phantom) && editGroupId.length > 0)
			{
				library.registerMethods();

				CivicWeb.Common.SignalR.start().then(function ()
				{
					concurrentEditorsHub.client.announceEditor(userId, '', true);
					concurrentEditorsHub.server.announceEditor(editGroupId, true);
				});
			}
		};

		var displayChat = function ()
		{
			$(document.getElementById(chatLoadingClientId)).remove();

			if (!chatWindowElement)
			{
				$('body')
					.append(chatWindowElement = $('<div></div>').attr({ 'id': chatWindowClientId, 'class': 'hidden' })
						.append($('<div></div>').attr({ 'class': 'chat layout' })
							.append($('<div></div>').attr({ 'id': chatContentClientId, 'class': 'chat-content layout-section layout-section-fill' }))
							.append($('<div></div>').addClass('layout-section')
								.append($('<textarea></textarea>').attr({ 'id': chatTextBoxClientId, 'placeholder': localization.placeholderSendAMessage, 'class': 'chat-text-box' }).on('keydown', chatTextBoxKeyDown)))));
			}

			if (!chatWindow)
			{
				chatWindowElement.kendoWindow({
					width: '250px',
					height: '300px',
					position: {
						left: '20px',
						top: ($(window).height() - 350).toString() + 'px'
					},
					modal: false,
					visible: false,
					title: getChatTitle(),
					open: function ()
					{
						$(document.getElementById(openChatContainerClientId)).addClass('hidden');
					},
					close: function ()
					{
						$(document.getElementById(openChatContainerClientId)).toggleClass('hidden', editors.length <= 1);

						chatOpen = false;
					}
				});

				chatWindowElement.css({ 'padding': '0', 'overflow': 'initial' }); //Override Kendo UI styles

				chatWindow = chatWindowElement.data('kendoWindow');
			}

			chatWindowElement.removeClass('hidden').css({ 'visibility': '' });
			chatWindow.open();

			chatOpen = true;

			queuedMessages.forEach(function (message)
			{
				displayMessageInternal(message.senderId, message.name, message.message);
			});

			setTimeout(function () { $(document.getElementById(chatTextBoxClientId)).focus(); }, 500);

			queuedMessages = [];
		};

		var getChatTitle = function ()
		{
			return localization.titleChatWithEditors + (editors.length > 1 ? ': ' : '') + editors.reduce(function (title, editor)
			{
				return title + (editor.editorId !== userId ? (title.length > 0 ? ', ' : '') + editor.name : '');
			}, '');
		};

		load();
	};

	//Methods
	library.create = function (id, args)
	{
		//Remove existing control
		var existingIndex = instances.findIndex(function (element)
		{
			return element.getId() === id;
		});
		if (existingIndex >= 0)
		{
			instances.splice(existingIndex, 1);
		}

		var control = new Control(id, args);
		instances.push(control);

		return control;
	};

	library.find = function (id)
	{
		return instances.find(function (element)
		{
			return element.getId() === id;
		});
	};

	library.signOut = function () {
		instances.forEach(function (instance) {
			if (instance) {
				instance.removeConcurrentEditor();				
			}
		});
	};

	library.registerMethods = function ()
	{
		//This needs to be called before CivicWeb.Common.SignalR.start() is called anywhere on the page
		if (!concurrentEditorsHub && Function.prototype.bind && !(window.callPhantom || window._phantom) && $.connection && $.connection.hub)
		{
			concurrentEditorsHub = $.connection.concurrentEditorsHub;

			concurrentEditorsHub.client.announceEditor = function (editorId, name, joined)
			{
				var instance = instances.length > 0 ? instances[0] : null;
				if (instance)
				{
					instance.addEditor(editorId, name);

					instance.displayEditors();

					if (joined)
					{
						concurrentEditorsHub.server.announceEditor(instance.getEditGroupId(), false);
					}
				}
			};

			concurrentEditorsHub.client.removeEditor = function (editorId)
			{
				var instance = instances.length > 0 ? instances[0] : null;
				if (instance)
				{
					instance.removeEditor(editorId);

					instance.displayEditors();
				}
			};	

			concurrentEditorsHub.client.sendMessage = function (senderId, name, message)
			{
				var instance = instances.length > 0 ? instances[0] : null;
				if (instance)
				{
					if (senderId !== instance.getUserId())
					{
						instance.displayMessage(senderId, name, message);
					}
				}
			};
		}
	};
})(window.CivicWeb.Common.ConcurrentEditors = window.CivicWeb.Common.ConcurrentEditors || {}, jQuery);
;
var CivicWeb = CivicWeb || {};
CivicWeb.Common = CivicWeb.Common || {};

(function (library, $)
{
	//Properties
	var yesNoInstances = [];

	var confirmationWindowClientId = 'confirmation-window';
	var confirmationContentClientId = 'confirmation-content';
	var confirmationPasswordContainerClientId = 'confirmation-password-container';
	var confirmationPasswordClientId = 'confirmation-password';
	var confirmationConfirmButtonClientId = 'confirmation-confirm-button';
	var confirmationCancelButtonClientId = 'confirmation-cancel-button';
	var confirmationResultClientId = 'confirmation-result';

	var promise;
	var confirmMethod;
	var validatePassword;

	//Classes
	// ReSharper disable once InconsistentNaming
	var YesNoControl = function (id, options)
	{
		var clientId = id;
		var contentContainerClientId = clientId + '-content-container';
		var yesButtonClientId = clientId + '-yes-button';
		var noButtonClientId = clientId + '-no-button';
		var cancelButtonClientId = clientId + '-cancel-button';

		var localization;

		var title;
		var width;
		var minWidth;
		var maxWidth;
		var height;
		var minHeight;
		var maxHeight;
		var content;
		var includeCancel = true;
		var toolTipPlacement;

		var activate;
		var yes;
		var no;
		var cancel;
		var getContentData;

		var control = this;
		var popupWindowElement = null;
		var contentElement = null;
		var cancelButtonElement = null;

		//Event Handlers
		var popupWindowActivate = function ()
		{
			CivicWeb.Common.fitKendoWindowToContent(popupWindowElement);
		};

		var yesButtonClick = function (e)
		{
			if ('function' === typeof yes)
			{
				yes('function' === typeof getContentData ? getContentData(contentElement) : undefined);
			}

			closePopup();

			e.preventDefault();
		};

		var noButtonClick = function (e)
		{
			if ('function' === typeof no)
			{
				no('function' === typeof getContentData ? getContentData(contentElement) : undefined);
			}

			closePopup();

			e.preventDefault();
		};

		var cancelButtonClick = function (e)
		{
			if ('function' === typeof cancel)
			{
				cancel();
			}

			closePopup();

			e.preventDefault();
		};

		//Methods
		this.getId = function ()
		{
			return clientId;
		};

		this.open = function (options)
		{
			if (options)
			{
				loadOptions(options);
				updateOptions();
			}

			openPopup();

			return control;
		};

		this.close = function ()
		{
			closePopup();

			return control;
		};

		//Method
		var loadOptions = function (options)
		{
			localization = options.localization || localization || {};

			title = localization.titleYesNoConfirmation || title || '';
			width = options.width || width || '400px';
			minWidth = options.minWidth || minWidth;
			maxWidth = options.maxWidth || maxWidth;
			height = options.height || height;
			minHeight = options.minHeight || minHeight;
			maxHeight = options.maxHeight || maxHeight;
			content = options.content || content;
			includeCancel = 'boolean' === typeof options.includeCancel ? options.includeCancel : !!includeCancel;
			toolTipPlacement = options.toolTipPlacement || toolTipPlacement || 'auto top';

			activate = 'undefined' !== typeof options.activate ? options.activate : activate;
			yes = 'undefined' !== typeof options.yes ? options.yes : yes;
			no = 'undefined' !== typeof options.no ? options.no : no;
			cancel = 'undefined' !== typeof options.cancel ? options.cancel : cancel;
			getContentData = 'undefined' !== typeof options.getContentData ? options.getContentData : getContentData;
		};

		var load = function (options)
		{
			if (CivicWeb.Common.loadKendoUi(function () { load(options); }))
			{
				loadOptions(options);

				popupWindowElement = $(document.getElementById(clientId));
				if (popupWindowElement.length === 0)
				{
					$('body')
						.append(popupWindowElement = $('<div></div>').attr({ 'id': clientId, 'class': 'hidden' }));
				}

				var popupWindow = popupWindowElement.data('kendoWindow');
				if (popupWindow)
				{
					popupWindow.destroy();
				}

				popupWindowElement.addClass('hidden').empty()
					.append(contentElement = $('<div></div>').attr({ 'id': contentContainerClientId })
						.append(content))
					.append($('<div></div>').addClass('button-row')
						.append(CivicWeb.Common.Button.create(yesButtonClientId, localization.buttonYes, localization.toolTipYes).attr({ 'data-viewport': '#' + clientId, 'data-placement': toolTipPlacement }).on('click', yesButtonClick))
						.append(CivicWeb.Common.Button.create(noButtonClientId, localization.buttonNo, localization.toolTipNo).attr({ 'data-viewport': '#' + clientId, 'data-placement': toolTipPlacement }).on('click', noButtonClick))
						.append(cancelButtonElement = CivicWeb.Common.Button.create(cancelButtonClientId, localization.buttonCancel, localization.toolTipCancel).toggleClass('hidden', !includeCancel).attr({ 'data-viewport': '#' + clientId, 'data-placement': toolTipPlacement }).on('click', cancelButtonClick)));

				popupWindowElement.kendoWindow({
					modal: true,
					visible: false,
					width: width,
					minWidth: minWidth,
					maxWidth: maxWidth,
					height: height,
					minHeight: minHeight,
					maxHeight: maxHeight,
					title: title,
					activate: popupWindowActivate
				});

				popupWindowElement.data('kendoWindow').center();

				popupWindowElement.find('[title]').tooltip();

				if ('function' === typeof activate)
				{
					activate({
						element: popupWindowElement
					});
				}
			}
		};

		var updateOptions = function ()
		{
			contentElement.empty()
				.append(content);

			cancelButtonElement.toggleClass('hidden', !includeCancel);

			popupWindowElement.data('kendoWindow').setOptions({
				width: width,
				minWidth: minWidth,
				maxWidth: maxWidth,
				height: height,
				minHeight: minHeight,
				maxHeight: maxHeight,
				title: title
			});
		};

		var openPopup = function ()
		{
			popupWindowElement.removeClass('hidden').css({ 'visibility': '' }).data('kendoWindow').open();
		};

		var closePopup = function ()
		{
			popupWindowElement.addClass('hidden').data('kendoWindow').close();
		};

		load(options);
	};

	//Event Handlers
	var confirmationPasswordKeyDown = function (e)
	{
		if (e.which === 13)
		{
			submitConfirmation();

			e.preventDefault();
		}
	};

	var confirmationConfirmButtonClick = function (e)
	{
		submitConfirmation();

		e.preventDefault();
	};

	var confirmationCancelButtonClick = function (e)
	{
		library.close();

		e.preventDefault();
	};

	//Functions
	var isPasswordValid = function (valid)
	{
		if (valid)
		{
			library.close(true);
		}
		else
		{
			window.CivicWeb.Common.Notification.show(confirmationResultClientId, window.CivicWeb.Common.Notification.types.warning);
		}
	};

	var submitConfirmation = function ()
	{
		window.CivicWeb.Common.Notification.hide(confirmationResultClientId);

		confirmMethod(promise, validatePassword ? $(document.getElementById(confirmationPasswordClientId)).val() : '', isPasswordValid);
	};

	//Methods
	library.open = function (content, checkPassword, windowOptions, confirmCallback)
	{
		var loadPromise = null;
		if (CivicWeb.Common.loadKendoUi(function () { loadPromise.resolve(library.open(content, checkPassword, windowOptions, confirmCallback)); }))
		{
			if ('function' === typeof (confirmCallback))
			{
				//onConfirm should take a promise, a string, and callback if the password is invalid
				confirmMethod = confirmCallback;
			}
			else
			{
				return $.Deferred().reject();
			}

			//Ensure window exists
			var confirmationWindowElement = $(document.getElementById(confirmationWindowClientId));
			if (confirmationWindowElement.length === 0)
			{
				var localization = windowOptions.localization;

				$('body')
					.append(confirmationWindowElement = $('<div></div>').attr({ 'id': confirmationWindowClientId, 'class': 'hidden' })
						.append($('<div></div>').addClass('confirmation-body')
							.append($('<div></div>').attr({ 'id': confirmationContentClientId }))
							.append($('<div></div>').addClass('confirmation-commands')
								.append($('<div></div>').attr({ 'id': confirmationPasswordContainerClientId })
									.append($('<label></label>').attr({ 'for': confirmationPasswordClientId }).text(localization.confirmPassword))
									.append(' ')
									.append($('<input />').attr({ 'id': confirmationPasswordClientId, 'type': 'password', 'title': localization.toolTipPassword, 'data-trigger': 'hover' })))
								.append($('<div></div>').addClass('button-row')
									.append(CivicWeb.Common.Button.create(confirmationConfirmButtonClientId, localization.confirmPassword, localization.confirmPassword))
									.append(CivicWeb.Common.Button.create(confirmationCancelButtonClientId, localization.buttonCancel, localization.buttonCancel)))
								.append(CivicWeb.Common.Notification.create(confirmationResultClientId, CivicWeb.Common.Notification.types.warning, localization.warningMessageInvalidPassword, true)))));

				$(document.getElementById(confirmationPasswordClientId)).off('keydown').on('keydown', confirmationPasswordKeyDown);
				$(document.getElementById(confirmationConfirmButtonClientId)).off('click').on('click', confirmationConfirmButtonClick);
				$(document.getElementById(confirmationCancelButtonClientId)).off('click').on('click', confirmationCancelButtonClick);
			}

			library.setDisabled(false);

			//Set content
			var contentContainer = $(document.getElementById(confirmationContentClientId)).empty();
			if ('string' === typeof content)
			{
				contentContainer.text(content);
			}
			else if (content instanceof jQuery || content instanceof $)
			{
				contentContainer.append(content);
			}

			validatePassword = !!checkPassword;
			$(document.getElementById(confirmationPasswordContainerClientId)).toggleClass('hidden', !validatePassword);
			var passwordInput = $(document.getElementById(confirmationPasswordClientId)).val('');

			window.CivicWeb.Common.Notification.hide(confirmationResultClientId);

			//Set options
			var options = windowOptions || {};
			options = {
				modal: true,
				title: options.title || '',
				width: options.width || 400,
				height: options.height || 300,
				activate: function ()
				{
					if (validatePassword)
					{
						passwordInput.focus();
					}
				},
				close: function (e)
				{
					if (e.userTriggered)
					{
						promise.reject();
					}
				}
			};

			var confirmationWindow = confirmationWindowElement.data('kendoWindow');
			if (confirmationWindow)
			{
				confirmationWindow.close();

				confirmationWindow.setOptions(options);
			}
			else
			{
				confirmationWindowElement.kendoWindow(options);

				(confirmationWindow = confirmationWindowElement.removeClass('hidden').css({ 'visibility': '' }).data('kendoWindow')).center();
			}

			confirmationWindow.open();

			return (promise = $.Deferred());
		}
		else
		{
			return (loadPromise = $.Deferred());
		}
	};

	library.close = function (valid)
	{
		var confirmationWindow = $(document.getElementById(confirmationWindowClientId)).data('kendoWindow');
		if (confirmationWindow)
		{
			confirmationWindow.close();

			if (promise && !valid)
			{
				promise.reject();
			}
		}
	};

	library.setContent = function (content, append)
	{
		//Set content
		var contentContainer = $(document.getElementById(confirmationContentClientId));
		if (!append)
		{
			contentContainer.empty();
		}
		if ('string' === typeof content)
		{
			contentContainer.text(content);
		}
		else if (content instanceof jQuery || content instanceof $)
		{
			contentContainer.append(content);
		}
	};

	library.setDisabled = function (disabled)
	{
		window.CivicWeb.Common.Button.updateOptions(confirmationConfirmButtonClientId, { disabled: !!disabled });
		window.CivicWeb.Common.Button.updateOptions(confirmationCancelButtonClientId, { disabled: !!disabled });
	};

	library.createYesNo = function (id, options)
	{
		//Remove existing control
		var existingIndex = yesNoInstances.findIndex(function (element)
		{
			return element.getId() === id;
		});
		if (existingIndex >= 0)
		{
			yesNoInstances.splice(existingIndex, 1);
		}

		var control = new YesNoControl(id, options);
		yesNoInstances.push(control);

		return control;
	};

	library.findYesNo = function (id)
	{
		return yesNoInstances.find(function (element)
		{
			return element.getId() === id;
		});
	};

	(function ()
	{
		$(document.getElementById(confirmationPasswordClientId)).off('keydown').on('keydown', confirmationPasswordKeyDown);
		$(document.getElementById(confirmationConfirmButtonClientId)).off('click').on('click', confirmationConfirmButtonClick);
		$(document.getElementById(confirmationCancelButtonClientId)).off('click').on('click', confirmationCancelButtonClick);
	})();
})(window.CivicWeb.Common.Confirmation = window.CivicWeb.Common.Confirmation || {}, jQuery);
;
window.CivicWeb = window.CivicWeb || {};
window.CivicWeb.Common = window.CivicWeb.Common || {};

(function (library, $)
{
	//Methods
	library.get = function (name)
	{
		var promise = $.Deferred();

		$.ajax({
			url: '/api/system/cookie?name=' + encodeURIComponent(name),
			contentType: 'application/json',
			dataType: 'json',
			async: true,
			cache: false,
			type: 'GET'
		}).done(function (data)
		{
			promise.resolve(data);
		}).fail(function ()
		{
			promise.reject();
		});

		return promise;
	};

	library.set = function (name, value, expires)
	{
		return $.ajax({
			url: '/api/system/cookie',
			contentType: 'application/json',
			dataType: 'json',
			async: true,
			cache: false,
			type: 'PUT',
			data: JSON.stringify({
				name: name,
				value: value,
				expires: expires || 7
			})
		});
	};
})(window.CivicWeb.Common.Cookie = window.CivicWeb.Common.Cookie || {}, jQuery);
;
window.CivicWeb = window.CivicWeb || {};
window.CivicWeb.Common = window.CivicWeb.Common || {};

(function (library, $)
{
	//Properties
	var instances = [];

	//Classes
	// ReSharper disable once InconsistentNaming
	var Control = function (id, args)
	{
		var clientId = id;
		var mapLockIconClientId = id + '-map-lock-icon';
		var mapLockLabelClientId = id + '-map-lock-label';
		var mapClientId = id + '-map';

		var localization = args.localization;

		var zoom = args.zoom;
		var defaultLatitude = args.defaultLatitude;
		var defaultLongitude = args.defaultLongitude;

		var change = args.change;

		var images = {
			marker: 'https://i.civicweb.net/Global/Images/marker.png',
			markerDisabled: 'https://i.civicweb.net/Global/Images/marker_disabled.png'
		};

		var lock;
		var map;
		var oldMarker;

		//Event Handlers
		var lockMapClick = function (e)
		{
			lockMap();

			e.preventDefault();
		};

		//Methods
		this.getId = function ()
		{
			return clientId;
		};

		var valueInternal = this.value = function (newCoordinates)
		{
			var control = $(document.getElementById(clientId));
			var canEdit = control.is('input');
			if ('undefined' !== typeof newCoordinates)
			{
				if (canEdit)
				{
					control.val(newCoordinates);
				}
				else
				{
					control.text(newCoordinates);
				}
			}

			return (canEdit ? control.val() : control.text()).trim();
		};

		//Functions
		var load = function ()
		{
			loadMap(getCoordinates());
		};

		var getCoordinates = function ()
		{
			var components = valueInternal().match(/\S+/g) || [];

			var latitude = CivicWeb.Common.toFloat(components.length >= 1 ? components[0] : (defaultLatitude !== 0.0 ? defaultLatitude : null));
			var longitude = CivicWeb.Common.toFloat(components.length >= 2 ? components[1] : (defaultLongitude !== 0.0 ? defaultLongitude : null));

			return {
				latitude: latitude !== 0.0 || longitude !== 0.0 ? latitude : 44.666,
				longitude: latitude !== 0.0 || longitude !== 0.0 ? longitude : -98.633,
				zoom: latitude !== 0.0 || longitude !== 0.0 ? zoom : 2
			};
		};

		var loadMap = function (coordinates)
		{
			if (window.google !== null)
			{
				var control = $(document.getElementById(clientId)).addClass('invisible');
				if (control.is('input')) //It's editable
				{
					control
						.before($('<div></div>').addClass('form-map-lock-container')
							.append($('<img />').attr({ 'id': mapLockIconClientId, 'class': 'form-map-lock-image', 'src': images.markerDisabled, 'alt': localization.toolTipUnlockMarker }).on('click', lockMapClick)
								.after($('<label></label>').attr({ 'id': mapLockLabelClientId, 'for': mapLockIconClientId, 'class': 'form-map-lock-label' }).on('click', lockMapClick).text(localization.toolTipUnlockMarker))));
				}
				control
					.after($('<div></div>').attr({ 'id': mapClientId, 'class': 'form-map' }));

				lock = valueInternal().length > 0;

				var latitudeLongitude = new window.google.maps.LatLng(coordinates.latitude, coordinates.longitude);
				var settings = {
					zoom: parseFloat(coordinates.zoom),
					center: latitudeLongitude,
					mapTypeControl: true,
					mapTypeControlOptions: {
						style: window.google.maps.MapTypeControlStyle.DROPDOWN_MENU
					},
					navigationControl: true,
					navigationControlOptions: {
						style: window.google.maps.NavigationControlStyle.SMALL
					},
					mapTypeId: window.google.maps.MapTypeId.ROADMAP
				};

				map = new window.google.maps.Map(document.getElementById(mapClientId), settings);
				oldMarker = new window.google.maps.Marker({ position: latitudeLongitude, map: map });
			}
		};

		var lockMap = function ()
		{
			if (lock)
			{
				window.google.maps.event.addListener(map, 'click', function (event)
				{
					oldMarker.setMap(null);

					var marker = new window.google.maps.Marker({
						position: event.latLng,
						map: map
					});

					valueInternal(marker.position.lat() + ' ' + marker.position.lng());

					onChange();

					oldMarker = marker;
				});
			}
			else
			{
				window.google.maps.event.clearListeners(map, 'click');
			}

			lock = !lock;

			$(document.getElementById(mapLockIconClientId)).attr({ 'src': lock ? images.markerDisabled : images.marker, 'alt': lock ? localization.toolTipUnlockMarker : localization.toolTipLockMarker });
		};

		var onChange = function ()
		{
			if ('function' === typeof change)
			{
				change({
					target: $(document.getElementById(clientId)),
					value: valueInternal()
				});
			}
		};

		load();
	};

	//Methods
	library.create = function (id, args)
	{
		//Remove existing control
		var existingIndex = instances.findIndex(function (element)
		{
			return element.getId() === id;
		});
		if (existingIndex >= 0)
		{
			instances.splice(existingIndex, 1);
		}

		var control = new Control(id, args);
		instances.push(control);

		return control;
	};

	library.find = function (id)
	{
		return instances.find(function (element)
		{
			return element.getId() === id;
		});
	};
})(window.CivicWeb.Common.Coordinates = window.CivicWeb.Common.Coordinates || {}, jQuery);
;
// Declare namespaces
var CivicWeb = CivicWeb || {};
CivicWeb.Common = CivicWeb.Common || {};

//Create classes
CivicWeb.Common.Date = new function ()
{
	//Methods
	this.toDateStringForJson = function (date)
	{
		var dateString = '';
		if (date && date.getFullYear)
		{
			dateString = date.getFullYear().toString() + '-' + (date.getMonth() + 1).toString() + '-' + date.getDate().toString();
		}
		else if (typeof date === 'string')
		{
			dateString = date;
		}

		return dateString;
	};
};
;
// Declare namespaces
var CivicWeb = CivicWeb || {};
CivicWeb.Common = CivicWeb.Common || {};

//Create classes
CivicWeb.Common.Destroy = function (args)
{
	//Properties
	var destroyWindowClientId = 'destroy-window';
	var confirmPasswordClientId = 'destroy-confirm-password';
	var destroySaveClientId = 'destroy-save';
	var destroyCancelClientId = 'destroy-cancel';
	var destroyResultClientId = 'destroy-result';

	var localization = args.localization;

	var kendoUiLoaded = false;
	var destroyWindow = null;
	var saveCallback = null;
	var saveCallbackArgs = null;

	//Events
	var selectAllClick = function (e)
	{
		var checkBox = $(e.target);
		checkBox.closest('.destroy-group').find('input[data-id]').prop('checked', checkBox.prop('checked'));
	};

	var documentCheckBoxClick = function (e)
	{
		var select = true;
		var checkBox = $(e.target);
		checkBox.closest('.destroy-group').find('input[data-id]').each(function ()
		{
			select = select && $(this).prop('checked');

			return select;
		});

		checkBox.closest('.destroy-group').find('input[data-type="all"]').prop('checked', select);
	};

	var destroyClick = function ()
	{
		var valid = true;
		var destructionErrors = new Array();

		CivicWeb.Common.Notification.hide(destroyResultClientId);

		//Validate the password
		var passwordTextBox = $(document.getElementById(confirmPasswordClientId)).removeClass('invalid');
		if (passwordTextBox.val().length === 0)
		{
			valid = false;
			passwordTextBox.addClass('invalid').focus();

			destructionErrors.push(localization.warningMessagePasswordRequired);
		}

		if (valid)
		{
			$.ajax({
				url: '/api/user/password/validate',
				contentType: 'application/json', dataType: 'json', async: false, cache: false, type: 'POST', data: JSON.stringify({ password: passwordTextBox.val() }),
				success: function (result)
				{
					if (!result.Result)
					{
						valid = false;
						passwordTextBox.addClass('invalid').focus();

						destructionErrors.push(localization.warningMessageInvalidPassword);
					}
				}
			});
		}

		if (destructionErrors.length > 0)
		{
			CivicWeb.Common.Notification.show(destroyResultClientId, CivicWeb.Common.Notification.types.warning, destructionErrors);
		}

		if (valid)
		{
			var documents = buildDestroyObject();
			var destroyedDocuments = [];
			if (documents.length > 0)
			{
				$.ajax({
					url: '/api/documents/destroy',
					contentType: 'application/json', dataType: 'json', async: false, cache: false, type: 'POST', data: JSON.stringify(documents),
					success: function (result)
					{
						destroyedDocuments = result;
					}
				});
			}

			closeWindow(true, destroyedDocuments);
		}
	};

	var destroyCancelClick = function ()
	{
		closeWindow(true);
	};

	//Methods
	var loadKendoUi = function (callback)
	{
		kendoUiLoaded = kendoUiLoaded || !!$('<div></div>').kendoWindow;
		if (!kendoUiLoaded)
		{
			var body = $('body');

			//Load styles
			body.append($('<link />').attr({ 'rel': 'stylesheet', 'type': 'text/css', 'href': '/css/kendo/kendoui?t=' + new Date().getTime().toString() }));

			//Load scripts
			$.getScript('/js/kendo/kendoui?t=' + new Date().getTime().toString(), function () { kendoUiLoaded = true; if (typeof callback === 'function') { callback(); } });
		}

		return kendoUiLoaded;
	};

	var loadInternal = this.load = function (items, callback)
	{
		if (items && items.valid && items.invalid && (items.valid.length > 0 || items.invalid.length > 0))
		{
			if (loadKendoUi(function () { loadInternal(items, callback) }))
			{
				saveCallback = callback;

				//Create window
				if (!destroyWindow)
				{
					destroyWindow = $('<div></div>').attr({ 'id': destroyWindowClientId, 'class': 'hidden' })
						.append($('<div></div>').attr({ 'class': 'destroy-list' }))
						.append($('<div></div>').attr({ 'class': 'destroy-confirmation' })
							.append($('<table></table>').attr({ 'class': 'data-form' })
								.append($('<tbody></tbody>')
									.append($('<tr></tr>')
										.append($('<td></td>')
											.append($('<label></label>').attr({ 'for': confirmPasswordClientId }).text(localization.formFieldLabelConfirmPassword)))
										.append($('<td></td>')
											.append($('<input />').attr({ 'id': confirmPasswordClientId, 'type': 'password' }))))))
							.append($('<div></div>').attr({ 'class': 'button-row' })
								.append(CivicWeb.Common.Button.create(destroySaveClientId, localization.buttonDestroySelectedRecords, localization.toolTipDestroySelectedRecords, CivicWeb.Common.Button.types.none).on('click', destroyClick))
								.append(CivicWeb.Common.Button.create(destroyCancelClientId, localization.buttonCancel, localization.toolTipCancel, CivicWeb.Common.Button.types.none).on('click', destroyCancelClick)))
							.append(CivicWeb.Common.Notification.create(destroyResultClientId, CivicWeb.Common.Notification.warning, '', true)));
					$('body').append(destroyWindow);

					destroyWindow.kendoWindow({
						width: '90%',
						modal: true,
						visible: false,
						title: localization.titleConfirmRecordDestruction,
						close: function ()
						{
							if (typeof saveCallback === 'function')
							{
								saveCallback(saveCallbackArgs);
								saveCallback = null;
								saveCallbackArgs = null;
							}
						}
					});
				}

				//Grid
				var destroyList = destroyWindow.find('.destroy-list').empty();
				$(document.getElementById(confirmPasswordClientId)).val('');

				var columns = [];
				columns.push({
					field: 'Title',
					filterable: false,
					width: '22em',
					headerTemplate: function ()
					{
						return '<input type="checkbox" data-type="all" /> ' + localization.columnHeaderTitle;
					},
					template: function (dataItem)
					{
						return '<div class="destroy-title-cell"><input type="checkbox" data-id="' + dataItem.id.toString() + '" /> <span class="' + (!dataItem.folder ? ('icon-file-' + (dataItem.type.length > 0 ? dataItem.type.replace('docx', 'doc') : 'blank') + '-24') : '') + '" title="' + dataItem.type + '">' + (dataItem.folder ? '<img class="folder-image" src="https://i.civicweb.net/Images/folder.png" title="' + localization.toolTipFolder + '" alt="' + localization.toolTipFolder + '" />' : '') + '</span> <a href="/filepro/documents/' + dataItem.id.toString() + '" title="' + dataItem.title + '" target="_blank">' + dataItem.title + '</a></div>';
					}
				});
				columns.push({
					field: 'DestructionDate',
					filterable: false,
					title: localization.columnHeaderDestructionDate,
					template: function (dataItem)
					{
						return '<div class="destroy-validity"><img src="/Global/Images/' + (dataItem.valid ? 'success' : 'failure') + '-icon.png" alt="' + (dataItem.valid ? 'Valid' : 'Invalid') + '" /></div>' + (dataItem.destructionDate.length > 0 ? dataItem.destructionDate : localization.labelNotApplicable);
					}
				});

				var singleList = items.valid.length === 0 || items.invalid.length === 0;

				destroyWindow.data('kendoWindow').setOptions({ width: singleList ? '50%' : '90%' });

				if (items.valid.length > 0)
				{
					var destroyValidChildrenTable = $('<table></table>');
					destroyList
						.append($('<div></div>').attr({ 'class': 'destroy-group' + (singleList ? ' destroy-group-single' : '') })
							.append($('<h1></h1>').text(localization.labelDestructionDateTodayOrEarlier))
							.append(destroyValidChildrenTable));

					destroyValidChildrenTable.kendoGrid({
						dataSource: items.valid,
						columns: columns
					});

					destroyValidChildrenTable.closest('.destroy-group').find('input').prop('checked', true);
				}

				if (items.invalid.length > 0)
				{
					var destroyInvalidChildrenTable = $('<table></table>');
					destroyList
						.append($('<div></div>').attr({ 'class': 'destroy-group' + (singleList ? ' destroy-group-single' : '') })
							.append($('<h1></h1>').text(localization.labelDestructionDateAfterTodayOrNotSet))
							.append(destroyInvalidChildrenTable));

					destroyInvalidChildrenTable.kendoGrid({
						dataSource: items.invalid,
						columns: columns
					});
				}

				$('.destroy-group input[data-type="all"]').on('click', selectAllClick);
				$('.destroy-group input[data-id]').on('click', documentCheckBoxClick);

				destroyWindow.removeClass('hidden').data('kendoWindow').center().open();
			}
		}
		else if (typeof callback === 'function')
		{
			//Pass through to callback
			callback();
		}
	};

	var buildDestroyObject = function ()
	{
		var documents = [];

		destroyWindow.find('.destroy-list').find('input[data-id]:checked').each(function ()
		{
			documents.push(CivicWeb.Common.toNumber(parseInt($(this).attr('data-id'))));
		});

		return documents;
	};

	var closeWindow = function (close, args)
	{
		saveCallbackArgs = args;

		if (close)
		{
			destroyWindow.addClass('hidden').data('kendoWindow').close();
		}
	};
};

//Objects
CivicWeb.Common.Destroys = {
	//Properties
	instance: null,

	createInstance: function (args)
	{
		if (this.instance)
		{
			delete this.instance;
		}
		this.instance = new CivicWeb.Common.Destroy(args);
	},

	load: function (items, callback)
	{
		this.instance.load(items, callback);
	}
};
;
window.CivicWeb = window.CivicWeb || {};
window.CivicWeb.Common = window.CivicWeb.Common || {};

(function (library, $)
{
	//TODO: Cannot use strict mode until AgendaPopUp.aspx is no longer used - this includes jQuery

	//Properties
	var instances = [];

	var images = {
		expandImageUrl: 'cw-icon-node-open',
		collapseImageUrl: 'cw-icon-node-close',
		folderImageUrl: 'https://i.civicweb.net/Global/Images/tree_folder.png',
		documentImageUrl: 'https://i.civicweb.net/Global/Images/tree_document.png'
	};

	library.providers = {
		documentCenter: 'filepro',
		laserfiche: 'laserfiche',
		sharePoint: 'sharepoint'
	}

	var cache = {};

	//Classes
	// ReSharper disable once InconsistentNaming
	var Control = function (id, args)
	{
		var clientId = id;
		var selectedPathClientId = args.selectedPathClientId || (clientId + '-selected-document-path');
		var selectedIdClientId = args.selectedIdClientId || (clientId + '-selected-document-id');
		var openWindowButtonClientId = args.openWindowButtonClientId || (clientId + '-show-selector');
		var sortClientId = clientId + '-sort';
		var sortDefaultClientId = clientId + '-sort-default';
		var sortRelevanceClientId = clientId + '-sort-relevance';
		var sortNameClientId = clientId + '-sort-name';
		var searchClientId = clientId + '-search';
		var searchButtonClientId = clientId + '-search-button';
		var treeviewClientId = clientId + '-treeview';
		var searchResultsContainerClientId = clientId + '-search-results-container';
		var searchResultsClientId = clientId + '-search-results';
		var searchResultsPagerClientId = clientId + '-search-results-pager';

		var sortName = clientId + '-sort';

		var localization = args.options.localization;

		var provider = args.provider || library.providers.documentCenter;
		var expandPath = args.expandPath;
		var searchFolders = 'undefined' !== typeof args.searchFolders ? args.searchFolders : true;
		var includeDocuments = !!args.includeDocuments;
		var title = args.title;
		var data = args.data;

		var open = args.open;
		var select = args.select;
		var close = args.close;

		var sortOptions = {
			'default': args.options.orderFieldId.toString(),
			relevance: 'Rank',
			name: args.options.titleFieldId.toString()
		};

		var control = this;
		var popupWindowElement = null;
		var searchElement = null;
		var searchButtonElement = null;
		var treeviewElement = null;
		var searchResultsContainerElement = null;
		var searchResultsElement = null;
		var searchResultsPagerElement = null;

		var sortColumn = args.options.currentUserSort.DocumentSortField !== 'Title' ? sortOptions.default : sortOptions.name;
		var searchSortColumn = sortOptions.relevance;
		var searchActive = false;
		var searchPage = 1;
		var customNodes = {
			nodes: [],
			cssClass: null,
			toolTip: null
		};

		//Event Handlers
		var openWindowButtonClick = function (e)
		{
			openPopup();

			e.preventDefault();
		};

		var sortChange = function ()
		{
			if (!searchActive)
			{
				sortColumn = $('input[name="' + sortName + '"]:checked').val();

				reloadTreeView();
			}
			else
			{
				searchSortColumn = $('input[name="' + sortName + '"]:checked').val();
				search();
			}
		};

		var searchKeyDown = function (e)
		{
			if (e.which === 13)
			{
				search();

				e.preventDefault();
			}
		};

		var searchButtonClick = function (e)
		{
			if (searchActive)
			{
				clearSearch();
			}
			else
			{
				search();
			}

			e.preventDefault();
		};

		var pathLinkClick = function (e)
		{
			e.stopPropagation();
		};

		var nodeSelect = function (e)
		{
			var currentNode = e.node;
			var node = this.dataItem(currentNode);
			var parentNode = node;
			var path = '';
			var pathArray = [];
			var idArray = [];
			while (parentNode != null && (parentNode.Id > 0 || (parentNode.Path && parentNode.Path.length)))
			{
				path = parentNode.Title + (path.length > 0 ? '\\' + path : '');
				pathArray.splice(0, 0, parentNode.Title);
				idArray.splice(0, 0, parentNode.Id);

				if (currentNode)
				{
					parentNode = (currentNode = $(currentNode).parent().closest('li').get(0)) != null ? this.dataItem(currentNode) : null;
				}
			}

			while (path.indexOf('\\') === 0)
			{
				path = path.substr(1, path.length - 1);
			}

			var selectArgs = {
				sender: control,
				element: $(document.getElementById(clientId)),
				id: node.Id,
				idArray: idArray,
				path: path,
				pathArray: pathArray,
				title: node.Title,
				folder: node.Folder,
				provider: provider,
				data: data,
				treeView: this,
				node: e.node,
				itemData: node,
				fromSearch: false,
				close: !select
			};
			(select || selectDefault)(selectArgs);

			if (selectArgs.close)
			{
				closePopup();

				setTimeout(function () { treeviewElement.data('kendoTreeView').select($()); }, 0); //Don't retain the selection, it's not needed
			}
		};

		var searchNodeSelect = function (e)
		{
			var currentNode = e.node;
			var node = this.dataItem(currentNode);
			currentNode = $(currentNode);
			var path = [];
			var idArray = [];
			currentNode.find('[data-path] a').each(function ()
			{
				var link = $(this);
				path.push(link.text());
				idArray.push(CivicWeb.Common.toNumber(link.attr('data-id')));
			});

			var title = currentNode.find('[data-title]').text();
			path.push(title);
			idArray.push(node.Id);
			var pathArray = path;
			path = path.join('\\');

			var selectArgs = {
				sender: control,
				element: $(document.getElementById(clientId)),
				id: node.Id,
				idArray: idArray,
				path: path,
				pathArray: pathArray,
				title: title,
				folder: node.Folder,
				provider: provider,
				treeView: this,
				node: e.node,
				itemData: node,
				fromSearch: true,
				close: !select
			};
			(select || selectDefault)(selectArgs);

			if (selectArgs.close)
			{
				closePopup();
			}
		};

		var searchPageClick = function (e)
		{
			searchPage = parseInt($(e.target).closest('a').attr('data-page'));
			if (isNaN(searchPage))
			{
				searchPage = 1;
			}

			search(true);

			e.preventDefault();
		};

		//Methods
		this.getId = function ()
		{
			return clientId;
		};

		this.getProvider = function ()
		{
			return provider;
		};

		this.open = function ()
		{
			openPopup();
		};

		this.close = function ()
		{
			closePopup();
		};

		this.startThrobber = function (node, toolTip)
		{
			var icon = (typeof (node) === 'number' || typeof (node) === 'string') ? treeviewElement.find('[data-id="' + node + '"][data-icon]') : CivicWeb.Common.getJqueryObject(node).find('[data-icon]');
			var height = icon.height();

			icon.empty().attr({ 'class': '', 'title': toolTip, 'data-custom': true })
				.append(CivicWeb.Common.Button.getThrobber(clientId + icon.attr('data-id') + '-throbber').css({ 'height': height + 'px', 'display': 'inline-block', 'vertical-align': 'middle' }));
		};

		this.endThrobber = function (node)
		{
			var icon = (typeof (node) === 'number' || typeof (node) === 'string') ? treeviewElement.find('[data-id="' + node + '"][data-icon]') : CivicWeb.Common.getJqueryObject(node).find('[data-icon]');

			icon.empty().attr({ 'class': icon.attr('data-icon-class'), 'title': icon.attr('data-tooltip') }).removeAttr('data-custom');

			applyCustomNodes(icon.closest('li'));
		};

		this.setCustomNodes = function (nodes, cssClass, toolTip)
		{
			customNodes.nodes = nodes;
			customNodes.cssClass = cssClass;
			customNodes.toolTip = toolTip;

			applyCustomNodes();
		};

		this.addCustomNode = function (node, cssClass, toolTip)
		{
			customNodes.nodes.push(node);
			customNodes.cssClass = cssClass || customNodes.cssClass;
			customNodes.toolTip = toolTip || customNodes.toolTip;

			applyCustomNodes();
		};

		//Method
		var load = function ()
		{
			if (CivicWeb.Common.loadKendoUi(load))
			{
				var displayOptions = provider === library.providers.documentCenter;

				popupWindowElement = $(document.getElementById(clientId));
				if (popupWindowElement.length === 0)
				{
					$('body')
						.append(popupWindowElement = $('<div></div>').attr({ 'id': clientId }));
				}

				popupWindowElement.addClass('hidden document-selector' + (!displayOptions ? ' document-selector-no-options' : '')).empty()
					.append($('<div></div>').attr({ 'class': 'document-selector-options' + (!displayOptions ? ' hidden' : '') })
						.append($('<div></div>').attr({ 'class': 'left-middle document-selector-sort-section' })
							.append($('<label></label>').attr({ 'for': sortClientId }).text(localization.formFieldLabelSort))
							.append($('<span></span>').attr({ 'id': sortClientId })
								.append($('<input />').attr({ 'id': sortDefaultClientId, 'name': sortName, 'type': 'radio', 'value': sortOptions.default }).on('change', sortChange))
								.append($('<label></label>').attr({ 'for': sortDefaultClientId }).text(localization.optionDefault))
								.append($('<input />').attr({ 'id': sortRelevanceClientId, 'name': sortName, 'type': 'radio', 'class': 'hidden', 'value': sortOptions.relevance }).on('change', sortChange))
								.append($('<label></label>').attr({ 'for': sortRelevanceClientId, 'class': 'hidden' }).text(localization.optionRelevance))
								.append($('<input />').attr({ 'id': sortNameClientId, 'name': sortName, 'type': 'radio', 'value': sortOptions.name }).on('change', sortChange))
								.append($('<label></label>').attr({ 'for': sortNameClientId }).text(localization.optionName))))
						.append($('<div></div>').attr({ 'class': 'right-middle document-selector-search-section' })
							.append(searchElement = $('<input />').attr({ 'id': searchClientId, 'type': 'text', 'placeholder': localization.placeholderSearch, 'class': 'document-selector-search', 'title': includeDocuments ? localization.toolTipSearchDocumentsAndFolders : localization.toolTipSearchFolders, 'data-container': '#' + clientId, 'data-placement': 'bottom', 'data-html': 'true' }).on('keydown', searchKeyDown))
							.append(searchButtonElement = $('<button></button>').attr({ 'id': searchButtonClientId, 'class': 'document-selector-search-button', 'title': includeDocuments ? localization.toolTipSearchDocumentsAndFolders : localization.toolTipSearchFolders, 'data-container': '#' + clientId, 'data-placement': 'bottom', 'data-html': 'true' }).on('click', searchButtonClick)
								.append($('<span></span>').attr({ 'class': 'glyphicon glyphicon-search' })))))
					.append(treeviewElement = $('<div></div>').attr({ 'id': treeviewClientId, 'class': 'document-selector-treeview' }))
					.append(searchResultsContainerElement = $('<div></div>').attr({ 'id': searchResultsContainerClientId, 'class': 'hidden document-selector-search-results' })
						.append(searchResultsElement = $('<div></div>').attr({ 'id': searchResultsClientId }))
						.append(searchResultsPagerElement = $('<div></div>').attr({ 'id': searchResultsPagerClientId })));

				$('input[name="' + sortName + '"][value="' + sortColumn + '"]').prop('checked', true);

				reloadTreeView();

				popupWindowElement.kendoWindow({
					modal: true,
					visible: false,
					width: '40%',
					height: '50%',
					minWidth: '600px',
					title: title || (includeDocuments ? localization.titleSelectDocument : localization.titleSelectLocation),
					open: function ()
					{
						if (typeof (open) === 'function')
						{
							open(control);
						}

						if (CivicWeb.Common.isIe())
						{
							$('iframe:not(.hidden):not(.k-content)').addClass('hidden').attr({ 'data-document-selector-hidden': true });
						}
					},
					activate: function ()
					{
						if (CivicWeb.Common.isIe())
						{
							$('input[name="' + sortName + '"]:checked').focus();
						}
					},
					close: function ()
					{
						if (typeof (close) === 'function')
						{
							close(control);
						}

						if (CivicWeb.Common.isIe())
						{
							$('iframe[data-document-selector-hidden]').removeClass('hidden').removeAttr('data-document-selector-hidden');
						}
					}
				});

				popupWindowElement.find('[title]').tooltip();

				$(document.getElementById(openWindowButtonClientId)).off('click').on('click', openWindowButtonClick);
			}
		};

		var reloadTreeView = function ()
		{
			//Destroy the search tree
			var treeview = treeviewElement.data('kendoTreeView');
			if (treeview)
			{
				treeview.destroy();
			}
			treeviewElement.empty();

			treeviewElement.kendoTreeView({
				dataSource: getTreeDataSource(),
				dataTextField: 'Title',
				dataImageUrlField: null,
				select: nodeSelect,
				dataBound: function (e)
				{
					if (expandPath != null && expandPath.length > 0)
					{
						treeviewElement.data('kendoTreeView').expandPath(expandPath);
					}

					applyCustomNodes(e.node);
				},
				template: function (dataItem)
				{
					return getTreeItemTemplate(dataItem.item);
				}
			});
		};

		var getTreeDataSource = function ()
		{
			var providerUsesPath = provider === library.providers.sharePoint;

			return new window.kendo.data.HierarchicalDataSource({
				transport: {
					read: function (options)
					{
						var url = '/api/document/' + (!providerUsesPath && options && options.data && options.data.Id > 0 ? options.data.Id.toString() : '0') + '/getchildlist?' + (providerUsesPath ? 'path=' + (options && options.data.Path && options.data.Path.length > 0 ? options.data.Path.toString() : '') + '&' : '') + 'includeDocuments=' + includeDocuments.toString() + '&ordercolumn=' + sortColumn + '&provider=' + provider;
						var dataCache = cache[url] || {};
						var data = (dataCache.expires || 1) >= Date.now() ? dataCache.data : null;
						if (!data && !dataCache.pending)
						{
							cache[url] = {
								data: null,
								expires: 1,
								pending: true
							};

							$.ajax({
								url: url,
								contentType: 'application/json',
								dataType: 'json',
								async: true,
								type: 'GET',
								timeout: 30000
							}).done(function (data)
							{
								cache[url] = {
									data: data,
									expires: Date.now() + 300000,
									pending: false
								};

								options.success(data);
							}).fail(function (data)
							{
								options.error(data);
							});
						}
						else if (dataCache.pending)
						{
							setTimeout(function ()
							{
								checkCache(url, options.success);
							}, 1000);
						}
						else
						{
							options.success(data);
						}
					}
				},
				schema: {
					model: {
						id: (providerUsesPath ? 'Path' : 'Id'),
						hasChildren: 'HasChildren'
					}
				},
				requestEnd: function (e)
				{
					if (e.type === 'read')
					{
						for (var index = 0; index < e.response.length; index++)
						{
							var document = e.response[index];
							document.ImageUrl = document.Folder ? images.folderImageUrl : images.documentImageUrl;
						}
					}
				}
			});
		};

		var checkCache = function (url, successMethod, iteration)
		{
			iteration = iteration || 0;
			if (iteration < 45 && 'function' === typeof successMethod)
			{
				var dataCache = cache[url] || {};
				var data = (dataCache.expires || 1) >= Date.now() ? dataCache.data : null;
				if (data != null && !dataCache.pending)
				{
					successMethod(data);
				}
				else
				{
					setTimeout(function ()
					{
						checkCache(url, successMethod, iteration + 1);
					}, 1000);
				}
			}
		};

		var getTreeItemTemplate = function (dataItem)
		{
			var title = dataItem.Title.length > 0 ? dataItem.Title : 'Untitled';

			var documentRow = $('<div></div>');

			var iconClass = dataItem.Folder ? 'folder-image cw-icon-folder-lg' : CivicWeb.Common.getFileIconClass(dataItem.FileFormat);
			var toolTip = dataItem.Folder ? localization.toolTipFolder : dataItem.FileFormat.toUpperCase();
			documentRow.append($('<span></span>', { 'class': iconClass, 'title': toolTip, 'data-id': dataItem.Id, 'data-icon': true, 'data-type': dataItem.Folder ? 'folder' : 'document', 'data-icon-class': iconClass, 'data-tooltip': toolTip }));

			documentRow.append($('<span style="padding-left: 0.25em;"></span>').attr({ 'title': title, 'data-type': (dataItem.Folder ? 'folder' : 'document'), 'data-provider': provider }).text(title));

			return documentRow.html();
		};

		var applyCustomNodes = function (container)
		{
			//Apply within this container
			container = container || treeviewElement;
			var searchContainer = searchResultsElement;

			container.find('[data-icon][data-custom]').add(searchContainer.find('[data-icon][data-custom]')).each(function ()
			{
				var icon = $(this);
				icon.empty().attr({ 'class': icon.attr('data-icon-class'), 'title': icon.attr('data-tooltip') }).removeAttr('data-custom');
			});

			customNodes.nodes.forEach(function (currentValue)
			{
				var icon = container.find('[data-id="' + currentValue.id + '"][data-icon]').add(searchContainer.find('[data-id="' + currentValue.id + '"][data-icon]'));

				icon.empty().attr({ 'class': currentValue.cssClass || customNodes.cssClass || icon.attr('data-icon-class'), 'title': currentValue.toolTip || customNodes.toolTip || icon.attr('data-tooltip'), 'data-custom': true });
			});
		};

		var openPopup = function ()
		{
			popupWindowElement.removeClass('hidden').css({ 'visibility': '' }).data('kendoWindow').center().open();
		};

		var closePopup = function ()
		{
			popupWindowElement.addClass('hidden').data('kendoWindow').close();
		};

		var search = function (pageChange)
		{
			var criteria = searchElement.val();
			if (criteria.length > 0)
			{
				clearSearchResults();

				$(document.getElementById(sortDefaultClientId)).add('label[for="' + sortDefaultClientId + '"]').addClass('hidden');
				$(document.getElementById(sortRelevanceClientId)).add('label[for="' + sortRelevanceClientId + '"]').removeClass('hidden');
				searchButtonElement.find('span').removeClass('glyphicon-search').addClass('glyphicon-remove');
				treeviewElement.addClass('hidden');

				$('input[name="' + sortName + '"][value="' + searchSortColumn + '"]').prop('checked', true);

				searchResultsContainerElement.removeClass('hidden')
					.append($('<div></div>').attr({ 'class': 'document-selector-search-throbber center-middle' })
						.append(CivicWeb.Common.Button.getThrobber(clientId + '-search-throbber')));

				if (!pageChange)
				{
					searchPage = 1;
				}

				$.ajax({
					url: '/api/documents/search?keywords=' + encodeURIComponent(criteria) + '&page=' + searchPage + '&ordercolumn=' + searchSortColumn + '&includefolders=' + searchFolders.toString() + '&includedocuments=' + includeDocuments.toString(),
					contentType: 'application/json',
					dataType: 'json',
					async: true,
					cache: false,
					type: 'GET',
					data: null
				}).done(function (data)
				{
					searchPage = data.Page;

					searchResultsContainerElement.find('.document-selector-search-throbber').remove();

					displaySearchResults(data.Results, data.Total);

					searchElement.blur();
				}).fail(function ()
				{
					searchResultsContainerElement.find('.document-selector-search-throbber').remove();

					clearSearch();
				});

				searchActive = true;
			}
		};

		var clearSearchResults = function ()
		{
			//Destroy the search tree
			var searchResults = searchResultsElement.data('kendoTreeView');
			if (searchResults)
			{
				searchResults.destroy();
			}
			searchResultsElement.empty();
		};

		var generatePager = function (numberOfResults)
		{
			searchResultsPagerElement.empty();

			numberOfResults = numberOfResults || 0;
			if (numberOfResults > 0)
			{
				var maxPages = Math.ceil(numberOfResults / 10);

				searchResultsPagerElement.append(CivicWeb.Common.Pager.create(searchPage, maxPages, searchPageClick, false, localization.pagerLocalization));
			}
		};

		var displaySearchResults = function (results, total)
		{
			clearSearchResults();

			generatePager(total);

			//Load list view
			if (results != null)
			{
				searchResultsElement.kendoTreeView({
					dataSource: new window.kendo.data.HierarchicalDataSource({
						data: results,
						schema: {
							model: {
								id: 'Id'
							}
						}
					}),
					select: searchNodeSelect,
					dataBound: function ()
					{
						$('.document-list-sample').find('div[data-path] a').off('click').on('click', pathLinkClick);
					},
					template: function (dataItem)
					{
						dataItem = dataItem.item;
						var documentRow = '<div class="document-list-view-documents" data-id="' + dataItem.Id.toString() + '">';
						documentRow += '<div>';
						documentRow += '<span class="document-list-view-name document-search-list-view-name">';

						if (dataItem.Folder)
						{
							documentRow += ' <span class="folder-image cw-icon-folder-lg" alt="' + localization.folderLabel + '"></span>';
							documentRow += '<span title="' + dataItem.TitleHtml + '" data-container="#' + clientId + '" data-placement="bottom" data-title>' + dataItem.TitleHtml + '</span>';
						}
						else
						{
							var iconClass = CivicWeb.Common.getFileIconClass(dataItem.FileFormat);
							documentRow += ' <span class="' + iconClass + '" data-icon-class="' + iconClass + '" data-icon="true" data-id="' + dataItem.Id.toString() + '" title="' + dataItem.TitleHtml + '" data-tooltip="' + dataItem.TitleHtml + '"></span> ';
							documentRow += '<span title="' + dataItem.TitleHtml + '" data-container="#' + clientId + '" data-placement="bottom" data-title>' + dataItem.TitleHtml + '</span>';
						}

						documentRow += '</span>';

						documentRow += '</div>';
						documentRow += '<div class="document-list-sample">';
						documentRow += '<div>' + dataItem.SampleHtml + '</div>';
						documentRow += '<div data-path>' + dataItem.PathHtml + '</div>';
						documentRow += '</div>';
						documentRow += '</div>';

						return documentRow;
					}
				});

				var searchResults = searchResultsElement.data('kendoTreeView');
				if (searchResults)
				{
					$(searchResults.element).addClass('document-search-list-view document-selector-search-results-container');
				}

				//Strip HTML from titles
				searchResultsElement.find('[data-title]').each(function ()
				{
					var title = $(this);
					title.attr({ 'title': title.text() });
				});
				searchResultsElement.find('a').attr({ 'target': '_blank' });

				searchResultsElement.find('[title]').tooltip();
			}

			applyCustomNodes();

			searchResultsContainerElement.scrollTop(0);
		};

		var clearSearch = function ()
		{
			searchElement.val('');
			$(document.getElementById(sortDefaultClientId)).add('label[for="' + sortDefaultClientId + '"]').removeClass('hidden');
			$(document.getElementById(sortRelevanceClientId)).add('label[for="' + sortRelevanceClientId + '"]').addClass('hidden');
			searchButtonElement.find('span').removeClass('glyphicon-remove').addClass('glyphicon-search');
			searchResultsContainerElement.addClass('hidden');
			treeviewElement.removeClass('hidden');

			$('input[name="' + sortName + '"][value="' + sortColumn + '"]').prop('checked', true);

			clearSearchResults();

			searchActive = false;
		};

		var selectDefault = function (e)
		{
			var pathContainer = $(document.getElementById(selectedPathClientId));
			if (pathContainer.prop('tagName').toLowerCase() === 'input' || pathContainer.prop('tagName').toLowerCase() === 'textarea')
			{
				pathContainer.val(e.path);
			}
			else
			{
				pathContainer.text(e.path);
			}
			$(document.getElementById(selectedIdClientId)).val(e.id);
		};

		load();
	};

	//Methods
	library.create = function (id, args)
	{
		//Remove existing control
		var existingIndex = instances.findIndex(function (element)
		{
			return element.getId() === id;
		});
		if (existingIndex >= 0)
		{
			instances.splice(existingIndex, 1);
		}

		var control = new Control(id, args);
		instances.push(control);

		return control;
	};

	library.find = function (id)
	{
		return instances.find(function (element)
		{
			return element.getId() === id;
		});
	};
})(window.CivicWeb.Common.DocumentSelector = window.CivicWeb.Common.DocumentSelector || {}, jQuery);
;
// Declare namespaces
var CivicWeb = CivicWeb || {};
CivicWeb.Common = CivicWeb.Common || {};

//Create classes
CivicWeb.Common.Form = function (args, $) {
	//Properties
	var dateFormat = args.dateFormat;
	var timeFormat = args.timeFormat;
	var localization = args.localization;
	var coordinatesArguments = args.coordinatesArguments;
	var classificationArguements = args.classificationArguements;
	var commentListArguements = args.commentListArguements;
	var kendoEditorLocalization = args.kendoEditorLocalization;
	var relationshipsArguments = args.relationshipsArguments;

	var forms = [];
	var fields = [];

	var fieldHelpEditorClientId = 'form-help-editor-';
	var formSelect = 'div[data-form][data-editable]';
	var fieldIdAttribute = 'data-id';
	var fieldLocalizationAttribute = 'data-localization';
	var fieldTypeAttribute = 'data-field-type';
	var textFieldSelect = 'input[type="text"]:not([' + fieldTypeAttribute + '="editor"]):not([' + fieldTypeAttribute + '="coordinates"]),textarea:not([' + fieldTypeAttribute + '="editor"]),input[type="number"]';
	var coordinatesFieldSelect = 'input[' + fieldTypeAttribute + '="coordinates"],span[' + fieldTypeAttribute + '="coordinates"]';
	var classificationFieldSelect = 'div[' + fieldTypeAttribute + '="classification"]';
	var checkBoxFieldSelect = 'input[type="checkbox"]';
	var selectFieldSelect = 'select';
	var radioButtonListSelect = 'div[' + fieldTypeAttribute + '="radio-button-list"]';
	var radioButtonSelect = 'input[type="radio"]';
	var cascadingDropDownFieldSelect = 'div[' + fieldTypeAttribute + '="cascading"]';
	var commentListFieldSelect = 'button[' + fieldTypeAttribute + '="comments"]';
	var programmaticFieldSelect = 'span[data-save]';
	var editorSelect = 'input[' + fieldTypeAttribute + '="editor"],textarea[' + fieldTypeAttribute + '="editor"],div[' + fieldTypeAttribute + '="editor"]';
	var dateSelect = 'input[' + fieldTypeAttribute + '="date"]';
	var timeSelect = 'input[' + fieldTypeAttribute + '="time"]';
	var classificationSimplifiedSelect = 'input[' + fieldTypeAttribute + '="classification-simplified"]';
	var classificationTextSelect = 'div[' + fieldTypeAttribute + '="classification"] input[type="text"]';
	var buttonFieldSelect = 'button:not([' + fieldTypeAttribute + '="comments"])';
	var meetingTypeFieldSelect = '[data-list-type="meeting-type"]';
	var meetingFieldSelect = '[data-list-type="meeting"]';
	var headingFieldSelect = '[data-list-type="heading"]';

	var fieldType = {
		none: 0,
		text: 1,
		checkBox: 2,
		select: 3,
		radio: 4,
		cascading: 5,
		comments: 6,
		editor: 7,
		date: 8,
		time: 9,
		coordinates: 10,
		meetingType: 11,
		meeting: 12,
		heading: 13
	};

	var valueType = {
		none: 0,
		simple: 1,
		array: 2,
		objectArray: 3
	};

	var eventHandlers = {
		change: [],
		click: [],
		kendoKeyDown: []
	};

	//Events
	var textChange = function (e) {
		var field = $(e.target);
		var form = findForm(field);
		if (form) {
			var fieldData = findField(getFieldId(field), form, field.attr(fieldLocalizationAttribute));
			if (fieldData) {
				handleTextBoxChange(field, e.type, form, fieldData);
			}
		}
	};

	var coordinatesChange = function (e) {
		var field = $(e.target).closest(coordinatesFieldSelect);
		var form = findForm(field);
		if (form) {
			var fieldData = findField(getFieldId(field), form);
			if (fieldData) {
				handleCoordinatesChange(e.value, form, fieldData);
			}
		}
	};

	var kendoKeyDown = function (e) {
		eventHandlers.kendoKeyDown.forEach(function (handler) {
			if ('function' === typeof handler) {
				handler(e);
			}
		});

		kendoChange.call(this, e);
	};

	var kendoChange = function (e) {
		var data = this.element ? this : e;
		var field = $(data.element);
		var form = findForm(field);
		if (form) {
			var fieldData = findField(getFieldId(field), form);
			if (fieldData) {
				handleKendoChange(data, form, fieldData);
			}
		}
	};

	var kendoEditorPaste = function (e) {
		if (e.html.indexOf('<img') >= 0) {
			var editor = this;
			$('<div></div>').html(e.html).find('img') //Get images
				.map(function () {
					return $(this).attr('src'); //Get src attribute
				})
				.get()
				.filter(function (src) {
					return src.indexOf('base64') >= 0; //Get base64 sources
				})
				.reduce(function (promise, src) {
					//Replace base64 sources
					return promise.then(function () {
						return $.ajax({
							url: '/api/fields/pasteimage',
							contentType: 'application/json',
							dataType: 'json',
							type: 'POST',
							data: JSON.stringify({ imageData: src })
						}).done(function (data) {
							if (data && data.path) {
								editor.value(editor.value().replace(src, data.path));

								editor.trigger('change');
							}
						});
					});
				}, $.Deferred().resolve());
		}
	};

	var checkBoxChange = function (e) {
		var field = $(e.target);
		var form = findForm(field);
		if (form) {
			var fieldData = findField(getFieldId(field), form);
			if (fieldData) {
				handleCheckBoxChange(field, form, fieldData);
			}
		}
	};

	var listChange = function (e) {
		var field = $(e.target);
		var form = findForm(field);
		if (form) {
			var fieldData = findField(getFieldId(field), form);
			if (fieldData) {
				handleListChange(field, form, fieldData);
			}
		}
	};

	var radioButtonChange = function (e) {
		var field = $(e.target).closest(radioButtonListSelect);
		var form = findForm(field);
		if (form) {
			var fieldData = findField(getFieldId(field), form);
			if (fieldData) {
				fieldData.value = CivicWeb.Common.forceArray(field.find(radioButtonSelect + ':checked').val() || '');
				checkFieldChanged(form, fieldData);
			}
		}
	};

	var cascadingDropDownChange = function (e) {
		var field = $(e.target).closest(cascadingDropDownFieldSelect);
		var form = findForm(field);
		if (form) {
			var fieldData = findField(getFieldId(field), form);
			if (fieldData) {
				fieldData.value = e.value;
				checkFieldChanged(form, fieldData);
			}
		}
	};

	var buttonClick = function (e) {
		var field = $(e.target).closest('button');
		var form = findForm(field);
		if (form) {
			var fieldData = findField(getFieldId(field), form);
			if (fieldData) {
				e.preventDefault();

				CivicWeb.Common.callControlEventHandler(fieldData.eventHandlers, 'click', { event: e, id: fieldData.id, formId: form.id, localization: fieldData.localization, value: fieldData.value });
			}
		}
	};

	var commentListChange = function (e) {
		var field = $(e.target).closest(commentListFieldSelect);
		var form = findForm(field);
		if (form) {
			var fieldData = findField(getFieldId(field), form);
			if (fieldData) {
				fieldData.value = e.value;
				checkFieldChanged(form, fieldData);
			}
		}
	};

	var windowCloseHelpEditPopoverClick = function () {
		closeAllHelpEditPopovers();
	};

	var fieldHelpClick = function (e) {
		var helpIcon = $(e.target);

		closeAllHelpEditPopovers(helpIcon);

		helpIcon.popover('show');

		e.preventDefault();
		e.stopPropagation();
	};

	var fieldHelpEditorClick = function (e) {
		e.stopPropagation();
	};

	var fieldHelpEditorChange = function (e) {
		saveFieldHelp($(e.target));
	};

	//Methods
	var load = function () {
		$(formSelect).each(function () {
			var form = $(this);
			var data = {
				id: form.attr('id'),
				updated: false,
				fields: [],
				editHelp: form.is('[data-help-edit="True"]'),
				headings: []
			};

			//Get the form fields
			var fields = form.find('div[' + fieldTypeAttribute + '="cascading"],div[' + fieldTypeAttribute + '="radio-button-list"],div[' + fieldTypeAttribute + '="editor"],input,select,span[data-save],textarea,button').filter('[' + fieldIdAttribute + ']');

			//Text fields
			fields.filter(textFieldSelect).each(function () {
				var field = $(this).off('change keyup', textChange).on('change keyup', textChange).textAreaExpander(40);
				var fieldData = {
					id: field.attr('id'),
					fieldId: getFieldId(field),
					localization: field.attr(fieldLocalizationAttribute) || '',
					fieldType: field.is(dateSelect) ? fieldType.date : (field.is(timeSelect) ? fieldType.time : fieldType.text),
					valueType: valueType.simple,
					required: field.is('[required]'),
					originalValue: field.val() || ''
				};
				fieldData.value = fieldData.originalValue;
				data.fields.push(fieldData);

				if (field.is('[data-show-progress="true"]')) {
					CivicWeb.Common.ProgressField.create(fieldData.id);
				}
			});

			//Coordinates fields
			fields.filter(coordinatesFieldSelect).each(function () {
				var field = $(this);
				coordinatesArguments.change = coordinatesChange;
				var coordinates = CivicWeb.Common.Coordinates.create(field.attr('id'), coordinatesArguments);
				var fieldData = {
					id: coordinates.getId(),
					fieldId: getFieldId(field),
					localization: '',
					fieldType: fieldType.coordinates,
					valueType: valueType.simple,
					required: field.is('[required]'),
					originalValue: coordinates.value()
				};
				fieldData.value = fieldData.originalValue;
				data.fields.push(fieldData);
			});

			//Check boxes
			fields.filter(checkBoxFieldSelect).each(function () {
				var field = $(this).off('change click').on('change click', checkBoxChange);
				var fieldData = {
					id: field.attr('id'),
					fieldId: getFieldId(field),
					localization: '',
					fieldType: fieldType.checkBox,
					valueType: valueType.simple,
					required: field.is('[required]'),
					originalValue: field.prop('checked') || false
				};
				fieldData.value = fieldData.originalValue;
				data.fields.push(fieldData);
			});

			//List boxes
			fields.filter(selectFieldSelect).each(function () {
				var field = $(this).off('change').on('change', listChange);
				var fieldData = {
					id: field.attr('id'),
					fieldId: getFieldId(field),
					localization: '',
					fieldType: field.is(meetingTypeFieldSelect) ? fieldType.meetingType : (field.is(meetingFieldSelect) ? fieldType.meeting : (field.is(headingFieldSelect) ? fieldType.heading : fieldType.select)),
					valueType: valueType.array,
					required: field.is('[required]'),
					originalValue: CivicWeb.Common.forceArray(field.val() || '')
				};
				fieldData.value = fieldData.originalValue;
				data.fields.push(fieldData);
			});

			//Radio buttons
			fields.filter(radioButtonListSelect).each(function () {
				var field = $(this);
				var selectedRadioButton = field.find(radioButtonSelect).off('change click').on('change click', radioButtonChange).filter(':checked');
				var fieldData = {
					id: field.attr('id'),
					fieldId: getFieldId(field),
					localization: '',
					fieldType: fieldType.radio,
					valueType: valueType.array,
					required: field.find(radioButtonSelect).filter('[required]').length > 0,
					originalValue: CivicWeb.Common.forceArray(selectedRadioButton.val() || '')
				};
				fieldData.value = fieldData.originalValue;
				data.fields.push(fieldData);
			});

			//Cascading drop downs
			fields.filter(cascadingDropDownFieldSelect).each(function () {
				var field = $(this);
				var cascadingDropDown = CivicWeb.Common.CascadingDropDown.create(field.attr('id'), {
					change: cascadingDropDownChange
				});
				var fieldData = {
					id: cascadingDropDown.getId(),
					fieldId: getFieldId(field),
					localization: '',
					fieldType: fieldType.cascading,
					valueType: valueType.simple,
					required: field.find('select').filter('[required]').length > 0,
					originalValue: cascadingDropDown.value()
				};
				fieldData.value = fieldData.originalValue;
				data.fields.push(fieldData);
			});

			//Programatically editable fields
			fields.filter(programmaticFieldSelect).each(function () {
				var field = $(this);
				var fieldData = {
					id: field.attr('id'),
					fieldId: getFieldId(field),
					localization: '',
					fieldType: fieldType.none,
					valueType: valueType.simple,
					required: false,
					originalValue: getDisplayFieldValue(field)
				};
				fieldData.value = fieldData.originalValue;
				data.fields.push(fieldData);
			});

			//Buttons
			fields.filter(buttonFieldSelect).each(function () {
				var field = $(this).off('click').on('click', buttonClick);
				var fieldData = {
					id: field.attr('id'),
					fieldId: getFieldId(field),
					localization: '',
					fieldType: fieldType.none,
					valueType: valueType.none,
					required: false,
					originalValue: ''
				};
				fieldData.value = fieldData.originalValue;
				data.fields.push(fieldData);
			});

			//Comment lists
			fields.filter(commentListFieldSelect).each(function () {
				var field = $(this);
				commentListArguements.change = commentListChange;
				var commentList = CivicWeb.Common.CommentList.create(field.attr('id'), commentListArguements);
				var fieldData = {
					id: commentList.getId(),
					fieldId: getFieldId(field),
					localization: '',
					fieldType: fieldType.comments,
					valueType: valueType.objectArray,
					required: field.is('[required]'),
					originalValue: commentList.value()
				};
				fieldData.value = fieldData.originalValue;
				data.fields.push(fieldData);
			});

			//Editors
			fields.filter(editorSelect).each(function () {
				var field = $(this);
				var fieldData = {
					id: field.attr('id'),
					fieldId: getFieldId(field),
					localization: field.attr(fieldLocalizationAttribute) || '',
					fieldType: fieldType.editor,
					valueType: valueType.simple,
					required: field.is('[required]'),
					originalValue: (field.text() || '').trim()
				};
				fieldData.value = fieldData.originalValue;

				$(this).kendoEditor({
					tools: CivicWeb.Common.Forms.editorTools,
					stylesheets: ['/css/kendo/editor/document?t=' + new Date().getTime(), '/settings/defaultfont'],
					messages: {
						fontNameInherit: kendoEditorLocalization.defaultFont,
						fontSizeInherit: kendoEditorLocalization.defaultFontSize
					},
					imageBrowser: CivicWeb.Common.Forms.getImageBrowser(kendoEditorLocalization.imageBrowserMessages),
					resizable: {
						content: true
					},
					keydown: kendoKeyDown,
					change: kendoChange,
					paste: kendoEditorPaste,
					value: fieldData.value
				});
				$(this).parent().height('auto').css('height', 'auto');

				$($(this).data('kendoEditor').toolbar.window.element).parent().css('font-size', '13px').css('font-family', 'Segoe UI, Helvetica, Tahoma, Arial, Calibri, Verdana, sans-serif');

				$(this).focus(function () {
					$('.editorToolbarWindow:visible').parent().hide();
					var toolbar = $($(this).data('kendoEditor').toolbar.window.element).parent();
					toolbar.css('position', 'static').show();
					$(this).parent().prepend(toolbar);
					$(this).css({ 'margin-top': toolbar.outerHeight(true) + 'px' });
				});

				$(this).blur(function () {
					$(this).css({ 'margin-top': '' });
				});

				$('#content').scroll(function () {
					var contentElem = $(this);
					if (($(document.activeElement).is('div[contenteditable="true"]') || $(document.activeElement).is('.editorToolbarWindow:visible'))) {

						var editorParent = $('.editorToolbarWindow:visible').parent();

						if ((($(document.activeElement).closest('div.inline-Editor').offset().top - contentElem.offset().top) < 0) && !(($(document.activeElement).closest('div.inline-Editor').offset().top + $(document.activeElement).closest('div.inline-Editor').outerHeight(true)) - ($(this).offset().top + $('.editorToolbarWindow:visible').parent().outerHeight(true) + $('footer').outerHeight(true)) < 0)) {
							if (!editorParent.parent().is(contentElem)) {
								//show on top of content
								contentElem.prepend(editorParent);
								editorParent.css('position', 'fixed').css('top', contentElem.offset().top);
								$(document.activeElement).closest('div.inline-Editor');
							}
						}
						else if (editorParent.parent().is(contentElem) && !(($(document.activeElement).closest('div.inline-Editor').offset().top - contentElem.offset().top) < $('.editorToolbarWindow:visible').outerHeight(true))) {
							// show on top of feild
							editorParent.css('position', 'fixed').css('top', 'initial').css('position', 'static');
							$(document.activeElement).closest('div.inline-Editor').prepend(editorParent).css('padding-top', '3px').css('border-top', '3px');
						}
						else if (editorParent.parent().is(contentElem) && (($(document.activeElement).closest('div.inline-Editor').outerHeight(true) - $(document.activeElement).closest('div.inline-Editor').offset().top) > contentElem.offset().top)) {
							// hide if scroll above content area
							editorParent.css('position', 'fixed').css('top', 'initial').css('position', 'static');
							$(document.activeElement).closest('div.inline-Editor').prepend(editorParent).css('padding-top', '3px').css('border-top', '3px');
						}
					}
				});


				data.fields.push(fieldData);
			});

			//Date pickers
			fields.filter(dateSelect).kendoDatePicker({
				format: dateFormat,
				change: kendoChange
			});

			//Time pickers
			fields.filter(timeSelect).kendoTimePicker({
				format: timeFormat,
				change: kendoChange
			});

			//Classification
			fields.filter(classificationSimplifiedSelect).add(classificationTextSelect).kendoAutoComplete({
				dataSource: {
					serverFiltering: true,
					delay: 500,
					transport: {
						read: function (options) {
							$.ajax({
								url: '/api/fields/classification/' + classificationArguements.classificationFieldId.toString() + '/values/matching?value=' + encodeURIComponent(options.data.filter.filters[0].value),
								contentType: 'application/json',
								dataType: 'json',
								async: true,
								cache: false,
								type: 'GET',
								success: function (result) {
									options.success(result);
								},
								error: function () {
									options.error();
								}
							});
						}
					}
				},
				select: function (e) {
					if (e.sender.element.closest(classificationFieldSelect).length > 0) {
						CivicWeb.Common.Classifications.setRetentionInformation(e.sender.element, classificationArguements.classificationFieldId, e.item.text());
					}
				},
				change: function (e) {
					if (e.sender.element.closest(classificationFieldSelect).length > 0) {
						CivicWeb.Common.Classifications.setRetentionInformation(e.sender.element, classificationArguements.classificationFieldId, e.sender.element.val());
					}
				}
			});

			//Read-only progress field
			$(formSelect).find('span[data-show-progress="true"]').each(function () {
				CivicWeb.Common.ProgressField.create($(this).attr('id'));
			});

			//Relationships
			CivicWeb.Common.Relationships.create(form.find('div[data-form-control-type="relationships"]'), relationshipsArguments);

			for (var index = 0; index < data.fields.length; index++) {
				data.fields[index].eventHandlers = {
					change: [],
					click: []
				};
			}

			forms.push(data);

			if (data.editHelp) {
				$(window).off('click', windowCloseHelpEditPopoverClick).on('click', windowCloseHelpEditPopoverClick);

				form.find('.form-help-icon[data-title]').off('click').on('click', fieldHelpClick).popover({
					sanitize: false,
					placement: 'auto',
					html: true,
					trigger: 'manual',
					title: localization.titleEditFieldHelp,
					content: function () {
						var helpIcon = $(this);
						var fieldId = helpIcon.attr('data-id');

						return $('<textarea></textarea>').attr({ 'id': fieldHelpEditorClientId + fieldId, 'class': 'form-help-editor', 'data-id': fieldId }).val(helpIcon.attr('data-title')).on('click', fieldHelpEditorClick).on('change', fieldHelpEditorChange);
					}
				}).on('hide.bs.popover', function () {
					var fieldId = $(this).attr('data-id');

					saveFieldHelp($(document.getElementById(fieldHelpEditorClientId + fieldId)));
				});
			}
			else {
				form.find('.form-help-icon[data-title]').tooltip();
			}
		});
	};

	var getFieldId = function (field) {
		return parseInt(field.attr(fieldIdAttribute));
	};

	var getDisplayFieldValue = function (field) {
		var value = '';
		if (field) {
			value = field.text();
			if (value === '&nbsp;') {
				value = '';
			}
		}

		return value;
	};

	var findForm = function (element) {
		var form = null;
		var id = CivicWeb.Common.getJqueryObject(element).closest(formSelect).attr('id');
		for (var index = 0; index < forms.length; index++) {
			if (forms[index].id === id) {
				form = forms[index];
				break;
			}
		}

		return form;
	};

	var findField = function (fieldId, form, localization) {
		var field = null;
		if (fieldId && form) {
			for (var index = 0; index < form.fields.length; index++) {
				if (form.fields[index].fieldId === fieldId && ('undefined' === typeof localization || localization == null || form.fields[index].localization === localization)) {
					field = form.fields[index];
				}
			}
		}

		return field;
	};

	var handleTextBoxChange = function (element, eventType, form, field, excludeLinked) {
		var value = element.val() || '';
		if (eventType !== 'keyup' && (field.fieldType === fieldType.date || field.fieldType === fieldType.time)) {
			value = window.kendo.parseDate(value, field.fieldType === fieldType.date ? dateFormat : timeFormat) || '';
			if (value.length === 0) {
				element.val('');
			}
			else {
				field.value = value;
			}
		}
		else {
			field.value = value;
		}
		checkFieldChanged(form, field, excludeLinked);
	};

	var handleCoordinatesChange = function (value, form, field, excludeLinked) {
		field.value = value;
		checkFieldChanged(form, field, excludeLinked);
	};

	var handleKendoChange = function (data, form, field, excludeLinked) {
		field.value = ((data.value() instanceof String ? data.value().trim() : data.value()) || '');
		if (field.value instanceof Date && (data instanceof window.kendo.ui.DatePicker || data instanceof window.kendo.ui.TimePicker)) {
			//Correct timezone offset
			field.value.setHours(field.value.getHours() - (field.value.getTimezoneOffset() / 60));
		}
		checkFieldChanged(form, field, excludeLinked);
	};

	var handleCheckBoxChange = function (element, form, field, excludeLinked) {
		field.value = element.prop('checked') || false;
		checkFieldChanged(form, field, excludeLinked);
	};

	var handleListChange = function (element, form, field, excludeLinked, headingsCallBack) {
		field.value = CivicWeb.Common.forceArray(element.val() || '');
		checkFieldChanged(form, field, excludeLinked);

		var value = field.value.length > 0 ? CivicWeb.Common.toNumber(field.value[0]) : 0;
		if (field.fieldType === fieldType.meeting) {
			getHeadings(form, value, headingsCallBack);
		}
	};

	var handleRadioButtonChange = function (element, form, field, excludeLinked) {
		field.value = CivicWeb.Common.forceArray(element.find(radioButtonSelect + ':checked').val() || '');
		checkFieldChanged(form, field, excludeLinked);
	};

	var checkFieldChanged = function (form, field, excludeLinked) {
		if (form && field) {
			form.updated = form.updated || ((field.valueType === valueType.simple && field.originalValue !== field.value) || ((field.valueType === valueType.array || field.valueType === valueType.objectArray) && !CivicWeb.Common.arraysEqual(field.originalValue, field.value)));
			CivicWeb.Common.callControlEventHandler(eventHandlers, 'change', { id: form.id, updated: isUpdatedInternal(true, form.id) });
			CivicWeb.Common.callControlEventHandler(field.eventHandlers, 'change', { id: field.id, formId: form.id, localization: field.localization, value: field.value });

			//Update linked forms
			if (!excludeLinked && (form.linkedForms || []).length > 0) {
				form.linkedForms.forEach(function (linkedForm) {
					updateLinkedForm(linkedForm, field);
				});
			}
		}
	};

	var updateLinkedForm = function (linkedForm, field) {
		var linkedField = findField(field.fieldId, linkedForm, field.localization);
		setFieldValue(linkedForm, linkedField, field.value, true);
	};

	var getFieldValue = function (form, field) {
		var value = null;
		if (form && field) {
			value = field.value;
		}

		return value || '';
	};

	var setFieldValue = function (form, field, value, excludeLinked) {
		if (form && field) {
			var element = $(document.getElementById(field.id));
			if (element.is(textFieldSelect) && element.is(':not(' + editorSelect + ',' + dateSelect + ',' + timeSelect + ')')) {
				element.val(value);
				handleTextBoxChange(element, undefined, form, field, excludeLinked);
			}
			else if (element.is(selectFieldSelect)) {
				element.val(value);
				handleListChange(element, form, field, excludeLinked);
			}
			else if (element.is(checkBoxFieldSelect)) {
				element.prop('checked', !!value);
				handleCheckBoxChange(element, form, field, excludeLinked);
			}
			else if (element.is(radioButtonListSelect)) {
				element.find(radioButtonSelect).prop('checked', false).filter('[value="' + value + '"]').prop('checked', true);
				handleRadioButtonChange(element, form, field, excludeLinked);
			}
			else if (element.is(programmaticFieldSelect)) {
				field.value = value && value !== '&nbsp;' ? value : '';
				element.html(value && value.length > 0 ? value : '&nbsp;');
				checkFieldChanged(form, field, excludeLinked);
			}
			else if (element.is(editorSelect)) {
				setKendoElementData(element, 'kendoEditor', value, form, field, excludeLinked);
			}
			else if (element.is(dateSelect)) {
				setKendoElementData(element, 'kendoDatePicker', value, form, field, excludeLinked);
			}
			else if (element.is(timeSelect)) {
				setKendoElementData(element, 'kendoTimePicker', value, form, field, excludeLinked);
			}
		}
	};

	var setKendoElementData = function (element, type, value, form, field, excludeLinked) {
		if (element) {
			element = element.data(type);
			element.value(value);
			handleKendoChange(element, form, field, excludeLinked);
		}
	};

	var getHeadings = function (form, meetingId, headingsCallBack) {
		var headings = $(document.getElementById(form.id)).find('select[data-list-type="heading"]:not([data-meeting-id="' + meetingId + '"])');
		headings.find('option:not([value="0"])').remove();
		headings.val(0);
		if (meetingId > 0) {
			var meetingHeadings = form.headings[meetingId];
			if (meetingHeadings) {
				meetingHeadings.forEach(function (heading) {
					headings
						.append($('<option></option>').attr({ 'value': heading.id }).text(heading.description));
				});

				headings.each(function () {
					var field = findField(getFieldId($(this)), form);
					if (field) {
						handleListChange($(this), form, field);
					}
				});

				if ('function' === typeof headingsCallBack) {
					headingsCallBack();
				}
			}
			else {
				$.ajax({
					url: '/api/meeting/' + meetingId + '/headings',
					type: 'GET',
					dataType: 'json',
					contentType: 'application/json',
					cache: false,
					async: true
				}).done(function (data) {
					form.headings[meetingId] = data || [];

					getHeadings(form, meetingId, headingsCallBack);
				});
			}
		}
	};

	var setMeetingValuesInternal = function (form, meetingTypeId, meetingId, headingId) {
		if (form) {
			//Update meeting types - They are not linked to the meeting drop-down so they can be done separately
			if (meetingTypeId > 0) {
				var meetingTypes = $(document.getElementById(form.id)).find('select[data-list-type="meeting-type"]');
				meetingTypes.val(meetingTypeId);
				meetingTypes.each(function () {
					var field = findField(getFieldId($(this)), form);
					if (field) {
						handleListChange($(this), form, field);
					}
				});
			}

			//Update the meetings
			if (meetingId > 0) {
				var meetings = $(document.getElementById(form.id)).find('select[data-list-type="meeting"]');
				meetings.val(meetingId);
				meetings.each(function () {
					var field = findField(getFieldId($(this)), form);
					if (field) {
						handleListChange($(this),
							form,
							field,
							undefined,
							function () {
								//Update the headings
								if (headingId > 0) {
									var headings = $(document.getElementById(form.id)).find('select[data-list-type="heading"]');
									headings.val(headingId);
									headings.each(function () {
										var field = findField(getFieldId($(this)), form);
										if (field) {
											handleListChange($(this), form, field);
										}
									});
								}
							});
					}
				});
			}
		}
	};

	this.on = function (event, handler, fieldId) {
		onOff(event, handler, fieldId, CivicWeb.Common.addControlEventHandler);
	};

	this.off = function (event, handler, fieldId) {
		onOff(event, handler, fieldId, CivicWeb.Common.removeControlEventHandler);
	};

	var onOff = function (event, handler, fieldId, addRemoveMethod) {
		if (fieldId) {
			for (var index = 0; index < forms.length; index++) {
				var form = forms[index];
				for (var index2 = 0; index2 < form.fields.length; index2++) {
					var field = form.fields[index2];
					if (field.fieldId === fieldId) {
						addRemoveMethod(field.eventHandlers, event, handler);
					}
				}
			}
		}
		else {
			addRemoveMethod(eventHandlers, event, handler);
		}
	};

	this.enable = function (control) {
		var form = findForm(control);
		if (form) {
		}
	};

	this.disable = function (control) {
		var form = findForm(control);
		if (form) {
		}
	};

	this.value = function (control, fieldId, value, updateEmptyFieldOnly, localization) {
		var form = findForm(control);
		var field = findField(fieldId, form, localization);
		var fieldValue = null;
		if (field) {
			if ('undefined' === typeof value || value == null) {
				fieldValue = getFieldValue(form, field);
			}
			else if (!updateEmptyFieldOnly || !field.value || field.value.length === 0) {
				setFieldValue(form, field, value);
			}
		}
		else if (form) {
			//Update span
			var span = $(document.getElementById(form.id)).find('span[' + fieldIdAttribute + '="' + fieldId + '"]');
			if ('undefined' === typeof value || value == null) {
				fieldValue = span.html();
			}
			else if (!updateEmptyFieldOnly || span.text().trim().length === 0) {
				span.html(value || '');
			}
		}

		return fieldValue;
	};

	this.link = function (controls) {
		if (controls && controls.length > 0) {

			var controlForms = controls.map(function (control) {
				return findForm(control);
			});

			controlForms.forEach(function (form) {
				form.linkedForms = controlForms.filter(function (otherForm) {
					return otherForm.id !== form.id;
				});
			});
		}
	};

	this.show = function (control, fieldId) {
		var form = findForm(control);
		var field = findField(fieldId, form);
		if (field) {
			$(document.getElementById(field.id)).closest('.form-field').removeClass('hidden');
		}
	};

	this.hide = function (control, fieldId) {
		var form = findForm(control);
		var field = findField(fieldId, form);
		if (field) {
			$(document.getElementById(field.id)).closest('.form-field').addClass('hidden');
		}
	};

	this.label = function (control, fieldId, text, cssClass, styles, group) {
		var form = findForm(control);
		if (group) {
			CivicWeb.Common.setStyles(CivicWeb.Common.getJqueryObject($(document.getElementById(form.id)).find('.form-group')[fieldId]).find('legend'), cssClass, styles).text(text);
		}
		else {
			CivicWeb.Common.setStyles($(document.getElementById(form.id)).find('label[for="' + form.id + '-field-' + fieldId.toString() + '"]'), cssClass, styles).text(text);
		}
	};

	this.isUpdated = function (deepCheck, formId) {
		return isUpdatedInternal(deepCheck, formId);
	};

	var isUpdatedInternal = function (deepCheck, formId) {
		var updated = false;

		var formsToCheck = CivicWeb.Common.removeNull(formId ? CivicWeb.Common.forceArray(findForm(formId)) : forms);
		for (var index = 0; index < formsToCheck.length; index++) {
			var form = formsToCheck[index];
			if (deepCheck) {
				//Check all fields directly
				for (var index2 = 0; index2 < form.fields.length; index2++) {
					var field = form.fields[index2];
					if (updated = ((field.valueType === valueType.simple && field.originalValue !== field.value) || (field.valueType === valueType.array && !CivicWeb.Common.arraysEqual(field.originalValue, field.value)))) {
						break;
					}
				}

				if (updated) {
					break;
				}
			}
			else {
				if (updated = form.updated) {
					break;
				}
			}
		}

		return updated;
	};

	var closeAllHelpEditPopovers = function (exclude) {
		$('.form-help-icon[data-title]').not(exclude).popover('hide');
	};

	var saveFieldHelp = function (editor) {
		var fieldId = CivicWeb.Common.toNumber(editor.attr('data-id'));

		var field = fields.find(function (field) {
			return field.id === fieldId;
		});
		if (!field) {
			fields.push(field = {
				id: fieldId
			});
		}

		field.helpText = editor.val();

		$('.form-help-icon[data-title][data-id="' + fieldId + '"]').attr({ 'data-title': field.helpText });
	};

	var validateInternal = this.validate = function (validationMessages, setFocus, formId) {
		var valid = false;
		if ('undefined' !== typeof formId) {
			var form = findForm(formId);
			if (form) {
				var formElement = $(document.getElementById(form.id));
				formElement.find('input, select, textarea, table.k-editor-widget, div.k-editor-inline').removeClass('invalid');

				valid = true;

				for (var index = 0; index < form.fields.length; index++) {
					var field = form.fields[index];
					if (field && field.valueType !== valueType.none) {
						var fieldValid = (!field.required ||
							(field.valueType === valueType.simple && (('string' === typeof field.value && field.value.trim().length > 0) || ('number' === typeof field.value && field.value > 0) || ('boolean' === typeof field.value && field.value) || (field.value instanceof Date && field.value.getTime() !== 0))) ||
							(field.valueType === valueType.array && field.value && field.value.length > 0 && field.value.some(function (value) { return CivicWeb.Common.toNumber(value) > 0; })));

						valid = valid && fieldValid;
						if (!fieldValid) {
							if (validationMessages) {
								validationMessages.push(localization.warningMessageTheFieldIsRequired.replace('{0}', field.label || $('label[for="' + field.id + '"]').text()));
							}

							if (field.fieldType === fieldType.editor) {
								var element = $(document.getElementById(field.id));
								element.addClass('invalid');
								element.closest('table.k-editor-widget').addClass('invalid');
								element.closest('div.k-editor-inline').addClass('invalid');
							}
							else if (field.fieldType === fieldType.radio) {
								$(document.getElementById(field.id)).find(radioButtonSelect).addClass('invalid');
							}
							else if (field.fieldType === fieldType.cascading) {
								$(document.getElementById(field.id)).find('select').addClass('invalid');
							}
							else {
								$(document.getElementById(field.id)).addClass('invalid');
							}
						}
					}
				}

				if (setFocus) {
					//Focus on the first element of the form
					var invalidElement = formElement.find('.invalid:first');
					if (invalidElement.length > 0) {
						var isEditor = invalidElement.is('table.k-editor-widget.invalid:first');
						if (isEditor) {
							invalidElement = invalidElement.find('textarea');
						}

						var field = form.fields.find(function (field) {
							return field.fieldId === getFieldId(invalidElement.closest('[' + fieldIdAttribute + ']'));
						});

						if ('function' === typeof field.focus) {
							field.focus();
						}
						else if (isEditor) {
							invalidElement.data('kendoEditor').focus();
						}
						else {
							invalidElement.focus();
						}
					}

					setFocus = false;
				}
			}
		}
		else {
			//Check all forms
			valid = forms.reduce(function (valid, form) {
				return validateInternal(validationMessages, setFocus, form.id) && valid;
			}, true);
		}

		return valid;
	};

	this.buildFormObject = function (formId) {
		var formData = null;
		var form = findForm(formId);
		if (form) {
			formData = {
				fields: []
			};
			for (var index = 0; index < form.fields.length; index++) {
				var field = form.fields[index];
				if (field && field.valueType !== valueType.none) {
					formData.fields.push({ id: field.fieldId, localization: field.localization, valueType: field.valueType, value: typeof field.value === 'string' ? field.value.replaceAll("'", "''").replaceAll("=", "==") : field.value, escaped: typeof field.value === 'string' });
				}
			}
		}

		return formData;
	};

	this.buildFieldsObject = function () {
		return fields;
	};

	this.setMeetingValues = function (formId, meetingTypeId, meetingId, headingId) {
		if (formId) {
			setMeetingValuesInternal(findForm(formId), meetingTypeId, meetingId, headingId);
		}
		else {
			forms.forEach(function (form) {
				setMeetingValuesInternal(form, meetingTypeId, meetingId, headingId);
			});
		}
	};

	(function () {
		load();

		CivicWeb.Common.Classifications.createInstance(classificationArguements);
	})();
};

//Objects
CivicWeb.Common.Forms = {
	//Properties
	instance: null,
	editorTools: ['viewHtml', 'cleanFormatting',
		'bold', 'italic', 'underline', 'strikethrough',
		'createLink', 'unlink',
		'insertUnorderedList', 'insertOrderedList', 'indent', 'outdent',
		'justifyLeft', 'justifyCenter', 'justifyRight', 'justifyFull',
		'tableWizard', 'createTable', 'addRowAbove', 'addRowBelow', 'addColumnLeft', 'addColumnRight', 'deleteRow', 'deleteColumn', 'mergeCellsHorizontally', 'mergeCellsVertically', 'splitCellHorizontally', 'splitCellVertically',
		'insertImage',
		'foreColor', 'backColor', 'fontName', {
			name: "fontSize",
			items: [
				{ text: "8pt", value: "8pt" },
				{ text: "10pt", value: "10pt" },
				{ text: "12pt", value: "12pt" },
				{ text: "14pt", value: "14pt" },
				{ text: "18pt", value: "18pt" },
				{ text: "24pt", value: "24pt" },
				{ text: "36pt", value: "36pt" }
			]
		}
	],
	pending: [],

	createInstance: function (args) {
		if (this.instance) {
			delete this.instance;
		}
		this.instance = new CivicWeb.Common.Form(args, window.jQuery);

		//Call pending methods
		for (var index = 0; index < this.pending.length; index++) {
			var method = this.pending[index];
			if ('function' === typeof method) {
				method();
			}
		}

		this.pending = [];
	},

	on: function (event, handler, fieldId) {
		if (this.instance) {
			this.instance.on(event, handler, fieldId);
		}
		else {
			this.pending.push(function () { CivicWeb.Common.Forms.on(event, handler, fieldId); });
		}
	},

	off: function (event, handler, fieldId) {
		if (this.instance) {
			this.instance.off(event, handler, fieldId);
		}
		else {
			this.pending.push(function () { CivicWeb.Common.Forms.off(event, handler, fieldId); });
		}
	},

	value: function (control, fieldId, value, updateEmptyFieldOnly, localization) {
		return this.instance.value(control, fieldId, value, updateEmptyFieldOnly, localization);
	},

	link: function (controls) {
		this.instance.link(controls);
	},

	show: function (control, fieldId) {
		this.instance.show(control, fieldId);
	},

	hide: function (control, fieldId) {
		this.instance.hide(control, fieldId);
	},

	label: function (control, fieldId, text, cssClass, styles, group) {
		this.instance.label(control, fieldId, text, cssClass, styles, group);
	},

	enable: function (control) {
		return this.instance.enable(control);
	},

	disable: function (control) {
		return this.instance.disable(control);
	},

	isUpdated: function (deepCheck, formId) {
		return this.instance.isUpdated(deepCheck, formId);
	},

	validate: function (validationMessages, setFocus, formId) {
		return this.instance.validate(validationMessages, setFocus, formId);
	},

	buildFormObject: function (formId) {
		return this.instance.buildFormObject(formId);
	},

	buildFieldsObject: function () {
		return this.instance.buildFieldsObject();
	},

	setMeetingValues: function (formId, meetingTypeId, meetingId, headingId) {
		if (this.instance) {
			this.instance.setMeetingValues(formId, meetingTypeId, meetingId, headingId);
		}
	},

	classificationAutoComplete: function (element, classificationFieldId) {
		element = CivicWeb.Common.getJqueryObject(element);

		element.kendoAutoComplete({
			dataSource: {
				serverFiltering: true,
				delay: 500,
				transport: {
					read: function (options) {
						var value = options.data.filter.filters[0].value || '';
						window.$.ajax({
							url: '/api/fields/classification/' + classificationFieldId.toString() + '/values/matching?value=' + encodeURIComponent(value),
							contentType: 'application/json', dataType: 'json', async: true, cache: false, type: 'GET',
							success: function (result) {
								//Get other values
								var sort = false;
								var activeId = CivicWeb.Common.getJqueryObject(document.activeElement).attr('data-id') || '';
								element.each(function () {
									var textBox = window.$(this);
									var otherValue = textBox.val() || '';
									if (textBox.attr('data-id') !== activeId && otherValue.length > 0 && otherValue.toLowerCase().indexOf(value.toLowerCase()) === 0 && window.$.inArray(otherValue, result) === -1) {
										result.push(textBox.val());

										sort = true;
									}
								});

								if (sort) {
									result.sort(function (a, b) {
										return a.toLowerCase().localeCompare(b.toLowerCase());
									});
								}

								options.success(result);
							},
							error: function () {
								options.error();
							}
						});
					}
				}
			}
		});

		return element;
	},

	getImageBrowser: function (messages) {
		return {
			messages: messages,
			transport: {
				read: {
					url: '/filepro/documents/images',
					type: 'GET'
				},
				destroy: {
					url: '/api/documents/image',
					type: 'DELETE'
				},
				create: {
					url: '/api/documents/image/folder',
					type: 'POST'
				},
				thumbnailUrl: '/filepro/documents/image/thumbnail',
				uploadUrl: '/api/documents/image',
				imageUrl: '/filepro/documents/image/{0}'
			},
			fileTypes: '.jpg,.jpeg,.png,.gif,.bmp'
		};
	}
};
;
window.CivicWeb = window.CivicWeb || {};
CivicWeb.Common = CivicWeb.Common || {};

(function (library, $)
{
	//Variables
	var resizeFixed;
	var scrollFixed;

	//Methods
	library.applyFixedHeader = function (grid)
	{
		var wrapper = grid.wrapper;
		var header = wrapper.find('.k-grid-header');

		//TODO: Get rid of this once we don't support IE 11 anymore
		if (CivicWeb.Common.isIe())
		{
			//Set table column widths
			var widths = [];
			header.find('th').each(function ()
			{
				var header = $(this);
				widths.push(header.outerWidth());
				header.css({ 'min-width': header.width() + 'px' });
			});
			wrapper.find('col').each(function (index)
			{
				var column = $(this);
				var style = column.attr('style') || '';
				if (style.indexOf('width') < 0)
				{
					column.width(widths[index]);
				}
			});
			header.closest('table').css({ 'table-layout': 'fixed' });

			//Get scrollable parent
			var scrollableParent = $(window);
			header.parents().each(function ()
			{
				var elementStyle = this.currentStyle || window.getComputedStyle(this, '');
				var overflow = elementStyle.overflow;
				var found = false;
				if ('auto' === overflow)
				{
					scrollableParent = $(this);

					found = true;
				}

				return !found;
			});

			$(window).off('resize', resizeFixed);
			scrollableParent.off('scroll', scrollFixed);

			resizeFixed = function ()
			{
				var paddingRight = parseInt(header.css('padding-right'));
				header.css('width', wrapper.width() - paddingRight);
			};

			scrollFixed = function ()
			{
				var offset = $(this).scrollTop() - 1;
				var tableOffsetTop = wrapper.scrollTop();
				var tableOffsetBottom = tableOffsetTop + wrapper.height() - header.height();
				if (offset <= tableOffsetTop || offset > tableOffsetBottom)
				{
					header.removeClass('fixed-header').css({ 'top': '' });
				}
				else if (offset >= tableOffsetTop && offset <= tableOffsetBottom)
				{
					console.log(offset + ' ; ' + tableOffsetTop + ' ; ' + tableOffsetBottom);
					header.addClass('fixed-header').css({ 'top': offset + 'px' });
				}
			};

			resizeFixed();

			$(window).on('resize', resizeFixed);
			scrollableParent.on('scroll', scrollFixed);
		}
		else
		{
			header.addClass('fixed-header');
		}
	};
})(window.CivicWeb.Common.Grid = window.CivicWeb.Common.Grid || {}, jQuery);
;
// Declare namespaces
var CivicWeb = CivicWeb || {};
CivicWeb.Common = CivicWeb.Common || {};

//Create classes
CivicWeb.Common.HistoryList = function (args) {
	//Properties
	var clientId = args.clientId;

	var container = args.container && args.container instanceof jQuery ? args.container : (args.container && args.container instanceof HTMLElement ? $(args.container) : (args.container && args.container.length ? $(document.getElementById(args.container)) : null));
	var restore = args.restore;
	var detailUrl = args.detailUrl;

	var localization = {
		expandToolTipText: args.localization.expandToolTipText,
		collapseToolTipText: args.localization.collapseToolTipText,
		restoreChangesWarningMessageText: args.localization.restoreChangesWarningMessageText,
		labelNoChanges: args.localization.labelNoChanges
	};

	var images = {
		expandImage: 'https://i.civicweb.net/Global/Images/Node_Open.png',
		collapseImage: 'https://i.civicweb.net/Global/Images/Node_Close.png'
	};

	//Event Handlers
	var dataToggleClick = function (e) {
		//Check to see which changes need to be shown
		var showAll = true;
		var visibleDataTypes = [];
		var hiddenDataTypes = [];
		var togglesContainer = $(e.target).closest('.history-data-toggle-container');
		togglesContainer.find('input[type="checkbox"]').each(function () {
			var checkBox = $(this);
			var checked = checkBox.prop('checked');
			showAll = showAll && checked;
			if (checked) {
				visibleDataTypes.push(checkBox.attr('data-change-type').toLowerCase());
			}
			else {
				hiddenDataTypes.push(checkBox.attr('data-change-type').toLowerCase());
			}
		});

		//Toggle changes
		var historyTable = container.find('table.history-table');
		historyTable.find('tr.history-change-set').removeClass('hidden');
		historyTable.find('tr.history-table-change-set-detail').find('div').removeClass('hidden');
		if (!showAll) {
			historyTable.find('tr.history-change-set').each(function () {
				var row = $(this);
				var dataChangeTypes = row.attr('data-change-types').split(' ');
				var show = false;
				for (var index = 0; index < dataChangeTypes.length; index++) {
					for (var index2 = 0; index2 < visibleDataTypes.length; index2++) {
						show = dataChangeTypes[index].toLowerCase() === visibleDataTypes[index2].toLowerCase();
						if (show) {
							break;
						}
					}

					if (show) {
						break;
					}
				}

				if (!show) {
					//Hide row
					row.addClass('hidden');
					toggleChangeSetDetail(row.find('img.history-expand-image'), false);
				}
				else {
					//Hide detail tables
					var changeSetId = row.attr('data-change-set-id');
					for (var index3 = 0; index3 < hiddenDataTypes.length; index3++) {
						$('.history-table-change-set-detail[data-change-set-id="' + changeSetId + '"]').find('div[data-change-type="' + hiddenDataTypes[index3] + '"]').addClass('hidden');
					}
				}
			});
		}
	};

	var allChangeSetsExpandCollapseClick = function (e) {
		var button = $(e.target);
		var expand = button.attr('src') === images.expandImage;
		button.attr({ 'src': expand ? images.collapseImage : images.expandImage, 'alt': expand ? localization.collapseToolTipText : localization.expandToolTipText, 'title': expand ? localization.collapseToolTipText : localization.expandToolTipText });
		container.find('img.history-expand-image[data-change-set-id]').each(function () {
			toggleChangeSetDetail($(this), expand);
		});
	};

	var changeSetExpandCollapseClick = function (e) {
		toggleChangeSetDetail($(e.target));
	};

	var restoreClick = function (e) {
		if (restore && typeof restore === 'function' && confirm(localization.restoreChangesWarningMessageText)) {
			var button = $(e.target).closest('button');

			restore({ clientId: clientId, changeSetId: button.attr('data-change-set-id'), type: button.attr('data-change-type'), button: button });
		}
	};

	//Methods
	var loadDetail = function (detailRow, changeSetId) {
		if (detailUrl)
		{
			$.ajax({
				url: detailUrl.replace('{changeSetId}', changeSetId),
				type: 'GET',
				dataType: 'json',
				contentType: 'application/json',
				cache: false,
				async: true
			}).done(function(data)
			{
					detailRow
						.find('td')
						.empty()
						.append(data && data.html ? data.html : localization.labelNoChanges);
			});
		}
	};

	var toggleChangeSetDetail = function (button, show) {
		if (button) {
			var expand = typeof show === 'boolean' ? show : (button.attr('src') === images.expandImage);
			button.attr({ 'src': expand ? images.collapseImage : images.expandImage, 'alt': expand ? localization.collapseToolTipText : localization.expandToolTipText, 'title': expand ? localization.collapseToolTipText : localization.expandToolTipText });
			var detailTable = $('tr.history-table-change-set-detail[data-change-set-id="' + button.attr('data-change-set-id') + '"]');
			if (expand) {
				// Show loading indicator if needed
				if (detailTable.attr('data-loaded').toLowerCase() === 'false') {
					loadDetail(detailTable, button.attr('data-change-set-id'));

					detailTable
						.find('td')
						.empty()
						.append($('<div></div>').addClass('history-change-set-loading')
							.append(CivicWeb.Common.Button.getThrobber()));
				}

				detailTable.removeClass('hidden');
			}
			else {
				detailTable.addClass('hidden');
			}
		}
	};

	(function () {
		container.find('.history-data-toggle-container input[type="checkbox"]').off('click').on('click', dataToggleClick);
		container.find('th img.history-expand-image').off('click').on('click', allChangeSetsExpandCollapseClick);
		container.find('td img.history-expand-image').off('click').on('click', changeSetExpandCollapseClick);
		container.find('button[data-type="restore"]').off('click').on('click', restoreClick);
	})();
};

//Objects
CivicWeb.Common.HistoryLists = {
	//Properties
	instances: new Array(),

	//Methods
	getInstance: function (clientId) {
		var found = null;
		for (var index = 0; index < this.instances.length; index++) {
			var current = this.instances[index];
			if (current.getClientId() === clientId) {
				found = current;
				break;
			}
		}

		return found;
	},

	getIndex: function (clientId) {
		var index;
		for (index = 0; index < this.instances.length; index++) {
			var current = this.instances[index];
			if (current.getClientId() === clientId) {
				break;
			}
		}

		return index >= this.instances.length ? -1 : index;
	},

	createInstance: function (args) {
		var instance = this.getInstance(args.clientId);
		var index = this.getIndex(args.clientId);
		if (instance) {
			delete instance;
		}
		if (index < 0) {
			index = this.instances.length;
		}
		this.instances[index] = new CivicWeb.Common.HistoryList(args);
	},

	//Events
	Events: {
	}
};
;
window.CivicWeb = window.CivicWeb || {};
window.CivicWeb.Common = window.CivicWeb.Common || {};

(function (library, $)
{
	//TODO: Cannot use strict mode until AgendaPopUp.aspx is no longer used - this includes jQuery

	//Properties
	var instances = [];

	//Classes
	// ReSharper disable once InconsistentNaming
	var Control = function (id, args)
	{
		var clientId = id;
		var loadingClientId = id + '-loading';
		var exportClientId = id + '-export';
		var detailClientId = id + '-detail';
		var detailSubjectClientId = detailClientId + '-subject';
		var detailBodyClientId = detailClientId + '-body';

		var baseClass = 'history-notification';
		var detailClass = baseClass + '-detail';
		var detailSectionClass = detailClass + '-section';

		var localization = args.localization;

		var itemId = args.itemId;
		var meetingId = args.meetingId;
		var meetingOutputType = args.meetingOutputType;
		var onMeetingTab = !!args.onMeetingTab;
		var webFormsNotificationControlClientId = args.webFormsNotificationControlClientId || '';
		var historyLoaded = args.historyLoaded;

		var control = this;

		var container;
		var page = 1;
		var notifications = [];

		var statuses = {
			success: 1,
			partialSuccess: 2,
			failure: 3,
			backupSuccess: 4,
			backupPartialSuccess: 5,
		};

		//Event Handlers
		var exportClick = function (e)
		{
			window.location.href = itemId ?
				'/item/' + itemId + '/notificationhistoryexport' :
				'/meeting/' + meetingId + '/notificationhistoryexport?outputtype=' + meetingOutputType;

			e.preventDefault();
		};

		var pagerClick = function (e)
		{
			page = CivicWeb.Common.toNumber(parseInt($(e.target).closest('a').attr('data-page')), 1);

			loadHistory();

			e.preventDefault();
		};

		var viewButtonClick = function (e)
		{
			var notificationId = parseInt($(e.target).closest('button').attr('data-id'));
			if (!isNaN(notificationId) && notificationId > 0)
			{
				showDetail(findNotification(notificationId));
			}

			e.preventDefault();
		};

		var editButtonClick = function (e, cancel)
		{
			var notificationId = parseInt($(e.target).closest('button').attr('data-id'));
			var notification;
			if (!isNaN(notificationId) && notificationId > 0 && (notification = findNotification(notificationId)) != null)
			{
				if (webFormsNotificationControlClientId.length === 0)
				{
					CivicWeb.Common.NotificationControls.updateMeeting(notification, cancel);
				}
				else
				{
					if (cancel)
					{
						$(document.getElementById(webFormsNotificationControlClientId + '_meetingStatus')).val('Cancel');
						$(document.getElementById(webFormsNotificationControlClientId + '_btnSend')).val('Cancel').css({ 'font-weight': 'bold', 'font-size': '13px' });
					}
					else
					{
						$(document.getElementById(webFormsNotificationControlClientId + '_btnSend')).val('Update').css({ 'font-weight': 'bold', 'font-size': '13px' });
					}
					$(document.getElementById(webFormsNotificationControlClientId + '_meetingGUI')).val(notification.meetingGuid);
					$(document.getElementById(webFormsNotificationControlClientId + '_meetingSequence')).val(notification.meetingSequence);

					//populate the meeting fields and change the 'Send' button to an 'Update' button
					$(document.getElementById(webFormsNotificationControlClientId + '_txtTo')).val(notification.to);
					$(document.getElementById(webFormsNotificationControlClientId + '_txtCc')).val(notification.cc);
					$(document.getElementById(webFormsNotificationControlClientId + '_txtBcc')).val(notification.bcc);
					$(document.getElementById(webFormsNotificationControlClientId + '_txtSubject')).val(notification.subject);
					$(document.getElementById(webFormsNotificationControlClientId + '_location')).val(notification.location);

					var fromDate = window.$find(webFormsNotificationControlClientId + '_fromDate');
					if (fromDate != null)
					{
						fromDate.set_selectedDate(new Date(notification.startTime));
					}

					var toDate = window.$find(webFormsNotificationControlClientId + '_toDate');
					if (toDate != null)
					{
						toDate.set_selectedDate(new Date(notification.endTime));
					}

					var fromTime = window.$find(webFormsNotificationControlClientId + '_fromTime');
					if (fromTime != null)
					{
						fromTime.set_selectedDate(new Date(notification.startTime));
					}

					var toTime = window.$find(webFormsNotificationControlClientId + '_toTime');
					if (toTime != null)
					{
						toTime.set_selectedDate(new Date(notification.endTime));
					}

					var reminder = window.$find(webFormsNotificationControlClientId + '_reminder');
					if (reminder != null)
					{
						var item = reminder.findItemByValue(notification.reminder);
						if (item)
						{
							item.select();
						}
					}

					var editor = window.$find(webFormsNotificationControlClientId + '_body-editor');
					if (editor != null)
					{
						editor.set_html(notification.body);
					}
				}
			}

			e.preventDefault();
		};

		var cancelButtonClick = function (e)
		{
			editButtonClick(e, true);

			e.preventDefault();
		};

		//Functions
		var showLoading = function ()
		{
			return (container || (container = $(document.getElementById(clientId)))).empty().addClass(baseClass)
				.append($('<div></div>').attr({ 'id': loadingClientId, 'class': baseClass + '-loading' })
					.append($('<div></div>').addClass('center-middle')
						.append($('<span></span>')
							.append(CivicWeb.Common.Button.getThrobber(loadingClientId + '-throbber')))));
		};

		var loadHistory = function ()
		{
			return $.ajax({
				url: itemId ?
					'/api/item/' + itemId + '/notificationhistory?page=' + page :
					'/api/meeting/' + meetingId + '/notificationhistory?meetingoutputtype=' + meetingOutputType + '&page=' + page,
				contentType: 'application/json',
				dataType: 'json',
				async: true,
				cache: false,
				type: 'GET'
			}).done(function (data)
			{
				if (data)
				{
					notifications = data.notifications;
					displayHistory(data);

					if ('function' === typeof historyLoaded)
					{
						historyLoaded({ hasHistory: notifications.length > 0 });
					}
				}
			});
		};

		var displayHistory = function (history)
		{
			if (history)
			{
				var innerContainer;

				container.empty()
					.append(innerContainer = $('<div></div>').addClass(baseClass)
						.append(CivicWeb.Common.Button.create(exportClientId, localization.buttonExport, localization.toolTipExportToExcel, CivicWeb.Common.Button.types.short, undefined, 'fas fa-file-excel').on('click', exportClick))
						.append(CivicWeb.Common.Pager.create(history.page, history.pages, pagerClick, false, localization.pagerLocalization)));

				for (var index = 0; index < history.notifications.length; index++)
				{
					var notification = history.notifications[index];

					var item;
					var recipients;

					innerContainer
						.append(item = $('<div></div>').addClass(baseClass + '-item')
							.append(recipients = $('<div></div>').addClass(baseClass + '-recipients')));

					if (notification.externalEmailAddresses.length > 0)
					{
						recipients
							.append($('<div></div>').text(localization.labelExternalEmailAddresses));

						notification.externalEmailAddresses.reduce(function (recipients, emailAddress)
						{
							return recipients
								.append($('<div></div>').addClass(baseClass + '-email-address').text(emailAddress));
						}, recipients);
					}

					notification.internalEmailAddresses.reduce(function (item, emailAddress)
					{
						var recipients;

						item
							.append(recipients = $('<div></div>').addClass(baseClass + '-recipients'));

						emailAddress.displayNames.reduce(function (recipients, displayName)
						{
							return recipients
								.append($('<div></div>').text(displayName));
						}, recipients);

						recipients
							.append($('<div></div>').addClass(baseClass + '-email-address').text(emailAddress.emailAddress));

						return item;
					}, item);

					var notificationSendByClientId = clientId + '-notification-send-by-' + notification.id;
					item
						.append($('<div></div>').addClass(baseClass + '-date-sent').text(notification.dateSent))
						.append($('<div></div>').addClass(baseClass + '-sent-by')
							.append($('<label></label>').attr({ 'for': notificationSendByClientId }).text(localization.formFieldLabelSentBy))
							.append($('<span></span>').attr({ 'id': notificationSendByClientId }).text(notification.sentBy)));

					var buttons;

					item
						.append($('<div></div>').addClass(baseClass + '-status')
							.append(notification.status > 0 ?
								CivicWeb.Common.Notification.create(
									clientId + '-status-' + notification.id,
									[statuses.success, statuses.backupSuccess].includes(notification.status) ? CivicWeb.Common.Notification.types.success : ([statuses.partialSuccess, statuses.backupPartialSuccess].includes(notification.status) ? CivicWeb.Common.Notification.types.warning : CivicWeb.Common.Notification.types.failure),
									getStatusText(notification.status),
									false) :
								null))
						.append(buttons = $('<div></div>').addClass(baseClass + '-buttons')
							.append($('<span></span>').addClass(baseClass + '-view')
								.append(CivicWeb.Common.Button.create(clientId + '-notification-view-button-' + notification.id, localization.buttonView, localization.toolTipViewNotification, CivicWeb.Common.Button.types.short, { 'data-id': notification.id }).on('click', viewButtonClick))));

					if (notification.meetingGuid.length > 0)
					{
						if (notification.canceled)
						{
							buttons
								.append($('<span></span>').addClass(baseClass + '-canceled').text(localization.labelThisMeetingHasBeenCanceled));
						}
						else
						{
							var attributes = { 'data-id': notification.id };
							buttons
								.append($('<span></span>').addClass(baseClass + '-edit')
									.append(CivicWeb.Common.Button.create(clientId + '-notification-edit-button-' + notification.id, localization.buttonUpdateMeeting, localization.toolTipUpdateCancelMeetingNotification, CivicWeb.Common.Button.types.short, attributes).on('click', editButtonClick)))
								.append($('<span></span>').addClass(baseClass + '-cancel')
									.append(CivicWeb.Common.Button.create(clientId + '-notification-cancel-button-' + notification.id, localization.buttonCancelMeeting, localization.toolTipUpdateCancelMeetingNotification, CivicWeb.Common.Button.types.short, attributes).on('click', cancelButtonClick)));

							CivicWeb.Common.Button.update(clientId + '-notification-edit-button-' + notification.id, '', !onMeetingTab, false);
							CivicWeb.Common.Button.update(clientId + '-notification-cancel-button-' + notification.id, '', !onMeetingTab, false);
						}
					}
				}

				innerContainer
					.append(CivicWeb.Common.Pager.create(history.page, history.pages, pagerClick, false, localization.pagerLocalization));
			}
		};

		var getStatusText = function (status) {
			switch (status) {
				case statuses.success:
					return localization.notificationSuccess;

				case statuses.partialSuccess:
					return localization.notificationPartialSuccess;

				case statuses.backupSuccess:
					return localization.notificationBackupSuccess;

				case statuses.backupPartialSuccess:
					return localization.notificationBackupPartialSuccess;

				default:
					return localization.notificationFailure;
			}
		}

		var findNotification = function (id)
		{
			return notifications.find(function (notification)
			{
				return notification.id === id;
			});
		};

		var showDetail = function (notification)
		{
			if (notification)
			{
				if (CivicWeb.Common.loadKendoUi(function () { showDetail(notification); }))
				{
					var popup = $(document.getElementById(detailClientId));
					if (popup.length === 0)
					{
						//Create popup
						container
							.append(popup = $('<div></div>').attr({ 'id': detailClientId, 'class': detailClass })
								.append($('<div></div>').attr({ 'class': detailSectionClass })
									.append($('<div></div>')
										.append($('<label></label>').attr({ 'for': detailSubjectClientId }).text(localization.subjectText)))
									.append($('<div></div>').attr({ 'id': detailSubjectClientId })))
								.append($('<div></div>').attr({ 'class': detailSectionClass })
									.append($('<div></div>')
										.append($('<label></label>').attr({ 'for': detailBodyClientId }).text(localization.bodyText)))
									.append($('<div></div>').attr({ 'id': detailBodyClientId }))));

						popup.kendoWindow({
							modal: true,
							visible: false,
							width: '40%',
							height: '50%',
							minWidth: '600px',
							title: localization.notificationTitleText
						});

						popup.data('kendoWindow').center();
					}

					$(document.getElementById(detailSubjectClientId)).text(notification.subject);
					$(document.getElementById(detailBodyClientId)).html(notification.body);

					popup.removeClass('hidden').css({ 'visibility': '' }).data('kendoWindow').open();
				}
			}
		}

		//Methods
		this.getId = function ()
		{
			return clientId;
		};

		this.load = function ()
		{
			page = 1;

			showLoading();

			loadHistory();

			return control;
		};
	};

	//Methods
	library.create = function (id, args)
	{
		//Remove existing control
		var existingIndex = instances.findIndex(function (element)
		{
			return element.getId() === id;
		});
		if (existingIndex >= 0)
		{
			instances.splice(existingIndex, 1);
		}

		var control = new Control(id, args);
		instances.push(control);

		return control;
	};

	library.find = function (id)
	{
		return instances.find(function (element)
		{
			return element.getId() === id;
		});
	};
})(window.CivicWeb.Common.NotificationHistory = window.CivicWeb.Common.NotificationHistory || {}, jQuery);
;
window.CivicWeb=window.CivicWeb||{};window.CivicWeb.Common=window.CivicWeb.Common||{},function(n,t){var r=n.recordAction=function(n,r,u){return i(n),t.ajax({url:"/api/users/recordaction",contentType:"application/json",dataType:"json","async":!0,cache:!1,type:"POST",data:JSON.stringify({url:window.location.pathname+window.location.search,action:n||"",id:r||0,externalLog:"boolean"==typeof u?u:!0})})},i;n.logDynamicScriptLoadTime=function(n,t){var u=Date.now(),i=function(){var n=Date.now();t&&setTimeout(function(){r(t)})};n.readyState?n.onreadystatechange=function(){(n.readyState==="loaded"||n.readyState==="complete")&&(n.onreadystatechange=null,i())}:n.onload=function(){i()}};i=function(n,t){try{pendo&&pendo.track(n,t)}catch{}}}(window.CivicWeb.Common.Instrumentation=window.CivicWeb.Common.Instrumentation||{},jQuery);;
window.CivicWeb = window.CivicWeb || {};
window.CivicWeb.Common = window.CivicWeb.Common || {};

(function (library, $)
{
	//Properties
	var instances = [];
	var addNewWindowBaseClientId = '-add-new-window';

	//Classes
	// ReSharper disable once InconsistentNaming
	var Control = function (id, args, additionalArgs)
	{
		var clientId = id;
		var openWindowButtonClientId = args.openWindowButtonClientId || (clientId + '-show-selector');
		var addNewSelectClientId = clientId + '-add-new-select';
		var addNewClientId = clientId + '-add-new';
		var addNewWindowClientId = clientId + addNewWindowBaseClientId;
		var searchClientId = clientId + '-search';
		var searchButtonClientId = clientId + '-search-button';
		var searchOptionsButtonClientId = clientId + '-search-options-button';
		var listClientId = clientId + '-list';
		var gridClientId = clientId + '-grid';
		var searchOptionsClientId = clientId + '-search-options';
		var applySearchOptionsClientId = clientId + '-apply-search-options';

		var localization = args.localization;

		var title = args.title;
		var trackers = args.trackers;
		var fields = args.fields;
		var relatedItemId = args.relatedItemId;
		var relationshipType = args.relationshipType || additionalArgs.relationshipType;
		var relatedItems = args.relatedItems || additionalArgs.relatedItems || [];
		var searchColumns = args.searchColumns || additionalArgs.searchColumns || [];

		var open = args.open;
		var relationshipCreated = args.relationshipCreated || additionalArgs.relationshipCreated;
		var close = args.close;

		var control = this;
		var popupWindowElement = null;
		var addNewSelectElement = null;
		var searchElement = null;
		var searchButtonElement = null;
		var listElement = null;
		var searchOptionsElement = null;

		var centered = false;
		var selectedTrackers = trackers.map(function (tracker)
		{
			return tracker.id;
		});
		var selectedFields = searchColumns.concat(trackers.map(function (tracker)
		{
			return tracker.descriptionFieldId;
		}).filter(function (item)
		{
			return searchColumns.indexOf(item) < 0;
		}));
		var searchActive = false;
		var searchPage = 1;
		var viewingOptions = false;

		var addClass = 'glyphicon-plus item-selector-add';
		var addedClass = 'glyphicon-ok item-selector-added';

		var schemaTypes = {
			trackers: relationshipType.type + '-' + relationshipType.reverse + '-trackers',
			fields: relationshipType.type + '-' + relationshipType.reverse + '-fields'
		};

		var listSchemas = {};
		listSchemas[schemaTypes.trackers] = {
			items: trackers,
			selectedIds: selectedTrackers,
			type: schemaTypes.trackers,
			id: 'id',
			name: 'name',
			deleted: 'deleted',
			selected: 'selected',
			prefix: 'T',
			subCollections: [],
			imageUrl: 'glyphicon glyphicon-list-alt',
			toolTip: localization.groupToolTipText,
			noSubItemsExistText: '',
			load: true,
			sort: function (a, b)
			{
				var nameA = a ? a.name.toLowerCase() : '';
				var nameB = b ? b.name.toLowerCase() : '';

				return nameA < nameB ? -1 : (nameA > nameB ? 1 : 0);
			},
			lastSelection: {
				available: null,
				selected: null
			},
			controlIds: CivicWeb.Common.ListBoxes.getClientIds(schemaTypes.trackers)
		};
		listSchemas[schemaTypes.fields] = {
			items: fields,
			selectedIds: selectedFields,
			type: schemaTypes.fields,
			id: 'id',
			name: 'name',
			deleted: 'deleted',
			selected: 'selected',
			prefix: 'F',
			subCollections: [],
			imageUrl: 'glyphicon glyphicon-tasks',
			toolTip: localization.userToolTipText,
			noSubItemsExistText: '',
			load: true,
			sort: function (a, b)
			{
				var nameA = a ? a.name.toLowerCase() : '';
				var nameB = b ? b.name.toLowerCase() : '';

				return nameA < nameB ? -1 : (nameA > nameB ? 1 : 0);
			},
			lastSelection: {
				available: null,
				selected: null
			},
			controlIds: CivicWeb.Common.ListBoxes.getClientIds(schemaTypes.fields)
		};

		//Event Handlers
		var openWindowButtonClick = function (e)
		{
			openPopup();

			e.preventDefault();
		};

		var addNewButtonClick = function (e)
		{
			var trackerId = CivicWeb.Common.toNumber(addNewSelectElement.val());
			if (trackerId > 0)
			{
				addNewItem(trackerId);
			}
			else
			{
				addNewSelectElement.focus();
			}

			e.preventDefault();
		};

		var searchKeyDown = function (e)
		{
			if (e.which === 13)
			{
				search();

				e.preventDefault();
			}
		};

		var searchButtonClick = function (e)
		{
			if (searchActive)
			{
				clearSearch();
			}
			else
			{
				search();
			}

			e.preventDefault();
		};

		var searchOptionsButtonClick = function (e)
		{
			listElement.toggleClass('hidden', !viewingOptions);
			searchOptionsElement.toggleClass('hidden', viewingOptions);

			viewingOptions = !viewingOptions;
			if (!viewingOptions)
			{
				updateSearchOptions();

				if (searchActive)
				{
					search();
				}
			}

			e.preventDefault();
		};

		var searchPageClick = function (e)
		{
			searchPage = CivicWeb.Common.toNumber($(e.target).closest('a').attr('data-page'), 1);

			search(true);

			e.preventDefault();
		};

		var addRelationshipClick = function (e)
		{
			var button = $(e.target);
			var id = CivicWeb.Common.toNumber(button.attr('data-id'));
			if (id > 0)
			{
				addRelationship(id).done(function (data)
				{
					if (data)
					{
						button.removeClass(addClass).addClass(addedClass);
					}
				});
			}

			e.preventDefault();
		};

		var applySearchOptionsClick = function (e)
		{
			listElement.removeClass('hidden');
			searchOptionsElement.addClass('hidden');

			viewingOptions = false;

			updateSearchOptions();

			if (searchActive)
			{
				search();
			}

			e.preventDefault();
		};

		//Methods
		this.getId = function ()
		{
			return clientId;
		};

		this.open = function ()
		{
			openPopup();
		};

		this.close = function ()
		{
			closePopup();
		};

		this.setOptions = function (options)
		{
			relationshipType = options.relationshipType || relationshipType;
			relatedItems = options.relatedItems || [];
			searchColumns = options.searchColumns || [];

			//Update the add item dropdown
			addNewSelectElement.find('option[value!="0"]').remove();
			getFilteredTrackers().reduce(function (addNewSelectElement, tracker)
			{
				return addNewSelectElement
					.append($('<option></option>').attr({ 'value': tracker.id }).text(tracker.name));
			}, addNewSelectElement);

			return this;
		};

		//Functions
		var load = function ()
		{
			if (CivicWeb.Common.loadKendoUi(load))
			{
				var container = $(document.getElementById(clientId));
				if (container.length === 0)
				{
					$('body')
						.append(container = $('<div></div>').attr({ 'id': clientId, 'class': 'hidden' }));
				}

				popupWindowElement = container.addClass('hidden item-selector').empty()
					.append($('<div></div>').attr({ 'class': 'item-selector-options' })
						.append($('<div></div>').attr({ 'class': 'left-middle item-selector-create-section' })
							.append($('<label></label>').attr({ 'for': addNewSelectClientId, 'class': (CivicWeb.Common.isIe() ? 'is-ie' : '') }).text(localization.labelAddNew))
							.append(addNewSelectElement = $('<select></select>').attr({ 'id': addNewSelectClientId })
								.append($('<option></option>').attr({ 'value': 0 }).text(localization.optionSelect)))
							.append($('<button></button>').attr({ 'id': addNewClientId, 'class': (CivicWeb.Common.isIe() ? 'is-ie' : ''), 'title': localization.toolTipAddNewItem, 'data-container': '#' + clientId, 'data-placement': 'bottom', 'data-html': 'true' }).on('click', addNewButtonClick)
								.append($('<span></span>').attr({ 'class': 'glyphicon glyphicon-plus item-selector-add' }))))
						.append($('<div></div>').attr({ 'class': 'right-middle item-selector-search-section' })
							.append(searchElement = $('<input />').attr({ 'id': searchClientId, 'type': 'text', 'placeholder': localization.placeholderSearch, 'class': 'item-selector-search', 'title': localization.toolTipSearchItems, 'data-container': '#' + clientId, 'data-placement': 'bottom', 'data-html': 'true' }).on('keydown', searchKeyDown))
							.append(searchButtonElement = $('<button></button>').attr({ 'id': searchButtonClientId, 'class': 'item-selector-search-button', 'title': localization.toolTipSearchItems, 'data-container': '#' + clientId, 'data-placement': 'bottom', 'data-html': 'true' }).on('click', searchButtonClick)
								.append($('<span></span>').attr({ 'class': 'glyphicon glyphicon-search' })))
							.append($('<button></button>').attr({ 'id': searchOptionsButtonClientId, 'class': 'item-selector-search-button', 'title': localization.toolTipSetSearchOptions, 'data-container': '#' + clientId, 'data-placement': 'bottom', 'data-html': 'true' }).on('click', searchOptionsButtonClick)
								.append($('<span></span>').attr({ 'class': 'glyphicon glyphicon-cog' })))))
					.append(listElement = $('<div></div>').attr({ 'id': listClientId, 'class': 'item-selector-list' }))
					.append(searchOptionsElement = $('<div></div>').attr({ 'id': searchOptionsClientId, 'class': 'hidden item-selector-search-options' })
						.append($('<div></div>').addClass('item-selector-options-listbox')
							.append(CivicWeb.Common.ListBoxes.generateListBoxes(schemaTypes.trackers, localization.formFieldLabelAvailableTrackers, localization.formFieldLabelSelectedTrackers, localization.buttonAdd, localization.toolTipAdd, localization.buttonRemove, localization.toolTipRemove)))
						.append($('<div></div>').addClass('item-selector-options-listbox')
							.append(CivicWeb.Common.ListBoxes.generateListBoxes(schemaTypes.fields, localization.formFieldLabelAvailableFields, localization.formFieldLabelSelectedFields, localization.buttonAdd, localization.toolTipAdd, localization.buttonRemove, localization.toolTipRemove)))
						.append($('<div></div>').addClass('button-row')
							.append(CivicWeb.Common.Button.create(applySearchOptionsClientId, localization.buttonApply, localization.toolTipApplyOptions).on('click', applySearchOptionsClick))));

				getFilteredTrackers().reduce(function (addNewSelectElement, tracker)
				{
					return addNewSelectElement
						.append($('<option></option>').attr({ 'value': tracker.id }).text(tracker.name));
				}, addNewSelectElement);

				popupWindowElement.kendoWindow({
					modal: true,
					visible: false,
					width: '40%',
					height: '50%',
					minWidth: '600px',
					title: title,
					open: function ()
					{
						if (typeof (open) === 'function')
						{
							open(control);
						}

						if (CivicWeb.Common.isIe())
						{
							$('iframe:not(.hidden)').addClass('hidden').attr({ 'data-item-selector-hidden': true });
						}
					},
					close: function ()
					{
						if (typeof (close) === 'function')
						{
							close(control);
						}

						if (CivicWeb.Common.isIe())
						{
							$('iframe[data-item-selector-hidden]').removeClass('hidden').removeAttr('data-item-selector-hidden');
						}
					}
				});

				popupWindowElement.find('[title]').tooltip({ trigger: 'hover' });

				$(document.getElementById(openWindowButtonClientId)).off('click').on('click', openWindowButtonClick);

				CivicWeb.Common.ListBoxes.createInstance({ clientId: relationshipType.type + '-' + relationshipType.reverse, schemas: listSchemas, enabled: true });
			}
		};

		var openPopup = function ()
		{
			var popupWindow = popupWindowElement.removeClass('hidden').css({ 'visibility': '' }).data('kendoWindow');
			if (!centered)
			{
				popupWindow.center();
				centered = true;
			}
			popupWindow.open();
		};

		var closePopup = function ()
		{
			popupWindowElement.addClass('hidden').data('kendoWindow').close();
		};

		var getFilteredTrackers = function ()
		{
			return relationshipType.trackers ? trackers.filter(function (tracker)
			{
				return relationshipType.trackers.includes(tracker.id);
			}) : trackers;
		};

		var addNewItem = function (trackerId)
		{
			var addNewWindowElement = $(document.getElementById(addNewWindowClientId));
			var addNewWindow = addNewWindowElement.data('kendoWindow');
			if (addNewWindow)
			{
				addNewWindow.destroy();
			}
			if (addNewWindowElement.length > 0)
			{
				addNewWindowElement.remove();
			}

			$('body')
				.append(addNewWindowElement = $('<div></div>').attr({ 'id': addNewWindowClientId, 'class': 'hidden' }));

			addNewWindowElement.kendoWindow({
				modal: true,
				visible: false,
				width: '90%',
				height: '90%',
				content: '/items/item/?trackerid=' + trackerId + '&relateditemid=' + relatedItemId + '&relationshiptype=' + relationshipType.type + '&reverserelationship=' + relationshipType.reverse + '&popup=true',
				iframe: true,
				refresh: function ()
				{
					var url = addNewWindowElement.find('iframe').get(0).contentWindow.location.href.toLowerCase();
					if (url.indexOf('/items/item') < 0 && url.indexOf('/item/') < 0)
					{
						addNewWindow.close();
					}
				},
				close: function ()
				{
					if (typeof (relationshipCreated) === 'function')
					{
						relationshipCreated(relationshipType);
					}
				}
			});

			addNewWindow = addNewWindowElement.removeClass('hidden').data('kendoWindow');
			addNewWindow.center().open();
		};

		var addRelationship = function (id)
		{
			var relationship = {
				relatedItemId: id,
				type: relationshipType.type,
				reverse: relationshipType.reverse
			};

			return $.ajax({
				url: '/api/item/' + relatedItemId + '/relatedItem',
				contentType: 'application/json',
				dataType: 'json',
				async: true,
				cache: false,
				type: 'POST',
				data: JSON.stringify(relationship)
			}).done(function (data)
			{
				if (data)
				{
					relationshipCreated(relationshipType);
				}
			});
		};

		var search = function (pageChange)
		{
			var criteria = searchElement.val();
			if (criteria.length > 0)
			{
				clearSearchResults();

				searchButtonElement.find('span').removeClass('glyphicon-search').addClass('glyphicon-remove');
				searchOptionsElement.addClass('hidden');

				viewingOptions = false;

				listElement.removeClass('hidden').empty()
					.append($('<div></div>').attr({ 'class': 'item-selector-search-throbber center-middle' })
						.append(CivicWeb.Common.Button.getThrobber(clientId + '-search-throbber')));

				if (!pageChange)
				{
					searchPage = 1;
				}

				$.ajax({
					url: '/api/items/search?keywords=' + encodeURIComponent(criteria) + '&page=' + searchPage + '&trackerids=' + (relationshipType.trackers ? relationshipType.trackers : selectedTrackers).join(',') + '&fieldids=' + selectedFields.join(','),
					contentType: 'application/json',
					dataType: 'json',
					async: true,
					cache: false,
					type: 'GET',
					data: null
				}).done(function (data)
				{
					searchPage = data.page;

					listElement.find('.item-selector-search-throbber').remove();

					displaySearchResults(data);

					searchElement.blur();
				}).fail(function ()
				{
					listElement.find('.item-selector-search-throbber').remove();

					clearSearch();
				});

				searchActive = true;
			}
		};

		var clearSearchResults = function ()
		{
			var searchResults = $(document.getElementById(gridClientId)).data('kendoGrid');
			if (searchResults)
			{
				searchResults.destroy();
			}
			listElement.empty();
		};

		var generatePager = function (numberOfResults, resultsPerPage)
		{
			numberOfResults = numberOfResults || 0;
			resultsPerPage = resultsPerPage || 50;

			var pager = null;
			if (numberOfResults > 0)
			{
				var maxPages = Math.ceil(numberOfResults / resultsPerPage);

				pager = CivicWeb.Common.Pager.create(searchPage, maxPages, searchPageClick, false, localization.pagerLocalization);
			}

			return pager;
		};

		var displaySearchResults = function (data)
		{
			clearSearchResults();

			//Load list view
			if (data && data.results.length > 0)
			{
				var gridElement;
				listElement
					.append(generatePager(data.total, data.resultsPerPage))
					.append(gridElement = $('<table></table>').attr({ 'id': gridClientId })
						.append($('<colgroup></colgroup>')
							.append($('<col></col>').addClass('item-selector-search-results-add-column')))
						.append($('<thead></thead>')
							.append($('<tr></tr>')
								.append($('<th></th>'))
								.append($('<th></th>').text(localization.columnHeaderType))
								.append(data.fields.map(function (field)
								{
									return $('<th></th>').text(field.name);
								}))))
						.append($('<tbody></tbody>')
							.append(data.results.map(function (result)
							{
								return $('<tr></tr>')
									.append($('<td></td>'))
									.append($('<td></td>')
										.append((!result.viewAllowed ? $('<a></a>').attr({ 'href': '/items/item/?id=' + result.id, 'target': '_blank' }) : $('<span></span>')).attr({ 'data-id': result.id }).text(result.trackers)))
									.append(data.fields.map(function (field)
									{
										return $('<td></td>')
											.append((result.viewAllowed ? $('<a></a>').attr({ 'href': '/items/item/?id=' + result.id, 'target': '_blank' }) : $('<span></span>')).attr({ 'data-id': result.id }).text((result.values.find(function (value)
											{
												return value.id === field.id;
											}) || { value: '' }).value));
									}));
							}))))
					.append(generatePager(data.total, data.resultsPerPage));

				gridElement.kendoGrid({
					scrollable: false
				});

				//Add create relationship buttons
				gridElement.data('kendoGrid').tbody.find('tr').each(function ()
				{
					var row = $(this);
					var id = CivicWeb.Common.toNumber(row.find('[data-id]').attr('data-id'));
					row.find('td:first-child')
						.append($('<span></span>').attr({ 'class': 'glyphicon ' + (relatedItems.indexOf(id) < 0 ? addClass : addedClass), 'data-id': id }).on('click', addRelationshipClick));
				});
			}

			listElement.scrollTop(0);
		};

		var clearSearch = function ()
		{
			searchElement.val('');
			searchButtonElement.find('span').removeClass('glyphicon-remove').addClass('glyphicon-search');
			searchOptionsElement.addClass('hidden');

			viewingOptions = false;

			clearSearchResults();

			searchActive = false;
		};

		var updateSearchOptions = function ()
		{
			selectedTrackers = trackers.filter(function (tracker)
			{
				return tracker.selected;
			}).map(function (tracker)
			{
				return tracker.id;
			});
			selectedFields = fields.filter(function (fields)
			{
				return fields.selected;
			}).map(function (fields)
			{
				return fields.id;
			});
		};

		load();
	};

	//Methods
	library.create = function (id, args, additionalArgs)
	{
		//Remove existing control
		var existingIndex = instances.findIndex(function (element)
		{
			return element.getId() === id;
		});
		if (existingIndex >= 0)
		{
			instances.splice(existingIndex, 1);
		}

		var control = new Control(id, args, additionalArgs);
		instances.push(control);

		return control;
	};

	library.find = function (id)
	{
		return instances.find(function (element)
		{
			return element.getId() === id;
		});
	};

	library.getAddNewWindowElementId = function (element)
	{
		var windowElement = CivicWeb.Common.getJqueryObject(element).closest('.k-window-content');
		var id = windowElement.attr('id') || '';
		var isAddNewWindow = false;
		if (id.indexOf(addNewWindowBaseClientId) >= 0)
		{
			isAddNewWindow = true;
		}

		return isAddNewWindow ? id : undefined;
	};

	library.closeAddNewWindow = function (id)
	{
		var windowControl = $(document.getElementById(id)).data('kendoWindow');
		if (windowControl)
		{
			windowControl.close();
		}
	};
})(window.CivicWeb.Common.ItemSelector = window.CivicWeb.Common.ItemSelector || {}, jQuery);
;
window.CivicWeb = window.CivicWeb || {};

(function (library, $)
{
	//Variables
	var kendoUiLoaded = false;

	library.excludedFileTypes = ['.ade', '.adp', '.bat', '.chm', '.cmd', '.com', '.cpl', '.exe', '.hta', '.ins', '.isp', '.jar', '.js', '.jse', '.lib', '.lnk', '.mde', '.msc', '.msi', '.msp', '.mst', '.nsh', '.pif', '.scr', '.sct', '.shb', '.sys', '.vb', '.vbe', '.vbs', '.vxd', '.wsc', '.wsf', '.wsh'];

	//Methods
	library.noop = function ()
	{
	};

	library.forceArray = function (values)
	{
		if ('undefined' === typeof values || values == null)
		{
			values = [];
		}
		else if ('[object Array]' !== Object.prototype.toString.call(values))
		{
			values = [values];
		}

		return values;
	};

	library.toKeyValueArray = function (object)
	{
		var keyValues = [];
		if (object)
		{
			for (var key in object)
			{
				if (object.hasOwnProperty(key))
				{
					keyValues.push({
						key: key,
						value: object[key]
					});
				}
			}
		}

		return keyValues;
	};

	library.uniqueArray = function (array)
	{
		var values = [];
		if (Array.isArray(array))
		{
			for (var index = 0; index < array.length; index++)
			{
				if (!values.includes(array[index]))
				{
					values.push(array[index]);
				}
			}
		}

		return values;
	};

	library.removeNull = function (array)
	{
		if (array && 'function' == typeof array.splice)
		{
			for (var index = 0; index < array.length; index++)
			{
				if (array[index] == null)
				{
					array.splice(index, 1);
					index--;
				}
			}
		}

		return array;
	};

	library.arraysEqual = function (a, b)
	{
		var equal = true;
		if (a !== b && (a == null || b == null || a.length !== b.length))
		{
			equal = false;
		}
		else
		{
			for (var index = 0; a && index < a.length; ++index)
			{
				if (!library.objectPropertiesEqual(a[index], b[index]))
				{
					equal = false;
					break;
				}
			}
		}

		return equal;
	};

	library.objectPropertiesEqual = function (a, b)
	{
		a = 'undefined' === typeof a || a == null ? {} : a;
		b = 'undefined' === typeof b || b == null ? {} : b;

		//Check if one is a primitive type
		var typeA = typeof a;
		var typeB = typeof b;
		if (('object' !== typeA && 'function' !== typeA) || ('object' !== typeB && 'function' !== typeB))
		{
			return a === b;
		}

		//Loop through properties in a
		for (var propertyName in a)
		{
			//Check property exists on both objects
			if (a.hasOwnProperty(propertyName) !== b.hasOwnProperty(propertyName))
			{
				return false;
			}

			switch (typeof (a[propertyName]))
			{
				//Deep compare objects
				case 'object':
					if (!library.objectPropertiesEqual(a[propertyName], b[propertyName]))
					{
						return false;
					}
					break;

				//Compare function code
				case 'function':
					if (typeof (b[propertyName]) == 'undefined' || (a[propertyName].toString() !== b[propertyName].toString()))
					{
						return false;
					}
					break;

				//Compare values
				default:
					if (a[propertyName] !== b[propertyName])
					{
						return false;
					}
			}
		}

		//Check b for any extra properties
		for (var propertyName in b)
		{
			if (b.hasOwnProperty(propertyName))
			{
				if (typeof (a[propertyName]) == 'undefined')
				{
					return false;
				}
			}
		}

		return true;
	};

	library.toNumber = function (value, defaultValue)
	{
		defaultValue = defaultValue || 0;
		value = 'string' === typeof value ? parseInt(value) : value;

		return Number('undefined' !== typeof value && value != null && !isNaN(value) ? value : defaultValue);
	};

	library.toFloat = function (value, defaultValue)
	{
		defaultValue = defaultValue || 0;
		value = 'string' === typeof value ? parseFloat(value) : value;

		return Number('undefined' !== typeof value && value != null && !isNaN(value) ? value : defaultValue);
	};

	library.toBoolean = function (value, defaultValue)
	{
		defaultValue = defaultValue || false;

		var type;
		var valueLowerCase;

		return 'string' === (type = typeof value) ? ('true' === (valueLowerCase = value.toLowerCase()) ? true : ('false' === valueLowerCase ? false : defaultValue)) : ('boolean' === type ? value : defaultValue);
	};

	library.getJqueryObject = function (element)
	{
		var object = null;
		if (element)
		{
			if ('[object Array]' !== Object.prototype.toString.call(element))
			{
				element = [element];
			}

			for (var index = 0; index < element.length; index++)
			{
				var current = element[index];
				var jQueryObject = current instanceof jQuery || current instanceof $ ? current : $('string' === typeof current ? (current.indexOf('.') === 0 || current.indexOf('#') === 0 ? current : (current.length > 0 ? document.getElementById(current) : null)) : (current && current.nodeType && 1 === current.nodeType ? current : null));
				if (object == null)
				{
					object = jQueryObject;
				}
				else
				{
					object = object.add(jQueryObject);
				}
			}
		}

		if (object == null)
		{
			object = $(null);
		}

		return object;
	};

	library.getParentIndexes = function (node, isStopElement)
	{
		var parentIndexes = [];
		if (node && node.nodeType)
		{
			while (node.parentNode != null && ('function' !== typeof isStopElement || !isStopElement(node)))
			{
				var index = 0;
				var sibling = node;
				while ((sibling = sibling.previousSibling) != null)
				{
					index++;
				}

				parentIndexes.push(index);

				node = node.parentNode;
			}
		}

		return parentIndexes.reverse();
	};

	library.getChildNode = function (parent, childIndexes)
	{
		var child = null;
		if (parent && parent.nodeType && childIndexes && childIndexes.length > 0)
		{
			for (var index = 0; index < childIndexes.length; index++)
			{
				if (parent.childNodes && parent.childNodes.length > childIndexes[index])
				{
					child = parent = parent.childNodes[childIndexes[index]];
				}
				else
				{
					break;
				}
			}
		}

		return child;
	};

	library.setStyles = function (element, cssClass, styles)
	{
		element = library.getJqueryObject(element);

		if ('undefined' !== typeof styles && styles != null)
		{
			if ('string' === typeof styles)
			{
				element.attr({ 'style': styles });
			}
			else if ('object' === typeof styles)
			{
				element.css(styles);
			}
		}
		if ('string' === typeof cssClass)
		{
			element.addClass(cssClass);
		}

		return element;
	};

	library.getStyleValue = function (element, cssProperty)
	{
		var value = '';
		if (element && 'string' === typeof cssProperty && cssProperty.length > 0)
		{
			element = library.getJqueryObject(element);
			var style = element.attr('style') || '';
			var matches = new RegExp(cssProperty + ':\s*([^\s;]+)\s*;?', 'g').exec(style);
			if (matches && matches.length > 1)
			{
				value = matches[1];
			}
		}

		return value || '';
	};

	library.setStyleValue = function (element, cssProperty, value)
	{
		if (element && 'string' === typeof cssProperty && cssProperty.length > 0 && 'string' === typeof value)
		{
			element = library.getJqueryObject(element);
			element.attr('style', ((element.attr('style') || '').replace(new RegExp(cssProperty + ':\s*[^\s;]+\s*;?', 'g'), '') + (value.length > 0 ? (' ' + cssProperty + ': ' + value + ';') : '')).trim());
		}

		return element;
	};

	library.addControlEventHandler = function (handlers, event, handler)
	{
		if (handlers && 'string' === typeof event && 'function' === typeof handler && handlers[event])
		{
			var found = false;
			for (var index = 0; index < handlers[event].length; index++)
			{
				if (found = (handlers[event][index] === handler))
				{
					break;
				}
			}

			if (!found)
			{
				handlers[event].push(handler);
			}
		}
	};

	library.removeControlEventHandler = function (handlers, event, handler)
	{
		if (handlers && 'string' === typeof event && 'function' === typeof handler && handlers[event])
		{
			for (var index = 0; index < handlers[event].length; index++)
			{
				if (handlers[event][index] === handler)
				{
					handlers[event].splice(index, 1);
					index--;
				}
			}
		}
	};

	library.callControlEventHandler = function (handlers, event, args)
	{
		if (handlers && 'string' === typeof event && handlers[event])
		{
			for (var index = 0; index < handlers[event].length; index++)
			{
				if ('function' === typeof handlers[event][index])
				{
					handlers[event][index](args);
				}
			}
		}
	};

	library.addLeavingPageWarning = function (showWarning, leaveWarning)
	{
		if ('function' === typeof showWarning)
		{
			window.onbeforeunload = function (e)
			{
				if (showWarning())
				{
					e = e || window.event;

					// For IE and Firefox
					if (e)
					{
						e.returnValue = leaveWarning;
					}

					// For Safari
					return leaveWarning;
				}

				return undefined;
			};
		}
	};

	library.loadKendoUi = function (callback)
	{
		kendoUiLoaded = kendoUiLoaded || !!$('<div></div>').kendoWindow;
		if (!kendoUiLoaded)
		{
			var body = $('body');

			//Load styles
			body.append($('<link />').attr({ 'rel': 'stylesheet', 'type': 'text/css', 'href': '/css/kendo/kendoui?t=' + new Date().getTime().toString() }));

			//Load scripts
			$.getScript('/js/kendo/kendoui?t=' + new Date().getTime().toString(), function () { kendoUiLoaded = true; if (typeof callback === 'function') { callback(); } });
		}

		return kendoUiLoaded;
	};

	library.fitKendoWindowToContent = function (windowElement)
	{
		if (windowElement)
		{
			var windowWrapper = windowElement.closest('.k-window');

			var maxHeight = parseInt($(window).height() * 0.8, 10);
			var windowHeight = windowWrapper.height();
			var scrollHeight = parseInt(windowElement.prop('scrollHeight'), 10);

			if (scrollHeight > maxHeight && windowHeight >= parseInt(windowWrapper.css('min-height'), 10))
			{
				windowWrapper.height(maxHeight - 30);
			}
			else if (maxHeight >= scrollHeight)
			{
				windowWrapper.height('');
			}
		}
	};

	library.resizeInstallContent = function (spacing)
	{
		var content = $(document.getElementById('install-content'));
		var navBar = $(document.getElementById('install-navigation-buttons'));
		if (content.length > 0 && navBar.length > 0)
		{
			content.height($(window).height() - content.offset().top - (spacing != null ? spacing : 90) - navBar.height());
		}
	};

	library.addUrlParameter = function (url, parameter, value)
	{
		if ('string' === typeof parameter && parameter.length > 0)
		{
			url = library.removeUrlParameter(url, parameter);

			url = url + (url.indexOf('?') >= 0 ? '&' : '?') + encodeURIComponent(parameter) + '=' + encodeURIComponent(value);
		}

		return url;
	};

	library.removeUrlParameter = function (url, parameter)
	{
		url = url || '';

		var urlParts = url.split('?');
		if (urlParts.length >= 2 && parameter)
		{
			var prefix = encodeURIComponent(parameter).toLowerCase() + '=';
			var parameters = urlParts[1].split(/[&;]/g);

			//reverse iteration as may be destructive
			for (var index = parameters.length; index-- > 0;)
			{
				//idiom for string.startsWith
				if (parameters[index].toLowerCase().lastIndexOf(prefix, 0) !== -1)
				{
					parameters.splice(index, 1);
				}
			}

			url = urlParts[0] + (parameters.length > 0 ? '?' + parameters.join('&') : '');
		}

		return url;
	};

	library.getUrlParameterValue = function (url, parameter)
	{
		var parameterValue;
		url = url || '';

		var urlParts = url.split('?');
		if (urlParts.length >= 2 && parameter)
		{
			var prefix = encodeURIComponent(parameter).toLowerCase() + '=';
			var parameters = urlParts[1].split(/[&;]/g);

			//reverse iteration as may be destructive
			for (var index = parameters.length; index-- > 0;)
			{
				//idiom for string.startsWith
				if (parameters[index].toLowerCase().lastIndexOf(prefix, 0) !== -1)
				{
					var parameterSplit = parameters[index].split('=');
					if (parameterSplit && parameterSplit.length > 1)
					{
						parameterValue = parameterSplit[1];
					}
				}
			}
		}

		return parameterValue;
	};

	library.getFileIconClass = function (ext)
	{
		var found = 'blank';
		var extensions = {
			blank: 'blank',
			page: 'page',
			aac: 'aac',
			ai: 'ai',
			aiff: 'aiff',
			avi: 'avi',
			bmp: 'bmp',
			c: 'c',
			cpp: 'cpp',
			css: 'css',
			dat: 'dat',
			dmg: 'dmg',
			doc: 'doc',
			dotx: 'dotx',
			dwg: 'dwg',
			dxf: 'dxf',
			eps: 'eps',
			exe: 'exe',
			flv: 'flv',
			gif: 'gif',
			h: 'h',
			hpp: 'hpp',
			html: 'html',
			ics: 'ics',
			iso: 'iso',
			java: 'java',
			jpg: 'jpg',
			key: 'key',
			mid: 'mid',
			mp3: 'mp3',
			mp4: 'mp4',
			mpg: 'mpg',
			odf: 'odf',
			ods: 'ods',
			odt: 'odt',
			otp: 'otp',
			ots: 'ots',
			ott: 'ott',
			pdf: 'pdf',
			php: 'php',
			png: 'png',
			ppt: 'ppt',
			pptx: 'pptx',
			psd: 'psd',
			py: 'py',
			qt: 'qt',
			rar: 'rar',
			rb: 'rb',
			rtf: 'rtf',
			sql: 'sql',
			tga: 'tga',
			tgz: 'tgz',
			tif: 'tif',
			tiff: 'tiff',
			txt: 'txt',
			wav: 'wav',
			xls: 'xls',
			xlsx: 'xlsx',
			xml: 'xml',
			yml: 'yml',
			zip: 'zip',
			m4a: 'm4a',
			wma: 'wma',
			mov: 'mov'
		};

		if (ext && ext.length > 0)
		{
			ext = ext.toLowerCase().replace('.', '');
			switch (ext)
			{
				case 'docx':
					ext = ext.replace(ext, 'doc');
					break;

				case 'htm':
					ext = ext.replace(ext, 'html');
					break;

				case 'splitscreen':
					ext = ext.replace(ext, 'html');
					break;

				case 'jpeg':
					ext = ext.replace(ext, 'jpg');
					break;

				case 'pptx':
				case 'pptm':
					ext = ext.replace(ext, 'ppt');
					break;

				case 'tif':
					ext = ext.replace(ext, 'tiff');
					break;
			}

			if (extensions[ext] != null)
			{
				found = ext;
			}
		}

		return 'icon-file-' + found + '-24';
	};

	library.isIe = function ()
	{
		return /msie/.test(navigator.userAgent.toLowerCase()) || /trident/.test(navigator.userAgent.toLowerCase());
	};

	if ($.ui && $.ui.autocomplete)
	{
		$.widget('ui.combobox', $.ui.autocomplete,
			{
				options: {
					/* override default values here */
					minLength: 0,
					/* the argument to pass to ajax to get the complete list */
					ajaxGetAll: { get: 'all' },
					/* you can specify the field to use as a label decorator,
						* it's appended to the end of the label and is excluded
						* from pattern matching.
						*/
					decoratorField: null
				},

				_create: function ()
				{
					if (this.element.is('SELECT'))
					{
						this._selectInit();
						return;
					}

					$.ui.autocomplete.prototype._create.call(this);
					var input = this.element;
					input.addClass('custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left')
						.attr('title', '')
						.css({ 'width': '200px', 'background': 'white' })
						.click(function () { this.select(); })
						.tooltip({
							classes: {
								"ui-tooltip": 'ui-state-highlight'
							}
						});;

					this.button = $("<button type='button'>&nbsp;</button>")
						.attr('tabIndex', -1)
						.attr('title', 'Show All Items')
						.insertAfter(input)
						.button({
							disabled: true, // to be enabled when the menu is ready.
							icons: { primary: 'ui-icon-triangle-1-s' },
							text: false
						})
						.css({ 'vertical-align': 'top', 'padding': '0' })
						.removeClass('ui-corner-all')
						.addClass('ui-corner-right ui-button-icon combobox-dropdown-button')
						.click(function (event)
						{
							// when user clicks the show all button, we display the cached full menu
							var data = input.data('ui-combobox');
							clearTimeout(data.closing);
							if (!input.isFullMenu)
							{
								data._swapMenu();
							}
							/* input/select that are initially hidden (display=none, i.e. second level menus),
								will not have position cordinates until they are visible. */
							input.combobox('widget').css('display', 'block')
								.position($.extend({ of: input },
									data.options.position
								));
							input.focus();
							data._trigger('open');
							// containers such as jquery-ui dialog box will adjust it's zIndex to overlay above other elements.
							// this becomes a problem if the combobox is inside of a dialog box, the full drop down will show
							// under the dialog box.
							if (input.combobox('widget').css('z-index') <= input.parent().css('z-index'))
							{
								input.combobox('widget').css('z-index', (input.parent().css('z-index') + 1));
							}
						});

					/* to better handle large lists, put in a queue and process sequentially */
					$(document).queue(function ()
					{
						var data = input.data('ui-combobox');
						if ($.isArray(data.options.source))
						{
							$.ui.combobox.prototype._renderFullMenu.call(data, data.options.source);
						} else if (typeof data.options.source === 'string')
						{
							$.getJSON(data.options.source, data.options.ajaxGetAll, function (source)
							{
								$.ui.combobox.prototype._renderFullMenu.call(data, source);
							});
						} else
						{
							$.ui.combobox.prototype._renderFullMenu.call(data, data.source());
						}
					});
				},

				/* initialize the full list of items, this menu will be reused whenever the user clicks the show all button */
				_renderFullMenu: function (source)
				{
					var self = this,
						input = this.element,
						ul = input.data('ui-combobox').menu.element,
						lis = [];
					source = this._normalize(source);
					input.data('ui-combobox').menuAll = input.data('ui-combobox').menu.element.clone(true).appendTo('body')[0];
					for (var i = 0; i < source.length; i++)
					{
						var item = source[i],
							label = item.label;
						if (this.options.decoratorField != null)
						{
							var d = item[this.options.decoratorField] || (item.option && $(item.option).attr(this.options.decoratorField));
							if (d != undefined)
								label = label + ' ' + d;
						}
						lis[i] = "<li class=\"ui-menu-item\" role=\"menuitem\"><div class=\"ui-menu-item-wrapper\" tabindex=\"-1\" style='word-wrap: break-word;'>" + label + '</div></li>';
					}
					ul[0].innerHTML = lis.join('');
					this._resizeMenu();

					var items = $('li', ul).on('mouseover', 'mouseout', function (event)
					{
						if (event.type == 'mouseover')
						{
							self.menu.focus(event, $(this));
						} else
						{
							self.menu.blur();
						}
					});
					for (var i = 0; i < items.length; i++)
					{
						$(items[i]).data('ui-autocomplete-item', source[i]);
					}
					input.isFullMenu = true;
					this._swapMenu();
					// full menu has been rendered, now we can enable the show all button.
					self.button.button('enable');
					setTimeout(function ()
					{
						$(document).dequeue();
					}, 0);
				},

				/* overwrite. make the matching string bold and added label decorator */
				_renderItem: function (ul, item)
				{
					var label = item.label.replace(new RegExp(
						'(?![^&;]+;)(?!<[^<>]*)(' + $.ui.autocomplete.escapeRegex(this.term) +
						')(?![^<>]*>)(?![^&;]+;)', 'gi'), '<strong>$1</strong>');
					if (this.options.decoratorField != null)
					{
						var d = item[this.options.decoratorField] || (item.option && $(item.option).attr(this.options.decoratorField));
						if (d != undefined)
						{
							label = label + ' ' + d;
						}
					}
					return $('<li></li>')
						.data('ui-autocomplete-item', item)
						.append("<div class='ui-menu-item-wrapper' style='word-wrap: break-word;'>" + label + '</div>')
						.appendTo(ul);
				},

				close: function ()
				{
					if (this.element.isFullMenu)
					{
						this._swapMenu();
					}
					// super()
					$.ui.autocomplete.prototype.close.call(this);
				},

				/* overwrite. to cleanup additional stuff that was added */
				destroy: function ()
				{
					if (this.element.is('SELECT'))
					{
						this.input.removeData('ui-combobox', 'menuAll');
						this.input.remove();
						this.element.removeData().show();
						return;
					}
					// super()
					$.ui.autocomplete.prototype.destroy.call(this);
					// clean up new stuff
					this.element.removeClass('ui-widget ui-widget-content ui-corner-left');
					this.button.remove();
				},

				/* overwrite. to swap out and preserve the full menu */
				search: function (value, event)
				{
					var input = this.element;
					if (input.isFullMenu)
					{
						this._swapMenu();
					}
					// super()
					$.ui.autocomplete.prototype.search.call(this, value, event);
				},

				_change: function (event)
				{
					if (!this.selectedItem)
					{
						var matcher = new RegExp('^' + $.ui.autocomplete.escapeRegex(this.element.val()) + '$', 'i'),
							match = $.grep(this.options.source, function (value)
							{
								return matcher.test(value.label);
							});
						if (match.length)
						{
							if (match[0].option != undefined) match[0].option.selected = true;
						} else
						{
							// remove invalid value, as it didn't match anything
							if (this.options.selectElement)
							{
								var firstItem = this.options.selectElement.children('option:first');
								this.element.val(firstItem.text());
								firstItem.prop('selected', true);
							} else
							{
								this.element.val('');
							}
							$(event.target).data('ui-combobox').previous = null;  // this will force a change event
						}
					}
					// super()
					$.ui.autocomplete.prototype._change.call(this, event);
				},

				_swapMenu: function ()
				{
					var input = this.element,
						data = input.data('ui-combobox'),
						tmp = data.menuAll;
					data.menuAll = data.menu.element.hide()[0];
					data.menu.element[0] = tmp;
					input.isFullMenu = !input.isFullMenu;
				},

				/* build the source array from the options of the select element */
				_selectInit: function ()
				{
					var select = this.element,
						selectClass = select.attr('class'),
						selectStyle = select.attr('style'),
						selected = select.children(':selected'),
						value = $.trim(selected.text());
					select.hide();
					this.options.source = select.children('option').map(function ()
					{
						return { label: $.trim(this.text), option: this };
					}).toArray();
					var userSelectCallback = this.options.select;
					var userSelectedCallback = this.options.selected;
					this.options.select = function (event, ui)
					{
						ui.item.option.selected = true;
						select.change();
						if (userSelectCallback) userSelectCallback(event, ui);
						// compatibility with jQuery UI's combobox.
						if (userSelectedCallback) userSelectedCallback(event, ui);
					};
					this.options.selectElement = select;
					this.input = $('<input>').insertAfter(select).val(value);
					if (selectStyle)
					{
						this.input.attr('style', selectStyle);
					}
					if (selectClass)
					{
						this.input.attr('class', selectClass);
					}
					this.input.combobox(this.options);
				},

				inputbox: function ()
				{
					if (this.element.is('SELECT'))
					{
						return this.input;
					} else
					{
						return this.element;
					}
				}
			});
	}

	(function ()
	{
		//JQuery insertAt
		$.fn.insertAt = function (index, element)
		{
			var lastIndex = this.children().length;
			if (index < 0)
			{
				index = Math.max(0, lastIndex + 1 + index);
			}
			this.append(element);
			if (index < lastIndex)
			{
				this.children().eq(index).before(this.children().last());
			}
			return this;
		};

		//JQuery textAreaExpander
		$.fn.textAreaExpander = function (minHeight, maxHeight)
		{
			// resize a textarea
			var resizeTextArea = function (e)
			{

				// event or initialize element?
				e = e.target || e;

				// find content length and box width
				var vlen = e.value.length, ewidth = e.offsetWidth;
				if (vlen !== e.valLength || ewidth !== e.boxWidth)
				{

					var h = Math.max(e.expandMin, Math.min(e.scrollHeight, e.expandMax));

					e.style.overflow = (e.scrollHeight > h ? 'auto' : 'hidden');
					e.style.height = h + 'px';

					e.valLength = vlen;
					e.boxWidth = ewidth;
				}

				return true;
			};

			// initialize
			this.each(function ()
			{
				// is a textarea?
				if (this.nodeName.toLowerCase() !== 'textarea') return;

				// set height restrictions
				var p = this.className.match(/expand(\d+)\-*(\d+)*/i);
				this.expandMin = minHeight || (p ? parseInt('0' + p[1], 10) : 0);
				this.expandMax = maxHeight || (p ? parseInt('0' + p[2], 10) : 99999);

				// initial resize
				resizeTextArea(this);

				// zero vertical padding and add events
				if (!this.initialized)
				{
					this.initialized = true;
					$(this).css({ 'padding-top': 0, 'padding-bottom': 0 });
					$(this).off('keyup focus', resizeTextArea).on('keyup focus', resizeTextArea);
				}
			});

			return this;
		};

		//Polyfill String.endsWith
		if (!String.prototype.endsWith)
		{
			// ReSharper disable once NativeTypePrototypeExtending
			String.prototype.endsWith = function (searchString, position)
			{
				var subjectString = this.toString();
				if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length)
				{
					position = subjectString.length;
				}
				position -= searchString.length;
				var lastIndex = subjectString.indexOf(searchString, position);
				return lastIndex !== -1 && lastIndex === position;
			};
		}

		//Polyfill Array.find
		if (!Array.prototype.find)
		{
			// ReSharper disable once NativeTypePrototypeExtending
			Array.prototype.find = function (predicate)
			{
				// ReSharper disable once ConditionIsAlwaysConst
				if (this === null)
				// ReSharper disable once HeuristicallyUnreachableCode
				{
					throw new TypeError('Array.prototype.find called on null or undefined');
				}
				if (typeof predicate !== 'function')
				{
					throw new TypeError('predicate must be a function');
				}
				var list = Object(this);
				var length = list.length >>> 0;
				var thisArg = arguments[1];
				var value;

				for (var i = 0; i < length; i++)
				{
					value = list[i];
					if (predicate.call(thisArg, value, i, list))
					{
						return value;
					}
				}
				return undefined;
			};
		}

		//Polyfill Array.findIndex
		if (!Array.prototype.findIndex)
		{
			// ReSharper disable once NativeTypePrototypeExtending
			Array.prototype.findIndex = function (predicate)
			{
				'use strict';
				if (this == null)
				{
					throw new TypeError('Array.prototype.findIndex called on null or undefined');
				}
				if (typeof predicate !== 'function')
				{
					throw new TypeError('predicate must be a function');
				}
				var list = Object(this);
				var length = list.length >>> 0;
				var thisArg = arguments[1];
				var value;

				for (var i = 0; i < length; i++)
				{
					value = list[i];
					if (predicate.call(thisArg, value, i, list))
					{
						return i;
					}
				}
				return -1;
			};
		}

		//Polyfill Array.includes
		if (!Array.prototype.includes)
		{
			// ReSharper disable once NativeTypePrototypeExtending
			Array.prototype.includes = function (searchElement /*, fromIndex*/)
			{
				'use strict';
				var o = Object(this);
				var len = parseInt(o.length) || 0;
				if (len === 0)
				{
					return false;
				}
				var n = parseInt(arguments[1]) || 0;
				var k;
				if (n >= 0)
				{
					k = n;
				} else
				{
					k = len + n;
					if (k < 0) { k = 0; }
				}
				var currentElement;
				while (k < len)
				{
					currentElement = o[k];
					if (searchElement === currentElement ||
						(searchElement !== searchElement && currentElement !== currentElement))
					{ // NaN !== NaN
						return true;
					}
					k++;
				}
				return false;
			};
		}

		//Polyfill DocumentOrShadowRoot.elementsFromPoint
		if (!document.elementsFromPoint)
		{
			// ReSharper disable once NativeTypePrototypeExtending
			document.elementsFromPoint = function elementsFromPoint(x, y)
			{
				if (typeof document.msElementsFromPoint === 'function')
				{
					return Array.prototype.slice.call(document.msElementsFromPoint(x, y));
				}

				var parents = [];
				var parent = void 0;
				do
				{
					if (parent !== document.elementFromPoint(x, y))
					{
						parent = document.elementFromPoint(x, y);
						parents.push(parent);
						parent.style.pointerEvents = 'none';
					}
					else
					{
						parent = false;
					}
				} while (parent);
				parents.forEach(function (parent)
				{
					return parent.style.pointerEvents = 'all';
				});
				return parents;
			};
		}

		//Create Array.sameValues method
		if (!Array.prototype.sameValues)
		{
			// ReSharper disable once NativeTypePrototypeExtending
			Array.prototype.sameValues = function (testArr)
			{
				if (this.length !== testArr.length)
				{
					return false;
				}

				for (var i = 0; i < testArr.length; i++)
				{
					if (!this.includes(testArr[i]))
					{
						return false;
					}
				}

				return true;
			}
		}

		//Display fonts in points
		if (window.Telerik &&
			window.Telerik.Web &&
			window.Telerik.Web.UI &&
			window.Telerik.Web.UI.Editor &&
			window.Telerik.Web.UI.Editor.RealFontSize)
		{
			var originalGetValue = window.Telerik.Web.UI.Editor.RealFontSize.prototype.getValue;

			window.Telerik.Web.UI.Editor.RealFontSize.prototype.getValue = function (wnd, range)
			{
				var originalresult = originalGetValue.call(this, wnd, range);
				var resultInPoints = Math.round(parseFloat(originalresult) / 1.33) + 'pt';
				return resultInPoints;
			};
		}
	})();
})(window.CivicWeb.Common = window.CivicWeb.Common || {}, jQuery);
;
// Declare namespaces
var CivicWeb = CivicWeb || {};
CivicWeb.Common = CivicWeb.Common || {};

//Create classes
CivicWeb.Common.ListBox = function (args)
{
	//Properties
	var clientId = args.clientId || '';

	var schemas = args.schemas;
	var enabled = args.enabled;

	var localization = args.localization;
	var images = args.images;

	var expansionState = {
		collapsed: 'collapsed',
		expanded: 'expanded'
	};

	//Events
	var listItemClick = function (e)
	{
		if (e.shiftKey)
		{
			//Deselect text
			if (window.getSelection)
			{
				if (window.getSelection().empty) // Chrome					
				{
					window.getSelection().empty();
				}
				else if (window.getSelection().removeAllRanges) // Firefox
				{
					window.getSelection().removeAllRanges();
				}
			}
			else if (document.selection) //IE
			{
				document.selection.empty();
			}
		}

		var listItem = $(e.target).closest('li');
		var list = listItem.closest('ol');
		var type = listItem.attr('data-type');
		var schema = schemas[type];
		var usingAvailableList = list.attr('id') === schema.controlIds.available;
		var lastSelected = usingAvailableList ? schema.lastSelection.available : schema.lastSelection.selected;
		var itemSelected = listItem.hasClass('list-item-selected');

		if (!e.ctrlKey && !e.shiftKey)
		{
			list.find('li').removeClass('list-item-selected');
		}

		if (!itemSelected)
		{
			listItem.addClass('list-item-selected');
		}
		else
		{
			listItem.removeClass('list-item-selected');
		}

		if (lastSelected && e.shiftKey)
		{
			var found = false;
			list.find('li:not(.sub)').each(function ()
			{
				var item = $(this);
				var final = false;
				if ((item.attr('data-id') === listItem.attr('data-id')) || (item.attr('data-id') === lastSelected.attr('data-id')))
				{
					//Found shift-select endpoint
					found = !found;
					final = !found;
				}
				if (found || final)
				{
					item.addClass('list-item-selected');

					if (final)
					{
						return false;
					}
				}

				return true;
			});
		}

		//Remember last selection
		if (usingAvailableList)
		{
			schema.lastSelection.available = listItem;
		}
		else
		{
			schema.lastSelection.selected = listItem;
		}

		e.preventDefault();
	};

	var listItemDragHelper = function ()
	{
		var item = $(this);
		var clone = item.clone().attr({ 'data-helper': true.toString() }).addClass('list-item-selected drag-helper');
		clone.find('span.expand-collapse').remove();

		var multiple = item.closest('ol').find('li.list-item-selected:not(.sub)').length > 1;
		if (multiple)
		{
			var text = clone.find('span');
			text.text(text.text() + ', ...');
		}

		return clone;
	};

	var listItemDragStart = function ()
	{
		$(this).closest('li').addClass('list-item-selected');
	};

	var listItemDrop = function (e, ui)
	{
		var dropTarget = $(this);
		var type = dropTarget.attr('data-type');

		var schema = schemas[type];
		var droppedOnSelected = dropTarget.attr('id') === schema.controlIds.selected;
		var valid = ui.draggable.closest('ol').attr('id') !== dropTarget.attr('id');
		if (valid)
		{
			ui.draggable.remove();
			if (droppedOnSelected)
			{
				addSelectedItem(schema);
			}
			else
			{
				removeSelectedItem(schema);
			}

			schemaChange(schema);
		}
	};

	var expandListItemClick = function (e)
	{
		var button = $(e.target);
		var expanding = button.attr('data-state') === expansionState.collapsed;
		var listItem = button.closest('li');
		var type = listItem.attr('data-type');
		var item = findItem(schemas[type], parseInt(listItem.attr('data-id')));
		if (item)
		{
			var path = listItem.attr('data-path');
			listItem.parent('ol').find('li[data-path^="' + path + '-"]').remove();

			if (expanding)
			{
				var depth = path.split('-').length;
				var subItemsExist = false;
				for (var index = schemas[type].subCollections.length - 1; index >= 0; index--)
				{
					var subCollection = schemas[type].subCollections[index];
					var subSchema = schemas[subCollection.type];
					var subCollectionItems = item[subCollection.collection];
					//Load sub-items
					for (var index2 = subCollectionItems.length - 1; index2 >= 0; index2--)
					{
						var subItem = subCollectionItems[index2];
						if (subItem)
						{
							var subListItem = $('<li></li>').attr({ 'class': 'sub', 'data-id': subItem[subSchema.id].toString(), 'data-path': path + '-' + subSchema.prefix + subItem[subSchema.id].toString(), 'data-depth': depth.toString(), 'data-type': subSchema.type })
								.append($('<div></div>')
									.append($('<span></span>').attr({ 'class': subSchema.imageUrl, 'alt': subSchema.toolTip, 'title': subSchema.toolTip }))
									.append(
										subSchema.subCollections != null && subSchema.subCollections.length > 0 && subCollection.recurse
											? $('<span></span>').attr({ 'class': 'expand-collapse ' + images.expandImageUrl, 'title': subSchema.toolTip, 'data-state': expansionState.collapsed }).on('click', expandListItemClick)
											: null)
									.append($('<span></span>').text(subItem[subSchema.name]))
									.append(subSchema.prefix === 'F' ? $('<span></span>').attr({ 'class': 'function-help cw-icon-help', 'data-container': 'body', 'data-original-title': subItem[subSchema.name] + (subItem[subSchema.deleted] ? ' (' + localization.deletedText + ')' : ''), 'data-content': subItem[subSchema.description] }) : null)
								);
							listItem.after(subListItem);
							subItemsExist = true;
						}
					}
				}
				if (!subItemsExist)
				{
					var subListItem = $('<li></li>').attr({ 'class': 'sub', 'data-id': '0', 'data-path': path + '-' + schemas[type].prefix + '0', 'data-depth': depth.toString() })
						.append($('<div></div>')
							.append($('<span></span>').text(schemas[type].noSubItemsExistText)));
					listItem.after(subListItem);
				}
			}
		}
		addPopOverToHelpImage();
		button.removeClass(expanding ? images.expandImage : images.collapseImage);
		button.addClass(expanding ? images.collapseImage : images.expandImage);
		button.attr({ 'data-state': expanding ? expansionState.expanded : expansionState.collapsed });

		e.stopPropagation();
	};

	var addPopOverToHelpImage = function ()
	{
		$('.function-help').popover({ sanitize: false, trigger: "hover", placement: 'left' });
	};

	var addItemsButtonClick = function (e)
	{
		var schema = schemas[$(e.target).closest('button').attr('data-type')];

		addSelectedItem(schema);

		schemaChange(schema);
	};

	var removeItemsButtonClick = function (e)
	{
		var schema = schemas[$(e.target).closest('button').attr('data-type')];

		removeSelectedItem(schema);

		schemaChange(schema);
	};

	var schemaChange = function (schema)
	{
		if ('function' === typeof schema.change)
		{
			schema.change({ data: getSelectedIds(schema) });
		}
	};

	//Methods
	this.getId = function ()
	{
		return clientId;
	};

	this.resize = function ()
	{
		setWidths();
	};

	var loadLists = function ()
	{
		if (schemas)
		{
			for (var type in schemas)
			{
				if (schemas.hasOwnProperty(type))
				{
					var schema = schemas[type];
					initializeItems(schema);
					if (schema.load)
					{
						loadList(schema, enabled);
					}
				}
			}
		}
	};

	var initializeItems = function (schema)
	{
		if (schema)
		{
			var items = schema.items;
			var selectedIds = schema.selectedIds;
			if (items)
			{
				//Items
				for (var index = 0; index < items.length; index++)
				{
					var item = items[index];
					if (selectedIds)
					{
						item[schema.selected] = false;
					}

					//Sub-collections
					if (schema.subCollections)
					{
						for (var index2 = 0; index2 < schema.subCollections.length; index2++)
						{
							var subCollection = schema.subCollections[index2];
							var subSchema = schemas[subCollection.type];

							//Sub-collection ids
							if (item[subCollection.type])
							{
								for (var index3 = 0; index3 < item[subCollection.type].length; index3++)
								{
									var id = item[subCollection.type][index3];
									if (typeof id == 'number')
									{
										//Sub-collection items
										var found = false;
										for (var index4 = 0; index4 < subSchema.items.length; index4++)
										{
											var subItem = subSchema.items[index4];
											if (subItem && id === subItem[subSchema.id])
											{
												item[subCollection.type][index3] = subItem;
												found = true;
												break;
											}
										}

										if (!found)
										{
											item[subCollection.type][index3] = null;
										}
									}
								}

								//Sort the sub-collection
								if (subSchema.sort && typeof subSchema.sort == 'function')
								{
									item[subCollection.type].sort(subSchema.sort);
								}
							}
						}
					}

					//Set selections
					if (selectedIds)
					{
						for (var index2 = 0; index2 < selectedIds.length; index2++)
						{
							var id = selectedIds[index2];
							if (typeof id == 'number' && item[schema.id] === id)
							{
								item[schema.selected] = true;
								break;
							}
						}
					}
				}

				if (schema.sort && typeof schema.sort == 'function')
				{
					items.sort(schema.sort);
				}
			}
		}
	};

	var loadList = function (schema, enabled)
	{
		var available = $(document.getElementById(schema.controlIds.available)).attr({ 'data-type': schema.type }).empty().droppable({ drop: listItemDrop });
		var selected = $(document.getElementById(schema.controlIds.selected)).attr({ 'data-type': schema.type }).empty().droppable({ drop: listItemDrop });
		for (var index = 0; index < schema.items.length; index++)
		{
			if (!schema.filter || schema.filter(schema.items[index], schema.items[index][schema.selected]))
			{
				if (!schema.items[index][schema.selected] && !schema.items[index][schema.deleted])
				{
					available.append(createListItem(schema.items[index], schema, enabled));
				}
				else if (schema.items[index][schema.selected])
				{
					selected.append(createListItem(schema.items[index], schema, enabled));
				}
			}
		}

		addPopOverToHelpImage();
		var addButton = $(document.getElementById(schema.controlIds.addButton)).off('click');
		var removeButton = $(document.getElementById(schema.controlIds.removeButton)).off('click');
		if (enabled)
		{
			available.parent().removeClass('hidden');
			addButton.removeAttr('disabled').on('click', addItemsButtonClick);
			removeButton.removeAttr('disabled').on('click', removeItemsButtonClick);
			addButton.parent().removeClass('hidden');
		}
		else
		{
			available.parent().addClass('hidden');
			addButton.attr({ 'disabled': 'disabled' });
			removeButton.attr({ 'disabled': 'disabled' });
			addButton.parent().addClass('hidden');
		}
	};

	var createListItem = function (item, schema, enabled)
	{
		var listItem = $('<li></li>').attr({ 'data-id': item[schema.id].toString(), 'data-path': schema.prefix + item[schema.id].toString(), 'data-type': schema.type }).on('click', enabled ? listItemClick : function () { })
			.append($('<div></div>')
				.append($('<span><span>').attr({ 'class': schema.imageUrl, 'title': schema.toolTip }))
				.append(
					schema.subCollections != null && schema.subCollections.length > 0
						? $('<span></span>').attr({ 'class': 'expand-collapse cw-icon-node-open', 'title': schema.toolTip, 'data-state': expansionState.collapsed }).on('click', expandListItemClick)
						: null)
				.append($('<span></span>').text(item[schema.name] + (item[schema.deleted] ? ' (' + localization.deletedText + ')' : '')))
				.append(schema.prefix === 'F' ? $('<span></span>').attr({ 'class': schema.helpImageUrl + ' function-help', 'data-container': 'body', 'data-original-title': item[schema.name] + (item[schema.deleted] ? ' (' + localization.deletedText + ')' : ''), 'data-content': item[schema.description] }) : null)
			).draggable({ revert: 'invalid', scroll: false, helper: listItemDragHelper, start: listItemDragStart, disabled: !enabled });

		return listItem;
	};

	var findItem = function (schema, id, useFilter, additionalResults)
	{
		var found = null;
		for (var index = 0; index < schema.items.length; index++)
		{
			var current = schema.items[index];
			if (current[schema.id] === id)
			{
				found = current;
				break;
			}
			if (additionalResults && (!useFilter || (schema.filter && schema.filter(current)) || !schema.filter))
			{
				additionalResults.previousItem = current;
				if (current[schema.selected])
				{
					additionalResults.previousSelectedItem = current;
				}
				else if (typeof schema.deleted === 'undefined' || !current[schema.deleted])
				{
					additionalResults.previousNonSelectedItem = current;
				}
			}
		}

		return found;
	};

	var getSelectedIds = function (schema)
	{
		var ids = [];
		if (schema)
		{
			ids = schema.items
				.filter(function (item)
				{
					return !!item[schema.selected];
				})
				.map(function (item)
				{
					return CivicWeb.Common.toNumber(item[schema.id]);
				});
		}

		return ids;
	};

	var addSelectedItem = function (schema)
	{
		//Add selections to the selected list
		var available = $(document.getElementById(schema.controlIds.available));
		var selected = $(document.getElementById(schema.controlIds.selected));
		available.find('.list-item-selected:not(.sub)').each(function ()
		{
			var id = $(this).attr('data-id');
			available.find('li.sub[data-path^="' + schema.prefix + id + '-"]').remove();
			var additionalResults = {};
			var item = findItem(schema, parseInt(id), true, additionalResults);
			if (item)
			{
				item[schema.selected] = true;
				if (additionalResults.previousSelectedItem)
				{
					selected.find('li[data-id="' + additionalResults.previousSelectedItem[schema.id].toString() + '"]:not(.sub)').after(createListItem(item, schema, true));
				}
				else
				{
					selected.prepend(createListItem(item, schema, true));
				}
			}
		}).remove();
		addPopOverToHelpImage();
	};

	var removeSelectedItem = function (schema)
	{
		//Remove selections from the selected list
		var available = $(document.getElementById(schema.controlIds.available));
		var selected = $(document.getElementById(schema.controlIds.selected));
		selected.find('.list-item-selected:not(.sub)').each(function ()
		{
			var id = $(this).attr('data-id');
			selected.find('li.sub[data-path^="' + schema.prefix + id + '-"]').remove();
			var additionalResults = {};
			var item = findItem(schema, parseInt(id), true, additionalResults);
			if (item)
			{
				item[schema.selected] = false;
				if (additionalResults.previousNonSelectedItem)
				{
					available.find('li[data-id="' + additionalResults.previousNonSelectedItem[schema.id].toString() + '"]:not(.sub)').after(createListItem(item, schema, true));
				}
				else
				{
					available.prepend(createListItem(item, schema, true));
				}
			}
		}).remove();
		addPopOverToHelpImage();
	};

	var setWidths = function ()
	{
		if (schemas)
		{
			for (var type in schemas)
			{
				if (schemas.hasOwnProperty(type))
				{
					var schema = schemas[type];
					var container = $(document.getElementById(schema.controlIds.selected)).closest('.list-boxes');

					var buttonsWidth = container.find('.list-box-buttons').width();
					var boxWidth = (container.width() - buttonsWidth - 28) / 2;
					if (boxWidth > 0)
					{
						container.find('.list-box-available').width(boxWidth);
						//Messes up security control with td
						if (!container.find('.list-box-selected').parent('td').length > 0)
						{
							container.find('.list-box-selected').width(boxWidth);
						}
					}
				}
			}
		}
	};

	(function ()
	{
		loadLists();
		setWidths();

		window.onresize = function ()
		{
			setWidths();
		};
	})();
};

//Objects
CivicWeb.Common.ListBoxes = {
	//Properties
	instances: [],

	//Methods
	getInstance: function (clientId)
	{
		return this.instances.find(function (instance)
		{
			return instance.getId() === clientId;
		});
	},

	getIndex: function (clientId)
	{
		var index;
		for (index = 0; index < this.instances.length; index++)
		{
			var current = this.instances[index];
			if (current.getId() === clientId)
			{
				break;
			}
		}

		return index >= this.instances.length ? -1 : index;
	},

	createInstance: function (args)
	{
		var instance = this.getInstance(args.clientId);
		var index = this.getIndex(args.clientId);
		if (instance)
		{
			delete instance;
		}
		if (index < 0)
		{
			index = this.instances.length;
		}
		this.instances[index] = new CivicWeb.Common.ListBox(args);
	},

	resize: function ()
	{
		this.getInstance().resize();
	},

	generateListBoxes: function (type, availableLabel, selectedLabel, addButtonText, addButtonToolTip, removeButtonText, removeButtonToolTip)
	{
		return $('<div></div>').addClass('list-boxes')
			.append($('<div></div>').addClass('list-box list-box-available')
				.append($('<label></label>').attr({ 'for': this.defaultClientIds.available + type }).text(availableLabel))
				.append($('<ol></ol>').attr({ 'id': this.defaultClientIds.available + type })))
			.append($('<div></div>').addClass('list-box list-box-buttons')
				.append(CivicWeb.Common.Button.create(type + this.defaultClientIds.addButton, addButtonText, addButtonToolTip, CivicWeb.Common.Button.types.short, { 'data-type': type }))
				.append($('<br />'))
				.append($('<br />'))
				.append(CivicWeb.Common.Button.create(type + this.defaultClientIds.removeButton, removeButtonText, removeButtonToolTip, CivicWeb.Common.Button.types.short, { 'data-type': type })))
			.append($('<div></div>').addClass('list-box list-box-selected')
				.append($('<label></label>').attr({ 'for': this.defaultClientIds.selected + type }).text(selectedLabel))
				.append($('<ol></ol>').attr({ 'id': this.defaultClientIds.selected + type })));
	},

	defaultClientIds: {
		available: 'available-',
		selected: 'selected-',
		addButton: '-add-button',
		removeButton: '-remove-button'
	},

	getClientIds: function (type)
	{
		return {
			available: this.defaultClientIds.available + type,
			selected: this.defaultClientIds.selected + type,
			addButton: type + this.defaultClientIds.addButton,
			removeButton: type + this.defaultClientIds.removeButton
		}
	},

	//Events
	events: {
	}
};
;
window.CivicWeb = window.CivicWeb || {};
window.CivicWeb.Common = window.CivicWeb.Common || {};

(function (library, $)
{
	//Functions
	var getLanguageFromId = function (id)
	{
		id = id || '';
		var idParts = id.split('-');
		if (idParts.length > 2)
		{
			idParts.splice(0, idParts.length - 2);
		}
		return idParts.join('-');
	};

	//Methods
	library.values = function (container, fieldClientIdPrefix, defaultValue, unique)
	{
		defaultValue = defaultValue || '';
		unique = typeof unique !== 'boolean' || unique;

		var values = [];
		CivicWeb.Common.getJqueryObject(container).find('input[id^="' + fieldClientIdPrefix + '"]').each(function ()
		{
			var value = $(this).val() || '';
			if (!unique || $.inArray(value, values) < 0)
			{
				values.push(value.length > 0 ? value : defaultValue);
			}
		});

		return values;
	};

	library.getFieldData = function (container, fieldClientIdPrefix, defaultValue)
	{
		defaultValue = defaultValue || '';

		var data = [];
		CivicWeb.Common.getJqueryObject(container).find('input[id^="' + fieldClientIdPrefix + '"]').each(function ()
		{
			var field = $(this);
			var id = field.attr('id');
			var language = getLanguageFromId(id);
			var value = field.val() || '';
			data.push({ language: language, value: value.length > 0 ? value : defaultValue });
		});

		return data;
	};

	library.getTextAreaFieldData = function (container, fieldClientIdPrefix, defaultValue)
	{
		defaultValue = defaultValue || '';

		var data = [];
		CivicWeb.Common.getJqueryObject(container).find('textarea[id^="' + fieldClientIdPrefix + '"]').each(function ()
		{
			var field = $(this);
			var id = field.attr('id');
			var language = getLanguageFromId(id);
			var value = field.val() || '';
			data.push({ language: language, value: value.length > 0 ? value : defaultValue });
		});

		return data;
	};

	library.join = function (container, fieldClientIdPrefix, separator, unique)
	{
		separator = separator || ',';
		unique = typeof unique !== 'boolean' || unique;

		var values = [];
		CivicWeb.Common.getJqueryObject(container).find('input[id^="' + fieldClientIdPrefix + '"]').each(function ()
		{
			var value = $(this).val() || '';
			if (!unique || $.inArray(value, values) < 0)
			{
				values.push(value);
			}
		});

		return values.join(separator);
	};

	library.getEditorFieldData = function (container, fieldClientIdPrefix)
	{
		var data = [];
		CivicWeb.Common.getJqueryObject(container).find('textarea[id^="' + fieldClientIdPrefix + '"]').each(function ()
		{
			var field = $(this);
			var id = field.attr('id');
			var language = getLanguageFromId(id);
			data.push({ language: language, value: field.data('kendoEditor').value() });
		});

		return data;
	};

	library.getLocalizationData = function (language, value)
	{
		return [{ language: language, value: value || '' }];
	};
})(window.CivicWeb.Common.Localization = window.CivicWeb.Common.Localization || {}, jQuery);
;
window.CivicWeb = window.CivicWeb || {};
window.CivicWeb.Common = window.CivicWeb.Common || {};

(function (library, $)
{
	//Methods
	library.logEvent = function (message)
	{
		return $.ajax({
			url: '/api/users/event',
			contentType: 'application/json',
			dataType: 'json',
			async: true,
			cache: false,
			type: 'POST',
			data: JSON.stringify({ message: message || '' })
		});
	};
})(window.CivicWeb.Common.Log = window.CivicWeb.Common.Log || {}, jQuery);
;
// Declare namespaces
var CivicWeb = CivicWeb || {};
CivicWeb.Common = CivicWeb.Common || {};

//Create classes
(CivicWeb.Common.Menu = function ()
{
	//Event Handlers
	var sidebarMenuTopLevelClick = function (e)
	{
		var clickedDiv;
		if (e.target.nodeName === 'SPAN')
		{
			clickedDiv = $(e.target).parent();
		}
		else
		{
			clickedDiv = $(e.target);
		}

		clickedDiv.siblings('ul').toggleClass('hidden');
		clickedDiv.children('.ic-icon-caret').toggleClass('arrow-down').toggleClass('arrow-right');
	};

	//Methods
	(function ()
	{
		$(document).ready(function ()
		{
			$('.side-bar-menu').find('div.side-bar-main').off('click').on('click', sidebarMenuTopLevelClick);
			$('a.menuHelpLink').attr({ 'href': '/Global/Help.aspx?Catagory=' + window.location.pathname });
		});
	})(this);
})();
;
window.CivicWeb = window.CivicWeb || {};
window.CivicWeb.Common = window.CivicWeb.Common || {};

(function (control, $)
{
	//Variables
	var pushToAllNoticesBarClientId = 'push-to-all-notices';
	var noticesThrobberOverlayClientId = 'notices-loading';
	var noticeWindowClientId = 'notices-window';
	var previousButtonClientId = 'notices-previous';
	var nextButtonClientId = 'notices-next';
	var markAsReadButtonClientId = 'notices-mark-as-read';

	var userId = 0;
	var localization = null;
	var pushToAllNotices = [];
	var notices = null;
	var noticeWindow = null;
	var currentIndex = 0;

	//Events
	var windowResize = function ()
	{
		setNoticeWindowSize();
	};

	var pushToAllNoticesBarClick = function (e)
	{
		loadNotices(true);

		$(document.getElementById(pushToAllNoticesBarClientId)).remove();
		$('body').find('.Main').css({ 'height': '' });

		e.preventDefault();
	};

	var previousClick = function (e)
	{
		currentIndex--;
		loadNotice();

		e.preventDefault();
	};

	var nextClick = function (e)
	{
		currentIndex++;
		loadNotice();

		e.preventDefault();
	};

	var markAsReadClick = function (e)
	{
		markAsRead();

		closeWindow();

		e.preventDefault();
	};

	var reviewLaterClick = function (e)
	{
		closeWindow();

		e.preventDefault();
	};

	//Functions
	var loadNotices = function (forceLoad, id)
	{
		if (window.location.href.indexOf('notices=True') >= 0 || forceLoad)
		{
			if (!notices)
			{
				$.ajax({
					url: '/api/notices',
					contentType: 'application/json',
					dataType: 'json',
					async: true,
					cache: false,
					type: 'GET'
				}).done(function (data)
				{
					if (data && data.notices.length > 0)
					{
						userId = data.userId;
						localization = data.localization;
						notices = data.notices;

						loadNoticeWindow(id);
					}
				});
			}
			else
			{
				loadNoticeWindow(id);
			}
		}
		else if ($('a.user-sign-in').length === 0)
		{
			setTimeout(loadPushToAllNotices, 100);
		}
	};

	var loadPushToAllNotices = function ()
	{
		$.ajax({
			url: '/api/notices?pushtousersonly=true',
			contentType: 'application/json',
			dataType: 'json',
			async: true,
			cache: false,
			type: 'GET'
		}).done(function (data)
		{
			if (data && data.notices.length > 0)
			{
				userId = data.userId;
				localization = data.localization;
				pushToAllNotices = data.notices;

				displayPushToAllNotices();
			}
		});
	};

	var displayPushToAllNotices = function (index)
	{
		if (pushToAllNotices.length > 0)
		{
			index = Math.max(Math.min(index || 0, pushToAllNotices.length - 1), 0);

			var pushToAllNoticesBar = $(document.getElementById(pushToAllNoticesBarClientId));
			if (pushToAllNoticesBar.length === 0)
			{
				var useFlexBox = true;
				var container = $('body').children('div.layout').first();
				if (container.length === 0)
				{
					(container = $('body').find('form').first()).find('.Main').css({ 'height': 'calc(100% - 64px - 3em)' });

					useFlexBox = false;
				}

				container
					.prepend(pushToAllNoticesBar = $('<div></div>').attr({ 'id': pushToAllNoticesBarClientId, 'class': 'notice-push-to-all-users' + (useFlexBox ? ' layout-section' : '') }).on('click', pushToAllNoticesBarClick));
			}

			pushToAllNoticesBar.empty().attr({ 'data-id': pushToAllNotices[index].Id })
				.append($('<span></span>').attr({ 'class': 'cw-icon-warning left-middle' }))
				.append($('<span></span>').attr({ 'class': 'notice-push-to-all-users-text left-middle' }).text(pushToAllNotices[index].Title));

			if (pushToAllNotices.length > 1)
			{
				index++;
				if (index >= pushToAllNotices.length)
				{
					index = 0;
				}

				setTimeout((function (index)
				{
					return function ()
					{
						displayPushToAllNotices(index);
					};
				})(index), 10000);
			}
		}
	};

	var loadNoticeWindow = function (id)
	{
		if (notices && notices.length > 0)
		{
			if (CivicWeb.Common.loadKendoUi(function () { loadNoticeWindow(id) }))
			{
				$(document.getElementById(noticesThrobberOverlayClientId)).remove();

				if (!noticeWindow)
				{
					currentIndex = 0;
					if (id)
					{
						currentIndex = Math.max(notices.findIndex(function (notice) { return notice.Id === id; }), 0);
					}

					noticeWindow = $('<div></div>').attr({ 'id': noticeWindowClientId, 'class': 'notice hidden' })
						.append($('<div></div>').attr({ 'class': 'notice-body' }).html(notices[currentIndex].Body))
						.append($('<div></div>').attr({ 'class': 'notice-footer' })
							.append($('<div></div>').attr({ 'class': 'left-middle' })
								.append($('<a></a>').attr({ 'class': (notices[currentIndex].preview ? ' hidden' : ''), 'href': '/notices/read', 'target': '_blank' }).text(localization.linkReadPreviousNotices)))
							.append($('<div></div>').attr({ 'class': 'right-middle' })
								.append($('<a></a>').attr({ 'class': (notices[currentIndex].preview ? ' hidden' : ''), 'href': '/user/' + userId.toString(), 'target': '_blank' }).text(localization.editYourNoticesText)))
							.append($('<div></div>').attr({ 'class': 'center-middle' })
								.append($('<button></button>').attr({ 'id': previousButtonClientId, 'class': 'button hidden' }).text(localization.previousText).on('click', previousClick))
								.append($('<button></button>').attr({ 'id': nextButtonClientId, 'class': 'button' + (notices.length === 1 ? ' hidden' : '') }).text(localization.nextText).on('click', nextClick))
								.append($('<button></button>').attr({ 'id': markAsReadButtonClientId, 'class': 'button' + (notices.length > 1 || notices[currentIndex].preview ? ' hidden' : '') }).text(localization.markAsReadText).on('click', markAsReadClick))
								.append($('<button></button>').attr({ 'class': 'button' + (notices[currentIndex].preview ? ' hidden' : '') }).text(localization.reviewLaterText).on('click', reviewLaterClick))));
					$('body').append(noticeWindow);

					loadGrids();

					noticeWindow.kendoWindow({
						width: '800px',
						height: Math.min(600, Math.max($(window).height() - 150, 300)) + 'px',
						modal: true,
						visible: false,
						title: notices[currentIndex].Title,
						close: function ()
						{
							markAsRead();

							if (history && history.pushState)
							{
								history.replaceState(null, null, CivicWeb.Common.removeUrlParameter(window.location.href, 'notices'));
							}
						}
					});

					noticeWindow.css({ 'padding': '0', 'overflow': 'initial' }); //Override Kendo UI styles
				}

				noticeWindow.removeClass('hidden').css({ 'visibility': '' }).data('kendoWindow').center().open();
			}
			else
			{
				//Show loading throbber
				$('body')
					.append($('<div></div>').attr({ 'id': noticesThrobberOverlayClientId, 'class': 'overlay-all' })
						.append($('<div></div>').addClass('overlay-content')
							.append($('<span></span>').attr({ 'class': 'overlay-throbber' })
								.append(CivicWeb.Common.Button.getThrobber(noticesThrobberOverlayClientId + '-throbber')))));
			}
		}
	};

	var setNoticeWindowSize = function ()
	{
		if (noticeWindow)
		{
			var noticeKendoWindow = noticeWindow.data('kendoWindow');

			noticeKendoWindow.setOptions({
				width: '80%',
				maxWidth: '800px',
				height: Math.min(600, Math.max($(window).height() - 150, 300)) + 'px',
				maxHeight: Math.min(10000, Math.max($(window).height() - 150, 300)) + 'px'
			});

			noticeKendoWindow.center();
		}
	};

	var loadNotice = function ()
	{
		if (notices && notices.length > 0)
		{
			if (currentIndex < 0)
			{
				currentIndex = 0;
			}
			if (currentIndex >= notices.length)
			{
				currentIndex = notices.length;
			}

			if (noticeWindow)
			{
				destroyGrids();

				noticeWindow.data('kendoWindow').title(notices[currentIndex].Title);
				noticeWindow.find('.notice-body').html(notices[currentIndex].Body);

				loadGrids();

				//Toggle buttons
				if (currentIndex === 0)
				{
					$(document.getElementById(previousButtonClientId)).addClass('hidden');
				}
				else
				{
					$(document.getElementById(previousButtonClientId)).removeClass('hidden');
				}
				if (currentIndex === (notices.length - 1))
				{
					$(document.getElementById(nextButtonClientId)).addClass('hidden');
					if (!notices[currentIndex].preview)
					{
						$(document.getElementById(markAsReadButtonClientId)).removeClass('hidden');
					}
				}
				else
				{
					$(document.getElementById(nextButtonClientId)).removeClass('hidden');
					$(document.getElementById(markAsReadButtonClientId)).addClass('hidden');
				}
			}
		}
	};

	var destroyGrids = function ()
	{
		if (noticeWindow)
		{
			var grid = noticeWindow.find('.record-list').data('kendoGrid');
			if (grid)
			{
				grid.destroy();
			}
		}
	};

	var loadGrids = function ()
	{
		if (noticeWindow)
		{
			noticeWindow.find('.record-list').kendoGrid({
				scrollable: false
			});
		}
	};

	var markAsRead = function ()
	{
		var noticeIds = notices.map(function (currentValue) { return currentValue.Id });

		return $.ajax({
			url: '/api/notices/read',
			contentType: 'application/json',
			dataType: 'json',
			async: true,
			cache: false,
			type: 'POST',
			data: JSON.stringify(noticeIds)
		});
	};

	var closeWindow = function ()
	{
		if (noticeWindow)
		{
			noticeWindow.addClass('hidden').data('kendoWindow').close();
		}
	};

	//Methods
	control.preview = function (previewNotices, previewLocalization)
	{
		if (previewNotices && previewNotices.length > 0)
		{
			localization = previewLocalization;
			notices = previewNotices;

			loadNoticeWindow();

			loadNotice();
		}
	};

	(function ()
	{
		loadNotices();

		$(window).on('resize', windowResize);
	})();
})(window.CivicWeb.Common.Notice = window.CivicWeb.Common.Notice || {}, jQuery);
;
window.CivicWeb = window.CivicWeb || {};
window.CivicWeb.Common = window.CivicWeb.Common || {};

(function (library, $)
{
	//Variables
	var hiddenClass = 'hidden';
	var classes = {
		success: 'notification-success',
		warning: 'notification-warning',
		failure: 'notification-failure',
		error: 'notification-error',
		instruction: 'notification-instruction'
	};

	var iconClasses = {
		success: 'cw-icon-success',
		failure: 'cw-icon-failure',
		error: 'cw-icon-failure',
		warning: 'cw-icon-warning',
		instruction: 'cw-icon-instruction'
	};

	//Methods
	library.create = function (id, type, text, hidden, escapeText)
	{
		text = text || '';
		type = type || library.types.instruction;
		escapeText = 'undefined' === typeof escapeText || escapeText == null ? true : escapeText;
		var typeClass = classes[type] || '';
		var iconClass = iconClasses[type] || '';

		var iconObject = $('<span></span>').attr({ 'class': 'notification-icon ' + iconClass });
		var textObject = $('<span></span>').attr({ 'class': 'notification-text' });
		if ('string' === typeof text)
		{
			if (escapeText)
			{
				textObject.text(text);
			}
			else
			{
				textObject.html(text);
			}
		}
		else if (text instanceof jQuery)
		{
			textObject.append(text);
		}

		var object = $(document.getElementById(id) || '<div></div>').empty().attr({ 'id': id, 'class': 'notification' + (typeClass.length > 0 ? ' ' + typeClass : '') + (hidden ? ' hidden' : ''), 'role': 'alert', 'aria-live': 'polite' })
			.append(iconObject)
			.append(textObject);

		return object;
	};

	library.hide = function (element, changeCallback)
	{
		var object = CivicWeb.Common.getJqueryObject(element);

		var changed = 'function' === typeof changeCallback && !object.hasClass(hiddenClass); //Is there a callback and should we call it?

		object.addClass(hiddenClass).removeClass(classes.success + ' ' + classes.warning + ' ' + classes.failure + ' ' + classes.error + ' ' + classes.instruction);

		if (changed && 'function' === typeof changeCallback)
		{
			changeCallback(false);
		}

		return object;
	};

	library.show = function (element, type, text, preventSuccessFadeOut, escapeText, changeCallback)
	{
		var object = CivicWeb.Common.getJqueryObject(element);
		
		var changed = object.hasClass(hiddenClass); //Is there a change?

		library.hide(object);

		var textObject = object.find('.notification-text');
		var existingText = textObject.html();

		text = text || existingText || '';
		type = type || library.types.instruction;
		preventSuccessFadeOut = !!preventSuccessFadeOut;
		escapeText = 'undefined' === typeof escapeText || escapeText == null ? true : escapeText;

		changed = changed || text !== existingText; //Is there a change?

		object.find('.notification-icon').attr('class', 'notification-icon').addClass(iconClasses[type]);
		textObject.empty();
		if ('string' === typeof text)
		{
			if (escapeText)
			{
				textObject.text(text);
			}
			else
			{
				textObject.html(text);
			}
		}
		else if ('[object Array]' === Object.prototype.toString.call(text))
		{
			var list = $('<ul></ul>').attr({ 'class': 'compact' });
			for (var index = 0; index < text.length; index++)
			{
				if ('string' === typeof text[index])
				{
					list
						.append($('<li></li>').text(text[index]));
				}
				else if (text instanceof jQuery)
				{
					list
						.append($('<li></li>').append(text));
				}
			}
			textObject.append(list);
		}
		else if (text instanceof jQuery)
		{
			textObject.append(text);
		}
		if (type === library.types.success && !preventSuccessFadeOut)
		{
			setTimeout(function () { object.fadeOut(); }, 3000);
			setTimeout(function () { object.addClass(hiddenClass); object.fadeIn(); object.css('display', ''); }, 4000);
		}
		
		object.addClass(classes[type]).removeClass(hiddenClass).attr({ 'role': 'alert', 'aria-live': 'polite' });

		if (changed && 'function' === typeof changeCallback) //Is there a callback and should we call it?
		{
			changeCallback(true);
		}
		
		return object;
	};

	//Properties
	library.types = {
		success: 'success',
		warning: 'warning',
		failure: 'failure',
		error: 'error',
		instruction: 'instruction'
	};
})(window.CivicWeb.Common.Notification = window.CivicWeb.Common.Notification || {}, jQuery);
;
// Declare namespaces
var CivicWeb = CivicWeb || {};
CivicWeb.Common = CivicWeb.Common || {};

//Create classes
CivicWeb.Common.NotificationControl = function (args)
{
	//Properties
	var id = args.id;
	var subjectContent = args.subjectContent;
	var bodyContent = args.bodyContent;
	var schema = args.schema;
	var localization = args.localization;
	var itemId = args.itemId;
	var sendCallback = args.sendCallback;

	var sendButtonClientId = id + '-send-button';
	var toButtonClientId = id + '-to-button';
	var ccButtonClientId = id + '-cc-button';
	var bccButtonClientId = id + '-bcc-button';
	var closeButtonClientId = id + '-close-contact-list-button';

	var toTextBoxClientId = id + '-to-textbox';
	var ccTextBoxClientId = id + '-cc-textbox';
	var bccTextBoxClientId = id + '-bcc-textbox';

	var contactListClientId = id + '-contact-list';
	var contactListSelectClientId = id + '-contact-list-select';

	var subjectClientId = id + '-subject';
	var meetingClientId = id + '-meeting';
	var locationClientId = id + '-location';
	var startDateClientId = id + '-start-date';
	var startTimeClientId = id + '-start-time';
	var endDateClientId = id + '-end-date';
	var endTimeClientId = id + '-end-time';
	var reminderClientId = id + '-reminder';
	var bodyEditorClientId = id + '-body-editor';

	var notificationResultNotificationClientId = id + '-notification';

	var errorMsg = '';

	var recipients = {
		to: {
			internal: [],
			external: []
		},
		cc: {
			internal: [],
			external: []
		},
		bcc: {
			internal: [],
			external: []
		}
	};
	var activeType = '';
	var createMeeting = false;
	var meeting = {
		update: false,
		uid: undefined,
		cancel: false,
		sequence: undefined
	}

	//Events
	var sendButtonClick = function ()
	{
		var data = buildNotificationObject();
		if (validate())
		{
			CivicWeb.Common.Button.update(sendButtonClientId, localization.sendingEmailLabel, true, true);
			$(document.getElementById(sendButtonClientId)).find('img').addClass('hidden');

			$.ajax({
				url: '/api/notification/send',
				contentType: 'application/json',
				dataType: 'json',
				async: true,
				cache: false,
				type: 'POST',
				data: JSON.stringify(data)
			}).done(function (result)
			{
				CivicWeb.Common.Button.update(sendButtonClientId, localization.sendEmailLabel, false, false);
				$(document.getElementById(sendButtonClientId)).find('img').removeClass('hidden');
				if (result.Result)
				{
					CivicWeb.Common.Notification.show(notificationResultNotificationClientId, CivicWeb.Common.Notification.types.success, localization.sendingSucceededNotificationText);
				}

				stopUpdatingMeeting();

				if (sendCallback)
				{
					sendCallback();
				}
			}).fail(function ()
			{
				CivicWeb.Common.Notification.show(notificationResultNotificationClientId, CivicWeb.Common.Notification.types.failed, localization.sendingFailedNotificationText);
				CivicWeb.Common.Button.update(sendButtonClientId, localization.sendEmailLabel, false, false);
				$(document.getElementById(sendButtonClientId)).find('img').removeClass('hidden');
			});
		}
	};

	var selectRecipientClick = function (e)
	{
		var button = $(e.target).closest('button');
		var type = button.attr('data-type');
		if (recipients.hasOwnProperty(type))
		{
			activeType = type;
			button.closest('tr').find('input[data-type="' + type + '"]').change();

			$(document.getElementById(contactListSelectClientId)).val(recipients[type].internal);

			button.after($(document.getElementById(contactListClientId)));
			$(document.getElementById(contactListClientId)).removeClass('hidden');
		}
	};

	var recipientTextBoxFocus = function (e)
	{
		$(e.target).data('kendoAutoComplete').search('');
	};

	var recipientTextBoxChange = function (e)
	{
		var textBox = $(e.target).closest('input');
		var type = textBox.attr('data-type');
		if (recipients.hasOwnProperty(type))
		{
			recipients[type] = {
				internal: [],
				external: []
			};
			(textBox.val() || '').split(';').forEach(function (currentValue)
			{
				var internalOrExternal = currentValue.indexOf('@') !== -1 && !schema.lists.users.find(function (element)
				{
					return element.DisplayName === currentValue;
				}) ? 'external' : 'internal';
				if ($.inArray(currentValue, recipients[type][internalOrExternal]) === -1)
				{
					recipients[type][internalOrExternal].push(currentValue);
				}
			});
		}
	};

	var closeButtonClick = function ()
	{
		$(document.getElementById(contactListClientId)).addClass('hidden');
	};

	var contactListSelectChange = function (e)
	{
		if (recipients.hasOwnProperty(activeType))
		{
			recipients[activeType].internal = [];

			var listBox = $(e.target).closest('select');
			(listBox.val() || []).forEach(function (currentValue)
			{
				if ($.inArray(currentValue, recipients[activeType].internal) === -1)
				{
					recipients[activeType].internal.push(currentValue);
				}
			});

			listBox.closest('.notification-control').find('input[data-type="' + activeType + '"]').val([].concat(recipients[activeType].internal, recipients[activeType].external).join(';'));
		}
	};

	var meetingClick = function (e)
	{
		createMeeting = !createMeeting;
		$(document.getElementById(id)).find('tr[data-meeting]').toggleClass('hidden', !createMeeting);

		CivicWeb.Common.Button.updateOptions($(e.target).closest('button'), { text: createMeeting ? localization.buttonOnlySendNotification : localization.buttonCreateMeetingAppointment, toolTip: createMeeting ? localization.toolTipOnlySendNotification : localization.toolTipCreateMeetingAppointment });

		e.preventDefault();
	};

	//Methods
	var loadAutocomplete = function (suggestions, textBox)
	{
		suggestions = suggestions || [];

		if (!textBox)
		{
			loadAutocomplete(suggestions, $(document.getElementById(toTextBoxClientId)));
			loadAutocomplete(suggestions, $(document.getElementById(ccTextBoxClientId)));
			loadAutocomplete(suggestions, $(document.getElementById(bccTextBoxClientId)));
		}
		else
		{
			var autoComplete = textBox.data('kendoAutoComplete');
			if (autoComplete)
			{
				autoComplete.destroy();
			}

			textBox.kendoAutoComplete({
				separator: ['; ', ';'],
				filter: 'contains',
				dataSource: {
					data: suggestions
				},
				dataTextField: 'value',
				template: '<span>#: name #</span>'
			});

			textBox.off('focus', recipientTextBoxFocus).on('focus', recipientTextBoxFocus);
		}
	};

	var loadMeeting = function ()
	{
		if ($(document.getElementById(locationClientId)).length === 1)
		{
			$(document.getElementById(startDateClientId)).add(document.getElementById(endDateClientId)).kendoDatePicker({
				format: localization.dateFormat
			});
			$(document.getElementById(startTimeClientId)).add(document.getElementById(endTimeClientId)).kendoTimePicker({
				format: localization.timeFormat
			});
		}
	};

	var validate = function ()
	{
		var blnValid = true;
		var strTo = document.getElementById(toTextBoxClientId).value;
		var strCc = document.getElementById(ccTextBoxClientId).value;
		var strBcc = document.getElementById(bccTextBoxClientId).value;
		var strSubject = document.getElementById(subjectClientId).value;
		var editor = document.getElementById(bodyEditorClientId);
		var strBody = editor.value;
		errorMsg = '';
		
		if (strTo.length === 0 && strBcc.length === 0)
		{
			blnValid = false;
			errorMsg += localization.warningToBlank + '\n';// 'To cannot be blank; ';
		}
		if (strSubject.length === 0)
		{
			blnValid = false;
			errorMsg += localization.warningSubjectBlank + '\n'; //'Subject cannot be blank; ';
		}
		if (strBody.length === 0)
		{
			blnValid = false;
			errorMsg += localization.warningBodyBlank + '\n'; //'Email body cannot be blank; ';
		}
		if (!validateRecipients(strTo))
		{
			blnValid = false;
		}
		if (!validateRecipients(strCc))
		{
			blnValid = false;
		}
		if (!validateRecipients(strBcc))
		{
			blnValid = false;
		}

		if (createMeeting)
		{
			if (($(document.getElementById(startDateClientId)).val() || '').length === 0)
			{
				blnValid = false;
				errorMsg += localization.warningMessagePleaseSelectAStartDate + '\n';
			}
			if (($(document.getElementById(startTimeClientId)).val() || '').length === 0)
			{
				blnValid = false;
				errorMsg += localization.warningMessagePleaseSelectAStartTime + '\n';
			}
			if (($(document.getElementById(endDateClientId)).val() || '').length === 0)
			{
				blnValid = false;
				errorMsg += localization.warningMessagePleaseSelectAnEndDate + '\n';
			}
			if (($(document.getElementById(endTimeClientId)).val() || '').length === 0)
			{
				blnValid = false;
				errorMsg += localization.warningMessagePleaseSelectAnEndTime + '\n';
			}
		}

		if (!blnValid)
		{
			alert(errorMsg);

			return false;
		}
		else
		{
			return true;
		}
	};

	var validateRecipients = function (strRecipients)
	{
		var blnValid = true;

		strRecipients = strRecipients.split(',').join(';');
		if (strRecipients.length !== 0)
		{
			var arEmail = strRecipients.split(';');
			var arLen = arEmail.length;

			for (var i = 0; i < arLen; i++)
			{
				if (arEmail[i].length > 0 && arEmail[i] !== ' ')
				{
					arEmail[i] = $.trim(arEmail[i]);
					if (!isEmail(arEmail[i]) && !isGroup(arEmail[i]))
					{
						blnValid = false;
						errorMsg += arEmail[i] + ' ' + localization.warningInvalidEmail + ';'; // ' is not valid email address or group; ';
					}
				}
			}
		}

		return blnValid;
	};

	var isGroup = function (strGroup)
	{
		var blnValid = false;

		for (var i = 0; i <= document.getElementById(contactListSelectClientId).options.length - 1; i++)
		{
			if (document.getElementById(contactListSelectClientId).options[i].value === strGroup)
			{
				blnValid = true;
				break;
			}
		}

		return blnValid;
	};

	var isEmail = function (strEmail)
	{
		var blnValid = true;
		var regEmailPattern = /^(-|\w)+([\.\+&](-|\w)+)*@(-|\w)+(\.(-|\w)+)+$/i;

		if (!regEmailPattern.test(strEmail))
		{
			blnValid = false;
		}

		return blnValid;
	};

	var buildNotificationObject = function ()
	{
		var notificationObject = {};
		notificationObject.to = $(document.getElementById(toTextBoxClientId)).val();
		notificationObject.cc = $(document.getElementById(ccTextBoxClientId)).val();
		notificationObject.bcc = $(document.getElementById(bccTextBoxClientId)).val();

		notificationObject.subject = $(document.getElementById(subjectClientId)).val();

		if (createMeeting)
		{
			notificationObject.location = $(document.getElementById(locationClientId)).val();
			notificationObject.startDate = $(document.getElementById(startDateClientId)).val();
			notificationObject.startTime = $(document.getElementById(startTimeClientId)).val();
			notificationObject.endDate = $(document.getElementById(endDateClientId)).val();
			notificationObject.endTime = $(document.getElementById(endTimeClientId)).val();
			notificationObject.reminder = $(document.getElementById(reminderClientId)).val();
			notificationObject.uid = meeting.uid;
			notificationObject.cancel = meeting.cancel;
			notificationObject.sequence = meeting.sequence;
		}

		var editor = $(document.getElementById(bodyEditorClientId)).data('kendoEditor');
		var editorBody = $('<div></div>').html(editor.value());
		editorBody.find('p').css({ 'margin': '0' });
		notificationObject.body = editorBody.html();

		notificationObject.itemId = itemId;

		return notificationObject;
	};

	var initializeContactList = function ()
	{
		var autoCompleteSuggestions = [];

		var contactList = $(document.getElementById(contactListSelectClientId));
		if (schema.lists.groups)
		{
			var groupList = $('<optgroup/>').attr({ 'label': schema.localization.groupsLabel });
			$.each(schema.lists.groups, function (index, value)
			{
				groupList.append($('<option/>').attr({ 'value': value.DisplayName }).text(value.ListName));
				autoCompleteSuggestions.push({ value: value.DisplayName, name: localization.formFieldLabelGroup + value.ListName });
			});
			contactList.append(groupList);
		}

		if (schema.lists.emailGroups)
		{
			var emailGroupList = $('<optgroup/>').attr({ 'label': schema.localization.labelMailingLists });
			$.each(schema.lists.emailGroups, function (index, value)
			{
				emailGroupList.append($('<option/>').attr({ 'value': value.DisplayName }).text(value.ListName));
				autoCompleteSuggestions.push({ value: value.DisplayName, name: localization.formFieldLabelMailingList + value.ListName });
			});
			contactList.append(emailGroupList);
		}

		if (schema.lists.users)
		{
			var userList = $('<optgroup/>').attr({ 'label': schema.localization.usersLabel });
			$.each(schema.lists.users, function (index, value)
			{
				userList.append($('<option/>').attr({ 'value': value.DisplayName }).text(value.ListName));
				autoCompleteSuggestions.push({ value: value.DisplayName, name: value.ListName });
			});
			contactList.append(userList);
		}
		$(document.getElementById('notification-contacts-loading')).remove();

		loadAutocomplete(autoCompleteSuggestions);
	};

	var loadNotificationSchema = function ()
	{
		$.ajax({
			url: '/api/notification/notificationcontrolschema',
			contentType: 'application/json',
			dataType: 'json',
			async: true,
			cache: false,
			type: 'GET'
		}).done(function (data)
		{
			if (data)
			{
				if (!schema)
				{
					schema = data;
				}

				if (data.localization && !localization)
				{
					localization = data.localization;
				}

				loadEditor();
				initializeContactList();
			}
		});
	};

	var loadEditor = function ()
	{
		if ($(document.getElementById(bodyEditorClientId)).data('kendoEditor'))
		{
			$(document.getElementById(bodyEditorClientId)).data('kendoEditor').value(bodyContent);
		}
		else
		{
			$(document.getElementById(bodyEditorClientId)).kendoEditor({
				tools: CivicWeb.Common.Forms.editorTools,
				stylesheets: ['/css/kendo/editor/basic?d=' + Date.now().toString(), '/settings/defaultfont'],
				messages: {
					fontNameInherit: localization.kendoEditorLocalization.defaultFont,
					fontSizeInherit: localization.kendoEditorLocalization.defaultFontSize
				}
			}).data('kendoEditor').value(bodyContent);
		}
	};

	this.setOptions = function (options)
	{
		subjectContent = options.subjectContent || subjectContent;
		bodyContent = options.bodyContent || bodyContent;

		$(document.getElementById(subjectClientId)).val(subjectContent);
		loadEditor();
	};

	this.updateMeeting = function (notification, cancel)
	{
		meeting.update = true;

		//Show meeting information
		if (!createMeeting)
		{
			$(document.getElementById(meetingClientId)).click();
		}

		meeting.cancel = cancel;
		CivicWeb.Common.Button.update($(document.getElementById(sendButtonClientId)).addClass('font-bold'), cancel ? localization.buttonCancel : localization.buttonUpdate, false, false);

		meeting.uid = notification.meetingGuid;
		meeting.sequence = notification.meetingSequence;

		//populate the meeting fields and change the 'Send' button to an 'Update' button
		$(document.getElementById(toTextBoxClientId)).val(notification.to);
		$(document.getElementById(ccTextBoxClientId)).val(notification.cc);
		$(document.getElementById(bccTextBoxClientId)).val(notification.bcc);
		$(document.getElementById(subjectClientId)).val(notification.subject);
		$(document.getElementById(locationClientId)).val(notification.location);
		$(document.getElementById(startDateClientId)).data('kendoDatePicker').value(new Date(notification.startTime));
		$(document.getElementById(endDateClientId)).data('kendoDatePicker').value(new Date(notification.endTime));
		$(document.getElementById(startTimeClientId)).data('kendoTimePicker').value(new Date(notification.startTime));
		$(document.getElementById(endTimeClientId)).data('kendoTimePicker').value(new Date(notification.endTime));
		$(document.getElementById(reminderClientId)).val(notification.reminder);
		$(document.getElementById(bodyEditorClientId)).data('kendoEditor').value(notification.body);
	};

	var stopUpdatingMeeting = function ()
	{
		if (meeting.update)
		{
			meeting.update = false;
			meeting.uid = undefined;
			meeting.cancel = false;
			meeting.sequence = undefined;

			CivicWeb.Common.Button.update($(document.getElementById(sendButtonClientId)).removeClass('font-bold'), localization.sendEmailLabel, false, false);

			$(document.getElementById(meetingClientId)).click();
		}
	};

	(function ()
	{
		$(document.getElementById(subjectClientId)).val(subjectContent);

		$(document.getElementById(toButtonClientId)).add(document.getElementById(ccButtonClientId)).add(document.getElementById(bccButtonClientId)).off('click').on('click', selectRecipientClick);
		$(document.getElementById(toTextBoxClientId)).add(document.getElementById(ccTextBoxClientId)).add(document.getElementById(bccTextBoxClientId)).off('change').on('change', recipientTextBoxChange);
		$(document.getElementById(contactListSelectClientId)).off('change').on('change', contactListSelectChange);

		$(document.getElementById(closeButtonClientId)).off('click').on('click', closeButtonClick);
		$(document.getElementById(sendButtonClientId)).off('click').on('click', sendButtonClick);
		$(document.getElementById(meetingClientId)).off('click').on('click', meetingClick);

		loadMeeting();

		if (!schema || !localization)
		{
			loadNotificationSchema();
		}
		else
		{
			loadEditor();
			initializeContactList();
		}
	})();
};

//Objects
CivicWeb.Common.NotificationControls = {
	//Properties
	instances: new Array(),

	//Methods
	getInstance: function ()
	{
		return this.instances.length > 0 ? this.instances[0] : null;
	},

	getIndex: function ()
	{
		var index = 0;

		return index >= this.instances.length ? -1 : index;
	},

	createInstance: function (args)
	{
		var instance = this.getInstance(args.clientId);
		var index = this.getIndex(args.clientId);
		if (instance)
		{
			delete instance;
		}
		if (index < 0)
		{
			index = this.instances.length;
		}
		this.instances[index] = new CivicWeb.Common.NotificationControl(args);
	},

	setOptions: function (options)
	{
		this.getInstance().setOptions(options);
	},

	updateMeeting: function (notification, cancel)
	{
		this.getInstance().updateMeeting(notification, cancel);
	},

	//Events
	events: {
	}
};
;
window.CivicWeb = window.CivicWeb || {};
window.CivicWeb.Common = window.CivicWeb.Common || {};

(function (control, $) {
	//Properties
	var outputDocumentUpdateClientId = 'output-document-update';
	var descriptionClientId = outputDocumentUpdateClientId + '-description';
	var changeClientId = outputDocumentUpdateClientId + '-change';
	var defaultHtmlFolderClientId = outputDocumentUpdateClientId + '-default-html-folder';
	var defaultHtmlFolderLabelClientId = defaultHtmlFolderClientId + '-label';
	var htmlOutputDocumentsClientId = outputDocumentUpdateClientId + '-html-output-documents';
	var defaultPdfFolderClientId = outputDocumentUpdateClientId + '-default-pdf-folder';
	var defaultPdfFolderLabelClientId = defaultPdfFolderClientId + '-label';
	var pdfOutputDocumentsClientId = outputDocumentUpdateClientId + '-pdf-output-documents';
	var updateClientId = outputDocumentUpdateClientId + '-update';
	var cancelClientId = outputDocumentUpdateClientId + '-cancel';
	var updateNotificationClientId = outputDocumentUpdateClientId + '-update-notification';
	var loadingThrobberOverlayClientId = outputDocumentUpdateClientId + '-overlay';

	var baseCssClass = 'output-document-update';

	var localization;

	var onAfterUpdate;

	var isLoaded = false;
	var popupElement;
	var itemId;
	var closed;
	var description;
	var outputDocumentInformation;

	//Event Handlers
	var updateClick = function (e) {
		var button = $(e.target).closest('button');
		var existingText = CivicWeb.Common.Button.update(button, localization.buttonUpdatingOutputDocuments, true, true);
		button.tooltip('destroy');

		var updateNotification = CivicWeb.Common.Notification.hide(updateNotificationClientId);

		$.ajax({
			url: '/api/item/' + itemId + '/moveandupdateoutputdocuments',
			contentType: 'application/json',
			dataType: 'json',
			async: true,
			type: 'POST',
			data: JSON.stringify({
				html: { pathId: outputDocumentInformation.html.defaultPathId, path: outputDocumentInformation.html.defaultPath },
				pdf: { pathId: outputDocumentInformation.pdf.defaultPathId, path: outputDocumentInformation.pdf.defaultPath }
			})
		}).done(function () {
			CivicWeb.Common.Notification.show(updateNotification, CivicWeb.Common.Notification.types.success, localization.notificationOutputDocumentUpdateSucceeded, true);

			CivicWeb.Common.Button.update(button, existingText, true, false);

			if ('function' === typeof onAfterUpdate) {
				onAfterUpdate();
			}

			setTimeout(function () {
				popupElement.data('kendoWindow').close();
				CivicWeb.Common.Button.update(button, existingText, false, false);
				button.tooltip();
			}, 3000);
		}).fail(function () {
			CivicWeb.Common.Notification.show(updateNotification, CivicWeb.Common.Notification.types.failure, localization.notificationOutputDocumentUpdateFailed, true);

			CivicWeb.Common.Button.update(button, existingText, false, false);
			button.tooltip();
		});

		e.preventDefault();
	};

	var cancelClick = function (e) {
		popupElement.data('kendoWindow').close();

		e.preventDefault();
	};

	//Functions
	var getOutputDocumentInformation = function () {
		outputDocumentInformation = null;

		return $.ajax({
			url: '/api/item/' + itemId + '/outputdocumentinformation?showOutputDocuments=true&showDefaultPath=true&closed=' + closed,
			contentType: 'application/json',
			dataType: 'json',
			async: true,
			type: 'GET'
		}).done(function (data) {
			outputDocumentInformation = data;
		});
	};

	var htmlFilter = function (outputDocument) {
		return outputDocument.extension !== '.pdf';
	};

	var pdfFilter = function (outputDocument) {
		return outputDocument.extension === '.pdf';
	};

	var loadPopUp = function () {
		var htmlOutputDocuments = outputDocumentInformation.outputDocuments.filter(htmlFilter);
		var pdfOutputDocuments = outputDocumentInformation.outputDocuments.filter(pdfFilter);

		if (outputDocumentInformation.updateAllowed && outputDocumentInformation.outputDocuments.length > 0 &&
			(outputDocumentInformation.html.defaultPathId === null || 'undefined' !== typeof htmlOutputDocuments.find(function (outputDocument) { return outputDocument.parentId !== outputDocumentInformation.html.defaultPathId; }) ||
				outputDocumentInformation.pdf.defaultPathId === null || 'undefined' !== typeof pdfOutputDocuments.find(function (outputDocument) { return outputDocument.parentId !== outputDocumentInformation.pdf.defaultPathId; }))) {
			if (CivicWeb.Common.loadKendoUi(loadPopUp)) {
				var hasHtml = htmlOutputDocuments.length > 0;
				var hasPdf = pdfOutputDocuments.length > 0;

				$(document.getElementById(loadingThrobberOverlayClientId)).remove();

				var newPopup = !popupElement;
				if (!popupElement) {
					$('body')
						.append(popupElement = $('<div></div>').attr({ 'id': outputDocumentUpdateClientId, 'class': 'hidden' })
							.append($('<div></div>').addClass(baseCssClass)
								.append($('<div></div>').addClass(baseCssClass + '-section')
									.append($('<div></div>')
										.append($('<label></label>').attr({ 'for': descriptionClientId }).text(localization.formFieldLabelItem)))
									.append($('<div></div>').attr({ 'id': descriptionClientId, 'class': baseCssClass + '-description' })))
								.append($('<div></div>').addClass(baseCssClass + '-section')
									.append(CivicWeb.Common.Notification.create(changeClientId, CivicWeb.Common.Notification.types.instruction, '', false)))
								.append(hasHtml ? $('<div></div>').addClass(baseCssClass + '-section')
									.append($('<div></div>')
										.append($('<label></label>').attr({ 'id': defaultHtmlFolderLabelClientId, 'for': defaultHtmlFolderClientId })))
									.append($('<div></div>').attr({ 'id': defaultHtmlFolderClientId, 'class': baseCssClass + '-path' })) : null)
								.append(hasHtml ? $('<div></div>').addClass(baseCssClass + '-section')
									.append($('<div></div>')
										.append($('<label></label>').attr({ 'for': htmlOutputDocumentsClientId }).text(localization.formFieldLabelHtmlOutputDocuments)))
									.append($('<div></div>')
										.append($('<ol></ol>').attr({ 'id': htmlOutputDocumentsClientId, 'class': baseCssClass + '-output-documents clean' }))) : null)
								.append(hasPdf ? $('<div></div>').addClass(baseCssClass + '-section')
									.append($('<div></div>')
										.append($('<label></label>').attr({ 'id': defaultPdfFolderLabelClientId, 'for': defaultPdfFolderClientId })))
									.append($('<div></div>').attr({ 'id': defaultPdfFolderClientId, 'class': baseCssClass + '-path' })) : null)
								.append(hasPdf ? $('<div></div>').addClass(baseCssClass + '-section')
									.append($('<div></div>')
										.append($('<label></label>').attr({ 'for': pdfOutputDocumentsClientId }).text(localization.formFieldLabelPdfOutputDocuments)))
									.append($('<div></div>')
										.append($('<ol></ol>').attr({ 'id': pdfOutputDocumentsClientId, 'class': baseCssClass + '-output-documents clean' }))) : null)
								.append($('<div></div>').attr({ 'class': baseCssClass + '-section button-row' })
									.append(CivicWeb.Common.Button.create(updateClientId, localization.buttonUpdateOutputDocumentsLocationAndPermissions, localization.toolTipUpdateOutputDocumentsLocationAndPermissions, CivicWeb.Common.Button.types.important).on('click', updateClick))
									.append(CivicWeb.Common.Button.create(cancelClientId, localization.buttonMakeNoChanges, localization.toolTipMakeNoChangesToOutputDocumentLocationAndPermissions).on('click', cancelClick)))
								.append($('<div></div>').addClass(baseCssClass + '-section')
									.append(CivicWeb.Common.Notification.create(updateNotificationClientId, CivicWeb.Common.Notification.types.instruction, '', true)))));

					popupElement.kendoWindow({
						width: '800px',
						modal: true,
						visible: false,
						title: localization.titleUpdateOutputDocuments
					});

					popupElement.css({ 'padding': '0', 'overflow': 'initial' }); //Override Kendo UI styles
					popupElement.find('[title]').tooltip();
				}

				//Load data
				$(document.getElementById(descriptionClientId)).html(description);

				CivicWeb.Common.Notification.show(changeClientId, CivicWeb.Common.Notification.types.instruction, closed ? localization.instructionNotClosedToClosedItemWithOutputDocuments : localization.instructionClosedToNotClosedItemWithOutputDocuments, true, false);

				// Html
				if (hasHtml) {
					$(document.getElementById(defaultHtmlFolderLabelClientId)).text(closed ? localization.formFieldLabelClosedHtmlOutputDocumentsFolder : localization.formFieldLabelOpenHtmlOutputDocumentsFolder);
					var defaultHtmlFolder = $(document.getElementById(defaultHtmlFolderClientId)).empty()
						.append($('<span></span>', { 'class': 'folder-image cw-icon-folder-lg', 'title': localization.toolTipFolder }))
						.append(outputDocumentInformation.html.defaultPathExistingPath ? $('<a></a>').attr({ 'href': '/filepro/documents/' + outputDocumentInformation.html.defaultPathExistingFolderId, 'target': '_blank' }).text(outputDocumentInformation.html.defaultPathExistingPath) : null)
						.append(outputDocumentInformation.html.defaultPathRemainingPath ? $('<span></span>').text(outputDocumentInformation.html.defaultPathRemainingPath) : null)
						.append($('<a></a>').attr({ 'href': outputDocumentInformation.html.defaultPathExistingFolderId ? '/filepro/document/' + outputDocumentInformation.html.defaultPathExistingFolderId + '?tab=security' : '/filepro/document/ensureexists?path=' + encodeURIComponent(outputDocumentInformation.html.defaultPath), 'target': '_blank', 'class': 'undecorated' })
							.append($('<span></span>').addClass(baseCssClass + '-permission-label label label-' + (outputDocumentInformation.html.defaultPathIsPublic ? 'success' : 'danger'))
								.append($('<span></span>').addClass('cw-icon-folder-' + (outputDocumentInformation.html.defaultPathIsPublic ? 'permit' : 'forbid')))
								.append($('<span></span>').text(outputDocumentInformation.html.defaultPathIsPublic ? localization.labelPublic : localization.labelPrivate))));
					defaultHtmlFolder.find('[title]').tooltip();

					var htmlOutputDocumentList = $(document.getElementById(htmlOutputDocumentsClientId)).empty();
					htmlOutputDocuments.forEach(function (outputDocument) {
						var extension = outputDocument.extension.replace('.', '');
						var isPublic = outputDocument.isPublic;

						htmlOutputDocumentList
							.append($('<li></li>').addClass(baseCssClass + '-path')
								.append($('<span></span>', { 'class': CivicWeb.Common.getFileIconClass(extension), 'title': extension.toUpperCase() }))
								.append($('<a></a>').attr({ 'href': '/filepro/documents/' + outputDocument.id, 'target': '_blank' }).text(outputDocument.name))
								.append($('<a></a>').attr({ 'href': '/filepro/document/' + outputDocument.id + '?tab=security', 'target': '_blank', 'class': 'undecorated' })
									.append($('<span></span>').addClass(baseCssClass + '-permission-label label label-' + (isPublic ? 'success' : 'danger'))
										.append($('<span></span>').addClass('cw-icon-folder-' + (isPublic ? 'permit' : 'forbid')))
										.append($('<span></span>').text(isPublic ? localization.labelPublic : localization.labelPrivate)))));
					});
					htmlOutputDocumentList.find('[title]').tooltip();
				}

				// Pdf
				if (hasPdf) {
					$(document.getElementById(defaultPdfFolderLabelClientId)).text(closed ? localization.formFieldLabelClosedPdfOutputDocumentsFolder : localization.formFieldLabelOpenPdfOutputDocumentsFolder);
					var defaultPdfFolder = $(document.getElementById(defaultPdfFolderClientId)).empty()
						.append($('<span></span>', { 'class': 'folder-image cw-icon-folder-lg', 'title': localization.toolTipFolder }))
						.append(outputDocumentInformation.pdf.defaultPathExistingPath ? $('<a></a>').attr({ 'href': '/filepro/documents/' + outputDocumentInformation.pdf.defaultPathExistingFolderId, 'target': '_blank' }).text(outputDocumentInformation.pdf.defaultPathExistingPath) : null)
						.append(outputDocumentInformation.pdf.defaultPathRemainingPath ? $('<span></span>').text(outputDocumentInformation.pdf.defaultPathRemainingPath) : null)
						.append($('<a></a>').attr({ 'href': outputDocumentInformation.pdf.defaultPathExistingFolderId ? '/filepro/document/' + outputDocumentInformation.pdf.defaultPathExistingFolderId + '?tab=security' : '/filepro/document/ensureexists?path=' + encodeURIComponent(outputDocumentInformation.pdf.defaultPath), 'target': '_blank', 'class': 'undecorated' })
							.append($('<span></span>').addClass(baseCssClass + '-permission-label label label-' + (outputDocumentInformation.pdf.defaultPathIsPublic ? 'success' : 'danger'))
								.append($('<span></span>').addClass('cw-icon-folder-' + (outputDocumentInformation.pdf.defaultPathIsPublic ? 'permit' : 'forbid')))
								.append($('<span></span>').text(outputDocumentInformation.pdf.defaultPathIsPublic ? localization.labelPublic : localization.labelPrivate))));
					defaultPdfFolder.find('[title]').tooltip();

					var pdfOutputDocumentList = $(document.getElementById(pdfOutputDocumentsClientId)).empty();
					pdfOutputDocuments.forEach(function (outputDocument) {
						var extension = outputDocument.extension.replace('.', '');
						var isPublic = outputDocument.isPublic;

						pdfOutputDocumentList
							.append($('<li></li>').addClass(baseCssClass + '-path')
								.append($('<span></span>', { 'class': CivicWeb.Common.getFileIconClass(extension), 'title': extension.toUpperCase() }))
								.append($('<a></a>').attr({ 'href': '/filepro/documents/' + outputDocument.id, 'target': '_blank' }).text(outputDocument.name))
								.append($('<a></a>').attr({ 'href': '/filepro/document/' + outputDocument.id + '?tab=security', 'target': '_blank', 'class': 'undecorated' })
									.append($('<span></span>').addClass(baseCssClass + '-permission-label label label-' + (isPublic ? 'success' : 'danger'))
										.append($('<span></span>').addClass('cw-icon-folder-' + (isPublic ? 'permit' : 'forbid')))
										.append($('<span></span>').text(isPublic ? localization.labelPublic : localization.labelPrivate)))));
					});
					pdfOutputDocumentList.find('[title]').tooltip();
				}

				CivicWeb.Common.Notification.hide(updateNotificationClientId);

				popupElement.removeClass('hidden').css({ 'visibility': '' }).data('kendoWindow').open();

				if (newPopup) {
					popupElement.data('kendoWindow').center();
				}
			}
			else {
				//Show loading throbber
				$('body')
					.append($('<div></div>').attr({ 'id': loadingThrobberOverlayClientId, 'class': 'overlay-all' })
						.append($('<div></div>').addClass('overlay-content')
							.append($('<span></span>').attr({ 'class': 'overlay-throbber' })
								.append(CivicWeb.Common.Button.getThrobber(loadingThrobberOverlayClientId + '-throbber')))));
			}
		}
	};

	//Methods
	control.load = function (args) {
		localization = args.localization;
		onAfterUpdate = args.afterUpdate;

		isLoaded = true;
	};

	control.show = function (args) {
		if (isLoaded) {
			itemId = args.itemId;
			closed = args.closed;
			description = args.description;
			onAfterUpdate = 'undefined' !== typeof args.afterUpdate ? args.afterUpdate : onAfterUpdate;

			if (itemId > 0) {
				getOutputDocumentInformation().then(loadPopUp);
			}
		}
		else {
			console.log('Output Document Update control not loaded.');
		}
	};
})(window.CivicWeb.Common.OutputDocumentUpdate = window.CivicWeb.Common.OutputDocumentUpdate || {}, jQuery);
;
window.CivicWeb = window.CivicWeb || {};
window.CivicWeb.Common = window.CivicWeb.Common || {};

(function (library, $)
{
	//Methods
	library.create = function (page, pages, navigateMethod, generateLinksForNavigation, localization)
	{
		page = Math.min(Math.max(page, 1), pages);

		var pager = null;
		if (pages > 1)
		{
			var startPage = Math.max(1, page - 5);
			var endPage = Math.min(startPage + 9, pages);
			startPage = Math.max(1, endPage - 9);

			var list;

			pager = $('<div></div>').addClass('pager-container')
				.append(list = $('<ol></ol>').addClass('pagination'));

			if (page >= 2)
			{
				list
					.append($('<li></li>')
						.append($('<a></a>').attr({ 'href': generateLinksForNavigation ? navigateMethod(1) : '#', 'role': 'navigation', 'data-page': 1 }).text(localization.linkFirst)));
			}
			if (page > 2)
			{
				list
					.append($('<li></li>')
						.append($('<a></a>').attr({ 'href': generateLinksForNavigation ? navigateMethod(page - 1) : '#', 'role': 'navigation', 'data-page': page - 1 }).text(localization.linkPrevious)));
			}
			for (var count = startPage; count <= endPage; count++)
			{
				var listItem;

				list
					.append(listItem = $('<li></li>'));

				if (count !== page)
				{
					listItem
						.append($('<a></a>').attr({ 'href': generateLinksForNavigation ? navigateMethod(count) : '#', 'role': 'navigation', 'data-page': count }).text(count));
				}
				else
				{
					listItem.addClass('active')
						.append($('<span></span>').addClass('background-color').text(count));
				}
			}
			if (page < pages - 1)
			{
				list
					.append($('<li></li>')
						.append($('<a></a>').attr({ 'href': generateLinksForNavigation ? navigateMethod(page + 1) : '#', 'role': 'navigation', 'data-page': page + 1 }).text(localization.linkNext)));
			}
			if (page <= pages - 1)
			{
				list
					.append($('<li></li>')
						.append($('<a></a>').attr({ 'href': generateLinksForNavigation ? navigateMethod(pages) : '#', 'role': 'navigation', 'data-page': pages }).text(localization.linkLast)));
			}

			if (!generateLinksForNavigation)
			{
				pager.find('a').on('click', navigateMethod);
			}
		}

		return pager;
	};
})(window.CivicWeb.Common.Pager = window.CivicWeb.Common.Pager || {}, jQuery);
;
window.CivicWeb = window.CivicWeb || {};
window.CivicWeb.Common = window.CivicWeb.Common || {};

(function (library, $) {
	//Properties
	var instances = [];

	//Classes
	// ReSharper disable once InconsistentNaming
	var Control = function (id, args) {
		var clientId = id;
		var notificationClientId = clientId + '-password-strength-notification';
		var okayClientId = clientId + '-password-strength-okay';
		var warningClientId = clientId + '-password-strength-warning';
		var warningLengthClientId = clientId + '-password-strength-warning-length';
		var warningComplexityClientId = clientId + '-password-strength-warning-complexity';
		var warningContainsPiiClientId = clientId + '-password-strength-warning-contains-pii';
		var warningCommonClientId = clientId + '-password-strength-warning-common';

		var passwordControl = args ? args.passwordControl : null;
		var getUserId = args.getUserId;
		var getFirstName = args.getFirstName;
		var getLastName = args.getLastName;
		var getUserName = args.getUserName;
		var getEmailAddress = args.getEmailAddress;

		var controlExists = false;
		var notification;

		//Event Handlers
		var passwordControlChange = function () {
			validatePassword();
		};

		//Methods
		this.getId = function () {
			return clientId;
		};

		var getPasswordData = function (data) {
			data = data || {};

			return {
				password: data.password || (passwordControl ? passwordControl.val() : null),
				userId: data.userId || (typeof getUserId === 'function' ? getUserId() : undefined),
				firstName: data.firstName || (typeof getFirstName === 'function' ? getFirstName() : undefined),
				lastName: data.lastName || (typeof getLastName === 'function' ? getLastName() : undefined),
				userName: data.userName || (typeof getUserName === 'function' ? getUserName() : undefined),
				emailAddress: data.emailAddress || (typeof getEmailAddress === 'function' ? getEmailAddress() : undefined),
			}
		};

		var checkPasswordInternal = this.checkPassword = function (data) {
			var result = $.Deferred();

			data = getPasswordData(data);
			if (controlExists && 'string' === typeof data.password && data.password.length > 0) {
				$.ajax({
					url: '/api/user/passwordstrength/validate',
					contentType: 'application/json',
					dataType: 'json',
					async: true,
					cache: false,
					type: 'POST',
					data: JSON.stringify(data)
				}).done(function (data) {
					$(document.getElementById(okayClientId)).toggleClass('hidden', !data.valid);
					$(document.getElementById(warningClientId)).toggleClass('hidden', data.valid);
					$(document.getElementById(warningLengthClientId)).toggleClass('hidden', !data.failedCriteria.includes(window.CivicWeb.Common.PasswordStrength.passwordCriteria.length));
					$(document.getElementById(warningComplexityClientId)).toggleClass('hidden', !data.failedCriteria.includes(window.CivicWeb.Common.PasswordStrength.passwordCriteria.complexity));
					$(document.getElementById(warningContainsPiiClientId)).toggleClass('hidden', !data.failedCriteria.includes(window.CivicWeb.Common.PasswordStrength.passwordCriteria.containsPii));
					$(document.getElementById(warningCommonClientId)).toggleClass('hidden', !data.failedCriteria.includes(window.CivicWeb.Common.PasswordStrength.passwordCriteria.common));

					CivicWeb.Common.Notification.show(notification, CivicWeb.Common.Notification.types[data.valid ? 'success' : 'failure'], null, true, false);

					return result.resolve(data.valid);
				});
			}
			else {
				result.resolve(true);

				CivicWeb.Common.Notification.hide(notification);
			}

			return result;
		};

		//Method
		var load = function (password) {
			var strengthControl = $('[data-for="' + clientId + '"]');
			if (strengthControl.length > 0) {
				notification = CivicWeb.Common.Notification.hide(notificationClientId);

				controlExists = true;

				if (password) {
					checkPasswordInternal({ password: password });
				}

				if (passwordControl) {
					passwordControl = CivicWeb.Common.getJqueryObject(passwordControl).off('change keydown keyup', passwordControlChange).on('change keydown keyup', passwordControlChange);
					validatePassword();
				}
			}
			else {
				//If password strength is not enabled, don't try to check this control
				passwordControl = null;
			}
		};

		var validatePassword = function () {
			return checkPasswordInternal();
		};

		load(args ? args.password : null);
	};

	//Methods
	library.create = function (id, args) {
		//Remove existing control
		var existingIndex = instances.findIndex(function (element) {
			return element.getId() === id;
		});
		if (existingIndex >= 0) {
			instances.splice(existingIndex, 1);
		}

		var control = new Control(id, args);
		instances.push(control);

		return control;
	};

	library.find = function (id) {
		return instances.find(function (element) {
			return element.getId() === id;
		});
	};

	library.passwordCriteria = {
		length: 1,
		complexity: 2,
		containsPii: 3,
		common: 4,
	};
})(window.CivicWeb.Common.PasswordStrength = window.CivicWeb.Common.PasswordStrength || {}, jQuery);
;
var CivicWeb = CivicWeb || {};
CivicWeb.Common = CivicWeb.Common || {};

//Create classes
CivicWeb.Common.PathToken = function (args)
{
	//Properties
	var localization = {
		trackerNameText: args.localization.trackerNameText,
		meetingTypeText: args.localization.meetingTypeText,
		meetingNameText: args.localization.meetingNameText,
		yearText: args.localization.yearText,
		monthText: args.localization.monthText,
		itemNumberText: args.localization.itemNumberText,
		descriptionText: args.localization.descriptionText,
		closeText: args.localization.closeText
	};

	var cursorStartPosition = null;
	var cursorEndPosition = null;
	var tokenPopup = null;

	//Event Handlers
	var addTokenButtonClick = function (e)
	{
		var button = $(e.target).closest('button');
		var textBox = $(document.getElementById(button.attr('data-for')));

		cursorStartPosition = document.getElementById(button.attr('data-for')).selectionStart;
		cursorEndPosition = document.getElementById(button.attr('data-for')).selectionEnd;

		createTokenPopup(button, textBox);

		e.stopPropagation();
		e.preventDefault();
	};

	var appendTokenButtonClick = function (e)
	{
		var textBox = $(document.getElementById(tokenPopup.attr('data-for')));

		if (cursorStartPosition && cursorEndPosition)
		{
			var textLeft = textBox.val().substring(0, cursorStartPosition);
			var textRight = textBox.val().substring(cursorEndPosition, textBox.val().length);

			//Remove {} if only the token word was selected
			textLeft = textLeft.charAt(textLeft.length - 1) === '{' ? textLeft.slice(0, -1) : textLeft;
			textRight = textRight.charAt(0) === '}' ? textRight.slice(1) : textRight;

			//Add \\ if they are missing
			textLeft = textLeft.charAt(textLeft.length - 1) !== '\\' ? textLeft + '\\' : textLeft;
			textRight = textRight.charAt(0).length > 0 && textRight.charAt(0) !== '\\' ? '\\' + textRight : textRight;

			textBox.val(textLeft + $(e.target).closest('button').attr('data-token') + textRight);
			document.getElementById(tokenPopup.attr('data-for')).selectionStart = document.getElementById(tokenPopup.attr('data-for')).selectionEnd = cursorStartPosition = cursorEndPosition = (cursorEndPosition + $(e.target).closest('button').attr('data-token').length + 1);
		}
		else
		{
			textBox.val((textBox.val().charAt(textBox.val().length - 1) !== '\\' ? textBox.val() + '\\' : textBox.val()) + $(e.target).closest('button').attr('data-token'));
		}

		textBox.change();

		e.preventDefault();
	};

	var tokenPopupExternalClick = function ()
	{
		if (tokenPopup)
		{
			tokenPopup.addClass('hidden');
		}
	};

	var tokenPopupInternalClick = function (e)
	{
		e.stopPropagation();
	};

	//Methods
	var createTokenPopup = function (button, textBox)
	{
		if (!tokenPopup)
		{
			$('div[data-type="path-token-popup"]').remove();
			$('body').off('click', tokenPopupExternalClick).on('click', tokenPopupExternalClick)
				.append(tokenPopup = $('<div></div>').attr({ 'class': 'path-token-popup', 'data-type': 'path-token-popup' }).css({ 'position': 'absolute' }).off('click', tokenPopupInternalClick).on('click', tokenPopupInternalClick)
					.append($('<div></div>')
						.append($('<em></em>').attr({ 'class': 'icon-remove', 'title': localization.closeText }).off('click').on('click', tokenPopupExternalClick)))
					.append($('<div></div>')
						.append($('<button></button>').css({ 'text-align': 'left' }).attr({ 'data-token': '{Description}' }).text(localization.descriptionText).off('click').on('click', appendTokenButtonClick)))
					.append($('<div></div>')
						.append($('<button></button>').css({ 'text-align': 'left' }).attr({ 'data-token': '{ItemNumber}' }).text(localization.itemNumberText).off('click').on('click', appendTokenButtonClick)))
					.append($('<div></div>')
						.append($('<button></button>').css({ 'text-align': 'left' }).attr({ 'data-token': '{MeetingName}' }).text(localization.meetingNameText).off('click').on('click', appendTokenButtonClick)))
					.append($('<div></div>')
						.append($('<button></button>').css({ 'text-align': 'left' }).attr({ 'data-token': '{MeetingType}' }).text(localization.meetingTypeText).off('click').on('click', appendTokenButtonClick)))
					.append($('<div></div>')
						.append($('<button></button>').css({ 'text-align': 'left' }).attr({ 'data-token': '{Month}' }).text(localization.monthText).off('click').on('click', appendTokenButtonClick)))
					.append($('<div></div>')
						.append($('<button></button>').css({ 'text-align': 'left' }).attr({ 'data-token': '{Tracker}' }).text(localization.trackerNameText).off('click').on('click', appendTokenButtonClick)))
					.append($('<div></div>')
						.append($('<button></button>').css({ 'text-align': 'left' }).attr({ 'data-token': '{Year}' }).text(localization.yearText).off('click').on('click', appendTokenButtonClick))));
		}

		//Show or hide tracker name
		var trackerName = tokenPopup.find('button[data-token="{Tracker}"]').parent('div');
		var meetingTypeName = tokenPopup.find('button[data-token="{MeetingType}"]').parent('div');
		var meetingName = tokenPopup.find('button[data-token="{MeetingName}"]').parent('div');
		var itemNumber = tokenPopup.find('button[data-token="{ItemNumber}"]').parent('div');
		var itemDescription = tokenPopup.find('button[data-token="{Description}"]').parent('div');
		if (button.attr('data-path-type') !== 'publishing' && button.attr('data-path-type') !== 'meeting-type-publishing' && button.attr('data-path-type') !== 'attachment')
		{
			trackerName.removeClass('hidden');
		}
		else
		{
			trackerName.addClass('hidden');
		}

		if (button.attr('data-path-type') !== 'meeting-type-publishing' && button.attr('data-path-type') !== 'attachment')
		{
			meetingTypeName.addClass('hidden');
			meetingName.addClass('hidden');
		}
		else
		{
			if (button.attr('data-path-type') === 'meeting-type-publishing' || button.attr('data-path-type') === 'attachment')
			{
				meetingTypeName.removeClass('hidden');
				meetingName.removeClass('hidden');
			}
			else
			{
				meetingTypeName.addClass('hidden');
				meetingName.addClass('hidden');
			}
		}

		if (button.attr('data-path-type') !== 'publishing' && button.attr('data-path-type') !== 'meeting-type-publishing')
		{
			itemNumber.removeClass('hidden');
			itemDescription.removeClass('hidden');
		}
		else
		{
			itemNumber.addClass('hidden');
			itemDescription.addClass('hidden');
		}

		var buttonOffset = button.offset();
		var popupWidth = tokenPopup.outerWidth();
		tokenPopup.removeClass('hidden').attr({ 'data-for': textBox.attr('id') }).css({ 'top': (buttonOffset.top + button.outerHeight()).toString() + 'px' }).css((buttonOffset.left + popupWidth >= ($(window).width() - 10)) ? { 'right': '1em' } : { 'left': buttonOffset.left.toString() + 'px' });
	};

	(function ()
	{
		$('button[data-type="path-tokens"][data-for]').off('click').on('click', addTokenButtonClick);
	})();
};

//Objects
CivicWeb.Common.PathTokens = {
	//Properties
	instance: null,

	createInstance: function (args)
	{
		if (this.instance)
		{
			delete this.instance;
		}
		this.instance = new CivicWeb.Common.PathToken(args);
	},

	//Events
	events: {
	}
};
;
window.CivicWeb = window.CivicWeb || {};
window.CivicWeb.Common = window.CivicWeb.Common || {};

(function (control, $)
{
	//Variables
	var baseClientId = 'permission-contact-administrator';
	var windowClientId = baseClientId + '-window';
	var administrativeUsersClientId = baseClientId + '-administrative-users';
	var subjectClientId = baseClientId + '-subject';
	var bodyClientId = baseClientId + '-body';
	var sendButtonClientId = baseClientId + '-send';
	var cancelButtonClientId = baseClientId + '-cancel';
	var sendNotificationClientId = baseClientId + '-send-notification';

	var baseCssClass = 'permissions-contact-administator';

	var userFullNamePlaceholder = '[Selected Admin - Full Name]';

	var localization = null;
	var kendoEditorLocalization = null;
	var userData = null;

	var isPermissions = true;
	var documentId = 0;
	var path = '';

	var controlWindow = null;

	//Events
	var subjectKeyPress = function (e)
	{
		e.stopPropagation();
	};

	var sendClick = function (e)
	{
		var button = $(document.getElementById(sendButtonClientId));
		var existingButtonText = CivicWeb.Common.Button.update(button, localization.buttonSending, true, true);
		var sendNotification = CivicWeb.Common.Notification.hide(sendNotificationClientId);

		if (validate(button))
		{
			var data = {};
			data.notificationData = buildContactObject();
			data.userData = userData;

			$.ajax({
				url: '/api/notification/send/multiple',
				contentType: 'application/json', dataType: 'json', async: true, cache: false, type: 'POST', data: JSON.stringify(data),
				success: function (response)
				{
					if (response.Result)
					{
						CivicWeb.Common.Notification.show(sendNotification, CivicWeb.Common.Notification.types.success, localization.notificationSendSucceeded, true);

						setTimeout(function ()
						{
							closeWindow();
						}, 5000);
					}
					else
					{
						CivicWeb.Common.Notification.show(sendNotification, CivicWeb.Common.Notification.types.failure, localization.notificationSendFailed);
					}

					CivicWeb.Common.Button.update(button, existingButtonText, false, false);
				},
				error: function ()
				{
					CivicWeb.Common.Notification.show(sendNotification, CivicWeb.Common.Notification.types.error, localization.notificationSendErrored);
					CivicWeb.Common.Button.update(button, existingButtonText, false, false);
				}
			});
		}
		else
		{
			CivicWeb.Common.Button.update(button, existingButtonText, false, false);
		}

		e.preventDefault();
	};

	var cancelClick = function (e)
	{
		closeWindow();

		e.preventDefault();
	};

	//Methods
	control.load = function (options)
	{
		options = options || {};
		localization = options.localization || {};
		kendoEditorLocalization = options.kendoEditorLocalization || {};
		isPermissions = options.isPermissions;
		documentId = CivicWeb.Common.toNumber(options.documentId);
		userData = options.userData || {};
		path = options.path || '';
		if (controlWindow)
		{
			controlWindow.data('kendoWindow').destroy();
			controlWindow.remove();
			controlWindow = null;
		}

		loadWindow();
	};

	//Functions
	var loadWindow = function ()
	{
		if (CivicWeb.Common.loadKendoUi(loadWindow))
		{
			if (!controlWindow)
			{
				controlWindow = $('<div></div>').attr({ 'id': windowClientId, 'class': baseCssClass + ' hidden' })
					.append($('<div></div>')
						.append($('<table></table>').attr({ 'class': baseCssClass + '-form data-form' })
							.append($('<tbody></tbody>')
								.append($('<tr></tr>')
									.append($('<td></td>').attr({ 'class': baseCssClass + '-administrative-users' })
										.append($('<label></label>').attr({ 'for': administrativeUsersClientId }).text(localization.formFieldLabelAdministrativeUsers))
										.append($('<div></div>').attr({ 'id': administrativeUsersClientId })))
									.append($('<td></td>').attr({ 'class': baseCssClass + '-contact-form' })
										.append($('<table></table>').attr({ 'class': 'data-form' })
											.append($('<tbody></tbody>')
												.append($('<tr></tr>')
													.append($('<td></td>')
														.append($('<label></label>').attr({ 'for': subjectClientId }).text(localization.formFieldLabelSubject)))
													.append($('<td></td>')
														.append($('<input />').attr({ 'id': subjectClientId, 'type': 'textbox', 'required': 'required' }))))
												.append($('<tr></tr>')
													.append($('<td></td>').attr({ 'colspan': 2 })
														.append($('<textarea></textarea>').attr({ 'id': bodyClientId, 'required': 'required' }))))))))))
						.append($('<div></div>').attr({ 'class': 'button-row' })
							.append($('<button></button>').attr({ 'id': sendButtonClientId, 'class': 'button' }).text(localization.buttonSend).on('click', sendClick))
							.append($('<button></button>').attr({ 'id': cancelButtonClientId, 'class': 'button' }).text(localization.buttonCancel).on('click', cancelClick)))
						.append(CivicWeb.Common.Notification.create(sendNotificationClientId, CivicWeb.Common.Notification.types.warning, '', true, false)));
				$('body').append(controlWindow);

				$(document.getElementById(bodyClientId)).kendoEditor({
					tools: CivicWeb.Common.Forms.editorTools,
					stylesheets: ['/css/kendo/editor/document?t=' + new Date().getTime(), '/settings/defaultfont'],
					messages: {
						fontNameInherit: kendoEditorLocalization.defaultFont,
						fontSizeInherit: kendoEditorLocalization.defaultFontSize
					}
				});

				controlWindow.kendoWindow({
					width: '800px',
					height: '500px',
					modal: true,
					visible: false,
					title: localization.titleContactAdministrator
				});
			}

			$.ajax({
				url: isPermissions ?
					'/api/users/itemcontrol/' + documentId.toString() :
					'/api/users/useradministrate',
				contentType: 'application/json', dataType: 'json', async: true, cache: false, type: 'GET',
				success: function (result)
				{
					var administrativeUsers = $(document.getElementById(administrativeUsersClientId)).empty();
					for (var index = 0; index < result.length; index++)
					{
						var user = result[index];

						administrativeUsers
							.append($('<div></div>')
								.append($('<input />').attr({ 'id': administrativeUsersClientId + '-' + user.Id.toString(), 'type': 'checkbox' }).val(user.Id.toString()))
								.append($('<label></label>').attr({ 'for': administrativeUsersClientId + '-' + user.Id.toString() }).text(user.Name)));
					}

					$(document.getElementById(subjectClientId)).off('keyup keydown').on('keyup keydown', subjectKeyPress).val(localization.defaultPermissionsContactAdministratorSubject);

					$(document.getElementById(bodyClientId)).data('kendoEditor').value(localization.defaultPermissionsContactAdministratorBody.replace(/\{0\}/g, documentId.toString()).replace(/\{1\}/g, path).replace(/\{Email\}/g, userData ? (userData.emailAddress || '') : ''));

					controlWindow.removeClass('hidden').css({ 'visibility': '' }).data('kendoWindow').center().open();
				}
			});
		}
	};

	var closeWindow = function ()
	{
		if (controlWindow)
		{
			controlWindow.addClass('hidden').data('kendoWindow').close();
		}
	};

	var validate = function (button)
	{
		var existingButtonText = CivicWeb.Common.Button.update(button, localization.buttonValidating, null, null);

		var sendNotification = CivicWeb.Common.Notification.hide(sendNotificationClientId);

		var valid = true;
		var focusSet = false;

		//Validate
		var errors = new Array();
		if ($(document.getElementById(administrativeUsersClientId)).find('input[type="checkbox"]:checked').length === 0)
		{
			valid = false;

			errors.push(localization.warningMessageSelectAnAdministrativeUser);
		}

		var input = $(document.getElementById(subjectClientId)).removeClass('invalid');
		if (input.val().length === 0)
		{
			valid = false;
			input.addClass('invalid');
			focusSet = true;
			input.focus();

			errors.push(localization.warningMessageSubjectRequired);
		}

		input = $(document.getElementById(bodyClientId)).data('kendoEditor');

		if (input.value().length === 0)
		{
			valid = false;
			if (!focusSet)
			{
				input.focus();
			}

			errors.push(localization.warningMessageBodyRequired);
		}

		if (errors.length > 0)
		{
			CivicWeb.Common.Notification.show(sendNotification, CivicWeb.Common.Notification.types.warning, errors);
		}

		CivicWeb.Common.Button.update(button, existingButtonText, null, null);

		return valid;
	};

	var buildContactObject = function ()
	{
		var subject = $(document.getElementById(subjectClientId)).val() || '';
		var body = $(document.getElementById(bodyClientId)).data('kendoEditor').value() || '';

		var contactData = [];
		$(document.getElementById(administrativeUsersClientId)).find('input[type="checkbox"]:checked').each(function ()
		{
			var checkBox = $(this);
			var userId = CivicWeb.Common.toNumber(parseInt(checkBox.val()));
			if (userId > 0)
			{
				var fullName = checkBox.closest('div').find('label').text() || '';

				contactData.push(
				{
					itemId: documentId,
					users: [userId],
					subject: subject.replace(userFullNamePlaceholder, fullName),
					body: body.replace(userFullNamePlaceholder, fullName)
				});
			}
		});

		return contactData;
	};
})(window.CivicWeb.Common.ContactAdministrator = window.CivicWeb.Common.ContactAdministrator || {}, jQuery);
;
// Declare namespaces
var CivicWeb = CivicWeb || {};
CivicWeb.Common = CivicWeb.Common || {};

//Create classes
CivicWeb.Common.Permission = function (args)
{
	//Properties
	var schemas = args.schemas;
	var enabled = args.enabled;
	var simplePermissions = args.simplePermissions;
	var canMakeAvailableToAll = args.canMakeAvailableToAll;
	var showPublicOnlyItemsForAllUsers = args.showPublicOnlyItemsForAllUsers;
	var change = args.change;

	var localization = args.localization;

	var images = {
		expandImageClass: args.images.expandImageClass,
		collapseImageClass: args.images.collapseImageClass
	};

	var expansionState = {
		collapsed: 'collapsed',
		expanded: 'expanded'
	};

	//Events
	var availableToAllCheckBoxClick = function (e)
	{
		var checkbox = $(e.target).closest('input');
		var schema = schemas[checkbox.attr('data-type')];
		if (checkbox.prop('checked'))
		{
			var selectedCount = $(document.getElementById(schema.controlIds.selected)).find('li:not(.list-item-selected)').filter(':not(.sub)').length;
			if (selectedCount === 0 || (canMakeAvailableToAll && confirm(localization.makingPubliclyAvailableWarningMessageText)))
			{
				$(document.getElementById(schema.controlIds.selected)).find('li:not(.sub)').addClass('list-item-selected');

				removeSelectedItem(schema, true);
			}
			else
			{
				checkbox.prop('checked', false);
			}
		}

		enable(schema, enabled, !checkbox.prop('checked'));
	};

	var availableClick = function (e)
	{
		var available = $(e.target).closest('ol');
		var schema = schemas[available.attr('data-type')];

		var availableToAllCheckboxContainer = $(document.getElementById(schema.controlIds.availableToAll)).closest('span').addClass('highlight');

		setTimeout(function () { availableToAllCheckboxContainer.removeClass('highlight'); }, 2000);
	};

	var listItemClick = function (e)
	{
		if (e.shiftKey)
		{
			//Deselect text
			if (window.getSelection)
			{
				if (window.getSelection().empty) // Chrome
				{
					window.getSelection().empty();
				}
				else if (window.getSelection().removeAllRanges) // Firefox
				{
					window.getSelection().removeAllRanges();
				}
			}
			else if (document.selection) //IE
			{
				document.selection.empty();
			}
		}

		var listItem = $(e.target).closest('li');
		var list = listItem.closest('ol');
		var parentType = listItem.attr('data-parent-type');
		var schema = schemas[parentType];
		var usingAvailableList = list.attr('id') === schema.controlIds.available;
		var lastSelected = usingAvailableList ? schema.lastSelection.available : schema.lastSelection.selected;
		var itemSelected = listItem.hasClass('list-item-selected');

		if (!e.ctrlKey && !e.shiftKey)
		{
			list.find('li').removeClass('list-item-selected');
		}

		if (!itemSelected)
		{
			listItem.addClass('list-item-selected');
		}
		else
		{
			listItem.removeClass('list-item-selected');
		}

		if (lastSelected && e.shiftKey)
		{
			var found = false;
			list.find('li:not(.sub)').each(function ()
			{
				var item = $(this);
				var final = false;
				if ((item.attr('data-id') === listItem.attr('data-id')) || (item.attr('data-id') === lastSelected.attr('data-id')))
				{
					//Found shift-select endpoint
					found = !found;
					final = !found;
				}
				if (found || final)
				{
					item.addClass('list-item-selected');

					if (final)
					{
						return false;
					}
				}

				return true;
			});
		}

		//Remember last selection
		if (usingAvailableList)
		{
			schema.lastSelection.available = listItem;
		}
		else
		{
			schema.lastSelection.selected = listItem;
		}

		e.preventDefault();
	};

	var listItemDragHelper = function ()
	{
		var item = $(this);
		var clone = item.clone().attr({ 'data-helper': true.toString() }).addClass('list-item-selected drag-helper');
		clone.find('span.expand-collapse').remove();
		clone.find('div.permission-set').remove();

		var multiple = item.closest('ol').find('li.list-item-selected:not(.sub)').length > 1;
		if (multiple)
		{
			var text = clone.find('span');
			text.text(text.text() + ', ...');
		}

		return clone;
	};

	var listItemDragStart = function ()
	{
		$(this).closest('li').addClass('list-item-selected');
	};

	var listItemDrop = function (e, ui)
	{
		var dropTarget = $(this);
		var type = dropTarget.attr('data-type');
		var schema = schemas[type];
		var droppedOnSelected = dropTarget.attr('id') === schema.controlIds.selected;
		var remainingSelectedCount = $(document.getElementById(schema.controlIds.selected)).find('li:not(.list-item-selected)').filter(':not(.sub)').length;
		var valid = ui.draggable.closest('ol').attr('id') !== dropTarget.attr('id') && (droppedOnSelected || remainingSelectedCount > 0 || (canMakeAvailableToAll && confirm(localization.makingPubliclyAvailableWarningMessageText)));
		if (valid)
		{
			ui.draggable.remove();
			if (droppedOnSelected)
			{
				addSelectedItem(schema);
			}
			else
			{
				removeSelectedItem(schema, true);
			}
		}
	};

	var expandListItemClick = function (e)
	{
		var button = $(e.target);
		var expanding = button.attr('data-state') === expansionState.collapsed;
		var listItem = button.closest('li');
		var parentType = listItem.attr('data-parent-type');
		var type = listItem.attr('data-type');
		var item = findItem(schemas[parentType], listItem.attr('data-id'));
		var rootId = (listItem.attr('data-path') || '').split('-').find(value => Boolean(value)); // Get the first value in the path
		var rootItem = findItem(schemas[parentType], rootId) || item;
		var showPermissions = listItem.parent().attr('id') === schemas[parentType].controlIds.selected && !simplePermissions;
		if (item)
		{
			var path = listItem.attr('data-path');
			listItem.parent('ol').find('li[data-path^="' + path + '-"]').remove();

			if (expanding)
			{
				var depth = path.split('-').length;
				var subItemsExist = false;
				for (var index = schemas[parentType][type].subCollections.length - 1; index >= 0; index--)
				{
					var subCollection = schemas[parentType][type].subCollections[index];
					var subSchema = schemas[parentType][subCollection.type];
					var subCollectionItems = item[subCollection.collection];
					//Load sub-items
					for (var index2 = subCollectionItems.length - 1; index2 >= 0; index2--)
					{
						var subItem = subCollectionItems[index2];
						if (subItem)
						{
							var subListItem = $('<li></li>').attr({ 'class': 'sub', 'data-id': subSchema.prefix + subItem[subSchema.id].toString(), 'data-path': path + '-' + subSchema.prefix + subItem[subSchema.id].toString(), 'data-depth': depth.toString(), 'data-parent-type': parentType, 'data-type': subSchema.type })
								.append($('<div></div>')
									.append($('<span></span>').attr({ 'class': subSchema.imageUrl, 'title': subSchema.toolTip }))
									.append(subSchema.subCollections != null && subSchema.subCollections.length > 0 && subCollection.recurse
										? $('<span></span>').attr({ 'class': 'expand-collapse ' + images.expandImageClass, 'title': subSchema.toolTip, 'data-state': expansionState.collapsed }).on('click', expandListItemClick)
										: null)
									.append($('<span></span>').text(subItem[subSchema.name])));
							if (showPermissions)
							{
								var assignedSubItemPermissions = findItem(schemas[parentType], subSchema.prefix + subItem[subSchema.id].toString()).permissions[parentType];
								subListItem.append(createPermissionsControls(assignedSubItemPermissions[schemas[parentType].selected] ? assignedSubItemPermissions : rootItem.permissions[parentType], false, !!subItem.isPublic));
							}
							listItem.after(subListItem);

							subItemsExist = true;
						}
					}
				}
				if (!subItemsExist)
				{
					var subListItem = $('<li></li>').attr({ 'class': 'sub', 'data-id': '0', 'data-path': path + '-' + schemas[parentType][type].prefix + '0', 'data-depth': depth.toString() })
						.append($('<div></div>')
							.append($('<span></span>').text(schemas[parentType][type].noSubItemsExistText)));
					listItem.after(subListItem);
				}
			}
		}

		button.attr({ 'class': 'expand-collapse ' + (expanding ? images.collapseImageClass : images.expandImageClass), 'data-state': expanding ? expansionState.expanded : expansionState.collapsed });

		resize();

		e.stopPropagation();
	};

	var addItemsButtonClick = function (e)
	{
		addSelectedItem(schemas[$(e.target).closest('button').attr('data-type')]);

		e.preventDefault();
	};

	var removeItemsButtonClick = function (e)
	{
		removeSelectedItem(schemas[$(e.target).closest('button').attr('data-type')]);

		e.preventDefault();
	};

	var permissionClick = function (e)
	{
		var checkBox = $(e.target);
		if (!checkBox.prop('disabled'))
		{
			var listItem = checkBox.closest('li');
			var parentType = listItem.attr('data-parent-type');
			var type = listItem.attr('data-type');
			var id = listItem.attr('data-id');
			var item = findItem(schemas[parentType], id);
			var publicSelected = item && !!item.isPublic;

			if (!checkBox.prop('checked') || (!publicSelected || confirm(localization.makingPubliclyAvailableWarningMessageText)))
			{
				var container = checkBox.closest('.permission-set');
				if (checkBox.attr('data-permission-type') === 'view' && !checkBox.prop('checked'))
				{
					//Remove update permission
					container.find('input[data-permission-type="update"]').prop('checked', false);
				}
				else if (checkBox.attr('data-permission-type') === 'update' && checkBox.prop('checked'))
				{
					//Give view permission
					container.find('input[data-permission-type="view"]').prop('checked', true);
				}

				//Record updated permissions
				var permissions = item.permissions[parentType];
				permissions.viewAllowed = listItem.find('input[data-permission-type="view"]').prop('checked');
				permissions.updateAllowed = listItem.find('input[data-permission-type="update"]').prop('checked');
				permissions.deleteAllowed = listItem.find('input[data-permission-type="delete"]').prop('checked');

				var subItems = listItem.parent().find('li.sub[data-path^="' + id + '-"],li.sub[data-path$="-' + id + '"]');
				//Remove explicity added users
				if (type === 'groups')
				{
					listItem.parent().find('li[data-type="users"]:not(.sub)').each(function ()
					{
						var userId = $(this).attr('data-id');
						subItems = subItems.not('[data-path$="-' + userId + '"]');
					});
				}

				subItems.find('input[data-permission-type="view"]').prop('checked', permissions.viewAllowed);
				subItems.find('input[data-permission-type="update"]').prop('checked', permissions.updateAllowed);
				subItems.find('input[data-permission-type="delete"]').prop('checked', permissions.deleteAllowed);
			}
			else
			{
				checkBox.prop('checked', false);
			}

			schemas[parentType].changed = true;

			onChange();
		}

		e.stopPropagation();
	};

	var applyToChildrenClick = function ()
	{
		onChange();
	};

	//Methods
	this.isType = function (types)
	{
		var found = false;
		CivicWeb.Common.forceArray(types).forEach(function (type)
		{
			found = found || 'undefined' !== typeof schemas[type];
		});

		return found;
	};

	var resize = function ()
	{
		$('.permissions').each(function ()
		{
			var permissionLists = $('.permissions').find($('.list-box ol'));
			var outerParent = permissionLists.closest('.pane');
			var permissionListsBackgrounds = $('.permissions').find('.permission-selected-background,.permission-available-background');

			if (outerParent && outerParent.height())
			{
				var outerParentHeight = (outerParent.height() * .65) - 10;
				permissionLists.css({ 'height': outerParentHeight });
				if (outerParentHeight < 256)
				{
					permissionListsBackgrounds.css({ 'font-size': outerParentHeight });
				}
			}

			var control = $(this);

			if (!simplePermissions)
			{
				//Set header labels width
				//var permissionHeaders = control.find('.permissions-labels span').css({ 'width': '' });
				//var width = Math.max.apply(Math, permissionHeaders.map(function () { return $(this).width(); }).get());
				//permissionHeaders.width(width);

				//Set top header label width
				//var outerWidth = permissionHeaders.outerWidth();
				//control.find('.permissions-label').width(outerWidth * 3 + 4);

				////Set column widths
				var permissionContainers = control.find('.permission-set span');
				//permissionContainers.width(outerWidth);

				//Middle-align checkboxes
				var height = permissionContainers.height();
				var permissionCheckBoxes = permissionContainers.find('input');
				permissionCheckBoxes.css({ 'margin-top': ((height - permissionCheckBoxes.outerHeight()) / 2).toString() + 'px' });
			}
		});

		//Ensure that these are the same width - only test the visible ones
		var topLabel = $('.permissions-label:visible');
		var bottomLabels = $('.permissions-labels:visible');
		var topLabelWidth = topLabel.outerWidth();
		var bottomLabelsWidth = bottomLabels.outerWidth();
		if (topLabelWidth > 0 && bottomLabelsWidth > 0 && topLabelWidth !== bottomLabelsWidth)
		{
			topLabel.width(topLabel.width() + bottomLabelsWidth - topLabelWidth);
		}
	};

	this.externalResize = function ()
	{
		resize();
	};

	this.hide = function (type)
	{
		var schema = schemas[type];
		if (schema)
		{
			$(document.getElementById(schema.controlIds.availableToAll)).closest('.permissions').addClass('hidden');
		}
	};

	this.show = function (type)
	{
		var schema = schemas[type];
		if (schema)
		{
			$(document.getElementById(schema.controlIds.availableToAll)).closest('.permissions').removeClass('hidden');
			resize();
		}
	};

	var loadLists = function ()
	{
		if (schemas)
		{
			for (var type in schemas)
			{
				if (schemas.hasOwnProperty(type))
				{
					var schema = schemas[type];
					initializeItems(schema.groups, type);
					initializeItems(schema.users, type);
					loadList(schema, enabled);

					schema.changed = false;
				}
			}
		}

		resize();
	};

	var initializeItems = function (schema, type)
	{
		if (schema)
		{
			var items = schema.items;
			var selectedPermissions = schema.selectedPermissions;
			if (items)
			{
				//Items
				for (var index = 0; index < items.length; index++)
				{
					var item = items[index];
					item.permissions = item.permissions || {};
					item.permissions[type] = item.permissions[type] || {}; //Sub-collections
					if (schema.subCollections)
					{
						for (var index2 = 0; index2 < schema.subCollections.length; index2++)
						{
							var subCollection = schema.subCollections[index2];
							var subSchema = schemas[type][subCollection.type];

							//Sub-collection ids
							if (item[subCollection.type])
							{
								for (var index3 = 0; index3 < item[subCollection.type].length; index3++)
								{
									var id = item[subCollection.type][index3];
									if (typeof id == 'number')
									{
										//Sub-collection items
										var found = false;
										for (var index4 = 0; index4 < subSchema.items.length; index4++)
										{
											var subItem = subSchema.items[index4];
											if (subItem && id === subItem[subSchema.id])
											{
												item[subCollection.type][index3] = subItem;
												found = true;
												break;
											}
										}

										if (!found)
										{
											item[subCollection.type][index3] = null;
										}
									}
								}

								//Sort the sub-collection
								if (subSchema.sort && typeof subSchema.sort == 'function')
								{
									item[subCollection.type].sort(subSchema.sort);
								}
							}
						}
					}

					//Set selections
					if (selectedPermissions)
					{
						item.permissions[type][schema.selected] = false;
						for (var index2 = 0; index2 < selectedPermissions.length; index2++)
						{
							var permissionSet = selectedPermissions[index2];
							if (item[schema.id] === permissionSet.securityId)
							{
								item.permissions[type][schema.selected] = true;
								item.permissions[type].viewAllowed = permissionSet.viewAllowed;
								item.permissions[type].updateAllowed = permissionSet.updateAllowed;
								item.permissions[type].deleteAllowed = permissionSet.deleteAllowed;
								break;
							}
						}
					}
				}

				if (schema.sort && typeof schema.sort == 'function')
				{
					items.sort(schema.sort);
				}
			}
		}
	};

	var loadList = function (schema, enabled)
	{
		var availableToAll = $(document.getElementById(schema.controlIds.availableToAll)).off('click').on('click', availableToAllCheckBoxClick);
		if (!canMakeAvailableToAll && !availableToAll.prop('checked'))
		{
			availableToAll.closest('.permissions-available-to-all').addClass('hidden');
		}

		var available = $(document.getElementById(schema.controlIds.available)).attr({ 'data-type': schema.type }).empty().droppable({ drop: listItemDrop });
		var selected = $(document.getElementById(schema.controlIds.selected)).attr({ 'data-type': schema.type }).empty().droppable({ drop: listItemDrop });
		loadListItems(schema, 'groups', enabled, available, selected);
		loadListItems(schema, 'users', enabled, available, selected);
		$(document.getElementById(schema.controlIds.applyToChildren)).off('click').on('click', applyToChildrenClick);

		enable(schema, enabled, !availableToAll.prop('checked'), available, selected);
	};

	var enable = function (schema, enabled, editable, available, selected)
	{
		var availableToAll = $(document.getElementById(schema.controlIds.availableToAll));
		var applyToChildren = $(document.getElementById(schema.controlIds.applyToChildren));
		var disableAvailableToAll = $(document.getElementById(schema.controlIds.disableAvailableToAll));
		var available = available || $(document.getElementById(schema.controlIds.available));
		var selected = selected || $(document.getElementById(schema.controlIds.selected));
		var addButton = $(document.getElementById(schema.controlIds.addButton)).off('click');
		var removeButton = $(document.getElementById(schema.controlIds.removeButton)).off('click');
		if (enabled)
		{
			availableToAll.removeAttr('disabled');
			applyToChildren.removeAttr('disabled');
			disableAvailableToAll.removeAttr('disabled');

			addButton.parent().removeClass('hidden');

			available.off('click');
			if (editable)
			{
				addButton.removeAttr('disabled').addClass('background-color-hover').off('click').on('click', addItemsButtonClick);
				removeButton.removeAttr('disabled').addClass('background-color-hover').off('click').on('click', removeItemsButtonClick);
				available.find('li:not(.sub)').removeClass('ui-state-disabled').off('click').on('click', listItemClick).draggable('option', 'disabled', false);
				selected.find('li:not(.sub)').removeClass('ui-state-disabled').off('click').on('click', listItemClick).draggable('option', 'disabled', false);
			}
			else
			{
				available.on('click', availableClick);
				addButton.attr({ 'disabled': 'disabled' }).removeClass('background-color-hover');
				removeButton.attr({ 'disabled': 'disabled' }).removeClass('background-color-hover');
				available.find('li:not(.sub)').addClass('ui-state-disabled').off('click').draggable('option', 'disabled', true);
				selected.find('li:not(.sub)').addClass('ui-state-disabled').off('click').draggable('option', 'disabled', true);
			}
		}
		else
		{
			availableToAll.attr({ 'disabled': 'disabled' });
			applyToChildren.attr({ 'disabled': 'disabled' });
			disableAvailableToAll.attr({ 'disabled': 'disabled' });

			addButton.attr({ 'disabled': 'disabled' });
			removeButton.attr({ 'disabled': 'disabled' });
			addButton.parent().addClass('hidden');

			available.find('li:not(.sub)').addClass('ui-state-disabled');
			selected.find('li:not(.sub)').addClass('ui-state-disabled');
		}
	};

	var loadListItems = function (schema, type, enabled, available, selected)
	{
		for (var index = 0; index < schema[type].items.length; index++)
		{
			if (!schema[type].filter || schema[type].filter(schema[type].items[index]))
			{
				if (!schema[type].items[index].permissions[schema.type][schema.selected] && !schema[type].items[index]['inactive'] && !schema[type].items[index][schema[type].deleted])
				{
					if ((canMakeAvailableToAll || !schema[type].items[index].isPublic) && !schema[type].items[index].everyone)
					{
						available.append(createListItem(schema[type].items[index], schema, schema[type], enabled));
					}
				}
				else if (schema[type].items[index].permissions[schema.type][schema.selected])
				{
					selected.append(createListItem(schema[type].items[index], schema, schema[type], enabled, !simplePermissions));
				}
			}
		}
	};

	var createListItem = function (item, parentSchema, schema, enabled, showPermissions)
	{
		var listItem = $('<li></li>').attr({ 'data-id': schema.prefix + item[schema.id].toString(), 'data-path': schema.prefix + item[schema.id].toString(), 'data-parent-type': parentSchema.type, 'data-type': schema.type }).on('click', enabled ? listItemClick : function () { })
			.append($('<div></div>').attr({ 'class': 'permission-list-name' })
				.append($('<span></span>').attr({ 'class': (item.isPublic ? schema.userPublicImageUrl : schema.imageUrl), 'title': schema.toolTip }))
				.append(schema.subCollections != null && schema.subCollections.length > 0
					? $('<span></span>').attr({ 'class': 'expand-collapse ' + images.expandImageClass, 'title': schema.toolTip, 'data-state': expansionState.collapsed }).on('click', expandListItemClick)
					: null)
				.append($('<span></span>').text((showPublicOnlyItemsForAllUsers && item.isPublic ? localization.publicUserAndAllInternalUsersText : item[schema.name]) + (item[schema.deleted] ? ' (' + localization.deletedText + ')' : '')))).draggable({ revert: 'invalid', scroll: false, helper: listItemDragHelper, start: listItemDragStart, disabled: !enabled });
		if (showPermissions)
		{
			listItem.append(createPermissionsControls(item.permissions[parentSchema.type], enabled, !!item.isPublic));
		}

		return listItem;
	};

	var createPermissionsControls = function (permission, enabled, isPublic)
	{
		var viewPermissions = $('<span></span>').attr({ 'class': 'permission-view' })
			.append($('<input />').attr({ 'type': 'checkbox', 'data-permission-type': 'view' }).prop('checked', permission.viewAllowed).on('click', permissionClick));
		var updatePermissions = $('<span></span>').attr({ 'class': 'permission-update' })
			.append($('<input />').attr({ 'type': 'checkbox', 'data-permission-type': 'update' }).prop('checked', permission.updateAllowed).on('click', permissionClick));
		var deletePermissions = $('<span></span>').attr({ 'class': 'permission-delete' })
			.append($('<input />').attr({ 'type': 'checkbox', 'data-permission-type': 'delete' }).prop('checked', permission.deleteAllowed).on('click', permissionClick));

		if (!enabled)
		{
			viewPermissions.find('input').attr({ 'data-inactive': true.toString() }).prop('disabled', true);
		}
		if (isPublic || !enabled)
		{
			updatePermissions.find('input').attr({ 'data-inactive': true.toString() }).prop('disabled', true);
			deletePermissions.find('input').attr({ 'data-inactive': true.toString() }).prop('disabled', true);
		}
		if (isPublic)
		{
			updatePermissions.find('input').css({ 'display': 'none' });
			deletePermissions.find('input').css({ 'display': 'none' });
		}

		return $('<div></div>').attr({ 'class': 'permission-set' })
			.append(viewPermissions)
			.append(updatePermissions)
			.append(deletePermissions);
	};

	var findItem = function (schema, id, useFilter, additionalResults)
	{
		return findSubSchemaItem(schema.groups, schema.type, id, useFilter, additionalResults) || findSubSchemaItem(schema.users, schema.type, id, useFilter, additionalResults);
	};

	var findSubSchemaItem = function (schema, parentType, id, useFilter, additionalResults)
	{
		var found = null;
		for (var index = 0; index < schema.items.length; index++)
		{
			var current = schema.items[index];
			if ((schema.prefix + current[schema.id].toString()) === id)
			{
				found = current;
				break;
			}
			if (additionalResults && (!useFilter || (schema.filter && schema.filter(current)) || !schema.filter))
			{
				additionalResults.previousItem = current;
				if (current.permissions[parentType][schema.selected])
				{
					additionalResults.previousSelectedSchema = schema;
					additionalResults.previousSelectedItem = current;
				}
				else if (!current[schema.deleted])
				{
					additionalResults.previousNonSelectedSchema = schema;
					additionalResults.previousNonSelectedItem = current;
				}
			}
		}

		return found;
	};

	var addSelectedItem = function (schema)
	{
		//Add selections to the selected list
		var available = $(document.getElementById(schema.controlIds.available));
		var selected = $(document.getElementById(schema.controlIds.selected));
		available.find('.list-item-selected:not(.sub)').each(function ()
		{
			var listItem = $(this);
			var id = listItem.attr('data-id');
			var type = listItem.attr('data-type');
			available.find('li.sub[data-path^="' + id + '-"]').remove();
			var additionalResults = {};
			var item = findItem(schema, id, true, additionalResults);
			if (item)
			{
				item.permissions[schema.type][schema.selected] = true;
				item.permissions[schema.type].viewAllowed = true;
				if (additionalResults.previousSelectedItem)
				{
					var previousSchema = additionalResults.previousSelectedSchema;
					selected.find('li[data-id="' + previousSchema.prefix + additionalResults.previousSelectedItem[previousSchema.id].toString() + '"]:not(.sub)').after(createListItem(item, schema, schema[type], true, !simplePermissions));
				}
				else
				{
					selected.prepend(createListItem(item, schema, schema[type], true, !simplePermissions));
				}
			}
		}).remove();

		schema.changed = true;

		onChange();

		resize();
	};

	var removeSelectedItem = function (schema, bypassAvailableToAllConfirmation)
	{
		//Remove selections from the selected list
		var available = $(document.getElementById(schema.controlIds.available));
		var selected = $(document.getElementById(schema.controlIds.selected));
		var remainingSelectedCount = selected.find('li:not(.list-item-selected)').filter(':not(.sub)').length;
		if (remainingSelectedCount > 0 || bypassAvailableToAllConfirmation || (canMakeAvailableToAll && confirm(localization.makingPubliclyAvailableWarningMessageText)))
		{
			selected.find('.list-item-selected:not(.sub)').each(function ()
			{
				var listItem = $(this);
				var id = listItem.attr('data-id');
				var type = listItem.attr('data-type');
				selected.find('li.sub[data-path^="' + id + '-"]').remove();
				var additionalResults = {};
				var item = findItem(schema, id, true, additionalResults);
				if (item)
				{
					item.permissions[schema.type][schema.selected] = false;
					if ((canMakeAvailableToAll || !item.isPublic) && !item.everyone)
					{
						if (additionalResults.previousNonSelectedItem)
						{
							var previousSchema = additionalResults.previousNonSelectedSchema;
							available.find('li[data-id="' + previousSchema.prefix + additionalResults.previousNonSelectedItem[previousSchema.id].toString() + '"]:not(.sub)').after(createListItem(item, schema, schema[type], true));
						}
						else
						{
							available.prepend(createListItem(item, schema, schema[type], true));
						}
					}
				}
			}).remove();

			if (remainingSelectedCount === 0)
			{
				$(document.getElementById(schema.controlIds.availableToAll)).prop('checked', true);
				enable(schema, enabled, false);
			}
		}

		schema.changed = true;

		onChange();
	};

	this.setPermissions = function (type, permissions)
	{
		var schema = schemas[type];
		if (schema)
		{
			schema.groups.selectedPermissions = permissions.groups;
			schema.users.selectedPermissions = permissions.users;

			$(document.getElementById(schema.controlIds.availableToAll)).prop('checked', permissions.groups.length === 0 && permissions.users.length === 0);
			initializeItems(schema.groups, type);
			initializeItems(schema.users, type);
			loadList(schema, true);

			schema.changed = false;
		}
	};

	this.buildPermissionsObject = function (type)
	{
		var permissions = {
			groups: [],
			users: [],
			applyToChildren: false,
			disableAvailableToAll: false
		};

		var schema = schemas[type];
		if (schema)
		{
			for (var index = 0; index < schema.groups.items.length; index++)
			{
				var id = schema.groups.items[index][schema.groups.id];
				var groupPermissions = schema.groups.items[index].permissions[type];
				if (groupPermissions[schema.selected])
				{
					permissions.groups.push({ id: id, viewAllowed: !!groupPermissions.viewAllowed, updateAllowed: !!groupPermissions.updateAllowed, deleteAllowed: !!groupPermissions.deleteAllowed });
				}
			}

			for (var index = 0; index < schema.users.items.length; index++)
			{
				var id = schema.users.items[index][schema.users.id];
				var userPermissions = schema.users.items[index].permissions[type];
				if (userPermissions[schema.selected])
				{
					permissions.users.push({ id: id, viewAllowed: !!userPermissions.viewAllowed, updateAllowed: !!userPermissions.updateAllowed, deleteAllowed: !!userPermissions.deleteAllowed });
				}
			}

			permissions.applyToChildren = !!$(document.getElementById(schema.controlIds.applyToChildren)).prop('checked');
			permissions.disableAvailableToAll = !!$(document.getElementById(schema.controlIds.disableAvailableToAll)).prop('checked');

			if (permissions.groups.length === 0 && permissions.users.length === 0)
			{
				$(document.getElementById(schema.controlIds.availableToAll)).prop('checked', false).click();
			}
		}

		return permissions;
	};

	this.validate = function (type, errors)
	{
		var valid = true;

		errors = errors || [];

		var schema = schemas[type];
		if (schema)
		{
			var disableAvailableToAll = !!$(document.getElementById(schema.controlIds.disableAvailableToAll)).prop('checked');
			if (disableAvailableToAll)
			{
				var selectedGroups = schema.groups.items.filter(function (group)
				{
					return group.permissions[type][schema.selected];
				});
				var selectedUsers = schema.users.items.filter(function (user)
				{
					return user.permissions[type][schema.selected];
				});
				var publicUser = selectedUsers.find(function (user)
				{
					return user.isPublic && (simplePermissions || (!simplePermissions && user.permissions[type].viewAllowed));
				});
				
				if (selectedGroups.length === 0 && selectedUsers.length === 0 || publicUser != null)
				{
					valid = false;

					errors.push(localization.warningMessageCannotDisablePublicAccessWhilePublicHasAccess);
				}
			}
		}
		
		return valid;
	};

	this.isLockedOut = function (type)
	{
		var currentPermissions = this.buildPermissionsObject(type);
		var permissions = '';
		for (var index = 0; index < currentPermissions.groups.length; index++)
		{
			permissions += 'G' + currentPermissions.groups[index].id.toString() + (currentPermissions.groups[index].viewAllowed ? '1' : '0') + (currentPermissions.groups[index].updateAllowed ? '1' : '0') + (currentPermissions.groups[index].deleteAllowed ? '1' : '0') + ',';
		}
		for (var index = 0; index < currentPermissions.users.length; index++)
		{
			permissions += 'U' + currentPermissions.users[index].id.toString() + (currentPermissions.users[index].viewAllowed ? '1' : '0') + (currentPermissions.users[index].updateAllowed ? '1' : '0') + (currentPermissions.users[index].deleteAllowed ? '1' : '0') + ',';
		}

		var promise = $.Deferred();
		$.ajax({
			url: '/Global/WebServices/SecurityWebService.asmx/IsLockedOut',
			contentType: 'application/json',
			dataType: 'json',
			async: true,
			type: 'POST',
			data: JSON.stringify({
				serializedPermissions: permissions,
				type: type
			})
		}).done(function (data)
		{
			promise.resolve(data.d);
		}).fail(function ()
		{
			promise.reject();
		});

		return promise;
	};

	this.isChanged = function (type)
	{
		return type && schemas[type] && schemas[type].changed;
	};

	this.setChanged = function (type, value)
	{
		if (type && schemas[type])
		{
			schemas[type].changed = !!value;

			if (schemas[type].changed)
			{
				onChange();
			}
		};
	};

	var onChange = function ()
	{
		if ('function' === typeof change)
		{
			change();
		}
	};

	(function ()
	{
		loadLists();
	})();
};

//Objects
CivicWeb.Common.Permissions = {
	//Properties
	instances: new Array(),

	//Methods
	getInstance: function (types)
	{
		return this.instances.find(function (instance)
		{
			return instance.isType(types);
		});
	},

	getIndex: function (types)
	{
		var index = 0;
		for (; index < this.instances.length; index++)
		{
			if (this.instances[index].isType(types))
			{
				break;
			}
		}

		return index >= this.instances.length ? -1 : index;
	},

	getTypes: function (schemas)
	{
		var types = [];
		if (schemas)
		{
			for (var key in schemas)
			{
				if (schemas.hasOwnProperty(key))
				{
					types.push(key);
				}
			}
		}
	},

	createInstance: function (args)
	{
		var instance = this.getInstance(this.getTypes(args.schemas));
		var index = this.getIndex(this.getTypes(args.schemas));
		if (instance)
		{
			delete instance;
		}
		if (index < 0)
		{
			index = this.instances.length;
		}
		this.instances[index] = new CivicWeb.Common.Permission(args);
	},

	setPermissions: function (type, permissions)
	{
		return this.getInstance(type).setPermissions(type, permissions);
	},

	hide: function (type)
	{
		return this.getInstance(type).hide(type);
	},

	show: function (type)
	{
		return this.getInstance(type).show(type);
	},

	resize: function ()
	{
		this.instances.forEach(function (instance)
		{
			instance.externalResize();
		});
	},

	buildPermissionsObject: function (type)
	{
		return this.getInstance(type).buildPermissionsObject(type);
	},

	validate: function (type, errors)
	{
		return this.getInstance(type).validate(type, errors);
	},

	isLockedOut: function (type)
	{
		return this.getInstance(type).isLockedOut(type);
	},

	isChanged: function (type)
	{
		return this.getInstance(type).isChanged(type);
	},

	setChanged: function (type, value)
	{
		return this.getInstance(type).setChanged(type, value);
	}
};
;
window.CivicWeb = window.CivicWeb || {};
window.CivicWeb.Common = window.CivicWeb.Common || {};

(function (control, $)
{
	//Variables
	var baseClientId = 'permission-role-setup';
	var windowClientId = baseClientId + '-window';
	var tableClientId = baseClientId + '-table';
	var usersClientId = baseClientId + '-users';
	var rolesClientId = baseClientId + '-roles';
	var roleClientId = baseClientId + '-role-';
	var saveButtonClientId = baseClientId + '-save';
	var cancelButtonClientId = baseClientId + '-cancel';
	var saveNotificationClientId = baseClientId + '-save-notification';

	var baseCssClass = 'permissions-role-setup';

	var localization = null;
	var users = null;
	var roles = null;
	var parentContainer = null;
	var useButtons = true;
	var afterSaveHandler = null;

	var controlWindow = null;

	var images = {
		userImageUrl: 'cw-icon-user-lg',
		userPublicImageUrl: 'cw-icon-user-public-lg',
		expandImageClass: 'cw-icon-node-open',
		collapseImageClass: 'cw-icon-node-close'
	};

	var schemaTypes = {
		users: 'users'
	};

	var schemas = null;
	var changed = false;

	//Events
	var listItemClick = function (e)
	{
		if (e.shiftKey)
		{
			//Deselect text
			if (window.getSelection)
			{
				if (window.getSelection().empty) // Chrome					
				{
					window.getSelection().empty();
				}
				else if (window.getSelection().removeAllRanges) // Firefox
				{
					window.getSelection().removeAllRanges();
				}
			}
			else if (document.selection) //IE
			{
				document.selection.empty();
			}
		}

		var listItem = $(e.target).closest('li');
		var list = listItem.closest('ol');
		var type = listItem.attr('data-type');
		var schema = schemas[type];
		var usingAvailableList = list.attr('id') === schema.controlIds.available;
		var lastSelected = usingAvailableList ? schema.lastSelection.available : schema.lastSelection.selected[list.attr('id')];
		var itemSelected = listItem.hasClass('list-item-selected');

		if (!e.ctrlKey && !e.shiftKey)
		{
			list.find('li').removeClass('list-item-selected');
		}

		if (!itemSelected)
		{
			listItem.addClass('list-item-selected');
		}
		else
		{
			listItem.removeClass('list-item-selected');
		}

		if (lastSelected && e.shiftKey)
		{
			var found = false;
			list.find('li:not(.sub)').each(function ()
			{
				var item = $(this);
				var final = false;
				if ((item.attr('data-id') === listItem.attr('data-id')) || (item.attr('data-id') === lastSelected.attr('data-id')))
				{
					//Found shift-select endpoint
					found = !found;
					final = !found;
				}
				if (found || final)
				{
					item.addClass('list-item-selected');

					if (final)
					{
						return false;
					}
				}

				return true;
			});
		}

		//Remember last selection
		if (usingAvailableList)
		{
			schema.lastSelection.available = listItem;
		}
		else
		{
			schema.lastSelection.selected[list.attr('id')] = listItem;
		}

		e.preventDefault();
	};

	var listItemDragHelper = function ()
	{
		var item = $(this);
		var clone = item.clone().attr({ 'data-helper': true.toString() }).addClass('list-item-selected drag-helper');
		clone.find('span.expand-collapse').remove();

		var multiple = item.closest('ol').find('li.list-item-selected:not(.sub)').length > 1;
		if (multiple)
		{
			var text = clone.find('span');
			text.text(text.text() + ', ...');
		}

		return clone;
	};

	var listItemDragStart = function ()
	{
		$(this).closest('li').addClass('list-item-selected');
	};

	var listItemDrop = function (e, ui)
	{
		var dropTarget = $(this).closest('ol');

		var schema = schemas.users;
		var droppedOnSelected = dropTarget.attr('id') !== schema.controlIds.available;
		var dropSource = ui.draggable.closest('ol');
		if (dropTarget.attr('id') !== dropSource.attr('id'))
		{
			if (droppedOnSelected)
			{
				addSelectedItem(schema, dropTarget, dropSource);
			}
			else
			{
				removeSelectedItem(schema, ui.draggable.closest('ol'));
			}
		}
	};

	var addClick = function (e)
	{
		addSelectedItem(schemas.users, $(document.getElementById(roleClientId + $(e.target).closest('button').attr('data-id'))));
	};

	var removeClick = function (e)
	{
		removeSelectedItem(schemas.users, $(document.getElementById(roleClientId + $(e.target).closest('button').attr('data-id'))));
	};

	var saveClick = function (e)
	{
		control.save($(document.getElementById(saveButtonClientId)));

		e.preventDefault();
	};

	var cancelClick = function (e)
	{
		closeWindow();

		control.disableSetup();

		e.preventDefault();
	};

	var showDepartmentsChanged = function (e)
	{
		var checked = $(this).prop('checked');
		if (checked)
		{
			$('span.department-names').removeClass('hidden');
		}
		else
		{
			$('span.department-names').addClass('hidden');
		}

		var permissionSetupUsers = $(document.getElementById(usersClientId));
		var userLiList = permissionSetupUsers.find('li');
		userLiList.sort(sort);
		permissionSetupUsers.empty().append(userLiList);
		permissionSetupUsers.find('li').on('click', listItemClick).draggable({ revert: 'invalid', scroll: false, helper: listItemDragHelper, start: listItemDragStart, disabled: false });

		$.each($('ol[id^=' + roleClientId + ']'), function (j, roleuserol)
		{
			var userLiList = $(roleuserol).find('li');
			userLiList.sort(sort);
			$(roleuserol).empty().append(userLiList);
			$(roleuserol).find('li').on('click', listItemClick).draggable({ revert: 'invalid', scroll: false, helper: listItemDragHelper, start: listItemDragStart, disabled: false });
		});

		function sort(a, b)
		{
			var aId = parseInt($(a).attr('data-id'));
			var bId = parseInt($(b).attr('data-id'));
			var aItem = findItem(schemas.users, aId);
			var bItem = findItem(schemas.users, bId);
			var compA = checked ? aItem.departmentsNames : aItem.name;
			var compB = checked ? bItem.departmentsNames : bItem.name;

			return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
		}
	};

	//Methods
	control.load = function (options, afterSave)
	{
		options = options || {};
		localization = options.localization || {};
		users = null;
		roles = options.roles || [];
		parentContainer = options.parentContainer != null && typeof options.parentContainer != 'undefined' ? CivicWeb.Common.getJqueryObject(options.parentContainer) : null;
		useButtons = options.useButtons != null && typeof options.useButtons != 'undefined' ? options.useButtons : true;
		afterSaveHandler = afterSave != null && typeof afterSave === 'function' ? afterSave : null;

		schemas = {
			users: {
				type: schemaTypes.users,
				id: 'id',
				name: 'name',
				deleted: 'deleted',
				selected: 'selected',
				prefix: 'U',
				subCollections: [],
				imageUrl: images.userImageUrl,
				userPublicImageUrl: images.userPublicImageUrl,
				toolTip: localization.userToolTipText,
				noSubItemsExistText: '',
				sort: function (a, b)
				{
					var nameA = a ? a.name.toLowerCase() : '';
					var nameB = b ? b.name.toLowerCase() : '';
					var publicA = a ? a.isPublic : false;
					var publicB = b ? b.isPublic : false;

					return (publicA === publicB && nameA < nameB) || (publicA && !publicB) ? -1 : ((publicA === publicB && nameA > nameB) || (!publicA && publicB) ? 1 : 0);
				},
				filter: function (item)
				{
					return item && !item.isPublic && !item.administrator && !item.systemAdministrator && !item.inactive && !item.deleted;
				},
				controlIds: {
					available: usersClientId
				},
				lastSelection: {
					available: null,
					selected: {
					}
				}
			}
		};

		if (controlWindow)
		{
			controlWindow.data('kendoWindow').destroy();
			controlWindow.remove();
			controlWindow = null;
		}

		loadWindow();
	};

	control.save = function (button)
	{
		var existingButtonText = CivicWeb.Common.Button.update(button, localization.buttonSaving, true, true);
		var saveNotification = CivicWeb.Common.Notification.hide(saveNotificationClientId);

		if (validate(button))
		{
			var data = buildRolesObject();

			$.ajax({
				url: '/api/roles/users',
				contentType: 'application/json', dataType: 'json', async: true, cache: false, type: 'POST', data: JSON.stringify(data),
				success: function (response)
				{
					if (response)
					{
						CivicWeb.Common.Notification.show(saveNotification, CivicWeb.Common.Notification.types.success, localization.notificationSavingSucceeded, true);

						setTimeout(function ()
						{
							closeWindow();

							if (afterSaveHandler)
							{
								afterSaveHandler();
							}

							control.disableSetup();
						}, 3000);
					}
					else
					{
						CivicWeb.Common.Notification.show(saveNotification, CivicWeb.Common.Notification.types.failure, localization.notificationSavingFailed);
					}

					CivicWeb.Common.Button.update(button, existingButtonText, false, false);
				},
				error: function ()
				{
					CivicWeb.Common.Notification.show(saveNotification, CivicWeb.Common.Notification.types.error, localization.notificationSavingErrored);
					CivicWeb.Common.Button.update(button, existingButtonText, false, false);
				}
			});
		}
		else
		{
			CivicWeb.Common.Button.update(button, existingButtonText, false, false);
		}
	};

	control.disableSetup = function (href)
	{
		if (window.location.href.indexOf('setup=true') >= 0)
		{
			window.location.href = CivicWeb.Common.removeUrlParameter(href || window.location.href, 'setup');
		}
	};

	control.isChanged = function ()
	{
		return changed;
	};

	//Functions
	var loadWindow = function ()
	{
		if (CivicWeb.Common.loadKendoUi(loadWindow))
		{
			if (!controlWindow)
			{
				controlWindow = $('<div></div>').attr({ 'id': windowClientId, 'class': baseCssClass + ' hidden' })
					.append($('<div></div>')
						.append($('<table></table>').attr({ 'id': tableClientId, 'class': baseCssClass + '-form data-form' })
							.append($('<tbody></tbody>')
								.append($('<tr></tr>')
									.append($('<td></td>').attr({ 'class': baseCssClass + '-available' })
										.append($('<div></div>').attr({ 'class': baseCssClass + '-available-users' })
											.append($('<label></label>').attr({ 'for': usersClientId }).css({ 'font-weight': 'bold' }).text(localization.formFieldLabelAvailableUsers))
											.append($('<div></div>').attr({ 'class': 'list-box list-box-available' })
												.append($('<div></div>')
													.append($('<input/>', { 'id': 'show-departments', 'type': 'checkbox' }).off('change').on('change', showDepartmentsChanged))
													.append($('<label/>', { 'for': 'show-departments' }).text('Show/sort departments')))
												.append($('<ol></ol>').attr({ 'id': usersClientId }).droppable({ drop: listItemDrop })))))
									.append($('<td></td>').attr({ 'class': baseCssClass + '-selected' })
										.append($('<table></table>').attr({ 'id': rolesClientId, 'class': 'data-form' })
											.append($('<tbody></tbody>')))))))
						.append(useButtons ?
							$('<div></div>').attr({ 'class': 'button-row' })
								.append(CivicWeb.Common.Button.create(saveButtonClientId, localization.buttonSave, localization.buttonSave).on('click', saveClick))
								.append(CivicWeb.Common.Button.create(cancelButtonClientId, localization.buttonCancel, localization.buttonCancel).on('click', cancelClick)) :
								null)
						.append(CivicWeb.Common.Notification.create(saveNotificationClientId, CivicWeb.Common.Notification.types.warning, '', true, false)));
				$('body').append(controlWindow);

				if (parentContainer == null)
				{
					controlWindow.kendoWindow({
						width: '975px',
						height: '640px',
						modal: true,
						visible: false,
						title: localization.titleRoleSetup
					});
				}
				else
				{
					parentContainer.empty()
						.append(controlWindow.removeClass('hidden'));
				}
			}

			$.ajax({
				url: '/api/users',
				contentType: 'application/json', dataType: 'json', async: true, cache: false, type: 'GET',
				success: function (result)
				{
					//Add users
					schemas.users.items = users = result;
					var list = $(document.getElementById(usersClientId)).empty();
					for (var index = 0; index < users.length; index++)
					{
						var user = users[index];
						if (schemas.users.filter(user) && !isUserSelected(user.id))
						{
							list
								.append(createListItem(user, schemas.users, true));
						}
					}

					//Add roles
					var table = $(document.getElementById(rolesClientId));
					table.find('tr').remove();
					for (var index = 0; index < roles.length; index++)
					{
						var buttonCell = $('<td></td>');
						var selectedCell = $('<td></td>');

						table.find('tbody')
							.append($('<tr></tr>')
								.append(buttonCell)
								.append(selectedCell));

						if (index === 0)
						{
							selectedCell
								.append($('<label></label>').css({ 'font-weight': 'bold' }).text(localization.formFieldLabelRoles));
						}

						var role = roles[index];

						buttonCell
							.append($('<div></div>').attr({ 'class': 'list-box list-box-buttons' })
								.append(CivicWeb.Common.Button.create(roleClientId + 'add-' + role.id.toString(), localization.buttonAdd, localization.toolTipAdd, CivicWeb.Common.Button.types.short, { 'data-id': role.id.toString() }).on('click', addClick))
								.append($('<br />'))
								.append($('<br />'))
								.append(CivicWeb.Common.Button.create(roleClientId + 'remove-' + role.id.toString(), localization.buttonRemove, localization.toolTipRemove, CivicWeb.Common.Button.types.short, { 'data-id': role.id.toString() }).on('click', removeClick)));

						var roleList = $('<ol></ol>').attr({ 'id': roleClientId + role.id.toString(), 'data-id': role.id.toString() }).droppable({ drop: listItemDrop });

						selectedCell
							.append($('<fieldset></fieldset>')
								.append($('<legend></legend>').text(role.name))
								.append($('<div></div>').text(role.description))
								.append($('<div></div>').attr({ 'class': 'list-box list-box-selected' })
									.append(roleList)));

						for (var roleUserIndex = 0; roleUserIndex < role.users.length; roleUserIndex++)
						{
							for (var userIndex = 0; userIndex < users.length; userIndex++)
							{
								if (role.users[roleUserIndex] === users[userIndex].id)
								{
									roleList
										.append(createListItem(users[userIndex], schemas.users, true));
								}
							}
						}
					}

					if (parentContainer == null)
					{
						controlWindow.removeClass('hidden').css({ 'visibility': '' }).data('kendoWindow').center().open();
					}

					changed = false;
				}
			});
		}
	};

	var closeWindow = function ()
	{
		if (parentContainer == null && controlWindow)
		{
			controlWindow.addClass('hidden').data('kendoWindow').close();
		}
	};

	var createListItem = function (item, schema, enabled)
	{
		var item = $('<li></li>').attr({ 'data-id': item[schema.id].toString(), 'data-path': schema.prefix + item[schema.id].toString(), 'data-type': schema.type }).on('click', enabled ? listItemClick : function () { })
			.append($('<div></div>')
				.append($('<span><span>').attr({ 'class': schema.imageUrl, 'title': schema.toolTip }))
				.append($('<span></span>').text(item[schema.name] + (item[schema.deleted] ? ' (' + localization.deletedText + ')' : '')))
				.append(schema.prefix === 'F' ? $('<span></span>').attr({ 'class': schema.helpImageUrl + ' function-help', 'data-container': 'body', 'data-original-title': item[schema.name] + (item[schema.deleted] ? ' (' + localization.deletedText + ')' : ''), 'data-content': item[schema.description] }) : null)
				.append(schema.prefix === 'U' && item.departmentsNames && item.departmentsNames.length ? $('<span></span>', { 'class': 'department-names' + ($('#show-departments').prop('checked') ? '' : ' hidden') }).text(' (' + item.departmentsNames + ')') : '')
				).draggable({ revert: 'invalid', scroll: false, helper: listItemDragHelper, start: listItemDragStart, disabled: !enabled });

		return item;
	};

	var addSelectedItem = function (schema, selected)
	{
		//Add selections to the selected list
		var available = $(document.getElementById(schema.controlIds.available));
		var role = findRole(selected.attr('data-id'));
		available.find('.list-item-selected:not(.sub):not(.drag-helper)').each(function ()
		{
			var id = $(this).attr('data-id');
			var additionalResults = {};
			var item = findItem(schema, parseInt(id), true, role.users, additionalResults);
			if (item && addUser(role, CivicWeb.Common.toNumber(id)))
			{
				item.selected = true;
				if (additionalResults.previousSelectedItem)
				{
					selected.find('li[data-id="' + additionalResults.previousSelectedItem[schema.id].toString() + '"]:not(.sub)').after(createListItem(item, schema, true));
				}
				else
				{
					selected.prepend(createListItem(item, schema, true));
				}
			}
		}).remove();
	};

	var removeSelectedItem = function (schema, selected)
	{
		//Remove selections from the selected list
		var available = $(document.getElementById(schema.controlIds.available));
		var role = findRole(selected.attr('data-id'));
		selected.find('.list-item-selected:not(.sub):not(.drag-helper)').each(function ()
		{
			var id = $(this).attr('data-id');
			var additionalResults = {};
			var item = findItem(schema, parseInt(id), true, schema.items.filter(function (item)
			{
				//Fresh filter for each item
				return !item.selected;
			}), additionalResults);
			if (item)
			{
				item.selected = false;
				removeUser(role, CivicWeb.Common.toNumber(id));
				if (additionalResults.previousSelectedItem)
				{
					available.find('li[data-id="' + additionalResults.previousSelectedItem[schema.id].toString() + '"]:not(.sub)').after(createListItem(item, schema, true));
				}
				else
				{
					available.prepend(createListItem(item, schema, true));
				}
			}
		}).remove();
	};

	var findItem = function (schema, id, useFilter, selectedItems, additionalResults)
	{
		var found = null;
		for (var index = 0; index < schema.items.length; index++)
		{
			var current = schema.items[index];
			if (current[schema.id] === id)
			{
				found = current;
				break;
			}
			if (additionalResults && (!useFilter || (schema.filter && schema.filter(current)) || !schema.filter))
			{
				additionalResults.previousItem = current;
				if (containsUser(selectedItems, current[schema.id]))
				{
					additionalResults.previousSelectedItem = current;
				}
				else
				{
					additionalResults.previousNonSelectedItem = current;
				}
			}
		}

		return found;
	};

	var findRole = function (id)
	{
		var role = null;
		if (roles)
		{
			id = CivicWeb.Common.toNumber(id);
			for (var index = 0; index < roles.length; index++)
			{
				if (roles[index].id === id)
				{
					role = roles[index];
				}
			}
		}

		return role;
	};

	var containsUser = function (users, userId)
	{
		var contains = false;
		if (users && userId > 0)
		{
			for (var index = 0; index < users.length; index++)
			{
				var currentUserId = CivicWeb.Common.toNumber(users[index].id || users[index]);
				if (contains = (currentUserId === userId))
				{
					break;
				}
			}
		}

		return contains;
	};

	var isUserSelected = function (userId)
	{
		var selected = false;
		if (roles)
		{
			userId = CivicWeb.Common.toNumber(userId);
			for (var index = 0; index < roles.length; index++)
			{
				if (selected = containsUser(roles[index].users, userId))
				{
					break;
				}
			}
		}

		return selected;
	};

	var addUser = function (role, userId)
	{
		//Remove from other roles
		for (var index = 0; index < roles.length; index++)
		{
			if (roles[index].id !== role.id)
			{
				removeUser(roles[index], userId);
			}
		}

		//Add to selected role
		var added = false;
		if (role && userId > 0)
		{
			if (added = !containsUser(role.users, userId))
			{
				role.users.push(userId);
			}
		}

		changed = changed || added;

		return added;
	};

	var removeUser = function (role, userId)
	{
		if (role && userId > 0)
		{
			for (var index = 0; index < role.users.length; index++)
			{
				if (role.users[index] === userId)
				{
					role.users.splice(index, 1);
					index--;

					changed = true;
				}
			}
		}
	};

	var validate = function (button)
	{
		var existingButtonText = CivicWeb.Common.Button.update(button, localization.buttonValidating, null, null);

		var saveNotification = CivicWeb.Common.Notification.hide(saveNotificationClientId);

		//Validate
		var errors = new Array();

		if (errors.length > 0)
		{
			CivicWeb.Common.Notification.show(saveNotification, CivicWeb.Common.Notification.types.warning, errors);
		}

		CivicWeb.Common.Button.update(button, existingButtonText, null, null);

		return true;
	};

	var buildRolesObject = function ()
	{
		var rolesObject = [];
		for (var index = 0; index < roles.length; index++)
		{
			rolesObject.push({
				id: roles[index].id,
				users: roles[index].users
			});
		}

		return rolesObject;
	};
})(window.CivicWeb.Common.RoleSetup = window.CivicWeb.Common.RoleSetup || {}, jQuery);
;
window.CivicWeb = window.CivicWeb || {};
window.CivicWeb.Common = window.CivicWeb.Common || {};

(function (library, $)
{
	//Properties
	var instances = [];

	//Classes
	// ReSharper disable once InconsistentNaming
	var Control = function (id)
	{
		var clientId = id;
		var progressBarClientId = clientId + '-progress-bar';

		//Event Handlers
		var inputChange = function ()
		{
			displayProgressInternal();
		};

		//Functions
		var displayProgressInternal = function ()
		{
			var input = $(document.getElementById(clientId));
			var percentage;
			if (input.is('input'))
			{
				percentage = input.val();
			}
			else
			{
				percentage = input.text();
			}

			percentage = Math.max(Math.min(CivicWeb.Common.toNumber(percentage), 100), 0);

			$(document.getElementById(progressBarClientId)).attr({ 'aria-valuenow': percentage.toString() }).text(Math.round(percentage).toString() + '%').width(percentage.toString() + '%');
		};

		//Methods
		this.getId = function ()
		{
			return clientId;
		};

		//Functions
		var load = function ()
		{
			var input = $(document.getElementById(clientId));
			if (input.is('input'))
			{
				input.attr({ 'max': 100, 'min': 0, 'class': 'form-progress' }).off('change keyup', inputChange).on('change keyup', inputChange);
			}
			else
			{
				input.addClass('hidden');
			}
			$(document.getElementById(progressBarClientId)).closest('.progress').remove();
			input.closest('.form-field')
				.append($('<div></div>').addClass('progress form-progress')
					.append($('<div></div>').attr({ 'id': progressBarClientId, 'class': 'progress-bar progress-bar-success', 'role': 'progressbar', 'aria-valuenow': '0', 'aria-valuemin': '0', 'aria-valuemax': '100' })));

			displayProgressInternal();
		};

		load();
	};

	//Methods
	library.create = function (id, args)
	{
		var control = library.find(id);
		if (!control)
		{
			control = new Control(id, args);
			instances.push(control);
		}

		return control;
	};

	library.find = function (id)
	{
		return instances.find(function (element)
		{
			return element.getId() === (id || '');
		});
	};
})(window.CivicWeb.Common.ProgressField = window.CivicWeb.Common.ProgressField || {}, jQuery);
;
window.CivicWeb = window.CivicWeb || {};
window.CivicWeb.Common = window.CivicWeb.Common || {};

(function (library, $)
{
	//Properties
	var instances = [];
	var progressHub;

	//Classes
	// ReSharper disable once InconsistentNaming
	var Control = function (id, args)
	{
		var clientId = id || '';
		var progressOverlayClientId = (clientId.length > 0 ? clientId + '-' : '') + 'progress-overlay';
		var progressMessageClientId = (clientId.length > 0 ? clientId + '-' : '') + 'progress-message';
		var progressBarClientId = (clientId.length > 0 ? clientId + '-' : '') + 'progress-bar';

		var progressGuid = args.progressGuid;
		var finishTimeout = args.finishTimeout || 3000;
		var maxTimeout = args.maxTimeout || 10000;

		var hideProgressTimeout;

		//Functions
		var resetProgressBar = function ()
		{
			//Reset the progress bar
			$(document.getElementById(progressOverlayClientId)).addClass('hidden');
			$(document.getElementById(progressMessageClientId)).text('');
			$(document.getElementById(progressBarClientId)).attr({ 'aria-valuenow': '0' }).text('0%').width('0%');
		};

		//Methods
		this.getId = function ()
		{
			return clientId;
		};

		this.displayProgress = function (percentage, message)
		{
			percentage = percentage || 0;

			$(document.getElementById(progressMessageClientId)).text(message || '');
			$(document.getElementById(progressBarClientId)).attr({ 'aria-valuenow': percentage.toString() }).text(Math.round(percentage).toString() + '%').width(percentage.toString() + '%');
			$(document.getElementById(progressOverlayClientId)).removeClass('hidden');

			if (hideProgressTimeout)
			{
				clearTimeout(hideProgressTimeout);
			}

			hideProgressTimeout = setTimeout(resetProgressBar, maxTimeout);

			if (percentage >= 100)
			{
				setTimeout(resetProgressBar, finishTimeout);
			}
		};

		//Functions
		var load = function ()
		{
			resetProgressBar();

			if ($(document.getElementById(progressOverlayClientId)).length > 0 && Function.prototype.bind && !(window.callPhantom || window._phantom))
			{
				library.registerMethods();
				
				CivicWeb.Common.SignalR.start().then(function ()
					{
						progressHub.server.registerProgressGuid(progressGuid);
					});
			}
		};

		load();
	};

	//Methods
	library.create = function (id, args)
	{
		var control = library.find(id);
		if (!control)
		{
			control = new Control(id, args);
			instances.push(control);
		}

		return control;
	};

	library.find = function (id)
	{
		return instances.find(function (element)
		{
			return element.getId() === (id || '');
		});
	};

	library.registerMethods = function ()
	{
		//This needs to be called before CivicWeb.Common.SignalR.start() is called anywhere on the page
		if (!progressHub && Function.prototype.bind && !(window.callPhantom || window._phantom) && $.connection && $.connection.hub)
		{
			progressHub = $.connection.progressHub;
			
			progressHub.client.announceProgress = function (percentage, message)
			{
				var instance = instances.length > 0 ? instances[0] : null;
				if (instance)
				{
					instance.displayProgress(percentage, message);
				}
			};
		}
	};
})(window.CivicWeb.Common.Progress = window.CivicWeb.Common.Progress || {}, jQuery);
;
// Declare namespaces
var CivicWeb = CivicWeb || {};
CivicWeb.Common = CivicWeb.Common || {};

//Create classes
CivicWeb.Common.QuickView = function (args)
{
	var isLoggedIn = args.isLoggedIn;
	var localization = args.localization;
	var purchasedVideo = args.purchasedVideo;
	var openSplitScreen = args.openSplitScreen;
	var currentId = 0;
	var currentContentUrl = '';
	var previousId = 0;
	var nextId = 0;
	var idArray;
	var viewDeleted = false;
	var batchUploadPath = false;
	var searchDocument = false;
	var searchText = '';
	var fromWidget = false;
	var attachmentUrl;
	var isTablet = false;
	var isPhone = false;
	var fileName = '';

	this.getCurrentId = function ()
	{
		return currentId;
	};

	this.loadQuickview = function (id, ids, options)
	{
		options = options || {};
		viewDeleted = !!options.viewDeleted;
		batchUploadPath = !!options.batchUploadPath;
		searchDocument = !!options.searchDocument;
		searchText = options.searchText;
		fromWidget = !!options.fromWidget;
		attachmentUrl = options.attachmentUrl;

		if (id > 0)
		{
			idArray = ids;
			getDocument(id);
		}
		else if (batchUploadPath && id.length > 0)
		{
			idArray = ids;
			getDocument(id);
		}

		$(document).ready(function ()
		{
			$('body').off('keydown', keyPress).on('keydown', keyPress);
		});
	};

	this.closeQuickView = function (e)
	{
		$('.document-quickview').addClass('hidden');

		if ($('.document-quickview-content').find('iframe').contents().find('audio').length > 0)
		{
			var audio = $('.document-quickview-content').find('iframe').contents().find('audio');
			audio[0].pause();
			audio.remove();
		}
		else if ($('.document-quickview-content').find('iframe').contents().find('video').length > 0)
		{
			var video = $('.document-quickview-content').find('iframe').contents().find('video');
			video[0].pause();
			video.remove();
		}
		else if (purchasedVideo && $('.document-quickview-content').find('iframe').contents().find('#videoDiv').length > 0)
		{
			$('.document-quickview-content').find('iframe').contents().find('#videoDiv').remove();
		}
		else if (purchasedVideo && $('.document-quickview-content').find('#parentIframe').contents().find('iframe').contents().find('#videoDiv').length > 0)
		{
			$('.document-quickview-content').find('#parentIframe').contents().find('iframe').contents().find('#videoDiv').remove();
		}

		CivicWeb.Documents.DocumentOperations.Events.changePreviewUrl();
		$('body').off('keydown', keyPress);
		e.preventDefault();
	};

	var previousDocumentKeyDown = function (e) {
		if (e.which == 13 || e.which == 32) {
			previousDocumentClick(e);
		}
	};

	var nextDocumentKeyDown = function (e) {
		if (e.which == 13 || e.which == 32) {
			nextDocumentClick(e);
		}
	};

	var previousDocumentClick = function (e)
	{
		if (previousId > 0 || (batchUploadPath && previousId && previousId.length > 0))
		{
			getDocument(previousId);
		}
		e.preventDefault();
	};

	var nextDocumentClick = function (e)
	{
		if (nextId > 0 || (batchUploadPath && nextId && nextId.length > 0))
		{
			getDocument(nextId);
		}
		e.preventDefault();
	};

	var getDocument = function (id)
	{
		currentId = id;
		var index = $.inArray(id, idArray);
		previousId = idArray[index - 1];
		nextId = idArray[index + 1];

		if (previousId > 0 || (batchUploadPath && previousId && previousId.length > 0))
		{
			$('#previousQuickView').show();
		}
		else
		{
			$('#previousQuickView').hide();
		}

		if (nextId > 0 || (batchUploadPath && nextId && nextId.length > 0))
		{
			$('#nextQuickView').show();
		}
		else
		{
			$('#nextQuickView').hide();
		}

		var contentHeight = isTablet || isPhone ? $(window).height() - 33 : $(window).height() - 30;

		var height = 800;
		var width = 600;
		var contentContainer;
		if ((contentContainer = $('.document-quickview-content').find('img')).length > 0)
		{
			height = contentContainer.height();
			width = contentContainer.width();
		}
		else if ((contentContainer = $('.document-quickview-content').find('iframe')).length > 0)
		{
			height = contentContainer.height();
			width = contentContainer.width();
		}
		else if ((contentContainer = $('.document-quickview-content').find('div')).length > 0)
		{
			height = contentContainer.height();
			width = contentContainer.width();
		}
		$('.document-quickview-content').html('<div style=\'margin: auto; background-color: white; color: black; border: 1px solid black; vertical-align: middle; text-align: center; height:' + ($(window).height() - 38) + 'px; width: 8.5in;\'><div style=\'padding-top: 10em;\'><div style=\'vertical-align: middle;\' class=\'loader\'></div> ' + localization.loadingInProgress + '</div></div>');
		$('.document-quickview').removeClass('hidden');
		//load the document quickview

		var documentQuickView = $('.document-quickview-content');
		if (batchUploadPath)
		{
			//used to store document view history -(could be reduced to true false return as all information is already loaded)
			$.ajax({
				url: '/api/documents/getimportdocument',
				contentType: 'application/json', dataType: 'json', async: true, cache: false, type: 'GET',
				data: { 'documentPath': id }
			}).done(function (result)
			{
				if (result)
				{
					switch (result.FileFormat.toLowerCase())
					{
						case 'pdf':
							documentQuickView.html('<iframe id=\'preview-content\' frameborder=\'0\' scrolling=\'auto\' style=\'border: 0; height:' + (contentHeight - 6) + 'px;\' class=\'parent-iframe quickView-80\' src=\'' + result.ContentUrl + '\' />');
							documentQuickViewClearandClose();
							break;
						case 'bmp':
						case 'gif':
						case 'jpg':
						case 'jpeg':
						case 'png':
						case 'webp':
						case 'svg':
							documentQuickView.html('<iframe id=\'preview-content\' frameborder=\'0\' scrolling=\'auto\' style=\'border: 0; height:' + (contentHeight - 6) + 'px;\' class=\'parent-iframe quickView-80\' src=\'' + result.ContentUrl + '\' />');
							documentQuickViewClearandClose();
							break;
						case 'html':
						case 'htm':
						case 'txt':
						case 'xml':
						case 'docx':
						case 'doc':
						case 'odt':
							documentQuickView.html('<iframe id=\'preview-content\' frameborder=\'0\' scrolling=\'auto\' allowfullscreen=\'1\' style=\'border: 0; height:' + (contentHeight - 6) + 'px;\' class=\'parent-iframe quickView-80\' />');
							documentQuickView.find('iframe').contents().find('body').html(result.ContentUrl);
							documentQuickViewClearandClose();
							break;
						case 'm4a':
						case 'mp3':
							//audio
							result.FileFormat = 'mpeg';
						case 'wav':							
							//audio
							if (result.FileFormat.toLowerCase() === 'mp3') {
								result.FileFormat = 'mpeg';
							}
							else if (result.FileFormat.toLowerCase() === 'm4a') {
								result.FileFormat = 'mp4';
							}
							documentQuickView.html('<audio id=\'preview-content\' style=\'margin-top:35%;\' controls><source src=\'' + result.ContentUrl + '\' type=\'audio/' + result.FileFormat + '\'></audio>');
							documentQuickViewClearandClose();
							break;													
						case 'm4v':												
						case 'wmv':
						case 'ogg':						
						case 'mp4':							
						case 'avi':
						case 'mov':
						case 'mpg':
						case 'webm':
						case 'mpeg':
							//Video
							documentQuickView.html('<video id=\'preview-content\' width=\'600\' height=\'450\' controls><source src=\'' + result.ContentUrl + '\' type=\'video/' + result.FileFormat + '\'></video>');
							documentQuickViewClearandClose();
							break;
						default:
							documentQuickView.html('<img id=\'preview-content\' style=\'background-color: #888;\' alt=\'' + localization.clickToDownLoadDocument + '\' src=\'https://i.civicweb.net/Global/Images/IconFiles512/' + (result.FileFormat.length > 0 ? result.FileFormat + '.png\'' : '_blank.png') + '\' style=\'margin-top: 1em;\'></img><br /><span class=\'document-control-bar-button background-color-hover document-content\' style=\'padding: 1em; width: 348px;\'>' + localization.clickToDownLoadDocument + '</span></div>');
							documentQuickViewClearandClose();
							documentQuickView.children().children().off('click').on('click', downloadDocument).addClass('quickview-downloadDocument').attr('title', 'Download Document');
							break;
					}
					fileName = result.Description;
					$('#OpenFullPdfMenuItem, #DownloadDocumentMenuItem, #EditDetails').hide();
					$('#QuickViewDocumentIcon').html(' <em class=\'icon-file-' + (result.FileFormat.length > 0 ? (result.FileFormat === 'splitscreen' ? 'html' : result.FileFormat.replace('docx', 'doc')) : 'blank') + '-24\' ></em>');
					$('#QuickViewDocumentName').html(result.Description);
					$('.container-document-quickview').height($(document).height());
					$('.document-quickview').removeClass('hidden');

					var navigationFromTop = $('.document-quickview').height() * 0.4;
					$('.navigation').css('top', navigationFromTop);
					currentContentUrl = result.Path;
				}
			});
		}
		else
		{
			CivicWeb.Documents.DocumentOperations.Events.changePreviewUrl(id);
			$('#PrintDocument').addClass('hidden');

			$.ajax({
				url: '/api/documents/getdocument/' + id + (viewDeleted ? '?deleted=True' : ''),
				contentType: 'application/json', dataType: 'json', async: true, cache: false, type: 'GET'
			}).done(function (result)
			{
				if (result)
				{
					if (result && result.PublicReleaseDelayDateString.length > 0 && result.IsPublic)
					{
						result.FileFormat = 'publicdelay';
					}

					$(document.getElementById('PrintNotes')).addClass('hidden');
					switch (result.FileFormat.toLowerCase())
					{
						case 'publicdelay':

							var noPublicAccessWarning = result.AgendaCover + '<br/><br/>Public Release: ' + result.PublicReleaseDelayDateString;
							documentQuickView.html('<span id=\'preview\' title=\'Public Release: ' + result.PublicReleaseDelayDateString + '\' ><span style=\'cursor:pointer; display:inline-table; background-color:white; border:#6A6B6D solid 2px; padding: 2px 15px 2px 15px; color:black; height:700px; width:600px;\'><div style=\'padding-top: 25px; font-weight:bold;\'>' + noPublicAccessWarning + '</div></span>');
							documentQuickViewClearandClose();
							break;

						case 'pdf':
						case 'tif':
						case 'tiff':
							try
							{
								if (result.Thumbnails && result.Thumbnails.length)
								{
									var thumbnailUrl = location.protocol + '//' + location.host + JSON.parse(decodeURIComponent(result.Thumbnails))['large'];
									documentQuickView.html('<span id=\'preview\' title=\'' + localization.toolTipClicktoOpenLoadFullPDF + '\' class=\'unselectable\'><img class=\'unselectable\' title=\'' + localization.toolTipClicktoOpenLoadFullPDF + '\' style=\'cursor:pointer; max-width:100%; max-height:' + (contentHeight - 10) + 'px;\' src=\'' + thumbnailUrl + '\' alt=\'' + result.Description + '\' />');
								}
								else
								{
									currentContentUrl = result.ContentUrl;
									openFullPdfClick();
								}
							}
							catch (exeption)
							{
								documentQuickView.html('<span id=\'preview\' title=\'' + localization.toolTipClicktoOpenLoadFullPDF + '\' ><span style=\'cursor:pointer; display:inline-table; background-color:white; border:#6A6B6D solid 2px; padding: 2px 15px 2px 15px; color:black; height:700px; width:600px;\'><div style=\'padding-top: 25px; font-weight:bold;\'>NO PREVIEW AVAILABLE</div></span>');
							}
							var clicktoDownLoadnotice = jQuery('<div/>', {
								id: 'ClicktoDownLoadnotice',
								title: localization.toolTipClicktoOpenLoadFullPDF,
								style: 'cursor:pointer; margin-top:-160px; color:#EE0000; font-weight:Bold; display:none;'
							}).append(jQuery('<span/>', {
								title: localization.toolTipClicktoOpenLoadFullPDF,
								text: localization.toolTipClicktoOpenLoadFullPDF,
								style: 'background-color:white; border:#6A6B6D solid 2px; padding: 2px 15px 2px 15px'
							})).off('click').on('click', downloadDocument);
							clicktoDownLoadnotice.appendTo(documentQuickView);
							clicktoDownLoadnotice.show().animate({
								fontSize: '1.65em'
							}, 750);

							documentQuickViewClearandClose();
							documentQuickView.find('#preview').off('click').on('click', openFullPdfClick).removeClass('quickview-openfullpdf').attr('title', '');
							clicktoDownLoadnotice.off('click').on('click', openFullPdfClick).removeClass('quickview-openfullpdf').attr('title', '');
							$('#OpenFullPdfMenuItem, #CoverPreviewLabel').show();
							$('#DownloadDocumentMenuItem').hide();
							$('#PrintDocument').addClass('hidden');
							if (purchasedVideo && result.MeetingId > 0 && CivicWeb.Integration.Video != null)
							{
								CivicWeb.Integration.Video.showPdfQuickViewVideoLink(result.MeetingId, id);
							}
							break;
						case 'bmp':
						case 'gif':
						case 'jpg':
						case 'jpeg':
						case 'png':
						case 'webp':
						case 'svg':
						case 'ico':
							documentQuickView.html($(new Image()).css('max-height', (contentHeight - 6) + 'px').attr({ 'alt': result.Description, 'src': processUrl(result.ContentUrl) }).addClass('quickView-80'));

							//documentQuickView.html("<img style=':" + (contentHeight - 6) + "px;' alt='" + result.Description + "' class='' src='" + result.ContentUrl + "' />");
							documentQuickViewClearandClose();

							$('#OpenFullPdfMenuItem, #CoverPreviewLabel, #DownloadDocumentMenuItem').hide();
							$('#PrintDocument').removeClass('hidden');
							break;
						case 'docx':
						case 'doc':
						case 'odt':
							var urlQueryObj = CivicWeb.Documents.DocumentOperations.Events.getCurrentUrlQueryValues();
							var splitscreenQuery = result.OpenSplitScreen || (urlQueryObj && urlQueryObj.splitscreen);
							var notesQuery = urlQueryObj && urlQueryObj.notes;
							var docUrl = CivicWeb.Common.addUrlParameter(processUrl(CivicWeb.Common.addUrlParameter(CivicWeb.Common.addUrlParameter(result.ContentUrl, splitscreenQuery ? 'splitscreen' : '', 'true'), notesQuery ? 'notes' : '', 'true')), 'preview', 'true');
							if ((attachmentUrl || '').length > 0)
							{
								docUrl = CivicWeb.Common.addUrlParameter(docUrl, 'attachmenturl', encodeURI(attachmentUrl));
							}

							documentQuickView.html('<iframe frameborder=\'0\' scrolling=\'auto\' allowfullscreen=\'1\' style=\'border: 0; max-width:' + (splitscreenQuery ? '100%' : '8.5in') + '; height:' + (contentHeight - 6) + 'px;\' class=\'parent-iframe quickView-80\' src=\'' + docUrl + '\' />');
							documentQuickViewClearandClose();

							$('#DownloadDocumentMenuItem').show();
							$('#OpenFullPdfMenuItem, #CoverPreviewLabel').hide();
							$('#PrintDocument').removeClass('hidden');
							break;
						case 'html':
						case 'htm':
						case 'xml':
						case 'txt':
							documentQuickView.html('<iframe frameborder=\'0\' scrolling=\'auto\' allowfullscreen=\'1\' style=\'border: 0; max-width:8.5in; height:' + (contentHeight - 6) + 'px;\' class=\'parent-iframe quickView-80\' src=\'' + processUrl(result.ContentUrl) + '\' />');
							documentQuickViewClearandClose();

							$('#OpenFullPdfMenuItem, #CoverPreviewLabel, #DownloadDocumentMenuItem').hide();
							$('#PrintDocument').removeClass('hidden');
							break;
						case 'splitscreen':
							documentQuickView.html('<iframe frameborder=\'0\' id=\'parentIframe\' scrolling=\'auto\' allowfullscreen=\'1\' style=\'border: 0;  max-width:100%; height:' + (contentHeight - 6) + 'px; class=\'parent-iframe\' src=\'' + processUrl(result.ContentUrl) + '\' />');
							documentQuickViewClearandClose();
							$(document.getElementById('parentIframe')).addClass('parent-iframe quickView-80').css('max-width', 'none');

							$('#OpenFullPdfMenuItem, #CoverPreviewLabel, #DownloadDocumentMenuItem').hide();
							break;
						case 'm4a':	
						case 'mp3':
							//audio
							result.FileFormat = 'mpeg';
						case 'wav':
							//audio
							if (result.FileFormat.toLowerCase() === 'mp3') {
								result.FileFormat = 'mpeg';
							}
							else if (result.FileFormat.toLowerCase() === 'm4a') {
								result.FileFormat = 'mp4';
							}
							documentQuickView.html('');
							documentQuickView.append($('<iframe></iframe>', { 'frameborder': 0, 'scrolling': 'auto' }).css({ 'width': '450px', 'height': '125px', 'margin-top': '25%', 'border': 'none', 'background-color': 'transparent' }).on('load', function ()
							{
								$(this).contents().find('body').html('<audio style=\'width: 400px; height:100px; display: inherit; margin: auto;\' controls><source src=\'' + processUrl(result.ContentUrl) + '\' type=\'audio/' + result.FileFormat + '\'></audio>');
							}));
							documentQuickViewClearandClose();
							$('#DownloadDocumentMenuItem').show();
							$('#OpenFullPdfMenuItem, #CoverPreviewLabel').hide();
							break;													
						case 'm4v':
						case 'wmv':
						case 'ogg':
						case 'mp4':								
						case 'avi':
						case 'mov':
						case 'mpg':
						case 'webm':
						case 'mpeg':
							//Video
							var videoFormat = result.FileFormat == 'mov' ? 'mp4' : result.FileFormat;
							var videoMarginTop = Math.max($(window).height() - $(document.getElementById('quickview-header-container')).height() - $('.footer').height() - 450, 0) / 2;
							documentQuickView.html('');
							documentQuickView.append($('<iframe></iframe>', { 'frameborder': 0, 'scrolling': 'auto' }).css({ 'width': '625px', 'height': '450px', 'margin-top': videoMarginTop + 'px', 'border': 'none', 'background-color': 'transparent' }).on('load', function ()
							{
								$(this).contents().find('body').html('<video width=\'600\' height=\'425\' style=\'display: inherit; \' controls><source src=\'' + processUrl(result.ContentUrl) + '\' type=\'video/' + videoFormat + '\'></video>');
							}));
							documentQuickViewClearandClose();
							$('#OpenFullPdfMenuItem, #CoverPreviewLabel').hide();
							$('#DownloadDocumentMenuItem').show();
							break;
						default:
							documentQuickView.html('<img style=\'background-color: #888;  max-width:100%; \' alt=\'' + localization.clickToDownLoadDocument + '\' src=\'https://i.civicweb.net/Images/IconFiles512/' + (result.FileFormat.length > 0 ? result.FileFormat + '.png\'' : '_blank.png') + '\' style=\'margin-top: 1em;\'></img><br /><span class=\'document-control-bar-button background-color-hover document-content\' style=\'padding: 1em; max-width: 348; width:80%\'>' + localization.clickToDownLoadDocument + '</span>');
							documentQuickViewClearandClose();
							documentQuickView.children().off('click').on('click', downloadDocument).addClass('quickview-downloadDocument').attr('title', 'Download Document');
							$('#OpenFullPdfMenuItem, #CoverPreviewLabel, #DownloadDocumentMenuItem').hide();
							break;
					}
					fileName = result.UrlFriendlyFileName;
					$('#QuickViewDocumentIcon').html(' <em class=\'icon-file-' + (result.FileFormat.length > 0 ? (result.FileFormat === 'splitscreen' ? 'html' : result.FileFormat.replace('docx', 'doc')) : 'blank') + '-24\' ></em>');
					$('#QuickViewDocumentName').html($('<div/>').html(result.Description).text());
					$('.container-document-quickview').height($(document).height());
					$('.document-quickview').removeClass('hidden');

					if (result.UpdateAllowed)
					{
						$('#EditDetails').removeClass('hidden');
					}
					else
					{
						$('#EditDetails').addClass('hidden');
					}

					if (viewDeleted)
					{
						$('#QuickViewFavorite').addClass('hidden');
						$('#social-media-share-quick-view').addClass('hidden');
					}
					else
					{
						$('#QuickViewFavorite').removeClass('hidden');
						$('#social-media-share-quick-view-span').removeClass('hidden').children().removeClass('hidden');
						if (searchDocument)
						{
							var quickviewFav = $('#QuickViewFavorite');
							quickviewFav.attr('data-type', (result.Favorite ? 'remove' : 'add'));
							quickviewFav.attr('data-id', id);
							quickviewFav.removeClass('cw-fp-icon-star').removeClass('cw-fp-icon-star-disabled');
							quickviewFav.addClass(result.Favorite ? 'cw-fp-icon-star' : 'cw-fp-icon-star-disabled');
							quickviewFav.off('click', function (e)
							{
								CivicWeb.Documents.DocumentOperations.Events.favoriteDocument(id, !result.Favorite, isLoggedIn, function ()
								{
									result.Favorite = !result.Favorite;
									$('#QuickViewFavorite').attr('src', (result.Favorite ? 'https://i.civicweb.net/Images/star-icon.png' : 'https://i.civicweb.net/Images/star-icon-disabled.png'));
									$('#QuickViewFavorite').attr('data-type', (result.Favorite ? 'remove' : 'add'));
								}, null);
								e.preventDefault();
							}).on('click', function (e)
							{
								CivicWeb.Documents.DocumentOperations.Events.favoriteDocument(id, !result.Favorite, isLoggedIn, function ()
								{
									result.Favorite = !result.Favorite;
									$('#QuickViewFavorite').attr('src', (result.Favorite ? 'https://i.civicweb.net/Images/star-icon.png' : 'https://i.civicweb.net/Images/star-icon-disabled.png'));
									$('#QuickViewFavorite').attr('data-type', (result.Favorite ? 'remove' : 'add'));
								}, null);
								e.preventDefault();
							});
						}
						else
						{
							var quickviewFav = $('#QuickViewFavorite');
							var e1 = $('div.document-list-view-documents[data-id=\'' + id + '\']');
							var imgElement = e1.find('span.favorite-icon');
							quickviewFav.removeClass('cw-fp-icon-star').removeClass('cw-fp-icon-star-disabled');
							quickviewFav.addClass(result.Favorite ? 'cw-fp-icon-star' : 'cw-fp-icon-star-disabled');
							quickviewFav.attr('data-type', imgElement.attr('data-type'));
							quickviewFav.attr('data-id', id);
							quickviewFav.attr('data-uid', e1.closest('[data-uid]').attr('data-uid'));
						}
					}

					if (documentQuickView.find('iframe') != null)
					{
						documentQuickView.find('iframe').on('load', function ()
						{
							switch (result.FileFormat.toLowerCase())
							{
								case 'bmp':
								case 'gif':
								case 'jpg':
								case 'jpeg':
								case 'png':
								case 'webp':
								case 'svg':
									$(documentQuickView.find('iframe').contents()).find('img').css('max-width', '100%');
									documentQuickView.find('iframe').css('background-color', 'transparent');
									break;

								case 'doc':
								case 'docx':
								case 'odt':
								case 'splitscreen':
									$(documentQuickView.find('iframe').contents()).find('a#document-splitscreen').on('click', function ()
									{
										$(documentQuickView.find('iframe')).css('max-width', '100%');
										$(documentQuickView.find('iframe')).attr('src', $(this).attr('href'));
									});
									$(documentQuickView.find('iframe').contents()).find('div#ToogleNotes').on('click', function ()
									{
										var notesEnabled = $(documentQuickView.find('iframe').contents()).find('div#ToogleNotes').find('a').attr('data-enabled');
										if (notesEnabled === 'false')
										{
											$(document.getElementById('nextQuickView')).addClass('hidden');
											$(document.getElementById('previousQuickViewCell')).addClass('hidden');
										}
										else
										{
											$(document.getElementById('nextQuickView')).removeClass('hidden');
											$(document.getElementById('previousQuickViewCell')).removeClass('hidden');
										}
									});
									$(window).resize(function (e)
									{
										setTimeout(function ()
										{
											var parentIframe = $('iframe.parent-iframe');
											if (parentIframe && parentIframe.length)
											{
												var height = $(window).height() - (parentIframe.length > 0 ? Math.floor(parentIframe.offset().top) : 0);
												if (!navigator.userAgent.match(/(android|ipad)/i))
												{
													height = height - 34;
												}
												parentIframe.contents().find('#AttachmentScrollBar').height(height);
												parentIframe.contents().find('#AgendaScrollBar').height(height);
												parentIframe.contents().find('#AgendaFrame').height(height);
												parentIframe.contents().find('#AttachmentFrame').height(height);
												parentIframe.contents().find('#AgendaPane').height(height);
												parentIframe.contents().find('#AttachmentPane').height(height);
												parentIframe.height(height);
											}
										}, 0);

										e.preventDefault();
									});

									if (searchText)
									{
										setTimeout(function ()
										{
											if (result.FileFormat.toLowerCase() === 'splitscreen')
											{
												CivicWeb.Documents.DocumentSearchPage.events.highlightSearchText(searchText, documentQuickView.find('iframe').contents().find('iframe#AgendaFrame').contents().find('body').get(0));
												var firstHighlightedElement = $(documentQuickView.find('iframe').contents().find('iframe#AgendaFrame').contents().find('span.highlighted').get(0));
												if (firstHighlightedElement.length)
												{
													documentQuickView.find('iframe').contents().find('iframe#AgendaFrame').contents().find('body').animate({
														scrollTop: firstHighlightedElement.offset().top + 'px'
													});
												}
											}
											else
											{
												CivicWeb.Documents.DocumentSearchPage.events.highlightSearchText(searchText, documentQuickView.find('iframe').contents().find('body').get(0));
												var firstHighlightedElement = $(documentQuickView.find('iframe').contents().find('span.highlighted').get(0));
												if (firstHighlightedElement.length)
												{
													documentQuickView.find('iframe').contents().find('body').animate({
														scrollTop: firstHighlightedElement.offset().top + 'px'
													});
												}
											}
										}, 500);
									}

									if (isTablet)
									{
										documentQuickView.css({ 'height': contentHeight + 'px' }).addClass('ipad');
										documentQuickView.find('iframe').css({ 'height': '100%', 'width': '100%' });
									}
									break;

								case 'html':
									if (searchText)
									{
										setTimeout(function ()
										{
											CivicWeb.Documents.DocumentSearchPage.events.highlightSearchText(searchText, documentQuickView.find('iframe').contents().find('body').get(0));
											var firstHighlightedElement = $(documentQuickView.find('iframe').contents().find('span.highlighted').get(0));
											if (firstHighlightedElement.length)
											{
												documentQuickView.find('iframe').contents().find('body').animate({
													scrollTop: firstHighlightedElement.offset().top + 'px'
												});
											}
										}, 500);
									}
									break;
							}
							$(documentQuickView.find('iframe').get(0).contentWindow.document).off('keydown', keyPress).on('keydown', keyPress);

							if ($('.navigation').is(':visible'))
							{
								$(document.getElementById('documentQuickViewCell')).find('iframe.parent-iframe').removeClass('quickView-100');
								$(document.getElementById('documentQuickViewCell')).find('iframe.parent-iframe').addClass('quickView-80');
							}
							else
							{
								$(document.getElementById('documentQuickViewCell')).find('iframe.parent-iframe').removeClass('quickView-80');
								$(document.getElementById('documentQuickViewCell')).find('iframe.parent-iframe').addClass('quickView-100');
							}
						});
					}

					var navigationFromTop = $('.document-quickview').height() * 0.4;
					$('.navigation').css('top', navigationFromTop);
					currentContentUrl = result.ContentUrl;

					if (result.FileFormat == 'publicdelay')
					{
						$('#FullScreen').addClass('hidden');
					}
					else if (result.FileFormat.toLowerCase() === 'docx' || result.FileFormat.toLowerCase() === 'doc' || result.FileFormat.toLowerCase() === 'odt')
					{
						$('#FullScreen').removeClass('hidden').attr('href', result.ContentUrl);
					}
					else
					{
						$('#FullScreen').removeClass('hidden').attr('href', result.FullScreenUrl);
					}
				}
			});
		}
	};

	var documentQuickViewClearandClose = function ()
	{
		$('.document-quickview-content').off('click').on('click', checkTagetCloseQuickView).removeClass('quickview-openfullpdf').attr('title', '');
	};

	var checkTagetCloseQuickView = function (e)
	{
		if (e.target === this && !isTablet)
		{
			CivicWeb.Common.QuickViews.closeQuickView(e);
		}
		e.preventDefault();
	};

	var previousDocumentCellClick = function ()
	{
		if (!$('#previousQuickView:hover').length > 0)
		{
			$('.document-quickview').addClass('hidden');
		}
	};

	var nextDocumentCellClick = function ()
	{
		if (!$('#nextQuickView:hover').length > 0)
		{
			$('.document-quickview').addClass('hidden');
		}
	};

	var documentQuickViewContentCellClick = function ()
	{
		if (!$('.document-quickview-content:hover').length > 0)
		{
			$('.document-quickview').addClass('hidden');
		}
	};

	var openFullPdfClick = function ()
	{
		var isMobileDevice = (/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent.toLowerCase()));
		if (isMobileDevice)
		{
			window.open(currentContentUrl);
		}
		else
		{
			var contentHeight = $(window).height() - 38;
			if ((/msie/.test(navigator.userAgent.toLowerCase())) || (/trident/.test(navigator.userAgent.toLowerCase())))
			{
				$('.document-quickview-content').empty();
			}
			else
			{
				$('.document-quickview-content').html('<div id=\'loading-background\' style=\'margin: auto; background-color: white; color: black; border: 1px solid black; vertical-align: middle; text-align: center; height:' + contentHeight + 'px; width: 8.5in; max-width: 100%;\'><div style=\'padding-top: 10em;\'><div style=\'vertical-align: middle;\' class=\'loader\'></div> ' + localization.loadingInProgress + '</div></div>');
			}
			var iframe = $('<iframe></iframe>')
				.attr({ 'id': 'pdf-quickview', 'class': 'quickView-80' + (!((/msie/.test(navigator.userAgent.toLowerCase())) || (/trident/.test(navigator.userAgent.toLowerCase()))) ? ' hidden' : ''), 'frameborder': '0', 'scrolling': 'auto', 'src': (currentContentUrl + (searchDocument && searchText && !/trident/.test(navigator.userAgent.toLowerCase()) ? '#search="' + searchText + '"&' : '#') + 'view=fitH,100&pagemode=bookmarks') })
				.css({ 'border': '0', 'height': (contentHeight - 6) + 'px' })
				.css(/firefox/i.test(navigator.userAgent) ? { 'width': '10.5in', 'max-width': '100%' } : {}) //Allow room for bookmarks in PDF.js
				.on('load', function ()
				{
					$('.document-quickview-content').find('div#loading-background').remove();
					$('.document-quickview-content').find('iframe').removeClass('hidden');
				});
			$('.document-quickview-content').append(iframe);
			$('#OpenFullPdfMenuItem, #CoverPreviewLabel').hide();
			setTimeout(function () { $('.document-quickview').removeClass('hidden') }, 0); //Stop surface pro from hiding the quickview
		}
	};

	var downloadWordDocumentClick = function (e)
	{
		window.location.href = '/filepro/document/' + currentId.toString() + '/' + fileName + '?viewOriginal=True';

		e.preventDefault();
	};

	var downloadDocument = function ()
	{
		$('.document-quickview-content').append('<iframe frameborder="0" scrolling="auto" style="display:none;" src="' + currentContentUrl + '">');
	};

	var editDetailsClick = function (e)
	{
		window.location = '/filepro/document/' + currentId + (window.location.href.indexOf('recyclebin') !== -1 ? '?deleted=True' : '');

		e.preventDefault();
	};

	var fullScreenClick = function (e)
	{
		var isMobileDevice = (/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent.toLowerCase()));
		if (isMobileDevice)
		{
			window.open(currentContentUrl);
			e.preventDefault();
		}
	};

	var keyPress = function (e)
	{
		var evt = window.event ? window.event : e;
		if (evt != null)
		{
			if ($(document.getElementById('ToogleNotes')).find('a').attr('data-enabled') === 'false')
			{
				//left arrow key
				if (evt.keyCode === 37)
				{
					previousDocumentClick(evt);
				}//right arrow key
				else if (evt.keyCode === 39)
				{
					nextDocumentClick(evt);
				}
				else
				{
					CivicWeb.Documents.DocumentListPage.Events.windowKeyDown(evt);
				}
			}
		}

	};

	var processUrl = function (url)
	{
		return CivicWeb.Common.addUrlParameter(url || '', fromWidget ? 'widget' : '', 'true');
	};

	(function ()
	{
		if (purchasedVideo)
		{
			CivicWeb.Integration.Video.createInstance(args);
		}

		isTablet = navigator.userAgent.match(/(android|ipad)/i);
		isPhone = /android|webos|iphone|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent.toLowerCase());

		$('#previousQuickView').off('click').on('click', previousDocumentClick).on("keydown", previousDocumentKeyDown);
		$('#nextQuickView').off('click').on('click', nextDocumentClick).on("keydown", nextDocumentKeyDown);

		$('#previousQuickViewCell').off('click').on('click', previousDocumentCellClick).on("keydown", previousDocumentKeyDown);
		$('#nextQuickViewCell').off('click').on('click', nextDocumentCellClick).on("keydown", nextDocumentKeyDown);

		$('#documentQuickViewCell').off('click').on('click', documentQuickViewContentCellClick);
		$('#FullScreen').off('click').on('click', fullScreenClick);

		$('#OpenFullPdfMenuItem').off('click').on('click', openFullPdfClick);
		$('#DownloadDocumentMenuItem').off('click').on('click', downloadWordDocumentClick);
		$(document.getElementById('EditDetails')).off('click').on('click', editDetailsClick);

		$('#PrintDocument').off('click').on('click', function ()
		{
			var frame = $(document.getElementById('documentQuickViewCell')).find('iframe');
			if (frame.length === 0)
			{
				//Create a frame if there is not already one
				var documentQuickView = $('.document-quickview-content');
				var contentHeight = $(window).height() - 60;
				documentQuickView.html('<iframe frameborder=\'0\' scrolling=\'auto\' allowfullscreen=\'1\' style=\'border: 0; max-width: 8.5in; height:' + (contentHeight - 6) + 'px;\' class=\'parent-iframe quickView-80\' src=\'about:blank\' />');
				(frame = documentQuickView.find('iframe')).on('load', function ()
				{
					frame.get(0).contentWindow.focus();
					frame.get(0).contentWindow.print();
				}).attr({ 'src': '/document/' + currentId });
			}
			else
			{
				frame.get(0).contentWindow.focus();
				frame.get(0).contentWindow.print();
			}
		});

		if (isLoggedIn)
		{
			$(document.getElementById('EditDetails')).show();
		}
		else
		{
			$(document.getElementById('EditDetails')).hide();
		}
	})();
};

CivicWeb.Common.QuickViews = {
	//Properties
	instances: new Array(),

	//Methods
	getInstance: function ()
	{
		return this.instances.length > 0 ? this.instances[0] : null;
	},

	getIndex: function ()
	{
		var index = 0;

		return index >= this.instances.length ? -1 : index;
	},

	createInstance: function (args)
	{
		var instance = this.getInstance(args.clientId);
		var index = this.getIndex(args.clientId);
		if (instance)
		{
			delete instance;
		}
		if (index < 0)
		{
			index = this.instances.length;
		}
		this.instances[index] = new CivicWeb.Common.QuickView(args);
	},

	loadQuickView: function (id, ids, options)
	{
		return this.getInstance().loadQuickview(id, ids, options);
	},

	getCurrentId: function ()
	{
		return this.getInstance().getCurrentId();
	},

	closeQuickView: function (e)
	{
		return this.getInstance().closeQuickView(e);
	},

	//Events
	events: {
	}
};
;
window.CivicWeb = window.CivicWeb || {};
window.CivicWeb.Common = window.CivicWeb.Common || {};

(function (library, $)
{
	//TODO: Cannot use strict mode until AgendaPopUp.aspx is no longer used - this includes jQuery

	//Properties
	var instances = [];

	//Classes
	// ReSharper disable once InconsistentNaming
	var Control = function (id, args)
	{
		var clientId = id;
		var relatedItemsClientId = clientId + '-related-items-';
		var addButtonClientId = clientId + '-add-';

		var baseCssClass = 'relationships';

		var localization = args.localization;

		var itemId = args.itemId || 0;
		var culture = '';
		var relationshipTypes = args.relationshipTypes || [];
		var itemSelectorArguments = args.itemSelectorArguments || {};
		var linkTemplate;

		//Event Handlers
		var removeRelationshipClick = function (e)
		{
			var button = $(e.target);
			var relationship = {
				relatedItemId: CivicWeb.Common.toNumber(button.attr('data-id')),
				type: CivicWeb.Common.toNumber(button.attr('data-type')),
				reverse: CivicWeb.Common.toBoolean(button.attr('data-reverse'))
			};

			$.ajax({
				url: '/api/item/' + itemId + '/relatedItem',
				contentType: 'application/json',
				dataType: 'json',
				async: true,
				cache: false,
				type: 'DELETE',
				data: JSON.stringify(relationship)
			}).done(function (data)
			{
				if (data)
				{
					button.closest('.' + baseCssClass + '-item').remove();
				}
			});

			e.preventDefault();
		};

		var addButtonClick = function (e)
		{
			var button = $(e.target).closest('button');
			var trackers = button.attr('data-trackers') || '';
			if (trackers.length > 0)
			{
				trackers = JSON.parse(trackers);
			}
			var relationshipType = {
				type: CivicWeb.Common.toNumber(button.attr('data-type')),
				reverse: CivicWeb.Common.toBoolean(button.attr('data-reverse')),
				trackers: trackers.length > 0 ? trackers : undefined
			};
			var relatedItems = button.closest('.relationships-type').find('.relationships-items .relationships-remove').map(function ()
			{
				return CivicWeb.Common.toNumber($(this).attr('data-id'));
			}).get();
			var id = clientId + '-item-selector-' + relationshipType.type + '-' + relationshipType.reverse;
			var options = { relationshipType: relationshipType, relatedItems: relatedItems, searchColumns: getLinkTemplateFieldIds() };
			(CivicWeb.Common.ItemSelector.find(id) || CivicWeb.Common.ItemSelector.create(id, itemSelectorArguments, options)).setOptions(options).open();

			e.preventDefault();
		};

		//Methods
		this.getId = function ()
		{
			return clientId;
		};

		//Functions
		var load = function ()
		{
			itemSelectorArguments.relatedItemId = itemId;
			itemSelectorArguments.relationshipCreated = getRelatedItems;

			var container = $(document.getElementById(clientId));

			culture = container.attr('data-culture') || '';

			var attributeRelationshipTypes = container.attr('data-relationship-types') || '';
			if (attributeRelationshipTypes.length > 0)
			{
				relationshipTypes = JSON.parse(attributeRelationshipTypes);
			}
			
			if (relationshipTypes.trackers)
			{
				itemSelectorArguments.trackers = itemSelectorArguments.trackers.filter(function (tracker)
				{
					return relationshipTypes.trackers.includes(tracker.id);
				});
			}

			linkTemplate = container.attr('data-link-template') || '';

			relationshipTypes.reduce(generateRelationshipType, container.empty().addClass(baseCssClass));
			getRelatedItems();
		};

		var generateRelationshipType = function (container, relationshipType)
		{
			return container
				.append($('<div></div>').addClass(baseCssClass + '-type')
					.append($('<div></div>')
						.append($('<label></label>').toggleClass('hidden', !!relationshipType.hideLabel).text(relationshipType['label-' + culture] || relationshipType.label)))
					.append($('<div></div>').attr({ 'id': generateRelationshipTypeId(relatedItemsClientId, relationshipType), 'class': baseCssClass + '-items' }))
					.append($('<div></div>')
						.append(CivicWeb.Common.Button.create(generateRelationshipTypeId(addButtonClientId, relationshipType), relationshipType['buttonLabel-' + culture] || relationshipType.buttonLabel || localization.buttonPlusAdd, relationshipType['buttonToolTip-' + culture] || relationshipType.buttonToolTip || localization.toolTipAddRelatedItem, CivicWeb.Common.Button.types.short, { 'data-placement': 'right', 'data-type': relationshipType.type, 'data-reverse': relationshipType.reverse, 'data-trackers': JSON.stringify(relationshipType.trackers) }).on('click', addButtonClick))));
		};

		var generateRelationshipTypeId = function (baseId, relationshipType)
		{
			return baseId + relationshipType.type + '-' + relationshipType.reverse;
		};

		var getRelatedItems = function (relationshipType)
		{
			var relationshipTypesToUpdate = relationshipType
				? [relationshipType]
				: relationshipTypes.map(function (relationshipType)
				{
					return {
						type: relationshipType.type,
						reverse: relationshipType.reverse
					};
				});
			return $.ajax({
				url: '/api/item/' + itemId + '/relatedItems?relationshipTypes=' + encodeURIComponent(JSON.stringify(relationshipTypesToUpdate)) + '&linktemplate=' + encodeURIComponent(linkTemplate),
				contentType: 'application/json',
				dataType: 'json',
				async: true,
				cache: false,
				type: 'GET',
				data: null
			}).done(function (data)
			{
				relationshipTypesToUpdate.forEach(function (relationshipType)
				{
					var relatedItemsContainer = $(document.getElementById(generateRelationshipTypeId(relatedItemsClientId, relationshipType))).empty();
					return CivicWeb.Common.forceArray(data).find(function (dataRelationshipType)
					{
						return dataRelationshipType.type === relationshipType.type && dataRelationshipType.reverse === relationshipType.reverse;
					}).items.forEach(function (relatedItem)
					{
						relatedItemsContainer
							.append($('<div></div>').addClass(baseCssClass + '-item')
								.append((relatedItem.viewAllowed ? $('<a></a>').attr({ 'href': '/items/item?id=' + relatedItem.id }) : $('<span></span>')).html(relatedItem.description))
								.append(relatedItem.deleteAllowed ? $('<span></span>').attr({ 'title': localization.toolTipRemoveRelationship, 'class': 'glyphicon glyphicon-remove ' + baseCssClass + '-remove', 'data-id': relatedItem.id, 'data-type': relationshipType.type, 'data-reverse': relationshipType.reverse }).on('click', removeRelationshipClick) : null));
					});
				});

				$(document.getElementById(clientId)).find('[title]').tooltip({ trigger: 'hover' });
			});
		};

		var getLinkTemplateFieldIds = function ()
		{
			var fieldIds = [];
			var pattern = /\{[^:\}]+:(\d+)\}/gi;
			var match;
			do
			{
				match = pattern.exec(linkTemplate);
				if (match)
				{
					var fieldId = CivicWeb.Common.toNumber(match[1]);
					if (fieldId > 0)
					{
						fieldIds.push(fieldId);
					}
				}
			}
			while (match);

			return fieldIds;
		};

		load();
	};

	//Methods
	library.create = function (id, args)
	{
		var container = CivicWeb.Common.getJqueryObject(id);
		if (container.length === 0)
		{
			return undefined;
		}
		id = container.attr('id') || '';
		if (id.length === 0)
		{
			return undefined;
		}

		//Remove existing control
		var existingIndex = instances.findIndex(function (element)
		{
			return element.getId() === id;
		});
		if (existingIndex >= 0)
		{
			instances.splice(existingIndex, 1);
		}

		var control = new Control(id, args);
		instances.push(control);

		return control;
	};

	library.find = function (id)
	{
		return instances.find(function (element)
		{
			return element.getId() === id;
		});
	};
})(window.CivicWeb.Common.Relationships = window.CivicWeb.Common.Relationships || {}, jQuery);
;
window.CivicWeb = window.CivicWeb || {};
window.CivicWeb.Common = window.CivicWeb.Common || {};

(function (control, $)
{
	//Variables
	var securityPolicyWindowClientId = 'security-policy-window';
	var acceptButtonClientId = 'security-policy-accept';
	var policyAgreeCheckboxClientId = 'security-policy-agree-checkbox';
	var policyAgreeNotificationClientId = 'security-policy-agree-notification';

	var userId;
	var localization = null;
	var securityPolicy = null;
	var securityPolicyWindow = null;

	//Event
	var acceptClick = function (e)
	{
		var notification = CivicWeb.Common.Notification.hide(policyAgreeNotificationClientId);
		var agreeCheckbox = $(document.getElementById(policyAgreeCheckboxClientId));
		if (agreeCheckbox.prop('checked'))
		{
			$.ajax({
				url: '/api/accountmanagers/securitypolicy/accept',
				contentType: 'application/json',
				dataType: 'json',
				async: true,
				cache: false,
				type: 'POST'
			});

			closeWindow();
		}
		else
		{
			CivicWeb.Common.Notification.show(notification, CivicWeb.Common.Notification.types.warning);

			agreeCheckbox.focus();
		}

		e.preventDefault();
	};

	var reviewLaterClick = function (e)
	{
		closeWindow();

		e.preventDefault();
	};

	//Method
	var loadSecurityPolicy = function ()
	{
		if (window.location.href.indexOf('securityPolicy=True') >= 0)
		{
			if (!securityPolicy)
			{
				$.ajax({
					url: '/api/accountmanagers/securitypolicy',
					contentType: 'application/json',
					dataType: 'json',
					async: true,
					cache: false,
					type: 'GET',
					data: JSON.stringify(1)
				}).done(function (data)
				{
					if (data && data.securityPolicy.length > 0)
					{
						userId = data.userId;
						localization = data.localization;
						securityPolicy = data.securityPolicy;

						loadSecurityPolicyWindow();
					}
				});
			}
			else
			{
				loadSecurityPolicyWindow();
			}
		}
	};

	var loadSecurityPolicyWindow = function ()
	{
		if (securityPolicy && securityPolicy.length > 0)
		{
			if (CivicWeb.Common.loadKendoUi(loadSecurityPolicyWindow))
			{
				if (!securityPolicyWindow)
				{
					securityPolicyWindow = $('<div></div>').attr({ 'id': securityPolicyWindowClientId, 'class': 'notice hidden' })
						.append($('<div></div>').addClass('layout')
							.append($('<div></div>').attr({ 'class': 'notice-body layout-section layout-section-fill' }).html(securityPolicy))
							.append($('<div></div>').attr({ 'class': 'notice-footer layout-section' })
								.append($('<div></div>').attr({ 'class': 'notice-footer-row notice-footer-agree' })
									.append($('<input />').attr({ 'id': policyAgreeCheckboxClientId, 'type': 'checkbox', 'required': 'required', 'class': 'required' }))
									.append($('<label></label>').attr({ 'for': policyAgreeCheckboxClientId }).text(localization.readAndAgreed)))
								.append(CivicWeb.Common.Notification.create(policyAgreeNotificationClientId, CivicWeb.Common.Notification.types.warning, localization.notificationYouMustCheckAgreeWithTerms, true))
								.append($('<div></div>').attr({ 'class': 'notice-footer-row' })
									.append($('<button></button>').attr({ 'id': acceptButtonClientId, 'class': 'button background-color-hover' }).text(localization.agreeText).on('click', acceptClick))
									.append($('<button></button>').attr({ 'class': 'button background-color-hover' }).text(localization.reviewLaterText).on('click', reviewLaterClick)))));

					$('body').append(securityPolicyWindow);

					securityPolicyWindow.kendoWindow({
						width: '800px',
						height: '600px',
						modal: true,
						visible: false,
						title: localization.title
					});

					securityPolicyWindow.css({ 'padding': '0', 'overflow': 'initial' }); //Override Kendo UI styles

					securityPolicyWindow.data('kendoWindow').center();
				}

				securityPolicyWindow.removeClass('hidden').css({ 'visibility': '' }).data('kendoWindow').open();
			}
		}
	};

	var closeWindow = function ()
	{
		if (securityPolicyWindow)
		{
			securityPolicyWindow.addClass('hidden').data('kendoWindow').close();
		}
	};

	(function ()
	{
		loadSecurityPolicy();
	})();
})(window.CivicWeb.Common.SecurityPolicy = window.CivicWeb.Common.SecurityPolicy || {}, jQuery);
;
window.CivicWeb = window.CivicWeb || {};
window.CivicWeb.Common = window.CivicWeb.Common || {};

(function (control, $)
{
	//Properties
	var signInClientId = 'sign-in';
	var signInFormClientId = 'sign-in-form';
	var signInUserNameClientId = 'sign-in-user-name';
	var signInPasswordClientId = 'sign-in-password';
	var signInButtonClientId = 'sign-in-button';
	var signInRememberMeClientId = 'sign-in-remember-me';
	var signInWarningMessageClientId = 'sign-in-warning-message';
	var marketingFrameClientId = 'marketing-frame';
	var signInThrobberOverlayClientId = 'sign-in-overlay';

	var showSignInPopupButton;

	var localization;

	var isPopup;
	var showMarketing;
	var rememberMeSet;
	var signInWindow;
	var hasHeightIssue;

	//Event Handlers
	var showSignInPopupButtonClick = function (e)
	{
		if (isPopup)
		{
			loadPopUp();
		}

		e.preventDefault();
	};

	var signInTextBoxKeyDown = function (e)
	{
		if (e.which === 13)
		{
			var userNameTextBox = $(document.getElementById(signInUserNameClientId));
			if (userNameTextBox.val() === 0)
			{
				userNameTextBox.focus();
			}
			else
			{
				var passwordTextBox = $(document.getElementById(signInPasswordClientId));
				if (passwordTextBox.val() === 0)
				{
					passwordTextBox.focus();
				}
				else
				{
					attemptSignIn();
				}
			}

			e.preventDefault();
		}
		else
		{
			displayWarningMessage('');

			setTimeout(checkRendering, 0); //Typing when the marking is visible in Edge causes rendering issues (the first time you type at least)
		}
	};

	var signInButtonClick = function (e)
	{
		attemptSignIn();

		e.preventDefault();
	};

	//Functions
	var initialize = function ()
	{
		CivicWeb.Common.Cookie.get('UserName').then(function (rememberedUserName)
		{
			var userName = $(document.getElementById(signInUserNameClientId));
			if ((userName.val() || '').length === 0)
			{
				userName.val(rememberedUserName || '');
			}

			rememberMeSet = 'string' === typeof rememberedUserName && rememberedUserName.length > 0;
			$(document.getElementById(signInRememberMeClientId)).prop('checked', rememberMeSet);
		});
		
		if (!placeholderIsSupported())
		{
			$('label[for="' + signInUserNameClientId + '"],label[for="' + signInPasswordClientId + '"]').parent().removeClass('hidden');
		}
	};

	var placeholderIsSupported = function ()
	{
		var inputTest = document.createElement('input');
		return 'placeholder' in inputTest;
	};

	var checkRendering = function ()
	{
		hasHeightIssue = $(document.getElementById(signInClientId)).find('.layout-pane').height() < 150;

		if (hasHeightIssue)
		{
			//Safari on iPad and IE 11
			$(window).off('resize', checkRendering).on('resize', fixRendering);
			fixRendering();

			if (!isPopup)
			{
				$('.content').css({ 'overflow': 'hidden' });
			}
		}
	};

	var fixRendering = function ()
	{
		//Safari on iPad
		var signInColumn = $(document.getElementById(signInClientId)).css({ 'height': '' });
		signInColumn.css({ 'height': signInColumn.closest('.content,.k-window-content').height() + 'px' });
	};

	var loadPopUp = function ()
	{
		if (CivicWeb.Common.loadKendoUi(loadPopUp))
		{
			$(document.getElementById(signInThrobberOverlayClientId)).remove();

			if (!signInWindow)
			{
				signInWindow = $(document.getElementById(signInClientId));

				signInWindow.kendoWindow({
					width: showMarketing ? '80%' : '400px',
					height: showMarketing ? '80%' : '400px',
					modal: true,
					visible: false,
					title: localization.labelLogOn,
					open: function ()
					{
						if ((/msie/.test(navigator.userAgent.toLowerCase())) || (/trident/.test(navigator.userAgent.toLowerCase())))
						{
							$('iframe').addClass('invisible');
						}
					},
					activate: function ()
					{
						var signInWindowData = signInWindow.data('kendoWindow');
						signInWindowData.setOptions({ height: showMarketing ? '80%' : '400px' });

						checkRendering();
						setFocus();

						setTimeout(function ()
						{
							signInWindowData.center();
						}, 0);
					},
					close: function ()
					{
						$('iframe').removeClass('invisible');
					}
				});

				signInWindow.css({ 'padding': '0', 'overflow': 'initial' }); //Override Kendo UI styles

				signInWindow.data('kendoWindow').center();
			}

			showMarketingPage();

			signInWindow.removeClass('hidden').css({ 'visibility': '' }).data('kendoWindow').open();
		}
		else
		{
			//Show loading throbber
			$('body')
				.append($('<div></div>').attr({ 'id': signInThrobberOverlayClientId, 'class': 'overlay-all' })
					.append($('<div></div>').addClass('overlay-content')
						.append($('<span></span>').attr({ 'class': 'overlay-throbber' })
							.append(CivicWeb.Common.Button.getThrobber(signInThrobberOverlayClientId + '-throbber')))));
		}
	};

	var showMarketingPage = function ()
	{
		if (showMarketing)
		{
			var marketingFrame = $(document.getElementById(marketingFrameClientId));
			if (marketingFrame.attr('src') === 'about:blank')
			{
				marketingFrame.attr({ 'src': '/purchases/marketing' });
			}
		}
	};


	var setFocus = function ()
	{
		if (rememberMeSet)
		{
			$(document.getElementById(signInPasswordClientId)).focus();
		}
		else
		{
			$(document.getElementById(signInUserNameClientId)).focus();
		}
	};

	var attemptSignIn = function ()
	{
		var userNameTextBox = $(document.getElementById(signInUserNameClientId));
		var userName = userNameTextBox.val();
		if (userName.length === 0)
		{
			displayWarningMessage(localization.pleaseEnterAUserNameWarningMessageText);
			userNameTextBox.focus();
		}
		else
		{
			var passwordTextBox = $(document.getElementById(signInPasswordClientId));
			var password = passwordTextBox.val();
			if (password.length === 0)
			{
				displayWarningMessage(localization.pleaseEnterAPasswordWarningMessageText);
				passwordTextBox.focus();
			}
			else
			{
				var button = $(document.getElementById(signInButtonClientId));
				var existingText = CivicWeb.Common.Button.update(button, localization.signingInButtonLabelText, true, true);

				var payload = { userName: userName, password: password };
				$.ajax({
					url: '/api/user/signin',
					contentType: 'application/json',
					dataType: 'json',
					async: true,
					type: 'POST',
					data: JSON.stringify(payload)
				}).done(function (data)
				{
					if (data && data.authenticated)
					{
						//Save remember me information
						if ($(document.getElementById(signInRememberMeClientId)).prop('checked'))
						{
							CivicWeb.Common.Cookie.set('UserName', userName, 365);
						}
						else
						{
							CivicWeb.Common.Cookie.set('UserName', '', -1000);
						}

						var container = $(document.getElementById(signInClientId));
						if (container.attr('data-close') === 'True')
						{
							window.close();

							CivicWeb.Common.Button.update(button, existingText, false, false);
						}
						else
						{
							var signedInUrl = container.attr('data-url') || (window.location.href.indexOf('user/signin') < 0 ? window.location.href : null) || '/';
							if (signedInUrl.indexOf('notices=True') < 0)
							{
								var hashIndex = signedInUrl.indexOf('#');
								var hash = hashIndex >= 0 ? signedInUrl.substring(hashIndex) : '';
								signedInUrl = (hashIndex >= 0 ? signedInUrl.substring(0, hashIndex) : signedInUrl) + (signedInUrl.indexOf('?') >= 0 ? '&' : '?') + 'notices=True' + hash;
							}

							if (signedInUrl.indexOf('securityPolicy=True') < 0 && data.accountManagerPending)
							{
								signedInUrl = signedInUrl + (signedInUrl.indexOf('?') >= 0 ? '&' : '?') + 'securityPolicy=True';
							}

							var redirectUrl = '/';
							if (data.passwordExpiring)
							{
								redirectUrl = '/Administration/UserAdministration/ChangePassword.aspx?Url=' + encodeURIComponent(signedInUrl);
							}
							else
							{
								redirectUrl = signedInUrl;
							}

							$(document.getElementById(signInFormClientId)).attr({ 'action': '/user/signin?url=' + encodeURIComponent(redirectUrl) }).submit();
						}
					}
					else if (data.lockedOut)
					{
						var minutes = Math.floor(data.lockOutSecondsRemaining / 60);
						var seconds = data.lockOutSecondsRemaining % 60;
						displayWarningMessage((minutes > 1 ? localization.lockedOutMinutesWarningMessageText : (minutes === 1 ? localization.lockedOutMinuteWarningMessageText : (seconds > 1 ? localization.lockedOutSecondsWarningMessageText : localization.lockedOutSecondWarningMessageText))).replace('{0}', minutes.toString()).replace('{1}', seconds.toString()));
						userNameTextBox.focus();

						CivicWeb.Common.Button.update(button, existingText, false, false);
					}
					else if (data.passwordExpired)
					{
						displayWarningMessage(localization.passwordExpiredWarningMessageText);
						userNameTextBox.focus();

						CivicWeb.Common.Button.update(button, existingText, false, false);
					}
					else if (data.duplicateEmails)
					{
						displayWarningMessage(localization.notificationLoginDuplicateEmails);
						passwordTextBox.focus();

						CivicWeb.Common.Button.update(button, existingText, false, false);
					}
					else
					{
						displayWarningMessage(localization.invalidUserNameOrPasswordWarningMessageText);
						passwordTextBox.focus();

						CivicWeb.Common.Button.update(button, existingText, false, false);
					}
				}).fail(function ()
				{
					displayWarningMessage(localization.invalidUserNameOrPasswordWarningMessageText);
					passwordTextBox.focus();

					CivicWeb.Common.Button.update(button, existingText, false, false);
				});
			}
		}

		checkRendering();
	};

	var displayWarningMessage = function (text)
	{
		text = $.trim(text || '');

		var warningMessage = $(document.getElementById(signInWarningMessageClientId));
		warningMessage.parent().toggleClass('hidden', text.length === 0);
		if (text.length > 0)
		{
			CivicWeb.Common.Notification.show(warningMessage, CivicWeb.Common.Notification.types.warning, text, false);
		}
		else
		{
			CivicWeb.Common.Notification.hide(warningMessage);
		}
	};

	//Methods
	control.load = function (args)
	{
		showSignInPopupButton = args.signInButton && args.signInButton instanceof jQuery ?
			args.signInButton :
			(args.signInButton && args.signInButton instanceof HTMLElement ?
				$(args.signInButton) :
				(args.signInButton && args.signInButton.length ?
					$(document.getElementById(args.signInButton)) :
					null));

		localization = args.localization;

		var container = $(document.getElementById(signInClientId));
		isPopup = container.attr('data-popup') === 'True';
		showMarketing = container.find('.sign-in-marketing').length > 0;

		if (!isPopup)
		{
			showMarketingPage();
		}

		showSignInPopupButton.off('click').on('click', showSignInPopupButtonClick);

		if (!isPopup)
		{
			setFocus();

			if (/trident/.test(navigator.userAgent.toLowerCase()))
			{
				$(window).on('resize', checkRendering);
			}

			checkRendering();
		}
	};

	control.show = function ()
	{
		if (localization)
		{
			loadPopUp();
		}
		else
		{
			//Look for parent windows if the current sign in control is not loaded - Example: In a split-screen document that is inside an iframe
			var parent = window.parent;
			while (parent)
			{
				if (parent.CivicWeb && parent.CivicWeb.Common && parent.CivicWeb.Common.SignIn)
				{
					parent.CivicWeb.Common.SignIn.show();
					break;
				}
				else
				{
					parent = parent.parent;
				}
			}
		}
	};

	(function ()
	{
		$(document.getElementById(signInUserNameClientId)).add(document.getElementById(signInPasswordClientId)).on('keydown', signInTextBoxKeyDown);
		$(document.getElementById(signInButtonClientId)).on('click', signInButtonClick);

		initialize();
	})();
})(window.CivicWeb.Common.SignIn = window.CivicWeb.Common.SignIn || {}, jQuery);
;
window.CivicWeb = window.CivicWeb || {};
window.CivicWeb.Common = window.CivicWeb.Common || {};

(function (library, $)
{
	//Properties
	var reconnectCount = 0;
	var startPromise = $.Deferred();

	//Methods
	library.logAction = function (logType, userId, entityId, action)
	{
		try
		{
			if (localStorage && userId > 3)
			{
				var logName = logType + '-log';
				var userLog = JSON.parse(localStorage.getItem(logName));
				if (userLog)
				{
					userLog.push({ userId: userId, entityId: entityId, date: new Date().getTime(), action: action });
				}
				else
				{
					userLog = [{ userId: userId, entityId: entityId, date: new Date().getTime(), action: action }];
				}
				localStorage.setItem(logName, JSON.stringify(userLog));
			}
		}
		catch (err)
		{
		}
	};

	library.start = function ()
	{
		if ($.connection && $.connection.hub)
		{
			if ($.connection.hub.state === $.signalR.connectionState.disconnected)
			{
				startDone = function ()
				{
					reconnectCount = 0;

					startPromise.resolve();
				};
				$.connection.hub.start({ transport: ['webSockets', 'longPolling'] }).done(startDone);

				$.connection.hub.disconnected(function ()
				{
					if (reconnectCount < 10)
					{
						reconnectCount++;
						setTimeout(function ()
						{
							$.connection.hub.start().done(startDone);
						}, 3000); // Restart connection after 3 seconds.
					}
				});
			}
		}
		else
		{
			startPromise.reject('SignalR not loaded');
		}

		return startPromise;
	};
})(window.CivicWeb.Common.SignalR = window.CivicWeb.Common.SignalR || {}, window.jQuery);
;
// Declare namespaces
var CivicWeb = CivicWeb || {};
CivicWeb.Common = CivicWeb.Common || {};

//Create classes
CivicWeb.Common.SocialMediaShare = function (args)
{
	//Properties
	var clientId = args.clientId;

	var localization = args.localization;

	var url = args.url;
	var title = args.title;
	var itemId = args.itemId;
	var isFolder = args.isFolder || false;
	var show = args.show || false;
	var useBackgroundColor = 'undefined' === typeof args.useBackgroundColor || args.useBackgroundColor == null || args.useBackgroundColor;
	var fullWidth = args.fullWidth || false;
	var onEmail = args.onEmail;

	var expandedWith = '250px';
	var collapsedWidth = '24px';
	var expansionState = {
		collapsed: 'collapsed',
		expanded: 'expanded'
	};

	var toogleKeyDown = function (e) {
		if (e.which == 13 || e.which == 32) {
			toogle(e);
		}
	}

	//Methods
	var toogle = function (e)
	{
		var socialMediaContainer = $(e.target).closest('.social-media-share');
		if (socialMediaContainer.attr('data-state') === expansionState.expanded)
		{
			socialMediaContainer.stop().animate({ width: collapsedWidth }, 150, '', function ()
			{
				socialMediaContainer.find('.inner').removeClass('inner-active');
				socialMediaContainer.find('ul').removeClass('active').addClass('hidden');
			});
			socialMediaContainer.attr({ 'data-state': expansionState.collapsed });
		}
		else
		{
			socialMediaContainer.stop().animate(!fullWidth ? { width: expandedWith } : {}, 150, '', function ()
			{
				if (fullWidth)
				{
					socialMediaContainer.css({ 'width': 'auto' });
				}
				socialMediaContainer.find('.inner').addClass('inner-active');
				socialMediaContainer.find('ul').addClass('active').removeClass('hidden');
			});
			socialMediaContainer.attr({ 'data-state': expansionState.expanded });
		}
	};


	var socialMediaKeyDown = function (e) {
		if (e.which == 13 || e.which == 32) {
			toogle(e);
		}
	}

	var socialMediaClick = function (e)
	{
		var type = $(e.target).attr('data-type');
		var linkUrl = url != null && url.length > 0 ? url : window.location.href;
		linkUrl = encodeURIComponent(linkUrl);
		switch (type)
		{
			case 'email':
				if ('function' === typeof onEmail)
				{
					onEmail();
				}
				else
				{
					window.open('/eaengine/SendNotification.aspx?Type=FileProDocument&DocumentId=' + itemId + '&DocumentUrl=' + linkUrl, 'Notification', 'toolbar=0,location=0,directories=0,status=0,addressbar=0,menubar=0,scrollbars=0,resizable=1,width=750,height=600');
				}
				break;

			case 'facebook':
				var title = getTitle();
				window.open('http://www.facebook.com/share.php?u=' + linkUrl + '&caption=' + encodeURIComponent(title) + '&description=' + encodeURIComponent(title), '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=400,width=600');
				break;

			case 'twitter':
				window.open('https://twitter.com/intent/tweet?url=' + linkUrl, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=400,width=600');
				break;

			case 'linkedin':
				window.open('http://www.linkedin.com/shareArticle?mini=true&url=' + linkUrl, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=400,width=600');
				break;

			case 'link':
				var bookmarkPopup = $(document.getElementById('document-bookmark-window'));
				if (bookmarkPopup != null && bookmarkPopup.length)
				{
					bookmarkPopup.data('kendoWindow').destroy();
				}

				bookmarkPopup = $('<div></div>', { 'id': 'document-bookmark-window', 'class': 'document-bookmark-window hidden' }).append($('<ul></ul>')
					.append($('<li></li>')
						.append($('<input />', { 'id': 'document-list-link', 'type': 'radio', 'name': 'bookmark-link', 'data-url': '/filepro/documents/' + itemId, 'checked': true }))
						.append($('<label></label>', { 'for': 'document-list-link' }).text(isFolder ? localization.bookmarkDisplayRadioLabel : localization.bookmarkListRadioLabel))));
				if (!isFolder)
				{
					bookmarkPopup.find('ul').append($('<li></li>')
							.append($('<input />', { 'id': 'document-display-link', 'type': 'radio', 'name': 'bookmark-link', 'data-url': '/document/' + itemId }))
							.append($('<label></label>', { 'for': 'document-display-link' }).text(localization.bookmarkDisplayRadioLabel)));
				}
				bookmarkPopup.append($('<div></div>', { 'style': 'font-weight: bold; margin-top: 1em;' }).text(localization.copyLinkMessage + ":"));
				bookmarkPopup.append($('<input />', { 'type': 'text', 'id': 'document-bookmark-link', 'class': 'document-bookmark-link' }).val(location.protocol + '//' + location.hostname + '/filepro/documents/' + itemId).on('click', function ()
				{
					$(this).select();
				}));

				$('body').append(bookmarkPopup);

				$(document.getElementById('document-list-link')).attr('data-url', '/filepro/documents/' + itemId).off('click').on('click', function ()
				{
					$(document.getElementById('document-bookmark-link')).val(location.protocol + '//' + location.hostname + $(document.getElementById('document-list-link')).attr('data-url'));
				});
				$(document.getElementById('document-display-link')).attr('data-url', '/document/' + itemId).off('click').on('click', function ()
				{
					$(document.getElementById('document-bookmark-link')).val(location.protocol + '//' + location.hostname + $(document.getElementById('document-display-link')).attr('data-url'));
				});

				bookmarkPopup.kendoWindow({
					modal: false,
					visible: false,
					width: 400,
					close: function () { $(document.getElementById('document-bookmark-window')).data('kendoWindow').destroy(); $('iframe').removeClass('invisible'); }
				});

				//Hide pdf iframes
				$('iframe').filter(function ()
				{
					if ($(this).attr('src') != null && $(this).attr('src').indexOf('.pdf') > -1)
					{
						return $(this);
					}

					return null;
				}).addClass('invisible');
				bookmarkPopup.removeClass('hidden').css({ 'visibility': '' }).data('kendoWindow').center().open();
				bookmarkPopup.closest('.k-window').css({ 'z-index': '10011' });
				break;
		}

		return false;
	};

	this.SetUrl = function (linkUrl)
	{
		url = linkUrl;
	};

	var getTitle = function ()
	{
		return (typeof title === 'function' ? title() : (typeof title === 'string' ? title : '')) || '';
	};

	var initializeSocialMedia = function () {
		$(document.getElementById(clientId)).find('ul').addClass('hidden');
		$(document.getElementById(clientId)).off('click').on('click', toogle).on('keydown', toogleKeyDown);
		$(document.getElementById(clientId)).find('a').off('click').on('click', socialMediaClick).on('keydown', socialMediaKeyDown);
	};

	(function ()
	{
		initializeSocialMedia();

		var container = $(document.getElementById(clientId)).closest('.social-media-share');
		if (show)
		{
			container.removeClass('hidden');
		}
		if (!useBackgroundColor)
		{
			container.removeClass('background-color');
		}
	})();
};

//Objects
CivicWeb.Common.SocialMediaShares = {
	//Properties
	instances: new Array(),

	//Methods
	getInstance: function (clientId)
	{
		var found = null;
		for (var index = 0; index < this.instances.length; index++)
		{
			var current = this.instances[index];
			if (current.clientId === clientId)
			{
				found = current;
				break;
			}
		}

		return found;
	},

	getIndex: function ()
	{
		var index = 0;

		return index >= this.instances.length ? -1 : index;
	},

	createInstance: function (args)
	{
		var instance = this.getInstance(args.clientId);
		var index = this.getIndex(args.clientId);
		if (instance)
		{
			delete instance;
		}
		if (index < 0)
		{
			index = this.instances.length;
		}
		this.instances[index] = new CivicWeb.Common.SocialMediaShare(args);
	},

	//Events
	events: {
	}
};
;
window.CivicWeb = window.CivicWeb || {};
window.CivicWeb.Common = window.CivicWeb.Common || {};

(function (library, $)
{
	//Event Handlers
	var headingClick = function (e)
	{
		var heading = $(e.target).closest('a');
		var expand = heading.attr('aria-expanded') !== 'true';

		heading.find('.glyphicon').toggleClass('glyphicon-triangle-right', !expand).toggleClass('glyphicon-triangle-bottom', expand);
		heading.attr({ 'aria-expanded': expand });
		var body = heading.closest('.toggle-panel').find('.toggle-panel-body').toggleClass('hidden', !expand);

		e.panelData = {
			heading: heading,
			body: body,
			expanded: expand
		};

		e.preventDefault();
	};

	//Functions
	var doAccordianCollapse = function (panels, openPanel)
	{
		var openPanelClientId = openPanel ? openPanel.attr('id') : '';
		
		panels
			.forEach(function (panel)
			{
				var expand = panel === openPanelClientId;

				panel = CivicWeb.Common.getJqueryObject(panel).closest('.toggle-panel');

				panel.find('.toggle-panel-heading a').attr({ 'aria-expanded': expand }).find('.glyphicon').toggleClass('glyphicon-triangle-right', !expand).toggleClass('glyphicon-triangle-bottom', expand);
				panel.find('.toggle-panel-body').toggleClass('hidden', !expand);
			});
	};

	//Methods
	library.create = function (panels, args)
	{
		panels = CivicWeb.Common.forceArray(panels);
		args = args || {};

		var headingClickWithOptions = function (e)
		{
			headingClick(e);

			if (args.accordian)
			{
				doAccordianCollapse(panels, e.panelData.expanded ? e.panelData.body : undefined);
			}

			if ('function' === typeof args.toggle)
			{
				args.toggle(e);
			}
		};

		panels
			.map(function (panel)
			{
				return CivicWeb.Common.getJqueryObject(panel).closest('.toggle-panel');
			})
			.forEach(function (panel)
			{
				var heading = panel.find('.toggle-panel-heading a').off('click').on('click', headingClickWithOptions);
				var expanded = heading.attr('aria-expanded') === 'true';
				panel.find('.toggle-panel-body').toggleClass('hidden', !expanded);
			});
	};

	library.show = function (panel)
	{
		var heading = CivicWeb.Common.getJqueryObject(panel).closest('.toggle-panel').find('.toggle-panel-heading').find('a');
		var expanded = heading.attr('aria-expanded') === 'true';
		if (!expanded)
		{
			heading.click();
		}
	};
})(window.CivicWeb.Common.TogglePanel = window.CivicWeb.Common.TogglePanel || {}, jQuery);
;
window.CivicWeb = window.CivicWeb || {};
window.CivicWeb.Common = window.CivicWeb.Common || {};

(function (library, $)
{
	var controls = [];
	var localization = {};

	//Functions
	var findControl = function (id, createIfNotFound)
	{
		var control = controls.find(function (element)
		{
			return element.id === id;
		});

		if (!control && createIfNotFound)
		{
			controls.push(control = { id: id });
		}

		return control;
	};

	var createTokenPopup = function (control, button, textBox)
	{
		if (!control.popup)
		{
			$('body')
				.append(control.popup = $('<div></div>').attr({ 'class': 'token-popup', 'data-type': 'token-popup', 'data-for': textBox.attr('id') }).off('click', popupInternalClick).on('click', popupInternalClick)
					.append($('<div></div>')
						.append($('<em></em>').attr({ 'class': 'icon-remove', 'title': localization.toolTipClose }).off('click').on('click', popupExternalClick))));

			control.placeholders.forEach(function (currentValue)
			{
				control.popup.append($('<div></div>')
					.append($('<button></button>').css({ 'text-align': 'left' }).attr({ 'data-for': control.id, 'data-token': currentValue.token }).text(currentValue.text).off('click').on('click', appendTokenButtonClick)));
			});
		}

		var buttonOffset = button.offset();
		control.popup.removeClass('hidden').css({ 'top': '', 'left': '', 'right': '', 'bottom': '', 'visibility': 'hidden' });
		var popupWidth = control.popup.outerWidth();
		var popupHeight = control.popup.outerHeight();
		control.popup.css({ 'visibility': '' }).css((buttonOffset.top + popupHeight >= ($(window).height() - 10)) ? { 'bottom': '1em' } : { 'top': (buttonOffset.top + button.outerHeight()).toString() + 'px' }).css((buttonOffset.left + popupWidth >= ($(window).width() - 10)) ? { 'right': '1em' } : { 'left': buttonOffset.left.toString() + 'px' });
	};

	//Event Handlers
	var popupExternalClick = function ()
	{
		closePopup();
	};

	var addTokenButtonClick = function (e)
	{
		var button = $(e.target).closest('button');
		var textBox = $(document.getElementById(button.attr('data-for')));
		var control = findControl(button.attr('id'));

		if (textBox.is('input'))
		{
			control.cursorStartPosition = textBox.get(0).selectionStart;
			control.cursorEndPosition = textBox.get(0).selectionEnd;
		}

		createTokenPopup(control, button, textBox);

		e.stopPropagation();
		e.preventDefault();
	};

	var popupInternalClick = function (e)
	{
		e.stopPropagation();
	};

	var appendTokenButtonClick = function (e)
	{
		var button = $(e.target).closest('button');
		var control = findControl(button.attr('data-for'));
		var textBox = $(document.getElementById(control.popup.attr('data-for')));

		if (control.cursorStartPosition && control.cursorEndPosition)
		{
			var textLeft = textBox.val().substring(0, control.cursorStartPosition);
			var textRight = textBox.val().substring(control.cursorEndPosition, textBox.val().length);

			//Remove {} if only the token word was selected
			textLeft = textLeft.charAt(textLeft.length - 1) === '{' ? textLeft.slice(0, -1) : textLeft;
			textRight = textRight.charAt(0) === '}' ? textRight.slice(1) : textRight;

			textBox.val(textLeft + $(e.target).closest('button').attr('data-token') + textRight);
			document.getElementById(control.popup.attr('data-for')).selectionStart = document.getElementById(control.popup.attr('data-for')).selectionEnd = control.cursorStartPosition = control.cursorEndPosition = (control.cursorEndPosition + $(e.target).closest('button').attr('data-token').length + 1);
		}
		else
		{
			if (textBox.is('input'))
			{
				textBox.val(textBox.val() + $(e.target).closest('button').attr('data-token'));
			}
			else if (textBox.data('kendoEditor'))
			{
				textBox.data('kendoEditor').exec('insertHtml', { split: false, html: $(e.target).closest('button').attr('data-token') });
			}
		}

		textBox.change();

		if (control.closeAfterSelection)
		{
			closePopup();
		}

		e.preventDefault();
	};

	//Function
	var closePopup = function ()
	{
		$('div.token-popup[data-type="token-popup"]').addClass('hidden');
	};

	//Methods
	library.load = function (args)
	{
		localization = args.localization;

		var control = findControl(args.id, true);

		control.placeholders = args.placeholders;
		control.closeAfterSelection = !!args.closeAfterSelection;
		control.cursorStartPosition = 0;
		control.cursorEndPosition = 0;
		control.popup = null;		

		$(document.getElementById(control.id)).off('click', addTokenButtonClick).on('click', addTokenButtonClick);
	};

	(function ()
	{
		$('body').off('click', popupExternalClick).on('click', popupExternalClick);
	})();
})(window.CivicWeb.Common.Token = window.CivicWeb.Common.Token || {}, jQuery);
;
// Declare namespaces
var CivicWeb = CivicWeb || {};
CivicWeb.Common = CivicWeb.Common || {};
CivicWeb.Common.Validation = CivicWeb.Common.Validation || {};

//Create Functions
CivicWeb.Common.Validation.isEmailAddress = function (emailAddress)
{
	return emailAddress && 'string' === typeof emailAddress && emailAddress.length > 0 && /^(-|&|'|\+|\w)+(\.(-|&|'|\+|\w)+)*\@(-|\w)+(\.(-|\w)+)+$/i.test(emailAddress);
};

CivicWeb.Common.Validation.isNumeric = function (numericValue, emptyAllowed)
{
	return numericValue != null && 'string' === typeof numericValue && ((numericValue.length === 0 && !!emptyAllowed) || (numericValue.length > 0 && /^\d+$/i.test(numericValue)));
};
;
// Declare namespaces
var CivicWeb = CivicWeb || {};
CivicWeb.Common = CivicWeb.Common || {};

(function (page, $) {
	//Properties
	var workflowExportActionPdf = 'export-action-pdf';
	var workflowExportActionHtml = 'export-action-html';
	var workflowExportActionAttachments = 'export-action-attachments';
	var workflowExportToMeetingtypeClientId = 'workflow-export-to-meetingtype';
	var workflowExportToMeetingClientId = 'workflow-export-to-meeting';
	var workflowExportToHeadingClientId = 'workflow-export-to-heading';
	var availableItemsClientId = 'available-';
	var selectedItemsClientId = 'selected-';
	var addItemsButtonClientId = '-add-button';
	var removeItemsButtonClientId = '-remove-button';

	var currentUserId;
	var localization;
	var enabled;
	var canEdit;
	var itemId;
	var meetingId;
	var outputType;
	var workflowTemplates;
	var submitCallback;
	var cancelCallback;
	var defaultWorkflowData = {
		id: 0,
		templateId: 0,
		status: { id: 0, label: '' },
		submittedBy: '',
		submittedDate: '',
		actions: { export: false, republish: false, exportPdf: false, exportHtml: false, exportAttachments: false },
		exportTo: { meetingTypeId: 0, meetingId: 0, headingId: 0 },
		notification: { subject: '', body: '' },
		updateNotification: {
			sentOn: { notifyOnComment: false, notifyOnSubmitted: false, notifyPerApproval: false },
			users: [],
			selectedUsers: [],
			selectedCustomEmails: []
		},
		workflowHtml: '',
		canCustomize: false
	};
	var workflowData = $.extend(true, {}, defaultWorkflowData);

	var commentTextAreaHeight = 100;
	var textAreaExpanderLoaded = false;
	var isMobile = (/android|webos|iphone|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent.toLowerCase())) ||
		window.matchMedia('only screen and (max-width: 320px), (max-device-width: 320px), (max-width: 481px), (max-device-width: 481px), (max-width: 768px)').matches;

	var images = {
		groupImageUrl: 'cw-icon-users-lg',
		userImageUrl: 'cw-icon-user-lg',
		expandImageUrl: 'cw-icon-node-open',
		collapseImageUrl: 'cw-icon-node-close'
	};

	var schemaTypes = {
		groups: 'groups',
		users: 'users'
	};

	var listSchemas = {
		users: {
		}
	};

	//Event Handlers
	var submitClick = function (e) {
		if (canEdit && checkApprovalValid()) {
			updateWorkflowValues();
			var data = {
				notificationSubject: workflowData.notification.subject,
				notificationBody: workflowData.notification.body,
				selectedUsers: workflowData.updateNotification.selectedUsers,
				selectedCustomEmails: workflowData.updateNotification.selectedCustomEmails,
				exportHeadingId: workflowData.exportTo.headingId
			};

			var button = $(this);
			var existingText = CivicWeb.Common.Button.update(button, localization.buttonSubmitting, true, true);
			$.ajax({
				url: '/api/workflow/' + workflowData.id + '/submit?templateId=' + workflowData.templateId + '&itemId=' + itemId + '&meetingId=' + meetingId + '&outputType=' + outputType,
				contentType: 'application/json', dataType: 'json', async: true, cache: false, type: 'POST', data: JSON.stringify(data),
				success: function (response) {
					if (response.Result) {
						$(document.getElementById('workflow-status-value')).text(response.StatusLabel);
						$(document.getElementById('workflow-submittedby-value')).text(response.SubmittedBy);
						$(document.getElementById('workflow-submitted-date-value')).text(response.SubmittedDate);
						$(document.getElementById('workflow')).empty();
						$(document.getElementById('workflow')).append(response.WorkflowHtml);
						workflowData.id = response.WorkflowId;
						setWorkflowStatus(response.Status);

						reAlign();

						if (typeof submitCallback == 'function') {
							submitCallback(response);
						}
					}
					CivicWeb.Common.Button.update(button, existingText, false, false);
				},
				error: function (response) {
					CivicWeb.Common.Button.update(button, existingText, false, false);
				}
			});
		}
	};

	var cancelClick = function (e) {
		if (canEdit) {
			var button = $(this);
			var existingText = CivicWeb.Common.Button.update(button, localization.buttonCanceling, true, true);
			$.ajax({
				url: '/api/workflow/' + workflowData.id + '/cancel?itemId=' + itemId + '&meetingId=' + meetingId + '&outputType=' + outputType,
				contentType: 'application/json', dataType: 'json', async: true, cache: false, type: 'POST',
				success: function (response) {
					if (response.Result) {
						$(document.getElementById('workflow-status-value')).text(response.StatusLabel);
						$(document.getElementById('workflow-submittedby-value')).text('');
						$(document.getElementById('workflow-submitted-date-value')).text('');
						$(document.getElementById('workflow')).empty();
						$(document.getElementById('workflow')).append(response.WorkflowHtml);
						setWorkflowStatus(response.Status);

						reAlign();

						if (typeof cancelCallback == 'function') {
							cancelCallback(response);
						}
					}
					CivicWeb.Common.Button.update(button, existingText, false, false);
				},
				error: function (response) {
					CivicWeb.Common.Button.update(button, existingText, false, false);
				}
			});
		}
	};

	var workflowTemplateChange = function (e) {
		var selectedWorkflowTemplateId = $(document.getElementById('workflow-tempaltes')).val();
		if (selectedWorkflowTemplateId > 0) {
			$(document.getElementById('workflow-actions-container')).removeClass('hidden');
			$(document.getElementById('workflow-container')).removeClass('hidden');
			$.ajax({
				url: '/api/workflow/' + selectedWorkflowTemplateId + '/template?itemId=' + itemId + '&meetingId=' + meetingId + '&outputType=' + outputType,
				contentType: 'application/json', dataType: 'json', async: true, cache: false, type: 'GET',
				success: function (response) {
					if (response) {
						workflowData = $.extend(true, {}, defaultWorkflowData);
						$.extend(workflowData, response);
						loadWorkflow();
					}
				},
				error: function (response) {
				}
			});
		}
		else {
			$(document.getElementById('workflow-actions-container')).addClass('hidden');
			$(document.getElementById('workflow-container')).addClass('hidden');
		}
	};

	var exportToMeetingTypeChange = function (e) {
		var selectedMeetingTypeId = $(document.getElementById(workflowExportToMeetingtypeClientId)).val();
		if (selectedMeetingTypeId > 0) {
			loadMeetings(selectedMeetingTypeId, updateFormMeetingValues);
		}
	};

	var exportToMeetingChange = function (e) {
		var selectedMeetingId = $(document.getElementById(workflowExportToMeetingClientId)).val();
		if (selectedMeetingId > 0) {
			loadHeadings(selectedMeetingId, updateFormMeetingValues);
		}
	};

	var exportToHeadingChange = function () {
		updateFormMeetingValues();
	};

	var customEmailListItemClick = function (e) {
		var listItem = $(this);
		var itemSelected = listItem.hasClass('list-item-selected');
		if (!itemSelected) {
			listItem.addClass('list-item-selected');
		}
		else {
			listItem.removeClass('list-item-selected');
		}
	};

	var addExternalEmailClick = function (e) {
		var customEmail = $(document.getElementById('custom-emailto')).val();
		if (customEmail && customEmail.length && CivicWeb.Common.Validation.isEmailAddress(customEmail)) {
			addCustomEmailToSelected(customEmail);
			$(document.getElementById('custom-emailto')).val('');
		}

		e.preventDefault();
	};

	var customizeWorkflowClick = function (e) {
		if (workflowData.id > 0) {
			var button = $(this);
			var existingText = CivicWeb.Common.Button.update(button, localization.labelProcessing, true, true);
			if (workflowData.id == workflowData.templateId) {
				saveWorkflow(function () {
					CivicWeb.Common.Button.update(button, existingText, false, false);
					window.location.href = '/workflow/' + workflowData.id + '?' + (itemId > 0 ? 'ItemDetailId=' + itemId : 'MeetingId=' + meetingId + '&MeetingOutputType=' + outputType);
				});
			}
			else {
				CivicWeb.Common.Button.update(button, existingText, false, false);
				window.location.href = '/workflow/' + workflowData.id + '?' + (itemId > 0 ? 'ItemDetailId=' + itemId : 'MeetingId=' + meetingId + '&MeetingOutputType=' + outputType);
			}
		}
	};

	//Functions
	var saveWorkflow = function (callback) {
		if (canEdit) {
			updateWorkflowValues();
			var data = {
				notificationSubject: workflowData.notification.subject,
				notificationBody: workflowData.notification.body,
				selectedUsers: workflowData.updateNotification.selectedUsers,
				selectedCustomEmails: workflowData.updateNotification.selectedCustomEmails,
				exportHeadingId: workflowData.exportTo.headingId
			};
			$.ajax({
				url: '/api/workflow/' + workflowData.id + '/saveassignworkflow?templateId=' + workflowData.templateId + '&itemId=' + itemId + '&meetingId=' + meetingId + '&outputType=' + outputType,
				contentType: 'application/json', dataType: 'json', async: true, cache: false, type: 'POST', data: JSON.stringify(data),
				success: function (response) {
					workflowData = $.extend(true, {}, defaultWorkflowData);
					$.extend(workflowData, response);

					if (workflowData.notification.subject != $(document.getElementById('workflow-notification-subject')).val()) {
						$(document.getElementById('workflow-notification-subject')).val(workflowData.notification.subject);
					}

					if (typeof callback == 'function') {
						callback();
					}
				},
				error: function (response) {
				}
			});
		}
	};

	var loadWorkflowTemplates = function () {
		for (var i = 0; i < workflowTemplates.length; i++) {
			var workflowTemplate = workflowTemplates[i];
			if (workflowTemplate) {
				$(document.getElementById('workflow-tempaltes')).append($('<option>', { 'value': workflowTemplate.id }).text(workflowTemplate.name));
			}
		}

		if (workflowData.templateId > 0) {
			$(document.getElementById('workflow-tempaltes')).val(workflowData.templateId);
		}
	};

	var loadWorkflow = function () {
		if (workflowData.id > 0) {
			$(document.getElementById('workflow-status-value')).text(workflowData.status.label);
			$(document.getElementById('workflow-submittedby-value')).text(workflowData.submittedBy);
			$(document.getElementById('workflow-submitted-date-value')).text(workflowData.submittedDate);
			$(document.getElementById('workflow')).empty();
			$(document.getElementById('workflow')).append(workflowData.workflowHtml);

			$(document.getElementById('actions-after-approval')).addClass('hidden');
			$(document.getElementById('republish-action')).addClass('hidden');
			$(document.getElementById('export-action')).addClass('hidden');
			$(document.getElementById('export-container')).addClass('hidden');
			if (workflowData.actions.republish) {
				$(document.getElementById('actions-after-approval')).removeClass('hidden');
				$(document.getElementById('republish-action')).removeClass('hidden');
			}
			if (workflowData.actions.export) {
				$(document.getElementById('actions-after-approval')).removeClass('hidden');
				$(document.getElementById('export-action')).removeClass('hidden');
				$(document.getElementById('export-container')).removeClass('hidden');
			}

			$(document.getElementById(workflowExportActionPdf)).toggleClass('hidden', !workflowData.actions.exportPdf);
			$(document.getElementById(workflowExportActionHtml)).toggleClass('hidden', !workflowData.actions.exportHtml);
			$(document.getElementById(workflowExportActionAttachments)).toggleClass('hidden', !workflowData.actions.exportAttachments);

			if (!textAreaExpanderLoaded) {
				loadTextExpander(initializeWorkflowEvents);
			}
			else {
				reAlign();
			}
		}
		else {
			$(document.getElementById('workflow-actions-container')).addClass('hidden');
			$(document.getElementById('workflow-container')).addClass('hidden');
		}

		loadActionsAfterApproval();
		loadApproverNotifications();
		loadUpdateNotifications();

		setWorkflowStatus(workflowData.status.id);
	};

	var loadActionsAfterApproval = function () {
		if (workflowData.exportTo != null && workflowData.exportTo.headingId > 0) {
			$(document.getElementById(workflowExportToMeetingtypeClientId)).val(workflowData.exportTo.meetingTypeId);
			loadMeetings(workflowData.exportTo.meetingTypeId, function () {
				$(document.getElementById(workflowExportToMeetingClientId)).val(workflowData.exportTo.meetingId);
				loadHeadings(workflowData.exportTo.meetingId, function () {
					$(document.getElementById(workflowExportToHeadingClientId)).val(workflowData.exportTo.headingId);
				});
			});
		}
	};

	var loadApproverNotifications = function () {
		if (workflowData.notification != null) {
			$(document.getElementById('workflow-notification-subject')).val(workflowData.notification.subject);
			$(document.getElementById('workflow-notification-body')).val(workflowData.notification.body);
		}
	};

	var loadUpdateNotifications = function () {
		if (workflowData.updateNotification != null) {
			if (workflowData.updateNotification.sentOn != null) {
				$(document.getElementById('notify-comment')).toggleClass('hidden', !workflowData.updateNotification.sentOn.notifyOnComment);
				$(document.getElementById('notify-submitted')).toggleClass('hidden', !workflowData.updateNotification.sentOn.notifyOnSubmitted);
				$(document.getElementById('notify-approve')).toggleClass('hidden', !workflowData.updateNotification.sentOn.notifyPerApproval);
			}

			listSchemas.users = {
				items: workflowData.updateNotification.users,
				selectedIds: workflowData.updateNotification.selectedUsers,
				type: schemaTypes.users,
				id: 'id',
				name: 'name',
				deleted: 'deleted',
				selected: 'selected',
				prefix: 'U',
				subCollections: [],
				imageUrl: images.userImageUrl,
				toolTip: localization.toolTipUser,
				noSubItemsExistText: '',
				load: true,
				sort: function (a, b) {
					var nameA = a ? a.name.toLowerCase() : '';
					var nameB = b ? b.name.toLowerCase() : '';
					var publicA = a ? a.isPublic : false;
					var publicB = b ? b.isPublic : false;

					return (publicA === publicB && nameA < nameB) || (publicA && !publicB) ? -1 : ((publicA === publicB && nameA > nameB) || (!publicA && publicB) ? 1 : 0);
				},
				filter: function (item) {
					return item && !item.isPublic && !item.administrator && !item.systemAdministrator;
				},
				lastSelection: {
					available: null,
					selected: null
				},
				controlIds: {
					available: availableItemsClientId + schemaTypes.users,
					selected: selectedItemsClientId + schemaTypes.users,
					addButton: schemaTypes.users + addItemsButtonClientId,
					removeButton: schemaTypes.users + removeItemsButtonClientId
				}
			};

			CivicWeb.Common.ListBoxes.createInstance({ clientId: 'workflow', schemas: listSchemas, enabled: true });

			for (var i = 0; i < workflowData.updateNotification.selectedCustomEmails.length; i++) {
				var customEmail = workflowData.updateNotification.selectedCustomEmails[i];
				addCustomEmailToSelected(customEmail);
			}

			addCurrentUserUpdateNotifications();

			$(document.getElementById('workflow-notifications-users')).find('#available-users').css({ 'height': '15.5em' }).after($(document.getElementById('workflow-update-notifications-external-email')));
		}
	};

	var loadMeetings = function (id, callback) {
		if (id > 0) {
			var date = new Date();
			date.setMonth(date.getMonth() - 1);
			$.ajax({
				url: '/api/meetings/filteredlist?meetingtypeid=' + id + '&from=' + (encodeURIComponent(date.toDateString())),
				contentType: 'application/json', dataType: 'json', async: true, cache: false, type: 'GET',
				success: function (response) {
					if (response.Meetings) {
						$(document.getElementById(workflowExportToMeetingClientId)).find('option:not([value=0])').remove();
						$(document.getElementById(workflowExportToHeadingClientId)).val(0);
						for (var i = 0; i < response.Meetings.length; i++) {
							var meeting = response.Meetings[i];
							$(document.getElementById(workflowExportToMeetingClientId)).append($('<option>', { 'value': meeting.MeetingId }).text(meeting.Name));
						}

						if (callback) {
							callback();
						}
					}
				},
				error: function (response) {
				}
			});
		}
	};

	var loadHeadings = function (id, callback) {
		if (id > 0) {
			$.ajax({
				url: '/api/meeting/' + id + '/headings/',
				contentType: 'application/json', dataType: 'json', async: true, cache: false, type: 'GET',
				success: function (response) {
					if (response) {
						$(document.getElementById(workflowExportToHeadingClientId)).find('option:not([value=0])').remove();
						for (var i = 0; i < response.length; i++) {
							var heading = response[i];
							$(document.getElementById(workflowExportToHeadingClientId)).append($('<option>', { 'value': heading.id }).text(heading.description));
						}

						if (callback) {
							callback();
						}
					}
				},
				error: function (response) {
				}
			});
		}
	};

	var setWorkflowStatus = function (status) {
		switch (status) {
			case 0://none
			case 1://draft
				$(document.getElementById('workflow-tempaltes')).removeAttr('disabled');
				$(document.getElementById('workflow-status-value')).attr('class', 'label label-primary');
				$(document.getElementById('workflow-submittedby')).addClass('hidden');
				$(document.getElementById('workflow-submitted-date')).addClass('hidden');

				$(document.getElementById('workflow-submit')).addClass('hidden');
				$(document.getElementById('workflow-resubmit')).addClass('hidden');
				$(document.getElementById('workflow-cancel')).addClass('hidden');

				if (canEdit) {
					$(document.getElementById('workflow-submit')).removeClass('hidden');
				}

				$(document.getElementById(workflowExportToMeetingtypeClientId)).removeAttr('disabled');
				$(document.getElementById(workflowExportToMeetingClientId)).removeAttr('disabled');
				$(document.getElementById(workflowExportToHeadingClientId)).removeAttr('disabled');

				$(document.getElementById('workflow-approver-notifications')).removeClass('hidden');

				$(document.getElementById('workflow-approval-message')).text('');
				break;
			case 2://pending
				$(document.getElementById('workflow-tempaltes')).attr('disabled', 'disabled');

				$(document.getElementById('workflow-status-value')).attr('class', 'label label-default');
				$(document.getElementById('workflow-submittedby')).removeClass('hidden');
				$(document.getElementById('workflow-submitted-date')).removeClass('hidden');

				$(document.getElementById('workflow-submit')).addClass('hidden');
				$(document.getElementById('workflow-resubmit')).addClass('hidden');
				$(document.getElementById('workflow-cancel')).addClass('hidden');
				if (canEdit) {
					$(document.getElementById('workflow-cancel')).removeClass('hidden');
				}

				$(document.getElementById(workflowExportToMeetingtypeClientId)).attr('disabled', 'disabled');
				$(document.getElementById(workflowExportToMeetingClientId)).attr('disabled', 'disabled');
				$(document.getElementById(workflowExportToHeadingClientId)).attr('disabled', 'disabled');

				$(document.getElementById('workflow-approver-notifications')).addClass('hidden');

				$(document.getElementById('workflow-approval-message')).text('');
				break;
			case 3://approved
				$(document.getElementById('workflow-tempaltes')).attr('disabled', 'disabled');
				$(document.getElementById('workflow-status-value')).attr('class', 'label label-success');

				$(document.getElementById('customize-workflow')).addClass('hidden');
				$(document.getElementById('workflow-submit')).addClass('hidden');
				$(document.getElementById('workflow-resubmit')).addClass('hidden');
				$(document.getElementById('workflow-cancel')).addClass('hidden');
				if (canEdit) {
					$(document.getElementById('workflow-cancel')).removeClass('hidden');
				}

				$(document.getElementById('actions-after-approval')).addClass('hidden');
				$(document.getElementById('workflow-approver-notifications')).addClass('hidden');
				$(document.getElementById('workflow-update-notifications')).addClass('hidden');

				$(document.getElementById('workflow-approval-message')).text(localization.notficationThisItemHasBeenApproved);
				break;
			case 4://denied
				$(document.getElementById('workflow-tempaltes')).removeAttr('disabled');
				$(document.getElementById('workflow-status-value')).attr('class', 'label label-danger');
				$(document.getElementById('workflow-submittedby')).removeClass('hidden');
				$(document.getElementById('workflow-submitted-date')).removeClass('hidden');

				$(document.getElementById('workflow-submit')).addClass('hidden');
				$(document.getElementById('workflow-resubmit')).addClass('hidden');
				$(document.getElementById('workflow-cancel')).addClass('hidden');
				if (canEdit) {
					$(document.getElementById('workflow-resubmit')).removeClass('hidden');
					$(document.getElementById('workflow-cancel')).removeClass('hidden');
				}

				$(document.getElementById(workflowExportToMeetingtypeClientId)).removeAttr('disabled');
				$(document.getElementById(workflowExportToMeetingClientId)).removeAttr('disabled');
				$(document.getElementById(workflowExportToHeadingClientId)).removeAttr('disabled');

				$(document.getElementById('workflow-approver-notifications')).removeClass('hidden');

				$(document.getElementById('workflow-approval-message')).text('');
				break;
		}
	};

	var updateWorkflowValues = function () {
		workflowData.notification.subject = $(document.getElementById('workflow-notification-subject')).val();
		workflowData.notification.body = $(document.getElementById('workflow-notification-body')).val();
		var selectedUsers = [];
		var selectedUsersListItems = $(document.getElementById('workflow-notifications-users')).find('#selected-users > li[data-type="users"]');
		for (var i = 0; i < selectedUsersListItems.length; i++) {
			var selectedUser = selectedUsersListItems[i];
			selectedUsers.push($(selectedUser).attr('data-id'));
		}
		workflowData.updateNotification.selectedUsers = selectedUsers;
		var selectedCustomEmails = [];
		var selectedCustomEmailListItems = $(document.getElementById('workflow-notifications-users')).find('#selected-users > li[data-type="custom-email"]');
		for (var j = 0; j < selectedCustomEmailListItems.length; j++) {
			var selectedCustomEmail = selectedCustomEmailListItems[j];
			selectedCustomEmails.push($(selectedCustomEmail).attr('data-id'));
		}
		workflowData.updateNotification.selectedCustomEmails = selectedCustomEmails;
		workflowData.exportTo.headingId = $(document.getElementById(workflowExportToHeadingClientId)).val();
	};

	var addCustomEmailToSelected = function (customEmail) {
		var customEmailLi = $('<li>', { 'data-id': customEmail, 'data-path': 'U0', 'data-type': 'custom-email', 'class': 'ui-draggable' }).on('click', customEmailListItemClick)
			.append($('<div>').append($('<span>', { 'class': 'cw-icon-mail' }).css({ 'margin': '5px' })).append($('<span>').text(customEmail)));

		$(document.getElementById('workflow-notifications-users')).find('#selected-users').append(customEmailLi);
	};

	var saveComment = function (blockId, comment) {
		if (workflowData && workflowData.id > 0 && workflowData.id != workflowData.templateId) {
			var saveButton = $('input#' + blockId);
			if (saveButton && saveButton.length) {
				saveButton.attr('disabled', 'disabled').val(localization.buttonSaving);
			}
			var id = itemId > 0 ? itemId : meetingId;
			var workflowId = workflowData.id;
			var outputType = workflowData.outputType;
			var data = {
				'comment': comment
			};

			$.ajax({
				url: '/api/workflow/comment/' + id + '/' + workflowId + '/' + blockId + '/' + (meetingId > 0 == 'meeting' ? outputType : 0),
				contentType: 'application/json', dataType: 'json', async: true, cache: false, type: 'POST', data: JSON.stringify(data),
				success: function (response) {
					if (saveButton && saveButton.length) {
						saveButton.val(localization.buttonSaved);
						saveButton.removeAttr('disabled');
						setTimeout(function () {
							saveButton.val(localization.buttonSave);
						}, 1500);
					}
				},
				error: function (response) {
					if (saveButton && saveButton.length) {
						saveButton.removeAttr('disabled');
						saveButton.val(localization.buttonSave);
					}
				}
			});
		}
	};

	var checkApprovalValid = function () {
		CivicWeb.Common.Notification.hide($(document.getElementById('actions-after-approval-notification')));
		if (workflowData.actions.export && $(document.getElementById(workflowExportToHeadingClientId)).val() == 0) {
			CivicWeb.Common.Notification.show($(document.getElementById('actions-after-approval-notification')), CivicWeb.Common.Notification.types.warning);
			return false;
		}

		return true;
	};

	var addCurrentUserUpdateNotifications = function () {
		var selectedUserLi = $(document.getElementById('workflow-notifications-users')).find('ol#selected-users > li');
		var currentUserAdded = false;
		$.each(selectedUserLi, function (index, userLi) {
			if ($(userLi).attr('data-id') == currentUserId) {
				currentUserAdded = true;
			}
		});

		if (!currentUserAdded) {
			var currentUserLi = $(document.getElementById('workflow-notifications-users')).find('ol#available-users > li[data-id=' + currentUserId + ']');
			if (currentUserLi && currentUserLi.length) {
				$(document.getElementById('workflow-notifications-users')).find('ol#selected-users').prepend(currentUserLi);
			}
		}
	};

	var updateFormMeetingValues = function () {
		CivicWeb.Common.Forms.setMeetingValues(
			undefined,
			CivicWeb.Common.toNumber($(document.getElementById(workflowExportToMeetingtypeClientId)).val()),
			CivicWeb.Common.toNumber($(document.getElementById(workflowExportToMeetingClientId)).val()),
			CivicWeb.Common.toNumber($(document.getElementById(workflowExportToHeadingClientId)).val()));
	};

	//Workflow functions
	var resizeCommentTextArea = function (i) {
		var difference = i.height() - commentTextAreaHeight;
		if (difference > 0) {
			i.parent().parent().parent().height(i.parent().parent().parent().height() + difference);
			i.parent().parent().parent().parent().height(i.parent().parent().parent().parent().height() + difference);
			commentTextAreaHeight = i.height();
		}
	};

	var reAlign = function () {
		$('#workflow').children().each(function () {
			$(this).stackedDivs();
		});
	};

	var checkCommentAndSecurityWarning = function () {
		var haveUserComments;
		var workFlowTierCollection = $('#workflow').children();
		workFlowTierCollection.children().each(function () {

			haveUserComments = $(this).children().children().children().hasClass("CommentImg");
			var haveUserSecurityWarning = $(this).children().children().children().hasClass("WarningImg");
			if (haveUserComments) {
				$(this).children(".CommentImg").css("display", "block");
			}
			if (haveUserSecurityWarning) {
				$(this).children(".WarningImg").css("display", "block");
			}
		});
	};

	var saveComments = function () {
		$(".SaveComment").each(function () {
			var comment = $(this).parent().siblings(".CommentTextArea").val();
			var blockId = this.id;
			saveComment(blockId, comment);
		});
	};

	$.fn.stackedDivs = function (options) {
		var settings = $.extend({
			left: 5,
			down: 24,
			width: 300,
			css: true,
			speed: 200,
			scrunch: true,
			margin: 12,
			visual: 'scoot'
		}, options),
			kids = this.children();

		function posFor(i) {
			return {
				top: (kids.length - i - 1) * settings.down,
				left: i * settings.left,
				zIndex: kids.length - i
			};
		}

		var clickers = {
			scoot: function () {
				var topIndex = $(this).data('i');
				var chld = $(this).children();
				var newHeight = 0;
				chld.each(function () {
					//get the height of all the children div
					newHeight = newHeight + $(this).height();
				});
				var noOfBlocks = $(this).parent().children().length;
				var newTop = (noOfBlocks - 1) * settings.down;
				$(this).parent().height(newHeight + newTop + 2 * settings.margin);
				$(this).height(newHeight + settings.margin);
				kidsHeight[topIndex] = newHeight + settings.margin;

				kids.each(function (i) {
					var nextIndex = (kids.length + i - topIndex) % kids.length,
						newCss = posFor(nextIndex);
					if (settings.scrunch)
						newCss.height = kidsHeight[topIndex];
					$(this)
						.css('zIndex', newCss.zIndex)
						.animate(newCss, settings.speed)
						.data('currentIndex', nextIndex);
				});
				var newHeight = (kidsHeight[topIndex]);
			}
		};
		if (settings.css) {
			kids.css({
				position: 'absolute',
				border: '1px solid black',
				backgroundColor: 'white',
				overflow: 'hidden',
				cursor: 'pointer'
			});
		}

		var kidsHeight = kids.toArray();
		kids.each(function (index) {
			kidsHeight[index] = $(this).outerHeight();
		}); //skip if page has not rendered yet
		if (kidsHeight[0] > settings.margin) {
			kids.each(function (i) {
				$(this).css(posFor(i)).data({
					i: i,
					currentIndex: i
				}).click(clickers[settings.visual]);
			}).height(kidsHeight[0]); //var kidsTop = kids.toArray().map(function (e) { return $(e).css("top") })
			var kidsTop = kids.toArray();
			kids.each(function (index) {
				kidsTop[index] = $(this).css("top");
			});
			$(this).height((kidsHeight[0]) + parseInt(kidsTop[0]) + settings.margin);
		}
		return this;
	};

	var initializeWorkflowEvents = function () {
		var workflowTemplate = false;
		$(".CommentTextArea").TextAreaExpander(commentTextAreaHeight);
		$('.CommentTextArea').click(function () {
			commentTextAreaHeight = $(this).height();
		});
		$('.CommentTextArea').on('keypress', function () {
			resizeCommentTextArea($(this));
		});

		if (!workflowTemplate) {
			$(".ExpandCollapseUsers").css("display", "block");
			$(".WorkflowBlockUserBlock").hover(
				function () {
					$(this).addClass("hoverDrop");
				},
				function () {
					$(this).removeClass("hoverDrop");
				}
			);
			$(".WorkflowBlockUser").hover(
				function () {
					$(this).addClass("hover");
				},
				function () {
					$(this).removeClass("hover");
				}
			);

			$(".ExpandCollapseUsers").hover(
				function () {
					$(this).addClass("hover");
				},
				function () {
					$(this).removeClass("hover");
				}
			);

			$(".WorkflowBlockUser ").click(function () {
				if ($(this).hasClass("WorkflowBlockUserExpanded")) {
					if (!$(this).parent().siblings().children(".WorkflowBlockUser").hasClass("WorkflowBlockUserExpanded")) {
						$(this).parent().parent().parent().removeClass("WorkflowBlockExpanded"); //for ie7
					}

					$(this).removeClass("WorkflowBlockUserExpanded");
					$(this).children(".DateUpdated").css("display", "none");
					$(this).siblings(".CommentArea").css("display", "none");
				}
				else {
					$(this).parent().parent().parent().addClass("WorkflowBlockExpanded");
					$(this).addClass("WorkflowBlockUserExpanded");

					$(this).children(".DateUpdated").css("display", "block");
					$(this).siblings(".CommentArea").css("display", "block");
					$(this).siblings(".CommentArea").find('.CommentTextArea').focus();
				}
			});

			$(".ExpandCollapseUsers").click(function () {
				if ($(this).hasClass("ExpandImg")) {
					$(this).removeClass("ExpandImg");

					$(this).children("#expandImg").css("display", "none");
					$(this).children("#collapseImg").css("display", "inline");

					$(this).parent().parent().addClass("WorkflowBlockExpanded");
					$(this).siblings(".WorkflowBlockUserBlock").children(".WorkflowBlockUser").addClass("WorkflowBlockUserExpanded");
					$(this).siblings(".WorkflowBlockUserBlock").children(".WorkflowBlockUser").children(".DateUpdated").css("display", "inline");
					$(this).siblings(".WorkflowBlockUserBlock").children(".CommentArea").css("display", "block");
					$(this).siblings(".WorkflowBlockUserBlock").children(".CommentArea").find('.CommentTextArea').focus();

					if (!isMobile) {
						$('#approval-comments').css('width', '20%');
						$('#approval-details').css('width', '60%');
					}
				}
				else {
					$(this).addClass("ExpandImg");

					$(this).children("#expandImg").css("display", "inline");
					$(this).children("#collapseImg").css("display", "none");

					$(this).parent().parent().removeClass("WorkflowBlockExpanded");
					$(this).siblings(".WorkflowBlockUserBlock").children(".WorkflowBlockUser").removeClass("WorkflowBlockUserExpanded");
					$(this).siblings(".WorkflowBlockUserBlock").children(".WorkflowBlockUser").children(".DateUpdated").css("display", "none");
					$(this).siblings(".WorkflowBlockUserBlock").children(".CommentArea").css("display", "none");

					if (!isMobile) {
						$('#approval-comments').css('width', '');
						$('#approval-details').css('width', '');
					}
				}

			});

			$(".SaveComment").click(function () {
				var comment = $(this).parent().siblings(".CommentTextArea").val();
				var blockId = this.id;
				saveComment(blockId, comment);
			});

			reAlign();
		}
		checkCommentAndSecurityWarning();
	};

	var loadTextExpander = function (callback) {
		if ($('<div>').TextAreaExpander == null) {
			var body = $('body');
			$.getScript('/eaengine/Scripts/jquery.textarea-expander.js?t=' + new Date().getTime().toString(), function () { textAreaExpanderLoaded = true; if (typeof callback === 'function') { callback(); } });
		}
	};

	//Methods
	page.saveWorkflow = function (callback) {
		saveWorkflow(callback);
	};

	page.realignBlocks = function () {
		$('.TierWorkflowBlock, .WorkflowBlock').each(function (i, node) { $(node).css('height', ''); });
		reAlign();
	};

	page.load = function (args) {
		localization = args.localization;

		currentUserId = args.currentUserId != null ? args.currentUserId : 0;
		itemId = args.itemId != null ? args.itemId : 0;
		meetingId = args.meetingId != null ? args.meetingId : 0;
		outputType = args.outputType != null ? args.outputType : 0;
		enabled = args.enabled;
		canEdit = args.canEdit;
		workflowTemplates = args.workflowTemplates;
		submitCallback = args.submitCallback;
		cancelCallback = args.cancelCallback;

		workflowData = {
			id: args.workflowId,
			templateId: args.workflowTemplateId,
			defaultWorkflowId: args.defaultWorkflowId,
			status: args.status,
			submittedBy: args.submittedBy,
			submittedDate: args.submittedDate,
			actions: args.actions,
			exportTo: args.exportTo,
			notification: args.notification,
			updateNotification: args.updateNotification,
			workflowHtml: args.workflowHtml,
			canCustomize: args.canCustomize
		};

		loadWorkflowTemplates();
		loadWorkflow();

		if (workflowData.id == 0 && workflowData.defaultWorkflowId > 0) {
			$(document.getElementById('workflow-tempaltes')).val(workflowData.defaultWorkflowId);
			$(document.getElementById('workflow-tempaltes')).trigger('change');
		}
	};

	page.setExportValues = function (meetingTypeId, meetingId, headingId) {
		if (meetingTypeId > 0) {
			$(document.getElementById(workflowExportToMeetingtypeClientId)).val(meetingTypeId);
			loadMeetings(meetingTypeId,
				function () {
					$(document.getElementById(workflowExportToMeetingClientId)).val(meetingId);
					loadHeadings(meetingId,
						function () {
							$(document.getElementById(workflowExportToHeadingClientId)).val(headingId);
						});
				});
		}
	};

	(function () {
		$(document.getElementById('workflow-submit')).off('click').on('click', submitClick);
		$(document.getElementById('workflow-resubmit')).off('click').on('click', submitClick);
		$(document.getElementById('workflow-cancel')).off('click').on('click', cancelClick);
		$(document.getElementById('workflow-tempaltes')).off('change').on('change', workflowTemplateChange);
		$(document.getElementById('customize-workflow')).off('click').on('click', customizeWorkflowClick);
		$(document.getElementById(workflowExportToMeetingtypeClientId)).off('change').on('change', exportToMeetingTypeChange);
		$(document.getElementById(workflowExportToMeetingClientId)).off('change').on('change', exportToMeetingChange);
		$(document.getElementById(workflowExportToHeadingClientId)).off('change').on('change', exportToHeadingChange);
		$(document.getElementById('workflow-add-external-email')).off('click').on('click', addExternalEmailClick);
		$(document.getElementById('workflow')).off('show').on('show', reAlign);
	})();
})(window.CivicWeb.Common.Workflow = window.CivicWeb.Common.Workflow || {}, jQuery);
;
