You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

463 lines
12 KiB
JavaScript

var socket,
config,
11 years ago
app = {
'username': null,
'uid': null
};
(function () {
var showWelcomeMessage = false;
11 years ago
app.loadConfig = function() {
$.ajax({
url: RELATIVE_PATH + '/api/config',
success: function (data) {
config = data;
if(socket) {
socket.disconnect();
setTimeout(function() {
socket.socket.connect();
}, 200);
} else {
var max_reconnection_attemps = 5;
var reconnection_delay = 200;
socket = io.connect(RELATIVE_PATH, {
'max reconnection attempts': max_reconnection_attemps,
'reconnection delay': reconnection_delay
});
var reconnecting = false,
reconnectEl, reconnectTimer;
socket.on('event:connect', function (data) {
app.username = data.username;
11 years ago
app.uid = data.uid;
11 years ago
app.showLoginMessage();
socket.emit('api:updateHeader', {
fields: ['username', 'picture', 'userslug']
});
});
12 years ago
socket.on('event:alert', function (data) {
app.alert(data);
});
socket.on('connect', function (data) {
if (reconnecting) {
reconnectEl.html('<i class="icon-ok"></i> Connected!');
reconnecting = false;
setTimeout(function() {
reconnectEl.removeClass('active');
}, 3000);
}
socket.emit('api:updateHeader', {
fields: ['username', 'picture', 'userslug']
});
});
socket.on('event:disconnect', function() {
socket.socket.connect();
});
socket.on('reconnecting', function (data, attempt) {
if(attempt == max_reconnection_attemps) {
socket.socket.reconnectionAttempts = 0;
socket.socket.reconnectionDelay = reconnection_delay;
return;
}
if (!reconnectEl) reconnectEl = $('#reconnect');
reconnecting = true;
reconnectEl.addClass('active');
reconnectEl.html('<i class="icon-spinner icon-spin"></i> Reconnecting...');
});
socket.on('api:user.get_online_users', function (users) {
jQuery('a.username-field').each(function () {
if (this.processed === true)
return;
var el = jQuery(this),
uid = el.parents('li').attr('data-uid');
if (uid && jQuery.inArray(uid, users) !== -1) {
el.find('i').remove();
el.prepend('<i class="icon-circle"></i>');
} else {
el.find('i').remove();
el.prepend('<i class="icon-circle-blank"></i>');
}
el.processed = true;
});
jQuery('button .username-field').each(function () {
//DRY FAIL
if (this.processed === true)
return;
var el = jQuery(this),
uid = el.parents('li').attr('data-uid');
if (uid && jQuery.inArray(uid, users) !== -1) {
el.parent().addClass('btn-success');
} else {
el.parent().addClass('btn-danger');
}
el.processed = true;
});
});
11 years ago
socket.on('event:banned', function() {
app.alert({
title: 'Banned',
message: 'You are banned you will be logged out!',
type: 'warning',
timeout: 1000
});
setTimeout(app.logout, 1000);
});
app.enter_room('global');
}
},
async: false
});
}
11 years ago
app.logout = function() {
$.post(RELATIVE_PATH + '/logout', {
_csrf: $('#csrf_token').val()
}, function() {
window.location = RELATIVE_PATH + '/';
});
}
// takes a string like 1000 and returns 1,000
app.addCommas = function (text) {
12 years ago
return text.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
}
12 years ago
// Willingly stolen from: http://phpjs.org/functions/strip_tags/
app.strip_tags = function (input, allowed) {
12 years ago
allowed = (((allowed || "") + "").toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
12 years ago
var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
12 years ago
commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
return input.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) {
12 years ago
return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
});
}
// use unique alert_id to have multiple alerts visible at a time, use the same alert_id to fade out the current instance
// type : error, success, info, warning/notify
// title = bolded title text
// message = alert message content
// timeout default = permanent
// location : alert_window (default) or content
app.alert = function (params) {
var alert_id = 'alert_button_' + ((params.alert_id) ? params.alert_id : new Date().getTime());
12 years ago
var alert = $('#' + alert_id);
var title = params.title || '';
12 years ago
function startTimeout(div, timeout) {
var timeoutId = setTimeout(function () {
$(div).fadeOut(1000, function () {
$(this).remove();
12 years ago
});
}, timeout);
12 years ago
$(div).attr('timeoutId', timeoutId);
}
12 years ago
if (alert.length > 0) {
alert.find('strong').html(title);
alert.find('p').html(params.message);
alert.attr('class', "alert toaster-alert " + "alert-" + params.type);
12 years ago
clearTimeout(alert.attr('timeoutId'));
startTimeout(alert, params.timeout);
12 years ago
} else {
var div = document.createElement('div'),
button = document.createElement('button'),
strong = document.createElement('strong'),
p = document.createElement('p');
p.innerHTML = params.message;
strong.innerHTML = title;
div.className = "alert toaster-alert " + "alert-" + params.type;
div.setAttribute('id', alert_id);
div.appendChild(button);
div.appendChild(strong);
div.appendChild(p);
button.className = 'close';
button.innerHTML = '&times;';
button.onclick = function (ev) {
div.parentNode.removeChild(div);
}
if (params.location == null)
params.location = 'alert_window';
12 years ago
jQuery('#' + params.location).prepend(jQuery(div).fadeIn('100'));
if (params.timeout) {
12 years ago
startTimeout(div, params.timeout);
}
if (params.clickfn) {
div.onclick = function () {
params.clickfn();
jQuery(div).fadeOut(500, function () {
this.remove();
});
}
}
}
}
app.alertSuccess = function (message, timeout) {
12 years ago
if (!timeout)
timeout = 2000;
app.alert({
title: 'Success',
message: message,
type: 'success',
timeout: timeout
});
}
app.alertError = function (message, timeout) {
12 years ago
if (!timeout)
timeout = 2000;
app.alert({
title: 'Error',
message: message,
type: 'danger',
timeout: timeout
});
}
12 years ago
app.current_room = null;
app.enter_room = function (room) {
12 years ago
if (socket) {
if (app.current_room === room)
return;
socket.emit('event:enter_room', {
'enter': room,
'leave': app.current_room
});
app.current_room = room;
}
};
app.populate_online_users = function () {
var uids = [];
jQuery('.post-row').each(function () {
uids.push(this.getAttribute('data-uid'));
});
socket.emit('api:user.get_online_users', uids);
}
app.process_page = function () {
app.populate_online_users();
12 years ago
var url = window.location.href,
parts = url.split('/'),
12 years ago
active = parts[parts.length - 1];
12 years ago
jQuery('#main-nav li').removeClass('active');
12 years ago
if (active) {
jQuery('#main-nav li a').each(function () {
12 years ago
var href = this.getAttribute('href');
12 years ago
if (active == "sort-posts" || active == "sort-reputation" || active == "search" || active == "latest" || active == "online")
12 years ago
active = 'users';
12 years ago
if (href && href.match(active)) {
12 years ago
jQuery(this.parentNode).addClass('active');
return false;
}
});
}
12 years ago
$('span.timeago').timeago();
$('.post-content img').addClass('img-responsive');
12 years ago
setTimeout(function () {
window.scrollTo(0, 1); // rehide address bar on mobile after page load completes.
}, 100);
}
app.showLoginMessage = function () {
function showAlert() {
12 years ago
app.alert({
type: 'success',
title: 'Welcome Back ' + app.username + '!',
message: 'You have successfully logged in!',
timeout: 5000
});
}
12 years ago
if (showWelcomeMessage) {
showWelcomeMessage = false;
12 years ago
if (document.readyState !== 'complete') {
$(document).ready(showAlert);
} else {
showAlert();
}
}
12 years ago
}
app.addCommasToNumbers = function () {
$('.formatted-number').each(function (index, element) {
12 years ago
$(element).html(app.addCommas($(element).html()));
});
}
app.openChat = function (username, touid) {
require(['chat'], function (chat) {
12 years ago
var chatModal;
12 years ago
if (!chat.modalExists(touid)) {
12 years ago
chatModal = chat.createModal(username, touid);
} else {
chatModal = chat.getModal(touid);
}
chat.load(chatModal.attr('UUID'));
11 years ago
chat.center(chatModal);
12 years ago
});
}
app.createNewPosts = function (data) {
11 years ago
if (data.posts[0].uid !== app.uid) {
data.posts[0].display_moderator_tools = 'none';
}
var html = templates.prepare(templates['topic'].blocks['posts']).parse(data);
translator.translate(html, function(translatedHTML) {
var uniqueid = new Date().getTime(),
tempContainer = jQuery('<div id="' + uniqueid + '"></div>')
.appendTo("#post-container")
.hide()
.append(translatedHTML)
.fadeIn('slow');
for (var x = 0, numPosts = data.posts.length; x < numPosts; x++) {
socket.emit('api:post.privileges', data.posts[x].pid);
}
12 years ago
tempContainer.replaceWith(tempContainer.contents());
infiniteLoaderActive = false;
12 years ago
app.populate_online_users();
app.addCommasToNumbers();
$('span.timeago').timeago();
$('.post-content img').addClass('img-responsive');
});
12 years ago
}
app.infiniteLoaderActive = false;
app.loadMorePosts = function (tid, callback) {
12 years ago
if (app.infiniteLoaderActive)
12 years ago
return;
12 years ago
app.infiniteLoaderActive = true;
12 years ago
if ($('#loading-indicator').attr('done') === '0')
$('#loading-indicator').removeClass('hide');
socket.emit('api:topic.loadMore', {
tid: tid,
after: document.querySelectorAll('#post-container li[data-pid]').length
}, function (data) {
12 years ago
app.infiniteLoaderActive = false;
12 years ago
if (data.posts.length) {
$('#loading-indicator').attr('done', '0');
12 years ago
app.createNewPosts(data);
} else {
$('#loading-indicator').attr('done', '1');
12 years ago
}
$('#loading-indicator').addClass('hide');
12 years ago
if (callback)
callback(data.posts);
12 years ago
});
}
app.scrollToTop = function () {
$('body,html').animate({
scrollTop: 0
});
};
app.scrollToBottom = function () {
$('body,html').animate({
scrollTop: $('html').height() - 100
});
}
app.scrollToPost = function (pid) {
12 years ago
if (!pid)
12 years ago
return;
12 years ago
var container = $(document.body),
scrollTo = $('#post_anchor_' + pid),
tid = $('#post-container').attr('data-tid');
12 years ago
function animateScroll() {
$('body,html').animate({
scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - $('#header-menu').height()
}, 400);
//$('body,html').scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop() - $('#header-menu').height());
}
12 years ago
if (!scrollTo.length && tid) {
12 years ago
var intervalID = setInterval(function () {
app.loadMorePosts(tid, function (posts) {
scrollTo = $('#post_anchor_' + pid);
12 years ago
12 years ago
if (tid && scrollTo.length) {
12 years ago
animateScroll();
}
12 years ago
12 years ago
if (!posts.length || scrollTo.length)
clearInterval(intervalID);
});
}, 100);
12 years ago
12 years ago
} else if (tid) {
animateScroll();
}
12 years ago
}
jQuery('document').ready(function () {
$('#search-form').on('submit', function () {
var input = $(this).find('input');
12 years ago
ajaxify.go("search/" + input.val(), null, "search");
input.val('');
return false;
12 years ago
});
});
showWelcomeMessage = location.href.indexOf('loggedin') !== -1;
app.loadConfig();
12 years ago
}());