/**
 * Return1 Misc Javascript functions
 * 
 * Created by Lucas van Dijk (http://www.return1.net)
 */

function external_links()
{
	var links = document.getElementsByTagName('a');
	
	for(var i = 0; i < links.length; i++)
	{
		var attr = links[i].getAttribute('rel');
		if(attr && attr == 'external')
		{
			links[i].setAttribute('target', '_blank');
		}
	}
}

/**
 * Return1.net image resizer
 * Created by Lucas van Dijk
 * http://www.return1.net
 */
function resize_images()
{
	var max_width = 600;
	var max_height = 1000;
	
	var images = $$('img.bbcodeimg');
	
	for(var i = 0; i < images.length; i++)
	{
		if(images[i].width > max_width || images[i].height > max_height)
		{
			var ratio = Math.min(Math.min(max_width / images[i].width, max_height / images[i].height), 1.0);
			
			width = images[i].width;
			height = images[i].height;
			
			images[i].width = ratio * width;
			images[i].height = ratio * height;
			images[i].style.cursor = "pointer";
			
			images[i].onclick = (function() { window.open(this.src); }).bind(images[i]);
		}
	}
}

function URLEncode(text)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var encoded = "";
	for (var i = 0; i < text.length; i++ ) {
		var ch = text.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
}

function CloneDiv(read_div, write_object)
{
	var new_div = read_div.cloneNode(true);
	new_div.id = '';
	new_div.style.display = "block";
	
	write_object.appendChild(new_div);
}

function toggle_code(id)
{
	if($('code_text_' + id).style.display == 'block')
	{
		$('code_text_' + id).style.display = 'none';
		$('code_block_' + id).style.display = 'block';
	}
	else
	{
		$('code_text_' + id).style.display = 'block';
		$('code_block_' + id).style.display = 'none';
	}
}
	

window.addEvent("load", resize_images);
