/**
   Prototype snippet with header
**/

/*--------------------------------------------------------------------------
 *  Prototype: an object-oriented Javascript library, version 1.2.1
 *  (c) 2005 Sam Stephenson <sam@conio.net>
 *
 *  THIS FILE IS AUTOMATICALLY GENERATED. When sending patches, please diff
 *  against the source tree, available from the Prototype darcs repository. 
 *
 *  Prototype is freely distributable under the terms of an MIT-style license.
 *
 *  For details, see the Prototype web site: http://prototype.conio.net/
 *
/*--------------------------------------------------------------------------*/

var Prototype = { Version: '1.2.1' }

var Class = {
  create: function() {
    return function() { 
      this.initialize.apply(this, arguments);
    }
  }
}

//I hacked this actually, previous looked like utter rubbish
if (!Function.prototype.apply) {
  
  Function.prototype.apply = function(object, parameters) {
    var parameterStrings = "";
    if (!object)     object = window;
    if (!parameters) parameters = new Array();
    
    for (var i = 0; i < parameters.length; i++) {
    	parameterStrings += parameter[i];
		if (i != parameters.length) {
			 parameterStrings += ", ";
		}
	}
    
    object.__apply__ = this;
    var result = eval('object.__apply__(' + parameterStrings + ')');
    object.__apply__ = null;
    
    return result;
  }
}

Object.prototype.extend = function(object) {
  for (property in object) {
    this[property] = object[property];
  }
  return this;
}

Function.prototype.bind = function(object) {
  var method = this;
  return function() {
    method.apply(object, arguments);
  }
}

//mine
Function.prototype.bindWith = function(object, argArray) {
	var method = this;
	return function() {
		method.apply(object, argArray);
	}
}

Function.prototype.bindAsEventListener = function(object) {
  var method = this;
  return function(event) {
    method.call(object, event || window.event);
  }
}

Number.prototype.toColorPart = function() {
  var digits = this.toString(16);
  if (this < 16) return '0' + digits;
  return digits;
}

var Try = {
  these: function() {
    var returnValue;
    
    for (var i = 0; i < arguments.length; i++) {
      var lambda = arguments[i];
      try {
        returnValue = lambda();
        break;
      } catch (e) {}
    }
    
    return returnValue;
  }
}




/*--------------------------------------------------
 *
 *  End of imported prototype stuff, it's all my stuff now!
 *
 *--------------------------------------------------*/ 


 var Browser = {
 		isWin: function() { return navigator.platform.indexOf("Win") != -1;},
 		isOpera: function() { return navigator.userAgent.indexOf("Opera") != -1;},
 		isIE: function() { return this.isWin() && navigator.appName.indexOf("Microsoft") != -1 && !this.isOpera();},
		getIEVersion: function() { new RegExp("MSIE ([0-9]{1,}[.0-9]{0,})").exec(navigator.userAgent); return RegExp.$1;},
 		isGecko: function() { return navigator.userAgent.indexOf("Gecko") != -1;},
		doPNG: function() { return !this.isIE() || this.getIEVersion() >= 7 }
 };
 
var Assets = {
	blankGIF : "images/blank.gif"
};


/****************************************************************************************
*****************************************************************************************
*** Onload and initialization ***********************************************************
*****************************************************************************************
*****************************************************************************************/

function Runner() {
	this.runnables = new Array();
	this.priorityRunnables = new Array();
}

Runner.prototype = {
	
	add: function(newFuncRef) {				
		this.runnables.push(newFuncRef);
	},

	addPriority: function(newFuncRef) {	
		this.priorityRunnables.push(newFuncRef);
	},

	addLater: function(newFuncRef, later) {
		this.add(
			function() {
				setTimeout(newFuncRef, later);
			}
		);
	},

	run: function() {
		if (this.priorityRunnables.length > 0) {
			for (var i = 0; i < this.priorityRunnables.length; i++) {
				this.priorityRunnables[i]();
			}	
		}
		
		if (this.runnables.length > 0) {
			for (var j = 0; j < this.runnables.length; j++) {
				this.runnables[j]();
			}	
		}
	}
};

var INITIALIZER = new Runner();
var FINALIZER = new Runner();

window.onload = INITIALIZER.run.bind(INITIALIZER);
window.onunload = FINALIZER.run.bind(FINALIZER);


/**********************************

	Core object extras

**********************************/

if (!Array.prototype.push) {
	Array.prototype.push = function(value) {
    	this[this.length] = value; 
	}
}

Array.prototype.getIndexOfValue = function(value) {
	for (var i = 0; i < this.length; i++) {
		if (this[i] == value) return i;
	}
	return -1;
}

String.prototype.trim = function() {
	if (this.length == 0) return this;
	
	var startAt = 0;
	var endAt  = this.length;

	while (this.charAt(startAt) == ' ' && startAt < endAt) {
		startAt++;
	}

	while (this.charAt(endAt-1) == ' ' && endAt > startAt) {
		endAt--;
	}

	return ((startAt > 0 || endAt < this.length)?this.substring(startAt, endAt):this);
}

String.prototype.endsWith = function(ref) {
	if (this.length == 0) return false;
	if (!ref || ref.length == 0) return false;
    if (this.length < ref.length) return false;
	if (this == ref) return true;//trivially

	return (this.substr(this.length - ref.length) == ref);
}


/********
 debug
********/

var Debug = {
	on: false,
	id: "debugElementId",

	setOn: function(on) {
		this.on = on;
	},

	isOn: function() {
		return this.on;
	},

	setup: function() {
		if (!this.on) return;

		var debugPanel = this.getPanel();		
		
		this.print("****************************");
		this.print("*** Welcome to the debug ***");
		this.print("****************************");
		this.print(navigator.appName);
		this.print(navigator.userAgent);
			
		this.print("IE ? " + Browser.isIE());
		//this.print("IE6CSS ? " + isIE6CSS);
		this.print("Gecko ? " + Browser.isGecko());
	},

	getPanel: function() {
		var panel = document.getElementById(this.id);
		if (panel == null) {		
			panel= document.createElement("DIV");
			panel.id = this.id;	
			document.body.appendChild(panel);				
		}
		return panel;
	},

	print: function(msg) {		
		if (this.on != true) return;
		
		var textNode = document.createTextNode(msg);
		var breakNode = document.createElement("br");
		
		var panel = this.getPanel();
		//alert(panel);
		panel.appendChild(textNode);
		panel.appendChild(breakNode);	
		panel.scrollTop = 3000000;
	}
}

INITIALIZER.add(Debug.setup.bind(Debug));


/****************************************************************************************
***	PNG support for IE ******************************************************************
****************************************************************************************/
var IE = {};
IE.PNG = {

		_toAlphaLoaderString: function (imgURL, sizingMethod) {
			var sm = (sizingMethod?sizingMethod:"crop");

			return "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+ imgURL + "', sizingMethod='" + sm + "')";
		}
}

//INITIALIZER.addPriority(IE.PNG.init.bind(IE.PNG));

/*********************************************
* Background image preloader for stylesheets *
*********************************************/

var Preloader = {};

Preloader.CSSImages = {

	load:function() {
		var backgroundImages = new Array();

		try {
			var ___dummy = document.styleSheets.length;
		} catch (e) {
			Debug.print("document.styleSheets is unsupported");
			return;
		}

		for (var i=0; i < document.styleSheets.length; i++) {

			var sheet = document.styleSheets[i];
			var lastSlash = sheet.href.lastIndexOf("/");
			var rules = (Browser.isIE()?sheet.rules:sheet.cssRules);

			for (var j=0; j < rules.length; j++) {
				var bgURL = rules[j].style.backgroundImage;			
				if (bgURL && bgURL != 'none') {
					bgURL = bgURL.substring(4, bgURL.length-1);
					bgURL = sheet.href.substring(0, lastSlash) + "/" + bgURL;
					backgroundImages.push(bgURL);
				}
			}
		}

		Debug.print("-------------------------------");
		Debug.print(backgroundImages.length + " images to preload");

		for (var k=0; k < backgroundImages.length; k++) {
			var img = new Image();
			var imgURL = backgroundImages[k];

			Debug.print("Preloading image : " + imgURL);
			img.onerror = this.onError.bind(img);
			img.onload = this.onLoad.bind(img);
			img.src = imgURL;		
		}
	},

	onError: function() {
		Debug.print("Error loading " + this.src);
	},
	
	onLoad: function() {
		Debug.print("Finished loading " + this.src);
	}
}

//INITIALIZER.addLater(Preloader.CSSImages.load.bind(Preloader.CSSImages), 100);

/*** Util ***/

var EventUtil = {

	getEvent: function(evt) {
		return (evt)? evt: ((event)? event: null);
	},

	getEventSrc: function(evt) {
		var elem = null;
		evt = this.getEvent(evt);
		if (evt) {
			elem = (evt.target? evt.target : ((evt.srcElement) ? evt.srcElement : null));
		}
		return elem;
	},


	cancelEvent: function(evt) {
		if (evt.preventDefault) {
			evt.preventDefault();		
		} 
		else if (evt.returnValue) {
			evt.returnValue = false;
		}
	},

	cancelBubble: function(evt) {
		if (evt.stopPropagation) {
			evt.stopPropagation();
		}
		else {
			evt.cancelBubble = true;
		}
	},
	
	multicast: function(funcA, funcB) {
		if (!funcA) return funcB;
		if (!funcB) return funcA;
	
		return function(evt) {		
			evt = (evt != null?evt:window.event);		
			funcA.call(this, evt);
			funcB.call(this, evt);
		};
	}
}

var Util = {

	fromSomething: function(something, value) {
		var index = value.indexOf(something);
		if (index == -1) return value;

		return value.substring(0, index) + value.substring(index+something.length, value.length);
	},

	toSomething: function(something, value) {
		return value + something;	
	},

	fromSmall:function(value) {
		return this.fromSomething("_small", value);
	},

	fromPX:function(value) {
		//Debug.print("fromPX doing " + value);
		var index = value.indexOf("px");
		if (index == -1) return value;

		return value.substring(0, index);
	},

	toPX: function(value) {
		return value + "px";
	},

	isClass: function(elemRef, className) {
		return (elemRef.className.search('(^|\\s)' + className + '(\\s|$)') != -1);
	},
	replaceClass: function(elemRef, oldClass, newClass) {
		var fullClass = elemRef.className;
		var pos = fullClass.indexOf(oldClass);
		if (pos == -1) return;

		var newFullClass = 
			fullClass.substring(0, pos) +
			newClass +
			fullClass.substr(pos + oldClass.length);

		elemRef.className = newFullClass;
	},

	setClassTo: function(elemRef, something) {
		this.replaceClass(elemRef, elemRef.className, this.toSomething(something, elemRef.className));
	},
	
	setClassFrom: function(elemRef, something) {
		this.replaceClass(elemRef, elemRef.className, this.fromSomething(something, elemRef.className));
	}
}

document.getElementsByTagAndClass = function(tag, className) {
	var elems = this.getElementsByTagName(tag);
	var elemsOut = new Array();
	for (var i=0; i < elems.length; i++) {
		if (Util.isClass(elems[i], className)) {
			elemsOut.push(elems[i]);
		}
	}
	return elemsOut;
}

document.getDivByClass = function(className) {
	var divs = this.getElementsByTagName("DIV");
	var divOut = null;
	for (var i = 0; i < divs.length; i++) {
		if (Util.isClass(divs[i], className)) {
			divOut = divs[i];
			break;
		}
	}
	return divOut;
}

function findFirstTextChild(elemRef) {	
	return findChildByTag(elemRef, "#text");
}

function findChildByTag(elemRef, tagName) {
	if (elemRef && elemRef.childNodes.length != 0) {
		var nodes = elemRef.childNodes;
		for (var i=0; i < nodes.length; i++) {
			if (nodes[i].nodeName && nodes[i].nodeName == tagName) {
				return nodes[i];
			}
		}
	}
	return null;
}

function findChildByClass(elemRef, cName) {
	if (elemRef && elemRef.childNodes.length != 0) {
		var nodes = elemRef.childNodes;
		for (var i = 0; i < nodes.length; i++) {
			var node = nodes[i];
			if (nodes[i].className && node.className == cName) {
				return node;
			}
		}
	}
	return null;
}

var Element = {

// Retrieve the x coordinate of a positionable object
	getLeft:function(elemRef)  {
		var result = 0;
		var obj = elemRef;
	
		while (obj.offsetParent) {
			result += obj.offsetLeft;
			obj = obj.offsetParent;
		}

		if (isIE) {
			result += document.body.offsetLeft;
		}

    	return parseInt(result);
	},

// Retrieve the y coordinate of a positionable object
 	getTop: function(elemRef)  {   
    
		var result = 0;
		var obj = elemRef;

		while (obj.offsetParent) {
			result += obj.offsetTop;
			obj = obj.offsetParent;
		}	
	
		//Debug.print("getElemTop: pre parseInt: " + result);
    	return parseInt(result);
    },


// Retrieve the rendered width of an element
 	getWidth:function(elemRef)  {        
		var result = 0;
		result = elemRef.offsetWidth;
    	return parseInt(result);
	},

// Retrieve the rendered height of an element
	getHeight:function(elemRef)  {
    	var result = 0;
		if (elemRef == null) return result;
		result = elemRef.offsetHeight;		
    	return parseInt(result);
	},

	setOpacity: function(elemRef, percentOpacity) {
		if (Browser.isIE()) {
			elemRef.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=" + percentOpacity + ",style=0)";
		//} else if (isGecko) {
		} else if (elemRef.style.opacity) {
			elemRef.style.opacity = percentOpacity/100;
		} else {
			//need to add more browser support, if none then round to visible or not, PNG -> GIF stylee			
			elemRef.style.visibility = percentOpacity > 50?"visible":"hidden";			
		}	
	}
}

/*** cookie ***/


var Cookie = {

	set: function(name, value, days) {		
		//alert("Setting Cookie : " + name + " = " + value);
		
		days = days || 365;
		
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
		
		document.cookie = name+"="+value+expires+"; path=/";
	},

	get: function(name) {		
		var nameEQ = name + '=';
		var ca = document.cookie.split(';');
		for (var i=0; i < ca.length; i++) {
			var c = ca[i];
            var cPos = 0;
			
			while (c.charAt(cPos) == ' ') cPos++;

			if (c.indexOf(nameEQ) == cPos) return c.substr(cPos+nameEQ.length);
		}
		return "";
	}
}

/*** Timer controlled menus ***/

var Menu = {
		STYLE_DELAY: 1000,
		selectors: new Array(),
		createSelector: function(tag, className, something) {
			this.selectors.push(new Menu.Selector(tag, className, something));
		},
		clearSelectors: function() {			
			Debug.print("Menu.clearSelectors");
			for (var i =0; i < this.selectors.length; i++) {
				this.selectors[i].runStyleSetter();
			}
		}
	};

window.onclick = Menu.clearSelectors.bind(Menu);

Menu.Selector = Class.create();
Menu.Selector.prototype = {

	initialize: function(tag, className, something) {
		this.tag = tag;
		this.className = className;
		this.something = something;
		this.currentElemRef = null;		
		this.currentTimerRef = null;

		var clickCanceller = function(evt) {
			Debug.print("cancel event");
			evt = evt || window.event;
			EventUtil.cancelBubble(evt);
		}

		var elems = document.getElementsByTagAndClass(tag, className);
		for (var i=0; i < elems.length; i++) {
			var elem = elems[i];
			elem.onmouseover = this.setOver.bindWith(this, [elem]);
			elem.onmouseout = this.setOut.bindWith(this, [elem]);
			//elem.onclick = clickCanceller;
		}

		
	},

	runStyleSetter: function() {				
		if (this.currentElemRef != null) {
			Debug.print("runStyleSetter for id: " + this.currentElemRef.id + " and class: " + this.className);
			this.currentElemRef.className = this.className;			
			this.currentElemRef = null;
			this._clearTimerRef();
		}		
	},

	_clearTimerRef: function() {
		if (this.currentTimerRef != 0) {
			Debug.print("clear timeout");
			clearTimeout(this.currentTimerRef);
			this.currentTimerRef = 0;
		}
	},
	
	setOver: function(elemRef) {
		//var elemRef = EventUtil.getEventSrc(evt);		
		Debug.print("-----");
		Debug.print("setOver : " + elemRef.id + " with style " + this.className + this.something);
		//always clear any timers
		this._clearTimerRef();
		//clears out the old one, it is exists.
		//if old one is null, or different element then we do it.
		if (!this.currentElemRef || this.currentElemRef !== elemRef) {
			Debug.print("no currentElem(" + (!this.currentElemRef) + ") or current and elemRef different");
			//do old one
			this.runStyleSetter();			
			elemRef.className = this.className + this.something;
		} else {
			Debug.print("currentElem that is the same");
		}
	},

	setOut: function(elemRef) {
		//var elemRef = EventUtil.getEventSrc(evt);
		Debug.print("setOut : " + elemRef.id + " with style " + this.className);
		this.currentElemRef = elemRef;				
		Debug.print("Set timeout");
		this.currentTimerRef = setTimeout(this.runStyleSetter.bind(this), Menu.STYLE_DELAY);
	}
}

/*** Stelrad Specifically **/

var StelradArea = {
	_cookieName: "area",
	_rootPage: "/index.html",
	_menuID: "subMenuInternational",
	
	set: function(area) {
		//alert(area);
		area = (area == "/"?"":area);
		Cookie.set(this._cookieName, area);
	},

	get: function() {
		var area = Cookie.get(this._cookieName);
		Debug.print("Area = " + area);
		return area;
	},

	clear: function() {
		this.setArea("");
	},
	
	tryJump: function() {		
		if (window.location.pathname != this._rootPage && window.location.pathname != '/') {
			//alert("not root path : " + window.location.pathname);
			return;
		}
			
		var area = this.get();		
		if (area == "") return;

		window.location.href = "/" + area + this._rootPage;
	},

	_extractArea: function(href) {
		//okay start at the back and find the string between the last 2 '/'s
		if (!href || href == "") return "";
		var endPos = href.lastIndexOf('/');
		var startPos = href.lastIndexOf('/', endPos-1);
		
		return href.substring(startPos+1, endPos);
	},

	setupLinks: function() {
		var menu = document.getElementById(this._menuID);
		if (!menu) return;

		var ul = findChildByTag(menu, "UL");
		if (ul == null) return;

		for (var i=0; i < ul.childNodes.length; i++) {
			var li = ul.childNodes[i];
			if (li.nodeName && li.nodeName != "LI") continue;

            var p = findChildByTag(li, "P");
			if (p == null) continue;			

			var a = findChildByTag(p, "A");
			if (a == null) continue;

			//finally!
			
			var area = this._extractArea(a.pathname);			
			//alert(area);
            a.onclick = this.set.bindWith(this, [area]);
		}
	}
}

//StelradArea.tryJump();//don't need to wait for document to load
INITIALIZER.add(StelradArea.setupLinks.bind(StelradArea));


