/*
 * ALL CODE BY ROB TINSLEY UNLESS OTHERWISE NOTED
 *
 * 2006-03-16 v2.00
 *
 * 2006-03-22 v2.01
 *	+ warn if using Firefox 1.0, which causes quickreply() to scroll to the top
 *
 * 2006-10-27 v2.02
 *	+ update dom_is_loaded_start() with newer code from Dean Edwards' site
 *		- so we can lose lib_iedef.js ugliness -- woo!
 *
 * 2006-10-28 v2.03
 *	+ small fix for opera to show the quickreply box correctly
 *
 * 2006-10-28 v2.10
 *	+ ajaxify_vote
 *
 * 2006-12-21 v2.11
 *	+ ajaxify_vote uses classes instead of setting styles explicitly
 *
 * 2008-03-06 v2.12
 *	+ flash embedding support
* 2009-01-13 v2.13
*	+ image library support (cr3)
 */

/*
 * DOM_IS_LOADED
 *
 * adapated from http://dean.edwards.name/weblog/2006/06/again/
 *
 * NOTE: falls back on using document.onload so
 * there can't be another handler for that event
 */

var dom_is_loaded = 0;
var dom_is_loaded_started = 0;

function dom_is_loaded_set() {
	dom_is_loaded = 1;
}

function dom_is_loaded_start() {
	if (!dom_is_loaded_started) {
		dom_is_loaded_started = 1;
		if (document.addEventListener) {
			// for Mozilla (and Opera?)
			document.addEventListener("DOMContentLoaded", dom_is_loaded_set, null);
		} else if (window.ActiveXObject) {
			// for Internet Explorer 4+ and Pocket Internet Explorer (both allegedly understand the defer attribute)
			document.write("<script id=\"__ie_onload\" defer src=\"javascript:void(0);\"><\/script>\n");
			var script = document.getElementById("__ie_onload");
			script.onreadystatechange = function() {
				if (this.readyState == "complete") {
					dom_is_loaded_set();
				}
			};
		} else if (/WebKit/i.test(navigator.userAgent)) { // sniff
			// for Safari
			var webkit_timer = setInterval(function() {
				if (/loaded|complete/.test(document.readyState)) {
					clearInterval(webkit_timer);
					dom_is_loaded_set(); // call the onload handler
				}
			}, 100);
		}
		// fallback (it is safe to call our domloaded function more than once)
		document.onload = dom_is_loaded_set;
	}
}


/*
 * PROCESSLINKS()
 *
 */

var processlinks_regexp;		// matches local links
var processlinks_linktargets = 0;	// 0 => do nothing, 1 => local_self external_blank, 2 => always_self
var processlinks_quickreply = 0;	// 0 => disabled,   1 => enabled
var processlinks_i = 0;

function processlinks_next() {
	// processes the next 50 links, waits 250 milliseconds, then does it over again

	for (j = 0; processlinks_i < document.links.length && j < 50; j++) {
		thislink = document.links[processlinks_i++];

		if (thislink.title.indexOf('Quick ') == 0) { // quick test to discard links we've already processed
			continue;
		}

		if (processlinks_linktargets > 0) {
			if (processlinks_regexp.test(thislink.href)) {
//				thislink.style.color = 'green';
				if (thislink.target.length) {
					thislink.target = null;
				}
			} else {
//				thislink.style.color = 'red';
				if (processlinks_linktargets > 1) {
					thislink.target = '_self';
				} else {
					thislink.target = '_blank';
				}
			}
		}

		if (processlinks_quickreply > 0) {
			if (thislink.innerHTML == 'Reply' && thislink.href.indexOf('/write.php?parent=') >= 0) {
//				thislink.style.background = 'yellow';
				thislink.onclick = quickreply;
				thislink.title = 'Quick Reply';
			}
			if (thislink.innerHTML == 'I like this!' && thislink.href.indexOf('/vote.php?id=') >= 0) {
//				thislink.style.background = 'yellow';
				thislink.onclick = ajaxify_vote;
				thislink.title = 'Quick Vote';
				thislink.target = '_blank';
			}
		}
	}

	if (processlinks_i < document.links.length || !dom_is_loaded) {
		setTimeout('processlinks_next()', 250);
	}
}

function processlinks_start(user_linktargets, user_quickreply) {

	thisdomain = location.href.toLowerCase().replace(/^https?:\/\/((www|jelly)\.)?([a-z0-9-.]+)(\/.*|)$/, '$3');
	if (thisdomain.match(/[^a-z0-9-.]/)) {
		// we didn't find a domain in location.href
		user_linktargets = 0;
	} else {
		processlinks_regexp = new RegExp("^https?://((www|jelly)\\.)?("+thisdomain.replace(/\./g, '\\.')+"|b3ta\\.com)(/|$)", "i");
	}

	if (user_linktargets || user_quickreply) {
		dom_is_loaded_start();
		processlinks_linktargets = user_linktargets;
		processlinks_quickreply = user_quickreply;
		processlinks_i = 0;
		processlinks_next();
	}
}

/*
 * VERIFY_CODE
 *
 */

var verify_code_cached = '';

function verify_code_set(v) {
	verify_code_cached = v;
	return verify_code_cached;
}

function verify_code_lookup() {

	if (verify_code_cached.length) {
		return verify_code_cached;
	}

	for (i = 0; i < document.links.length && i < 100; i++) {
		p = document.links[i].href.indexOf('verify_code=');
		if (p < 0) {
			continue;
		}
		v = document.links[i].href.substring(p+12);
		q = v.indexOf('&');
		if (q > 1) {
			v = v.substring(0, q);
		}
		return verify_code_set(v);
	}
	return verify_code_set('');
}

/*
 * AJAXIFY
 *
 */

function ajaxify_vote() {
	var http_request = false;
	var url = this.href+'&ajax=1';

	if (window.XMLHttpRequest) { // Mozilla, Safari, ...
		http_request = new XMLHttpRequest();
		try {
			// for mozilla
			http_request.overrideMimeType('text/xml');
		} catch (e) {}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if (!http_request) {
            return true;
        }

	url = url + '&random='+Math.floor(Math.random()*1000000); // disable caching

	var el = this;
	el.className = 'voting';
	http_request.onreadystatechange = function() { ajaxify_vote_response(http_request, el); };
	http_request.open('GET', url, true);
	http_request.send(null);

	return false;
}

function ajaxify_vote_response(http_request, el) {
	if (http_request.readyState == 4 && (http_request.status == 200 || http_request.status == undefined /* safari */ )) {
		if (http_request.responseText == '<result>success</result>') {
			el.blur();
			el.className = 'voted';
		} else {
			el.blur();
			el.className = '';
		}
	}
}

/*
 * QUICKREPLY()
 *
 */

var quickreply_open_id = null;

function quickreply() {
	var p, q;

	p = this.href.indexOf('/write.php?parent=');
	if (p < 0) {
		return true;
	}

	q = parseInt(this.href.substring(p+18));
	if (q <= 0) {
		return true;
	}

	post = document.getElementById('post'+q);
	if (!post || !post.id) {
		return true;
	}

	verify_code = verify_code_lookup();
	if (!verify_code.length) {
		return true;
	}

	html = quickreply_html(this, post, verify_code);

	p = document.getElementById(post.id+'qr');
	if (p) {
		p.parentNode.removeChild(p);
		quickreply_open_id = null;
		return false;
	}

	q = document.getElementById(quickreply_open_id);
	if (q) {
		q.parentNode.removeChild(q);
		quickreply_open_id = null;
		q = null;
	}

	node = document.createElement('div');
	if (!node) {
		return true;
	}

	node.setAttribute('id', post.id+'qr');
	node.innerHTML = html;
	node.style.paddingLeft = post.style.paddingLeft;
	node.style.background  = '#bbb';
	post.parentNode.insertBefore(node, post.nextSibling);
	quickreply_open_id = post.id+'qr';

	document.getElementById(post.id+'subj').focus();

	return false;
}

function quickreply_html(link, post, verify_code) {

	html = '';

	html+= '<div style="background: transparent; padding: 8px 0 8px 50px;">';

	html+= '<form action="'+link.href+'" method="post" name="postform" style="">';
//	html+= '<input type="hidden" name="parent" value="'+id+'">'; // not needed as the parent_id is included in the form action-attribute
	html+= '<input type="hidden" name="done" value="1" id="'+post.id+'done">';
	html+= '<input type="hidden" name="verify_code" value="'+verify_code+'">';

//	html+= 'Subject:<br>';
	html+= '<input type="text" name="subject" value="" class="edit" maxlength="255" style="margin-bottom: 0.5em;" id="'+post.id+'subj"><br>';

//	html+= 'Message:<br>';
	html+= '<textarea name="message" class="edit" rows="5" wrap="virtual" style="margin-bottom: 0.5em;" id="'+post.id+'mesg"></textarea><br>';

	html+= '<input type="submit" value="post this message" onclick="return quickreply_validate(\''+post.id+'\');" style="font-size: 1em; margin-right: 1em;">';
	html+= '<input type="submit" value="linkify" title="Convert web URLs into links in your message" onclick="return quickreply_linkify(\''+post.id+'\');" style="font-size: 1em; margin-right: 1em;">';
	html+= '<input type="submit" value="full screen" onclick="document.getElementById(\''+post.id+'done\').value = 0; return true;" title="To preview this post or make it a competition entry you must use the full-screen editor." style="font-size: 1em; margin-right: 1em;">';
	
	// board-specific bits:
	if (link.href.match(/\/board\/write\.php(\?.*)?$/)) {
	
	html+= '<input style="font-size: 1em; margin-right: 1em;" type="button" value="my images" onclick="window.open(\'./my.php?bare=yes&post='+post.id+'mesg\',\'mywin\',\'width=930,height=500,scrollbars=1\')">';
	
		iscompo = html.indexOf('/board_posticon_c.gif');
		if (post.style.paddingLeft == '10px' || (iscompo > 0 && iscompo < html.toLowerCase().indexOf('<b'))) { // <b> or <br> or <br />
			html+= '<input type="checkbox" name="ilikethis">I like this!';
		}
		footnote = 'Posting a link? Consider using the <a href="/links/">links board</a>.';
	} else
	if (link.href.match(/\/talk\/write\.php(\?.*)?$/)) {
		footnote = 'Posting a link? Consider using the <a href="/links/">links board</a>.';
//		footnote = 'Posting a picture? Then you need the <a href="/board/">main board</a>.';
	} else
	if (link.href.match(/\/links\/write\.php(\?.*)?$/)) {
		if (post.style.paddingLeft == '10px') {
			html+= '<input type="checkbox" name="ilikethis">I like this!';
		}
		footnote = 'Please remember that this is not the place to slag off other members\' work.';
	} else
		footnote = '';

	if (navigator.userAgent.indexOf(' Firefox/1.0') >= 0) {
		footnote = "You are using Firefox 1.0. Please upgrade to v1.5 if you have scroll-to-the-top problems.";
	}

	html+= '</form>';

	if (footnote.length > 0) {
		html+= '<p style="padding: 0.6em 0 0 0; margin: 0; /* font-weight: bold; */">'+footnote+'</p>';
	}

	html+= '</div>';

	return html;
}

function quickreply_linkify_html(message) {
	if (message.match(/\s(alt|title)\s*=\s*(\"[^\">]*|\'[^\'>]*)[\s()](https?:\/\/|www\.)/i)) {
		// (we don't autolink anything if it looks like there's a url in an alt or title attribute somewhere)
		return message;
	}
	message = message.replace(/(^|[\s()])(https?:\/\/)([^\s\'\"<>()]+)/ig, '$1<a href="$2$3" target="_blank">$3</a>');
	message = message.replace(/(^|[\s()])(www\.)([^\s\'\"<>()]*)/ig, '$1<a href="http://$2$3" target="_blank">$2$3</a>');
	return message;
}

function quickreply_linkify(post_id) {
	message = document.getElementById(post_id+'mesg');
	message.value = quickreply_linkify_html(message.value); // XXX: should call livepreview_linkify() instead
	message.focus();
	return false;
}

function quickreply_validate(post_id) {

	subject = document.getElementById(post_id+'subj');
	message = document.getElementById(post_id+'mesg');
	if (!subject || !message) {
		// wtf? just let it through and let the server deal with it
		return true;
	}

	subject_length = subject.value.replace(/^\s*|\s*$/g,'').length;
	message_length = message.value.replace(/^\s*|\s*$/g,'').length;

	if (!subject_length && !message_length) {
		alert('You must enter a subject or message');
		return false;
	}

	// if the subject or message field is empty, fill it with a space ourselves so that the user doesn't have to
	if (!subject_length) {
		subject.value = ' ';
	}
	if (!message_length) {
		message.value = ' ';
	}

	return true;
}


/*
 * KEYNAV
 *
 */

/* by Dustin Diaz */
function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if (node == null)
		node = document;
	if (tag == null)
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

/* adapted from http://www.howtocreate.co.uk/tutorials/javascript/browserwindow */
function keynav_ypos() {
	if (typeof(window.pageYOffset) == 'number') {
		// Netscape compliant
		return window.pageYOffset;
	} else
	if (document.body && typeof(document.body.scrollTop) == 'number') {
		// DOM compliant
		return document.body.scrollTop;
	} else
	if (document.documentElement && typeof(document.documentElement.scrollTop) == 'number') {
		// IE6 standards compliant mode
		return document.documentElement.scrollTop;
	}

	return 0;
}

function keynav_cycle(searchClass, op) {

	current_ypos = keynav_ypos();

	posts = getElementsByClass(searchClass, null, 'div');

	this_ypos = 0;
	for (i = 0; i < posts.length; i++) {
		if (!posts[i].id) {
			continue;
		}
		post = document.getElementById(posts[i].id);
		if (!post || post.id.substring(0,4) != 'post' || typeof(post.offsetTop) != 'number') {
			continue;
		}

		prev_ypos = this_ypos;
		this_ypos = post.offsetTop;

		switch(op) {
			case 'down':
				if (this_ypos >  current_ypos) {
					return this_ypos;
				}
				break;
			case 'up':
				if (this_ypos >= current_ypos) {
					return prev_ypos;
				}
				break;
			default:
				return -1;
				break;
		}
	}

//	return (op == 'down' && searchClass != 'newpost') ? -1 : 0;
	return 0;
}

function keynav_thread_position(op) {

	current_ypos = keynav_ypos();

	posts = getElementsByClass('post[12]', null, 'div');

	this_ypos = 0;
	for (i = 0; i < posts.length; i++) {
		if (!posts[i].id) {
			continue;
		}
		post = document.getElementById(posts[i].id);
		if (!post || post.id.substring(0,4) != 'post' || typeof(post.offsetTop) != 'number') {
			continue;
		}
		if (parseInt(post.style.paddingLeft) >= 50) {
			continue;
		}

		prev_ypos = this_ypos;
		this_ypos = post.offsetTop;

		switch(op) {
			case 'down':
				if (this_ypos >  current_ypos) {
					return this_ypos;
				}
				break;
			case 'up':
				if (this_ypos >= current_ypos) {
					return prev_ypos;
				}
				break;
			default:
				return -1;
				break;
		}
	}

//	return (op == 'down') ? -1 : 0;
	return 0;
}

function keynav_parent_position() {

	current_ypos = keynav_ypos();

	posts = getElementsByClass('post[12]', null, 'div');

	prev_ypos = 0;
	for (i = 0; i < posts.length; i++) {
		if (!posts[i].id) {
			continue;
		}
		post = document.getElementById(posts[i].id);
		if (!post || post.id.substring(0,4) != 'post' || typeof(post.offsetTop) != 'number') {
			continue;
		}

		prev_ypos = post.offsetTop;
		prev_id   = post.id;
		prev_pad  = parseInt(post.style.paddingLeft);

		if (post.offsetTop >= current_ypos) {
			break;
		}
	}
	if (!prev_ypos) {
		return -1;
	}

	this_ypos = -1;
	for (i = 0; i < posts.length; i++) {
		if (!posts[i].id) {
			continue;
		}
		post = document.getElementById(posts[i].id);
		if (!post || post.id.substring(0,4) != 'post' || typeof(post.offsetTop) != 'number') {
			continue;
		}

		if (post.id == prev_id) {
			break;
		}

		if (parseInt(post.style.paddingLeft) < prev_pad) {
			this_ypos = post.offsetTop;
		}
	}

	return this_ypos;
}

var keynav_saved_position = 0;

function keynav_thread() {
	pos = keynav_thread_position('down');
	if (pos >= 0) {
		window.scrollTo(0, pos);
		keynav_saved_position = pos;
	}
	return false;
}

function keynav_thread_up() {
	pos = keynav_thread_position('up');
	if (pos >= 0) {
		window.scrollTo(0, pos);
		keynav_saved_position = pos;
	}
	return false;
}

function keynav_mynewpost() {		// don't save position
	pos = keynav_cycle('mynewpost', 'down');
	if (pos >= 0) {
		window.scrollTo(0, pos);
	}
	return false;
}

function keynav_mynewpost_up() {	// don't save position, not used
	pos = keynav_cycle('mynewpost', 'up');
	if (pos >= 0) {
		window.scrollTo(0, pos);
	}
	return false;
}

function keynav_parent() {		// don't save position
	pos = keynav_parent_position();
	if (pos >= 0) {
		window.scrollTo(0, pos);
	}
	return false;
}

function keynav_newpost() {
	pos = keynav_cycle('newpost', 'down');
	if (pos >= 0) {
		window.scrollTo(0, pos);
		keynav_saved_position = pos;
	}
	return false;
}

function keynav_newpost_up() {		// not used
	pos = keynav_cycle('newpost', 'up');
	if (pos >= 0) {
		window.scrollTo(0, pos);
		keynav_saved_position = pos;
	}
	return false;
}

function keynav_mypost() {
	pos = keynav_cycle('(mynewpost|mypost)', 'down');
	if (pos >= 0) {
		window.scrollTo(0, pos);
		keynav_saved_position = pos;
	}
	return false;
}

function keynav_mypost_up() {
	pos = keynav_cycle('(mynewpost|mypost)', 'up');
	if (pos >= 0) {
		window.scrollTo(0, pos);
		keynav_saved_position = pos;
	}
	return false;
}

function keynav_saved() {		// restore position
	pos = keynav_saved_position;
	keynav_saved_position = keynav_ypos();
	window.scrollTo(0, pos);
	return false;
}

/*
 * .SWF EMBEDDER
 */

function flash_clicktoplay( swf_url ) {
	document.writeln( '<div class="clicktoplay" onclick="flash_clicked(\'' + swf_url + '\', this); return false;" >' );
	document.writeln( '<center>Click to play</center>' );
	document.writeln( '</div>' );
}

function flash_clicked( swf_url, clicked ) {
	var prev = clicked;
	var flashContainer;
	do {
		prev = prev.previousSibling;
	} while ( prev && prev.nodeType != 1 );
	if ( prev.tagName == 'script' || prev.tagName == 'SCRIPT' ) {
		// start
		flashContainer = document.createElement( 'div' );
		flashContainer.className = 'embeddedplayer';
		var innerHTML = '';
		innerHTML = innerHTML + '<div class="flashmovie">';
		innerHTML = innerHTML + '<object width="550" height="400">';
		innerHTML = innerHTML + '<param name="movie" value="' + swf_url + '"></param>';
		if ( 0 ) {
		innerHTML = innerHTML + '<param name="wmode" value="transparent"></param>';
		innerHTML = innerHTML + '<embed src="' + swf_url + '" wmode="transparent" type="application/x-shockwave-flash" width="550" height="400"></embed>';
		} else {
		innerHTML = innerHTML + '<embed src="' + swf_url + '" type="application/x-shockwave-flash" width="550" height="400"></embed>';
		}
		innerHTML = innerHTML + '</object>';
		innerHTML = innerHTML + '</div>';
		flashContainer.innerHTML = innerHTML;
		clicked.parentNode.insertBefore( flashContainer, clicked );
		clicked.innerHTML = '<center>Click to STOP</center>';
	} else if ( ( prev.tagName == 'div' || prev.tagName == 'DIV' ) && prev.className == 'embeddedplayer' ) {
		clicked.parentNode.removeChild( prev );
		clicked.innerHTML = '<center>Click to play</center>';
	} else {
		/* wtf? */
	}
	clicked = prev = flashContainer = false; // clear all DOM references (might avoid memory leaks?)
	return false;
}

function flash_autoplay( swf_url ) {
	document.writeln( '<div class="embeddedplayer">' );
	document.writeln( '<div class="flashmovie">' );
	document.writeln( '<object width="550" height="400">' );
	document.writeln( '<param name="movie" value="' + swf_url + '"></param>' );
	if ( 0 ) {
	document.writeln( '<param name="wmode" value="transparent"></param>' );
	document.writeln( '<embed src="' + swf_url + '" wmode="transparent" type="application/x-shockwave-flash" width="550" height="400"></embed>' );
	} else {
	document.writeln( '<embed src="' + swf_url + '" type="application/x-shockwave-flash" width="550" height="400"></embed>' );
	}
	document.writeln( '</object>' );
	document.writeln( '</div>' );
	document.writeln( '</div>' );
}

