/* global phpbb */
/**
* phpBB3 forum functions
*/
/**
* Find a member
*/
function find_username(url) {
	'use strict';
	popup(url, 760, 570, '_usersearch');
	return false;
}
/**
* Window popup
*/
function popup(url, width, height, name) {
	'use strict';
	if (!name) {
		name = '_popup';
	}
	window.open(url.replace(/&/g, '&'), name, 'height=' + height + ',resizable=yes,scrollbars=yes, width=' + width);
	return false;
}
/**
* Jump to page
*/
function pageJump(item) {
	'use strict';
	var page = parseInt(item.val(), 10),
		perPage = item.attr('data-per-page'),
		baseUrl = item.attr('data-base-url'),
		startName = item.attr('data-start-name');
	if (page !== null && !isNaN(page) && page === Math.floor(page) && page > 0) {
		if (baseUrl.indexOf('?') === -1) {
			document.location.href = baseUrl + '?' + startName + '=' + ((page - 1) * perPage);
		} else {
			document.location.href = baseUrl.replace(/&/g, '&') + '&' + startName + '=' + ((page - 1) * perPage);
		}
	}
}
/**
* Mark/unmark checklist
* id = ID of parent container, name = name prefix, state = state [true/false]
*/
function marklist(id, name, state) {
	'use strict';
	jQuery('#' + id + ' input[type=checkbox][name]').each(function() {
		var $this = jQuery(this);
		if ($this.attr('name').substr(0, name.length) === name && !$this.prop('disabled')) {
			$this.prop('checked', state);
		}
	});
}
/**
* Resize viewable area for attached image or topic review panel (possibly others to come)
* e = element
*/
function viewableArea(e, itself) {
	'use strict';
	if (!e) {
		return;
	}
	if (!itself) {
		e = e.parentNode;
	}
	if (!e.vaHeight) {
		// Store viewable area height before changing style to auto
		e.vaHeight = e.offsetHeight;
		e.vaMaxHeight = e.style.maxHeight;
		e.style.height = 'auto';
		e.style.maxHeight = 'none';
		e.style.overflow = 'visible';
	} else {
		// Restore viewable area height to the default
		e.style.height = e.vaHeight + 'px';
		e.style.overflow = 'auto';
		e.style.maxHeight = e.vaMaxHeight;
		e.vaHeight = false;
	}
}
/**
* Alternate display of subPanels
*/
jQuery(function($) {
	'use strict';
	$('.sub-panels').each(function() {
		var $childNodes = $('a[data-subpanel]', this),
			panels = $childNodes.map(function () {
				return this.getAttribute('data-subpanel');
			}),
			showPanel = this.getAttribute('data-show-panel');
		if (panels.length) {
			activateSubPanel(showPanel, panels);
			$childNodes.click(function () {
				activateSubPanel(this.getAttribute('data-subpanel'), panels);
				return false;
			});
		}
	});
});
/**
* Activate specific subPanel
*/
function activateSubPanel(p, panels) {
	'use strict';
	var i, showPanel;
	if (typeof p === 'string') {
		showPanel = p;
	}
	$('input[name="show_panel"]').val(showPanel);
	if (typeof panels === 'undefined') {
		panels = jQuery('.sub-panels a[data-subpanel]').map(function() {
			return this.getAttribute('data-subpanel');
		});
	}
	for (i = 0; i < panels.length; i++) {
		jQuery('#' + panels[i]).css('display', panels[i] === showPanel ? 'block' : 'none');
		jQuery('#' + panels[i] + '-tab').toggleClass('activetab', panels[i] === showPanel);
	}
}
function selectCode(a) {
	'use strict';
	// Get ID of code block
	var e = a.parentNode.parentNode.getElementsByTagName('CODE')[0];
	var s, r;
	// Not IE and IE9+
	if (window.getSelection) {
		s = window.getSelection();
		// Safari and Chrome
		if (s.setBaseAndExtent) {
			var l = (e.innerText.length > 1) ? e.innerText.length - 1 : 1;
			try {
				s.setBaseAndExtent(e, 0, e, l);
			} catch (error) {
				r = document.createRange();
				r.selectNodeContents(e);
				s.removeAllRanges();
				s.addRange(r);
			}
		}
		// Firefox and Opera
		else {
			// workaround for bug # 42885
			if (window.opera && e.innerHTML.substring(e.innerHTML.length - 4) === '
') {
				e.innerHTML = e.innerHTML + ' ';
			}
			r = document.createRange();
			r.selectNodeContents(e);
			s.removeAllRanges();
			s.addRange(r);
		}
	}
	// Some older browsers
	else if (document.getSelection) {
		s = document.getSelection();
		r = document.createRange();
		r.selectNodeContents(e);
		s.removeAllRanges();
		s.addRange(r);
	}
	// IE
	else if (document.selection) {
		r = document.body.createTextRange();
		r.moveToElementText(e);
		r.select();
	}
}
var inAutocomplete = false;
var lastKeyEntered = '';
/**
* Check event key
*/
function phpbbCheckKey(event) {
	'use strict';
	// Keycode is array down or up?
	if (event.keyCode && (event.keyCode === 40 || event.keyCode === 38)) {
		inAutocomplete = true;
	}
	// Make sure we are not within an "autocompletion" field
	if (inAutocomplete) {
		// If return pressed and key changed we reset the autocompletion
		if (!lastKeyEntered || lastKeyEntered === event.which) {
			inAutocomplete = false;
			return true;
		}
	}
	// Keycode is not return, then return. ;)
	if (event.which !== 13) {
		lastKeyEntered = event.which;
		return true;
	}
	return false;
}
/**
* Apply onkeypress event for forcing default submit button on ENTER key press
*/
jQuery(function($) {
	'use strict';
	$('form input[type=text], form input[type=password]').on('keypress', function (e) {
		var defaultButton = $(this).parents('form').find('input[type=submit].default-submit-action');
		if (!defaultButton || defaultButton.length <= 0) {
			return true;
		}
		if (phpbbCheckKey(e)) {
			return true;
		}
		if ((e.which && e.which === 13) || (e.keyCode && e.keyCode === 13)) {
			defaultButton.click();
			return false;
		}
		return true;
	});
});
/**
* Functions for user search popup
*/
function insertUser(formId, value) {
	'use strict';
	var $form = jQuery(formId),
		formName = $form.attr('data-form-name'),
		fieldName = $form.attr('data-field-name'),
		item = opener.document.forms[formName][fieldName];
	if (item.value.length && item.type === 'textarea') {
		value = item.value + '\n' + value;
	}
	item.value = value;
}
function insert_marked_users(formId, users) {
	'use strict';
	$(users).filter(':checked').each(function() {
		insertUser(formId, this.value);
	});
	window.close();
}
function insert_single_user(formId, user) {
	'use strict';
	insertUser(formId, user);
	window.close();
}
/**
* Parse document block
*/
function parseDocument($container) {
	'use strict';
	var test = document.createElement('div'),
		oldBrowser = (typeof test.style.borderRadius === 'undefined'),
		$body = $('body');
	/**
	* Reset avatar dimensions when changing URL or EMAIL
	*/
	$container.find('input[data-reset-on-edit]').on('keyup', function() {
		$(this.getAttribute('data-reset-on-edit')).val('');
	});
	/**
	* Pagination
	*/
	$container.find('.pagination .page-jump-form :button').click(function() {
		var $input = $(this).siblings('input.inputbox');
		pageJump($input);
	});
	$container.find('.pagination .page-jump-form input.inputbox').on('keypress', function(event) {
		if (event.which === 13 || event.keyCode === 13) {
			event.preventDefault();
			pageJump($(this));
		}
	});
	$container.find('.pagination .dropdown-trigger').click(function() {
		var $dropdownContainer = $(this).parent();
		// Wait a little bit to make sure the dropdown has activated
		setTimeout(function() {
			if ($dropdownContainer.hasClass('dropdown-visible')) {
				$dropdownContainer.find('input.inputbox').focus();
			}
		}, 100);
	});
	/**
	* Adjust HTML code for IE8 and older versions
	*/
	// if (oldBrowser) {
	// 	// Fix .linklist.bulletin lists
	// 	$container
	// 		.find('ul.linklist.bulletin > li')
	// 		.filter(':first-child, .rightside:last-child')
	// 		.addClass('no-bulletin');
	// }
	/**
	* Resize navigation (breadcrumbs) block to keep all links on same line
	*/
	$container.find('.navlinks').each(function() {
		var $this = $(this),
			$left = $this.children().not('.rightside'),
			$right = $this.children('.rightside');
		if ($left.length !== 1 || !$right.length) {
			return;
		}
		function resize() {
			var width = 0,
				diff = $left.outerWidth(true) - $left.width(),
				minWidth = Math.max($this.width() / 3, 240),
				maxWidth;
			$right.each(function() {
				var $this = $(this);
				if ($this.is(':visible')) {
					width += $this.outerWidth(true);
				}
			});
			maxWidth = $this.width() - width - diff;
			$left.css('max-width', Math.floor(Math.max(maxWidth, minWidth)) + 'px');
		}
		resize();
		$(window).resize(resize);
	});
	/**
	* Makes breadcrumbs responsive
	*/
	$container.find('.breadcrumbs:not([data-skip-responsive])').each(function() {
		var $this = $(this),
			$links = $this.find('.crumb'),
			length = $links.length,
			classes = ['wrapped-max', 'wrapped-wide', 'wrapped-medium', 'wrapped-small', 'wrapped-tiny'],
			classesLength = classes.length,
			maxHeight = 0,
			lastWidth = false,
			wrapped = false;
		// Set tooltips
		$this.find('a').each(function() {
			var $link = $(this);
			$link.attr('title', $link.text());
		});
		// Function that checks breadcrumbs
		function check() {
			var height = $this.height(),
				width;
			// Test max-width set in code for .navlinks above
			width = parseInt($this.css('max-width'), 10);
			if (!width) {
				width = $body.width();
			}
			maxHeight = parseInt($this.css('line-height'), 10);
			$links.each(function() {
				if ($(this).height() > 0) {
					maxHeight = Math.max(maxHeight, $(this).outerHeight(true));
				}
			});
			if (height <= maxHeight) {
				if (!wrapped || lastWidth === false || lastWidth >= width) {
					return;
				}
			}
			lastWidth = width;
			if (wrapped) {
				$this.removeClass('wrapped').find('.crumb.wrapped').removeClass('wrapped ' + classes.join(' '));
				if ($this.height() <= maxHeight) {
					return;
				}
			}
			wrapped = true;
			$this.addClass('wrapped');
			if ($this.height() <= maxHeight) {
				return;
			}
			for (var i = 0; i < classesLength; i++) {
				for (var j = length - 1; j >= 0; j--) {
					$links.eq(j).addClass('wrapped ' + classes[i]);
					if ($this.height() <= maxHeight) {
						return;
					}
				}
			}
		}
		// Run function and set event
		check();
		$(window).resize(check);
	});
	/**
	* Responsive link lists
	*/
	var selector = '.linklist:not(.navlinks, [data-skip-responsive]),' +
		'.postbody .post-buttons:not([data-skip-responsive])';
	$container.find(selector).each(function() {
		var $this = $(this),
			filterSkip = '.breadcrumbs, [data-skip-responsive]',
			filterLast = '.edit-icon, .quote-icon, [data-last-responsive]',
			$linksAll = $this.children(),
			$linksNotSkip = $linksAll.not(filterSkip), // All items that can potentially be hidden
			$linksFirst = $linksNotSkip.not(filterLast), // The items that will be hidden first
			$linksLast = $linksNotSkip.filter(filterLast), // The items that will be hidden last
			persistent = $this.attr('id') === 'nav-main', // Does this list already have a menu (such as quick-links)?
			html = '