﻿/*
	Util namespace (
	M-XP211234:2012-01-03
*/
Util = {
/*=======================================================================*/

	kDotNETIDSep: "_",
	kTRAltRowColor: "#E8E8E8",
	gApplNameEmpty: false,
	gConsoleGroupPrefix: "",
	gAppSessionData: undefined, //assoc. array of JSON data, for a give /Appl, (or global?)

/*-----------------------------------------------------------------------*/

	addEvent : function(aObj, aEventName, aFunc) {
		var aOldEventFunc = aObj[aEventName];
		if (typeof aObj[aEventName] != 'function') {
			aObj[aEventName] = aFunc;
		}
		else {
			aObj[aEventName] = function(e) {
				if (aOldEventFunc) {
					aOldEventFunc(e);
				}
				return aFunc(e);
			}
		}
	},

/*-----------------------------------------------------------------------*/

	addWindowOnLoad: function(aFunc) {
		Util.addEvent(window, "onload", aFunc);
	},

/*-----------------------------------------------------------------------*/

	getEvent: function(e) {
		if (window.event != null) {
			e = window.event;
		}
		
		return e;
	},

/*-----------------------------------------------------------------------*/
/*
	Assumes e is valid; getEvent() already called
*/
	getEventEle: function(e) {
		var aEle;
		
		if (e.target) {
			aEle = e.target;
		}
		if (e.srcElement) {
			aEle = e.srcElement;
		}
		
		if (aEle != null && aEle.nodeType==3) // defeat Safari bug
			aEle = aEle.parentNode; 

		return aEle;
  },

/*-----------------------------------------------------------------------*/

	getEventKey: function(e) {
		if (window.event != null) {
			return window.event.keyCode;
		}
		else {
			return e.which;
		}
		
		return e;
	},

/*=======================================================================*/

	applNameFromLocation: function() {
		/*Util.YUIDebug.log("host: " + location.host);
		Util.YUIDebug.log("pathname: " + location.pathname);*/
		
		if (!Util.gApplNameEmpty) {
			var i = document.location.pathname.indexOf("/", 1);
			if (i == -1) return document.location.pathname;
			return document.location.pathname.substr(0, i);
		}
		else {
			return "";
		}
	},

/*-----------------------------------------------------------------------*/

	buildRootURL: function(aURL) {
		if (aURL.indexOf(".") != 0) {
			//Util.YUIDebug.log("url: " + location.host + Util.applNameFromPathName(aURL) + aURL);
			return location.protocol + "//" + location.host + Util.applNameFromLocation() + aURL;
		}
		return aURL;
	},
	
/*-----------------------------------------------------------------------*/
/*
	Return number of milliseconds since midnight of January 1, 1970 according to universal time.
	Guranteed to be unique.
*/
	uniqueURLValue: function() {
		var aDate = new Date();
		return Date.UTC(aDate.getFullYear(), aDate.getMonth(), aDate.getDate(), 
			aDate.getHours(), aDate.getMinutes(), aDate.getSeconds());
	},
	
/*=======================================================================*/

	initNamespace: function(aNameSpaceStr) {
		try {
			if (eval(aNameSpaceStr)) {}
		}
		catch(e) {
			eval(aNameSpaceStr + "= new Object()");
			//eval(aNameSpaceStr + ".foo = 'Inited'");
		}
	},
	
/*-----------------------------------------------------------------------*/

	ensureNamespacePath: function(aNameSpaceStr) {
		var aPaths = aNameSpaceStr.split(".");
		
		Util.initNamespace(aPaths[0]);
		
		for (var i = 1; i < aPaths.length; i++) {
			if (!eval(aPaths[0]+"."+aPaths[i]))
				eval(aPaths[0]+"."+aPaths[i]+" = new Object()");
				
			aPaths[0] += "."+aPaths[i]
		}
	},
	
/*=======================================================================*/

	preventDefault: function(e) {
		if (e && e.preventDefault)
			e.preventDefault();
		return false;
	},
	
/*-----------------------------------------------------------------------*/

	passKeyToFunc: function(aSrcInputEle, aKeyCds, aCallbackFunc) {
		var aFunc = function(e) {
			var aKey = Util.getEventKey(e);
			if (aKey in(aKeyCds)) {
				aCallbackFunc(e);
				return false; //kills the beep in IE
			}
		}
		
		Util.addEvent(aSrcInputEle, 'onkeydown', aFunc);
	},
	
/*-----------------------------------------------------------------------*/

	passEnterKeyTo: function(aSrcInputID, aDestInputID) {
		//alert("passEnterKeyTo");
		var aSrcInputEle = document.getElementById(aSrcInputID);
		if (aSrcInputEle == null)
			return;
		var aDestInputEle = document.getElementById(aDestInputID);
		if (aDestInputEle == null)
			return;
		
		var aCallbackFunc = function() {eval(decodeURIComponent(aDestInputEle.href));};
			
		Util.passKeyToFunc(aSrcInputEle, {13:0}, aCallbackFunc);
	},

/*-----------------------------------------------------------------------*/

	//retrieves only the text of aEle, if it exists, no children
	getText: function(aEle) {
		if (!aEle || !aEle.firstChild || !aEle.firstChild.nodeType == 3)
			return null;
		return aEle.firstChild.data;
	},
	
/*=======================================================================*/
/*
	Round aInt to the nearest increment aInc.
	7 to increment of 5 = 5
	8 to increment of 5 = 10
*/
	roundIntToIncrement: function(aInt, aInc) {
		return Math.floor((aInt + Math.floor(aInc / 2)) / aInc) * aInc;
	},
	
/*=======================================================================*/
/*
	returns aObj.mText, aObj.mID
	built-in RegExp assumes [value] ([id])
	* if id does not need to be numeric, use .+ (rather than [0-9]+
*/
	parseTextAndID: function(aValue, aProps) {
		if (aProps) {
			//could get RegEx from aProps
		}
		
		var aResult = new Object();

		var aRegEx = / \([0-9]+\)$/;
		//var aRegEx = new RegExp(' \\([0-9]+\\)$');
		aResult.mID = aRegEx.exec(aValue);
		if (!aResult.mID)
			return null;
		
		aResult.mText = RegExp.leftContext;
		
		aRegEx = /[0-9]+/;
		aResult.mID = aRegEx.exec(aResult.mID);
		
		return aResult;
	},

/*-----------------------------------------------------------------------*/
/*
	finds a URL param
*/
	parseURLParam: function(aURLStr, aParamName) {
		if (!aURLStr)
			aURLStr = window.location.search;
		var aSearchStr = aParamName+"=";
		var aSIndex = aURLStr.indexOf(aSearchStr);
		var aEIndex = aURLStr.indexOf("&", aSIndex+aSearchStr.length);
		var aResult = null;
		if (aEIndex >= 0)
			aResult = aURLStr.substring(aSIndex+aSearchStr.length, aEIndex);
		else
			aResult = aURLStr.substring(aSIndex+aSearchStr.length);
		
		return aResult;
	},

/*-----------------------------------------------------------------------*/
/*
	aProps.mThousSep: thousands separators
	aProps.mNegInParen: boolean to put neg in parens
	aProps.mDec
		.mNum, mTrail0s
*/
	formatNumber: function(aNum, aProps) {
		if (aProps.mDec) {
			aNum = aNum.toFixed(aProps.mDec.mNum);
		}

		var aNumStr = new String(aNum);
		
		if (aProps.mThousSep) {
			var aIndex = aNumStr.indexOf(".");
			if (aIndex < 0)
				aIndex = aNumStr.length;

			aIndex -= 3;
			while (aIndex >= (aNum < 0 ? 2 : 1)) {
				aNumStr = aNumStr.substring(0, aIndex) + aProps.mThousSep +
							aNumStr.substring(aIndex, aNumStr.length)
				aIndex -= 3;
			}		
		}
		
		if (aProps.mNegInParen) {
			if (aNum < 0)
				aNumStr = "(" + aNumStr.substring(1,aNumStr.length) + ")";
		}
		
		return aNumStr;
	},

/*-----------------------------------------------------------------------*/

	abbreviateStr: function(aStr, aMaxChars) {
		if (aStr.length <= aMaxChars)
			return aStr;
		
		aMaxChars = (aMaxChars-2) / 2;
		return aStr.substr(0, aMaxChars) + ".." +
				aStr.substr(aStr.length-aMaxChars);
	},
	
/*-----------------------------------------------------------------------*/

	clearFileUploadText: function(aFileUpload, aAlertMessage) {
		if (aAlertMessage)
			alert(aAlertMessage);

		try {
			aFileUpload.value = "";
			if (aFileUpload.value == "")
				return;

			//value is read-only, so we will clone/replace the node:
			var aFileUpload2 = aFileUpload.cloneNode(false);
			if (aFileUpload2) {
				aFileUpload2.onchange= aFileUpload.onchange;
				aFileUpload.parentNode.replaceChild(aFileUpload2, aFileUpload); 
			}
		}
		catch (aErr) {

		}
	},

/*=======================================================================*/

	countOfProps: function(aObj, aMax) {
		var aCount = 0;

		if (aObj) {
			for (aProp in aObj) {
				if (!aObj[aProp]) //hasOwnProperty
					continue;
				aCount++;
				if (aCount >= aMax)
					break;
			}
		}

		return aCount;
	},

/*=======================================================================*/

	console: function() {
		try {
			return console;
		}
		catch (e) {
			//Util.gConsole = null;
			return null;
		}
	},

/*-----------------------------------------------------------------------*/

	consoleLog: function(aMsg) {
		try {
			if (Util.console())
				Util.console().log(Util.gConsoleGroupPrefix+aMsg);
		}
		catch (e) {
		}
	},

/*-----------------------------------------------------------------------*/

	consoleInfo: function(aMsg) {
		try {
			if (Util.console())
				Util.console().info(Util.gConsoleGroupPrefix+aMsg);
		}
		catch (e) {
		}
	},

/*-----------------------------------------------------------------------*/

	consoleWarn: function(aMsg) {
		try {
			if (Util.console())
				Util.console().warn(Util.gConsoleGroupPrefix+aMsg);
		}
		catch (e) {
			Util.consoleInfo(Util.gConsoleGroupPrefix+"Warn: " + aMsg);
		}
	},

/*-----------------------------------------------------------------------*/

	consoleError: function(aMsg) {
		try {
			if (Util.console())
				Util.console().error(Util.gConsoleGroupPrefix+aMsg);
		}
		catch (e) {
			Util.consoleInfo(Util.gConsoleGroupPrefix+"Err: " + aMsg);
		}
	},

/*-----------------------------------------------------------------------*/

	consoleGroup: function(aTitle) {
		try {
			if (aTitle) {
				if (Util.console())
					Util.console().group(aTitle);
			}
			else {
				Util.console().groupEnd();
			}
		}
		catch (e) {
			if (aTitle) {
				Util.consoleInfo(Util.gConsoleGroupPrefix+"===== " + aTitle + " =====");
				Util.gConsoleGroupPrefix += "\t";
			}
			else {
				if (Util.gConsoleGroupPrefix.length > 0)
					Util.gConsoleGroupPrefix = Util.gConsoleGroupPrefix.substr(0, Util.gConsoleGroupPrefix.length-1);
			}
		}
	},

/*=======================================================================*/
//Application Storage
/*=======================================================================*/

	getAppSessData: function(aAppName) {
		if (!aAppName)
			aAppName = Util.applNameFromLocation();
		if (!Util.gAppSessionData)
			Util.gAppSessionData = new Object();
		if (!Util.gAppSessionData[aAppName]) {
			var aAppSessData = sessionStorage.getItem(aAppName);
			if (!aAppSessData) {
				Util.gAppSessionData[aAppName] = new Object();
			}
			else {
				Util.gAppSessionData[aAppName] = JSON.parse(aAppSessData);
			}
		}

		return Util.gAppSessionData[aAppName];
	},

/*-----------------------------------------------------------------------*/

	getAppSessObj: function(aName, aCrFlag, aAppName) {
		var aObj = Util.getAppSessData(aAppName)[aName];
		if (aObj == null && aCrFlag) {
			aObj = new Object();
			Util.getAppSessData(aAppName)[aName] = aObj;
		}
		return aObj;
	},

/*-----------------------------------------------------------------------*/

	setAppSessData: function(aAppName) {
		if (!Util.gAppSessionData)
			return;
		if (!aAppName)
			aAppName = Util.applNameFromLocation();
		if (Util.gAppSessionData[aAppName]) {
			sessionStorage.setItem(aAppName, JSON.stringify(Util.gAppSessionData[aAppName]));
		}
		else {
			//remove it?
		}
	},

/*-----------------------------------------------------------------------*/
//LocalStorage
//unimplemented
/*-----------------------------------------------------------------------*/
//Cookie
	getAppSessCookieData: function() {
	},
	getAppSessCookieObj: function(aName, aCrFlag) {
	},
	setAppSessCookieObj: function(aName, aObj) {
	},
	delAppSessCookieObj: function(aName) {
	},

/*=======================================================================*/
//functions requiring jQuery
/*=======================================================================*/

	jqDisableSelectOption: function(aSelEle, aValues, aMsg) {
		if (aSelEle == null)
			return;
		
		aSelEle.mCurSelIndex = aSelEle.selectedIndex;
		for (var i = 0; i < aValues.length; i++)
			$(aSelEle).find(">option[value='"+aValues[i]+"']").attr("disabled", "disabled");

		$(aSelEle).change(function(event) {
			var aSelValue = this.options[this.selectedIndex].value;
			//alert(this.selectedIndex + " - " + this.mCurSelIndex);
			for (var i = 0; i < aValues.length; i++) {
				if (aSelValue == aValues[i]) {
					alert(aMsg +
						"\r\rIf you migrate away from old, unsecure, and non-compliant versions of Internet Explorer, the interface you see will improve.");
					
					this.selectedIndex = this.mCurSelIndex;
					break;
				}
			}
			
			this.mCurSelIndex = this.selectedIndex;
		});
	},

/*-----------------------------------------------------------------------*/

	parseResponseParts: function (aResponseTxt) {
		var aResults = new Object();
		var aDataParts = aResponseTxt.split("[~]");

		for (var aDataPart = 0; aDataPart < aDataParts.length; aDataPart += 2) {
			aDataParts[aDataPart] = $.trim(aDataParts[aDataPart]);
			if (aDataParts[aDataPart] == "")
				break;
			var aDataSpec = aDataParts[aDataPart].split(":");
			if (aDataSpec.length > 1) {
				if ($.trim(aDataSpec[1]).toLowerCase() == "xml")
					aResults[aDataSpec[0]] = $.parseXML(aDataParts[aDataPart+1]);
				else if ($.trim(aDataSpec[1]).toLowerCase() == "json")
					aResults[aDataSpec[0]] = JSON.parse(aDataParts[aDataPart+1]);
				else {
					//other types?
				}
			}
			//fall through to text
			if (!aResults[aDataSpec[0]])
				aResults[aDataSpec[0]] = aDataParts[aDataPart+1];
		}

		return aResults;
	}

/*=======================================================================*/
} //Util namespace

/*=======================================================================*/
/*
	jQuery extension to parse XML (plugin CONVERT XML TO STRING)
*/
/*
	jQuery.fn.xml = function(all) {
      
		var aResult = "";
  
		//Anything to process ?
		if (this.length)
			//"object" with nodes to convert to string  
			(
				((typeof all != 'undefined') && all ) ?
					//all the nodes 
					this 
				:
				//content of the first matched element 
				jQuery(this[0]).contents()
			)
			//convert node(s) to string  
			.each(function() {
				aResult += window.ActiveXObject ?//==  IE browser ?
					//for IE
					this.xml
				:
					//for other browsers
					(new XMLSerializer()).serializeToString(this)
				;
			}); 
    
		return aResult;		
	}
*/

