/*

MOKO.UI (requires yahoo-dom-event.js)

- 'el' and 'form' parameters can be either an object or object id
- 'focus' is optional, sets focus to first text input, parameter should be written as string 'focus'
- 'closebutton' is optional, parameter should be written as image path relative from page
- 'elWidth' and 'elHeight' should be in pixels, they parsed as integers so CSS values with unit are OK
- 'e' is event object required by some browsers to handle keypress, eg. onkeypress="mokoNumbersOnly(event)"
- 'fn' is function to fire when Enter key is pressed
- 'exception' is ascii value of key to allow as well as numbers

mokoObject(el);
mokoModalLightbox(url,width,height,returnFunc);
mokoModalHide()
mokoLightbox(el,focus,closebutton);
mokoLightboxHide(el);
mokoCentreElement(el,elWidth,elHeight);
mokoGetStyle(el,cssRule);
mokoSetFocus(form);
mokoHighlightInputs(form,color);
mokoGetTextInputs(el);
mokoNumbersOnly(e,fn);
mokoHideSelects(true); // Targets IE6
mokoWatermark(el, strMessage, color);
mokoMaxLength(el, maxLength);

*/

function $(id) {return document.getElementById(id);}

var gReturnFunc;
var focusElement; // Global element used for setting focus with setTimeout()
var isIE6; if (navigator.userAgent.indexOf('MSIE 6.') != -1) isIE6 = true;

function mokoObject(el) {
	if (typeof el == 'string') el = $(el);
	return el;
}
function doDebug() {
    alert('debugging');
    var i = 1;
}
function mokoModalLightbox(url,width,height,returnFunc) {
	var container = $('popup-container');
	var frame = $('modalFrame');
	var dimmer = $('popup-dimmer');
	var marginOffset = parseInt(mokoGetStyle(document.body,'margin-top')) + parseInt(mokoGetStyle(document.body,'margin-bottom')); 
	dimmer.style.height = document.body.clientHeight + marginOffset + 20 + 'px';
	container.style.display = 'block';
	frame.width = width;
	frame.height = height;
	frame.src = url;
	mokoCentreElement(container, container.offsetWidth, container.offsetHeight);
	dimmer.style.display = 'block';
	mokoHideSelects(true);
	dimmer.style.visibility = 'visible';
	if (document.body.offsetHeight >= mokoGetViewportHeight()) {
    	dimmer.style.height = document.body.offsetHeight + "px";
    } else {
        dimmer.style.height = mokoGetViewportHeight() + "px";
    }	
	frame.style.visibility = 'visible';
	container.style.visibility = 'visible';
	gReturnFunc = returnFunc;
}

function mokoModalHide(callReturnFunc) {
	mokoHideSelects(false);
	$('popup-container').style.display = 'none';
	$('popup-dimmer').style.display = 'none';
	$('popup-container').style.visibility = 'hidden';
	$('popup-dimmer').style.visibility = 'hidden';
	if (callReturnFunc == true && gReturnFunc != null)
		gReturnFunc();
	$('modalFrame').src = '/loading.html';
}

function mokoLightbox(el,focus,closebutton) {
	// Creates a full screen lightbox effect with specified element positioned in centre of page
	// Lightbox elements are added to the DOM and styled inline, no CSS required
	el = mokoObject(el);
	var dimmer = document.createElement('div');
	var marginOffset = parseInt(mokoGetStyle(document.body,'margin-top')) + parseInt(mokoGetStyle(document.body,'margin-bottom')); 
	dimmer.id = 'dimmer';
	if (isIE6) dimmer.style.position = 'absolute';
	else dimmer.style.position = 'fixed';
	dimmer.style.top = '0px';
	dimmer.style.left = '0px';
	dimmer.style.background = '#000';
	dimmer.style.opacity = '.65';
	dimmer.style.filter = 'alpha(opacity=65)';
	dimmer.style.width = '100%';
	if (document.body.offsetHeight >= mokoGetViewportHeight()) {
    	dimmer.style.height = document.body.offsetHeight + "px";
    } else {
        dimmer.style.height = mokoGetViewportHeight() + "px";
    }	
	dimmer.style.zIndex = '1000';
	el.style.visibility = 'hidden';
	el.style.position = 'absolute';
	el.style.zIndex = '1001';
	el.style.display = 'block';
	if (closebutton) {
		var closeButton = document.createElement('img');
		closeButton.id = 'closebutton';
		closeButton.src = closebutton;
		closeButton.alt = 'Close';
		closeButton.title = 'Close';
		closeButton.style.position = 'absolute';
		closeButton.style.top = '6px';
		closeButton.style.right = '6px';
		closeButton.style.opacity = '0';
		el.appendChild(closeButton);
		// Workaround for Safari Mac, which needs CSS width and height for absolute position to work properly
		closeButton.onload = function() {
			closeButton.style.width = closeButton.width + 'px';
			closeButton.style.height = closeButton.height + 'px';
			closeButton.style.opacity = '1';
		}
	}
	// This bit is to stop selects showing above popup in IE6
	if (isIE6) {
		mokoHideSelects(true);
		// Then we have to show the ones inside the popup
		var elSelects = el.getElementsByTagName('select');
		for (i = 0; i < elSelects.length; i++) {
			elSelects[i].style.visibility = 'visible';
		}
	}
	el.parentNode.removeChild(el);
	document.body.appendChild(dimmer);
	document.forms[0].appendChild(el);
	mokoCentreElement(el,el.offsetWidth,el.offsetHeight);
	el.style.visibility = 'visible';
	if (focus == 'focus') mokoSetFocus(el);
	YAHOO.util.Event.on('dimmer','click',function(){mokoLightboxHide(el)});
	if (closebutton) YAHOO.util.Event.on('closebutton','click',function(){mokoLightboxHide(el)});
	//YAHOO.util.Event.on(window,'resize',function(){mokoCentreElement(el,el.offsetWidth,el.offsetHeight);});
}

function mokoLightboxHide(el) {
	// Hides lightbox element and removes dimmer and closebutton from DOM
	el = mokoObject(el);
	document.body.removeChild($('dimmer'));
	if ($('closebutton') != null) el.removeChild($('closebutton'));
	el.style.display = 'none';
	mokoHideSelects(false);
}

function mokoCentreElement(el,elWidth,elHeight) {
	// Centres an element within viewport horizontally and vertically
	// Repositions automatically on window resize
	el = mokoObject(el);
	elWidth = parseInt(elWidth);
	elHeight = parseInt(elHeight);
	var my_width  = mokoGetViewportWidth();
	var my_height = mokoGetViewportHeight();
	el.style.position = 'absolute';
	var scrollY = mokoGetScrollHeight();
	var setX = (my_width - elWidth)/2;
	var setY = (my_height - elHeight)/2 + scrollY;
	setX = (setX < 0) ? 0 : setX;
	setY = (setY < 0) ? 0 : setY;
	//el.style.left = setX + 'px';
	el.style.left = "280px";
	el.style.top  = setY + 'px';
	YAHOO.util.Event.on(window,'resize',function(){mokoCentreElement(el,el.offsetWidth,el.offsetHeight);});
}

function mokoGetViewportWidth() {
    var my_width = 0;
    if (typeof(window.innerWidth) == 'number') {
		my_width  = window.innerWidth;
	} else if (document.documentElement && (document.documentElement.clientWidth)) {
		my_width  = document.documentElement.clientWidth;
	} else if (document.body && (document.body.clientWidth)) {
		my_width  = document.body.clientWidth;
	}
	return my_width;
}

function mokoGetViewportHeight() {
    var my_height = 0;
    if (typeof(window.innerWidth) == 'number') {
		my_height = window.innerHeight;
	} else if (document.documentElement && (document.documentElement.clientHeight)) {
		my_height = document.documentElement.clientHeight;
	} else if (document.body && (document.body.clientHeight)) {
		my_height = document.body.clientHeight;
	}
	return my_height;
}

function mokoGetScrollHeight() {
	var scrollY = 0;
	if (document.documentElement && document.documentElement.scrollTop) {
		scrollY = document.documentElement.scrollTop;
	} else if (document.body && document.body.scrollTop) {
		scrollY = document.body.scrollTop;
	} else if (window.pageYOffset) {
		scrollY = window.pageYOffset;
	} else if (window.scrollY) {
		scrollY = window.scrollY;
	}
	return scrollY;
}

function mokoGetStyle(el,cssRule){
	// Returns CSS style value (including units), even if set externally
	el = mokoObject(el);
	var strValue = '';
	if (navigator.userAgent.indexOf('MSIE') != -1) {
		if (cssRule == 'margin-top') {cssRule = 'marginTop'};
		if (cssRule == 'margin-bottom') {cssRule = 'marginBottom'};
	}
	if (document.defaultView && document.defaultView.getComputedStyle) {
		strValue = document.defaultView.getComputedStyle(el,'').getPropertyValue(cssRule);
	}
	else if (el.currentStyle) {
		cssRule = cssRule.replace(/-(w)/g, function (strMatch, p1){
			return p1.toUpperCase();
		});
		strValue = el.currentStyle[cssRule];
	}
	return strValue;
}

function mokoSetFocus(form) {
	// Sets focus to first text input or textarea within an element
	form = mokoObject(form);
	var textInputs = mokoGetTextInputs(form);
	if (textInputs.length != 0) {
		focusElement = textInputs[0];
		setTimeout('focusElement.focus();',0);
		// Must use setTimeout for IE or won't work, and function must be global
	}	
}

function mokoHighlighter(form,color,focus) {
	// Changes text input and textarea background colour on focus
	form = mokoObject(form);
	if (form == null) return;
	var textInputs = mokoGetTextInputs(form);
	if (textInputs.length != 0) {
		for (var i = 0; i < textInputs.length; i++) {
			YAHOO.util.Event.on(textInputs[i],'focus',function() {
				this.style.backgroundColor = color;
			});
			YAHOO.util.Event.on(textInputs[i],'blur',function() {
				this.style.backgroundColor = '';
			});
		}
	}
	if (focus == 'focus') mokoSetFocus(form);
}

function mokoGetTextInputs(el) {
	// Returns array of text inputs, file inputs and textareas within an element
	el = mokoObject(el);
	var textInputs = new Array();
	var inputs = el.getElementsByTagName('input');
	var textareas = el.getElementsByTagName('textarea');
	for (var i = 0; i < inputs.length; i++) {
		if ((inputs[i].type == 'text' || inputs[i].type == 'file' || inputs[i].type == 'password') && !(inputs[i].disabled)) {
			textInputs.push(inputs[i]);
		}
	}
	for (i = 0; i < textareas.length; i++) {
		textInputs.push(textareas[i]);
	}
	return textInputs;
}
function mokoReadOnly(e,fn,exception) {
    var key;
	var keychar;
	if (window.event) key = window.event.keyCode;
	else if (e) key = e.which;
	else return true;
	keychar = String.fromCharCode(key);
	if ((key==null) || (key==0) || (key==8) || (key==9) || (key==27)) return true;
	if(exception) {
		if(key==exception)return true;
	}
	if ((key==13) && fn) {
		eval(fn);
		return false;
	}
	else return false;
}

function mokoNumbersOnly(e,fn,exception) {
	var key;
	var keychar;
	if (window.event) key = window.event.keyCode;
	else if (e) key = e.which;
	else return true;
	keychar = String.fromCharCode(key);
	if ((key==null) || (key==0) || (key==8) || (key==9) || (key==27)) return true;
	if(exception) {
		if(key==exception)return true;
	}
	if ((key==13) && fn) {
		eval(fn);
		return false;
	}
	else if ((("0123456789").indexOf(keychar) > -1)) return true;
	else return false;
}

function mokoHideSelects(hide) {
	if (hide) var visibility = 'hidden';
	else visibility = 'visible';
	if (isIE6) {
		var selects = document.getElementsByTagName('select');
		for (var i = 0; i < selects.length; i++) {
			selects[i].style.visibility = visibility;
		}	
	}
}

function mokoWatermark(el, strMessage, color) {
	el = mokoObject(el);
	if(!color) color = "#ccc";
	YAHOO.util.Event.removeListener(el, "blur");
	YAHOO.util.Event.removeListener(el, "focus");
	YAHOO.util.Event.on(el, "blur", function() {
		mokoWatermark(el, strMessage, color);
	});
	YAHOO.util.Event.on(el, "focus", function() {
		if (el.value == strMessage) {
			el.value = "";
			el.style.color = "#000";
		}	
	});
	if (el.value == "" || el.value == strMessage) {
		el.style.color = color;
		el.value = strMessage;
	}
}

function mokoMaxLength(el, maxLength) {
    el= mokoObject(el);
    el.onkeypress = function() {
        if (el.value.length > maxLength) { 
             return false;}
   };
}
function SlidingList(oList, oLinkList, boolHasButtons, oButtonPrev, oButtonNext) {
	this.list = oList;
	this.listLength = 0;
	this.listItems = this.list.getElementsByTagName("li");
	for (var i = 0; i < this.listItems.length; i++) {
		if (this.listItems[i].parentNode.id == this.list.id) {
			this.listLength++;
		}
	}
	this.linkList = oLinkList;
	if (this.linkList != null) {
		this.links = this.linkList.getElementsByTagName("li");
	}
	this.listItemNumber = null;
	this.currentPosition = 0;
	this.hasButtons = boolHasButtons;
	this.buttonPrev = oButtonPrev;
	this.buttonNext = oButtonNext;

	SlidingList.prototype.init = function() {
		if (this.linkList) {			
			for (var i = 0; i < this.listLength; i++) {
				YAHOO.util.Event.on(this.links[i], "click", this.jump, this);
				this.links[i].listItemNumber = i;
			}
		}	
		if (this.hasButtons) {
			YAHOO.util.Event.on(this.buttonPrev, "click", this.nudge, new Array(this, 1));
			YAHOO.util.Event.on(this.buttonNext, "click", this.nudge, new Array(this,-1));
			this.setButtonStatus(this.currentPosition);
		}
	}

	SlidingList.prototype.nudge = function(ev, args) {
		var obj = args[0];
		var direction = args[1];
		var newPosition = (obj.currentPosition + (listItemWidth * direction));
		obj.listItemNumber = (newPosition * -1) / listItemWidth;
		obj.slide(newPosition);
	}

	SlidingList.prototype.jump = function(ev, obj) {
		var newPosition = this.listItemNumber * listItemWidth * -1;
		obj.listItemNumber = this.listItemNumber;
		obj.slide(newPosition);
	}

	SlidingList.prototype.slide = function(newPosition) {
		this.list.style.marginLeft = newPosition + "px";
		//var slider = new YAHOO.util.Anim(this.list, {marginLeft:{to:newPosition}}, 1, YAHOO.util.Easing.easeOutStrong);
		//slider.animate();
		if (this.hasButtons) {
			this.setButtonStatus(newPosition);
		}
		this.currentPosition = newPosition;
		if (this.linkList) {
			for(var i = 0; i < this.listLength; i++) {
				this.links[i].className = "";
			}
			this.links[this.listItemNumber].className = "active";
		}	
	}
	
	SlidingList.prototype.setButtonStatus = function(position) {
		if (position == 0 && this.listLength <= 1) {
			this.buttonPrev.style.display = "none";
			this.buttonNext.style.display = "none";
		}
		else if (position == 0 && this.listLength > 1) {
			this.buttonPrev.style.display = "none";
			this.buttonNext.style.display = "block";
		}
		else if (position == (this.listLength - 1) * listItemWidth * -1) {
			this.buttonPrev.style.display = "block";
			this.buttonNext.style.display = "none";
		}
		else {
			this.buttonPrev.style.display = "block";
			this.buttonNext.style.display = "block";
		}
	}
}
function selectableUL(oList) {
    this.list = oList;
    
    selectableUL.prototype.init = function () {
        for (var i=0; i < this.list.childNodes.length; i++) {
            YAHOO.util.Event.on(this.list.childNodes[i], "click", this.select, this.list.childNodes[i], this);            
        }
    }
    
    selectableUL.prototype.select = function (ev, item) {
        __doPostBack(this.list.id, item.id);
    }
}

function suggest(oDs, oInput, oList, oPostbackInput, intLength) {
    this.items = oDs.items;
    this.input = oInput;
    this.list = oList;
    this.postbackInput = oPostbackInput;
    this.listLength = intLength;
    this.resultSet = new Array();
    this.selectIndex = -1;
    this.disableFetch = false;

    suggest.prototype.init = function() {
        this.input.autocomplete = "off";
        YAHOO.util.Event.on(this.input, "keyup", this.getResults, this, true);
        YAHOO.util.Event.on(this.input, "keypress", this.monitorKeys, this, true);
    }
    
    suggest.prototype.initList = function() {
        for (var i=0; i < this.list.childNodes.length; i++) {
            YAHOO.util.Event.on(this.list.childNodes[i], "mouseover", this.highlight, this.list.childNodes[i], this);
            YAHOO.util.Event.on(this.list.childNodes[i], "click", this.select, this.list.childNodes[i], this);
        }
    }
   
    suggest.prototype.select = function (ev, item){
        reloadGrid(item.id);
    }
    suggest.prototype.getResults = function() {
        var isMatch = -1;
        
        if (this.disableFetch) {
            this.disableFetch = false;
            return;
        }
        if (this.input.value != "") {
            for (var i=0; i < this.items.length; i++) {
                if (this.input.value.length < 4) {
                    isMatch = this.items[i].name.substring(0, this.input.value.length).toLowerCase() == this.input.value.toLowerCase();
                } else {
                    isMatch = this.items[i].name.toLowerCase().indexOf(this.input.value.toLowerCase()) != -1;
                }
                if (isMatch) 
                    this.resultSet[this.resultSet.length] = new Array(this.items[i].id, this.items[i].name);
                if (this.resultSet.length == this.listLength) {
                    break;
                }
            }
        }
        this.loadResults(this.resultSet);
        this.selectIndex = -1;
    }
    
    suggest.prototype.monitorKeys = function(ev) {
        var Event = YAHOO.util.Event;
        switch(ev.keyCode) {
            case 13: //enter key
                if (this.selectIndex >= 0) {
                    this.select(ev, this.list.childNodes[this.selectIndex]);
                    Event.preventDefault(ev);
                }
                break;
            case 38: //up arrow
                if (this.selectIndex > 0) {
                    this.selectIndex--;
                    this.highlight(ev, this.list.childNodes[this.selectIndex]);
                    this.disableFetch = true;
                }
                break;
            case 40: //down arrow
                if (this.selectIndex >= -1 && this.selectIndex < (this.list.childNodes.length - 1)) {
                    this.selectIndex++;
                    this.highlight(ev, this.list.childNodes[this.selectIndex]);
                    this.disableFetch = true;
                }
        }
    }
    
    suggest.prototype.highlight = function (ev, item) { 
        for (var i=0; i < this.list.childNodes.length; i++) {
            var oNode = this.list.childNodes[i];
            oLink = oNode.getElementsByTagName("a")[0];
            if (oNode == item) {
                oLink.className = "active"
            } else if (oLink.className == "active") {
                oLink.className = null;
            }
        }
    }
    
    suggest.prototype.loadResults = function(resultSet) {
        var strListItems = "";
        for (var i=0; i < resultSet.length; i++) {
            strListItems += "<li id='" + resultSet[i][0] + "'><a href='#'>" + resultSet[i][1] + "</a></li>";
        }
        this.list.innerHTML = strListItems;
        this.resultSet.length = 0;
        this.initList();
    }
}

/*
function panorama(oContainer, imagePath, intImageWidth, intImageHeight) {
	this.container = oContainer;
	this.imagePath = imagePath;
	this.imageWidth = intImageWidth;
	this.imageHeight = intImageHeight;
	this.imageContainer = document.createElement("div");
	this.shimL = document.createElement("div");
	this.shimR = document.createElement("div");
	this.image1 = document.createElement("img");
	this.image2 = document.createElement("img");
}

panorama.prototype = {
	
	init : function()
	{	
		this.container.style.position = "relative";
		this.container.style.overflow = "hidden";
		
		this.imageContainer.style.width = (this.imageWidth * 2) + "px";
		this.imageContainer.style.height = this.imageHeight + "px";
		this.imageContainer.style.marginLeft = 0;
		this.container.appendChild(this.imageContainer);
		
		this.shimL.style.position = "absolute";
		this.shimR.style.position = "absolute";
		this.shimL.style.width = "33%";
		this.shimR.style.width = "33%";
		this.shimL.style.height = this.imageHeight + "px";;
		this.shimR.style.height = this.imageHeight + "px";;
		this.shimL.style.top = "0px";
		this.shimR.style.top = "0px";
		this.shimL.style.left = "0px";
		this.shimR.style.right = "0px";
		this.container.appendChild(this.shimL);
		this.container.appendChild(this.shimR);
		
		this.image1.src = this.imagePath;
		this.image2.src = this.imagePath;
		this.image1.style.cssFloat = "left";
		this.image2.style.cssFloat = "left";
		this.imageContainer.appendChild(this.image1);
		this.imageContainer.appendChild(this.image2);
		
		YAHOO.util.Event.on(this.shimL, "mouseover", this.scrollLeft, this, true);
		YAHOO.util.Event.on(this.shimR, "mouseover", this.scrollRight, this, true);
	},
	
	scrollRight : function()
	{
		var newMargin = parseInt(this.imageContainer.style.marginLeft) - 100;
		var loop = function() {
			if (newMargin == -300) {return;} else {this.scrollRight();}
		}
		var scroll = new YAHOO.util.Anim(this.imageContainer, {marginLeft:{to:newMargin}}, 1);
		scroll.onComplete.subscribe(loop, this, true);
		scroll.animate();
	}
}*/