﻿
// =========================================
// MATWEB CODE LIBRARY OBJECT
// This is basically a library of functions wrapped in an object
// such that they can be globally identified with a common namespace/prefix: "matweb.somefunction()"
// =========================================	

//document.write("<div id=\"divPopupOverlay\" onclick=\"\" style=\"display:none;\"></div>");

var matweb = new _matweb();

//document.body.onload=alert('onload');
//document.body.onload=matweb.run_registered_code;

function _matweb(){

	this.debug = true; //this variable is set to true or false in main.master, depending on the dev environment settings

	/*
		ALLOWS CODE TO BE RUN IN WINDOW/BODY ONLOAD EVENT FROM ANYWHERE ON THE PAGE	
		Examples of how to call:
		matweb.register_onload(nameOfSomeFunctionToRunOnPageLoad);
		matweb.register_onload(function(){//some code to run....});
		Code courtesty of Simon Willison 
			http://simonwillison.net/2004/May/26/addLoadEvent/
			http://www.sitepoint.com/blogs/2004/05/26/closures-and-executing-javascript-on-page-load/
	*/
	this.register_onload = function (func) {
		//alert("matweb.register_onload()");
		var oldonload = window.onload; 
		if (typeof window.onload != 'function') {
			window.onload = func; 
		}
		else { 
			window.onload = function() { 
				oldonload(); 
				func(); 
			} 
		} 
	}//end function

	//ALLOWS CODE TO BE RUN IN _onload FROM ANYWHERE ON THE PAGE	
	//Adds a string of JS code to an array that will be evaluated later by run_registered code.
	/*
	var _aryRegisteredCode = new Array();
	
	this.register_code = function (strCodeToRun){
		var i = _aryRegisteredCode.length;
		if(i>0){i++}
		//alert(_aryRegisteredCode.length);
		_aryRegisteredCode[i] = strCodeToRun
	}
	
	//SET THIS FUNCTION TO RUN THE FROM THE BODY ONLOAD EVENT
	//<body onload="matweb.run_registered_code();" >
	this.run_registered_code = function(){
		var i;
		for (i in _aryRegisteredCode){
			//alert(_aryRegisteredCode[i]);
			try{
				eval(_aryRegisteredCode[i]);
			}
			catch(e){
				alert("Error attempting to run registered code: " + _aryRegisteredCode[i]);
			}
		}		
	}//end function
	*/

	this.DisableAutoSubmit = function(evt){
		//PROVIDES A CROSS-BROWSER WAY TO PREVENT AUTO-SUBMIT 
		//alert('hello from _disableautosubmit()');
		var charCode = this.GetEventKeyCode(evt);
		//alert(charCode);
		if (this.IsEnterKey(evt)){
			return this.CancelEvent(evt);
		}
		return true;
	}

	this.DoPostBack = function(eventTarget, eventArgument) {
		//A COPY OF THE ASP.NET __doPostBack() AUTO-GENERATED FUNCTION
		//THIS MAY NEED TO BE UPDATED IF THE ASP.NET HTML GENERATED OUTPUT, VERSION OR FRAMEWORK CHANGES
		//This does not seem to work for AJAX calls
		var myForm = document.forms['aspnetForm'];
		if (!myForm) {
				myForm = document.aspnetForm;
		}
	
		if (!myForm.onsubmit || (myForm.onsubmit() != false)) {
				myForm.__EVENTTARGET.value = eventTarget;
				myForm.__EVENTARGUMENT.value = eventArgument;
				myForm.submit();
		}
	}
	
	this.DoPostBack_OnEnter=function(evt,UniqueID) {
		//PROVIDES A CROSS-BROWSER WAY to run ASP.NET __doPostBack() function on enter key
		//alert("hello from the DoPostBack_OnEnter() event");
		if (this.IsEnterKey(evt)){
			__doPostBack(UniqueID,"");
			//this.doPostBack(UniqueID,"");
			return this.CancelEvent(evt);
		}
		else
			return true;
	}//end function
	
	this.CancelEvent = function(evt){
		//PROVIDES A CROSS-BROWSER WAY TO CANCEL AN EVENT
		evt = (evt) ? evt : window.event;
		evt.returnValue=false;
		evt.cancel = true;
		return false;
	}

	this.IsEnterKey=function(evt) {
		evt = (evt) ? evt : window.event;
		//PROVIDES A CROSS-BROWSER WAY TO CHECK IF THE ENTER KEY WAS HIT
		// charCode = 3 handles the Mac enter key code
		//alert("hello from the DoPostBack_OnEnter() event");
		var charCode = matweb.GetEventKeyCode(evt);
		//alert(charCode);
		if (charCode == 13 || charCode == 3) {
			return true;
		}
		return false;
	}//end function

	this.GetEventKeyCode=function(evt) {
		//PROVIDES A CROSS-BROWSER WAY TO GET THE KEYCODE FOR onkeyup, onkeydown EVENTS
		evt = (evt) ? evt : window.event;
		var charCode = (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);
		//alert(charCode);
		return charCode;
	}//end function
	
	this.writeOverlay = function(){
		document.write("<div id=\"divPopupOverlay\" style=\"display:none;\"></div>");
	}

	// =================================
	// GLOBAL WEB SERVICE ERROR HANDLER 
	// Used by web service calls, so we have a consistent/global way to handler JS errors for them.
	// =================================
	this.WebServiceErrorHandler = function (error,context) {
			//alert("WebServiceErrorHandler()");

			var stackTrace = error.get_stackTrace();
			var message = error.get_message();
			var statusCode = error.get_statusCode();
			var exceptionType = error.get_exceptionType();
			var timedout = error.get_timedOut();

			// Compose the error message...
			var ErrMsg =     
					"<h2>Stack Trace</h2>" +  stackTrace + "<br/>" +
					"<h2>WebService Error</h2>" + message + "<br/>" +
					"<h2>Status Code</h2>" + statusCode + "<br/>" +
					"<h2>Exception Type</h2>" + exceptionType + "<br/>" +
					"<h2>JS Context</h2>" + context + "<br/>" +
					"<h2>Timedout</h2>" + timedout;
	   
			matweb.alert(ErrMsg,"Error in WebService",null,"500");
			/*
			if(this.debug){
				matweb.alert(ErrMsg,"Error in WebService",null,"500");
			}
			else{
				matweb.alert("Sorry, there was a problem getting the data...");
				//ErrMsg = escape(ErrMsg);
				//window.location.href="/errorJS.aspx?ErrMsg=" + ErrMsg;
			}
			*/
		
	}
	
	//PROVIDES A CROSS BROWSER WAY TO SHOW/HIDE SELECT ELEMENTS BEHIND A SELECTED ELEMENT THAT YOU WANT TO SHOW OR HIDE
	this.toggleSelect = function(dv, vis){
		//alert('hi from toggleSelect()');
		var appVer = navigator.appVersion.toLowerCase();
		var iePos = appVer.indexOf('msie');
		if (iePos !=-1) {
			var is_minor = parseFloat(appVer.substring(iePos+5,appVer.indexOf(';',iePos)));
			var is_major = parseInt(is_minor);
		}
		var x=dv.offsetLeft;var y=dv.offsetTop;var w=dv.offsetWidth;var h=dv.offsetHeight;
		var selx,sely,selw,selh,i;
		
		//DMS 8/2/07 - OBJECT tags are also a problem, at least in Firefox....
		var sel=document.getElementsByTagName("OBJECT");
		for(i=0;i<sel.length;i++){
			selx=0;sely=0;var selp;
			sel[i].style.visibility=((vis==1)?"visible":'hidden');
		}

		if (navigator.appName.substring(0,9) == "Microsoft") {// Check if IE version is 6 or older
			if (is_major <= 6) {
				//var x=dv.offsetLeft;var y=dv.offsetTop;var w=dv.offsetWidth;var h=dv.offsetHeight;
				//var selx,sely,selw,selh,i;
				var sel=document.getElementsByTagName("SELECT");
				for(i=0;i<sel.length;i++){
					selx=0;sely=0;var selp;
					if(sel[i].offsetParent){
						selp=sel[i];
						while(selp.offsetParent){selp=selp.offsetParent;selx+=selp.offsetLeft;sely+=selp.offsetTop;}
						}
					selx+=sel[i].offsetLeft;sely+=sel[i].offsetTop;selw=sel[i].offsetWidth;selh=sel[i].offsetHeight;
					if(selx+selw>x && selx<x+w && sely+selh>y && sely<y+h)
						sel[i].style.visibility=((vis==1)?"visible":'hidden');
				}
			}
		}
	}
	
	this.alert = function(msg,title,btntext,height,width){
		//alert('hello from matweb.alert()');
		
		var popupElement = document.getElementById("divPopupAlert");
		//messageElement = document.getElementById('spanPopupAlertMessage');
		var messageElement = document.getElementById("tdPopupAlertMessage");
		var titleElement = document.getElementById("spanPopupAlertTitle");
		var buttonElement = document.getElementById("btnPopupAlert");
		var overlayElement = document.getElementById("divPopupOverlay");

		//center the popup element
		this.center(popupElement);

		//give the overlay the maximum height of the doc
		var h = this.docHeight();
		overlayElement.style.height=h + "px";
		
		messageElement.innerHTML = msg;
		if(title != null) titleElement.innerHTML = title;
		if(height != null) popupElement.style.height = height + "px";
		if(width != null) popupElement.style.width = width + "px";
		if(btntext!=null) {buttonElement.value = btntext;}

		// See Scriptaculous documentation
		// http://wiki.script.aculo.us/scriptaculous/show/CombinationEffects
		//new Effect.Appear(overlayElement,{duration:0.5});
		overlayElement.style.display="block";
		//new Effect.Appear(popupElement,{duration:0.5, queue: 'end'});// dependency --> scriptaculous.js
		popupElement.style.display = "block";
		//alert('width=' + popupElement.style.width);
		//alert('height=' + popupElement.style.height);
		this.toggleSelect(popupElement, 0);
	}
	
	this.confirm = function(msg,title,btntext,height,width){
		//alert('hello from matweb.confirm()');
		
		var popupElement = document.getElementById("divPopupConfirm");
		//messageElement = document.getElementById('spanPopupAlertMessage');
		var messageElement = document.getElementById("tdPopupConfirmMessage");
		var titleElement = document.getElementById("spanPopupConfirmTitle");
		var buttonElement = document.getElementById("btnPopupAlert");
		var overlayElement = document.getElementById("divPopupOverlay");

		//center the popup element
		this.center(popupElement);

		//give the overlay the maximum height of the doc
		var h = this.docHeight();
		overlayElement.style.height=h + "px";
		
		messageElement.innerHTML = msg;
		if(title != null) titleElement.innerHTML = title;
		if(height != null) popupElement.style.height = height + "px";
		if(width != null) popupElement.style.width = width + "px";
		if(btntext!=null) {buttonElement.value = btntext;}

		// See Scriptaculous documentation
		// http://wiki.script.aculo.us/scriptaculous/show/CombinationEffects
		//new Effect.Appear(overlayElement,{duration:0.5});
		overlayElement.style.display="block";
		//new Effect.Appear(popupElement,{duration:0.5, queue: 'end'});
		popupElement.style.display = "block";
	}
	
	this.alertClose = function(){
		var overlayElement = document.getElementById('divPopupOverlay'); 
		var popupElement = document.getElementById('divPopupAlert');
		this.toggleSelect(popupElement, 1);
		overlayElement.style.display = "none";
		popupElement.style.display = "none";
	}
	
	this.setFieldValue = function(id,value){
		f = document.getElementById(id);
		f.value = value;
	}

	this.setSelectValue = function(id,value){
		//alert("ID: " + id + " VALUE: " + value);
		f = document.getElementById(id);
		for (var i=0; i<f.options.length; i++){
			//alert("i: " + i + " option value: " + f.options[i].value);
			if(f.options[i].value==value){
				//alert("SET value: " + f.options[i].value);
				f.options[i].selected = true;
			}
		}
	}

	this.findSelectedOption = function(id){
		//alert("ID: " + id + " VALUE: " + value);
		f = document.getElementById(id);
		for (var i=0; i<f.options.length; i++){
			//alert("i: " + i + " option value: " + f.options[i].value);
			if(f.options[i].selected){
				return f.options[i];
			}
		}
	}

	this.setElementHTML = function(id,value){
		f = document.getElementById(id);
		f.innerHTML = value;
	}

	this.addEventHandler = function(element, event_name, observer) {	
		var capturing = true;
		if ( element.addEventListener ) {
			// the DOM2, W3C way	
			element.addEventListener( event_name, observer, capturing ); 
		}
		if ( element.attachEvent ) {
			// the IE way	
			element.attachEvent( "on" + event_name, observer ); 
		}
	}	
	
	///finds the position of the element relative to the page
	this.pageOffsetLeft = function(el){
		var ol=el.offsetLeft;
		while((el=el.offsetParent) != null)
			ol += el.offsetLeft;
		return ol + el;
	}

	///finds the position of the element relative to the page
	this.pageOffsetTop = function(el) {
		var ot=el.offsetTop;
		while((el=el.offsetParent) != null)
			ot += el.offsetTop;
		return ot;
	}

	//provides a cross-browser compatible way to find the document height
	this.docHeight=function(){
	
		var pageWidth;
		var pageHeight;
		
		if( window.innerHeight && window.scrollMaxY ) {
			// Firefox 
			pageWidth = window.innerWidth + window.scrollMaxX;
			pageHeight = window.innerHeight + window.scrollMaxY;
		}
		else if( document.body.scrollHeight > document.body.offsetHeight ) {
			// all but Explorer Mac
			pageWidth = document.body.scrollWidth;
			pageHeight = document.body.scrollHeight;
		}
		else { 
			// works in Explorer 6 Strict, Mozilla (not FF) and Safari
			pageWidth = document.body.offsetWidth + document.body.offsetLeft; 
			pageHeight = document.body.offsetHeight + document.body.offsetTop; 
		}
		
		return pageHeight;
	}

	//provides a cross-browser compatible way to find the HTML view port height
	this.windowHeight=function(){
	
		var windowWidth;
		var windowHeight;
		
		if( window.innerHeight) {
			// Provided by most browsers, but importantly, not Internet Explorer.
			windowWidth = window.innerWidth;
			windowHeight = window.innerHeight;
		}
		else if( document.body.clientHeight) {
			// Provided by many browsers, including Internet Explorer.
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}
		else if(document.documentElement.clientHeight){
			// Provided by most DOM browsers, including Internet Explorer
			windowWidth = document.body.offsetWidth + document.body.offsetLeft; 
			windowHeight = document.body.offsetHeight + document.body.offsetTop; 
		}
		else {
			alert("Error calling matweb.windowHeight(): Unsupported browser");
		}
		
		return windowHeight;
	}

	//provides a cross-browser compatible way to find the HTML view port width
	this.windowWidth=function(){
	
		var windowWidth;
		
		if( window.innerHeight) {
			// Provided by most browsers, but importantly, not Internet Explorer.
			windowWidth = window.innerWidth;
		}
		else if( document.body.clientHeight) {
			// Provided by many browsers, including Internet Explorer.
			windowWidth = document.body.clientWidth;
		}
		else if(document.documentElement.clientHeight){
			// Provided by most DOM browsers, including Internet Explorer
			windowWidth = document.body.offsetWidth + document.body.offsetLeft; 
		}
		else {
			alert("Error calling matweb.windowWidth(): Unsupported browser");
		}
		
		return windowWidth;
	}
	
	//provides a cross-browser compatible way to center an element in the WINDOW/SCREEN (not the full document).
	this.center = function(el){
	
		el = $(el);// dependency --> prototype.js
	
		if(!el){
			alert("Error in matweb.center() function. A non-existant element was passed.");
			return;
		}

		var my_width	= 0;
		var my_height = 0;

		if ( typeof( window.innerWidth ) == 'number' ){
				my_width	= window.innerWidth;
				my_height = window.innerHeight;
		}else if ( document.documentElement && 
						 ( document.documentElement.clientWidth ||
							 document.documentElement.clientHeight ) ){
				my_width	= document.documentElement.clientWidth;
				my_height = document.documentElement.clientHeight;
		}
		else if ( document.body && 
						( document.body.clientWidth || document.body.clientHeight ) ){
				my_width	= document.body.clientWidth;
				my_height = document.body.clientHeight;
		}

		el.style.position = 'absolute';
		el.style.zIndex	 = 99;

		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;
		}

		var elementDimensions = el.getDimensions(el); // dependency-->prototype.js
		var setX = ( my_width	- elementDimensions.width	) / 2;
		var setY = ( my_height - elementDimensions.height ) / 2 + scrollY;
		
		setX = ( setX < 0 ) ? 0 : setX;
		setY = ( setY < 0 ) ? 0 : setY;

		el.style.left = setX + "px";
		el.style.top	= setY + "px";
		
	}

	var _OldColor;
	
	this.DataRow_OnMouseOver = function(row){
		//alert(row.style.backgroundColor);
		//alert(row.className);
		_OldColor = row.style.backgroundColor;
		row.style.backgroundColor="#CCCCDD";
	}

	this.DataRow_OnMouseOut = function(row){
		row.style.backgroundColor=_OldColor;
	}

	
// ================================================================================================
// END OF _matweb() object 
// ================================================================================================

}	//CLOSE OBJECT FUNCTION - CAREFULL, DO NOT DELETE THIS CLOSING BRACKET
