// ==UserScript==
// @name           cn_ubb_enhance
// @namespace      http://shutterfreak.net/xtra/greasemonkey/ubb_enhance
// @description    Enhance CN forums by adding short links to individual posts in flat mode. It works in the live forums and in the forum archives.
// @author         Olivier Biot
// @version        0.3.5
// @include        http://www.cloudynights.com/ubbthreads/showflat.php*
// @include        http://www.cloudynights.com/ubbthreads/showthreaded.php*
// @include        http://www.cloudynights.com/ubbarchive/showflat.php*
// @include        http://www.cloudynights.com/ubbarchive/showthreaded.php*
// ==/UserScript==

/* History
 * 0.3.5 - Added links to the NGC/IC project
 * 0.3.3 - Added post links to flat mode
 * 0.2   - Fix some errors
 * 0.1   - First version: provide links to individual posts in threaded mode when in flat mode
 */
function cn_forum_base_url()
{
	if ( document.location.href.search( 'http://www.cloudynights.com/ubbarchive' ) == 0 ) {
		return 'http://www.cloudynights.com/ubbarchive';
	} else if ( document.location.href.search( 'http://www.cloudynights.com/ubbthreads' ) == 0 ) {
		return 'http://www.cloudynights.com/ubbthreads';
	}
	return null;
}

function cn_forum_flat_mode()
{
	if ( document.location.href.search( 'http://www.cloudynights.com/ubbarchive/showflat.php' ) == 0 ) {
		return true;
	} else if ( document.location.href.search( 'http://www.cloudynights.com/ubbthreads/showflat.php' ) == 0 ) {
		return true;
	}
	return false;
}

function isNumeric(input)
{
   return (input - 0) == input && input.length > 0;
}

function check_link_type(link_type)
{
	if (link_type == 'threaded') return 'threaded';
	return 'flat';
}

// Type = 'threaded' or 'flat' (default)
function ubbPostLink(post_id, id_prefix, link_type)
{
	link_type = check_link_type(link_type);
	var link = document.createElement('a');
	link.href = cn_forum_base_url() + '/show' + link_type + '.php/Number/' + post_id;
	if (link_type = 'flat') {
		link.href += '#Post' + post_id;
	}
	link.setAttribute('id', id_prefix + '-' + link_type + '-' + post_id);
	return link;
}

// Add a browse link to the UBB Context of a given post
// Link Type = 'threaded' or 'flat' (default)
function addUbbContextLink(post_id, link_type)
{
	link_type = check_link_type(link_type);
	// Create a link element that will contain the short,
	// quick link to the post in flat mode:
	var link = ubbPostLink(post_id, 'post_link', link_type);
	link.setAttribute('target', '_blank');
	// Add an image icon for the link:
	var img = document.createElement('img');
	img.setAttribute('src','http://www.cloudynights.com/ubbthreads/images/' + link_type + '.gif');
	img.setAttribute('border', "0");
	// First add the icon, then the text:
	link.appendChild(img);
	link.appendChild(document.createTextNode( '('+link_type+')' ) );
	return link;
}

// Type = 'threaded' or 'flat' (default)
function UbbLinkPopup(post_id, title, link_type)
{
	link_type = check_link_type(link_type);
	var link = ubbPostLink(post_id, 'post_link_popup', link_type);
    	node = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' + '<html><head>' + '<title>Create link to post #' + post_id +': ' + title + ' (' + link_type + ' mode)</title>' + '<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />' + '<link rel="stylesheet" href="/ubbthreads/stylesheets/template.css" type="text/css" />' + '</head><body>' + '<textarea name="linkfield-' + link_type + '-' + post_id + '" id="linkfield-' + post_id + '" cols="60" rows="5">' + '[url=' + link + ']' + title + '[/url]' + '</textarea>' + '<p>Copy the text above and paste it in a post if you want to link to this post.</p>' + '<p><a href="javascript:self.close()">Close this Window</a></p>' + '</body></html>';
	popup = window.open("", "Create_link_to_post", "resizeable,width=520,height=200,status=0,toolbar=0,scrollbars=1");
	popup.document.write(node);
	popup.document.close();
}

function ngcic_project_links()
{
	var posts = document.getElementsByTagName('font');
	// print('There are '+ posts.length + ' matching items.');
	for (var i = 0; i < posts.length; i++) {
		// print('Post ' + i + ': ' + posts[i].className);
		if (posts[i].className.search('post') >= 0) {
			// print('[' + i + '] match.'); print(posts[i].innerHTML);
			var str = posts[i].innerHTML.replace(/((NGC|IC)\s*\d+)/g, '<form action="http://www.ngcicproject.org/ngcicdb.asp" method="post" target="_blank"><input type="hidden" name="ngcicobject" value="$1"><input type="submit" value="$1" style="background:transparent;border:none;padding:0;margin:0;border: 1px dotted"></form>');
			// print('After transformation:' + str);
			posts[i].innerHTML = str;
		}
	}
}	

// Add a link popup
// Link type = 'threaded' or 'flat' (default)
function addUbbLinkPopup(post_id, title, link_type)
{
	link_type = check_link_type(link_type);
	var popup = document.createElement('a');
	popup.href='#';
	// popup.setAttribute('onclick', 'javascript:UbbLinkPopup(' + post_id + ", '" + title + "', '" + link_type + "'); return false;");
	popup.setAttribute('id', 'popup-' + link_type + '-' + post_id);
	popup.addEventListener('click', function() { UbbLinkPopup(post_id, title, link_type) }, false);
	// Add a link text to the popup link:
	popup.appendChild(document.createTextNode('UBB link (' + link_type + ')'));
	return popup;
}

function add_post_link_in_flat_mode()
{
	var links = document.getElementsByTagName('a');
	for (var i = 0; i < links.length; i++) {
		if (links[i].name && links[i].name[0] == '#') {
			// Get the Post ID: it's encoded as an anchor starting with '#'
			// followed with digits representing the post ID (the post number):
			var post_id = links[i].name.slice(1);
			if ( isNumeric(post_id) ) { // Valid Post ID anchor
				// Retrieve the parent element of this link (an HTML Font Element):
				var parent_node = document.getElementsByTagName('a')[i].parentNode;
				parent_node.appendChild(document.createTextNode(' | '));
				// The subject of the post (post title) is contained in the
				// 1st SPAN sibling of this parent:
				var post_subject = parent_node.parentNode.getElementsByTagName('span')[0].innerHTML;

				parent_node.appendChild(document.createElement('br'));
				// Create a link element that will contain the short,
				// quick link to the post in threaded mode:
				parent_node.appendChild(addUbbContextLink(post_id, 'threaded'));
				i++; // Skip the link we just created */

				// Separator
				parent_node.appendChild(document.createTextNode(' | '));

				// Create a link element that will contain the short,
				// quick link to the post in flat mode:
				parent_node.appendChild(addUbbContextLink(post_id, 'flat'));
				i++; // Skip the link we just created */

				// Separator
				parent_node.appendChild(document.createTextNode(' | '));

				// Now create a 'UBB link popup' link in threaded context:
				parent_node.appendChild(addUbbLinkPopup(post_id, post_subject, 'threaded'));
				i++; // Skip the link we just created */

				// Separator
				parent_node.appendChild(document.createTextNode(' | '));

				// Now create a 'UBB link popup' link in threaded context:
				parent_node.appendChild(addUbbLinkPopup(post_id, post_subject, 'flat'));
				i++; // Skip the link we just created */
			}
		}
	}
}

function main() {
	if ( cn_forum_flat_mode() == true ) {
		add_post_link_in_flat_mode()
	}
	ngcic_project_links();
}


main();


