/* *******************************************************************
 * js.js
 * This Javascript is run in all browsers
 * *******************************************************************/

/**
 * addLoadEvent	Adds functions to the document on load
 * @param func	Name of functions without "()", or function
 * 
 * Example Usage:
 * addLoadEvent(nameOfSomeFunctionToRunOnPageLoad);
 * addLoadEvent(function() {
 *		// more code to run on page load
 * });
 * Thank you Simon!!! http://simon.incutio.com/archive/2004/05/26/addLoadEvent
 */
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload) {
				oldonload();
			}
			func();
		}
	}
}

function redirect(url) {
	location.href = url;
}

/**
 * debug
 * @param aMsg	A message you want to send to the Console2 error console for Firefox.
 * This function helps in debugging JavaScript in Firefox by utilizing the Console2 extension
 * for debugging. This replaces the standard alert(msg) method of debugging.
 * NOTE: this will throw in error in ALL BROWSERS. Disable this function before
 * launch by uncommenting the first line of the function.
 */
function debug(aMsg) {
	if (document.all) { // don't operate in IE
		return false;
	}
	setTimeout(function() { throw new Error("[debug] " + aMsg); }, 0);
}


/**
 * Scrubs a URL, removing everything up to, and including, the first "#".
 * This is useful because IE returns the ABSOLUTE URL when calling Element.getAttribute("href");
 * instead of the ACTUAL VALUE OF THE HREF ATTRIBUTE.
 */
function cleanHref (href) {
	var anchor_start = href.indexOf("#");				// Find where "#" resides in string
	if (anchor_start != -1) {
		return href = href.substr(anchor_start + 1);	// return the HREF, minus the "#"
	} else {
		return false;
	}
}


// USED IN CONJUCTION WITH Link2PopupWin Object
// usage: popuplink(['js-only url',] this[, w[, h[, scroll[, extras]]]])
// site-wide defaults:
var popup_w = 600;
var popup_h = 450;
var popup_scroll = true;
var popup_extras = 'location=0,status=0,menubar=0,resizable=0';
// onclick="popuplink(this.href, this, 720, 535); return false;" !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// POPUP_FANCY = 'location=yes,toolbar=yes,menubar=yes,directories=yes,status=yes,resizable=yes';
function popuplink() {
	var undef, i=0, args=popuplink.arguments;
	var url = (typeof(args[i])=='string') ? args[i++] : args[i].getAttribute('href');
	var target = args[i++].getAttribute('target') || '_blank';
	var w = args[i++];
	var h = args[i++];
	var s = (args[i]===undef) ? popup_scroll : args[i++];

	//	centering: determine screen center
	var scrw=(screen.width/2)-((w || popup_w)/2);
	var scrh=(screen.height/2)-((h || popup_w)/2);
	 	if (scrh > 100) { scrh = scrh - 40; } // bump vertical pos. just above center, but only if it fits

	var features = 'width=' + (w || popup_w)
		 + ',height=' + (h || popup_h)
		 + ',scrollbars=' + (s ? 'yes,' : 'no,')
		 + (args[i] || popup_extras)
		 + ',left='+scrw+',top='+scrh+',screenX='+scrw+',screenY='+scrh; // positioning for IE and NS
	var win = window.open(url, target, features);
	win.focus();
	return false;
}
// END POP UP

/**
 * Link2PopupWin
 * Not the best, but it does the job for now.
 */
Link2PopupWin = function() {

	this.attach = function(CssClass) {

		this.cssClass = CssClass;
		this.htmlAnchors = document.getElementsByTagName("a");

		for (var i=0; i<this.htmlAnchors.length; i++) {
			if (this.htmlAnchors[i].className.indexOf("popup") != -1) {
				this.htmlAnchors[i].onclick = function() {
					popuplink(this.href, this, 720, 535);
					return false;
				}
			}
		}
	}
}
addLoadEvent(function() {
	var popups = new Link2PopupWin();
	popups.attach("popup");
});


/**
 * Find all <A> elements on the page with rel="fade" and attaches the JS Fade function to it.
 */
function attachFade() {
	if (!document.getElementsByTagName){ return; }
	var anchors = document.getElementsByTagName("a");

	// loop through all anchor tags
	for (var i=0; i<anchors.length; i++){
		var anchor = anchors[i];
		if (anchor.getAttribute("href") && (anchor.getAttribute("rel") == "fade")){
			anchor.onclick = function() {var fade = new Fade(cleanHref(this.href), '#BEC900', '#FFFFFF', 25, 100, 0); fade.init();}
		}
	}
}
addLoadEvent(attachFade);

/**
 * Script to gradually change background colour of an element
 * Thanks: http://www.brandnewbox.co.uk/logbook/web/dhtml/yellowfade.html
 * Should maybe be using script.aculo.us instead? The file size is so big though.
 * 
 * References: 
 *    http://www.37signals.com/svn/archives/000558.php
 *    http://www.meyerweb.com/eric/tools/color-blend/
 * 
 * Future work: 
 *    Could change foreground, border colours
 *    Transparency
 **/

function Fade(id, startColour, endColour, count, speed, delay ) {
	/* Properties */
	this.id = id;                    /* id/object ref of element to fade */
	this.startColour = startColour;  /* initial colour (3 or 6 digit) hex */
	this.endColour = endColour;      /* final colour (3 or 6 digit) hex */
	this.count = count;              /* No of steps to take during fade */
	this.speed = speed;              /* Delay in ms between steps */
	this.delay = delay;              /* Initial delay before fade begins */
	
	if (typeof this.id == "string") {
	this.obj = document.getElementById(id);  
	} else {
	this.obj = this.id;
	}
	this.colour = new Array();
	this.steps = 0;
	
	/* Methods */
	this.init = init;
	this.fade = fade;
	this.parseColour = parseColour;
	
	function init() {

		first = this.parseColour(this.startColour, 'hex');
		last = this.parseColour(this.endColour, 'hex');

		this.colour = new Array();
		this.colour[this.count] = this.startColour;
		for (i=0; i<this.count; i++) {
			temp = "rgb(";
			temp += parseInt(first[0]+(last[0]-first[0])/this.count*i);
			temp += ",";
			temp += parseInt(first[1]+(last[1]-first[1])/this.count*i);
			temp += ",";
			temp += parseInt(first[2]+(last[2]-first[2])/this.count*i);
			temp += ")";
			this.colour[this.count-i] = temp;
		}
		this.colour[0] = this.endColour;
		
		var thisObj = this;
		setTimeout( function() { thisObj.fade() }, this.delay);

	}

	function fade() {
	
		if (this.count >= 0) {
		
			this.obj.style.backgroundColor = this.colour[this.count--];
			
			// I want to do this:
			// setTimeout("this.fade()", init.speed);
			// but setTimeout runs in a different thread so 'this' 
			// is out of context. 
			// See: http://www.faqts.com/knowledge_base/view.phtml/aid/2311
			
			var thisObj = this;
			setTimeout( function() { thisObj.fade() }, this.speed);
		
		}
	}

	function parseColour(colour, t) {
		/* From: http://www.meyerweb.com/eric/tools/color-blend/ */
		var m = 1;
		col = colour.replace(/[\#rgb\(]*/,'');
		if (t == 'hex') {
			if (col.length == 3) {
				a = col.substr(0,1);
				b = col.substr(1,1);
				c = col.substr(2,1);
				col = a + a + b + b + c + c;
			}
			var num = new Array(col.substr(0,2),col.substr(2,2),col.substr(4,2));
			var base = 16;
		} else {
			var num = col.split(',');
			var base = 10;
		}
		if (t == 'rgbp') {m = 2.55}
		var ret = new Array(parseInt(num[0],base)*m,parseInt(num[1],base)*m,parseInt(num[2],base)*m);
		return(ret);
	}
}

function printPage(){
	// if window.print ( or, if js is enabled)
	if (window.print){
		// open print dialogue
		window.print();
		// don't for href value
		return false;
	} else {
		// follow href value
		alert("Please use your web browsers Print button.");
		return false;
	}
} 



