AUI.add(

	'com-placecube-cookieconsent',

	function(A) {

		var PPID = 'com_placecube_cookieconsent_web_portlet_CookieConsentPortlet';

		var CookieConsent = {

			initCookieConsentForm: function() {

				$(document).on('click', '.btn-cookie-consent', function(e) {
					event.preventDefault();

					var consentResponse = $(e.target).attr('data-cookie-consent');

					var selected = $('input[type="radio"][name="measure-website-use"]:checked');
					if (selected.length > 0) {
						consentResponse = selected.val();
					}
					A.CookieConsent.updateConsent(consentResponse);

				});
			},
			
			configureDoNotTrack: function(cookiesAccepted){
				var doNotTrack = cookiesAccepted == 'false';
				window['ac_client_disable_tracking'] = doNotTrack;
			},

			updateConsent: function(consentResponse) {

				var url = Liferay.PortletURL.createResourceURL();
				url.setPortletId(PPID);
				url.setResourceId("/cookie-consent/update-consent");
				url.setParameter("consentGiven", consentResponse);

				A.io.request(url.toString(), {

					on: {

						success: function() {
							A.CookieConsent.configureDoNotTrack(consentResponse);
							if($(".cookie-consent-updated-banner").length > 0){
								$(".cookie-consent-updated-banner").show();
								$(window).scrollTop(0);
							} else {
								location.reload();
							}
						}

					}

				});

			},

			initCookieHideAction: function(namespace){
				$('#' + namespace + 'cookie-consent-close').on('click', function() {
					$('.cookie-consent__modal-mode').addClass('hide');
					sessionStorage.setItem("isCookieModalClosed", true);
				})

				let isCookieModalClosed = (sessionStorage.getItem("isCookieModalClosed") === 'true');

				if (!isCookieModalClosed) {
					$('.cookie-consent__modal-mode').removeClass('hide');
				}
			}

		};

		A.CookieConsent = CookieConsent;
	},
	'',
	{
		requires: ['aui-io', 'liferay-portlet-url']
	}
);

(function () {
  // start monitoring lifecycle events
  Liferay.on('SPAReady', onLiferayReady);

  function onLiferayReady(evt) {
    fixLoginButton();

    // Register the event listeners only once
    Liferay.on('endNavigate', onEndNavigate);
  }

  function onEndNavigate(evt) {
    fixLoginButton();
  }

  /**
   * Fix the text for login in the top right from 'Log in' to 'Login'
   */
  function fixLoginButton() {
    if (!Liferay.ThemeDisplay.isSignedIn()) {
      fixTheLoginText();
      fixTheLoginMobileText();
    }
  }

  /**
   * Fix the login link text
   */
  function fixTheLoginText() {
    const logInLink = document.querySelector('#navigationCollapse > .account-links > a.log-in-link > span');
    if (!logInLink) return;

    let newText = logInLink.textContent.trim().replace(/log in/gi, 'Login');
    if (!newText) return;

    logInLink.textContent = newText;
  }

  /**
   * Fix the login link text in the mobile menu
   */
  function fixTheLoginMobileText() {
    const mobileLogInLink = document.querySelector('#navigationCollapse > .login-row > a > span');
    if (!mobileLogInLink) return;

    const newText = mobileLogInLink.textContent.trim().replace(/log in/gi, 'Login');
    if (!newText) return;

    mobileLogInLink.textContent = newText;
  }

})();

Liferay.Portlet.ready(
  function (portletId, node) {
    if (portletId === 'com_liferay_login_web_portlet_LoginPortlet') {
      if (themeDisplay.isSignedIn()) {
        const link = document.querySelector('.signed-in');
        if (link) link.setAttribute('href', '/group/guest/my-account');
      }
    }
  }
)
AUI().ready(
	function () {

		setInterval(function () {

			$("input[name^='_com_liferay_journal_web_portlet_JournalPortlet_ddm$$IncludeContentFieldSet'][name*='ContentType'][type='hidden'][value='']").each(function () {
                    var includeContent = $(this).parents('div[data-field-name^="_com_liferay_journal_web_portlet_JournalPortlet_ddm$$IncludeContentFieldSet"]');
                    includeContent.find('.ddm-field-container[data-field-name*="HTML"]').hide();
                    includeContent.find('.ddm-field-container[data-field-name*="WebContent"]').hide();
                    includeContent.find('.ddm-field-container[data-field-name*="Geolocation"]').hide();
                    includeContent.find('.ddm-field-container[data-field-name*="CTATitle"]').hide();
                    includeContent.find('.ddm-field-container[data-field-name*="DistrictCTA"]').hide();
                    includeContent.find('.ddm-field-container[data-field-name*="Title_achieve"]').hide();
		    });

			$("div[data-field-name^='_com_liferay_journal_web_portlet_JournalPortlet_ddm$$IncludeContentFieldSet'] input[type='radio']:checked").each(function () {
				var selectedContentTypeValue = $(this).val();
				var includeContent = $(this).parents('div[data-field-name^="_com_liferay_journal_web_portlet_JournalPortlet_ddm$$IncludeContentFieldSet"]');
				if (selectedContentTypeValue == 'html') {
					includeContent.find('.ddm-field-container[data-field-name*="HTML"]').show();
					includeContent.find('.ddm-field-container[data-field-name*="WebContent"]').hide();
					includeContent.find('.ddm-field-container[data-field-name*="Geolocation"]').hide();
					includeContent.find('.ddm-field-container[data-field-name*="CTATitle"]').hide();
					includeContent.find('.ddm-field-container[data-field-name*="DistrictCTA"]').hide();
                    includeContent.find('.ddm-field-container[data-field-name*="Title_achieve"]').hide();
				} else if (selectedContentTypeValue== 'webcontent') {
					includeContent.find('.ddm-field-container[data-field-name*="HTML"]').hide();
					includeContent.find('.ddm-field-container[data-field-name*="WebContent"]').show();
					includeContent.find('.ddm-field-container[data-field-name*="Geolocation"]').hide();
					includeContent.find('.ddm-field-container[data-field-name*="CTATitle"]').hide();
					includeContent.find('.ddm-field-container[data-field-name*="DistrictCTA"]').hide();
                    includeContent.find('.ddm-field-container[data-field-name*="Title_achieve"]').hide();
				} else if (selectedContentTypeValue == 'map') {
					includeContent.find('.ddm-field-container[data-field-name*="HTML"]').hide();
					includeContent.find('.ddm-field-container[data-field-name*="WebContent"]').hide();
					includeContent.find('.ddm-field-container[data-field-name*="Geolocation"]').show();
					includeContent.find('.ddm-field-container[data-field-name*="CTATitle"]').hide();
					includeContent.find('.ddm-field-container[data-field-name*="DistrictCTA"]').hide();
                    includeContent.find('.ddm-field-container[data-field-name*="Title_achieve"]').hide();
				} else if (selectedContentTypeValue == 'cta') {
					includeContent.find('.ddm-field-container[data-field-name*="HTML"]').hide();
					includeContent.find('.ddm-field-container[data-field-name*="WebContent"]').hide();
					includeContent.find('.ddm-field-container[data-field-name*="Geolocation"]').hide();
					includeContent.find('.ddm-field-container[data-field-name*="CTATitle"]').show();
					includeContent.find('.ddm-field-container[data-field-name*="DistrictCTA"]').hide();
                    includeContent.find('.ddm-field-container[data-field-name*="Title_achieve"]').hide();
				} else if (selectedContentTypeValue == 'districtcta') {
					includeContent.find('.ddm-field-container[data-field-name*="HTML"]').hide();
					includeContent.find('.ddm-field-container[data-field-name*="WebContent"]').hide();
					includeContent.find('.ddm-field-container[data-field-name*="Geolocation"]').hide();
					includeContent.find('.ddm-field-container[data-field-name*="CTATitle"]').hide();
					includeContent.find('.ddm-field-container[data-field-name*="DistrictCTA"]').show();
                    includeContent.find('.ddm-field-container[data-field-name*="Title_achieve"]').hide();
                } else if (selectedContentTypeValue == 'achievecta') {
					includeContent.find('.ddm-field-container[data-field-name*="HTML"]').hide();
					includeContent.find('.ddm-field-container[data-field-name*="WebContent"]').hide();
					includeContent.find('.ddm-field-container[data-field-name*="Geolocation"]').hide();
					includeContent.find('.ddm-field-container[data-field-name*="CTATitle"]').hide();
					includeContent.find('.ddm-field-container[data-field-name*="DistrictCTA"]').hide();
                    includeContent.find('.ddm-field-container[data-field-name*="Title_achieve"]').show();
                }
			});
			
			var journalForm = $(".portlet-journal form.edit-article-form");
			
			if (journalForm.length == 1) {
				if (typeof journalForm.attr("data-senna-off") == 'undefined') {				
					journalForm.attr("data-senna-off", "true");
				}
			}
			
		}, 500);

		$('.gallery__link').each(function() {
			var src = $(this).find('img').attr('src');
			$(this).attr('href', src);
		});

		$('.gallery__items').magnificPopup({
			delegate: 'a',
			type: 'image',
			gallery: {
				enabled:true
			}
		});

        function fixSearchBarAccessibilityIssue(){
            if($('.dp-search-search-bar') && $('.dp-search-search-bar .keyword-label').length === 0){
                $('.dp-search-search-bar input[name="keywords"]').closest('.input-group-item').prepend("<label for='keywords' class='keyword-label sr-only' aria-labelledby='keywords'>Keywords</label>");
                $('.dp-search-search-bar input[name="keywords"]').attr({"id":"keywords", "aria-labelledby":"keywords"});
                $('.dp-search-search-bar input[name="keywords"]').closest('.input-group-item').find('.btn').prepend('<span class="sr-only">Search</span>');
            }
        }

        setInterval(()=>{
            fixSearchBarAccessibilityIssue();
        }, 1000);

        Liferay.on('endNavigate', () => {
            fixSearchBarAccessibilityIssue();
        });

	}
);

/*! Magnific Popup - v0.9.9 - 2013-11-15
* http://dimsemenov.com/plugins/magnific-popup/
* Copyright (c) 2013 Dmitry Semenov; */
;(function($) {

/*>>core*/
/**
 * 
 * Magnific Popup Core JS file
 * 
 */


/**
 * Private static constants
 */
var CLOSE_EVENT = 'Close',
	BEFORE_CLOSE_EVENT = 'BeforeClose',
	AFTER_CLOSE_EVENT = 'AfterClose',
	BEFORE_APPEND_EVENT = 'BeforeAppend',
	MARKUP_PARSE_EVENT = 'MarkupParse',
	OPEN_EVENT = 'Open',
	CHANGE_EVENT = 'Change',
	NS = 'mfp',
	EVENT_NS = '.' + NS,
	READY_CLASS = 'mfp-ready',
	REMOVING_CLASS = 'mfp-removing',
	PREVENT_CLOSE_CLASS = 'mfp-prevent-close';


/**
 * Private vars 
 */
var mfp, // As we have only one instance of MagnificPopup object, we define it locally to not to use 'this'
	MagnificPopup = function(){},
	_isJQ = !!(window.jQuery),
	_prevStatus,
	_window = $(window),
	_body,
	_document,
	_prevContentType,
	_wrapClasses,
	_currPopupType;


/**
 * Private functions
 */
var _mfpOn = function(name, f) {
		mfp.ev.on(NS + name + EVENT_NS, f);
	},
	_getEl = function(className, appendTo, html, raw) {
		var el = document.createElement('div');
		el.className = 'mfp-'+className;
		if(html) {
			el.innerHTML = html;
		}
		if(!raw) {
			el = $(el);
			if(appendTo) {
				el.appendTo(appendTo);
			}
		} else if(appendTo) {
			appendTo.appendChild(el);
		}
		return el;
	},
	_mfpTrigger = function(e, data) {
		mfp.ev.triggerHandler(NS + e, data);

		if(mfp.st.callbacks) {
			// converts "mfpEventName" to "eventName" callback and triggers it if it's present
			e = e.charAt(0).toLowerCase() + e.slice(1);
			if(mfp.st.callbacks[e]) {
				mfp.st.callbacks[e].apply(mfp, $.isArray(data) ? data : [data]);
			}
		}
	},
	_getCloseBtn = function(type) {
		if(type !== _currPopupType || !mfp.currTemplate.closeBtn) {
			mfp.currTemplate.closeBtn = $( mfp.st.closeMarkup.replace('%title%', mfp.st.tClose ) );
			_currPopupType = type;
		}
		return mfp.currTemplate.closeBtn;
	},
	// Initialize Magnific Popup only when called at least once
	_checkInstance = function() {
		if(!$.magnificPopup.instance) {
			mfp = new MagnificPopup();
			mfp.init();
			$.magnificPopup.instance = mfp;
		}
	},
	// CSS transition detection, http://stackoverflow.com/questions/7264899/detect-css-transitions-using-javascript-and-without-modernizr
	supportsTransitions = function() {
		var s = document.createElement('p').style, // 's' for style. better to create an element if body yet to exist
			v = ['ms','O','Moz','Webkit']; // 'v' for vendor

		if( s['transition'] !== undefined ) {
			return true; 
		}
			
		while( v.length ) {
			if( v.pop() + 'Transition' in s ) {
				return true;
			}
		}
				
		return false;
	};



/**
 * Public functions
 */
MagnificPopup.prototype = {

	constructor: MagnificPopup,

	/**
	 * Initializes Magnific Popup plugin. 
	 * This function is triggered only once when $.fn.magnificPopup or $.magnificPopup is executed
	 */
	init: function() {
		var appVersion = navigator.appVersion;
		mfp.isIE7 = appVersion.indexOf("MSIE 7.") !== -1; 
		mfp.isIE8 = appVersion.indexOf("MSIE 8.") !== -1;
		mfp.isLowIE = mfp.isIE7 || mfp.isIE8;
		mfp.isAndroid = (/android/gi).test(appVersion);
		mfp.isIOS = (/iphone|ipad|ipod/gi).test(appVersion);
		mfp.supportsTransition = supportsTransitions();

		// We disable fixed positioned lightbox on devices that don't handle it nicely.
		// If you know a better way of detecting this - let me know.
		mfp.probablyMobile = (mfp.isAndroid || mfp.isIOS || /(Opera Mini)|Kindle|webOS|BlackBerry|(Opera Mobi)|(Windows Phone)|IEMobile/i.test(navigator.userAgent) );
		_body = $(document.body);
		_document = $(document);

		mfp.popupsCache = {};
	},

	/**
	 * Opens popup
	 * @param  data [description]
	 */
	open: function(data) {

		var i;

		if(data.isObj === false) { 
			// convert jQuery collection to array to avoid conflicts later
			mfp.items = data.items.toArray();

			mfp.index = 0;
			var items = data.items,
				item;
			for(i = 0; i < items.length; i++) {
				item = items[i];
				if(item.parsed) {
					item = item.el[0];
				}
				if(item === data.el[0]) {
					mfp.index = i;
					break;
				}
			}
		} else {
			mfp.items = $.isArray(data.items) ? data.items : [data.items];
			mfp.index = data.index || 0;
		}

		// if popup is already opened - we just update the content
		if(mfp.isOpen) {
			mfp.updateItemHTML();
			return;
		}
		
		mfp.types = []; 
		_wrapClasses = '';
		if(data.mainEl && data.mainEl.length) {
			mfp.ev = data.mainEl.eq(0);
		} else {
			mfp.ev = _document;
		}

		if(data.key) {
			if(!mfp.popupsCache[data.key]) {
				mfp.popupsCache[data.key] = {};
			}
			mfp.currTemplate = mfp.popupsCache[data.key];
		} else {
			mfp.currTemplate = {};
		}



		mfp.st = $.extend(true, {}, $.magnificPopup.defaults, data ); 
		mfp.fixedContentPos = mfp.st.fixedContentPos === 'auto' ? !mfp.probablyMobile : mfp.st.fixedContentPos;

		if(mfp.st.modal) {
			mfp.st.closeOnContentClick = false;
			mfp.st.closeOnBgClick = false;
			mfp.st.showCloseBtn = false;
			mfp.st.enableEscapeKey = false;
		}
		

		// Building markup
		// main containers are created only once
		if(!mfp.bgOverlay) {

			// Dark overlay
			mfp.bgOverlay = _getEl('bg').on('click'+EVENT_NS, function() {
				mfp.close();
			});

			mfp.wrap = _getEl('wrap').attr('tabindex', -1).on('click'+EVENT_NS, function(e) {
				if(mfp._checkIfClose(e.target)) {
					mfp.close();
				}
			});

			mfp.container = _getEl('container', mfp.wrap);
		}

		mfp.contentContainer = _getEl('content');
		if(mfp.st.preloader) {
			mfp.preloader = _getEl('preloader', mfp.container, mfp.st.tLoading);
		}


		// Initializing modules
		var modules = $.magnificPopup.modules;
		for(i = 0; i < modules.length; i++) {
			var n = modules[i];
			n = n.charAt(0).toUpperCase() + n.slice(1);
			mfp['init'+n].call(mfp);
		}
		_mfpTrigger('BeforeOpen');


		if(mfp.st.showCloseBtn) {
			// Close button
			if(!mfp.st.closeBtnInside) {
				mfp.wrap.append( _getCloseBtn() );
			} else {
				_mfpOn(MARKUP_PARSE_EVENT, function(e, template, values, item) {
					values.close_replaceWith = _getCloseBtn(item.type);
				});
				_wrapClasses += ' mfp-close-btn-in';
			}
		}

		if(mfp.st.alignTop) {
			_wrapClasses += ' mfp-align-top';
		}

	

		if(mfp.fixedContentPos) {
			mfp.wrap.css({
				overflow: mfp.st.overflowY,
				overflowX: 'hidden',
				overflowY: mfp.st.overflowY
			});
		} else {
			mfp.wrap.css({ 
				top: _window.scrollTop(),
				position: 'absolute'
			});
		}
		if( mfp.st.fixedBgPos === false || (mfp.st.fixedBgPos === 'auto' && !mfp.fixedContentPos) ) {
			mfp.bgOverlay.css({
				height: _document.height(),
				position: 'absolute'
			});
		}

		

		if(mfp.st.enableEscapeKey) {
			// Close on ESC key
			_document.on('keyup' + EVENT_NS, function(e) {
				if(e.keyCode === 27) {
					mfp.close();
				}
			});
		}

		_window.on('resize' + EVENT_NS, function() {
			mfp.updateSize();
		});


		if(!mfp.st.closeOnContentClick) {
			_wrapClasses += ' mfp-auto-cursor';
		}
		
		if(_wrapClasses)
			mfp.wrap.addClass(_wrapClasses);


		// this triggers recalculation of layout, so we get it once to not to trigger twice
		var windowHeight = mfp.wH = _window.height();

		
		var windowStyles = {};

		if( mfp.fixedContentPos ) {
            if(mfp._hasScrollBar(windowHeight)){
                var s = mfp._getScrollbarSize();
                if(s) {
                    windowStyles.marginRight = s;
                }
            }
        }

		if(mfp.fixedContentPos) {
			if(!mfp.isIE7) {
				windowStyles.overflow = 'hidden';
			} else {
				// ie7 double-scroll bug
				$('body, html').css('overflow', 'hidden');
			}
		}

		
		
		var classesToadd = mfp.st.mainClass;
		if(mfp.isIE7) {
			classesToadd += ' mfp-ie7';
		}
		if(classesToadd) {
			mfp._addClassToMFP( classesToadd );
		}

		// add content
		mfp.updateItemHTML();

		_mfpTrigger('BuildControls');


		// remove scrollbar, add margin e.t.c
		$('html').css(windowStyles);
		
		// add everything to DOM
		mfp.bgOverlay.add(mfp.wrap).prependTo( document.body );



		// Save last focused element
		mfp._lastFocusedEl = document.activeElement;
		
		// Wait for next cycle to allow CSS transition
		setTimeout(function() {
			
			if(mfp.content) {
				mfp._addClassToMFP(READY_CLASS);
				mfp._setFocus();
			} else {
				// if content is not defined (not loaded e.t.c) we add class only for BG
				mfp.bgOverlay.addClass(READY_CLASS);
			}
			
			// Trap the focus in popup
			_document.on('focusin' + EVENT_NS, mfp._onFocusIn);

		}, 16);

		mfp.isOpen = true;
		mfp.updateSize(windowHeight);
		_mfpTrigger(OPEN_EVENT);

		return data;
	},

	/**
	 * Closes the popup
	 */
	close: function() {
		if(!mfp.isOpen) return;
		_mfpTrigger(BEFORE_CLOSE_EVENT);

		mfp.isOpen = false;
		// for CSS3 animation
		if(mfp.st.removalDelay && !mfp.isLowIE && mfp.supportsTransition )  {
			mfp._addClassToMFP(REMOVING_CLASS);
			setTimeout(function() {
				mfp._close();
			}, mfp.st.removalDelay);
		} else {
			mfp._close();
		}
	},

	/**
	 * Helper for close() function
	 */
	_close: function() {
		_mfpTrigger(CLOSE_EVENT);

		var classesToRemove = REMOVING_CLASS + ' ' + READY_CLASS + ' ';

		mfp.bgOverlay.detach();
		mfp.wrap.detach();
		mfp.container.empty();

		if(mfp.st.mainClass) {
			classesToRemove += mfp.st.mainClass + ' ';
		}

		mfp._removeClassFromMFP(classesToRemove);

		if(mfp.fixedContentPos) {
			var windowStyles = {marginRight: ''};
			if(mfp.isIE7) {
				$('body, html').css('overflow', '');
			} else {
				windowStyles.overflow = '';
			}
			$('html').css(windowStyles);
		}
		
		_document.off('keyup' + EVENT_NS + ' focusin' + EVENT_NS);
		mfp.ev.off(EVENT_NS);

		// clean up DOM elements that aren't removed
		mfp.wrap.attr('class', 'mfp-wrap').removeAttr('style');
		mfp.bgOverlay.attr('class', 'mfp-bg');
		mfp.container.attr('class', 'mfp-container');

		// remove close button from target element
		if(mfp.st.showCloseBtn &&
		(!mfp.st.closeBtnInside || mfp.currTemplate[mfp.currItem.type] === true)) {
			if(mfp.currTemplate.closeBtn)
				mfp.currTemplate.closeBtn.detach();
		}


		if(mfp._lastFocusedEl) {
			$(mfp._lastFocusedEl).focus(); // put tab focus back
		}
		mfp.currItem = null;	
		mfp.content = null;
		mfp.currTemplate = null;
		mfp.prevHeight = 0;

		_mfpTrigger(AFTER_CLOSE_EVENT);
	},
	
	updateSize: function(winHeight) {

		if(mfp.isIOS) {
			// fixes iOS nav bars https://github.com/dimsemenov/Magnific-Popup/issues/2
			var zoomLevel = document.documentElement.clientWidth / window.innerWidth;
			var height = window.innerHeight * zoomLevel;
			mfp.wrap.css('height', height);
			mfp.wH = height;
		} else {
			mfp.wH = winHeight || _window.height();
		}
		// Fixes #84: popup incorrectly positioned with position:relative on body
		if(!mfp.fixedContentPos) {
			mfp.wrap.css('height', mfp.wH);
		}

		_mfpTrigger('Resize');

	},

	/**
	 * Set content of popup based on current index
	 */
	updateItemHTML: function() {
		var item = mfp.items[mfp.index];

		// Detach and perform modifications
		mfp.contentContainer.detach();

		if(mfp.content)
			mfp.content.detach();

		if(!item.parsed) {
			item = mfp.parseEl( mfp.index );
		}

		var type = item.type;	

		_mfpTrigger('BeforeChange', [mfp.currItem ? mfp.currItem.type : '', type]);
		// BeforeChange event works like so:
		// _mfpOn('BeforeChange', function(e, prevType, newType) { });
		
		mfp.currItem = item;

		

		

		if(!mfp.currTemplate[type]) {
			var markup = mfp.st[type] ? mfp.st[type].markup : false;

			// allows to modify markup
			_mfpTrigger('FirstMarkupParse', markup);

			if(markup) {
				mfp.currTemplate[type] = $(markup);
			} else {
				// if there is no markup found we just define that template is parsed
				mfp.currTemplate[type] = true;
			}
		}

		if(_prevContentType && _prevContentType !== item.type) {
			mfp.container.removeClass('mfp-'+_prevContentType+'-holder');
		}
		
		var newContent = mfp['get' + type.charAt(0).toUpperCase() + type.slice(1)](item, mfp.currTemplate[type]);
		mfp.appendContent(newContent, type);

		item.preloaded = true;

		_mfpTrigger(CHANGE_EVENT, item);
		_prevContentType = item.type;
		
		// Append container back after its content changed
		mfp.container.prepend(mfp.contentContainer);

		_mfpTrigger('AfterChange');
	},


	/**
	 * Set HTML content of popup
	 */
	appendContent: function(newContent, type) {
		mfp.content = newContent;
		
		if(newContent) {
			if(mfp.st.showCloseBtn && mfp.st.closeBtnInside &&
				mfp.currTemplate[type] === true) {
				// if there is no markup, we just append close button element inside
				if(!mfp.content.find('.mfp-close').length) {
					mfp.content.append(_getCloseBtn());
				}
			} else {
				mfp.content = newContent;
			}
		} else {
			mfp.content = '';
		}

		_mfpTrigger(BEFORE_APPEND_EVENT);
		mfp.container.addClass('mfp-'+type+'-holder');

		mfp.contentContainer.append(mfp.content);
	},



	
	/**
	 * Creates Magnific Popup data object based on given data
	 * @param  {int} index Index of item to parse
	 */
	parseEl: function(index) {
		var item = mfp.items[index],
			type = item.type;

		if(item.tagName) {
			item = { el: $(item) };
		} else {
			item = { data: item, src: item.src };
		}

		if(item.el) {
			var types = mfp.types;

			// check for 'mfp-TYPE' class
			for(var i = 0; i < types.length; i++) {
				if( item.el.hasClass('mfp-'+types[i]) ) {
					type = types[i];
					break;
				}
			}

			item.src = item.el.attr('data-mfp-src');
			if(!item.src) {
				item.src = item.el.attr('href');
			}
		}

		item.type = type || mfp.st.type || 'inline';
		item.index = index;
		item.parsed = true;
		mfp.items[index] = item;
		_mfpTrigger('ElementParse', item);

		return mfp.items[index];
	},


	/**
	 * Initializes single popup or a group of popups
	 */
	addGroup: function(el, options) {
		var eHandler = function(e) {
			e.mfpEl = this;
			mfp._openClick(e, el, options);
		};

		if(!options) {
			options = {};
		} 

		var eName = 'click.magnificPopup';
		options.mainEl = el;
		
		if(options.items) {
			options.isObj = true;
			el.off(eName).on(eName, eHandler);
		} else {
			options.isObj = false;
			if(options.delegate) {
				el.off(eName).on(eName, options.delegate , eHandler);
			} else {
				options.items = el;
				el.off(eName).on(eName, eHandler);
			}
		}
	},
	_openClick: function(e, el, options) {
		var midClick = options.midClick !== undefined ? options.midClick : $.magnificPopup.defaults.midClick;


		if(!midClick && ( e.which === 2 || e.ctrlKey || e.metaKey ) ) {
			return;
		}

		var disableOn = options.disableOn !== undefined ? options.disableOn : $.magnificPopup.defaults.disableOn;

		if(disableOn) {
			if($.isFunction(disableOn)) {
				if( !disableOn.call(mfp) ) {
					return true;
				}
			} else { // else it's number
				if( _window.width() < disableOn ) {
					return true;
				}
			}
		}
		
		if(e.type) {
			e.preventDefault();

			// This will prevent popup from closing if element is inside and popup is already opened
			if(mfp.isOpen) {
				e.stopPropagation();
			}
		}
			

		options.el = $(e.mfpEl);
		if(options.delegate) {
			options.items = el.find(options.delegate);
		}
		mfp.open(options);
	},


	/**
	 * Updates text on preloader
	 */
	updateStatus: function(status, text) {

		if(mfp.preloader) {
			if(_prevStatus !== status) {
				mfp.container.removeClass('mfp-s-'+_prevStatus);
			}

			if(!text && status === 'loading') {
				text = mfp.st.tLoading;
			}

			var data = {
				status: status,
				text: text
			};
			// allows to modify status
			_mfpTrigger('UpdateStatus', data);

			status = data.status;
			text = data.text;

			mfp.preloader.html(text);

			mfp.preloader.find('a').on('click', function(e) {
				e.stopImmediatePropagation();
			});

			mfp.container.addClass('mfp-s-'+status);
			_prevStatus = status;
		}
	},


	/*
		"Private" helpers that aren't private at all
	 */
	// Check to close popup or not
	// "target" is an element that was clicked
	_checkIfClose: function(target) {

		if($(target).hasClass(PREVENT_CLOSE_CLASS)) {
			return;
		}

		var closeOnContent = mfp.st.closeOnContentClick;
		var closeOnBg = mfp.st.closeOnBgClick;

		if(closeOnContent && closeOnBg) {
			return true;
		} else {

			// We close the popup if click is on close button or on preloader. Or if there is no content.
			if(!mfp.content || $(target).hasClass('mfp-close') || (mfp.preloader && target === mfp.preloader[0]) ) {
				return true;
			}

			// if click is outside the content
			if(  (target !== mfp.content[0] && !$.contains(mfp.content[0], target))  ) {
				if(closeOnBg) {
					// last check, if the clicked element is in DOM, (in case it's removed onclick)
					if( $.contains(document, target) ) {
						return true;
					}
				}
			} else if(closeOnContent) {
				return true;
			}

		}
		return false;
	},
	_addClassToMFP: function(cName) {
		mfp.bgOverlay.addClass(cName);
		mfp.wrap.addClass(cName);
	},
	_removeClassFromMFP: function(cName) {
		this.bgOverlay.removeClass(cName);
		mfp.wrap.removeClass(cName);
	},
	_hasScrollBar: function(winHeight) {
		return (  (mfp.isIE7 ? _document.height() : document.body.scrollHeight) > (winHeight || _window.height()) );
	},
	_setFocus: function() {
		(mfp.st.focus ? mfp.content.find(mfp.st.focus).eq(0) : mfp.wrap).focus();
	},
	_onFocusIn: function(e) {
		if( e.target !== mfp.wrap[0] && !$.contains(mfp.wrap[0], e.target) ) {
			mfp._setFocus();
			return false;
		}
	},
	_parseMarkup: function(template, values, item) {
		var arr;
		if(item.data) {
			values = $.extend(item.data, values);
		}
		_mfpTrigger(MARKUP_PARSE_EVENT, [template, values, item] );

		$.each(values, function(key, value) {
			if(value === undefined || value === false) {
				return true;
			}
			arr = key.split('_');
			if(arr.length > 1) {
				var el = template.find(EVENT_NS + '-'+arr[0]);

				if(el.length > 0) {
					var attr = arr[1];
					if(attr === 'replaceWith') {
						if(el[0] !== value[0]) {
							el.replaceWith(value);
						}
					} else if(attr === 'img') {
						if(el.is('img')) {
							el.attr('src', value);
						} else {
							el.replaceWith( '<img src="'+value+'" class="' + el.attr('class') + '" />' );
						}
					} else {
						el.attr(arr[1], value);
					}
				}

			} else {
				template.find(EVENT_NS + '-'+key).html(value);
			}
		});
	},

	_getScrollbarSize: function() {
		// thx David
		if(mfp.scrollbarSize === undefined) {
			var scrollDiv = document.createElement("div");
			scrollDiv.id = "mfp-sbm";
			scrollDiv.style.cssText = 'width: 99px; height: 99px; overflow: scroll; position: absolute; top: -9999px;';
			document.body.appendChild(scrollDiv);
			mfp.scrollbarSize = scrollDiv.offsetWidth - scrollDiv.clientWidth;
			document.body.removeChild(scrollDiv);
		}
		return mfp.scrollbarSize;
	}

}; /* MagnificPopup core prototype end */




/**
 * Public static functions
 */
$.magnificPopup = {
	instance: null,
	proto: MagnificPopup.prototype,
	modules: [],

	open: function(options, index) {
		_checkInstance();	

		if(!options) {
			options = {};
		} else {
			options = $.extend(true, {}, options);
		}
			

		options.isObj = true;
		options.index = index || 0;
		return this.instance.open(options);
	},

	close: function() {
		return $.magnificPopup.instance && $.magnificPopup.instance.close();
	},

	registerModule: function(name, module) {
		if(module.options) {
			$.magnificPopup.defaults[name] = module.options;
		}
		$.extend(this.proto, module.proto);			
		this.modules.push(name);
	},

	defaults: {   

		// Info about options is in docs:
		// http://dimsemenov.com/plugins/magnific-popup/documentation.html#options
		
		disableOn: 0,	

		key: null,

		midClick: false,

		mainClass: '',

		preloader: true,

		focus: '', // CSS selector of input to focus after popup is opened
		
		closeOnContentClick: false,

		closeOnBgClick: true,

		closeBtnInside: true, 

		showCloseBtn: true,

		enableEscapeKey: true,

		modal: false,

		alignTop: false,
	
		removalDelay: 0,
		
		fixedContentPos: 'auto', 
	
		fixedBgPos: 'auto',

		overflowY: 'auto',

		closeMarkup: '<button title="%title%" type="button" class="mfp-close">&times;</button>',

		tClose: 'Close (Esc)',

		tLoading: 'Loading...'

	}
};



$.fn.magnificPopup = function(options) {
	_checkInstance();

	var jqEl = $(this);

	// We call some API method of first param is a string
	if (typeof options === "string" ) {

		if(options === 'open') {
			var items,
				itemOpts = _isJQ ? jqEl.data('magnificPopup') : jqEl[0].magnificPopup,
				index = parseInt(arguments[1], 10) || 0;

			if(itemOpts.items) {
				items = itemOpts.items[index];
			} else {
				items = jqEl;
				if(itemOpts.delegate) {
					items = items.find(itemOpts.delegate);
				}
				items = items.eq( index );
			}
			mfp._openClick({mfpEl:items}, jqEl, itemOpts);
		} else {
			if(mfp.isOpen)
				mfp[options].apply(mfp, Array.prototype.slice.call(arguments, 1));
		}

	} else {
		// clone options obj
		options = $.extend(true, {}, options);
		
		/*
		 * As Zepto doesn't support .data() method for objects 
		 * and it works only in normal browsers
		 * we assign "options" object directly to the DOM element. FTW!
		 */
		if(_isJQ) {
			jqEl.data('magnificPopup', options);
		} else {
			jqEl[0].magnificPopup = options;
		}

		mfp.addGroup(jqEl, options);

	}
	return jqEl;
};


//Quick benchmark
/*
var start = performance.now(),
	i,
	rounds = 1000;

for(i = 0; i < rounds; i++) {

}
console.log('Test #1:', performance.now() - start);

start = performance.now();
for(i = 0; i < rounds; i++) {

}
console.log('Test #2:', performance.now() - start);
*/


/*>>core*/

/*>>inline*/

var INLINE_NS = 'inline',
	_hiddenClass,
	_inlinePlaceholder, 
	_lastInlineElement,
	_putInlineElementsBack = function() {
		if(_lastInlineElement) {
			_inlinePlaceholder.after( _lastInlineElement.addClass(_hiddenClass) ).detach();
			_lastInlineElement = null;
		}
	};

$.magnificPopup.registerModule(INLINE_NS, {
	options: {
		hiddenClass: 'hide', // will be appended with `mfp-` prefix
		markup: '',
		tNotFound: 'Content not found'
	},
	proto: {

		initInline: function() {
			mfp.types.push(INLINE_NS);

			_mfpOn(CLOSE_EVENT+'.'+INLINE_NS, function() {
				_putInlineElementsBack();
			});
		},

		getInline: function(item, template) {

			_putInlineElementsBack();

			if(item.src) {
				var inlineSt = mfp.st.inline,
					el = $(item.src);

				if(el.length) {

					// If target element has parent - we replace it with placeholder and put it back after popup is closed
					var parent = el[0].parentNode;
					if(parent && parent.tagName) {
						if(!_inlinePlaceholder) {
							_hiddenClass = inlineSt.hiddenClass;
							_inlinePlaceholder = _getEl(_hiddenClass);
							_hiddenClass = 'mfp-'+_hiddenClass;
						}
						// replace target inline element with placeholder
						_lastInlineElement = el.after(_inlinePlaceholder).detach().removeClass(_hiddenClass);
					}

					mfp.updateStatus('ready');
				} else {
					mfp.updateStatus('error', inlineSt.tNotFound);
					el = $('<div>');
				}

				item.inlineElement = el;
				return el;
			}

			mfp.updateStatus('ready');
			mfp._parseMarkup(template, {}, item);
			return template;
		}
	}
});

/*>>inline*/

/*>>ajax*/
var AJAX_NS = 'ajax',
	_ajaxCur,
	_removeAjaxCursor = function() {
		if(_ajaxCur) {
			_body.removeClass(_ajaxCur);
		}
	},
	_destroyAjaxRequest = function() {
		_removeAjaxCursor();
		if(mfp.req) {
			mfp.req.abort();
		}
	};

$.magnificPopup.registerModule(AJAX_NS, {

	options: {
		settings: null,
		cursor: 'mfp-ajax-cur',
		tError: '<a href="%url%">The content</a> could not be loaded.'
	},

	proto: {
		initAjax: function() {
			mfp.types.push(AJAX_NS);
			_ajaxCur = mfp.st.ajax.cursor;

			_mfpOn(CLOSE_EVENT+'.'+AJAX_NS, _destroyAjaxRequest);
			_mfpOn('BeforeChange.' + AJAX_NS, _destroyAjaxRequest);
		},
		getAjax: function(item) {

			if(_ajaxCur)
				_body.addClass(_ajaxCur);

			mfp.updateStatus('loading');

			var opts = $.extend({
				url: item.src,
				success: function(data, textStatus, jqXHR) {
					var temp = {
						data:data,
						xhr:jqXHR
					};

					_mfpTrigger('ParseAjax', temp);

					mfp.appendContent( $(temp.data), AJAX_NS );

					item.finished = true;

					_removeAjaxCursor();

					mfp._setFocus();

					setTimeout(function() {
						mfp.wrap.addClass(READY_CLASS);
					}, 16);

					mfp.updateStatus('ready');

					_mfpTrigger('AjaxContentAdded');
				},
				error: function() {
					_removeAjaxCursor();
					item.finished = item.loadError = true;
					mfp.updateStatus('error', mfp.st.ajax.tError.replace('%url%', item.src));
				}
			}, mfp.st.ajax.settings);

			mfp.req = $.ajax(opts);

			return '';
		}
	}
});





	

/*>>ajax*/

/*>>image*/
var _imgInterval,
	_getTitle = function(item) {
		if(item.data && item.data.title !== undefined) 
			return item.data.title;

		var src = mfp.st.image.titleSrc;

		if(src) {
			if($.isFunction(src)) {
				return src.call(mfp, item);
			} else if(item.el) {
				return item.el.attr(src) || '';
			}
		}
		return '';
	};

$.magnificPopup.registerModule('image', {

	options: {
		markup: '<div class="mfp-figure">'+
					'<div class="mfp-close"></div>'+
					'<figure>'+
						'<div class="mfp-img"></div>'+
						'<figcaption>'+
							'<div class="mfp-bottom-bar">'+
								'<div class="mfp-title"></div>'+
								'<div class="mfp-counter"></div>'+
							'</div>'+
						'</figcaption>'+
					'</figure>'+
				'</div>',
		cursor: 'mfp-zoom-out-cur',
		titleSrc: 'title', 
		verticalFit: true,
		tError: '<a href="%url%">The image</a> could not be loaded.'
	},

	proto: {
		initImage: function() {
			var imgSt = mfp.st.image,
				ns = '.image';

			mfp.types.push('image');

			_mfpOn(OPEN_EVENT+ns, function() {
				if(mfp.currItem.type === 'image' && imgSt.cursor) {
					_body.addClass(imgSt.cursor);
				}
			});

			_mfpOn(CLOSE_EVENT+ns, function() {
				if(imgSt.cursor) {
					_body.removeClass(imgSt.cursor);
				}
				_window.off('resize' + EVENT_NS);
			});

			_mfpOn('Resize'+ns, mfp.resizeImage);
			if(mfp.isLowIE) {
				_mfpOn('AfterChange', mfp.resizeImage);
			}
		},
		resizeImage: function() {
			var item = mfp.currItem;
			if(!item || !item.img) return;

			if(mfp.st.image.verticalFit) {
				var decr = 0;
				// fix box-sizing in ie7/8
				if(mfp.isLowIE) {
					decr = parseInt(item.img.css('padding-top'), 10) + parseInt(item.img.css('padding-bottom'),10);
				}
				item.img.css('max-height', mfp.wH-decr);
			}
		},
		_onImageHasSize: function(item) {
			if(item.img) {
				
				item.hasSize = true;

				if(_imgInterval) {
					clearInterval(_imgInterval);
				}
				
				item.isCheckingImgSize = false;

				_mfpTrigger('ImageHasSize', item);

				if(item.imgHidden) {
					if(mfp.content)
						mfp.content.removeClass('mfp-loading');
					
					item.imgHidden = false;
				}

			}
		},

		/**
		 * Function that loops until the image has size to display elements that rely on it asap
		 */
		findImageSize: function(item) {

			var counter = 0,
				img = item.img[0],
				mfpSetInterval = function(delay) {

					if(_imgInterval) {
						clearInterval(_imgInterval);
					}
					// decelerating interval that checks for size of an image
					_imgInterval = setInterval(function() {
						if(img.naturalWidth > 0) {
							mfp._onImageHasSize(item);
							return;
						}

						if(counter > 200) {
							clearInterval(_imgInterval);
						}

						counter++;
						if(counter === 3) {
							mfpSetInterval(10);
						} else if(counter === 40) {
							mfpSetInterval(50);
						} else if(counter === 100) {
							mfpSetInterval(500);
						}
					}, delay);
				};

			mfpSetInterval(1);
		},

		getImage: function(item, template) {

			var guard = 0,

				// image load complete handler
				onLoadComplete = function() {
					if(item) {
						if (item.img[0].complete) {
							item.img.off('.mfploader');
							
							if(item === mfp.currItem){
								mfp._onImageHasSize(item);

								mfp.updateStatus('ready');
							}

							item.hasSize = true;
							item.loaded = true;

							_mfpTrigger('ImageLoadComplete');
							
						}
						else {
							// if image complete check fails 200 times (20 sec), we assume that there was an error.
							guard++;
							if(guard < 200) {
								setTimeout(onLoadComplete,100);
							} else {
								onLoadError();
							}
						}
					}
				},

				// image error handler
				onLoadError = function() {
					if(item) {
						item.img.off('.mfploader');
						if(item === mfp.currItem){
							mfp._onImageHasSize(item);
							mfp.updateStatus('error', imgSt.tError.replace('%url%', item.src) );
						}

						item.hasSize = true;
						item.loaded = true;
						item.loadError = true;
					}
				},
				imgSt = mfp.st.image;


			var el = template.find('.mfp-img');
			if(el.length) {
				var img = document.createElement('img');
				img.className = 'mfp-img';
				item.img = $(img).on('load.mfploader', onLoadComplete).on('error.mfploader', onLoadError);
				img.src = item.src;

				// without clone() "error" event is not firing when IMG is replaced by new IMG
				// TODO: find a way to avoid such cloning
				if(el.is('img')) {
					item.img = item.img.clone();
				}
				if(item.img[0].naturalWidth > 0) {
					item.hasSize = true;
				}
			}

			mfp._parseMarkup(template, {
				title: _getTitle(item),
				img_replaceWith: item.img
			}, item);

			mfp.resizeImage();

			if(item.hasSize) {
				if(_imgInterval) clearInterval(_imgInterval);

				if(item.loadError) {
					template.addClass('mfp-loading');
					mfp.updateStatus('error', imgSt.tError.replace('%url%', item.src) );
				} else {
					template.removeClass('mfp-loading');
					mfp.updateStatus('ready');
				}
				return template;
			}

			mfp.updateStatus('loading');
			item.loading = true;

			if(!item.hasSize) {
				item.imgHidden = true;
				template.addClass('mfp-loading');
				mfp.findImageSize(item);
			} 

			return template;
		}
	}
});



/*>>image*/

/*>>zoom*/
var hasMozTransform,
	getHasMozTransform = function() {
		if(hasMozTransform === undefined) {
			hasMozTransform = document.createElement('p').style.MozTransform !== undefined;
		}
		return hasMozTransform;		
	};

$.magnificPopup.registerModule('zoom', {

	options: {
		enabled: false,
		easing: 'ease-in-out',
		duration: 300,
		opener: function(element) {
			return element.is('img') ? element : element.find('img');
		}
	},

	proto: {

		initZoom: function() {
			var zoomSt = mfp.st.zoom,
				ns = '.zoom',
				image;
				
			if(!zoomSt.enabled || !mfp.supportsTransition) {
				return;
			}

			var duration = zoomSt.duration,
				getElToAnimate = function(image) {
					var newImg = image.clone().removeAttr('style').removeAttr('class').addClass('mfp-animated-image'),
						transition = 'all '+(zoomSt.duration/1000)+'s ' + zoomSt.easing,
						cssObj = {
							position: 'fixed',
							zIndex: 9999,
							left: 0,
							top: 0,
							'-webkit-backface-visibility': 'hidden'
						},
						t = 'transition';

					cssObj['-webkit-'+t] = cssObj['-moz-'+t] = cssObj['-o-'+t] = cssObj[t] = transition;

					newImg.css(cssObj);
					return newImg;
				},
				showMainContent = function() {
					mfp.content.css('visibility', 'visible');
				},
				openTimeout,
				animatedImg;

			_mfpOn('BuildControls'+ns, function() {
				if(mfp._allowZoom()) {

					clearTimeout(openTimeout);
					mfp.content.css('visibility', 'hidden');

					// Basically, all code below does is clones existing image, puts in on top of the current one and animated it
					
					image = mfp._getItemToZoom();

					if(!image) {
						showMainContent();
						return;
					}

					animatedImg = getElToAnimate(image); 
					
					animatedImg.css( mfp._getOffset() );

					mfp.wrap.append(animatedImg);

					openTimeout = setTimeout(function() {
						animatedImg.css( mfp._getOffset( true ) );
						openTimeout = setTimeout(function() {

							showMainContent();

							setTimeout(function() {
								animatedImg.remove();
								image = animatedImg = null;
								_mfpTrigger('ZoomAnimationEnded');
							}, 16); // avoid blink when switching images 

						}, duration); // this timeout equals animation duration

					}, 16); // by adding this timeout we avoid short glitch at the beginning of animation


					// Lots of timeouts...
				}
			});
			_mfpOn(BEFORE_CLOSE_EVENT+ns, function() {
				if(mfp._allowZoom()) {

					clearTimeout(openTimeout);

					mfp.st.removalDelay = duration;

					if(!image) {
						image = mfp._getItemToZoom();
						if(!image) {
							return;
						}
						animatedImg = getElToAnimate(image);
					}
					
					
					animatedImg.css( mfp._getOffset(true) );
					mfp.wrap.append(animatedImg);
					mfp.content.css('visibility', 'hidden');
					
					setTimeout(function() {
						animatedImg.css( mfp._getOffset() );
					}, 16);
				}

			});

			_mfpOn(CLOSE_EVENT+ns, function() {
				if(mfp._allowZoom()) {
					showMainContent();
					if(animatedImg) {
						animatedImg.remove();
					}
					image = null;
				}	
			});
		},

		_allowZoom: function() {
			return mfp.currItem.type === 'image';
		},

		_getItemToZoom: function() {
			if(mfp.currItem.hasSize) {
				return mfp.currItem.img;
			} else {
				return false;
			}
		},

		// Get element postion relative to viewport
		_getOffset: function(isLarge) {
			var el;
			if(isLarge) {
				el = mfp.currItem.img;
			} else {
				el = mfp.st.zoom.opener(mfp.currItem.el || mfp.currItem);
			}

			var offset = el.offset();
			var paddingTop = parseInt(el.css('padding-top'),10);
			var paddingBottom = parseInt(el.css('padding-bottom'),10);
			offset.top -= ( $(window).scrollTop() - paddingTop );


			/*
			
			Animating left + top + width/height looks glitchy in Firefox, but perfect in Chrome. And vice-versa.

			 */
			var obj = {
				width: el.width(),
				// fix Zepto height+padding issue
				height: (_isJQ ? el.innerHeight() : el[0].offsetHeight) - paddingBottom - paddingTop
			};

			// I hate to do this, but there is no another option
			if( getHasMozTransform() ) {
				obj['-moz-transform'] = obj['transform'] = 'translate(' + offset.left + 'px,' + offset.top + 'px)';
			} else {
				obj.left = offset.left;
				obj.top = offset.top;
			}
			return obj;
		}

	}
});



/*>>zoom*/

/*>>iframe*/

var IFRAME_NS = 'iframe',
	_emptyPage = '//about:blank',
	
	_fixIframeBugs = function(isShowing) {
		if(mfp.currTemplate[IFRAME_NS]) {
			var el = mfp.currTemplate[IFRAME_NS].find('iframe');
			if(el.length) { 
				// reset src after the popup is closed to avoid "video keeps playing after popup is closed" bug
				if(!isShowing) {
					el[0].src = _emptyPage;
				}

				// IE8 black screen bug fix
				if(mfp.isIE8) {
					el.css('display', isShowing ? 'block' : 'none');
				}
			}
		}
	};

$.magnificPopup.registerModule(IFRAME_NS, {

	options: {
		markup: '<div class="mfp-iframe-scaler">'+
					'<div class="mfp-close"></div>'+
					'<iframe class="mfp-iframe" src="//about:blank" frameborder="0" allowfullscreen></iframe>'+
				'</div>',

		srcAction: 'iframe_src',

		// we don't care and support only one default type of URL by default
		patterns: {
			youtube: {
				index: 'youtube.com', 
				id: 'v=', 
				src: '//www.youtube.com/embed/%id%?autoplay=1'
			},
			vimeo: {
				index: 'vimeo.com/',
				id: '/',
				src: '//player.vimeo.com/video/%id%?autoplay=1'
			},
			gmaps: {
				index: '//maps.google.',
				src: '%id%&output=embed'
			}
		}
	},

	proto: {
		initIframe: function() {
			mfp.types.push(IFRAME_NS);

			_mfpOn('BeforeChange', function(e, prevType, newType) {
				if(prevType !== newType) {
					if(prevType === IFRAME_NS) {
						_fixIframeBugs(); // iframe if removed
					} else if(newType === IFRAME_NS) {
						_fixIframeBugs(true); // iframe is showing
					} 
				}// else {
					// iframe source is switched, don't do anything
				//}
			});

			_mfpOn(CLOSE_EVENT + '.' + IFRAME_NS, function() {
				_fixIframeBugs();
			});
		},

		getIframe: function(item, template) {
			var embedSrc = item.src;
			var iframeSt = mfp.st.iframe;
				
			$.each(iframeSt.patterns, function() {
				if(embedSrc.indexOf( this.index ) > -1) {
					if(this.id) {
						if(typeof this.id === 'string') {
							embedSrc = embedSrc.substr(embedSrc.lastIndexOf(this.id)+this.id.length, embedSrc.length);
						} else {
							embedSrc = this.id.call( this, embedSrc );
						}
					}
					embedSrc = this.src.replace('%id%', embedSrc );
					return false; // break;
				}
			});
			
			var dataObj = {};
			if(iframeSt.srcAction) {
				dataObj[iframeSt.srcAction] = embedSrc;
			}
			mfp._parseMarkup(template, dataObj, item);

			mfp.updateStatus('ready');

			return template;
		}
	}
});



/*>>iframe*/

/*>>gallery*/
/**
 * Get looped index depending on number of slides
 */
var _getLoopedId = function(index) {
		var numSlides = mfp.items.length;
		if(index > numSlides - 1) {
			return index - numSlides;
		} else  if(index < 0) {
			return numSlides + index;
		}
		return index;
	},
	_replaceCurrTotal = function(text, curr, total) {
		return text.replace(/%curr%/gi, curr + 1).replace(/%total%/gi, total);
	};

$.magnificPopup.registerModule('gallery', {

	options: {
		enabled: false,
		arrowMarkup: '<button title="%title%" type="button" class="mfp-arrow mfp-arrow-%dir%"></button>',
		preload: [0,2],
		navigateByImgClick: true,
		arrows: true,

		tPrev: 'Previous (Left arrow key)',
		tNext: 'Next (Right arrow key)',
		tCounter: '%curr% of %total%'
	},

	proto: {
		initGallery: function() {

			var gSt = mfp.st.gallery,
				ns = '.mfp-gallery',
				supportsFastClick = Boolean($.fn.mfpFastClick);

			mfp.direction = true; // true - next, false - prev
			
			if(!gSt || !gSt.enabled ) return false;

			_wrapClasses += ' mfp-gallery';

			_mfpOn(OPEN_EVENT+ns, function() {

				if(gSt.navigateByImgClick) {
					mfp.wrap.on('click'+ns, '.mfp-img', function() {
						if(mfp.items.length > 1) {
							mfp.next();
							return false;
						}
					});
				}

				_document.on('keydown'+ns, function(e) {
					if (e.keyCode === 37) {
						mfp.prev();
					} else if (e.keyCode === 39) {
						mfp.next();
					}
				});
			});

			_mfpOn('UpdateStatus'+ns, function(e, data) {
				if(data.text) {
					data.text = _replaceCurrTotal(data.text, mfp.currItem.index, mfp.items.length);
				}
			});

			_mfpOn(MARKUP_PARSE_EVENT+ns, function(e, element, values, item) {
				var l = mfp.items.length;
				values.counter = l > 1 ? _replaceCurrTotal(gSt.tCounter, item.index, l) : '';
			});

			_mfpOn('BuildControls' + ns, function() {
				if(mfp.items.length > 1 && gSt.arrows && !mfp.arrowLeft) {
					var markup = gSt.arrowMarkup,
						arrowLeft = mfp.arrowLeft = $( markup.replace(/%title%/gi, gSt.tPrev).replace(/%dir%/gi, 'left') ).addClass(PREVENT_CLOSE_CLASS),			
						arrowRight = mfp.arrowRight = $( markup.replace(/%title%/gi, gSt.tNext).replace(/%dir%/gi, 'right') ).addClass(PREVENT_CLOSE_CLASS);

					var eName = supportsFastClick ? 'mfpFastClick' : 'click';
					arrowLeft[eName](function() {
						mfp.prev();
					});			
					arrowRight[eName](function() {
						mfp.next();
					});	

					// Polyfill for :before and :after (adds elements with classes mfp-a and mfp-b)
					if(mfp.isIE7) {
						_getEl('b', arrowLeft[0], false, true);
						_getEl('a', arrowLeft[0], false, true);
						_getEl('b', arrowRight[0], false, true);
						_getEl('a', arrowRight[0], false, true);
					}

					mfp.container.append(arrowLeft.add(arrowRight));
				}
			});

			_mfpOn(CHANGE_EVENT+ns, function() {
				if(mfp._preloadTimeout) clearTimeout(mfp._preloadTimeout);

				mfp._preloadTimeout = setTimeout(function() {
					mfp.preloadNearbyImages();
					mfp._preloadTimeout = null;
				}, 16);		
			});


			_mfpOn(CLOSE_EVENT+ns, function() {
				_document.off(ns);
				mfp.wrap.off('click'+ns);
			
				if(mfp.arrowLeft && supportsFastClick) {
					mfp.arrowLeft.add(mfp.arrowRight).destroyMfpFastClick();
				}
				mfp.arrowRight = mfp.arrowLeft = null;
			});

		}, 
		next: function() {
			mfp.direction = true;
			mfp.index = _getLoopedId(mfp.index + 1);
			mfp.updateItemHTML();
		},
		prev: function() {
			mfp.direction = false;
			mfp.index = _getLoopedId(mfp.index - 1);
			mfp.updateItemHTML();
		},
		goTo: function(newIndex) {
			mfp.direction = (newIndex >= mfp.index);
			mfp.index = newIndex;
			mfp.updateItemHTML();
		},
		preloadNearbyImages: function() {
			var p = mfp.st.gallery.preload,
				preloadBefore = Math.min(p[0], mfp.items.length),
				preloadAfter = Math.min(p[1], mfp.items.length),
				i;

			for(i = 1; i <= (mfp.direction ? preloadAfter : preloadBefore); i++) {
				mfp._preloadItem(mfp.index+i);
			}
			for(i = 1; i <= (mfp.direction ? preloadBefore : preloadAfter); i++) {
				mfp._preloadItem(mfp.index-i);
			}
		},
		_preloadItem: function(index) {
			index = _getLoopedId(index);

			if(mfp.items[index].preloaded) {
				return;
			}

			var item = mfp.items[index];
			if(!item.parsed) {
				item = mfp.parseEl( index );
			}

			_mfpTrigger('LazyLoad', item);

			if(item.type === 'image') {
				item.img = $('<img class="mfp-img" />').on('load.mfploader', function() {
					item.hasSize = true;
				}).on('error.mfploader', function() {
					item.hasSize = true;
					item.loadError = true;
					_mfpTrigger('LazyLoadError', item);
				}).attr('src', item.src);
			}


			item.preloaded = true;
		}
	}
});

/*
Touch Support that might be implemented some day

addSwipeGesture: function() {
	var startX,
		moved,
		multipleTouches;

		return;

	var namespace = '.mfp',
		addEventNames = function(pref, down, move, up, cancel) {
			mfp._tStart = pref + down + namespace;
			mfp._tMove = pref + move + namespace;
			mfp._tEnd = pref + up + namespace;
			mfp._tCancel = pref + cancel + namespace;
		};

	if(window.navigator.msPointerEnabled) {
		addEventNames('MSPointer', 'Down', 'Move', 'Up', 'Cancel');
	} else if('ontouchstart' in window) {
		addEventNames('touch', 'start', 'move', 'end', 'cancel');
	} else {
		return;
	}
	_window.on(mfp._tStart, function(e) {
		var oE = e.originalEvent;
		multipleTouches = moved = false;
		startX = oE.pageX || oE.changedTouches[0].pageX;
	}).on(mfp._tMove, function(e) {
		if(e.originalEvent.touches.length > 1) {
			multipleTouches = e.originalEvent.touches.length;
		} else {
			//e.preventDefault();
			moved = true;
		}
	}).on(mfp._tEnd + ' ' + mfp._tCancel, function(e) {
		if(moved && !multipleTouches) {
			var oE = e.originalEvent,
				diff = startX - (oE.pageX || oE.changedTouches[0].pageX);

			if(diff > 20) {
				mfp.next();
			} else if(diff < -20) {
				mfp.prev();
			}
		}
	});
},
*/


/*>>gallery*/

/*>>retina*/

var RETINA_NS = 'retina';

$.magnificPopup.registerModule(RETINA_NS, {
	options: {
		replaceSrc: function(item) {
			return item.src.replace(/\.\w+$/, function(m) { return '@2x' + m; });
		},
		ratio: 1 // Function or number.  Set to 1 to disable.
	},
	proto: {
		initRetina: function() {
			if(window.devicePixelRatio > 1) {

				var st = mfp.st.retina,
					ratio = st.ratio;

				ratio = !isNaN(ratio) ? ratio : ratio();

				if(ratio > 1) {
					_mfpOn('ImageHasSize' + '.' + RETINA_NS, function(e, item) {
						item.img.css({
							'max-width': item.img[0].naturalWidth / ratio,
							'width': '100%'
						});
					});
					_mfpOn('ElementParse' + '.' + RETINA_NS, function(e, item) {
						item.src = st.replaceSrc(item, ratio);
					});
				}
			}

		}
	}
});

/*>>retina*/

/*>>fastclick*/
/**
 * FastClick event implementation. (removes 300ms delay on touch devices)
 * Based on https://developers.google.com/mobile/articles/fast_buttons
 *
 * You may use it outside the Magnific Popup by calling just:
 *
 * $('.your-el').mfpFastClick(function() {
 *     console.log('Clicked!');
 * });
 *
 * To unbind:
 * $('.your-el').destroyMfpFastClick();
 * 
 * 
 * Note that it's a very basic and simple implementation, it blocks ghost click on the same element where it was bound.
 * If you need something more advanced, use plugin by FT Labs https://github.com/ftlabs/fastclick
 * 
 */

(function() {
	var ghostClickDelay = 1000,
		supportsTouch = 'ontouchstart' in window,
		unbindTouchMove = function() {
			_window.off('touchmove'+ns+' touchend'+ns);
		},
		eName = 'mfpFastClick',
		ns = '.'+eName;


	// As Zepto.js doesn't have an easy way to add custom events (like jQuery), so we implement it in this way
	$.fn.mfpFastClick = function(callback) {

		return $(this).each(function() {

			var elem = $(this),
				lock;

			if( supportsTouch ) {

				var timeout,
					startX,
					startY,
					pointerMoved,
					point,
					numPointers;

				elem.on('touchstart' + ns, function(e) {
					pointerMoved = false;
					numPointers = 1;

					point = e.originalEvent ? e.originalEvent.touches[0] : e.touches[0];
					startX = point.clientX;
					startY = point.clientY;

					_window.on('touchmove'+ns, function(e) {
						point = e.originalEvent ? e.originalEvent.touches : e.touches;
						numPointers = point.length;
						point = point[0];
						if (Math.abs(point.clientX - startX) > 10 ||
							Math.abs(point.clientY - startY) > 10) {
							pointerMoved = true;
							unbindTouchMove();
						}
					}).on('touchend'+ns, function(e) {
						unbindTouchMove();
						if(pointerMoved || numPointers > 1) {
							return;
						}
						lock = true;
						e.preventDefault();
						clearTimeout(timeout);
						timeout = setTimeout(function() {
							lock = false;
						}, ghostClickDelay);
						callback();
					});
				});

			}

			elem.on('click' + ns, function() {
				if(!lock) {
					callback();
				}
			});
		});
	};

	$.fn.destroyMfpFastClick = function() {
		$(this).off('touchstart' + ns + ' click' + ns);
		if(supportsTouch) _window.off('touchmove'+ns+' touchend'+ns);
	};
})();

/*>>fastclick*/
 _checkInstance(); })(window.jQuery || window.Zepto);
AUI().ready(
	function () {
		
		setInterval(function () {
			updateJournalArticlesOptionsLabel();
		}, 1000);
		
	}
);


function updateJournalArticlesOptionsLabel() {
	let journalArticleAssetRenderFactoryOptions = $('#_com_liferay_asset_list_web_portlet_AssetListPortlet_JournalArticleAssetRendererFactoryOptions');

	if (journalArticleAssetRenderFactoryOptions.length == 1 && !isGlobalLabelPresentInWebContentArticlesOptions()) {
		
		Liferay.Service(
			'/classname/fetch-class-name',
			{
				value: 'com.liferay.journal.model.JournalArticle'
			},
			function(className) {

				Liferay.Service(
					'/ddm.ddmstructure/get-structures',
					{
						companyId: Liferay.ThemeDisplay.getCompanyId(),
						groupIds: [Liferay.ThemeDisplay.getCompanyGroupId()],
						classNameId: className.classNameId,
						status: Liferay.Workflow.STATUS_APPROVED
					},
					function(ddmStructures) {
						ddmStructures.forEach(function(ddmStructure) {
							let singleItemSubtypeOption = document.querySelector("#_com_liferay_asset_list_web_portlet_AssetListPortlet_JournalArticleAssetRendererFactoryOptions option[value='" + ddmStructure.structureId + "']");
							if(singleItemSubtypeOption){
								singleItemSubtypeOption.innerHTML = singleItemSubtypeOption.innerHTML + ' (Global)';
							}
							
							
							let choiceSelectorOption = document.querySelector("#_com_liferay_asset_list_web_portlet_AssetListPortlet_JournalArticleAssetRendererFactorycurrentClassTypeIds option[value='" + ddmStructure.structureId + "']");
							if(choiceSelectorOption){
								choiceSelectorOption.innerHTML = choiceSelectorOption.innerHTML + ' (Global)';
							}
							
							let availableSelectorOption = document.querySelector("#_com_liferay_asset_list_web_portlet_AssetListPortlet_JournalArticleAssetRendererFactoryavailableClassTypeIds option[value='" + ddmStructure.structureId + "']");
							if(availableSelectorOption){
								availableSelectorOption.innerHTML = availableSelectorOption.innerHTML + ' (Global)';
							}
						});
					}
				);
			}
		);
	}
}

function isGlobalLabelPresentInWebContentArticlesOptions() {
	let isGlobalLabelPresent = false;
	let optionGroup = document.querySelector("#_com_liferay_asset_list_web_portlet_AssetListPortlet_anyClassTypeJournalArticleAssetRendererFactory optgroup[label='Single Item Subtype']");

	for(const option of optionGroup.children) {
		let optionText = option.innerHTML;
		if (optionText.includes("(Global)")) {
			isGlobalLabelPresent = true;
			break;
		}
	}
	return isGlobalLabelPresent;
}

/**
* jquery-match-height master by @liabru
* http://brm.io/jquery-match-height/
* License: MIT
*/

;(function(factory) { // eslint-disable-line no-extra-semi
    'use strict';
    if (typeof define === 'function' && define.amd) {
        // AMD
        define(['jquery'], factory);
    } else if (typeof module !== 'undefined' && module.exports) {
        // CommonJS
        module.exports = factory(require('jquery'));
    } else {
        // Global
        factory(jQuery);
    }
})(function($) {
    /*
    *  internal
    */

    var _previousResizeWidth = -1,
        _updateTimeout = -1;

    /*
    *  _parse
    *  value parse utility function
    */

    var _parse = function(value) {
        // parse value and convert NaN to 0
        return parseFloat(value) || 0;
    };

    /*
    *  _rows
    *  utility function returns array of jQuery selections representing each row
    *  (as displayed after float wrapping applied by browser)
    */

    var _rows = function(elements) {
        var tolerance = 1,
            $elements = $(elements),
            lastTop = null,
            rows = [];

        // group elements by their top position
        $elements.each(function(){
            var $that = $(this),
                top = $that.offset().top - _parse($that.css('margin-top')),
                lastRow = rows.length > 0 ? rows[rows.length - 1] : null;

            if (lastRow === null) {
                // first item on the row, so just push it
                rows.push($that);
            } else {
                // if the row top is the same, add to the row group
                if (Math.floor(Math.abs(lastTop - top)) <= tolerance) {
                    rows[rows.length - 1] = lastRow.add($that);
                } else {
                    // otherwise start a new row group
                    rows.push($that);
                }
            }

            // keep track of the last row top
            lastTop = top;
        });

        return rows;
    };

    /*
    *  _parseOptions
    *  handle plugin options
    */

    var _parseOptions = function(options) {
        var opts = {
            byRow: true,
            property: 'height',
            target: null,
            remove: false
        };

        if (typeof options === 'object') {
            return $.extend(opts, options);
        }

        if (typeof options === 'boolean') {
            opts.byRow = options;
        } else if (options === 'remove') {
            opts.remove = true;
        }

        return opts;
    };

    /*
    *  matchHeight
    *  plugin definition
    */

    var matchHeight = $.fn.matchHeight = function(options) {
        var opts = _parseOptions(options);

        // handle remove
        if (opts.remove) {
            var that = this;

            // remove fixed height from all selected elements
            this.css(opts.property, '');

            // remove selected elements from all groups
            $.each(matchHeight._groups, function(key, group) {
                group.elements = group.elements.not(that);
            });

            // TODO: cleanup empty groups

            return this;
        }

        if (this.length <= 1 && !opts.target) {
            return this;
        }

        // keep track of this group so we can re-apply later on load and resize events
        matchHeight._groups.push({
            elements: this,
            options: opts
        });

        // match each element's height to the tallest element in the selection
        matchHeight._apply(this, opts);

        return this;
    };

    /*
    *  plugin global options
    */

    matchHeight.version = 'master';
    matchHeight._groups = [];
    matchHeight._throttle = 80;
    matchHeight._maintainScroll = false;
    matchHeight._beforeUpdate = null;
    matchHeight._afterUpdate = null;
    matchHeight._rows = _rows;
    matchHeight._parse = _parse;
    matchHeight._parseOptions = _parseOptions;

    /*
    *  matchHeight._apply
    *  apply matchHeight to given elements
    */

    matchHeight._apply = function(elements, options) {
        var opts = _parseOptions(options),
            $elements = $(elements),
            rows = [$elements];

        // take note of scroll position
        var scrollTop = $(window).scrollTop(),
            htmlHeight = $('html').outerHeight(true);

        // get hidden parents
        var $hiddenParents = $elements.parents().filter(':hidden');

        // cache the original inline style
        $hiddenParents.each(function() {
            var $that = $(this);
            $that.data('style-cache', $that.attr('style'));
        });

        // temporarily must force hidden parents visible
        $hiddenParents.css('display', 'block');

        // get rows if using byRow, otherwise assume one row
        if (opts.byRow && !opts.target) {

            // must first force an arbitrary equal height so floating elements break evenly
            $elements.each(function() {
                var $that = $(this),
                    display = $that.css('display');

                // temporarily force a usable display value
                if (display !== 'inline-block' && display !== 'flex' && display !== 'inline-flex') {
                    display = 'block';
                }

                // cache the original inline style
                $that.data('style-cache', $that.attr('style'));

                $that.css({
                    'display': display,
                    'padding-top': '0',
                    'padding-bottom': '0',
                    'margin-top': '0',
                    'margin-bottom': '0',
                    'border-top-width': '0',
                    'border-bottom-width': '0',
                    'height': '100px',
                    'overflow': 'hidden'
                });
            });

            // get the array of rows (based on element top position)
            rows = _rows($elements);

            // revert original inline styles
            $elements.each(function() {
                var $that = $(this);
                $that.attr('style', $that.data('style-cache') || '');
            });
        }

        $.each(rows, function(key, row) {
            var $row = $(row),
                targetHeight = 0;

            if (!opts.target) {
                // skip apply to rows with only one item
                if (opts.byRow && $row.length <= 1) {
                    $row.css(opts.property, '');
                    return;
                }

                // iterate the row and find the max height
                $row.each(function(){
                    var $that = $(this),
                        style = $that.attr('style'),
                        display = $that.css('display');

                    // temporarily force a usable display value
                    if (display !== 'inline-block' && display !== 'flex' && display !== 'inline-flex') {
                        display = 'block';
                    }

                    // ensure we get the correct actual height (and not a previously set height value)
                    var css = { 'display': display };
                    css[opts.property] = '';
                    $that.css(css);

                    // find the max height (including padding, but not margin)
                    if ($that.outerHeight(false) > targetHeight) {
                        targetHeight = $that.outerHeight(false);
                    }

                    // revert styles
                    if (style) {
                        $that.attr('style', style);
                    } else {
                        $that.css('display', '');
                    }
                });
            } else {
                // if target set, use the height of the target element
                targetHeight = opts.target.outerHeight(false);
            }

            // iterate the row and apply the height to all elements
            $row.each(function(){
                var $that = $(this),
                    verticalPadding = 0;

                // don't apply to a target
                if (opts.target && $that.is(opts.target)) {
                    return;
                }

                // handle padding and border correctly (required when not using border-box)
                if ($that.css('box-sizing') !== 'border-box') {
                    verticalPadding += _parse($that.css('border-top-width')) + _parse($that.css('border-bottom-width'));
                    verticalPadding += _parse($that.css('padding-top')) + _parse($that.css('padding-bottom'));
                }

                // set the height (accounting for padding and border)
                $that.css(opts.property, (targetHeight - verticalPadding) + 'px');
            });
        });

        // revert hidden parents
        $hiddenParents.each(function() {
            var $that = $(this);
            $that.attr('style', $that.data('style-cache') || null);
        });

        // restore scroll position if enabled
        if (matchHeight._maintainScroll) {
            $(window).scrollTop((scrollTop / htmlHeight) * $('html').outerHeight(true));
        }

        return this;
    };

    /*
    *  matchHeight._applyDataApi
    *  applies matchHeight to all elements with a data-match-height attribute
    */

    matchHeight._applyDataApi = function() {
        var groups = {};

        // generate groups by their groupId set by elements using data-match-height
        $('[data-match-height], [data-mh]').each(function() {
            var $this = $(this),
                groupId = $this.attr('data-mh') || $this.attr('data-match-height');

            if (groupId in groups) {
                groups[groupId] = groups[groupId].add($this);
            } else {
                groups[groupId] = $this;
            }
        });

        // apply matchHeight to each group
        $.each(groups, function() {
            this.matchHeight(true);
        });
    };

    /*
    *  matchHeight._update
    *  updates matchHeight on all current groups with their correct options
    */

    var _update = function(event) {
        if (matchHeight._beforeUpdate) {
            matchHeight._beforeUpdate(event, matchHeight._groups);
        }

        $.each(matchHeight._groups, function() {
            matchHeight._apply(this.elements, this.options);
        });

        if (matchHeight._afterUpdate) {
            matchHeight._afterUpdate(event, matchHeight._groups);
        }
    };

    matchHeight._update = function(throttle, event) {
        // prevent update if fired from a resize event
        // where the viewport width hasn't actually changed
        // fixes an event looping bug in IE8
        if (event && event.type === 'resize') {
            var windowWidth = $(window).width();
            if (windowWidth === _previousResizeWidth) {
                return;
            }
            _previousResizeWidth = windowWidth;
        }

        // throttle updates
        if (!throttle) {
            _update(event);
        } else if (_updateTimeout === -1) {
            _updateTimeout = setTimeout(function() {
                _update(event);
                _updateTimeout = -1;
            }, matchHeight._throttle);
        }
    };

    /*
    *  bind events
    */

    // apply on DOM ready event
    $(matchHeight._applyDataApi);

    // use on or bind where supported
    var on = $.fn.on ? 'on' : 'bind';

    // update heights on load and resize events
    $(window)[on]('load', function(event) {
        matchHeight._update(false, event);
    });

    // throttled update heights on resize events
    $(window)[on]('resize orientationchange', function(event) {
        matchHeight._update(true, event);
    });

});

Liferay.Portlet.ready(
    function (portletId) {
		if ($('[id*="_inputPermissionsViewRole"]').length) {
			Liferay.Util.fetch(
				Liferay.ThemeDisplay.getPortalURL() + '/o/inputPermission/services/check-model-name-default-publish-permission-as-guest?groupId=' + Liferay.ThemeDisplay.getScopeGroupId() + '&portletId=' + portletId,
				{
					method: 'GET',
					headers: {
					'Content-Type':
					'text/plain'
					}
			}).then( function(response) {
				if(response.ok){
					return response.text();
				}
			}).then(function(data) {
				if (data.toString() === 'true') {
					$('select[id$="inputPermissionsViewRole"]').val('Guest');
					$('select[id$="inputPermissionsViewRole"]').trigger('change');
				}
			});
		}
	}
);

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

Liferay.on('endNavigate', function() {
	initGDSThemeContributor();
	focusErrors();
});

Liferay.on('allPortletsReady', function() {
	focusErrors();
})

function focusErrors() {
	var errorsSummary = $(".govuk-error-summary").first();
	
	if (errorsSummary.length > 0) {
		errorsSummary.focus();
	}
}

function initGDSThemeContributor() {
	document.body.className = ((document.body.className) ? document.body.className + ' js-enabled' : 'js-enabled');
	window.GOVUKFrontend.initAll();
}
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define("GOVUKFrontend",["exports"],e):e(t.GOVUKFrontend={})}(this,(function(t){"use strict";function e(t,e){if(window.NodeList.prototype.forEach)return t.forEach(e);for(var n=0;n<t.length;n++)e.call(window,t[n],n,t)}function n(){for(var t=function(t){var e={},n=function(t,i){for(var o in t)if(Object.prototype.hasOwnProperty.call(t,o)){var s=t[o],r=i?i+"."+o:o;"object"==typeof s?n(s,r):e[r]=s}};return n(t),e},e={},n=0;n<arguments.length;n++){var i=t(arguments[n]);for(var o in i)Object.prototype.hasOwnProperty.call(i,o)&&(e[o]=i[o])}return e}function i(t,e){if(!t||"object"!=typeof t)throw new Error('Provide a `configObject` of type "object".');if(!e||"string"!=typeof e)throw new Error('Provide a `namespace` of type "string" to filter the `configObject` by.');var n={};for(var i in t){var o=i.split(".");if(Object.prototype.hasOwnProperty.call(t,i)&&o[0]===e)o.length>1&&o.shift(),n[o.join(".")]=t[i]}return n}function o(t){if("string"!=typeof t)return t;var e=t.trim();return"true"===e||"false"!==e&&(e.length>0&&isFinite(Number(e))?Number(e):t)}function s(t){var e={};for(var n in t)e[n]=o(t[n]);return e}function r(t,e){this.translations=t||{},this.locale=e&&e.locale||document.documentElement.lang||"en"}(function(t){var e,n,i,o;"defineProperty"in Object&&function(){try{return Object.defineProperty({},"test",{value:42}),!0}catch(t){return!1}}()||(e=Object.defineProperty,n=Object.prototype.hasOwnProperty("__defineGetter__"),i="Getters & setters cannot be defined on this javascript engine",o="A property cannot both have accessors and be writable or have a value",Object.defineProperty=function(t,s,r){if(e&&(t===window||t===document||t===Element.prototype||t instanceof Element))return e(t,s,r);if(null===t||!(t instanceof Object||"object"==typeof t))throw new TypeError("Object.defineProperty called on non-object");if(!(r instanceof Object))throw new TypeError("Property description must be an object");var a=String(s),l="value"in r||"writable"in r,c="get"in r&&typeof r.get,u="set"in r&&typeof r.set;if(c){if("function"!==c)throw new TypeError("Getter must be a function");if(!n)throw new TypeError(i);if(l)throw new TypeError(o);Object.__defineGetter__.call(t,a,r.get)}else t[a]=r.value;if(u){if("function"!==u)throw new TypeError("Setter must be a function");if(!n)throw new TypeError(i);if(l)throw new TypeError(o);Object.__defineSetter__.call(t,a,r.set)}return"value"in r&&(t[a]=r.value),t})}).call("object"==typeof window&&window||"object"==typeof self&&self||"object"==typeof global&&global||{}),function(t){"Document"in this||"undefined"==typeof WorkerGlobalScope&&"function"!=typeof importScripts&&(this.HTMLDocument?this.Document=this.HTMLDocument:(this.Document=this.HTMLDocument=document.constructor=new Function("return function Document() {}")(),this.Document.prototype=document))}.call("object"==typeof window&&window||"object"==typeof self&&self||"object"==typeof global&&global||{}),function(t){"Element"in this&&"HTMLElement"in this||function(){if(!window.Element||window.HTMLElement){window.Element=window.HTMLElement=new Function("return function Element() {}")();var t,e=document.appendChild(document.createElement("body")),n=e.appendChild(document.createElement("iframe")).contentWindow.document,i=Element.prototype=n.appendChild(n.createElement("*")),o={},s=function(t,e){var n,i,r,a=t.childNodes||[],l=-1;if(1===t.nodeType&&t.constructor!==Element)for(n in t.constructor=Element,o)i=o[n],t[n]=i;for(;r=e&&a[++l];)s(r,e);return t},r=document.getElementsByTagName("*"),a=document.createElement,l=100;i.attachEvent("onpropertychange",(function(t){for(var e,n=t.propertyName,s=!o.hasOwnProperty(n),a=i[n],l=o[n],c=-1;e=r[++c];)1===e.nodeType&&(s||e[n]===l)&&(e[n]=a);o[n]=a})),i.constructor=Element,i.hasAttribute||(i.hasAttribute=function(t){return null!==this.getAttribute(t)}),c()||(document.onreadystatechange=c,t=setInterval(c,25)),document.createElement=function(t){var e=a(String(t).toLowerCase());return s(e)},document.removeChild(e)}else window.HTMLElement=window.Element;function c(){return l--||clearTimeout(t),!(!document.body||document.body.prototype||!/(complete|interactive)/.test(document.readyState))&&(s(document,!0),t&&document.body.prototype&&clearTimeout(t),!!document.body.prototype)}}()}.call("object"==typeof window&&window||"object"==typeof self&&self||"object"==typeof global&&global||{}),function(t){(function(){if(!document.documentElement.dataset)return!1;var t=document.createElement("div");return t.setAttribute("data-a-b","c"),t.dataset&&"c"==t.dataset.aB})()||Object.defineProperty(Element.prototype,"dataset",{get:function(){for(var t=this.attributes,e={},n=0;n<t.length;n++){var i=t[n];if(i&&i.name&&/^data-\w[.\w-]*$/.test(i.name)){var o=i.name,s=i.value,r=o.substr(5).replace(/-./g,(function(t){return t.charAt(1).toUpperCase()}));"__defineGetter__"in Object.prototype&&"__defineSetter__"in Object.prototype?Object.defineProperty(e,r,{enumerable:!0,get:function(){return this.value}.bind({value:s||""}),set:function(t,e){void 0!==e?this.setAttribute(t,e):this.removeAttribute(t)}.bind(this,o)}):e[r]=s}}return e}})}.call("object"==typeof window&&window||"object"==typeof self&&self||"object"==typeof global&&global||{}),function(t){"trim"in String.prototype||(String.prototype.trim=function(){return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")})}.call("object"==typeof window&&window||"object"==typeof self&&self||"object"==typeof global&&global||{}),r.prototype.t=function(t,e){if(!t)throw new Error("i18n: lookup key missing");e&&"number"==typeof e.count&&(t=t+"."+this.getPluralSuffix(t,e.count));var n=this.translations[t];if("string"==typeof n){if(n.match(/%{(.\S+)}/)){if(!e)throw new Error("i18n: cannot replace placeholders in string if no option data provided");return this.replacePlaceholders(n,e)}return n}return t},r.prototype.replacePlaceholders=function(t,e){var n;return this.hasIntlNumberFormatSupport()&&(n=new Intl.NumberFormat(this.locale)),t.replace(/%{(.\S+)}/g,(function(t,i){if(Object.prototype.hasOwnProperty.call(e,i)){var o=e[i];return!1===o||"number"!=typeof o&&"string"!=typeof o?"":"number"==typeof o?n?n.format(o):o.toString():o}throw new Error("i18n: no data found to replace "+t+" placeholder in string")}))},r.prototype.hasIntlPluralRulesSupport=function(){return Boolean(window.Intl&&"PluralRules"in window.Intl&&Intl.PluralRules.supportedLocalesOf(this.locale).length)},r.prototype.hasIntlNumberFormatSupport=function(){return Boolean(window.Intl&&"NumberFormat"in window.Intl&&Intl.NumberFormat.supportedLocalesOf(this.locale).length)},r.prototype.getPluralSuffix=function(t,e){if(e=Number(e),!isFinite(e))return"other";var n;if(t+"."+(n=this.hasIntlPluralRulesSupport()?new Intl.PluralRules(this.locale).select(e):this.selectPluralFormUsingFallbackRules(e))in this.translations)return n;if(t+".other"in this.translations)return console&&"warn"in console&&console.warn('i18n: Missing plural form ".'+n+'" for "'+this.locale+'" locale. Falling back to ".other".'),"other";throw new Error('i18n: Plural form ".other" is required for "'+this.locale+'" locale')},r.prototype.selectPluralFormUsingFallbackRules=function(t){t=Math.abs(Math.floor(t));var e=this.getPluralRulesForLocale();return e?r.pluralRules[e](t):"other"},r.prototype.getPluralRulesForLocale=function(){var t=this.locale,e=t.split("-")[0];for(var n in r.pluralRulesMap)if(Object.prototype.hasOwnProperty.call(r.pluralRulesMap,n))for(var i=r.pluralRulesMap[n],o=0;o<i.length;o++)if(i[o]===t||i[o]===e)return n},r.pluralRulesMap={arabic:["ar"],chinese:["my","zh","id","ja","jv","ko","ms","th","vi"],french:["hy","bn","fr","gu","hi","fa","pa","zu"],german:["af","sq","az","eu","bg","ca","da","nl","en","et","fi","ka","de","el","hu","lb","no","so","sw","sv","ta","te","tr","ur"],irish:["ga"],russian:["ru","uk"],scottish:["gd"],spanish:["pt-PT","it","es"],welsh:["cy"]},r.pluralRules={arabic:function(t){return 0===t?"zero":1===t?"one":2===t?"two":t%100>=3&&t%100<=10?"few":t%100>=11&&t%100<=99?"many":"other"},chinese:function(){return"other"},french:function(t){return 0===t||1===t?"one":"other"},german:function(t){return 1===t?"one":"other"},irish:function(t){return 1===t?"one":2===t?"two":t>=3&&t<=6?"few":t>=7&&t<=10?"many":"other"},russian:function(t){var e=t%100,n=e%10;return 1===n&&11!==e?"one":n>=2&&n<=4&&!(e>=12&&e<=14)?"few":0===n||n>=5&&n<=9||e>=11&&e<=14?"many":"other"},scottish:function(t){return 1===t||11===t?"one":2===t||12===t?"two":t>=3&&t<=10||t>=13&&t<=19?"few":"other"},spanish:function(t){return 1===t?"one":t%1e6==0&&0!==t?"many":"other"},welsh:function(t){return 0===t?"zero":1===t?"one":2===t?"two":3===t?"few":6===t?"many":"other"}},function(t){var e;"DOMTokenList"in this&&(!("classList"in(e=document.createElement("x")))||!e.classList.toggle("x",!1)&&!e.className)||function(e){var n;"DOMTokenList"in e&&e.DOMTokenList&&(!document.createElementNS||!document.createElementNS("http://www.w3.org/2000/svg","svg")||document.createElementNS("http://www.w3.org/2000/svg","svg").classList instanceof DOMTokenList)||(e.DOMTokenList=function(){var e=!0,i=function(t,n,i,o){Object.defineProperty?Object.defineProperty(t,n,{configurable:!1===e||!!o,get:i}):t.__defineGetter__(n,i)};try{i({},"support")}catch(n){e=!1}return function(e,n){var o=this,s=[],r={},a=0,l=0,c=function(t){i(o,t,(function(){return d(),s[t]}),!1)},u=function(){if(a>=l)for(;l<a;++l)c(l)},d=function(){var t,i,o=arguments,l=/\s+/;if(o.length)for(i=0;i<o.length;++i)if(l.test(o[i]))throw(t=new SyntaxError('String "'+o[i]+'" contains an invalid character')).code=5,t.name="InvalidCharacterError",t;for(""===(s="object"==typeof e[n]?(""+e[n].baseVal).replace(/^\s+|\s+$/g,"").split(l):(""+e[n]).replace(/^\s+|\s+$/g,"").split(l))[0]&&(s=[]),r={},i=0;i<s.length;++i)r[s[i]]=!0;a=s.length,u()};return d(),i(o,"length",(function(){return d(),a})),o.toLocaleString=o.toString=function(){return d(),s.join(" ")},o.item=function(t){return d(),s[t]},o.contains=function(t){return d(),!!r[t]},o.add=function(){d.apply(o,t=arguments);for(var t,i,l=0,c=t.length;l<c;++l)r[i=t[l]]||(s.push(i),r[i]=!0);a!==s.length&&(a=s.length>>>0,"object"==typeof e[n]?e[n].baseVal=s.join(" "):e[n]=s.join(" "),u())},o.remove=function(){d.apply(o,t=arguments);for(var t,i={},l=0,c=[];l<t.length;++l)i[t[l]]=!0,delete r[t[l]];for(l=0;l<s.length;++l)i[s[l]]||c.push(s[l]);s=c,a=c.length>>>0,"object"==typeof e[n]?e[n].baseVal=s.join(" "):e[n]=s.join(" "),u()},o.toggle=function(e,n){return d.apply(o,[e]),t!==n?n?(o.add(e),!0):(o.remove(e),!1):r[e]?(o.remove(e),!1):(o.add(e),!0)},o}}()),"classList"in(n=document.createElement("span"))&&(n.classList.toggle("x",!1),n.classList.contains("x")&&(n.classList.constructor.prototype.toggle=function(e){var n=arguments[1];if(n===t){var i=!this.contains(e);return this[i?"add":"remove"](e),i}return this[(n=!!n)?"add":"remove"](e),n})),function(){var t=document.createElement("span");if("classList"in t&&(t.classList.add("a","b"),!t.classList.contains("b"))){var e=t.classList.constructor.prototype.add;t.classList.constructor.prototype.add=function(){for(var t=arguments,n=arguments.length,i=0;i<n;i++)e.call(this,t[i])}}}(),function(){var t=document.createElement("span");if("classList"in t&&(t.classList.add("a"),t.classList.add("b"),t.classList.remove("a","b"),t.classList.contains("b"))){var e=t.classList.constructor.prototype.remove;t.classList.constructor.prototype.remove=function(){for(var t=arguments,n=arguments.length,i=0;i<n;i++)e.call(this,t[i])}}}()}(this)}.call("object"==typeof window&&window||"object"==typeof self&&self||"object"==typeof global&&global||{}),function(t){var e;"document"in this&&"classList"in document.documentElement&&"Element"in this&&"classList"in Element.prototype&&((e=document.createElement("span")).classList.add("a","b"),e.classList.contains("b"))||function(t){var n=!0,i=function(t,e,i,o){Object.defineProperty?Object.defineProperty(t,e,{configurable:!1===n||!!o,get:i}):t.__defineGetter__(e,i)};try{i({},"support")}catch(e){n=!1}var o=function(t,e,s){i(t.prototype,e,(function(){var t,r=this,a="__defineGetter__DEFINE_PROPERTY"+e;if(r[a])return t;if(r[a]=!0,!1===n){for(var l,c=o.mirror||document.createElement("div"),u=c.childNodes,d=u.length,h=0;h<d;++h)if(u[h]._R===r){l=u[h];break}l||(l=c.appendChild(document.createElement("div"))),t=DOMTokenList.call(l,r,s)}else t=new DOMTokenList(r,s);return i(r,e,(function(){return t})),delete r[a],t}),!0)};o(t.Element,"classList","className"),o(t.HTMLElement,"classList","className"),o(t.HTMLLinkElement,"relList","rel"),o(t.HTMLAnchorElement,"relList","rel"),o(t.HTMLAreaElement,"relList","rel")}(this)}.call("object"==typeof window&&window||"object"==typeof self&&self||"object"==typeof global&&global||{}),function(t){"document"in this&&"matches"in document.documentElement||(Element.prototype.matches=Element.prototype.webkitMatchesSelector||Element.prototype.oMatchesSelector||Element.prototype.msMatchesSelector||Element.prototype.mozMatchesSelector||function(t){for(var e=this,n=(e.document||e.ownerDocument).querySelectorAll(t),i=0;n[i]&&n[i]!==e;)++i;return!!n[i]})}.call("object"==typeof window&&window||"object"==typeof self&&self||"object"==typeof global&&global||{}),function(t){"document"in this&&"closest"in document.documentElement||(Element.prototype.closest=function(t){for(var e=this;e;){if(e.matches(t))return e;e="SVGElement"in window&&e instanceof SVGElement?e.parentNode:e.parentElement}return null})}.call("object"==typeof window&&window||"object"==typeof self&&self||"object"==typeof global&&global||{}),function(t){"Window"in this||"undefined"==typeof WorkerGlobalScope&&"function"!=typeof importScripts&&function(t){t.constructor?t.Window=t.constructor:(t.Window=t.constructor=new Function("return function Window() {}")()).prototype=this}(this)}.call("object"==typeof window&&window||"object"==typeof self&&self||"object"==typeof global&&global||{}),function(t){(function(t){if(!("Event"in t))return!1;if("function"==typeof t.Event)return!0;try{return new Event("click"),!0}catch(e){return!1}})(this)||function(){var e={click:1,dblclick:1,keyup:1,keypress:1,keydown:1,mousedown:1,mouseup:1,mousemove:1,mouseover:1,mouseenter:1,mouseleave:1,mouseout:1,storage:1,storagecommit:1,textinput:1};if("undefined"!=typeof document&&"undefined"!=typeof window){var n=window.Event&&window.Event.prototype||null;window.Event=Window.prototype.Event=function(e,n){if(!e)throw new Error("Not enough arguments");var i;if("createEvent"in document){i=document.createEvent("Event");var o=!(!n||n.bubbles===t)&&n.bubbles,s=!(!n||n.cancelable===t)&&n.cancelable;return i.initEvent(e,o,s),i}return(i=document.createEventObject()).type=e,i.bubbles=!(!n||n.bubbles===t)&&n.bubbles,i.cancelable=!(!n||n.cancelable===t)&&n.cancelable,i},n&&Object.defineProperty(window.Event,"prototype",{configurable:!1,enumerable:!1,writable:!0,value:n}),"createEvent"in document||(window.addEventListener=Window.prototype.addEventListener=Document.prototype.addEventListener=Element.prototype.addEventListener=function(){var t=this,n=arguments[0],o=arguments[1];if(t===window&&n in e)throw new Error("In IE8 the event: "+n+" is not available on the window object. Please see https://github.com/Financial-Times/polyfill-service/issues/317 for more information.");t._events||(t._events={}),t._events[n]||(t._events[n]=function(e){var n,o=t._events[e.type].list,s=o.slice(),r=-1,a=s.length;for(e.preventDefault=function(){!1!==e.cancelable&&(e.returnValue=!1)},e.stopPropagation=function(){e.cancelBubble=!0},e.stopImmediatePropagation=function(){e.cancelBubble=!0,e.cancelImmediate=!0},e.currentTarget=t,e.relatedTarget=e.fromElement||null,e.target=e.target||e.srcElement||t,e.timeStamp=(new Date).getTime(),e.clientX&&(e.pageX=e.clientX+document.documentElement.scrollLeft,e.pageY=e.clientY+document.documentElement.scrollTop);++r<a&&!e.cancelImmediate;)r in s&&-1!==i(o,n=s[r])&&"function"==typeof n&&n.call(t,e)},t._events[n].list=[],t.attachEvent&&t.attachEvent("on"+n,t._events[n])),t._events[n].list.push(o)},window.removeEventListener=Window.prototype.removeEventListener=Document.prototype.removeEventListener=Element.prototype.removeEventListener=function(){var t,e=this,n=arguments[0],o=arguments[1];e._events&&e._events[n]&&e._events[n].list&&-1!==(t=i(e._events[n].list,o))&&(e._events[n].list.splice(t,1),e._events[n].list.length||(e.detachEvent&&e.detachEvent("on"+n,e._events[n]),delete e._events[n]))},window.dispatchEvent=Window.prototype.dispatchEvent=Document.prototype.dispatchEvent=Element.prototype.dispatchEvent=function(t){if(!arguments.length)throw new Error("Not enough arguments");if(!t||"string"!=typeof t.type)throw new Error("DOM Events Exception 0");var e=this,n=t.type;try{if(!t.bubbles){t.cancelBubble=!0;var i=function(t){t.cancelBubble=!0,(e||window).detachEvent("on"+n,i)};this.attachEvent("on"+n,i)}this.fireEvent("on"+n,t)}catch(o){t.target=e;do{t.currentTarget=e,"_events"in e&&"function"==typeof e._events[n]&&e._events[n].call(e,t),"function"==typeof e["on"+n]&&e["on"+n].call(e,t),e=9===e.nodeType?e.parentWindow:e.parentNode}while(e&&!t.cancelBubble)}return!0},document.attachEvent("onreadystatechange",(function(){"complete"===document.readyState&&document.dispatchEvent(new Event("DOMContentLoaded",{bubbles:!0}))})))}function i(t,e){for(var n=-1,i=t.length;++n<i;)if(n in t&&t[n]===e)return n;return-1}}()}.call("object"==typeof window&&window||"object"==typeof self&&self||"object"==typeof global&&global||{}),function(t){"bind"in Function.prototype||Object.defineProperty(Function.prototype,"bind",{value:function(t){var e,n=Array,i=Object,o=i.prototype,s=n.prototype,r=function(){},a=o.toString,l="function"==typeof Symbol&&"symbol"==typeof Symbol.toStringTag,c=Function.prototype.toString;e=function(t){if("function"!=typeof t)return!1;if(l)return function(t){try{return c.call(t),!0}catch(e){return!1}}(t);var e=a.call(t);return"[object Function]"===e||"[object GeneratorFunction]"===e};var u=s.slice,d=s.concat,h=s.push,p=Math.max,f=this;if(!e(f))throw new TypeError("Function.prototype.bind called on incompatible "+f);for(var m,v=u.call(arguments,1),b=p(0,f.length-v.length),g=[],y=0;y<b;y++)h.call(g,"$"+y);return m=Function("binder","return function ("+g.join(",")+"){ return binder.apply(this, arguments); }")((function(){if(this instanceof m){var e=f.apply(this,d.call(v,u.call(arguments)));return i(e)===e?e:this}return f.apply(t,d.call(v,u.call(arguments)))})),f.prototype&&(r.prototype=f.prototype,m.prototype=new r,r.prototype=null),m}})}.call("object"==typeof window&&window||"object"==typeof self&&self||"object"==typeof global&&global||{});var a={hideAllSections:"Hide all sections",hideSection:"Hide",hideSectionAriaLabel:"Hide this section",showAllSections:"Show all sections",showSection:"Show",showSectionAriaLabel:"Show this section"};function l(t,e){if(!(t instanceof HTMLElement))return this;this.$module=t;var o={i18n:a,rememberExpanded:!0};this.config=n(o,e||{},s(t.dataset)),this.i18n=new r(i(this.config,"i18n")),this.controlsClass="govuk-accordion__controls",this.showAllClass="govuk-accordion__show-all",this.showAllTextClass="govuk-accordion__show-all-text",this.sectionClass="govuk-accordion__section",this.sectionExpandedClass="govuk-accordion__section--expanded",this.sectionButtonClass="govuk-accordion__section-button",this.sectionHeaderClass="govuk-accordion__section-header",this.sectionHeadingClass="govuk-accordion__section-heading",this.sectionHeadingDividerClass="govuk-accordion__section-heading-divider",this.sectionHeadingTextClass="govuk-accordion__section-heading-text",this.sectionHeadingTextFocusClass="govuk-accordion__section-heading-text-focus",this.sectionShowHideToggleClass="govuk-accordion__section-toggle",this.sectionShowHideToggleFocusClass="govuk-accordion__section-toggle-focus",this.sectionShowHideTextClass="govuk-accordion__section-toggle-text",this.upChevronIconClass="govuk-accordion-nav__chevron",this.downChevronIconClass="govuk-accordion-nav__chevron--down",this.sectionSummaryClass="govuk-accordion__section-summary",this.sectionSummaryFocusClass="govuk-accordion__section-summary-focus",this.sectionContentClass="govuk-accordion__section-content";var l=this.$module.querySelectorAll("."+this.sectionClass);if(!l.length)return this;this.$sections=l,this.browserSupportsSessionStorage=c.checkForSessionStorage(),this.$showAllButton=null,this.$showAllIcon=null,this.$showAllText=null}l.prototype.init=function(){if(this.$module&&this.$sections){this.initControls(),this.initSectionHeaders();var t=this.checkIfAllSectionsOpen();this.updateShowAllButton(t)}},l.prototype.initControls=function(){this.$showAllButton=document.createElement("button"),this.$showAllButton.setAttribute("type","button"),this.$showAllButton.setAttribute("class",this.showAllClass),this.$showAllButton.setAttribute("aria-expanded","false"),this.$showAllIcon=document.createElement("span"),this.$showAllIcon.classList.add(this.upChevronIconClass),this.$showAllButton.appendChild(this.$showAllIcon);var t=document.createElement("div");t.setAttribute("class",this.controlsClass),t.appendChild(this.$showAllButton),this.$module.insertBefore(t,this.$module.firstChild),this.$showAllText=document.createElement("span"),this.$showAllText.classList.add(this.showAllTextClass),this.$showAllButton.appendChild(this.$showAllText),this.$showAllButton.addEventListener("click",this.onShowOrHideAllToggle.bind(this)),"onbeforematch"in document&&document.addEventListener("beforematch",this.onBeforeMatch.bind(this))},l.prototype.initSectionHeaders=function(){var t=this;e(this.$sections,(function(e,n){var i=e.querySelector("."+t.sectionHeaderClass);i&&(t.constructHeaderMarkup(i,n),t.setExpanded(t.isExpanded(e),e),i.addEventListener("click",t.onSectionToggle.bind(t,e)),t.setInitialState(e))}))},l.prototype.constructHeaderMarkup=function(t,e){var n=t.querySelector("."+this.sectionButtonClass),i=t.querySelector("."+this.sectionHeadingClass),o=t.querySelector("."+this.sectionSummaryClass);if(n&&i){var s=document.createElement("button");s.setAttribute("type","button"),s.setAttribute("aria-controls",this.$module.id+"-content-"+(e+1).toString());for(var r=0;r<n.attributes.length;r++){var a=n.attributes.item(r);"id"!==a.nodeName&&s.setAttribute(a.nodeName,a.nodeValue)}var l=document.createElement("span");l.classList.add(this.sectionHeadingTextClass),l.id=n.id;var c=document.createElement("span");c.classList.add(this.sectionHeadingTextFocusClass),l.appendChild(c),c.innerHTML=n.innerHTML;var u=document.createElement("span");u.classList.add(this.sectionShowHideToggleClass),u.setAttribute("data-nosnippet","");var d=document.createElement("span");d.classList.add(this.sectionShowHideToggleFocusClass),u.appendChild(d);var h=document.createElement("span"),p=document.createElement("span");if(p.classList.add(this.upChevronIconClass),d.appendChild(p),h.classList.add(this.sectionShowHideTextClass),d.appendChild(h),s.appendChild(l),s.appendChild(this.getButtonPunctuationEl()),o){var f=document.createElement("span"),m=document.createElement("span");m.classList.add(this.sectionSummaryFocusClass),f.appendChild(m);for(var v=0,b=o.attributes.length;v<b;++v){var g=o.attributes.item(v).nodeName,y=o.attributes.item(v).nodeValue;f.setAttribute(g,y)}m.innerHTML=o.innerHTML,o.parentNode.replaceChild(f,o),s.appendChild(f),s.appendChild(this.getButtonPunctuationEl())}s.appendChild(u),i.removeChild(n),i.appendChild(s)}},l.prototype.onBeforeMatch=function(t){var e=t.target;if(e instanceof Element){var n=e.closest("."+this.sectionClass);n&&this.setExpanded(!0,n)}},l.prototype.onSectionToggle=function(t){var e=this.isExpanded(t);this.setExpanded(!e,t),this.storeState(t)},l.prototype.onShowOrHideAllToggle=function(){var t=this,n=this.$sections,i=!this.checkIfAllSectionsOpen();e(n,(function(e){t.setExpanded(i,e),t.storeState(e)})),t.updateShowAllButton(i)},l.prototype.setExpanded=function(t,e){var n=e.querySelector("."+this.upChevronIconClass),i=e.querySelector("."+this.sectionShowHideTextClass),o=e.querySelector("."+this.sectionButtonClass),s=e.querySelector("."+this.sectionContentClass);if(n&&i instanceof HTMLElement&&o&&s){var r=t?this.i18n.t("hideSection"):this.i18n.t("showSection");i.innerText=r,o.setAttribute("aria-expanded",t.toString());var a=[],l=e.querySelector("."+this.sectionHeadingTextClass);l instanceof HTMLElement&&a.push(l.innerText.trim());var c=e.querySelector("."+this.sectionSummaryClass);c instanceof HTMLElement&&a.push(c.innerText.trim());var u=t?this.i18n.t("hideSectionAriaLabel"):this.i18n.t("showSectionAriaLabel");a.push(u),o.setAttribute("aria-label",a.join(" , ")),t?(s.removeAttribute("hidden"),e.classList.add(this.sectionExpandedClass),n.classList.remove(this.downChevronIconClass)):(s.setAttribute("hidden","until-found"),e.classList.remove(this.sectionExpandedClass),n.classList.add(this.downChevronIconClass));var d=this.checkIfAllSectionsOpen();this.updateShowAllButton(d)}},l.prototype.isExpanded=function(t){return t.classList.contains(this.sectionExpandedClass)},l.prototype.checkIfAllSectionsOpen=function(){return this.$sections.length===this.$module.querySelectorAll("."+this.sectionExpandedClass).length},l.prototype.updateShowAllButton=function(t){var e=t?this.i18n.t("hideAllSections"):this.i18n.t("showAllSections");this.$showAllButton.setAttribute("aria-expanded",t.toString()),this.$showAllText.innerText=e,t?this.$showAllIcon.classList.remove(this.downChevronIconClass):this.$showAllIcon.classList.add(this.downChevronIconClass)};var c={checkForSessionStorage:function(){var t,e="this is the test string";try{return window.sessionStorage.setItem(e,e),t=window.sessionStorage.getItem(e)===e.toString(),window.sessionStorage.removeItem(e),t}catch(n){return!1}}};l.prototype.storeState=function(t){if(this.browserSupportsSessionStorage&&this.config.rememberExpanded){var e=t.querySelector("."+this.sectionButtonClass);if(e){var n=e.getAttribute("aria-controls"),i=e.getAttribute("aria-expanded");n&&i&&window.sessionStorage.setItem(n,i)}}},l.prototype.setInitialState=function(t){if(this.browserSupportsSessionStorage&&this.config.rememberExpanded){var e=t.querySelector("."+this.sectionButtonClass);if(e){var n=e.getAttribute("aria-controls"),i=n?window.sessionStorage.getItem(n):null;null!==i&&this.setExpanded("true"===i,t)}}},l.prototype.getButtonPunctuationEl=function(){var t=document.createElement("span");return t.classList.add("govuk-visually-hidden",this.sectionHeadingDividerClass),t.innerHTML=", ",t};function u(t,e){if(!(t instanceof HTMLElement))return this;this.$module=t,this.debounceFormSubmitTimer=null;this.config=n({preventDoubleClick:!1},e||{},s(t.dataset))}u.prototype.init=function(){this.$module&&(this.$module.addEventListener("keydown",this.handleKeyDown),this.$module.addEventListener("click",this.debounce.bind(this)))},u.prototype.handleKeyDown=function(t){var e=t.target;32===t.keyCode&&e instanceof HTMLElement&&"button"===e.getAttribute("role")&&(t.preventDefault(),e.click())},u.prototype.debounce=function(t){if(this.config.preventDoubleClick)return this.debounceFormSubmitTimer?(t.preventDefault(),!1):void(this.debounceFormSubmitTimer=setTimeout(function(){this.debounceFormSubmitTimer=null}.bind(this),1e3))},function(t){"Date"in self&&"now"in self.Date&&"getTime"in self.Date.prototype||(Date.now=function(){return(new Date).getTime()})}.call("object"==typeof window&&window||"object"==typeof self&&self||"object"==typeof global&&global||{});var d={charactersUnderLimit:{one:"You have %{count} character remaining",other:"You have %{count} characters remaining"},charactersAtLimit:"You have 0 characters remaining",charactersOverLimit:{one:"You have %{count} character too many",other:"You have %{count} characters too many"},wordsUnderLimit:{one:"You have %{count} word remaining",other:"You have %{count} words remaining"},wordsAtLimit:"You have 0 words remaining",wordsOverLimit:{one:"You have %{count} word too many",other:"You have %{count} words too many"},textareaDescription:{other:""}};function h(t,e){if(!(t instanceof HTMLElement))return this;var o=t.querySelector(".govuk-js-character-count");if(!(o instanceof HTMLTextAreaElement||o instanceof HTMLInputElement))return this;var a,l,c,u={threshold:0,i18n:d},h=s(t.dataset),p={};if(("maxwords"in h||"maxlength"in h)&&(p={maxlength:!1,maxwords:!1}),this.config=n(u,e||{},p,h),this.i18n=new r(i(this.config,"i18n"),{locale:(a=t,l="lang",c=a.closest("["+l+"]"),c?c.getAttribute(l):null)}),this.maxLength=Infinity,"maxwords"in this.config&&this.config.maxwords)this.maxLength=this.config.maxwords;else{if(!("maxlength"in this.config)||!this.config.maxlength)return;this.maxLength=this.config.maxlength}this.$module=t,this.$textarea=o,this.$visibleCountMessage=null,this.$screenReaderCountMessage=null,this.lastInputTimestamp=null,this.lastInputValue="",this.valueChecker=null}function p(t){if(!(t instanceof HTMLElement))return this;var e=t.querySelectorAll('input[type="checkbox"]');if(!e.length)return this;this.$module=t,this.$inputs=e}h.prototype.init=function(){if(this.$module&&this.$textarea){var t=this.$textarea,e=document.getElementById(t.id+"-info");if(e){e.innerText.match(/^\s*$/)&&(e.innerText=this.i18n.t("textareaDescription",{count:this.maxLength})),t.insertAdjacentElement("afterend",e);var n=document.createElement("div");n.className="govuk-character-count__sr-status govuk-visually-hidden",n.setAttribute("aria-live","polite"),this.$screenReaderCountMessage=n,e.insertAdjacentElement("afterend",n);var i=document.createElement("div");i.className=e.className,i.classList.add("govuk-character-count__status"),i.setAttribute("aria-hidden","true"),this.$visibleCountMessage=i,e.insertAdjacentElement("afterend",i),e.classList.add("govuk-visually-hidden"),t.removeAttribute("maxlength"),this.bindChangeEvents(),window.addEventListener("onpageshow"in window?"pageshow":"DOMContentLoaded",this.updateCountMessage.bind(this)),this.updateCountMessage()}}},h.prototype.bindChangeEvents=function(){var t=this.$textarea;t.addEventListener("keyup",this.handleKeyUp.bind(this)),t.addEventListener("focus",this.handleFocus.bind(this)),t.addEventListener("blur",this.handleBlur.bind(this))},h.prototype.handleKeyUp=function(){this.updateVisibleCountMessage(),this.lastInputTimestamp=Date.now()},h.prototype.handleFocus=function(){this.valueChecker=setInterval(function(){(!this.lastInputTimestamp||Date.now()-500>=this.lastInputTimestamp)&&this.updateIfValueChanged()}.bind(this),1e3)},h.prototype.handleBlur=function(){clearInterval(this.valueChecker)},h.prototype.updateIfValueChanged=function(){this.$textarea.value!==this.lastInputValue&&(this.lastInputValue=this.$textarea.value,this.updateCountMessage())},h.prototype.updateCountMessage=function(){this.updateVisibleCountMessage(),this.updateScreenReaderCountMessage()},h.prototype.updateVisibleCountMessage=function(){var t=this.$textarea,e=this.$visibleCountMessage,n=this.maxLength-this.count(t.value);this.isOverThreshold()?e.classList.remove("govuk-character-count__message--disabled"):e.classList.add("govuk-character-count__message--disabled"),n<0?(t.classList.add("govuk-textarea--error"),e.classList.remove("govuk-hint"),e.classList.add("govuk-error-message")):(t.classList.remove("govuk-textarea--error"),e.classList.remove("govuk-error-message"),e.classList.add("govuk-hint")),e.innerText=this.getCountMessage()},h.prototype.updateScreenReaderCountMessage=function(){var t=this.$screenReaderCountMessage;this.isOverThreshold()?t.removeAttribute("aria-hidden"):t.setAttribute("aria-hidden","true"),t.innerText=this.getCountMessage()},h.prototype.count=function(t){return"maxwords"in this.config&&this.config.maxwords?(t.match(/\S+/g)||[]).length:t.length},h.prototype.getCountMessage=function(){var t=this.maxLength-this.count(this.$textarea.value),e="maxwords"in this.config&&this.config.maxwords?"words":"characters";return this.formatCountMessage(t,e)},h.prototype.formatCountMessage=function(t,e){if(0===t)return this.i18n.t(e+"AtLimit");var n=t<0?"OverLimit":"UnderLimit";return this.i18n.t(e+n,{count:Math.abs(t)})},h.prototype.isOverThreshold=function(){if(!this.config.threshold)return!0;var t=this.$textarea,e=this.count(t.value);return this.maxLength*this.config.threshold/100<=e},p.prototype.init=function(){if(this.$module&&this.$inputs){var t=this.$module;e(this.$inputs,(function(t){var e=t.getAttribute("data-aria-controls");e&&document.getElementById(e)&&(t.setAttribute("aria-controls",e),t.removeAttribute("data-aria-controls"))})),window.addEventListener("onpageshow"in window?"pageshow":"DOMContentLoaded",this.syncAllConditionalReveals.bind(this)),this.syncAllConditionalReveals(),t.addEventListener("click",this.handleClick.bind(this))}},p.prototype.syncAllConditionalReveals=function(){e(this.$inputs,this.syncConditionalRevealWithInputState.bind(this))},p.prototype.syncConditionalRevealWithInputState=function(t){var e=t.getAttribute("aria-controls");if(e){var n=document.getElementById(e);if(n&&n.classList.contains("govuk-checkboxes__conditional")){var i=t.checked;t.setAttribute("aria-expanded",i.toString()),n.classList.toggle("govuk-checkboxes__conditional--hidden",!i)}}},p.prototype.unCheckAllInputsExcept=function(t){var n=this;e(document.querySelectorAll('input[type="checkbox"][name="'+t.name+'"]'),(function(e){t.form===e.form&&e!==t&&(e.checked=!1,n.syncConditionalRevealWithInputState(e))}))},p.prototype.unCheckExclusiveInputs=function(t){var n=this;e(document.querySelectorAll('input[data-behaviour="exclusive"][type="checkbox"][name="'+t.name+'"]'),(function(e){t.form===e.form&&(e.checked=!1,n.syncConditionalRevealWithInputState(e))}))},p.prototype.handleClick=function(t){var e=t.target;e instanceof HTMLInputElement&&"checkbox"===e.type&&(e.getAttribute("aria-controls")&&this.syncConditionalRevealWithInputState(e),e.checked&&("exclusive"===e.getAttribute("data-behaviour")?this.unCheckAllInputsExcept(e):this.unCheckExclusiveInputs(e)))};function f(t){if(!(t instanceof HTMLElement))return this;this.$module=t,this.$summary=null,this.$content=null}function m(t,e){if(!(t instanceof HTMLElement))return this;this.$module=t;this.config=n({disableAutoFocus:!1},e||{},s(t.dataset))}f.prototype.init=function(){this.$module&&("HTMLDetailsElement"in window&&this.$module instanceof HTMLDetailsElement||this.polyfillDetails())},f.prototype.polyfillDetails=function(){var t,e=this.$module,n=this.$summary=e.getElementsByTagName("summary").item(0),i=this.$content=e.getElementsByTagName("div").item(0);n&&i&&(i.id||(i.id="details-content-"+(t=(new Date).getTime(),"undefined"!=typeof window.performance&&"function"==typeof window.performance.now&&(t+=window.performance.now()),"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var n=(t+16*Math.random())%16|0;return t=Math.floor(t/16),("x"===e?n:3&n|8).toString(16)})))),e.setAttribute("role","group"),n.setAttribute("role","button"),n.setAttribute("aria-controls",i.id),n.tabIndex=0,this.$module.hasAttribute("open")?n.setAttribute("aria-expanded","true"):(n.setAttribute("aria-expanded","false"),i.style.display="none"),this.polyfillHandleInputs(this.polyfillSetAttributes.bind(this)))},f.prototype.polyfillSetAttributes=function(){return this.$module.hasAttribute("open")?(this.$module.removeAttribute("open"),this.$summary.setAttribute("aria-expanded","false"),this.$content.style.display="none"):(this.$module.setAttribute("open","open"),this.$summary.setAttribute("aria-expanded","true"),this.$content.style.display=""),!0},f.prototype.polyfillHandleInputs=function(t){this.$summary.addEventListener("keypress",(function(e){var n=e.target;13!==e.keyCode&&32!==e.keyCode||n instanceof HTMLElement&&"summary"===n.nodeName.toLowerCase()&&(e.preventDefault(),n.click?n.click():t(e))})),this.$summary.addEventListener("keyup",(function(t){var e=t.target;32===t.keyCode&&e instanceof HTMLElement&&"summary"===e.nodeName.toLowerCase()&&t.preventDefault()})),this.$summary.addEventListener("click",t)},m.prototype.init=function(){if(this.$module){var t=this.$module;this.setFocus(),t.addEventListener("click",this.handleClick.bind(this))}},m.prototype.setFocus=function(){var t=this.$module;this.config.disableAutoFocus||(t.setAttribute("tabindex","-1"),t.addEventListener("blur",(function(){t.removeAttribute("tabindex")})),t.focus())},m.prototype.handleClick=function(t){var e=t.target;this.focusTarget(e)&&t.preventDefault()},m.prototype.focusTarget=function(t){if(!(t instanceof HTMLAnchorElement))return!1;var e=this.getFragmentFromUrl(t.href);if(!e)return!1;var n=document.getElementById(e);if(!n)return!1;var i=this.getAssociatedLegendOrLabel(n);return!!i&&(i.scrollIntoView(),n.focus({preventScroll:!0}),!0)},m.prototype.getFragmentFromUrl=function(t){return-1===t.indexOf("#")?undefined:t.split("#").pop()},m.prototype.getAssociatedLegendOrLabel=function(t){var e=t.closest("fieldset");if(e){var n=e.getElementsByTagName("legend");if(n.length){var i=n[0];if(t instanceof HTMLInputElement&&("checkbox"===t.type||"radio"===t.type))return i;var o=i.getBoundingClientRect().top,s=t.getBoundingClientRect();if(s.height&&window.innerHeight)if(s.top+s.height-o<window.innerHeight/2)return i}}return document.querySelector("label[for='"+t.getAttribute("id")+"']")||t.closest("label")};var v={activated:"Loading.",timedOut:"Exit this page expired.",pressTwoMoreTimes:"Shift, press 2 more times to exit.",pressOneMoreTime:"Shift, press 1 more time to exit."};function b(t,e){var o={i18n:v};if(!(t instanceof HTMLElement))return this;var a=t.querySelector(".govuk-exit-this-page__button");if(!(a instanceof HTMLElement))return this;this.config=n(o,e||{},s(t.dataset)),this.i18n=new r(i(this.config,"i18n")),this.$module=t,this.$button=a,this.$skiplinkButton=document.querySelector(".govuk-js-exit-this-page-skiplink"),this.$updateSpan=null,this.$indicatorContainer=null,this.$overlay=null,this.keypressCounter=0,this.lastKeyWasModified=!1,this.timeoutTime=5e3,this.keypressTimeoutId=null,this.timeoutMessageId=null}function g(t){if(!(t instanceof HTMLElement))return this;this.$module=t,this.$menuButton=t.querySelector(".govuk-js-header-toggle"),this.$menu=this.$menuButton&&t.querySelector("#"+this.$menuButton.getAttribute("aria-controls")),this.menuIsOpen=!1,this.mql=null}function y(t,e){if(!(t instanceof HTMLElement))return this;this.$module=t;this.config=n({disableAutoFocus:!1},e||{},s(t.dataset))}function w(t){if(!(t instanceof HTMLElement))return this;var e=t.querySelectorAll('input[type="radio"]');if(!e.length)return this;this.$module=t,this.$inputs=e}function E(t){if(!(t instanceof HTMLAnchorElement))return this;this.$module=t,this.$linkedElement=null,this.linkedElementListener=!1}function k(t){if(!(t instanceof HTMLElement))return this;var e=t.querySelectorAll("a.govuk-tabs__tab");if(!e.length)return this;this.$module=t,this.$tabs=e,this.keys={left:37,right:39,up:38,down:40},this.jsHiddenClass="govuk-tabs__panel--hidden",this.boundTabClick=this.onTabClick.bind(this),this.boundTabKeydown=this.onTabKeydown.bind(this),this.boundOnHashChange=this.onHashChange.bind(this),this.changingHash=!1}b.prototype.initUpdateSpan=function(){this.$updateSpan=document.createElement("span"),this.$updateSpan.setAttribute("role","status"),this.$updateSpan.className="govuk-visually-hidden",this.$module.appendChild(this.$updateSpan)},b.prototype.initButtonClickHandler=function(){this.$button.addEventListener("click",this.handleClick.bind(this)),this.$skiplinkButton&&this.$skiplinkButton.addEventListener("click",this.handleClick.bind(this))},b.prototype.buildIndicator=function(){this.$indicatorContainer=document.createElement("div"),this.$indicatorContainer.className="govuk-exit-this-page__indicator",this.$indicatorContainer.setAttribute("aria-hidden","true");for(var t=0;t<3;t++){var e=document.createElement("div");e.className="govuk-exit-this-page__indicator-light",this.$indicatorContainer.appendChild(e)}this.$button.appendChild(this.$indicatorContainer)},b.prototype.updateIndicator=function(){this.keypressCounter>0?this.$indicatorContainer.classList.add("govuk-exit-this-page__indicator--visible"):this.$indicatorContainer.classList.remove("govuk-exit-this-page__indicator--visible"),e(this.$indicatorContainer.querySelectorAll(".govuk-exit-this-page__indicator-light"),function(t,e){t.classList.toggle("govuk-exit-this-page__indicator-light--on",e<this.keypressCounter)}.bind(this))},b.prototype.exitPage=function(){this.$updateSpan.innerText="",document.body.classList.add("govuk-exit-this-page-hide-content"),this.$overlay=document.createElement("div"),this.$overlay.className="govuk-exit-this-page-overlay",this.$overlay.setAttribute("role","alert"),document.body.appendChild(this.$overlay),this.$overlay.innerText=this.i18n.t("activated"),window.location.href=this.$button.getAttribute("href")},b.prototype.handleClick=function(t){t.preventDefault(),this.exitPage()},b.prototype.handleKeypress=function(t){"Shift"!==t.key&&16!==t.keyCode&&16!==t.which||this.lastKeyWasModified?null!==this.keypressTimeoutId&&this.resetKeypressTimer():(this.keypressCounter+=1,this.updateIndicator(),null!==this.timeoutMessageId&&(clearTimeout(this.timeoutMessageId),this.timeoutMessageId=null),this.keypressCounter>=3?(this.keypressCounter=0,null!==this.keypressTimeoutId&&(clearTimeout(this.keypressTimeoutId),this.keypressTimeoutId=null),this.exitPage()):1===this.keypressCounter?this.$updateSpan.innerText=this.i18n.t("pressTwoMoreTimes"):this.$updateSpan.innerText=this.i18n.t("pressOneMoreTime"),this.setKeypressTimer()),this.lastKeyWasModified=t.shiftKey},b.prototype.setKeypressTimer=function(){clearTimeout(this.keypressTimeoutId),this.keypressTimeoutId=setTimeout(this.resetKeypressTimer.bind(this),this.timeoutTime)},b.prototype.resetKeypressTimer=function(){clearTimeout(this.keypressTimeoutId),this.keypressTimeoutId=null,this.keypressCounter=0,this.$updateSpan.innerText=this.i18n.t("timedOut"),this.timeoutMessageId=setTimeout(function(){this.$updateSpan.innerText=""}.bind(this),this.timeoutTime),this.updateIndicator()},b.prototype.resetPage=function(){document.body.classList.remove("govuk-exit-this-page-hide-content"),this.$overlay&&(this.$overlay.remove(),this.$overlay=null),this.$updateSpan.setAttribute("role","status"),this.$updateSpan.innerText="",this.updateIndicator(),this.keypressTimeoutId&&clearTimeout(this.keypressTimeoutId),this.timeoutMessageId&&clearTimeout(this.timeoutMessageId)},b.prototype.init=function(){this.buildIndicator(),this.initUpdateSpan(),this.initButtonClickHandler(),"govukFrontendExitThisPageKeypress"in document.body.dataset||(document.addEventListener("keyup",this.handleKeypress.bind(this),!0),document.body.dataset.govukFrontendExitThisPageKeypress="true"),window.addEventListener("onpageshow"in window?"pageshow":"DOMContentLoaded",this.resetPage.bind(this))},g.prototype.init=function(){this.$module&&this.$menuButton&&this.$menu&&("matchMedia"in window?(this.mql=window.matchMedia("(min-width: 48.0625em)"),"addEventListener"in this.mql?this.mql.addEventListener("change",this.syncState.bind(this)):this.mql.addListener(this.syncState.bind(this)),this.syncState(),this.$menuButton.addEventListener("click",this.handleMenuButtonClick.bind(this))):this.$menuButton.setAttribute("hidden",""))},g.prototype.syncState=function(){this.mql.matches?(this.$menu.removeAttribute("hidden"),this.$menuButton.setAttribute("hidden","")):(this.$menuButton.removeAttribute("hidden"),this.$menuButton.setAttribute("aria-expanded",this.menuIsOpen.toString()),this.menuIsOpen?this.$menu.removeAttribute("hidden"):this.$menu.setAttribute("hidden",""))},g.prototype.handleMenuButtonClick=function(){this.menuIsOpen=!this.menuIsOpen,this.syncState()},y.prototype.init=function(){this.$module&&this.setFocus()},y.prototype.setFocus=function(){var t=this.$module;this.config.disableAutoFocus||"alert"===t.getAttribute("role")&&(t.getAttribute("tabindex")||(t.setAttribute("tabindex","-1"),t.addEventListener("blur",(function(){t.removeAttribute("tabindex")}))),t.focus())},w.prototype.init=function(){if(this.$module&&this.$inputs){var t=this.$module;e(this.$inputs,(function(t){var e=t.getAttribute("data-aria-controls");e&&document.getElementById(e)&&(t.setAttribute("aria-controls",e),t.removeAttribute("data-aria-controls"))})),window.addEventListener("onpageshow"in window?"pageshow":"DOMContentLoaded",this.syncAllConditionalReveals.bind(this)),this.syncAllConditionalReveals(),t.addEventListener("click",this.handleClick.bind(this))}},w.prototype.syncAllConditionalReveals=function(){e(this.$inputs,this.syncConditionalRevealWithInputState.bind(this))},w.prototype.syncConditionalRevealWithInputState=function(t){var e=t.getAttribute("aria-controls");if(e){var n=document.getElementById(e);if(n&&n.classList.contains("govuk-radios__conditional")){var i=t.checked;t.setAttribute("aria-expanded",i.toString()),n.classList.toggle("govuk-radios__conditional--hidden",!i)}}},w.prototype.handleClick=function(t){var n=this,i=t.target;if(i instanceof HTMLInputElement&&"radio"===i.type){var o=document.querySelectorAll('input[type="radio"][aria-controls]'),s=i.form,r=i.name;e(o,(function(t){var e=t.form===s;t.name===r&&e&&n.syncConditionalRevealWithInputState(t)}))}},E.prototype.init=function(){if(this.$module){var t=this.getLinkedElement();t&&(this.$linkedElement=t,this.$module.addEventListener("click",this.focusLinkedElement.bind(this)))}},E.prototype.getLinkedElement=function(){var t=this.getFragmentFromUrl();return t?document.getElementById(t):null},E.prototype.focusLinkedElement=function(){var t=this.$linkedElement;t.getAttribute("tabindex")||(t.setAttribute("tabindex","-1"),t.classList.add("govuk-skip-link-focused-element"),this.linkedElementListener||(this.$linkedElement.addEventListener("blur",this.removeFocusProperties.bind(this)),this.linkedElementListener=!0)),t.focus()},E.prototype.removeFocusProperties=function(){this.$linkedElement.removeAttribute("tabindex"),this.$linkedElement.classList.remove("govuk-skip-link-focused-element")},E.prototype.getFragmentFromUrl=function(){if(this.$module.hash)return this.$module.hash.split("#").pop()},function(t){"document"in this&&"nextElementSibling"in document.documentElement||Object.defineProperty(Element.prototype,"nextElementSibling",{get:function(){for(var t=this.nextSibling;t&&1!==t.nodeType;)t=t.nextSibling;return t}})}.call("object"==typeof window&&window||"object"==typeof self&&self||"object"==typeof global&&global||{}),function(t){"document"in this&&"previousElementSibling"in document.documentElement||Object.defineProperty(Element.prototype,"previousElementSibling",{get:function(){for(var t=this.previousSibling;t&&1!==t.nodeType;)t=t.previousSibling;return t}})}.call("object"==typeof window&&window||"object"==typeof self&&self||"object"==typeof global&&global||{}),k.prototype.init=function(){this.$module&&this.$tabs&&("function"==typeof window.matchMedia?this.setupResponsiveChecks():this.setup())},k.prototype.setupResponsiveChecks=function(){this.mql=window.matchMedia("(min-width: 40.0625em)"),this.mql.addListener(this.checkMode.bind(this)),this.checkMode()},k.prototype.checkMode=function(){this.mql.matches?this.setup():this.teardown()},k.prototype.setup=function(){var t=this,n=this.$module,i=this.$tabs,o=n.querySelector(".govuk-tabs__list"),s=n.querySelectorAll(".govuk-tabs__list-item");if(i&&o&&s){o.setAttribute("role","tablist"),e(s,(function(t){t.setAttribute("role","presentation")})),e(i,(function(e){t.setAttributes(e),e.addEventListener("click",t.boundTabClick,!0),e.addEventListener("keydown",t.boundTabKeydown,!0),t.hideTab(e)}));var r=this.getTab(window.location.hash)||this.$tabs[0];r&&(this.showTab(r),window.addEventListener("hashchange",this.boundOnHashChange,!0))}},k.prototype.teardown=function(){var t=this,n=this.$module,i=this.$tabs,o=n.querySelector(".govuk-tabs__list"),s=n.querySelectorAll("a.govuk-tabs__list-item");i&&o&&s&&(o.removeAttribute("role"),e(s,(function(t){t.removeAttribute("role")})),e(i,(function(e){e.removeEventListener("click",t.boundTabClick,!0),e.removeEventListener("keydown",t.boundTabKeydown,!0),t.unsetAttributes(e)})),window.removeEventListener("hashchange",this.boundOnHashChange,!0))},k.prototype.onHashChange=function(){var t=window.location.hash,e=this.getTab(t);if(e)if(this.changingHash)this.changingHash=!1;else{var n=this.getCurrentTab();n&&(this.hideTab(n),this.showTab(e),e.focus())}},k.prototype.hideTab=function(t){this.unhighlightTab(t),this.hidePanel(t)},k.prototype.showTab=function(t){this.highlightTab(t),this.showPanel(t)},k.prototype.getTab=function(t){return this.$module.querySelector('a.govuk-tabs__tab[href="'+t+'"]')},k.prototype.setAttributes=function(t){var e=this.getHref(t).slice(1);t.setAttribute("id","tab_"+e),t.setAttribute("role","tab"),t.setAttribute("aria-controls",e),t.setAttribute("aria-selected","false"),t.setAttribute("tabindex","-1");var n=this.getPanel(t);n&&(n.setAttribute("role","tabpanel"),n.setAttribute("aria-labelledby",t.id),n.classList.add(this.jsHiddenClass))},k.prototype.unsetAttributes=function(t){t.removeAttribute("id"),t.removeAttribute("role"),t.removeAttribute("aria-controls"),t.removeAttribute("aria-selected"),t.removeAttribute("tabindex");var e=this.getPanel(t);e&&(e.removeAttribute("role"),e.removeAttribute("aria-labelledby"),e.classList.remove(this.jsHiddenClass))},k.prototype.onTabClick=function(t){var e=this.getCurrentTab(),n=t.currentTarget;e&&n instanceof HTMLAnchorElement&&(t.preventDefault(),this.hideTab(e),this.showTab(n),this.createHistoryEntry(n))},k.prototype.createHistoryEntry=function(t){var e=this.getPanel(t);if(e){var n=e.id;e.id="",this.changingHash=!0,window.location.hash=this.getHref(t).slice(1),e.id=n}},k.prototype.onTabKeydown=function(t){switch(t.keyCode){case this.keys.left:case this.keys.up:this.activatePreviousTab(),t.preventDefault();break;case this.keys.right:case this.keys.down:this.activateNextTab(),t.preventDefault()}},k.prototype.activateNextTab=function(){var t=this.getCurrentTab();if(t&&t.parentElement){var e=t.parentElement.nextElementSibling;if(e){var n=e.querySelector("a.govuk-tabs__tab");n&&(this.hideTab(t),this.showTab(n),n.focus(),this.createHistoryEntry(n))}}},k.prototype.activatePreviousTab=function(){var t=this.getCurrentTab();if(t&&t.parentElement){var e=t.parentElement.previousElementSibling;if(e){var n=e.querySelector("a.govuk-tabs__tab");n&&(this.hideTab(t),this.showTab(n),n.focus(),this.createHistoryEntry(n))}}},k.prototype.getPanel=function(t){return this.$module.querySelector(this.getHref(t))},k.prototype.showPanel=function(t){var e=this.getPanel(t);e&&e.classList.remove(this.jsHiddenClass)},k.prototype.hidePanel=function(t){var e=this.getPanel(t);e&&e.classList.add(this.jsHiddenClass)},k.prototype.unhighlightTab=function(t){t.parentElement&&(t.setAttribute("aria-selected","false"),t.parentElement.classList.remove("govuk-tabs__list-item--selected"),t.setAttribute("tabindex","-1"))},k.prototype.highlightTab=function(t){t.parentElement&&(t.setAttribute("aria-selected","true"),t.parentElement.classList.add("govuk-tabs__list-item--selected"),t.setAttribute("tabindex","0"))},k.prototype.getCurrentTab=function(){return this.$module.querySelector(".govuk-tabs__list-item--selected a.govuk-tabs__tab")},k.prototype.getHref=function(t){var e=t.getAttribute("href");return e.slice(e.indexOf("#"),e.length)},t.initAll=function(t){var n=(t=void 0!==t?t:{}).scope instanceof HTMLElement?t.scope:document;e(n.querySelectorAll('[data-module="govuk-accordion"]'),(function(e){new l(e,t.accordion).init()})),e(n.querySelectorAll('[data-module="govuk-button"]'),(function(e){new u(e,t.button).init()})),e(n.querySelectorAll('[data-module="govuk-character-count"]'),(function(e){new h(e,t.characterCount).init()})),e(n.querySelectorAll('[data-module="govuk-checkboxes"]'),(function(t){new p(t).init()})),e(n.querySelectorAll('[data-module="govuk-details"]'),(function(t){new f(t).init()}));var i=n.querySelector('[data-module="govuk-error-summary"]');i&&new m(i,t.errorSummary).init(),e(n.querySelectorAll('[data-module="govuk-exit-this-page"]'),(function(e){new b(e,t.exitThisPage).init()}));var o=n.querySelector('[data-module="govuk-header"]');o&&new g(o).init(),e(n.querySelectorAll('[data-module="govuk-notification-banner"]'),(function(e){new y(e,t.notificationBanner).init()})),e(n.querySelectorAll('[data-module="govuk-radios"]'),(function(t){new w(t).init()}));var s=n.querySelector('[data-module="govuk-skip-link"]');s&&new E(s).init(),e(n.querySelectorAll('[data-module="govuk-tabs"]'),(function(t){new k(t).init()}))},t.version="4.7.0",t.Accordion=l,t.Button=u,t.Details=f,t.CharacterCount=h,t.Checkboxes=p,t.ErrorSummary=m,t.ExitThisPage=b,t.Header=g,t.NotificationBanner=y,t.Radios=w,t.SkipLink=E,t.Tabs=k}));
//# sourceMappingURL=govuk-frontend-4.7.0.min.js.map
AUI().ready(

	function () {

		setTimeout(function () {
			$('form label, .portlet-forms .ddm-label').addClass('optional');
			$('form legend, .portlet-forms .lfr-ddm-legend').addClass('optional');
			$('form label .reference-mark, .portlet-forms .ddm-label .reference-mark').parent().removeClass('optional').addClass('required');
			$('form legend .reference-mark, .portlet-forms .lfr-ddm-legend .reference-mark').parent().removeClass('optional').addClass('required');
			$('.portlet-forms .liferay-ddm-form-field-paragraph').parent().find('.ddm-label, .lfr-ddm-legend').removeClass('optional');
			$('.portlet-forms .ddm-form-field-summarypage').parent().find('.ddm-label, .lfr-ddm-legend').removeClass('optional');
		}, 500);
	}
);

const contentElements = '.ddm-field p, .ddm-field li, .ddm-field h2, .ddm-field h3, .ddm-field h4, .ddm-field legend, .ddm-field span.form-text, .ddm-field dd, .ddm-field dt, .ddm-field th, .ddm-field td';
var fieldReferenceMap;

const isElementNotPresent = async selector => {
	while ( document.querySelector(selector) ) {
	  await new Promise( resolve =>  requestAnimationFrame(resolve) )
	}
	return true;
};

Liferay.on('ddmFormPageShow', function (event) {

	isElementNotPresent('.ddm-field-container .loading-animation').then((selector) => {

		const observer = new MutationObserver((mutations, observer) => {
			let triggerUpdate = mutations.filter(mutationRecord => mutationRecord.target.className === 'ddm-field' || mutationRecord.target.getAttribute('data-variable-field') === 'true');
	
			if (triggerUpdate.length > 0) {
				updateVariables();
				overrideInputSetter();
			}
		});
	
		$('.portlet-forms-display, .form-renderer').each(function () {
			observer.observe(this, {
				childList: true,
				subtree: true
			});
		});
	
		updateVariables();
		overrideInputSetter();
		addNameAttributeToRadioButtons();
	
		if (event.page > 0) {
			let target = $('form[data-ddmforminstanceid="' + event.formId + '"]');
			scrollToFormTop(target);
		}
    });

});

Liferay.on('allPortletsReady', function () {

	loadFieldReferenceMap();

	Liferay.on('fileFieldEdited', function (event) {
		updateVariables();
	});
	document.body.addEventListener('change', function (event) {
		if (event.target.getAttribute('data-variable-field') === 'true' || event.target.id.endsWith('_uprn') || event.target.id.endsWith('_postcode')) {
			updateVariables();
		}
	});

});

function addNameAttributeToRadioButtons() {

	$('.ddm-field-container').each(function(index, formFieldContainer) {

		const inputElements = $(formFieldContainer).find('input[type="radio"]');

		if (inputElements.length) {

			const dataFieldName = formFieldContainer.getAttribute('data-field-name');

			inputElements.each(function(index, inputElement){
			  inputElement.setAttribute("name", dataFieldName);
			});

		}

	});

}

function updateVariables() {
	tagVariablesInHTML();
	tagVariablesInTextfields()
	replaceURLVariablesInHTML();
	replaceURLVariablesInTextfields();
	replaceFieldVariablesInHTML();
	replaceFieldVariablesInTextfields();
}

function tagVariablesInHTML() {
	$(contentElements).each(function () {
		var text = $(this).html();
		$(this).html(text.replace(/{{(.*?)}}/g, '<span data-replace-name="$1"></span>'));
	});
}

function tagVariablesInTextfields() {
	$(".ddm-field input[type='text']").each(function () {
		let inputValue = $(this).val();
		if (inputValue.startsWith('[[') || inputValue.startsWith('{{')) {
			$(this).attr('data-variable', inputValue);
			setTextfieldValue($(this).attr('name'), ' ');
		}
	});
}

function replaceURLVariablesInHTML() {
	$(contentElements).each(function () {
		var text = $(this).html();
		$(this).html(text.replace(/\[\[(.*?)]]/, replacer));
	});
}

function replaceFieldVariablesInHTML() {
	$('.ddm-field span[data-replace-name]').each(function () {

		var fieldReference = $(this).attr('data-replace-name');
		let fieldName = getFieldName(fieldReference);
		let textValue = getFieldValue(fieldName);

		if ($(this).text() !== textValue) {
			$(this).text(textValue);
		}
	});
}

function replaceURLVariablesInTextfields() {
	$("input[data-variable][data-variable*='[[']").each(function () {
		var text = $(this).attr('data-variable');
		var value = text.replace(/\[\[(.*?)]]/, replacer);
		var name = $(this).attr('name');

		if (value && value != null && value != 'null') {
			$(this).attr('data-variable', value);
			setTextfieldValue(name, value);
		}
	});
}

function replaceFieldVariablesInTextfields() {
	$("input[data-variable][data-variable*='{{']").each(function () {
		var text = $(this).attr('data-variable');
		var fieldName = text.replace(/{{(.*?)}}/, replacerFieldValue);
		let value = getFieldValue(fieldName);
		var name = $(this).attr('name');

		if (value === '') {
			value = ' ';
		}

		if ($(this).val() !== value) {
			setTextfieldValue(name, value);
		}
	});
}

function getFieldValue(fieldName) {
	if (fieldName.startsWith('File')) {
		let field = $('input[type="hidden"][name*="' + fieldName.split('.')[0] + '"]');
		field.attr("data-variable-field", "true");
		if (field.length === 0 || field.val() === '') return '';
		return fieldName.includes('.') ? JSON.parse(field.val())[fieldName.split('.')[1]] : field.val();
	} else if (fieldName == 'fullAddress') {
		let field = $('input[type="hidden"][name*="' + fieldName + '"]');
		field.attr("data-variable-field", "true");
		return field.val();
	} else if (fieldName == 'uprn') {
		let field = $('select[name*="' + fieldName + '"]');
		field.attr("data-variable-field", "true");
		return field.val();
	} else if ($('input[type="text"][name*="' + fieldName + '"]').length) {
		let field = $('input[type="text"][name*="' + fieldName + '"]');
		field.attr("data-variable-field", "true");
		return field.val();
	} else if ($('textarea[type="text"][name*="' + fieldName + '"]').length) {
		let field = $('textarea[type="text"][name*="' + fieldName + '"]');
		field.attr("data-variable-field", "true");
		return field.val();
	} else if ($('select[name*="' + fieldName + '"]').length) {
		let field = $('select[name*="' + fieldName + '"]');
		field.attr("data-variable-field", "true");
		return $('select[name*="' + fieldName + '"] option:selected').text();
	} else if ($('input[type="radio"][name*="' + fieldName + '"]').length) {
		$('input[type="radio"][name*="' + fieldName + '"]').attr("data-variable-field", "true");
		if ($('input[type="radio"][name*="' + fieldName + '"]:checked').length) {
			return $('input[type="radio"][name*="' + fieldName + '"]:checked').siblings('.custom-control-label').find('.custom-control-label-text').text();
		}
	} else if ($('div[data-field-name="' + fieldName + '"] .date-picker input[name="datePicker"]').length) {
		let field = $('div[data-field-name="' + fieldName + '"] .date-picker input[name="datePicker"]');
		field.attr("data-variable-field", "true");
		return field.val();
	}
}

function setTextfieldValue(fieldName, value) {
	var input = document.querySelector('[name="' + fieldName + '"]');

	const valueSetter = Object.getOwnPropertyDescriptor(input, 'value').set;
	const prototype = Object.getPrototypeOf(input);
	const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;
	if (valueSetter && valueSetter !== prototypeValueSetter) {
		prototypeValueSetter.call(input, value);
	} else {
		valueSetter.call(input, value);
	}
	input.dispatchEvent(new Event('change', { bubbles: true, 'cancelable': true }));
	input.dispatchEvent(new Event('input', { bubbles: true, 'cancelable': true }));

	input.value = value;
}

function replacer(match, p1) {
	const urlParams = new URLSearchParams(window.location.search);
	return urlParams.get(p1) != null ? urlParams.get(p1) : '';
}

function replacerFieldValue(match, p1) {
	return getFieldName(p1);
}

function overrideInputSetter() {
	$('.portlet-forms input[type="text"]').each(function (index) {

		if (this.getAttribute('data-variable-field') === 'true') {

			const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(this), 'value');

			Object.defineProperty(this, 'value', {
				set: function (t) {
					let setVar = descriptor.set.apply(this, arguments);
					updateVariables();
					return setVar;
				},
				get: function () {
					return descriptor.get.apply(this);
				},
				configurable: true
			});
		}
	});
}

function loadFieldReferenceMap() {
	fieldReferenceMap = new Map();

	$('.portlet-forms input[type="hidden"][name*="formInstanceId"]').each(function () {
		Liferay.Util.fetch(
			Liferay.ThemeDisplay.getPortalURL() + '/o/dp-headless-form/1.0.0/forms/' + this.value + '/form-structure',
			{
				method: 'GET',
				headers: {
				'Content-Type':
				'application/json'
				}
			}
        ).then(function(response) {
			if(response.ok){
				return data = response.json();
			}else{
				console.debug(response);
			}
        }).then(function(data) {
       		 if(data){
				let fields = JSON.parse(data.definition).fields;
				fields.forEach(function (field) {
					fieldReferenceMap.set(field.fieldReference, field.name);
				});
			}
        });
	});
}

function getFieldName(fieldReference) {
	let fieldName = fieldReferenceMap && fieldReferenceMap.get(fieldReference);
	if (fieldName === undefined) {
		fieldName = fieldReference;
	}
	return fieldName;
}

function scrollToFormTop(target) {
	$('html, body').animate({
		scrollTop: $(target).offset().top - 50
	}, 'slow');
}

$(document).ready(function() {

	if ("searchModal_iframe_" == parent.name && window.self.frameElement.id == '_com_liferay_asset_categories_selector_web_portlet_AssetCategoriesSelectorPortlet_selectCategory_iframe_') {
		
	 let selectCategoryIntervalId =	setInterval(() => {
			
			let selectCategoryDiv = $(window.self.frameElement).contents().find('html').find('body').find('.select-category');
			if (selectCategoryDiv.length > 0) {
				selectCategoryDiv.find('.select-category-filter').find('button').remove();
				clearInterval(selectCategoryIntervalId);
			}

		}, 0);
	}
});

AUI.add(
		'com-placecube-digitalplace-customercontactmanagement-util',

		function(A) {

			A.CustomerContactManagement = A.Component.create({

				NAME : 'com-placecube-digitalplace-customercontactmanagement-util',

				EXTENDS : A.Component,

				ATTRS : {
				},

				prototype : {
					
					openCustomerProfileView: function(data, renderURL) {
						var userId = data.user_id;
						renderURL = renderURL.replace('userId=0', 'userId=' + userId);
						
						window.location = renderURL.toString();
					},
					
					openCustomerProfileWithEmailDetailView: function(data, renderURL) {
						var userId = data.user_id;
						var emailId = data.entry_class_pk;
						renderURL = renderURL.replace('userId=0', 'userId=' + userId).replace('emailId=0', 'emailId=' + emailId);
						
						window.location = renderURL.toString();
					},
					
					openEnquiryDetailView: function(portletId, mvcRenderCommandName, parameters){
						var titleLanguageKeyParams = [];

						Object.keys(parameters).forEach(function(key) {
							if (key.startsWith('language_key_')){
								titleLanguageKeyParams[parseInt(key.replace('language_key_',''))] = parameters[key];
							}
						});
						if (Object.keys(parameters).includes('background')) {
							titleLanguageKeyParams.push(parameters['background']);
						}

						var renderURL = Liferay.PortletURL.createRenderURL();
						renderURL.setPortletId(portletId);
						renderURL.setParameter('mvcRenderCommandName', mvcRenderCommandName);
						renderURL.setWindowState('pop_up');
						renderURL.setParameters(parameters);

						var headerContent = "<div class='modal-title'><span class='font-weight-bold'>Case details :</span><span>{0}</span> <span class='status-label coloured-label' style='background:{2}'>{1}</span></div>";
						headerContent = headerContent.replace('{0}',titleLanguageKeyParams[0]).replace('{1}',titleLanguageKeyParams[1]).replace('{2}',titleLanguageKeyParams[2]);
						
						var dialog = Liferay.Util.Window.getWindow(
								{
									dialog: {
										cssClass: 'enquiry-modal-view',
										destroyOnHide: true,
										resizable: false,
										headerContent: headerContent,
										toolbars: {
											footer: [
												{
													cssClass: "btn btn-primary",
													label: 'Close',
													on: {
														click: function(event) {
															dialog.hide();
															dialog.destroy();
														}
													}
												}
											],
											header: [
												{
													cssClass: 'close',
													discardDefaultButtonCssClasses: true,
													labelHTML: "<i class='dp-icon-close'></i>",
													on: {
														click: function(event) {
															dialog.hide();
															dialog.destroy();
														}
													}
												}
											]
										}
									},
									uri: renderURL.toString()
								}
							);


					},
					
					openEmailDetailView: function(data, parameters){
						var renderURL = Liferay.PortletURL.createRenderURL();
						renderURL.setPortletId(parameters.searchPortletId);
						renderURL.setParameter('mvcRenderCommandName', parameters.emailDetailViewMVCRenderCommand);
						renderURL.setWindowState('pop_up');
						renderURL.setParameters(data);

						var deleteURL = Liferay.PortletURL.createResourceURL();
						deleteURL.setPortletId(parameters.searchPortletId);
						deleteURL.setResourceId(parameters.deleteEmailMVCResourceCommand);
						deleteURL.setParameters(data);
						
						var headerContent = 
							"<div class='modal-title'>" +
								"<span class='font-weight-bold'>{0} :</span><span>{1}</span>" +
								"<span class='font-weight-bold ml-4'>{2} :</span><span>{3}</span>" +
							"</div>";
				
						headerContent = headerContent.replace('{0}', 'From');
						headerContent = headerContent.replace('{1}', data.from);
						headerContent = headerContent.replace('{2}', 'Date');
						headerContent = headerContent.replace('{3}', data.date);
							
						var footer = [];
						
						if (parameters.isCSAUser === 'true') {
							footer.push({
								cssClass: "btn btn-cancel btn-link",
								discardDefaultButtonCssClasses: true,
								label: 'Delete',
								on: {
									click: function(event) {
										if (confirm('remove-email-confirmation')) {
											$.get(deleteURL, function(){
												Liferay.Portlet.refresh('#p_p_id' + parameters.portletNamespace);
												Liferay.Util.openToast({message: 'email-deleted-successfully'});
												dialog.hide();
												dialog.destroy();
											});
										}
									}
								}
							});
							
							if (data.user_id <= 0) {
								var emailSearchURL = parameters.searchCustomerButtonURL;
								searchCustomerURL = emailSearchURL.replace('emailId=0', 'emailId=' + data.entry_class_pk);
								
								footer.push({
									cssClass: "btn btn-secondary btn-search-customer",
									label: parameters.searchCustomerButtonLabel,
									on: {
										click: function(event) {
											event.preventDefault();
											Liferay.Util.getOpener().location.href = searchCustomerURL;
										}
									}
								});
							}
						}
						
						footer.push({
							cssClass: "btn btn-primary btn-close-modal",
							label: 'Close',
							on: {
								click: function(event) {
									dialog.hide();
									dialog.destroy();
								}
							}
						});
						
						var dialog = Liferay.Util.Window.getWindow(
								{
									dialog: {
										cssClass: 'email-modal-view',
										destroyOnHide: true,
										resizable: false,
										headerContent: headerContent,
										toolbars: {
											footer: footer,
											header: [
												{
													cssClass: 'close',
													discardDefaultButtonCssClasses: true,
													labelHTML: "<i class='dp-icon-close'></i>",
													on: {
														click: function(event) {
															dialog.hide();
															dialog.destroy();
														}
													}
												}
											]
										}
									},
									id: 'emailDetailViewModal',
									uri: renderURL.toString()
								}
							);
					},

					openDialog: function(modalTitle, modalBodyContent, primaryButtonLabel, primaryButtonURL, secondaryButtonLabel, secondaryButtonURL){

						var dialog = Liferay.Util.Window.getWindow(
								{
									dialog: {
										bodyContent: modalBodyContent,
										cssClass: 'cust-modal dialog-iframe-modal',
										destroyOnHide: true,
										height: 270,
										resizable: false,
										toolbars: {
											footer: [
												{
													cssClass: "btn btn-primary",
													label: primaryButtonLabel,
													on: {
														click: function(event) {
															event.preventDefault();
															Liferay.Util.getOpener().document.location.href= primaryButtonURL;
														}
													}
												},
												{
													cssClass: "btn btn-primary",
													label: secondaryButtonLabel,
													on: {
														click: function(event) {
															event.preventDefault();
															Liferay.Util.getOpener().document.location.href= secondaryButtonURL;
														}
													}
												}
											],
											header: [
												{
													cssClass: 'close',
													discardDefaultButtonCssClasses: true,
													labelHTML: "<i class='dp-icon-close'></i>",
													on: {
														click: function(event) {
															dialog.hide();
															dialog.destroy();
														}
													}
												}
											]
										},
										width: 520
									},
									title: modalTitle
								}
							);

					}

				}
			});
		},
		'',
		{
			requires: [
				'liferay-portlet-url',
				'liferay-util-window'
            ]
		}
);
AUI.add(

	'com-placecube-digitalplace-casemanagement-frontend-caselisting',

	function(A) {

		var CaseListing = {

			init: function() {

				$(document).on('click', '.case-listing-entry', function(e){
					A.CaseListing.openCaseEntryDetailPopUp(e);
				});

			},

			getRenderUrl: function(ppid, mvcRenderCommandName, windowState, parameters){

				var renderURL = Liferay.PortletURL.createRenderURL();
				renderURL.setPortletId(ppid);
				renderURL.setParameter('mvcRenderCommandName', mvcRenderCommandName);
				renderURL.setWindowState(windowState);
				renderURL.setParameters(parameters);
				
				return renderURL;
			},

			openCaseEntryDetailPopUp: function(e){

				var caseListing = $(e.currentTarget).closest('.case-management .case-listing');
				var ppid = $(caseListing).attr('data-ppid');
				var mvcRenderCommandName = $(caseListing).attr('data-mvc-render-command-name');
				var entryId = $(e.currentTarget).attr('data-entry-id');
				var parameters = {entryId: entryId};

				var renderURL = this.getRenderUrl(ppid, mvcRenderCommandName, 'pop_up', parameters);

				Liferay.Util.openWindow(
					{
						dialog: {
							destroyOnHide: true,
							plugins: [Liferay.WidgetZIndex]
						},
						id: ppid + '_Dialog',
						title: '',
						uri: renderURL.toString()
					}
				);
			}
			
		};

		A.CaseListing = CaseListing;
	},
	'',
	{
		requires: [
			'liferay-portlet-url',
			'liferay-util-window'
		]
	}

);

AUI.add(

	'com-placecube-digitalplace-casemanagement-attachmentmanagement',

	function(A) {

		A.AttachmentManagement = {

			init: function (params) {

				var maxAttachmentsToUpload = params.maxAttachmentsToUpload;
				var portletNamespace = params.portletNamespace;
				var attachmentCount = 1;

				let autoFields = new Liferay.AutoFields(
					{
						contentBox: '#'+portletNamespace+'attachment-container',
						fieldIndexes: portletNamespace+'row-indexes',
						sortable: false,
						minimumRows: 1
					});

				autoFields.on("clone", function (event) {
					++attachmentCount;
					updateClonedRow(event.row);
					checkRowsLimit();
				});

				autoFields.on("delete", function (event) {
					--attachmentCount;
					event.deletedRow.remove();
					checkRowsLimit();
				});

				autoFields.render();

				function updateClonedRow(row) {
					let clonedRowElement = document.getElementById(row.getAttribute('id'));
					let rowInput = clonedRowElement.querySelector('input[type="file"]');
					let rowLabel = clonedRowElement.querySelector('label');
					row.setAttribute("data-row-id", attachmentCount)
					rowInput.value = '';
					rowInput.setAttribute('id', portletNamespace+'file'+attachmentCount)
					rowInput.setAttribute('name', portletNamespace+'file'+attachmentCount)
					rowLabel.setAttribute('for', portletNamespace+'file'+attachmentCount)
					rowLabel.innerText = "File "+attachmentCount;
				}

				function checkRowsLimit() {
					let contentBox = document.getElementById(portletNamespace+"attachment-container");
					if (contentBox) {
						let rowElements = contentBox.querySelectorAll(".row");
						let rowNumber = contentBox.querySelectorAll(".row").length;
						if (rowNumber >= maxAttachmentsToUpload) {
							let addRowButtons = contentBox.querySelectorAll(".add-row");
							for (let i = 0; i < addRowButtons.length; i++) {
								addRowButtons[i].classList.add("disabled");
							}
						} else {
							let addRowButtons = contentBox.querySelectorAll(".add-row");
							for (let i = 0; i < addRowButtons.length; i++) {
								if (addRowButtons[i].classList.contains("disabled")) {
									addRowButtons[i].classList.remove("disabled");
								}
							}
						}

						reindexAttachmentInputs(rowElements);
					}
				}

				function reindexAttachmentInputs(rows) {
					for (let i = 0; i < rows.length; i++) {
						let inputElement = rows[i].querySelector("input");
						let labelElement = rows[i].querySelector("label");
						inputElement.setAttribute('id', portletNamespace+'file'+(i+1))
						inputElement.setAttribute('name', portletNamespace+'file'+(i+1))
						labelElement.setAttribute('for', portletNamespace+'file'+(i+1))
						labelElement.innerText = "File "+(i+1);
					}
				}

				checkRowsLimit();
			},
		};
	},
	'',
	{
		requires: [
			'liferay-auto-fields'
		]
	}

);


AUI.add(

		'com-placecube-digitalplace-casemanagement-datastructureupdate',

		function(A) {
			var ENTRY_OPTION_TEMPLATE = '<option value="{optionValue}" id="{entryId}">{optionValue}</option>';

			var DataStructureUpdate = {

					init: function(params) {
						var instance = this;
						var groupIdParam = params.scopeGroupId;
						
						$('.data-structure-update').on('change', function(e) {
							var selectedDataStructurekey = $(this).attr('data-dataStructureKey');
							var parentDataStructureId =this.options[this.selectedIndex].id;
							
							var children = $('.data-structure-update[data-parentDataStructureKey="' + selectedDataStructurekey + '"]');

							if (children) {
	
								for (var i = 0; i < children.length; i++) {
									var dropdownSelectToUpdate = children[i];
									if (dropdownSelectToUpdate !== undefined) {
										
										if (isNaN(parentDataStructureId)) {
											instance._retrieveValuesForSelectedParentDataStructure(groupIdParam, selectedDataStructurekey, parentDataStructureId, dropdownSelectToUpdate);
										} else {
											instance._retrieveValuesForSelectedParentDataStructureById(groupIdParam, parentDataStructureId, dropdownSelectToUpdate);
										}

									}
								}
	
							}
						});
					}, 
					_retrieveValuesForSelectedParentDataStructureById: function (groupIdParam, parentDataStructureId, dropdownSelectToUpdate) {
						var datastructurekeyParam = $(dropdownSelectToUpdate).attr('data-dataStructureKey');

						Liferay.Service(
								'/casemanagement_datastructure.datastructureentry/get-linked-data-structure-entries',
								{
									groupId: groupIdParam,
									parentDataStructureEntryId: parentDataStructureId,
									dataStructureKey: datastructurekeyParam
								},
								function(data) {
									var dataStructureEntiresFound = data;

									$(dropdownSelectToUpdate).html('<option></option>');

									$.each(dataStructureEntiresFound, function(key, value) {

										var entryValue = A.Lang.sub(
												ENTRY_OPTION_TEMPLATE,
												{
													optionValue: value.name,
													entryId: value.dataStructureEntryId
												}
										);
										
										$(dropdownSelectToUpdate).append(entryValue);
									});
								}
						);
					},
					_retrieveValuesForSelectedParentDataStructure: function (groupIdParam, parentDataStructureKeyParam, optionSelectedParam, dropdownSelectToUpdate) {
						var datastructurekeyParam = $(dropdownSelectToUpdate).attr('data-dataStructureKey');
						
						Liferay.Service(
								'/casemanagement_datastructure.datastructureentry/get-linked-data-structure-entries',
								{
									groupId: groupIdParam,
									parentStructureKey: parentDataStructureKeyParam,
									parentStructureName: optionSelectedParam,
									dataStructureKey: datastructurekeyParam
								},
								function(data) {
									var dataStructureEntiresFound = data;

									$(dropdownSelectToUpdate).html('<option></option>');

									$.each(dataStructureEntiresFound, function(key, value) {

										var entryValue = A.Lang.sub(
												ENTRY_OPTION_TEMPLATE,
												{
													optionValue: value.name,
													entryId: value.dataStructureEntryId
												}
										);
										
										$(dropdownSelectToUpdate).append(entryValue);
									});
								}
						);
					}
			};

			A.DataStructureUpdate = DataStructureUpdate;
		},
		'',
		{
			requires: [
				'liferay-portlet-url'
				]
		}

);



;(function () {

	Liferay.provide(window, 'updateFieldFacetSelection', function (namespace, element, baseRemoveFilterUrl, baseUpdateFilterSelectionUrl, redirectUrl) {
		var A = AUI();
		
		var id = A.one(element).get('id');
		var oldField = A.one("#" + id + "_old");
		
		var optionSelectedValue = A.one(element).val();
		
		var selectedElement = A.one(element).one("option[value=" + optionSelectedValue + "]");
		var value = selectedElement.get('value');
		var label = selectedElement.get('label');

		var updateFilterSelectionUrl = baseUpdateFilterSelectionUrl + "&" + namespace + "filterValue=" + value + "&" + namespace + "filterLabel=" + label;
   		var removeFilterUrl = baseRemoveFilterUrl + "&" + namespace + "filterValue=" + oldField.val();

		$.ajax({
				type: "POST",
				url: removeFilterUrl,
				success : function(data) {					
					$.ajax({
						type: "POST",
						url: updateFilterSelectionUrl,
						success : function(data) {
							oldField.val(optionSelectedValue);
							window.location.href = redirectUrl;
						},
						error: function(jqXHR, textStatus, errorThrown){
					   		console.info("Update filter selection call failed: " + textStatus);
						}
				  	});			
  				},
		  		error: function(jqXHR, textStatus, errorThrown){
					console.info("Clear all filters call failed: " + textStatus);
				}
		  
		});
	});
	
})()
AUI.add(
	'com-placecube-field-filter-builder',
	function (A) {

		var groupTemplate;

		var optionTemplate;

		var hiddenFormField;

		var ns;

		var FieldFilterBuilder = {

			init: function (params) {
				groupTemplate = params.groupTemplate;
				optionTemplate = params.optionTemplate;
				hiddenFormField = params.hiddenFormField;
				ns = params.ns;

				FieldFilterBuilder.buildForm(params.jsonFilterConfig);

				$('#' + ns + 'addFilterGroupBtn').click(function (e) {
					FieldFilterBuilder.createFilterGroup();
				});

				$('#' + ns + 'filterGroups').on("click", "button.add-filter", function (event) {
					FieldFilterBuilder.createFilterFromClick(event.currentTarget);
				});

				$('#' + ns + 'filterGroups').on("click", "button.add-option", function (event) {
					FieldFilterBuilder.createFilterOptionFromClick(event.currentTarget);
				});

				$('#' + ns + 'filterGroups').on("click", "a.remove-group", function (event) {
					FieldFilterBuilder.removeItem(event, event.currentTarget, '.filter-group');
				});

				$('#' + ns + 'filterGroups').on("click", "a.remove-option", function (event) {
					FieldFilterBuilder.removeItem(event, event.currentTarget, '.filter-option');
				});

				$('#' + ns + 'filterGroups').on("click", "a.remove-filter", function (event) {
					FieldFilterBuilder.removeItem(event, event.currentTarget, '.field-filter');
				});
				
				$('#' + ns + 'filterGroups').on("change", ".filter-field-selector", function (event) {
					FieldFilterBuilder.updateAvailableInputs(event.currentTarget);
				});
			},

			createFilterGroup: function () {

				var templateHtml = groupTemplate.html().trim();

				var newFilterGroup = document.createElement('div');
				$(newFilterGroup).addClass('filter-group');
				newFilterGroup.innerHTML = templateHtml;

				var filterGroups = document.getElementById(ns + 'filterGroups');
				filterGroups.appendChild(newFilterGroup);
				return newFilterGroup;
			},

			createFilterOptionFromClick: function (element) {
				var filterValuesDiv = $(element).siblings('.filter-options').first().get(0);
				return FieldFilterBuilder.createFilterOption(filterValuesDiv);
			},

			createFilterOption: function (filterValuesDiv) {

				var templateHtml = optionTemplate.html().trim();

				var newFilterOption = document.createElement('div');
				$(newFilterOption).addClass('filter-option');
				newFilterOption.innerHTML = templateHtml;

				filterValuesDiv.appendChild(newFilterOption);
				return newFilterOption;

			},

			createFilterFromClick: function (element) {

				var filterValuesDiv = $(element).siblings('.filters').first().get(0);

				return FieldFilterBuilder.createFilter(filterValuesDiv);
			},

			createFilter: function (filterValuesDiv) {

				var templateHtml = $('#' + ns + 'field-filter-template').html().trim();

				var newFilterValue = document.createElement('div');
				$(newFilterValue).addClass('field-filter');
				newFilterValue.innerHTML = templateHtml;

				filterValuesDiv.appendChild(newFilterValue);
				return newFilterValue;
			},

			formToJson: function () {

				var groups = [];

				$('.filter-group').each(function () {
					var group = {};
					group.filterGroupName = $(this).find('[name="' + ns + 'filterGroupName"]').val();

					if (!group.filterGroupName) {
						return;
					}

					group.filterPreselectedOptionName = $(this).find('[name="' + ns + 'filterPreselectedOptionName"]').val();

					var options = [];
					group.options = options;
					groups.push(group);
					$(this).find('.filter-option').each(function () {

						var option = {};
						var filters = [];
						option.filters = filters;

						option.filterOptionName = $(this).find('[name="' + ns + 'filterOptionName"]').val();
						if (!option.filterOptionName) {
							return;
						}
						
						$(this).find('.field-filter').each(function () {
							var filter = {};
							
							filter.fieldName = $(this).find('[name="' + ns + 'fieldName"]').val();
							filter.filterOperator = $(this).find('[name="' + ns + 'filterOperator"]').val();
							filter.fieldValue = $(this).find('[name="' + ns + 'fieldValue"]:not(:disabled)').val();
							filter.numDays = $(this).find('[name="' + ns + 'numDays"]').val();
							filter.fieldType = $(this).find('[name="' + ns + 'fieldType"]').val();
							
							if (filter.fieldName && filter.filterOperator) {
								filters.push(filter);
							}
						});

						if (filters.length > 0) {
							options.push(option);
						} 
						
					});
				});


				hiddenFormField.val(JSON.stringify(groups));
			},

			removeItem: function (event, element, selector) {
				event.preventDefault();
				var nodeToRemove = $(element).parents(selector).first().get(0);
				nodeToRemove.parentNode.removeChild(nodeToRemove);
			},

			updateAvailableInputs: function (target) {
				var optionSelectedValue = $(target).val();
			
				if (optionSelectedValue != "") {
					var selectedElement = $(target).find("option[value=" + optionSelectedValue + "]");
					var tableRow = $(target).closest("tr");
					
					var type = selectedElement.attr('data-type');
					
					tableRow.find("input.field-type").val(type);
					
					FieldFilterBuilder.showAndHideFilterFields(tableRow, type);
				}
			},
			
			showAndHideFilterFields: function (filterElement, type) {
				if (type == "date") {
					filterElement.find(".date-field-wrapper").show();
					filterElement.find(".date-field-wrapper input").prop('disabled', false);
					filterElement.find(".num-days-cell").show();
					filterElement.find(".number-field-wrapper").hide();
					filterElement.find(".number-field-wrapper input").prop('disabled', true);
				}
				else {
					filterElement.find(".number-field-wrapper").show();
					filterElement.find(".number-field-wrapper input").prop('disabled', false);
					filterElement.find(".date-field-wrapper").hide();
					filterElement.find(".date-field-wrapper input").prop('disabled', true);
					filterElement.find(".num-days-cell").hide();
				}
			},

			buildForm: function (jsonConfigData) {

				var existingFilterGroups = JSON.parse(jsonConfigData);

				for (var i = 0; i < existingFilterGroups.length; i++) {
					var filterGroup = existingFilterGroups[i];
					var options = filterGroup.options;

					var filterGroupElement = FieldFilterBuilder.createFilterGroup();
					$(filterGroupElement).find('[name="' + ns + 'filterGroupName"]').val(filterGroup.filterGroupName);
					$(filterGroupElement).find('[name="' + ns + 'filterPreselectedOptionName"]').val(filterGroup.filterPreselectedOptionName);

					for (var x = 0; x < options.length; x++) {
						var option = options[x];
						var filterOptionElement = FieldFilterBuilder.createFilterOption($(filterGroupElement).find('.filter-options').get(0));
						$(filterOptionElement).find('[name="' + ns + 'filterOptionName"]').val(option.filterOptionName);

						var filters = option.filters;
						var filtersElement = ($(filterOptionElement).find('.filters').get(0));
						for (var y = 0; y < filters.length; y++) {
							var filter = filters[y];
							var filterElement = FieldFilterBuilder.createFilter(filtersElement);
							$(filterElement).find('[name="' + ns + 'fieldName"]').val(filter.fieldName);
							$(filterElement).find('[name="' + ns + 'filterOperator"]').val(filter.filterOperator);
							$(filterElement).find('[name="' + ns + 'fieldValue"]').val(filter.fieldValue);
							$(filterElement).find('[name="' + ns + 'numDays"]').val(filter.numDays);
							$(filterElement).find('[name="' + ns + 'fieldType"]').val(filter.fieldType);
							
							FieldFilterBuilder.showAndHideFilterFields($(filterElement), filter.fieldType);
						}

					}

				}
			}
		};

		A.FieldFilterBuilder = FieldFilterBuilder;

	},
	'', {
	requires: [
		'aui-base'
	]
});
var namespace;

function loadScript(GOOGLE_API_KEY, portletNamespace) {
	namespace = portletNamespace;
	if (!(window.google && window.google.maps)) {
		var script = document.createElement('script');
		script.type = 'text/javascript';
		script.src = 'https://maps.googleapis.com/maps/api/js?key=' + GOOGLE_API_KEY + '&callback=initAutocomplete&libraries=places&v=weekly'; //& needed
		document.body.appendChild(script);
	} else {
		initAutocomplete();
	}

}

function initAutocomplete() {
	var autocomplete = new google.maps.places.Autocomplete(document.querySelector('#' + namespace + 'autocomplete'), {
		componentRestrictions: { country: ['uk'] },
		fields: ['formatted_address', 'geometry', 'name'],
		types: ['geocode'],
	});
	autocomplete.addListener("place_changed", () => {
		var place = autocomplete.getPlace();
		if (!place.geometry || !place.geometry.location) {
			return;
		}
		if (place.geometry.location) {
			document.getElementById(namespace + "latitude").value = place.geometry.location.lat();
			document.getElementById(namespace + "longitude").value = place.geometry.location.lng();
			document.getElementById(namespace + "formattedAddress").value = place.formatted_address;
			document.getElementById(namespace + "location-search-form").submit();
		}

	});
}

function clearCurrentLocation() {
	document.getElementById(namespace + "formattedAddress").value = '';
	document.getElementById(namespace + "location-search-form").submit();
}

function getCurrentLocation() {
	if (navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(showPosition);
	} else {
		window.alert("Geolocation is not supported by this browser.");
	}
}

function showPosition(position) {
	document.getElementById(namespace + "latitude").value = position.coords.latitude;
	document.getElementById(namespace + "longitude").value = position.coords.longitude;
	document.getElementById(namespace + "formattedAddress").value = "Current location";
	document.getElementById(namespace + "location-search-form").submit();
}

AUI.add(
	'announcements-banner',
	function(A) {

		var AnnouncementsBanner = {
				init: function() {
					var elements = document.getElementsByClassName('announcement-dismiss-button');
					for(var i = 0; i < elements.length; i++){
						elements[i].onclick = function() {
							$.ajax({
								type: 'POST',
								url: $(this).attr("href")
							});
						}
					}
					
				}
		};

		A.AnnouncementsBanner = AnnouncementsBanner;
	},
	'',
	{
		requires: [	
			'aui-base'
		]
	}
);

function displayAnnouncementsBanner() {
	let announcements = $('#p_p_id_com_placecube_digitalplace_announcements_banner_web_AnnouncementsBannerPortlet_').detach();
	if(announcements.length == 0 || !announcements.is(':visible')){
		announcements.addClass('container');
		$('header').siblings('#content').prepend(announcements);
		announcements.show();
	}
}

Liferay.on('endNavigate', function(){
	displayAnnouncementsBanner()
});

Liferay.on('allPortletsReady', function(){
	displayAnnouncementsBanner()
});

AUI.add(

	'com-placecube-digitalplace-address-postcodelookup',

	function (A) {

		var NS = 'ns';
		var ENTRY_EMPTY_OPTION = '<option value="">{numberOfAddresses} addresses found for {postcode}</option>';

		var ENTRY_OPTION_TEMPLATE = '<option {selectedAddress} value="{addressId}">{addressValue}</option>';

		var SELECTED_CALLBACK = 'selectedCallback';

		var UNSELECTED_CALLBACK = 'unselectedCallback';

		var ADDRESS_FORM_CONTAINER_ID = 'addressFormContainerId';
		var ADDRESS_LOOKUP_RESET_ID = 'addressLookupResetId';
		var BUTTON_ADDRESS_LOOKUP_ID = 'btnAddressLookupId';
		var FULL_ADDRESS_ID = 'fullAddressId';
		var POST_CODE_FIELD_CONTAINER_ID = 'postcodeFieldContainerId';
		var POSTCODE_ID = 'postcodeId';
		var POST_CODE_LABEL_ID = 'postcodeLabelId';
		var UPRN_ID = 'uprnId';

		A.PostcodeLookup = A.Component.create({

			NAME: 'com-placecube-digitalplace-address-postcodelookup',

			EXTENDS: A.Component,

			ATTRS: {
				ns: {},
				selectedCallback: {},
				unselectedCallback: {},
				fallbackToNationalLookup: {},
				addressFormContainerId: {},
				addressLookupResetId: {},
				btnAddressLookupId: {},
				fullAddressId: {},
				postcodeFieldContainerId: {},
				postcodeId: {},
				postcodeLabelId: {},
				uprnId: {}
			},
			prototype: {


				render: function () {
					var instance = this;
					instance._init();
				},

				_init: function () {

					var instance = this;

					instance.set(ADDRESS_FORM_CONTAINER_ID, '#' + instance.get(NS) + 'addressFormContainer');
					instance.set(ADDRESS_LOOKUP_RESET_ID, '#' + instance.get(NS) + 'addressLookupReset');
					instance.set(BUTTON_ADDRESS_LOOKUP_ID, '#' + instance.get(NS) + 'btnAddressLookup');
					instance.set(FULL_ADDRESS_ID, '#' + instance.get(NS) + 'fullAddress');
					instance.set(POST_CODE_FIELD_CONTAINER_ID, '#' + instance.get(NS) + 'postcodeFieldContainer');
					instance.set(POSTCODE_ID, '#' + instance.get(NS) + 'postcode');
					instance.set(POST_CODE_LABEL_ID, '#' + instance.get(NS) + 'postcodeLabel');
					instance.set(UPRN_ID, '#' + instance.get(NS) + 'uprn');

					$(instance.get(BUTTON_ADDRESS_LOOKUP_ID)).on('click', function (e) {
						var postcodeValue = $(instance.get(POSTCODE_ID)).val();
						instance.lookupAddress(postcodeValue);
					});

					$(instance.get(ADDRESS_LOOKUP_RESET_ID)).on('click', function (e) {
						e.preventDefault();
						instance._resetAddressLookup();
						instance._callback(UNSELECTED_CALLBACK);
					});

					$(instance.get(UPRN_ID)).on('change', function (e) {
						instance._displaySelectedAddress(Liferay.Util.escape($(this).find("option:selected").text()));
						if ($(this).prop('selectedIndex') > 0) {
							instance._callback(SELECTED_CALLBACK);
						} else {
							instance._callback(UNSELECTED_CALLBACK);
						}
					});

				},

				lookupAddress: function (postcodeValue) {

					var instance = this;

					var uprnId = instance.get(UPRN_ID);
					var postcodeId = instance.get(POSTCODE_ID);
					var postcodeLabelId = instance.get(POST_CODE_LABEL_ID);
					var btnAddressLookupId = instance.get(BUTTON_ADDRESS_LOOKUP_ID);
					var addressFormContainerId = instance.get(ADDRESS_FORM_CONTAINER_ID);
					var addressLookupResetId = instance.get(ADDRESS_LOOKUP_RESET_ID);

					var isValidPostcode = postcodeValue.match(/[A-Z]{1,2}[0-9][0-9A-Z]?\s?[0-9][A-Z]{2}/gi);
					if (isValidPostcode != null) {
						postcodeValue = Liferay.Util.escape(postcodeValue);
						Liferay.Service(
							'/placecube_digitalplace.addresscontext/search-address-by-postcode',
							{
								companyId: Liferay.ThemeDisplay.getCompanyId(),
								postcode: postcodeValue,
								fallbackToNationalLookup: instance.get('fallbackToNationalLookup')
							},
							function (data) {

								var addressesFound = data;

								instance._displaySelectedAddress('');
								$(uprnId).html('');
								instance._clearErrorMessage();

								if (addressesFound.length === 0) {
									$(addressFormContainerId).addClass('hide');
									instance._configurePostcodeErrorMessage('We\x20did\x20not\x20find\x20any\x20address\x20with\x20that\x20postcode\x2e\x20Please\x20check\x20you\x27ve\x20entered\x20it\x20correctly\x2e');
								} else {
									$(postcodeId).addClass('hide');
									$(postcodeLabelId).html(postcodeValue);
									$(postcodeLabelId).removeClass('hide');
									$(btnAddressLookupId).addClass('hide');

									$(addressFormContainerId).removeClass('hide');
									$(addressLookupResetId).removeClass('hide');

									var emptyOption = A.Lang.sub(
										ENTRY_EMPTY_OPTION,
										{
											numberOfAddresses: addressesFound.length,
											postcode: postcodeValue
										}
									);
									$(uprnId).append(emptyOption);

									$.each(addressesFound, function (key, value) {
										var entryValue = A.Lang.sub(
											ENTRY_OPTION_TEMPLATE,
											{
												addressId: value.UPRN,
												addressValue: value.fullAddress,
												selectedAddress: ''
											}
										);
										$(uprnId).append(entryValue);
									});
								}
							}
						);

					} else {
						instance._displaySelectedAddress('');
						$(uprnId).html('');
						instance._clearErrorMessage();

						$(addressFormContainerId).addClass('hide');
						instance._configurePostcodeErrorMessage('Please\x20enter\x20a\x20valid\x20postcode');
					}
				},

				_callback: function (callback) {
					var instance = this;
					if (instance.get(callback)) {
						eval(instance.get(callback));
					}
				},

				_clearErrorMessage: function () {
					var instance = this;

					var postcodeFieldContainerId = instance.get(POST_CODE_FIELD_CONTAINER_ID);
					$(postcodeFieldContainerId + ' .form-group.input-text-wrapper').removeClass('has-success has-error');
					$(postcodeFieldContainerId + ' .field.form-control').removeClass('error-field');
					$(postcodeFieldContainerId + ' .form-group.input-text-wrapper .form-validator-stack').remove();
				},

				_configurePostcodeErrorMessage: function (errorMessage) {
					var instance = this;

					var postcodeFieldContainerId = instance.get(POST_CODE_FIELD_CONTAINER_ID);
					$(postcodeFieldContainerId + ' .form-group.input-text-wrapper').addClass('has-error');
					$(postcodeFieldContainerId + ' .field.form-control').addClass('error-field');
					$(postcodeFieldContainerId + ' .form-group.input-text-wrapper').append('<div class="form-validator-stack help-block"><div role="alert" class="required">' + errorMessage + '</div></div>');
				},

				_displaySelectedAddress: function (fullAddressSelected) {
					var instance = this;
					var fullAddressDetailsId = '#' + instance.get(NS) + 'fullAddressDetails';
					var addressDisplayContainerId = '#' + instance.get(NS) + 'addressDisplayContainer';

					if (fullAddressSelected !== undefined && fullAddressSelected.length > 0) {
						$(instance.get(FULL_ADDRESS_ID)).val(fullAddressSelected);
					}

					if ($(addressDisplayContainerId).length) {
						if (fullAddressSelected !== undefined && fullAddressSelected.length > 0) {
							$(fullAddressDetailsId).html(fullAddressSelected);
							$(addressDisplayContainerId).removeClass('hide');
						} else {
							$(fullAddressDetailsId).html('');
							$(addressDisplayContainerId).addClass('hide');
						}
					}
				},

				_resetAddressLookup: function () {
					var instance = this;

					$(instance.get(ADDRESS_FORM_CONTAINER_ID)).addClass('hide');
					$(instance.get(ADDRESS_LOOKUP_RESET_ID)).addClass('hide');
					$(instance.get(FULL_ADDRESS_ID)).val('');
					$(instance.get(UPRN_ID)).html('');

					$(instance.get(POST_CODE_FIELD_CONTAINER_ID) + ' .field.form-control').val('');
					$(instance.get(POST_CODE_LABEL_ID)).addClass('hide');
					$(instance.get(POSTCODE_ID)).removeClass('hide');
					$(instance.get(BUTTON_ADDRESS_LOOKUP_ID)).removeClass('hide');
				}
			}
		});
	},
	'',
	{
		requires: [
			'aui-base',
			'liferay-util-window'
		]
	}
);

