/********** Various Common Functions ************/

function addLoadListener(fn) {
	if (typeof window.addEventListener != 'undefined') {
		window.addEventListener('load', fn, false);
	}
	else if (typeof document.addEventListener != 'undefined') {
		document.addEventListener('load', fn, false);
	}
	else if (typeof window.attachEvent != 'undefined') {
		window.attachEvent('onload', fn);
	}
	else {
		var oldfn = window.onload;
		if (typeof window.onload != 'function') {
			window.onload = fn;
		}
		else {
			window.onload = function() {
				oldfn();
				fn();
			};
		}
	}
}

function attachEventListener(target, eventType, functionRef,capture) {
	if (typeof target.addEventListener != "undefined") {
		target.addEventListener(eventType, functionRef, capture);
	}
	else if (typeof target.attachEvent != "undefined") {
		var functionString = eventType + functionRef;
		target["e" + functionString] = functionRef;
		target[functionString] = function(event) {
			if (typeof event == "undefined") {
				event = window.event;
			}
			target["e" + functionString](event);
		};
		target.attachEvent("on" + eventType, target[functionString]);
	}
	else {
		eventType = "on" + eventType;
		if (typeof target[eventType] == "function") {
			var oldListener = target[eventType];
			target[eventType] = function() {
				oldListener();
				return functionRef();
			};
		}
		else {
			target[eventType] = functionRef;
		}
	}
}

function detachEventListener(target, eventType, functionRef,capture) {
	if (typeof target.removeEventListener != "undefined") {
		target.removeEventListener(eventType, functionRef, capture);
	}
	else if (typeof target.detachEvent != "undefined") {
		var functionString = eventType + functionRef;
		target.detachEvent("on" + eventType, target[functionString]);
		target["e" + functionString] = null;
		target[functionString] = null;
	}
	else {
		target["on" + eventType] = null;
	}
}

function stopDefaultAction(event) {
	event.returnValue = false;
	if (typeof event.preventDefault != "undefined") {
		event.preventDefault();
	}
}

function stopEvent(event) {
	if (typeof event.stopPropagation != "undefined") {
		event.stopPropagation();
	}
	else {
		event.cancelBubble = true;
	}
}

/*
 *	Written by Jonathan Snook, http://www.snook.ca/jonathan
 *	Add-ons by Robert Nyman, http://www.robertnyman.com
 */

function getElementsByClassName(oElm, strTagName, oClassNames){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	var arrRegExpClassNames = new Array();
	if(typeof oClassNames == "object"){
		for(var i=0; i<oClassNames.length; i++){
			arrRegExpClassNames.push(new RegExp("(^|\s)" + oClassNames[i].replace(/-/g, "\-") + "(\s|$)"));
		}
	}
	else{
		arrRegExpClassNames.push(new RegExp("(^|\s)" + oClassNames.replace(/-/g, "\-") + "(\s|$)"));
	}
	var oElement;
	var bMatchesAll;
	for(var j=0; j<arrElements.length; j++){
		oElement = arrElements[j];
		bMatchesAll = true;
		for(var k=0; k<arrRegExpClassNames.length; k++){
			if(!arrRegExpClassNames[k].test(oElement.className)){
				bMatchesAll = false;
				break;
			}
		}
		if(bMatchesAll){
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements)
}

/********************************************/

/* whitespace cleaner */
var notWhitespace = new RegExp("\\S");

function cleanWhitespace(node) {
	for (var x = 0; x < node.childNodes.length; x++) {
		var childNode = node.childNodes[x];
		if ((childNode.nodeType == 3)&&(!notWhitespace.test(childNode.nodeValue))) {
// that is, if it's a whitespace text node
			node.removeChild(node.childNodes[x]);
			x--;
		}
		if (childNode.nodeType == 1) {
// elements can have text child nodes of their own
			cleanWhitespace(childNode);
		}
	}
}

function getScrollingPosition() {
	var position = [0, 0];
//	var position = 0;
	if (typeof window.pageYOffset != 'undefined') {
		position = [window.pageXOffset, window.pageYOffset];
//		position = window.pageYOffset;
	} else if (typeof document.documentElement.scrollTop != 'undefined' && (document.documentElement.scrollTop > 0 || document.documentElement.scrollLeft > 0))	{
//	} else if (typeof document.documentElement.scrollTop != 'undefined' && document.documentElement.scrollTop > 0)	{
		position = [document.documentElement.scrollLeft, document.documentElement.scrollTop];
//		position = document.documentElement.scrollTop;
	} else if (typeof document.body.scrollTop != 'undefined') {
		position = [document.body.scrollLeft, document.body.scrollTop];
//		position = document.body.scrollTop;
	}
	return position;
}

function setScrollingPosition() {
	window.scrollTo(0, scrollpos[1]);
	return;
}

function getViewportSize() {
	var size = [0, 0];
//	var size = 0;
	if (typeof window.innerWidth != 'undefined') {
		size = [window.innerWidth, window.innerHeight];
//		size = window.innerHeight;
	} else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined'	&& document.documentElement.clientWidth != 0) {
		size = [document.documentElement.clientWidth, document.documentElement.clientHeight];
//		size = document.documentElement.clientHeight;
	} else {
		size = [document.getElementsByTagName('body')[0].clientWidth, document.getElementsByTagName('body')[0].clientHeight];
//		size = document.getElementsByTagName('body')[0].clientHeight;
	}
	return size;
}

function in_array(needle,haystack) {
	for(var i=0;i<haystack.length;i++) {
		if(needle==haystack[i]) {
			return true;
		}
    }
    return false;
}

function getGetVar(searchStr) {
	start = location.search.indexOf(searchStr)+searchStr.length+1;
	end = (location.search.indexOf('&', start) == -1)? location.search.length : location.search.indexOf('&', start);
	return unescape(location.search.substring(start, end));
}

/* Event Functions */

// Add an event to the obj given
// event_name refers to the event trigger, without the "on", like click or mouseover
// func_name refers to the function callback when event is triggered
function addEvent(obj,event_name,func_name){
	if (obj.attachEvent){
		obj.attachEvent("on"+event_name, func_name);
	}else if(obj.addEventListener){
		obj.addEventListener(event_name,func_name,true);
	}else{
		obj["on"+event_name] = func_name;
	}
}

// Removes an event from the object
function removeEvent(obj,event_name,func_name){
	if (obj.detachEvent){
		obj.detachEvent("on"+event_name,func_name);
	}else if(obj.removeEventListener){
		obj.removeEventListener(event_name,func_name,true);
	}else{
		obj["on"+event_name] = null;
	}
}

// Stop an event from bubbling up the event DOM
function stopEvent(evt){
	evt || window.event;
	if (evt.stopPropagation){
		evt.stopPropagation();
		evt.preventDefault();
	}else if(typeof evt.cancelBubble != "undefined"){
		evt.cancelBubble = true;
		evt.returnValue = false;
	}
	return false;
}

// Get the obj that starts the event
function getElement(evt){
	if (window.event){
		return window.event.srcElement;
	}else{
		return evt.currentTarget;
	}
}
// Get the obj that triggers off the event
function getTargetElement(evt){
	if (window.event){
		return window.event.srcElement;
	}else{
		return evt.target;
	}
}
// For IE only, stops the obj from being selected
function stopSelect(obj){
	if (typeof obj.onselectstart != 'undefined'){
		addEvent(obj,"selectstart",function(){ return false;});
	}
}

/*    Caret Functions     */

// Get the end position of the caret in the object. Note that the obj needs to be in focus first
function getCaretEnd(obj){
	if(typeof obj.selectionEnd != "undefined"){
		return obj.selectionEnd;
	}else if(document.selection&&document.selection.createRange){
		var M=document.selection.createRange();
		try{
			var Lp = M.duplicate();
			Lp.moveToElementText(obj);
		}catch(e){
			var Lp=obj.createTextRange();
		}
		Lp.setEndPoint("EndToEnd",M);
		var rb=Lp.text.length;
		if(rb>obj.value.length){
			return -1;
		}
		return rb;
	}
}
// Get the start position of the caret in the object
function getCaretStart(obj){
	if(typeof obj.selectionStart != "undefined"){
		return obj.selectionStart;
	}else if(document.selection&&document.selection.createRange){
		var M=document.selection.createRange();
		try{
			var Lp = M.duplicate();
			Lp.moveToElementText(obj);
		}catch(e){
			var Lp=obj.createTextRange();
		}
		Lp.setEndPoint("EndToStart",M);
		var rb=Lp.text.length;
		if(rb>obj.value.length){
			return -1;
		}
		return rb;
	}
}
// sets the caret position to l in the object
function setCaret(obj,l){
	obj.focus();
	if (obj.setSelectionRange){
		obj.setSelectionRange(l,l);
	}else if(obj.createTextRange){
		m = obj.createTextRange();		
		m.moveStart('character',l);
		m.collapse();
		m.select();
	}
}
// sets the caret selection from s to e in the object
function setSelection(obj,s,e){
	obj.focus();
	if (obj.setSelectionRange){
		obj.setSelectionRange(s,e);
	}else if(obj.createTextRange){
		m = obj.createTextRange();		
		m.moveStart('character',s);
		m.moveEnd('character',e);
		m.select();
	}
}

/*    Escape function   */
String.prototype.addslashes = function(){
	return this.replace(/(["\\\.\|\[\]\^\*\+\?\$\(\)])/g, '\\$1');
}
String.prototype.trim = function () {
    return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
};
/* --- Escape --- */

/* Offset position from top of the screen */
function curTop(obj){
	toreturn = 0;
	while(obj){
		toreturn += obj.offsetTop;
		obj = obj.offsetParent;
	}
	return toreturn;
}
function curLeft(obj){
	toreturn = 0;
	while(obj){
		toreturn += obj.offsetLeft;
		obj = obj.offsetParent;
	}
	return toreturn;
}
/* ------ End of Offset function ------- */

/* Types Function */

// is a given input a number?
function isNumber(a) {
    return typeof a == 'number' && isFinite(a);
}

/* Object Functions */

function replaceHTML(obj,text){
	while(el = obj.childNodes[0]){
		obj.removeChild(el);
	};
	obj.appendChild(document.createTextNode(text));
}
/******* cursor position ***********/
function getCursorPosition(event) {
	if (typeof event == "undefined") {
		event = window.event;
	}
	var scrollingPosition = getScrollingPosition();
	var cursorPosition = [0, 0];
	if (typeof event.pageX != "undefined" && typeof event.x != "undefined") {
		cursorPosition[0] = event.pageX;
		cursorPosition[1] = event.pageY;
	}
	else {
		cursorPosition[0] = event.clientX + scrollingPosition[0];
		cursorPosition[1] = event.clientY + scrollingPosition[1];
	}
	return cursorPosition;
}
/******* date selector ***********/
/*   Script inspired by "True Date Selector"
     Created by: Lee Hinder, lee.hinder@ntlworld.com 
     
     Tested with Windows IE 6.0
     Tested with Linux Opera 7.21, Mozilla 1.3, Konqueror 3.1.0
     
*/
function daysInFebruary (year) {
  // February has 28 days unless the year is divisible by four,
  // and if it is the turn of the century then the century year
  // must also be divisible by 400 when it has 29 days
	return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
//function for returning how many days there are in a month including leap years
function DaysInMonth(WhichMonth, WhichYear) {
	var DaysInMonth = 31;
	if (WhichMonth == "4" || WhichMonth == "6" || WhichMonth == "9" || WhichMonth == "11") {
		DaysInMonth = 30;
	}
	if (WhichMonth == "2") {
		DaysInMonth = daysInFebruary( WhichYear );
	}
	return DaysInMonth;
}
//function to change the available days in a months
function ChangeOptionDays(formObj, prefix) {
	var DaysObject = eval("formObj." + prefix + "day");
	var MonthObject = eval("formObj." + prefix + "month");
	var YearObject = eval("formObj." + prefix + "year");
	
	if (typeof DaysObject.selectedIndex == 'number' && DaysObject.options) { // The DOM2 standard way
		// alert("The DOM2 standard way");
		var DaySelIdx = DaysObject.selectedIndex;
		var Month = parseInt(MonthObject.options[MonthObject.selectedIndex].value);
		var Year = parseInt(YearObject.options[YearObject.selectedIndex].value);
	} else if (DaysObject.selectedIndex && DaysObject[DaysObject.selectedIndex]) { // The legacy MRBS way
		// alert("The legacy MRBS way");
		var DaySelIdx = DaysObject.selectedIndex;
		var Month = parseInt(MonthObject[MonthObject.selectedIndex].value);
		var Year = parseInt(YearObject[YearObject.selectedIndex].value);
	} else if (DaysObject.value) { // Opera 6 stores the selectedIndex in property 'value'.
		// alert("The Opera 6 way");
		var DaySelIdx = parseInt(DaysObject.value);
		var Month = parseInt(MonthObject.options[MonthObject.value].value);
		var Year = parseInt(YearObject.options[YearObject.value].value);
	}
	// alert("Day="+(DaySelIdx+1)+" Month="+Month+" Year="+Year);
	var DaysForThisSelection = DaysInMonth(Month, Year);
	var CurrentDaysInSelection = DaysObject.length;
	if (CurrentDaysInSelection > DaysForThisSelection) {
		for (i=0; i<(CurrentDaysInSelection-DaysForThisSelection); i++) {
			DaysObject.options[DaysObject.options.length - 1] = null
		}
	}
	if (DaysForThisSelection > CurrentDaysInSelection) {
		for (i=0; i<DaysForThisSelection; i++) {
			DaysObject.options[i] = new Option(eval(i + 1));
		}
	}
	if (DaysObject.selectedIndex < 0) {
		DaysObject.selectedIndex = 0;
	}
	if (DaySelIdx >= DaysForThisSelection) {
		DaysObject.selectedIndex = DaysForThisSelection-1;
	} else {
		DaysObject.selectedIndex = DaySelIdx;
	}
}

