[ticket/12982] Refactoring: made most JS nice.

PHPBB3-12982
This commit is contained in:
Callum Macrae 2014-08-13 22:44:21 +01:00
parent e4e7a8f849
commit 340f48fdeb
3 changed files with 327 additions and 295 deletions

View file

@ -3,7 +3,7 @@ phpbb.alertTime = 100;
(function($) { // Avoid conflicts with other libraries (function($) { // Avoid conflicts with other libraries
"use strict"; 'use strict';
// define a couple constants for keydown functions. // define a couple constants for keydown functions.
var keymap = { var keymap = {
@ -12,8 +12,8 @@ var keymap = {
ESC: 27 ESC: 27
}; };
var dark = $('#darkenwrapper'); var $dark = $('#darkenwrapper');
var loadingIndicator = $('#loading_indicator'); var $loadingIndicator = $('#loading_indicator');
var phpbbAlertTimer = null; var phpbbAlertTimer = null;
phpbb.isTouch = (window && typeof window.ontouchstart !== 'undefined'); phpbb.isTouch = (window && typeof window.ontouchstart !== 'undefined');
@ -24,18 +24,20 @@ phpbb.isTouch = (window && typeof window.ontouchstart !== 'undefined');
* @returns object Returns loadingIndicator. * @returns object Returns loadingIndicator.
*/ */
phpbb.loadingIndicator = function() { phpbb.loadingIndicator = function() {
if (!loadingIndicator.is(':visible')) { if (!$loadingIndicator.is(':visible')) {
loadingIndicator.fadeIn(phpbb.alertTime); $loadingIndicator.fadeIn(phpbb.alertTime);
// Wait fifteen seconds and display an error if nothing has been returned by then. // Wait fifteen seconds and display an error if nothing has been returned by then.
phpbb.clearLoadingTimeout(); phpbb.clearLoadingTimeout();
phpbbAlertTimer = setTimeout(function() { phpbbAlertTimer = setTimeout(function() {
if (loadingIndicator.is(':visible')) { var $alert = $('#phpbb_alert');
phpbb.alert($('#phpbb_alert').attr('data-l-err'), $('#phpbb_alert').attr('data-l-timeout-processing-req'));
if ($loadingIndicator.is(':visible')) {
phpbb.alert($alert.attr('data-l-err'), $alert.attr('data-l-timeout-processing-req'));
} }
}, 15000); }, 15000);
} }
return loadingIndicator; return $loadingIndicator;
}; };
/** /**
@ -73,24 +75,24 @@ phpbb.closeDarkenWrapper = function(delay) {
* @returns object Returns the div created. * @returns object Returns the div created.
*/ */
phpbb.alert = function(title, msg, fadedark) { phpbb.alert = function(title, msg, fadedark) {
var div = $('#phpbb_alert'); var $alert = $('#phpbb_alert');
div.find('.alert_title').html(title); $alert.find('.alert_title').html(title);
div.find('.alert_text').html(msg); $alert.find('.alert_text').html(msg);
if (!dark.is(':visible')) { if (!$dark.is(':visible')) {
dark.fadeIn(phpbb.alertTime); $dark.fadeIn(phpbb.alertTime);
} }
div.bind('click', function(e) { $alert.on('click', function(e) {
e.stopPropagation(); e.stopPropagation();
}); });
dark.one('click', function(e) { $dark.one('click', function(e) {
var fade; var fade;
div.find('.alert_close').unbind('click'); $alert.find('.alert_close').off('click');
fade = (typeof fadedark !== 'undefined' && !fadedark) ? div : dark; fade = (typeof fadedark !== 'undefined' && !fadedark) ? $alert : $dark;
fade.fadeOut(phpbb.alertTime, function() { fade.fadeOut(phpbb.alertTime, function() {
div.hide(); $alert.hide();
}); });
e.preventDefault(); e.preventDefault();
@ -98,35 +100,35 @@ phpbb.alert = function(title, msg, fadedark) {
}); });
$(document).keydown(function(e) { $(document).keydown(function(e) {
if ((e.keyCode === keymap.ENTER || e.keyCode === keymap.ESC) && dark.is(':visible')) { if ((e.keyCode === keymap.ENTER || e.keyCode === keymap.ESC) && $dark.is(':visible')) {
dark.trigger('click'); $dark.trigger('click');
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
} }
}); });
div.find('.alert_close').one('click', function(e) { $alert.find('.alert_close').one('click', function(e) {
dark.trigger('click'); $dark.trigger('click');
e.preventDefault(); e.preventDefault();
}); });
if (loadingIndicator.is(':visible')) { if ($loadingIndicator.is(':visible')) {
loadingIndicator.fadeOut(phpbb.alertTime, function() { $loadingIndicator.fadeOut(phpbb.alertTime, function() {
dark.append(div); $dark.append($alert);
div.fadeIn(phpbb.alertTime); $alert.fadeIn(phpbb.alertTime);
}); });
} else if (dark.is(':visible')) { } else if ($dark.is(':visible')) {
dark.append(div); $dark.append($alert);
div.fadeIn(phpbb.alertTime); $alert.fadeIn(phpbb.alertTime);
} else { } else {
dark.append(div); $dark.append($alert);
div.show(); $alert.show();
dark.fadeIn(phpbb.alertTime); $dark.fadeIn(phpbb.alertTime);
} }
return div; return $alert;
}; };
/** /**
@ -143,24 +145,24 @@ phpbb.alert = function(title, msg, fadedark) {
* @returns object Returns the div created. * @returns object Returns the div created.
*/ */
phpbb.confirm = function(msg, callback, fadedark) { phpbb.confirm = function(msg, callback, fadedark) {
var div = $('#phpbb_confirm'); var $confirmDiv = $('#phpbb_confirm');
div.find('.alert_text').html(msg); $confirmDiv.find('.alert_text').html(msg);
if (!dark.is(':visible')) { if (!$dark.is(':visible')) {
dark.fadeIn(phpbb.alertTime); $dark.fadeIn(phpbb.alertTime);
} }
div.bind('click', function(e) { $confirmDiv.on('click', function(e) {
e.stopPropagation(); e.stopPropagation();
}); });
var clickHandler = function(e) { var clickHandler = function(e) {
var res = this.name === 'confirm'; var res = this.name === 'confirm';
var fade = (typeof fadedark !== 'undefined' && !fadedark && res) ? div : dark; var $fade = (typeof fadedark !== 'undefined' && !fadedark && res) ? $confirmDiv : $dark;
fade.fadeOut(phpbb.alertTime, function() { $fade.fadeOut(phpbb.alertTime, function() {
div.hide(); $confirmDiv.hide();
}); });
div.find('input[type="button"]').unbind('click', clickHandler); $confirmDiv.find('input[type="button"]').off('click', clickHandler);
callback(res); callback(res);
if (e) { if (e) {
@ -168,12 +170,12 @@ phpbb.confirm = function(msg, callback, fadedark) {
e.stopPropagation(); e.stopPropagation();
} }
}; };
div.find('input[type="button"]').one('click', clickHandler); $confirmDiv.find('input[type="button"]').one('click', clickHandler);
dark.one('click', function(e) { $dark.one('click', function(e) {
div.find('.alert_close').unbind('click'); $confirmDiv.find('.alert_close').unbind('click');
dark.fadeOut(phpbb.alertTime, function() { $dark.fadeOut(phpbb.alertTime, function() {
div.hide(); $confirmDiv.hide();
}); });
callback(false); callback(false);
@ -181,7 +183,7 @@ phpbb.confirm = function(msg, callback, fadedark) {
e.stopPropagation(); e.stopPropagation();
}); });
$(document).bind('keydown', function(e) { $(document).on('keydown', function(e) {
if (e.keyCode === keymap.ENTER) { if (e.keyCode === keymap.ENTER) {
$('input[name="confirm"]').trigger('click'); $('input[name="confirm"]').trigger('click');
e.preventDefault(); e.preventDefault();
@ -193,31 +195,31 @@ phpbb.confirm = function(msg, callback, fadedark) {
} }
}); });
div.find('.alert_close').one('click', function(e) { $confirmDiv.find('.alert_close').one('click', function(e) {
var fade = (typeof fadedark !== 'undefined' && fadedark) ? div : dark; var $fade = (typeof fadedark !== 'undefined' && fadedark) ? $confirmDiv : $dark;
fade.fadeOut(phpbb.alertTime, function() { $fade.fadeOut(phpbb.alertTime, function() {
div.hide(); $confirmDiv.hide();
}); });
callback(false); callback(false);
e.preventDefault(); e.preventDefault();
}); });
if (loadingIndicator.is(':visible')) { if ($loadingIndicator.is(':visible')) {
loadingIndicator.fadeOut(phpbb.alertTime, function() { $loadingIndicator.fadeOut(phpbb.alertTime, function() {
dark.append(div); $dark.append($confirmDiv);
div.fadeIn(phpbb.alertTime); $confirmDiv.fadeIn(phpbb.alertTime);
}); });
} else if (dark.is(':visible')) { } else if ($dark.is(':visible')) {
dark.append(div); $dark.append($confirmDiv);
div.fadeIn(phpbb.alertTime); $confirmDiv.fadeIn(phpbb.alertTime);
} else { } else {
dark.append(div); $dark.append($confirmDiv);
div.show(); $confirmDiv.show();
dark.fadeIn(phpbb.alertTime); $dark.fadeIn(phpbb.alertTime);
} }
return div; return $confirmDiv;
}; };
/** /**
@ -257,12 +259,12 @@ phpbb.parseQuerystring = function(string) {
* that was returned and (if it is a form) the form action. * that was returned and (if it is a form) the form action.
*/ */
phpbb.ajaxify = function(options) { phpbb.ajaxify = function(options) {
var elements = $(options.selector), var $elements = $(options.selector),
refresh = options.refresh, refresh = options.refresh,
callback = options.callback, callback = options.callback,
overlay = (typeof options.overlay !== 'undefined') ? options.overlay : true, overlay = (typeof options.overlay !== 'undefined') ? options.overlay : true,
isForm = elements.is('form'), isForm = $elements.is('form'),
isText = elements.is('input[type="text"], textarea'), isText = $elements.is('input[type="text"], textarea'),
eventName; eventName;
if (isForm) { if (isForm) {
@ -273,7 +275,7 @@ phpbb.ajaxify = function(options) {
eventName = 'click'; eventName = 'click';
} }
elements.bind(eventName, function(event) { $elements.on(eventName, function(event) {
var action, method, data, submit, that = this, $this = $(this); var action, method, data, submit, that = this, $this = $(this);
if ($this.find('input[type="submit"][data-clicked]').attr('data-ajax') === 'false') { if ($this.find('input[type="submit"][data-clicked]').attr('data-ajax') === 'false') {
@ -293,11 +295,12 @@ phpbb.ajaxify = function(options) {
errorText = errorThrown; errorText = errorThrown;
} }
else { else {
errorText = dark.attr('data-ajax-error-text-' + textStatus); errorText = $dark.attr('data-ajax-error-text-' + textStatus);
if (typeof errorText !== 'string' || !errorText.length) if (typeof errorText !== 'string' || !errorText.length) {
errorText = dark.attr('data-ajax-error-text'); errorText = $dark.attr('data-ajax-error-text');
}
} }
phpbb.alert(dark.attr('data-ajax-error-title'), errorText); phpbb.alert($dark.attr('data-ajax-error-title'), errorText);
} }
/** /**
@ -322,7 +325,7 @@ phpbb.ajaxify = function(options) {
if (typeof res.MESSAGE_TITLE !== 'undefined') { if (typeof res.MESSAGE_TITLE !== 'undefined') {
alert = phpbb.alert(res.MESSAGE_TITLE, res.MESSAGE_TEXT); alert = phpbb.alert(res.MESSAGE_TITLE, res.MESSAGE_TEXT);
} else { } else {
dark.fadeOut(phpbb.alertTime); $dark.fadeOut(phpbb.alertTime);
} }
if (typeof phpbb.ajaxCallbacks[callback] === 'function') { if (typeof phpbb.ajaxCallbacks[callback] === 'function') {
@ -345,7 +348,7 @@ phpbb.ajaxify = function(options) {
// Hide the alert even if we refresh the page, in case the user // Hide the alert even if we refresh the page, in case the user
// presses the back button. // presses the back button.
dark.fadeOut(phpbb.alertTime, function() { $dark.fadeOut(phpbb.alertTime, function() {
if (typeof alert !== 'undefined') { if (typeof alert !== 'undefined') {
alert.hide(); alert.hide();
} }
@ -355,17 +358,19 @@ phpbb.ajaxify = function(options) {
} else { } else {
// If confirmation is required, display a dialog to the user. // If confirmation is required, display a dialog to the user.
phpbb.confirm(res.MESSAGE_BODY, function(del) { phpbb.confirm(res.MESSAGE_BODY, function(del) {
if (del) { if (!del) {
phpbb.loadingIndicator(); return;
data = $('<form>' + res.S_HIDDEN_FIELDS + '</form>').serialize();
$.ajax({
url: res.S_CONFIRM_ACTION,
type: 'POST',
data: data + '&confirm=' + res.YES_VALUE + '&' + $('#phpbb_confirm form').serialize(),
success: returnHandler,
error: errorHandler
});
} }
phpbb.loadingIndicator();
data = $('<form>' + res.S_HIDDEN_FIELDS + '</form>').serialize();
$.ajax({
url: res.S_CONFIRM_ACTION,
type: 'POST',
data: data + '&confirm=' + res.YES_VALUE + '&' + $('form', '#phpbb_confirm').serialize(),
success: returnHandler,
error: errorHandler
});
}, false); }, false);
} }
} }
@ -373,7 +378,7 @@ phpbb.ajaxify = function(options) {
// If the element is a form, POST must be used and some extra data must // If the element is a form, POST must be used and some extra data must
// be taken from the form. // be taken from the form.
var runFilter = (typeof options.filter === 'function'); var runFilter = (typeof options.filter === 'function');
var data = {}; data = {};
if (isForm) { if (isForm) {
action = $this.attr('action').replace('&amp;', '&'); action = $this.attr('action').replace('&amp;', '&');
@ -388,7 +393,7 @@ phpbb.ajaxify = function(options) {
}); });
} }
} else if (isText) { } else if (isText) {
var name = ($this.attr('data-name') !== undefined) ? $this.attr('data-name') : this['name']; var name = $this.attr('data-name') || this.name;
action = $this.attr('data-url').replace('&amp;', '&'); action = $this.attr('data-url').replace('&amp;', '&');
data[name] = this.value; data[name] = this.value;
method = 'POST'; method = 'POST';
@ -399,7 +404,8 @@ phpbb.ajaxify = function(options) {
} }
var sendRequest = function() { var sendRequest = function() {
if (overlay && (typeof $this.attr('data-overlay') === 'undefined' || $this.attr('data-overlay') === 'true')) { var dataOverlay = $this.attr('data-overlay');
if (overlay && (typeof dataOverlay === 'undefined' || dataOverlay === 'true')) {
phpbb.loadingIndicator(); phpbb.loadingIndicator();
} }
@ -411,7 +417,7 @@ phpbb.ajaxify = function(options) {
error: errorHandler error: errorHandler
}); });
request.always(function() { request.always(function() {
loadingIndicator.fadeOut(phpbb.alertTime); $loadingIndicator.fadeOut(phpbb.alertTime);
}); });
}; };
@ -426,7 +432,7 @@ phpbb.ajaxify = function(options) {
}); });
if (isForm) { if (isForm) {
elements.find('input:submit').click(function () { $elements.find('input:submit').click(function () {
var $this = $(this); var $this = $(this);
$this.siblings('[data-clicked]').removeAttr('data-clicked'); $this.siblings('[data-clicked]').removeAttr('data-clicked');
@ -437,7 +443,13 @@ phpbb.ajaxify = function(options) {
return this; return this;
}; };
phpbb.search = {cache: {data: []}, tpl: [], container: []}; phpbb.search = {
cache: {
data: []
},
tpl: [],
container: []
};
/** /**
* Get cached search data. * Get cached search data.
@ -478,7 +490,7 @@ phpbb.search.cache.set = function(id, key, value) {
* @return undefined * @return undefined
*/ */
phpbb.search.cache.setResults = function(id, keyword, value) { phpbb.search.cache.setResults = function(id, keyword, value) {
this.data[id]['results'][keyword] = value; this.data[id].results[keyword] = value;
}; };
/** /**
@ -504,7 +516,7 @@ phpbb.search.cleanKeyword = function(keyword) {
phpbb.search.getKeyword = function(el, keyword, multiline) { phpbb.search.getKeyword = function(el, keyword, multiline) {
if (multiline) { if (multiline) {
var line = phpbb.search.getKeywordLine(el); var line = phpbb.search.getKeywordLine(el);
keyword = keyword.split("\n").splice(line, 1); keyword = keyword.split('\n').splice(line, 1);
} }
return phpbb.search.cleanKeyword(keyword); return phpbb.search.cleanKeyword(keyword);
}; };
@ -517,7 +529,7 @@ phpbb.search.getKeyword = function(el, keyword, multiline) {
* @return int * @return int
*/ */
phpbb.search.getKeywordLine = function (el) { phpbb.search.getKeywordLine = function (el) {
return el.val().substr(0, el.get(0).selectionStart).split("\n").length - 1; return el.val().substr(0, el.get(0).selectionStart).split('\n').length - 1;
}; };
/** /**
@ -533,9 +545,9 @@ phpbb.search.getKeywordLine = function (el) {
phpbb.search.setValue = function(el, value, multiline) { phpbb.search.setValue = function(el, value, multiline) {
if (multiline) { if (multiline) {
var line = phpbb.search.getKeywordLine(el), var line = phpbb.search.getKeywordLine(el),
lines = el.val().split("\n"); lines = el.val().split('\n');
lines[line] = value; lines[line] = value;
value = lines.join("\n"); value = lines.join('\n');
} }
el.val(value); el.val(value);
}; };
@ -578,29 +590,29 @@ phpbb.search.filter = function(data, event, sendRequest) {
proceed = true; proceed = true;
data[dataName] = keyword; data[dataName] = keyword;
if (cache['timeout']) { if (cache.timeout) {
clearTimeout(cache['timeout']); clearTimeout(cache.timeout);
} }
var timeout = setTimeout(function() { var timeout = setTimeout(function() {
// Check min length and existence of cache. // Check min length and existence of cache.
if (minLength > keyword.length) { if (minLength > keyword.length) {
proceed = false; proceed = false;
} else if (cache['last_search']) { } else if (cache.last_search) {
// Has the keyword actually changed? // Has the keyword actually changed?
if (cache['last_search'] === keyword) { if (cache.last_search === keyword) {
proceed = false; proceed = false;
} else { } else {
// Do we already have results for this? // Do we already have results for this?
if (cache['results'][keyword]) { if (cache.results[keyword]) {
var response = {keyword: keyword, results: cache['results'][keyword]}; var response = {keyword: keyword, results: cache.results[keyword]};
phpbb.search.handleResponse(response, el, true); phpbb.search.handleResponse(response, el, true);
proceed = false; proceed = false;
} }
// If the previous search didn't yield results and the string only had characters added to it, // If the previous search didn't yield results and the string only had characters added to it,
// then we won't bother sending a request. // then we won't bother sending a request.
if (keyword.indexOf(cache['last_search']) === 0 && cache['results'][cache['last_search']].length === 0) { if (keyword.indexOf(cache.last_search) === 0 && cache.results[cache.last_search].length === 0) {
phpbb.search.cache.set(searchID, 'last_search', keyword); phpbb.search.cache.set(searchID, 'last_search', keyword);
phpbb.search.cache.setResults(searchID, keyword, []); phpbb.search.cache.setResults(searchID, keyword, []);
proceed = false; proceed = false;
@ -635,8 +647,8 @@ phpbb.search.handleResponse = function(res, el, fromCache, callback) {
var searchID = el.attr('data-results'), var searchID = el.attr('data-results'),
container = $(searchID); container = $(searchID);
if (this.cache.get(searchID)['callback']) { if (this.cache.get(searchID).callback) {
callback = this.cache.get(searchID)['callback']; callback = this.cache.get(searchID).callback;
} else if (typeof callback === 'function') { } else if (typeof callback === 'function') {
this.cache.set(searchID, 'callback', callback); this.cache.set(searchID, 'callback', callback);
} }
@ -718,10 +730,8 @@ phpbb.history = {};
* @return bool Returns true if the method is supported. * @return bool Returns true if the method is supported.
*/ */
phpbb.history.isSupported = function(fn) { phpbb.history.isSupported = function(fn) {
if (typeof history === 'undefined' || typeof history[fn] === 'undefined') { return !(typeof history === 'undefined' || typeof history[fn] === 'undefined');
return false;
}
return true;
}; };
/** /**
@ -783,36 +793,43 @@ phpbb.history.pushUrl = function(url, title, obj) {
* @param bool keepSelection Shall we keep the value selected, or shall the user be forced to repick one. * @param bool keepSelection Shall we keep the value selected, or shall the user be forced to repick one.
*/ */
phpbb.timezoneSwitchDate = function(keepSelection) { phpbb.timezoneSwitchDate = function(keepSelection) {
if ($('#timezone_copy').length === 0) { var $timezoneCopy = $('#timezone_copy');
var $timezone = $('#timezone');
var $tzDate = $('#tz_date');
var $tzSelectDateSuggest = $('#tz_select_date_suggest');
if ($timezoneCopy.length === 0) {
// We make a backup of the original dropdown, so we can remove optgroups // We make a backup of the original dropdown, so we can remove optgroups
// instead of setting display to none, because IE and chrome will not // instead of setting display to none, because IE and chrome will not
// hide options inside of optgroups and selects via css // hide options inside of optgroups and selects via css
$('#timezone').clone().attr('id', 'timezone_copy').css('display', 'none').attr('name', 'tz_copy').insertAfter('#timezone'); $timezone.clone().attr('id', 'timezone_copy').css('display', 'none').attr('name', 'tz_copy').insertAfter('#timezone');
} else { } else {
// Copy the content of our backup, so we can remove all unneeded options // Copy the content of our backup, so we can remove all unneeded options
$('#timezone').replaceWith($('#timezone_copy').clone().attr('id', 'timezone').css('display', 'block').attr('name', 'tz')); $timezone.replaceWith($timezoneCopy.clone().attr('id', 'timezone').css('display', 'block').attr('name', 'tz'));
} }
if ($('#tz_date').val() !== '') { if ($tzDate.val() !== '') {
$('#timezone > optgroup').remove(":not([label='" + $('#tz_date').val() + "'])"); $timezone.children('optgroup').remove(':not([label="' + $('#tz_date').val() + '"])');
} }
if ($('#tz_date').val() === $('#tz_select_date_suggest').attr('data-suggested-tz')) { if ($tzDate.val() === $tzSelectDateSuggest.attr('data-suggested-tz')) {
$('#tz_select_date_suggest').css('display', 'none'); $tzSelectDateSuggest.css('display', 'none');
} else { } else {
$('#tz_select_date_suggest').css('display', 'inline'); $tzSelectDateSuggest.css('display', 'inline');
} }
var $tzOptions = $timezone.children('optgroup[label="' + $tzDate.val() + '"]').children('option')
if ($("#timezone > optgroup[label='" + $('#tz_date').val() + "'] > option").size() === 1) { if ($tzOptions.length === 1) {
// If there is only one timezone for the selected date, we just select that automatically. // If there is only one timezone for the selected date, we just select that automatically.
$("#timezone > optgroup[label='" + $('#tz_date').val() + "'] > option:first").prop('selected', true); $tzOptions.prop('selected', true);
keepSelection = true; keepSelection = true;
} }
if (typeof keepSelection !== 'undefined' && !keepSelection) { if (typeof keepSelection !== 'undefined' && !keepSelection) {
var timezoneOptions = $('#timezone > optgroup option'); var $timezoneOptions = $timezone.find('optgroup option');
if (timezoneOptions.filter(':selected').length <= 0) { if ($timezoneOptions.filter(':selected').length <= 0) {
timezoneOptions.filter(':first').prop('selected', true); $timezoneOptions.filter(':first').prop('selected', true);
} }
} }
}; };
@ -832,7 +849,6 @@ phpbb.timezoneEnableDateSelection = function() {
phpbb.timezonePreselectSelect = function(forceSelector) { phpbb.timezonePreselectSelect = function(forceSelector) {
// The offset returned here is in minutes and negated. // The offset returned here is in minutes and negated.
// http://www.w3schools.com/jsref/jsref_getTimezoneOffset.asp
var offset = (new Date()).getTimezoneOffset(); var offset = (new Date()).getTimezoneOffset();
var sign = '-'; var sign = '-';
@ -858,9 +874,11 @@ phpbb.timezonePreselectSelect = function(forceSelector) {
var prefix = 'GMT' + sign + hours + ':' + minutes; var prefix = 'GMT' + sign + hours + ':' + minutes;
var prefixLength = prefix.length; var prefixLength = prefix.length;
var selectorOptions = $('#tz_date > option'); var selectorOptions = $('option', '#tz_date');
var i; var i;
var $tzSelectDateSuggest = $('#tz_select_date_suggest');
for (i = 0; i < selectorOptions.length; ++i) { for (i = 0; i < selectorOptions.length; ++i) {
var option = selectorOptions[i]; var option = selectorOptions[i];
@ -869,16 +887,18 @@ phpbb.timezonePreselectSelect = function(forceSelector) {
// We do not select the option for the user, but notify him, // We do not select the option for the user, but notify him,
// that we would suggest a different setting. // that we would suggest a different setting.
phpbb.timezoneSwitchDate(true); phpbb.timezoneSwitchDate(true);
$('#tz_select_date_suggest').css('display', 'inline'); $tzSelectDateSuggest.css('display', 'inline');
} else { } else {
option.selected = true; option.selected = true;
phpbb.timezoneSwitchDate(!forceSelector); phpbb.timezoneSwitchDate(!forceSelector);
$('#tz_select_date_suggest').css('display', 'none'); $tzSelectDateSuggest.css('display', 'none');
} }
$('#tz_select_date_suggest').attr('title', $('#tz_select_date_suggest').attr('data-l-suggestion').replace("%s", option.innerHTML)); var suggestion = $tzSelectDateSuggest.attr('data-l-suggestion');
$('#tz_select_date_suggest').attr('value', $('#tz_select_date_suggest').attr('data-l-suggestion').replace("%s", option.innerHTML.substring(0, 9)));
$('#tz_select_date_suggest').attr('data-suggested-tz', option.innerHTML); $tzSelectDateSuggest.attr('title', suggestion.replace('%s', option.innerHTML));
$tzSelectDateSuggest.attr('value', suggestion.replace('%s', option.innerHTML.substring(0, 9)));
$tzSelectDateSuggest.attr('data-suggested-tz', option.innerHTML);
// Found the suggestion, there cannot be more, so return from here. // Found the suggestion, there cannot be more, so return from here.
return; return;
@ -916,22 +936,22 @@ phpbb.addAjaxCallback('member_search', function(res) {
* current text so that the process can be repeated. * current text so that the process can be repeated.
*/ */
phpbb.addAjaxCallback('alt_text', function() { phpbb.addAjaxCallback('alt_text', function() {
var el, var $el,
updateAll = $(this).data('update-all'), updateAll = $(this).data('update-all'),
altText; altText;
if (updateAll !== undefined && updateAll.length) { if (updateAll !== undefined && updateAll.length) {
el = $(updateAll); $el = $(updateAll);
} else { } else {
el = $(this); $el = $(this);
} }
el.each(function() { $el.each(function() {
var el = $(this); var $this = $(this);
altText = el.attr('data-alt-text'); altText = $this.attr('data-alt-text');
el.attr('data-alt-text', el.text()); $this.attr('data-alt-text', $this.text());
el.attr('title', $.trim(altText)); $this.attr('title', $.trim(altText));
el.text(altText); $this.text(altText);
}); });
}); });
@ -945,36 +965,36 @@ phpbb.addAjaxCallback('alt_text', function() {
* and changes the link itself. * and changes the link itself.
*/ */
phpbb.addAjaxCallback('toggle_link', function() { phpbb.addAjaxCallback('toggle_link', function() {
var el, var $el,
updateAll = $(this).data('update-all') , updateAll = $(this).data('update-all') ,
toggleText, toggleText,
toggleUrl, toggleUrl,
toggleClass; toggleClass;
if (updateAll !== undefined && updateAll.length) { if (updateAll !== undefined && updateAll.length) {
el = $(updateAll); $el = $(updateAll);
} else { } else {
el = $(this); $el = $(this);
} }
el.each(function() { $el.each(function() {
var el = $(this); var $this = $(this);
// Toggle link text // Toggle link text
toggleText = el.attr('data-toggle-text'); toggleText = $this.attr('data-toggle-text');
el.attr('data-toggle-text', el.text()); $this.attr('data-toggle-text', $this.text());
el.attr('title', $.trim(toggleText)); $this.attr('title', $.trim(toggleText));
el.text(toggleText); $this.text(toggleText);
// Toggle link url // Toggle link url
toggleUrl = el.attr('data-toggle-url'); toggleUrl = $this.attr('data-toggle-url');
el.attr('data-toggle-url', el.attr('href')); $this.attr('data-toggle-url', $this.attr('href'));
el.attr('href', toggleUrl); $this.attr('href', toggleUrl);
// Toggle class of link parent // Toggle class of link parent
toggleClass = el.attr('data-toggle-class'); toggleClass = $this.attr('data-toggle-class');
el.attr('data-toggle-class', el.parent().attr('class')); $this.attr('data-toggle-class', $this.parent().attr('class'));
el.parent().attr('class', toggleClass); $this.parent().attr('class', toggleClass);
}); });
}); });
@ -984,7 +1004,7 @@ phpbb.addAjaxCallback('toggle_link', function() {
* This function automatically resizes textarea elements when user * This function automatically resizes textarea elements when user
* types text. * types text.
* *
* @param {jQuery} items jQuery object(s) to resize * @param {jQuery} $items jQuery object(s) to resize
* @param {object} options Optional parameter that adjusts default * @param {object} options Optional parameter that adjusts default
* configuration. See configuration variable * configuration. See configuration variable
* *
@ -1000,25 +1020,26 @@ phpbb.addAjaxCallback('toggle_link', function() {
* this points to DOM object * this points to DOM object
* item is a jQuery object, same as this * item is a jQuery object, same as this
*/ */
phpbb.resizeTextArea = function(items, options) { phpbb.resizeTextArea = function($items, options) {
// Configuration // Configuration
var configuration = { var configuration = {
minWindowHeight: 500, minWindowHeight: 500,
minHeight: 200, minHeight: 200,
maxHeight: 500, maxHeight: 500,
heightDiff: 200, heightDiff: 200,
resizeCallback: function(item) { }, resizeCallback: function() {},
resetCallback: function(item) { } resetCallback: function() {}
}; };
if (phpbb.isTouch) return; if (phpbb.isTouch) {
return;
}
if (arguments.length > 1) { if (arguments.length > 1) {
configuration = $.extend(configuration, options); configuration = $.extend(configuration, options);
} }
function resetAutoResize(item) function resetAutoResize(item) {
{
var $item = $(item); var $item = $(item);
if ($item.hasClass('auto-resized')) { if ($item.hasClass('auto-resized')) {
$(item).css({height: '', resize: ''}).removeClass('auto-resized'); $(item).css({height: '', resize: ''}).removeClass('auto-resized');
@ -1026,10 +1047,8 @@ phpbb.resizeTextArea = function(items, options) {
} }
} }
function autoResize(item) function autoResize(item) {
{ function setHeight(height) {
function setHeight(height)
{
height += parseInt($item.css('height')) - $item.height(); height += parseInt($item.css('height')) - $item.height();
$item.css({height: height + 'px', resize: 'none'}).addClass('auto-resized'); $item.css({height: height + 'px', resize: 'none'}).addClass('auto-resized');
configuration.resizeCallback.call(item, $item); configuration.resizeCallback.call(item, $item);
@ -1059,14 +1078,14 @@ phpbb.resizeTextArea = function(items, options) {
} }
} }
items.bind('focus change keyup', function() { $items.on('focus change keyup', function() {
$(this).each(function() { $(this).each(function() {
autoResize(this); autoResize(this);
}); });
}).change(); }).change();
$(window).resize(function() { $(window).resize(function() {
items.each(function() { $items.each(function() {
if ($(this).hasClass('auto-resized')) { if ($(this).hasClass('auto-resized')) {
autoResize(this); autoResize(this);
} }
@ -1104,7 +1123,9 @@ phpbb.inBBCodeTag = function(textarea, startTags, endTags) {
lastStart = Math.max(lastStart, index); lastStart = Math.max(lastStart, index);
} }
} }
if (lastStart == -1) return false; if (lastStart == -1) {
return false;
}
if (start > 0) { if (start > 0) {
for (i = 0; i < endTags.length; i++) { for (i = 0; i < endTags.length; i++) {
@ -1114,7 +1135,7 @@ phpbb.inBBCodeTag = function(textarea, startTags, endTags) {
} }
return (lastEnd < lastStart); return (lastEnd < lastStart);
} };
/** /**
@ -1158,7 +1179,7 @@ phpbb.applyCodeEditor = function(textarea) {
function getLastLine(stripCodeStart) { function getLastLine(stripCodeStart) {
var start = textarea.selectionStart, var start = textarea.selectionStart,
value = textarea.value, value = textarea.value,
index = value.lastIndexOf("\n", start - 1); index = value.lastIndexOf('\n', start - 1);
value = value.substring(index + 1, start); value = value.substring(index + 1, start);
@ -1207,7 +1228,7 @@ phpbb.applyCodeEditor = function(textarea) {
!event.altKey && !event.altKey &&
!event.metaKey) { !event.metaKey) {
if (inTag()) { if (inTag()) {
appendText("\t"); appendText('\t');
event.preventDefault(); event.preventDefault();
return; return;
} }
@ -1220,9 +1241,8 @@ phpbb.applyCodeEditor = function(textarea) {
code = '' + /^\s*/g.exec(lastLine); code = '' + /^\s*/g.exec(lastLine);
if (code.length > 0) { if (code.length > 0) {
appendText("\n" + code); appendText('\n' + code);
event.preventDefault(); event.preventDefault();
return;
} }
} }
} }
@ -1247,22 +1267,22 @@ phpbb.toggleDropdown = function() {
var $this = $(this), var $this = $(this),
options = $this.data('dropdown-options'), options = $this.data('dropdown-options'),
parent = options.parent, parent = options.parent,
visible = parent.hasClass('dropdown-visible'); visible = parent.hasClass('dropdown-visible'),
direction;
if (!visible) { if (!visible) {
// Hide other dropdown menus // Hide other dropdown menus
$(phpbb.dropdownHandles).each(phpbb.toggleDropdown); $(phpbb.dropdownHandles).each(phpbb.toggleDropdown);
// Figure out direction of dropdown // Figure out direction of dropdown
var direction = options.direction, direction = options.direction;
verticalDirection = options.verticalDirection, var verticalDirection = options.verticalDirection,
offset = $this.offset(); offset = $this.offset();
if (direction == 'auto') { if (direction == 'auto') {
if (($(window).width() - $this.outerWidth(true)) / 2 > offset.left) { if (($(window).width() - $this.outerWidth(true)) / 2 > offset.left) {
direction = 'right'; direction = 'right';
} } else {
else {
direction = 'left'; direction = 'left';
} }
} }
@ -1272,12 +1292,7 @@ phpbb.toggleDropdown = function() {
var height = $(window).height(), var height = $(window).height(),
top = offset.top - $(window).scrollTop(); top = offset.top - $(window).scrollTop();
if (top < height * 0.7) { verticalDirection = (top < height * 0.7) ? 'down' : 'up';
verticalDirection = 'down';
}
else {
verticalDirection = 'up';
}
} }
parent.toggleClass(options.upClass, verticalDirection == 'up').toggleClass(options.downClass, verticalDirection == 'down'); parent.toggleClass(options.upClass, verticalDirection == 'up').toggleClass(options.downClass, verticalDirection == 'down');
} }
@ -1304,8 +1319,7 @@ phpbb.toggleDropdown = function() {
if (offset < 2) { if (offset < 2) {
$this.css('left', (2 - offset) + 'px'); $this.css('left', (2 - offset) + 'px');
} } else if ((offset + width + 2) > windowWidth) {
else if ((offset + width + 2) > windowWidth) {
$this.css('margin-left', (windowWidth - offset - width - 2) + 'px'); $this.css('margin-left', (windowWidth - offset - width - 2) + 'px');
} }
@ -1342,8 +1356,7 @@ phpbb.toggleDropdown = function() {
var e = arguments[0]; var e = arguments[0];
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
} } catch (error) { }
catch (error) { }
} }
return false; return false;
}; };
@ -1354,7 +1367,7 @@ phpbb.toggleDropdown = function() {
phpbb.toggleSubmenu = function(e) { phpbb.toggleSubmenu = function(e) {
$(this).siblings('.dropdown-submenu').toggle(); $(this).siblings('.dropdown-submenu').toggle();
e.preventDefault(); e.preventDefault();
} };
/** /**
* Register dropdown menu * Register dropdown menu
@ -1364,8 +1377,7 @@ phpbb.toggleSubmenu = function(e) {
* @param {jQuery} dropdown Dropdown menu. * @param {jQuery} dropdown Dropdown menu.
* @param {Object} options List of options. Optional. * @param {Object} options List of options. Optional.
*/ */
phpbb.registerDropdown = function(toggle, dropdown, options) phpbb.registerDropdown = function(toggle, dropdown, options) {
{
var ops = { var ops = {
parent: toggle.parent(), // Parent item to add classes to parent: toggle.parent(), // Parent item to add classes to
direction: 'auto', // Direction of dropdown menu. Possible values: auto, left, right direction: 'auto', // Direction of dropdown menu. Possible values: auto, left, right
@ -1411,8 +1423,8 @@ phpbb.colorPalette = function(dir, width, height) {
numberList[3] = 'BF'; numberList[3] = 'BF';
numberList[4] = 'FF'; numberList[4] = 'FF';
var table_class = (dir == 'h') ? 'horizontal-palette' : 'vertical-palette'; var tableClass = (dir == 'h') ? 'horizontal-palette' : 'vertical-palette';
html += '<table class="not-responsive colour-palette ' + table_class + '" style="width: auto;">'; html += '<table class="not-responsive colour-palette ' + tableClass + '" style="width: auto;">';
for (r = 0; r < 5; r++) { for (r = 0; r < 5; r++) {
if (dir == 'h') { if (dir == 'h') {
@ -1442,7 +1454,7 @@ phpbb.colorPalette = function(dir, width, height) {
} }
html += '</table>'; html += '</table>';
return html; return html;
} };
/** /**
* Register a color palette. * Register a color palette.
@ -1492,12 +1504,14 @@ phpbb.toggleDisplay = function(id, action, type) {
type = 'block'; type = 'block';
} }
var display = $('#' + id).css('display'); var $el = $('#' + id);
var display = $el.css('display');
if (!action) { if (!action) {
action = (display === '' || display === type) ? -1 : 1; action = (display === '' || display === type) ? -1 : 1;
} }
$('#' + id).css('display', ((action === 1) ? type : 'none')); $el.css('display', ((action === 1) ? type : 'none'));
} };
/** /**
* Toggle additional settings based on the selected * Toggle additional settings based on the selected
@ -1508,9 +1522,9 @@ phpbb.toggleDisplay = function(id, action, type) {
*/ */
phpbb.toggleSelectSettings = function(el) { phpbb.toggleSelectSettings = function(el) {
el.children().each(function() { el.children().each(function() {
var option = $(this), var $this = $(this),
setting = $(option.data('toggle-setting')); $setting = $($this.data('toggle-setting'));
setting.toggle(option.is(':selected')); $setting.toggle($this.is(':selected'));
}); });
}; };
@ -1536,49 +1550,61 @@ phpbb.getFunctionByName = function (functionName) {
* Register page dropdowns. * Register page dropdowns.
*/ */
phpbb.registerPageDropdowns = function() { phpbb.registerPageDropdowns = function() {
$('body').find('.dropdown-container').each(function() { var $body = $('body');
$body.find('.dropdown-container').each(function() {
var $this = $(this), var $this = $(this),
trigger = $this.find('.dropdown-trigger:first'), $trigger = $this.find('.dropdown-trigger:first'),
contents = $this.find('.dropdown'), $contents = $this.find('.dropdown'),
options = { options = {
direction: 'auto', direction: 'auto',
verticalDirection: 'auto' verticalDirection: 'auto'
}, },
data; data;
if (!trigger.length) { if (!$trigger.length) {
data = $this.attr('data-dropdown-trigger'); data = $this.attr('data-dropdown-trigger');
trigger = data ? $this.children(data) : $this.children('a:first'); $trigger = data ? $this.children(data) : $this.children('a:first');
} }
if (!contents.length) { if (!$contents.length) {
data = $this.attr('data-dropdown-contents'); data = $this.attr('data-dropdown-contents');
contents = data ? $this.children(data) : $this.children('div:first'); $contents = data ? $this.children(data) : $this.children('div:first');
} }
if (!trigger.length || !contents.length) return; if (!$trigger.length || !$contents.length) {
return;
}
if ($this.hasClass('dropdown-up')) options.verticalDirection = 'up'; if ($this.hasClass('dropdown-up')) {
if ($this.hasClass('dropdown-down')) options.verticalDirection = 'down'; options.verticalDirection = 'up';
if ($this.hasClass('dropdown-left')) options.direction = 'left'; }
if ($this.hasClass('dropdown-right')) options.direction = 'right'; if ($this.hasClass('dropdown-down')) {
options.verticalDirection = 'down';
}
if ($this.hasClass('dropdown-left')) {
options.direction = 'left';
}
if ($this.hasClass('dropdown-right')) {
options.direction = 'right';
}
phpbb.registerDropdown(trigger, contents, options); phpbb.registerDropdown($trigger, $contents, options);
}); });
// Hide active dropdowns when click event happens outside // Hide active dropdowns when click event happens outside
$('body').click(function(e) { $body.click(function(e) {
var parents = $(e.target).parents(); var $parents = $(e.target).parents();
if (!parents.is(phpbb.dropdownVisibleContainers)) { if (!$parents.is(phpbb.dropdownVisibleContainers)) {
$(phpbb.dropdownHandles).each(phpbb.toggleDropdown); $(phpbb.dropdownHandles).each(phpbb.toggleDropdown);
} }
}); });
} };
/** /**
* Apply code editor to all textarea elements with data-bbcode attribute * Apply code editor to all textarea elements with data-bbcode attribute
*/ */
$(document).ready(function() { $(function() {
$('textarea[data-bbcode]').each(function() { $('textarea[data-bbcode]').each(function() {
phpbb.applyCodeEditor(this); phpbb.applyCodeEditor(this);
}); });
@ -1595,12 +1621,12 @@ $(document).ready(function() {
// Hide settings that are not selected via select element. // Hide settings that are not selected via select element.
$('select[data-togglable-settings]').each(function() { $('select[data-togglable-settings]').each(function() {
var select = $(this); var $this = $(this);
select.change(function() { $this.change(function() {
phpbb.toggleSelectSettings(select); phpbb.toggleSelectSettings($this);
}); });
phpbb.toggleSelectSettings(select); phpbb.toggleSelectSettings($this);
}); });
}); });

View file

@ -1,6 +1,8 @@
/* global phpbb */
(function($) { // Avoid conflicts with other libraries (function($) { // Avoid conflicts with other libraries
"use strict"; 'use strict';
// This callback will mark all forum icons read // This callback will mark all forum icons read
phpbb.addAjaxCallback('mark_forums_read', function(res) { phpbb.addAjaxCallback('mark_forums_read', function(res) {
@ -40,10 +42,10 @@ phpbb.addAjaxCallback('mark_forums_read', function(res) {
/** /**
* This callback will mark all topic icons read * This callback will mark all topic icons read
* *
* @param update_topic_links bool Wether "Mark topics read" links should be * @param update_topic_links bool Whether "Mark topics read" links should be
* updated. Defaults to true. * updated. Defaults to true.
*/ */
phpbb.addAjaxCallback('mark_topics_read', function(res, update_topic_links) { phpbb.addAjaxCallback('mark_topics_read', function(res, updateTopicLinks) {
var readTitle = res.NO_UNREAD_POSTS; var readTitle = res.NO_UNREAD_POSTS;
var unreadTitle = res.UNREAD_POSTS; var unreadTitle = res.UNREAD_POSTS;
var iconsArray = { var iconsArray = {
@ -53,12 +55,12 @@ phpbb.addAjaxCallback('mark_topics_read', function(res, update_topic_links) {
'topic_unread': 'topic_read' 'topic_unread': 'topic_read'
}; };
var iconsState = ['', '_hot', '_hot_mine', '_locked', '_locked_mine', '_mine']; var iconsState = ['', '_hot', '_hot_mine', '_locked', '_locked_mine', '_mine'];
var unreadClassSelectors = ''; var unreadClassSelectors;
var classMap = {}; var classMap = {};
var classNames = []; var classNames = [];
if (typeof update_topic_links === 'undefined') { if (typeof updateTopicLinks === 'undefined') {
update_topic_links = true; updateTopicLinks = true;
} }
$.each(iconsArray, function(unreadClass, readClass) { $.each(iconsArray, function(unreadClass, readClass) {
@ -88,7 +90,7 @@ phpbb.addAjaxCallback('mark_topics_read', function(res, update_topic_links) {
$('a').has('span.icon_topic_newest').remove(); $('a').has('span.icon_topic_newest').remove();
// Update mark topics read links // Update mark topics read links
if (update_topic_links) { if (updateTopicLinks) {
$('[data-ajax="mark_topics_read"]').attr('href', res.U_MARK_TOPICS); $('[data-ajax="mark_topics_read"]').attr('href', res.U_MARK_TOPICS);
} }
@ -114,22 +116,22 @@ phpbb.addAjaxCallback('notification.mark_read', function(res) {
/** /**
* Mark notification popup rows as read. * Mark notification popup rows as read.
* *
* @param {jQuery} el jQuery object(s) to mark read. * @param {jQuery} $el jQuery object(s) to mark read.
* @param {int} unreadCount The new unread notifications count. * @param {int} unreadCount The new unread notifications count.
*/ */
phpbb.markNotifications = function(el, unreadCount) { phpbb.markNotifications = function($el, unreadCount) {
// Remove the unread status. // Remove the unread status.
el.removeClass('bg2'); $el.removeClass('bg2');
el.find('a.mark_read').remove(); $el.find('a.mark_read').remove();
// Update the notification link to the real URL. // Update the notification link to the real URL.
el.each(function() { $el.each(function() {
var link = $(this).find('a'); var link = $(this).find('a');
link.attr('href', link.attr('data-real-url')); link.attr('href', link.attr('data-real-url'));
}); });
// Update the unread count. // Update the unread count.
$('#notification_list_button strong').html(unreadCount); $('strong', '#notification_list_button').html(unreadCount);
// Remove the Mark all read link if there are no unread notifications. // Remove the Mark all read link if there are no unread notifications.
if (!unreadCount) { if (!unreadCount) {
$('#mark_all_notifications').remove(); $('#mark_all_notifications').remove();
@ -138,12 +140,12 @@ phpbb.markNotifications = function(el, unreadCount) {
// This callback finds the post from the delete link, and removes it. // This callback finds the post from the delete link, and removes it.
phpbb.addAjaxCallback('post_delete', function() { phpbb.addAjaxCallback('post_delete', function() {
var el = $(this), var $this = $(this),
postId; postId;
if (el.attr('data-refresh') === undefined) { if ($this.attr('data-refresh') === undefined) {
postId = el[0].href.split('&p=')[1]; postId = $this[0].href.split('&p=')[1];
var post = el.parents('#p' + postId).css('pointer-events', 'none'); var post = $this.parents('#p' + postId).css('pointer-events', 'none');
if (post.hasClass('bg1') || post.hasClass('bg2')) { if (post.hasClass('bg1') || post.hasClass('bg2')) {
var posts1 = post.nextAll('.bg1'); var posts1 = post.nextAll('.bg1');
post.nextAll('.bg2').removeClass('bg2').addClass('bg1'); post.nextAll('.bg2').removeClass('bg2').addClass('bg1');
@ -194,18 +196,18 @@ phpbb.addAjaxCallback('vote_poll', function(res) {
if (typeof res.success !== 'undefined') { if (typeof res.success !== 'undefined') {
var poll = $('.topic_poll'); var poll = $('.topic_poll');
var panel = poll.find('.panel'); var panel = poll.find('.panel');
var results_visible = poll.find('dl:first-child .resultbar').is(':visible'); var resultsVisible = poll.find('dl:first-child .resultbar').is(':visible');
var most_votes = 0; var mostVotes = 0;
// Set min-height to prevent the page from jumping when the content changes // Set min-height to prevent the page from jumping when the content changes
var update_panel_height = function (height) { var updatePanelHeight = function (height) {
var height = (typeof height === 'undefined') ? panel.find('.inner').outerHeight() : height; var height = (typeof height === 'undefined') ? panel.find('.inner').outerHeight() : height;
panel.css('min-height', height); panel.css('min-height', height);
}; };
update_panel_height(); updatePanelHeight();
// Remove the View results link // Remove the View results link
if (!results_visible) { if (!resultsVisible) {
poll.find('.poll_view_results').hide(500); poll.find('.poll_view_results').hide(500);
} }
@ -221,8 +223,8 @@ phpbb.addAjaxCallback('vote_poll', function(res) {
// Get the votes count of the highest poll option // Get the votes count of the highest poll option
poll.find('[data-poll-option-id]').each(function() { poll.find('[data-poll-option-id]').each(function() {
var option = $(this); var option = $(this);
var option_id = option.attr('data-poll-option-id'); var optionId = option.attr('data-poll-option-id');
most_votes = (res.vote_counts[option_id] >= most_votes) ? res.vote_counts[option_id] : most_votes; mostVotes = (res.vote_counts[optionId] >= mostVotes) ? res.vote_counts[optionId] : mostVotes;
}); });
// Update the total votes count // Update the total votes count
@ -230,28 +232,30 @@ phpbb.addAjaxCallback('vote_poll', function(res) {
// Update each option // Update each option
poll.find('[data-poll-option-id]').each(function() { poll.find('[data-poll-option-id]').each(function() {
var option = $(this); var $this = $(this);
var option_id = option.attr('data-poll-option-id'); var optionId = $this.attr('data-poll-option-id');
var voted = (typeof res.user_votes[option_id] !== 'undefined') ? true : false; var voted = (typeof res.user_votes[optionId] !== 'undefined');
var most_voted = (res.vote_counts[option_id] == most_votes) ? true : false; var mostVoted = (res.vote_counts[optionId] == mostVotes);
var percent = (!res.total_votes) ? 0 : Math.round((res.vote_counts[option_id] / res.total_votes) * 100); var percent = (!res.total_votes) ? 0 : Math.round((res.vote_counts[optionId] / res.total_votes) * 100);
var percent_rel = (most_votes == 0) ? 0 : Math.round((res.vote_counts[option_id] / most_votes) * 100); var percentRel = (mostVotes === 0) ? 0 : Math.round((res.vote_counts[optionId] / mostVotes) * 100);
option.toggleClass('voted', voted); $this.toggleClass('voted', voted);
option.toggleClass('most-votes', most_voted); $this.toggleClass('most-votes', mostVoted);
// Update the bars // Update the bars
var bar = option.find('.resultbar div'); var bar = $this.find('.resultbar div');
var bar_time_lapse = (res.can_vote) ? 500 : 1500; var barTimeLapse = (res.can_vote) ? 500 : 1500;
var new_bar_class = (percent == 100) ? 'pollbar5' : 'pollbar' + (Math.floor(percent / 20) + 1); var newBarClass = (percent == 100) ? 'pollbar5' : 'pollbar' + (Math.floor(percent / 20) + 1);
setTimeout(function () { setTimeout(function () {
bar.animate({width: percent_rel + '%'}, 500).removeClass('pollbar1 pollbar2 pollbar3 pollbar4 pollbar5').addClass(new_bar_class); bar.animate({width: percentRel + '%'}, 500)
bar.html(res.vote_counts[option_id]); .removeClass('pollbar1 pollbar2 pollbar3 pollbar4 pollbar5')
.addClass(newBarClass)
.html(res.vote_counts[optionId]);
var percent_txt = (!percent) ? res.NO_VOTES : percent + '%'; var percentText = percent ? percent + '%' : res.NO_VOTES;
option.find('.poll_option_percent').html(percent_txt); $this.find('.poll_option_percent').html(percentText);
}, bar_time_lapse); }, barTimeLapse);
}); });
if (!res.can_vote) { if (!res.can_vote) {
@ -259,30 +263,31 @@ phpbb.addAjaxCallback('vote_poll', function(res) {
} }
// Display "Your vote has been cast." message. Disappears after 5 seconds. // Display "Your vote has been cast." message. Disappears after 5 seconds.
var confirmation_delay = (res.can_vote) ? 300 : 900; var confirmationDelay = (res.can_vote) ? 300 : 900;
poll.find('.vote-submitted').delay(confirmation_delay).slideDown(200, function() { poll.find('.vote-submitted').delay(confirmationDelay).slideDown(200, function() {
if (results_visible) { if (resultsVisible) {
update_panel_height(); updatePanelHeight();
} }
$(this).delay(5000).fadeOut(500, function() { $(this).delay(5000).fadeOut(500, function() {
resize_panel(300); resizePanel(300);
}); });
}); });
// Remove the gap resulting from removing options // Remove the gap resulting from removing options
setTimeout(function() { setTimeout(function() {
resize_panel(500); resizePanel(500);
}, 1500); }, 1500);
var resize_panel = function (time) { var resizePanel = function (time) {
var panel_height = panel.height(); var panelHeight = panel.height();
var inner_height = panel.find('.inner').outerHeight(); var innerHeight = panel.find('.inner').outerHeight();
if (panel_height != inner_height) { if (panelHeight != innerHeight) {
panel.css({'min-height': '', 'height': panel_height}).animate({height: inner_height}, time, function () { panel.css({'min-height': '', 'height': panelHeight})
panel.css({'min-height': inner_height, 'height': ''}); .animate({height: innerHeight}, time, function () {
}); panel.css({'min-height': innerHeight, 'height': ''});
});
} }
}; };
} }
@ -295,20 +300,19 @@ $('.poll_view_results a').click(function(e) {
// Do not follow the link // Do not follow the link
e.preventDefault(); e.preventDefault();
var poll = $(this).parents('.topic_poll'); var $poll = $(this).parents('.topic_poll');
poll.find('.resultbar, .poll_option_percent, .poll_total_votes').show(500); $poll.find('.resultbar, .poll_option_percent, .poll_total_votes').show(500);
poll.find('.poll_view_results').hide(500); $poll.find('.poll_view_results').hide(500);
}); });
$('[data-ajax]').each(function() { $('[data-ajax]').each(function() {
var $this = $(this), var $this = $(this);
ajax = $this.attr('data-ajax'), var ajax = $this.attr('data-ajax');
filter = $this.attr('data-filter'), var filter = $this.attr('data-filter');
fn;
if (ajax !== 'false') { if (ajax !== 'false') {
fn = (ajax !== 'true') ? ajax : null; var fn = (ajax !== 'true') ? ajax : null;
filter = (filter !== undefined) ? phpbb.getFunctionByName(filter) : null; filter = (filter !== undefined) ? phpbb.getFunctionByName(filter) : null;
phpbb.ajaxify({ phpbb.ajaxify({
@ -339,10 +343,10 @@ $('.display_post').click(function(e) {
// Do not follow the link // Do not follow the link
e.preventDefault(); e.preventDefault();
var post_id = $(this).attr('data-post-id'); var postId = $(this).attr('data-post-id');
$('#post_content' + post_id).show(); $('#post_content' + postId).show();
$('#profile' + post_id).show(); $('#profile' + postId).show();
$('#post_hidden' + post_id).hide(); $('#post_hidden' + postId).hide();
}); });
$('#delete_permanent').click(function () { $('#delete_permanent').click(function () {
@ -361,10 +365,13 @@ $('#delete_permanent').click(function () {
* appropriately changed based on the status of the search panel. * appropriately changed based on the status of the search panel.
*/ */
$('#member_search').click(function () { $('#member_search').click(function () {
$('#memberlist_search').slideToggle('fast'); var $memberlistSearch = $('#memberlist_search');
$memberlistSearch.slideToggle('fast');
phpbb.ajaxCallbacks.alt_text.call(this); phpbb.ajaxCallbacks.alt_text.call(this);
// Focus on the username textbox if it's available and displayed // Focus on the username textbox if it's available and displayed
if ($('#memberlist_search').is(':visible')) { if ($memberlistSearch.is(':visible')) {
$('#username').focus(); $('#username').focus();
} }
return false; return false;
@ -373,7 +380,7 @@ $('#member_search').click(function () {
/** /**
* Automatically resize textarea * Automatically resize textarea
*/ */
$(document).ready(function() { $(function() {
phpbb.resizeTextArea($('textarea:not(#message-box textarea, .no-auto-resize)'), {minHeight: 75, maxHeight: 250}); phpbb.resizeTextArea($('textarea:not(#message-box textarea, .no-auto-resize)'), {minHeight: 75, maxHeight: 250});
phpbb.resizeTextArea($('#message-box textarea')); phpbb.resizeTextArea($('#message-box textarea'));
}); });

View file

@ -1,6 +1,8 @@
/* global phpbb */
(function($) { // Avoid conflicts with other libraries (function($) { // Avoid conflicts with other libraries
"use strict"; 'use strict';
$('#tz_date').change(function() { $('#tz_date').change(function() {
phpbb.timezoneSwitchDate(false); phpbb.timezoneSwitchDate(false);
@ -10,12 +12,9 @@ $('#tz_select_date_suggest').click(function(){
phpbb.timezonePreselectSelect(true); phpbb.timezonePreselectSelect(true);
}); });
$(document).ready( $(function () {
phpbb.timezoneEnableDateSelection phpbb.timezoneEnableDateSelection();
); phpbb.timezonePreselectSelect($('#tz_select_date_suggest').attr('timezone-preselect') === 'true');
})
$(document).ready(
phpbb.timezonePreselectSelect($('#tz_select_date_suggest').attr('timezone-preselect') === 'true')
);
})(jQuery); // Avoid conflicts with other libraries })(jQuery); // Avoid conflicts with other libraries