/**
* This Page contains generic Javascript - DHTML functions to assist in writing consistant javascript funcitons
* @author: Joe Cummins
*/
var iw_String = {
	/**
	*This function removes leading and trailing whitespace from a string
	*@author found on net
	*@param str this is the string that will be stripped of it's leading and trailing whitespace
	*/
	trim: function (str){
		if(str != null){
			try{
				str = str.replace(/^\s*|\s*$/g,"");
			}catch(err){
				str = str;
			}
		}else{
			str = "";
		}
		return str;
	},
	replace: function(str, find, rep){
		var myStr = str.toString()
		return myStr.replace(/find/g, rep); 
	}
}

var iw_Math = {
	/**
	*returns Mod of two numbers
	*@author found on internet
	*@param a is the number
	*@param b is the divisor
	*/
	Mod: function(a, b) {
	    return a - Math.floor(a / b) * b;
	},
	
	/**
	*returns a number with a zero tacked on if it's under 10
	*@author found on internet
	*@param number is the number
	*@param numLength length of the number need 4 would be 1000 or 0001 if needed
	*/
	addZero: function(vNumber, numLength){
		var diff = numLength - (""+vNumber).length;
		var leadingZ = "";
		for(var i = 0;i<diff;i++){
			leadingZ += "0";
		}
		return leadingZ + vNumber;
	}
}


var iw_Date = {
	/**
	*returns a formated date - similar to VB function
	*@author found on internet by Joe Cummins
	*@param date this is the date to be formatted
	*@param format this is the fomat style
	*/
	formatDate : function (vDate, vFormat){ 
		var vDay              = iw_Math.addZero(vDate.getDate(),2); 
		var vMonth            = iw_Math.addZero(vDate.getMonth()+1,2); 
		var vYearLong         = iw_Math.addZero(vDate.getFullYear(),2); 
		var vYearShort        = iw_Math.addZero(vDate.getFullYear().toString().substring(3,4),2); 
		var vYear             = (vFormat.indexOf("yyyy")>-1?vYearLong:vYearShort);
		var vHour             = iw_Math.addZero(vDate.getHours(),2); 
		var vMinute           = iw_Math.addZero(vDate.getMinutes(),2); 
		var vSecond           = iw_Math.addZero(vDate.getSeconds(),2); 
		var vDateString       = vFormat.replace(/dd/g, vDay).replace(/MM/g, vMonth).replace(/y{1,4}/g, vYear);
		vDateString           = vDateString.replace(/hh/g, vHour).replace(/mm/g, vMinute).replace(/ss/g, vSecond);
		return vDateString;
	},
	
	/**
	*returns the difference between dates - uses the same syntax as the VB function, but only does seconds through Days
	*@author found on internet by Joe Cummins
	*@param interval this is interval "s", "n", "h", "d"
	*@param fromDate
	*@param toDate
	*/
	dateDiff: function(interval,fdate,tdate){
		var intVal;
		switch(interval){
			case "s" :intVal = 1000;break;
			case "n" :intVal = 1000*60;break;
			case "h" :intVal = 1000*60*60;break;
			case "d" :intVal = 1000*60*60*24;break;
		}
		var o_from_date = this.returnDate(fdate);
		var o_to_date  = this.returnDate(tdate);
		return Math.ceil((o_to_date.getTime()-o_from_date.getTime())/(intVal));
	},
	
	/**
	*returns the percent difference between dates
	*@author found on internet by Joe Cummins
	*@param interval this is interval "s", "n", "h", "d"
	*@param fromDate
	*@param toDate
	*/
	datePercentDiff: function(interval,sdate,edate,mdate){
		var wholeDays = iw_Date.dateDiff(interval,dt1,dt3);
		var partDays = iw_Date.dateDiff(interval,dt2,dt3);
		return (partDays / wholeDays) * 100;
	},
	
	/**
	*returns a date object or a null if there is an error
	*@author Joe Cummins
	*@param date must be formatted as a date mm/dd/yyyy or month dd, yyyy
	*/
	returnDate: function(p_date){
		return new Date(Date.parse(p_date));
	},
	
	/**
	*returns a date object from a Julian number
	*@author Joe Cummins
	*@param date must be formatted mm/dd/yyyy
	*/
	//returns a date object from a Julian number
	returnDateFromNumber: function (p){
		return new Date(p);
	},
	returnDateFromWord: function(str){
		var Now = new Date();
		var Today = this.formatDate(Now, 'MM/dd/yyyy');
		var returnDate = str;
		str = iw_String.upper(str);
		if(str == "TODAY"){returnDate = this.formatDate(Now, 'MM/dd/yyyy');}
		if(str == "YESTERDAY"){Now.setDate(Now.getDate() - 1); returnDate = this.formatDate(Now, 'MM/dd/yyyy');}
		if(str == "TOMORROW"){Now.setDate(Now.getDate() + 1); returnDate = this.formatDate(Now, 'MM/dd/yyyy');}
		return returnDate;
	}
}
/**
* This section extends the prototype Element
*/
Object.extend(
	Element, {
		getParentByType: function(obj, objType){
			while(obj.parentNode){
				obj = obj.parentNode;
				if (obj.tagName.toUpperCase() == objType.toUpperCase()) {return obj;}
			}
			return false;
		},
		getAttribute: function(obj, att){
			var ret = "";
			try{
				ret = obj.getAttribute(att);
			}catch(err){
				// do nothing
			}
			return ret;
		},
		getTop: function(obj){
			var objTop = 0;
			while (obj.offsetParent){
				objTop+=obj.offsetTop;
				obj = obj.offsetParent;
			}
			return objTop;
		},
		getLeft: function(obj){
			var objLeft = 0;
			while (obj.offsetParent){
				objLeft+=obj.offsetLeft;
				obj = obj.offsetParent;
			}
			return objLeft;
		},
		getHeight: function(obj){
			return obj.offsetHeight;
		},
		getWidth: function(obj){
			return obj.offsetWidth;
		},
		center: function(obj){
			/*var scrollTop = window.scrollY ? window.scrollY:document.body.scrollTop;
			var scrollLeft = window.scrollX ? window.scrollY:document.body.scrollLeft;
			var width = document.body.offsetWidth;
			var height = document.body.offsetHeight;*/
			var topCenter = ((window.scrollY ? window.scrollY:document.body.scrollTop) + document.body.offsetHeight)/2;
			var leftCenter = ((window.scrollX ? window.scrollY:document.body.scrollLeft) + document.body.offsetWidth)/2;
			var myTop = (this.getTop(obj)/2) - (this.getHeight(obj)/2);
			var myLeft = (this.getLeft(obj)/2) - (this.getWidth(obj)/2);
			alert(topCenter + " - " + myTop)
			alert(leftCenter + " - " + myLeft)
			//getTop(obj)
			obj.style.top = topCenter - myTop;
			obj.style.left = leftCenter - myLeft;
			obj.style.zIndex = 1000;
			//alert(window.scrollY)
			//alert(document.body.parentNode.scrollTop)
			
		}
	}
)
/**
* This section extends the prototype Form
*/
Object.extend(
	Form,{
		//TODO this isn't done at all
		 returnSelectBox: function(arr, name, value){
			var sel = document.createElement("SELECT");
			//sel.name = name;
			if(arr && arr.length>0){
				sel.options[0] = new Option("Select One", "");
				sel.options[0].style.color = "gray"
				for(var i=0;i<arr.length;i++){
					var opt = new Option(arr[i].display, arr[i].value);
					sel.options[i+1] = opt;
					if(MFFR_TrimString(arr[i].value) == value){sel.selectedIndex = i+1;}
				}
			}else{
				sel.options[0] = new Option("No Options Available", "");
				sel.disabled = true;
			}
			return sel;
		},
		//TODO this isn't done at all
		returnTextBox: function (value){
			var obj = document.createElement("INPUT");
			obj.type = "text";
			var tempVal = value;
			tempVal = tempVal.replace(/\$/g, "");
			tempVal = tempVal.replace(/,/g, "");
			if(MFFR_DataType(tempVal)=="date" || MFFR_DataType(tempVal)=="number"){
				obj.style.textAlign = "right";
				value = tempVal;
			}
			obj.value = MFFR_TrimString(value);
			return obj;
		},
		/**
		*returns a submit button object
		*@author Joe Cummins
		*@param name
		*@param value
		*/
		returnSubmitButton: function (nm, val){
			var obj = document.createElement("INPUT");
			obj.type = "submit";
			obj.value = val;
			obj.name = nm;
			return obj;
		},
		/**
		*returns a button object
		*@author Joe Cummins
		*@param name
		*@param value
		*/
		returnButton: function (nm, val){
			var obj = document.createElement("INPUT");
			obj.type = "button";
			obj.value = val;
			obj.name = nm;
			return obj;
		}
	}
)
function $2(obj){
	try{
		return $(obj)
	}catch(err){
		alert("Error:\n" + err + "\n" + obj)
		return null;
	}
}
var iw_DHTML = {
	/**
	* adapted from an article found at http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
	*/
	windowScroll:function(){
		var scrOfX = 0, scrOfY = 0;
		if( typeof( window.pageYOffset ) == 'number' ) {
		    //Netscape compliant
		    scrOfY = window.pageYOffset;
		    scrOfX = window.pageXOffset;
		} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		    //DOM compliant
		    scrOfY = document.body.scrollTop;
		    scrOfX = document.body.scrollLeft;
		} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		    //IE6 standards compliant mode
		    scrOfY = document.documentElement.scrollTop;
		    scrOfX = document.documentElement.scrollLeft;
		}
	  return [ scrOfX, scrOfY ];
	},
	/**
	* adapted from an article found at http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
	*/
	windowSize:function(){
		var myWidth = 0, myHeight = 0;
		if( typeof( window.innerWidth ) == 'number' ) {
			//Non-IE
			myWidth = window.innerWidth;
			myHeight = window.innerHeight;
		} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		    //IE 6+ in 'standards compliant mode'
			myWidth = document.documentElement.clientWidth;
		    myHeight = document.documentElement.clientHeight;
		} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		    //IE 4 compatible
		    myWidth = document.body.clientWidth;
		    myHeight = document.body.clientHeight;
		}
	    return [myWidth, myHeight];
	},
	swap: function (obj1, obj2, caller){
		if($2(caller).type == "checkbox"){
			if($(caller).checked){
				$2(obj1).style.display = "none";
				$2(obj2).style.display = "block";
			}else{
				$2(obj2).style.display = "none";
				$2(obj1).style.display = "block";
			}
		}else{
			$2(obj1).style.display = "none";
			$2(obj2).style.display = "block";
		}
		return true;		
	},
	toggle: function (obj1, caller){
		if($(caller).type == "checkbox"){
			if($(caller).checked){
				$(obj1).style.display = "block";
			}else{
				$(obj1).style.display = "none";
			}
		}else{
			if($(obj1).style.display == "none"){
				$(obj1).style.display = "block";
			}else{
				$(obj1).style.display = "none";
			}
		}
		return true;		
	},
	showPopUp : function(obj, text, myClass){
		//call to prototype
		var popUp = this.singleton("singlePopUp", "DIV")
		this.removeChildren(popUp);
		popUp.appendChild(document.createTextNode(text));
		document.body.appendChild(popUp);
		if(myClass != null || myClass != ""){popUp.className = myClass;}
		popUp.myObj = obj;
		this.placeOnTop(obj, popUp);
		window.status=text;
		return popUp;
		//try{popUp.filters.alpha.opacity = 0;}catch(err){}
		//this.fadeIn(popUp, 10);
		//iw_DHTML.parentInfo(obj);
	},
	hidePopUp: function(){
		if(document.getElementById("singlePopUp")){
			var popUp = document.getElementById("singlePopUp");
			this.removeChildren(popUp);
			popUp.className = "noDisplay";
			this.showBleed(popUp);
			window.status="";
			//try{popUp.filters.alpha.opacity = 0;}catch(err){}
		}
	},
	placeOnTop: function(source, target){
		source = $(source);
	    target = $(target);
	    target.style.position = 'absolute';
	    var offsets = Position.cumulativeOffset(source);
	    var scroll = this.windowScroll();
	    var size = this.windowSize();
	    var roomFromEdge = size[0] - offsets[0] + scroll[0];
	    if(roomFromEdge < 200){
	    	//iw_DHTML.alert("scrollLeft " + document.documentElement.scrollLeft)
	    	//iw_DHTML.alert("clientWidth " + (document.body.clientWidth - offsets[0]))
	    	target.style.left = (offsets[0] -  (200 - roomFromEdge)) + 'px';
	    }else{
	    	target.style.left = offsets[0] + 'px';
	    }
	    target.style.top = offsets[1] - target.offsetHeight - 2 + 'px';
	    this.hideBleed(target);
	},
	_w : null,
	alert : function(errtxt){
		try{if(this._w == null){this._w = window.open('',"alertWriter","toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,width=300,height=600");}}catch(err){}
		var innerT = "";
		try{innerT = this._w.document.body.innerHTML}catch(err){}
		this._w.document.open()
		this._w.document.write(innerT + "<br>" + errtxt);
		this._w.document.close();
	},
	parentInfo: function(obj){
		while(obj.offsetParent){
			iw_DHTML.alert(obj.tagName + " - " + obj.id + " - " + obj.offsetLeft)
			obj = obj.offsetParent
		}
	},
	singleton: function(obj, type){
		if(!$(obj)){
			var name = obj;
			obj = document.createElement(type);
			obj.id = name
		}
		return $(obj);
	},
	removeChildren: function(obj){
		while(obj.childNodes[0]){
			obj.removeChild(obj.childNodes[0]);
		}
	},
	getFirstChildByName: function(obj, type){
		for (var i = 0; i < obj.childNodes.length; i++) {
			var node = obj.childNodes[i];
			if (node.tagName == type){
				return obj.childNodes[i];
			}
		}
		return false;
	},
	fadeIn: function(obj){
		obj = $(obj);
		if(obj.id == null || obj.id == ""){
			var mytime = new Date();
			obj.id = mytime.getTime();
			obj = $(obj);
		}
	   /* try{
			var opacity = obj.style.MozOpacity;
			alert(opacity)
			if(opacity >= 91){opacity = 100;}else if(opacity < 91){opacity += 10;}
			alert(opacity)
			obj.style.MozOpacity = opacity/100; 
	    }catch(err){}*/
	    try{ 
	    	var opacity = obj.filters.alpha.opacity;
			if(opacity >= 91){opacity = 100;}else if(opacity < 91){opacity += 10;}
	    	obj.filters.alpha.opacity = opacity;
	    	setTimeout("iw_DHTML.fadeIn('"+obj.id+"');",50);
	    }catch(err){}
		if(opacity != 100){
	    	//setTimeout("iw_DHTML.fadeIn('"+obj.id+"');",50);
	    }else{
	    	return false;
	    }
	},
	//loops through the Document and hides all elements that will bleed through DHTML
	hideBleed: function(obj){
		var offsets = Position.cumulativeOffset(obj);
		var eT = offsets[1];
		var eH = obj.offsetHeight;
		var eL = offsets[0];
		var eW = obj.offsetHeight;
		var val_ArraySelect = new Array;
		var ctr = 0;
		for (var j=0; j < document.forms.length; j++){
			if(document.forms[j].name != "doNotScan"){
				for (var i=0; i < document.forms[j].elements.length; i++){
					var el = document.forms[j].elements[i];
					if (el.type=="select-one"||el.type=="textarea"||el.type=="select-multiple"){
						offsets = Position.cumulativeOffset(el);
						var thisT = offsets[1];
						var thisH = obj.offsetHeight;
						var thisL = offsets[0];
						var thisW = obj.offsetHeight;
						if(thisT > (eT-thisH) && thisT < (eT+eH)){
							if(thisL+thisW>eL&&thisL<eL+eW){
								if(el.style.visibility != 'hidden'){
									el.style.visibility = 'hidden';
									val_ArraySelect[ctr++]=el;
									obj.hideArray = val_ArraySelect;
								}
							}
						}
					}
				}
			}
		}
	},
	//Shows hidden elements
	showBleed: function(obj){
		if(obj.hideArray){
			val_ArraySelect = obj.hideArray
			for(var i=0;i<val_ArraySelect.length;i++){
				val_ArraySelect[i].style.visibility = 'visible';
			}
			obj.hideArray = null;
		}
	}
	/**
	*returns table from array
	*@author found on internet by Joe Cummins
	*@param arr is the array
	*@param head is a boolean saying whether you want a header or not
	*@param side Optional parameter if you want a side header for a list style
	*/
	/*table: function(arr, head) {
		var tab = document.createElement("TABLE");
		var thead = document.createElement("THEAD");
		var tbody = document.createElement("TBODY");
		tab.appendChild(thead);
		tab.appendChild(tbody);
		for(var i = 0;i<arr.length,i++){
			
		}
	    return tab;
	},*/
}
/**
* this is a overload of the Ajax.Updater function that catches system timeouts
* @author jcummins  
*/
/*var iw_Ajax = {};
	iw_Ajax.Updater = Class.create();
	iw_Ajax.Updater.ScriptFragment = '(?:<script.*?>)((\n|.)*?)(?:<\/script>)';

	iw_Ajax.Updater.prototype.extend(Ajax.Updater.prototype).extend({
		updateContent: function() {
		var receiver = this.responseIsSuccess() ?
		this.containers.success : this.containers.failure;

		var match    = new RegExp(Ajax.Updater.ScriptFragment, 'img');
		var response = this.transport.responseText.replace(match, '');
		var scripts  = this.transport.responseText.match(match);
		
		// I put this in to evaluate the text to spot timeouts
		var myText = this.transport.responseText;
		myText = iw_String.trim(myText).substring(0,5);
		if(myText == "<html"){
			alert("This application has timed out, or an error has happened.  Please, log in again");
			window.location.reload( false );
			return false;
		}
		
		if (receiver) {
			if (this.options.insertion) {
				new this.options.insertion(receiver, response);
			} else {
				receiver.innerHTML = response;
			}
		}
		
		if (this.responseIsSuccess()) {
			if (this.onComplete){
				setTimeout((function() {this.onComplete(this.transport)}).bind(this), 10);
				
			}
		}

		if (this.options.evalScripts && scripts) {
			match = new RegExp(Ajax.Updater.ScriptFragment, 'im');
			setTimeout((function() {
				for (var i = 0; i < scripts.length; i++)
					eval(scripts[i].match(match)[1]);
			}).bind(this), 10);
		}
	}
	});
*/
var iw_validate={
	checkForm:function(frm){
		iw_validate.hideSubmit(frm);
		var formGood = true;
		for(var i = 0; i < frm.elements.length; i++){
			var el = frm.elements[i];
			if(this.isRequired(el) && iw_String.trim(el.value) == ""){
				el.setAttribute("errMsg","This needs a value before the form can be submitted");
				//el.help="This needs a value before the form can be submitted";
				Event.observe(el, "focus", showHelpMessage, false);
				Event.observe(el, "blur", hideHelpMessage, false);
				el.style.borderColor = "red";
				formGood = false;
				var op = el;
				var c = true;
				while (op.parentElement){
					if(op.style.display=="none"||op.style.visibility=="hidden"){
						c=0;
					}
					op=op.parentElement;
				}
				if(c){
					try{el.focus();}catch(err){}
				}
			}else{
				el.setAttribute("errMsg","");
			}
		}
		if(formGood){return true;}else{this.showSubmit(frm);return false;}
	},
	submitAction:function(event){
		var obj = Event.element(event);
		var frm = Event.findElement(event, "FORM");
		if(iw_validate.checkForm(frm)){
			frm.submit();
		}
	},
	isRequired:function(obj){
		try{var att = obj.getAttribute("required")}catch(err){return false;}
		if(att=="true" || att == true){
			return true;
		}else{
			return false;
		}
	},
	//hides submit button to prevent double entry
	hideSubmit:function(frm){
		for(var i = 0; i < frm.elements.length; i++){
		var el = frm.elements[i];
			if((el.type=="submit" || el.type=="button") && el.value == "Save"){
				el.style.visibility="hidden";
			}
		}
	},
	//shows submit button if validation fails
	showSubmit:function(frm){
		for(var i = 0; i < frm.elements.length; i++){
			var el = frm.elements[i];
			if((el.type=="submit" || el.type=="button") && el.value == "Save"){
				el.style.visibility="visible"
			}
		}
	},
	initValidation:function(){
		for(var i = 0; i<document.forms.length;i++){
			var frm = document.forms.item(i);
			for(var j = 0;j< frm.elements.length;j++){
				var el = frm.elements.item(j);
				if(el.nodeType == 1 && ( el.type == "button")){
					if(el.value == "Save"){
						if(!el.onclick)
						Event.observe(el, "click", iw_validate.submitAction, false);
					}
				}
			}
		}
	}
}
//try{
//Event.observe(window, "load", iw_validate.initValidation, false);
//}catch(err){}
/*var iw_cookie = {
	getCookie: function( name ) {
		var start = document.cookie.indexOf( name + "=" );
		var len = start + name.length + 1;
		if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
			return null;
		}
		if ( start == -1 ) return null;
		var end = document.cookie.indexOf( ";", len );
		if ( end == -1 ) end = document.cookie.length;
		return unescape( document.cookie.substring( len, end ) );
	},
	setCookie: function( name, value, expires, path, domain, secure ) {
		var today = new Date();
		today.setTime( today.getTime() );
		if ( expires ) {
			expires = expires * 1000 * 60 * 60 * 24;
		}
		var expires_date = new Date( today.getTime() + (expires) );
		var cookie = name+"="+escape( value ) +
			( ( expires ) ? ";expires="+expires_date.toGMTString() : "" ) + //expires.toGMTString()
			( ( path ) ? ";path=" + path : "" ) +
			( ( domain ) ? ";domain=" + domain : "" ) +
			( ( secure ) ? ";secure" : "" );
		document.cookie = cookie;
	},
	deleteCookie: function( name, path, domain ) {
		if ( this.getCookie( name ) ) document.cookie = name + "=" +
				( ( path ) ? ";path=" + path : "") +
				( ( domain ) ? ";domain=" + domain : "" ) +
				";expires=Thu, 01-Jan-1970 00:00:01 GMT";
	},
	getDomain:function(){
		var x=window.location.href.split('/');
		x.length=3;
		var myString = "";
		for(var i=0; i< x.length; i++){
			myString += x[i] + "/";
		}
		return myString;
	}
}
*/