/*
 * show-op
 * https://github.com/savetheinternet/Tinyboard/blob/master/js/show-op.js
 *
 * Adds "(OP)" to >>X links when the OP is quoted.
 *
 * Released under the MIT license
 * Copyright (c) 2012 Michael Save <savetheinternet@tinyboard.org>
 * Copyright (c) 2014 Marcin Ɓabanowski <marcin@6irc.net>
 *
 * Usage:
 *   $config['additional_javascript'][] = 'js/jquery.min.js';
 *   $config['additional_javascript'][] = 'js/show-op.js';
 */

$(document).ready(function() {
	let threadPageOp;
	if (active_page === "thread") {
		threadPageOp = parseInt($('div.post.op a.post_no:eq(1)').text());
	}

	let showOPLinks = function() {
		// Use the cached op if we're in a thread, otherwise fetch it.
		let localOp = threadPageOp ? threadPageOp : parseInt($(this).parent().parent().parent().find('div.post.op a.post_no:eq(1)').text());

		let postID = $(this).text().match(/^>>(\d+)$/);

		if (postID) {
			postID = parseInt(postID[1]);
		} else {
			return;
		}

		if (postID === localOp) {
			$(this).after(' <small>(OP)</small>');
		}
	};

	$('div.post.reply > div.body a:not([rel="nofollow"])').each(showOPLinks);

	// allow to work with auto-reload.js, etc.
	$(document).on('new_post', function(e, post) {
		if ($(post).is('div.post.reply > div.body a:not([rel="nofollow"])')) {
			$(post).each(showOPLinks);
		} else {
			$(post).find('div.post.reply > div.body a:not([rel="nofollow"])').each(showOPLinks);
		}
	});
});