/* Support Library for Client side UI and Validation*/
var COL_SEP = "^";
var ROW_SEP = "|";
var _MainFrame = null;
var jsg_DebugFlag = false; // Debug flag
var jsg_winDebugConsole = null;
var _debugDocOpened = false;
var _debugMsg = "";
var jsg_iDebugCount = 0;
var _timeAtStartup = new Date();

// Browser check variables
var jsg_IsIE5OrAbove = false;
var jsg_IsIE = false;
var jsg_IsNS = false;
var jsg_IsNS6OrAbove = false;
var jsg_fVer = 0.0;  // Version number NS or IE
//******************************************************************************
function Utils_checkBrowserVersion()
//******************************************************************************
{
	var ver = 	navigator.appVersion; 
	var list = ver.split(/;/);
	var temp, temp2;
	for (var i = 0 ; i < list.length; i++)
	{
		temp = list[i]; 
		if (temp.search(/MSIE/) >= 0 ) 
		{
			jsg_IsIE = true;
			var list2 = temp.split(/ /); 
			// We are assming the format is MSIE X.Y where X.Y is the version number
			if (list2.length > 0) 
			{
				jsg_fVer = parseFloat(list2[1]); 
				if (jsg_fVer >= 5.0 )
					jsg_IsIE5OrAbove = true; 
			}
			break;
		}
	} 
	if (document.layers ) jsg_IsNS = true;
	if (document.getElementById&&!document.all ) jsg_IsNS6OrAbove = true;
} 

function debugMsg(msg)
{
	if (! jsg_DebugFlag) 
		return;
	var d = new Date();
	if ((jsg_winDebugConsole == null) || (jsg_winDebugConsole.closed) )
	{
		jsg_winDebugConsole = window.open("", "Debug" + jsg_iDebugCount++ ,"width=600,height=300,resizable=yes,status=yes,scrollbars=yes");
		jsg_winDebugConsole.document.open("text/html");
		jsg_winDebugConsole.document.write("<html><head><title>VT Debugging Window</title></head><body>");
		jsg_winDebugConsole.document.writeln("<br><b>" + _timeAtStartup.toLocaleString() + "</b> - Startup");
		millis = d.getTime();  // ar startup
	}
	jsg_winDebugConsole.document.writeln("<br><b>" + (d.getTime() - _timeAtStartup.getTime() ) + "</b> - " + msg);
	jsg_winDebugConsole.document.bgColor = "lightyellow";
	jsg_winDebugConsole.scrollBy(0,1000);
}

function UtilsLib_init()
{
	var winLevel = 0;
	if (_MainFrame != null)
		return;
	if (this == top)
	{
		_MainFrame = this;
		return;
	}
	if (window.parent._MainFrame)
	{
		_MainFrame = window.parent; 
		winLevel = 1;
	}
	else if (window.opener._MainFrame)
	{
		_MainFrame = window.opener._MainFrame;
		winLevel = 2;
	}
	else if (window.opener.parent._MainFrame)
	{
		_MainFrame = window.opener.parent._MainFrame;
		winLevel = 3;
	}
	else if (window.opener.opener.opener._MainFrame)
	{
		_MainFrame = window.opener.opener.opener._MainFrame;
		winLevel = 4;
	}
	else
	{
		alert("Too many windows are open. Please close all windows and restart VoyagerTrack"); 
		winLevel = 5;
	}
	if (_MainFrame == null)
	{
		alert("Error (13a): Setup error. Please contact support");
	}
}
//******************************************************************************
function UtilsLib_addPopupWindow(popup)
//******************************************************************************
{
	if (_MainFrame)
		_MainFrame.addNewMTPopup(popup);
	else
		alert ("Error (13a): Setup error. Please contact support"); 

}
//******************************************************************************
function UtilsLib_debugMsg(msg)
//******************************************************************************
{
	if (_MainFrame != null)
		_MainFrame.debugMsg(msg);
	else
		alert ("Error (13b): Setup error. Please contact support. Message For Support: " + msg); 

}
//******************************************************************************
function UtilsLib_cleanupPopups()
//******************************************************************************
{
	alert("Closing popups");
}
//******************************************************************************
function UtilsLib_getSessionID()
//******************************************************************************
{
	if (_MainFrame != null && (_MainFrame.jsg_SessionID ) )
		return _MainFrame.jsg_SessionID; 
	else
	{
		alert ("Error (13c): Setup error. Please contact support"); 
		return "Invalid";
	}
}
//******************************************************************************
function UtilsLib_getDebugFlag()
//******************************************************************************
{
	if (_MainFrame != null && (_MainFrame.jsg_DebugFlag == true ) )
		return "1"; 
	else
		return "0";
}
//******************************************************************************
function UtilsLib_getTerminalName(strSiteID)
//******************************************************************************
{
	if (_MainFrame != null && (_MainFrame.jsg_CurrentSiteName ) )
		return _MainFrame.jsg_CurrentSiteName.replace("&nbsp;", " "); 
	else
	{
		alert ("Error (13d): Setup error. Please contact support"); 
		return strSiteID;
	}
}
//******************************************************************************
function UtilsLib_getSiteID()
//******************************************************************************
{
	if (_MainFrame != null && (_MainFrame.jsg_CurrentSiteID ) )
		return _MainFrame.jsg_CurrentSiteID; 
	else
	{
		alert ("Error (13e): Setup error. Please contact support"); 
		return "";
	}
}

//******************************************************************************
function UtilsLib_QueryString(strParam)
//******************************************************************************
{ 
	var qStr = window.location.search; 
	var qStrArray; 
	if (qStr.length > 1) 
	{ 
		qStr = qStr.substring(1, qStr.length); 
		qStrArray = qStr.split("&"); 
		for (var i = 0; i < qStrArray.length; i++) 
		{
			var qVars = new Array; 
			var idx = qStrArray[i].indexOf("="); 
			qVars[0] = qStrArray[i].substring(0, idx); 
			qVars[1] = qStrArray[i].substring(idx + 1); 
			if (qVars[0].toLowerCase()==strParam.toLowerCase())
			{ 
				return qVars[1]; 
			} 
		} 
	} 
	return ""; 
} 
//******************************************************************************
function UtilsLib_openCalendar(o,strProp,oBtn){
//******************************************************************************
	var sDate="";
	var bReturn=false;	
	var oParent = oBtn.offsetParent; 
	var ileft = oBtn.left; 
	var itop = oBtn.top;	
	var sParam = "dialogWidth=320px;dialogHeight=365px;dialogLeft=" + ileft + "px;dialogTop=" 
		+ itop + "px;status=no;location=center;scroll=no;resizable=no;help=no;edge=sunken;unadorned=off;"		
	sDate = showModalDialog("/DatePopUp.htm","",sParam);
		
	if ( sDate != "" && sDate != null && sDate !="undefined"){
		eval("o." + strProp + "=sDate;" );
		if(strProp=="value") o.focus();
		else oBtn.focus();
		bReturn=true;
	}

	return bReturn;
}
//******************************************************************************
function UtilsLib_checkDateRange(strFromDate, strToDate, strFromTime, strToTime)
// Returns 0 if equal
// Returns > 1 if To date and time is grater than from date (normal case)
// Return < 1 if to date and time is less than from date time
// Returns -2 if invalid input params
// If fromTime or ToTime are invalid, zero min and hours are used.
//******************************************************************************
//		strFromDate, strToDate formatted as mm/dd/yy
//		strFromTime, strToTime formatted as HH:MM
{
//	alert (strFromDate+ "/" +  strToDate + "/" +strFromTime + "/" + strToTime);
	var bRet = -2;
	var compare = /^\s*(\d{1,2})\/(\d{1,2})\/(\d{1,4})\s*$/;
	var arrFromDate = strFromDate.match(compare);
	var arrToDate = strToDate.match(compare);
	var oFromDate, oToDate;
	var intMonth;
	var intDay;
	var intYear;
	var intHour = 0;
	var intMin = 0;
	var oFromTimeFields = strFromTime.split(':'); 
	var oToTimeFields = strToTime.split(':'); 
	if (arrFromDate != null && arrToDate != null)
	{
		intMonth = parseInt(arrFromDate[1],10);
		intDay = parseInt(arrFromDate[2],10);
		intYear = parseInt(arrFromDate[3],10);
		if (oFromTimeFields.length == 2)
		{
			intHour = parseInt (oFromTimeFields[0],10);
			intMin = parseInt (oFromTimeFields[1],10);
		} 
		oFromDate = new Date(intYear + 2000,intMonth -1, intDay, intHour,intMin,0,0);
		intMonth = parseInt(arrToDate[1],10);
		intDay = parseInt(arrToDate[2],10);
		intYear = parseInt(arrToDate[3],10);
		intHour = 0;
		intMin = 0;
		if (oToTimeFields.length == 2)
		{
			intHour = parseInt (oToTimeFields[0],10);
			intMin = parseInt (oToTimeFields[1],10);
		}
		oToDate = new Date(intYear + 2000,intMonth -1, intDay, intHour,intMin,0,0);
		bRet = oToDate.getTime() - oFromDate.getTime();
	}
	return bRet;
}
// returns true if OK
//******************************************************************************
function UtilsLib_checkTextFieldForBlanks(strTextFieldValue, strFieldName, bAlert)
//******************************************************************************
{
	if (strTextFieldValue.replace(/\s*(\w*)\s*/g, "$1") == "")
	{
		if (bAlert)
			alert("Please enter " + strFieldName + ".");
		return false;
	}
	else
		return true;
}
//******************************************************************************
function UtilsLib_validateDate(txtDateField)
{
	return UtilsLib_validateDateMaxPastDays(txtDateField,0);
}

//CR 14035
//******************************************************************************
function UtilsLib_validateFieldDate(txtDateField)
//******************************************************************************
{
    var iMaxPastDaysFromToday;
    iMaxPastDaysFromToday = 0;
    
	var dates = new String();
	var inputdate = new Date(txtDateField.value);
	var compare = /^\s*(\d{1,2})\/(\d{1,2})\/(\d{1,4})\s*$/;
	var result = new Array();
	var intMonth;
	var intDay;
	var intYear;

	// validate input date in mm/dd/yy format using regular expression
	dates = txtDateField.value;
	result = dates.match(compare);
		
	if (result != null)
	{
		intMonth = parseInt(result[1],10);
		intDay = parseInt(result[2],10);
		intYear = parseInt(result[3],10);
		// check the month within 1 to 12
		if ( !(intMonth <= 12 && intMonth >=1) )
			{
				//alert("Please enter a valid date (mm/dd/yy).");
				txtDateField.focus();
				return false;
			}

		// check the day within 1 to 31
		if ( !(intDay <= 31 && intDay >=1) )
			{
				//alert("Please enter a valid date (mm/dd/yy).");
				txtDateField.focus();
				return false;
			}
		
		// check the year within range
		if ( !(intYear <= 3000 && intYear >=0) )
			{
				//alert("Please enter a valid date (mm/dd/yy).");
				txtDateField.focus();
				return false;
			}
	}
	else
	{		// if format is not correct, output alert message.
			//alert("Please enter a valid date (mm/dd/yy).");
			txtDateField.focus();
			return false;
	}
	// check whether each month has 31 or not
	// also check the days in February.	
	inputdate.setYear((intYear >= 80) ? intYear : (intYear + 2000));
	inputdate.setMonth(intMonth-1);
	if (intDay == 31)
	{
		if(	  intMonth != 1 
 			&&intMonth != 3
			&&intMonth != 5
			&&intMonth != 7
			&&intMonth != 8
			&&intMonth != 10
			&&intMonth != 12 )

		{
			// if format is not correct, output alert message.
			//alert("Please enter a valid date (mm/dd/yy).");
			txtDateField.focus();
			return false;
		}
	}
	if(intMonth == 2)
	{
		// February has 29 days in any year evenly divisible by four,
		// EXCEPT for centurial years which are not also divisible by 400.

		var year = inputdate.getFullYear();
		var daysInFeb = ( ((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0) ) ) ? 29 : 28 )

		if (intDay > daysInFeb)
		{
			// if format is not correct, output alert message.
			//alert("Please enter a valid date (mm/dd/yy).");
			txtDateField.focus();
			return false;
		}
	}	
	
	// check max days 
	if (iMaxPastDaysFromToday > 0)
	{
		var oNow = new Date();
		var oNowCompare = new Date(oNow.getFullYear(), oNow.getMonth(),oNow.getDate(), 0,0,0,0);
		var oInputDate = new Date((intYear + 2000), 
			intMonth-1, intDay, 0,0,0,0);
		var iDiffDays = (oNowCompare.getTime() - oInputDate.getTime() )/(1000 * 3600 * 24); 
		if (Math.floor(iDiffDays) > iMaxPastDaysFromToday)
		{
			//alert("Please enter a date that is not more than " + iMaxPastDaysFromToday + " days in the past.");
			txtDateField.focus();
			return false;	
		}
	}	
	return true;
}


//******************************************************************************
function UtilsLib_validateDateMaxPastDays(txtDateField, iMaxPastDaysFromToday )
// 0 MaxPastDays means no check for past 
//******************************************************************************
{
//	alert ( lowerlimit + " - " + txtDateField.value);
	var dates = new String();
	var inputdate = new Date(txtDateField.value);
	var compare = /^\s*(\d{1,2})\/(\d{1,2})\/(\d{1,4})\s*$/;
	var result = new Array();
	var intMonth;
	var intDay;
	var intYear;

	// validate input date in mm/dd/yy format using regular expression
	dates = txtDateField.value;
	result = dates.match(compare);
		
	if (result != null)
	{
		intMonth = parseInt(result[1],10);
		intDay = parseInt(result[2],10);
		intYear = parseInt(result[3],10);
		// check the month within 1 to 12
		if ( !(intMonth <= 12 && intMonth >=1) )
			{
				alert("Please enter a valid date (mm/dd/yy).");
				txtDateField.focus();
				return false;
			}

		// check the day within 1 to 31
		if ( !(intDay <= 31 && intDay >=1) )
			{
				alert("Please enter a valid date (mm/dd/yy).");
				txtDateField.focus();
				return false;
			}
		
		// check the year within range
		if ( !(intYear <= 3000 && intYear >=0) )
			{
				alert("Please enter a valid date (mm/dd/yy).");
				txtDateField.focus();
				return false;
			}
	}
	else
	{		// if format is not correct, output alert message.
			alert("Please enter a valid date (mm/dd/yy).");
			txtDateField.focus();
			return false;
	}
	// check whether each month has 31 or not
	// also check the days in February.	
	inputdate.setYear((intYear >= 80) ? intYear : (intYear + 2000));
	inputdate.setMonth(intMonth-1);
	if (intDay == 31)
	{
		if(	  intMonth != 1 
 			&&intMonth != 3
			&&intMonth != 5
			&&intMonth != 7
			&&intMonth != 8
			&&intMonth != 10
			&&intMonth != 12 )

		{
			// if format is not correct, output alert message.
			alert("Please enter a valid date (mm/dd/yy).");
			txtDateField.focus();
			return false;
		}
	}
	if(intMonth == 2)
	{
		// February has 29 days in any year evenly divisible by four,
		// EXCEPT for centurial years which are not also divisible by 400.

		var year = inputdate.getFullYear();
		var daysInFeb = ( ((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0) ) ) ? 29 : 28 )

		if (intDay > daysInFeb)
		{
			// if format is not correct, output alert message.
			alert("Please enter a valid date (mm/dd/yy).");
			txtDateField.focus();
			return false;
		}
	}	
	
	// check max days 
	if (iMaxPastDaysFromToday > 0)
	{
		var oNow = new Date();
		var oNowCompare = new Date(oNow.getFullYear(), oNow.getMonth(),oNow.getDate(), 0,0,0,0);
		var oInputDate = new Date((intYear + 2000), 
			intMonth-1, intDay, 0,0,0,0);
		var iDiffDays = (oNowCompare.getTime() - oInputDate.getTime() )/(1000 * 3600 * 24); 
		if (Math.floor(iDiffDays) > iMaxPastDaysFromToday)
		{
			alert("Please enter a date that is not more than " + iMaxPastDaysFromToday + " days in the past.");
			txtDateField.focus();
			return false;	
		}
	}	
	return true;
}

//******************************************************************************
function UtilsLib_SetWaitMessage()
//******************************************************************************
{
	var oWaiter = null;
	oWaiter= document.getElementById("divWaitMessage");
	if(_MainFrame && oWaiter == null)  // 
	{
		UtilsLib_debugMsg("UtilsLib_SetWaitMessage() -> Checking MainFrame");
		if (_MainFrame.TopFrame)
			oWaiter= _MainFrame.TopFrame.document.getElementById("divWaitMessage");	
	}
	if (oWaiter == null)
	{
		UtilsLib_debugMsg ("UtilsLib_SetWaitMessage() divWaitMessage == null");
	}
	else
	{
		//UtilsLib_debugMsg ("UtilsLib_SetWaitMessage() divWaitMessage. Returned typeof: " + typeof(oWaiter));
		oWaiter.innerHTML = "<b>&nbsp;&nbsp;Please wait, your request is being processed...</b>";
		oWaiter.style.visibility = "visible"; 
	}
}
//******************************************************************************
function UtilsLib_ClearWaitMessage()
//******************************************************************************
{
	var oWaiter = null;
	oWaiter= document.getElementById("divWaitMessage");
	if(_MainFrame !=null && oWaiter == null)  // 
	{
		UtilsLib_debugMsg("UtilsLib_SetWaitMessage() -> Checking MainFrame");
		if (_MainFrame.TopFrame)
			oWaiter= _MainFrame.TopFrame.document.getElementById("divWaitMessage");	
	}
	if (oWaiter == null)
	{
		UtilsLib_debugMsg ("UtilsLib_SetWaitMessage() divWaitMessage == null");
	}
	else
	{
		//UtilsLib_debugMsg ("UtilsLib_SetWaitMessage() divWaitMessage. Returned typeof: " + typeof(oWaiter));
		oWaiter.innerHTML = "";
		oWaiter.style.visibility = "hidden"; 
	}
}
//******************************************************************************
function UtilsLib_upperCaseFormTextField (txtField)
//******************************************************************************
{
	var strValue = txtField.value;
	strValue = strValue.replace(/^\s*/, "");
	strValue = strValue.replace(/\s+$/g, "");
	strValue = strValue.replace(/\xA0/g, "");
	strValue = strValue.toUpperCase();
	txtField.value = strValue;		
}

// returns true if OK
//******************************************************************************
function UtilsLib_checkTextFieldForBlanks(strTextFieldValue, strFieldName, bAlert)
//******************************************************************************
{
	if (strTextFieldValue.replace(/\s*(\w*)\s*/g, "$1") == "")
	{
		if (bAlert)
			alert("Please enter " + strFieldName + ".");
		return false;
	}
	else
		return true;
}
//******************************************************************************
function UtilsLib_OnHelpPrint()
//******************************************************************************
{
	if (_MainFrame != null)
		_MainFrame.OnHelp('print');
	else
		alert("Error (13f): Setup error. Please contact support");
}

function UtilsLib_SetWaitCursor()
{
	try
	{
		document.body.style.cursor ="wait";	
	}
	catch(e)
	{
	}
	
}
function UtilsLib_SetDefaultCursor()
{
	try
	{
		document.body.style.cursor ="default";
	}
	catch(e)
	{
	}
}
// 
function UtilsLib_ValidateContainers(strCntrlist, txtField)
{

	if (strCntrlist.replace(/\s*(\w*)\s*/g, "$1") == "")
	{
		alert("Please enter container number(s).");
		txtField.focus();
		return false;
	}

	strCntrlist = strCntrlist.toUpperCase();
	txtField.value = strCntrlist;
	var arrCntrlist = strCntrlist.split(/\n/);
						
	var temp;
	for (var i = 0 ; i < arrCntrlist.length; i++)
	{
		temp = arrCntrlist[i];
		//temp = temp.replace(/^\s*(\w*)\s*$/g, "$1");
		temp = temp.replace(/^\s*/, "");
		temp = temp.replace(/\s+$/g, "");
		temp = temp.replace(/\xA0/g, "");
		if (temp == "") continue;
		if (!temp.match(/^\s*[A-Za-z]{4}\d{6}(\d{1}?|(-\d{1})?)\s*$/))
		{
			alert("Container number " + temp + " is invalid. Please enter container number(s) with 4 letters, 6 digits and an optional check digit (for example, ABCU123456 or ABCU1234567).");
			txtField.focus();
			return false;
		}	
	}		
	return true;
}
/* document.onkeydown = mykeyDownhandler;

function mykeyDownhandler() {
    if (window.event && window.event.keyCode == 8) {
        // try to cancel the backspace
        window.event.cancelBubble = true;
        window.event.returnValue = false;
        return false;
    }
}

*/
var g_iErrorCount = 0;
function UtilsLib_ErrorReport(msg, url, line)
{
	var w = window.open("", "Error"+g_iErrorCount++, "resisable,status,width=625,height=400");
	d = w.document;
	d.write('<HTML><HEAD>');
	d.write('\n<link rel="stylesheet" type="text/css" href="/Framework/body.css"> ');
	d.write('\n</head><body><h1>VoyagerTrack Error Report</h1>');
	d.write('\n<div class=Main><br><b>Message: </b>' + msg);
	d.write('\n<br><b>URL: </b>' + url);
	d.write('\n<br><b>Line: </b>' + line);
	d.write('\n<br><b>Browser Version: </b>' + navigator.userAgent);
	d.write('\n</div>');
	d.write('\n<br><div align=center><input type=button value="Close" onClick="self.close()"> </div>');
	d.write('\n</body></HTML>');
	
}
// Below are a list of messages displayed to the user depending on different cases.
//
// User is trying to access a feature that requires a login. 

var jsg_FeatureRequiresLoginMsg = "You need to log on to use this feature. To request an account, please use the Sign Up link."; 
var jsg_NoHelpTopicMsg = "There is no help available at this time for this feature. \nPlease check with your Site Administrator.";
var jsg_NoPermissionsMsg = "You do not have permission to use this feature in the selected site. \n\rTo update your permissions, please contact your Site Administrator."; 
var jsg_strPleaseWait = "<b>&nbsp;&nbsp;&nbsp;One moment, please...</b>"


function writetoLyr(name, message) {
    if (document.layers) {
        document.layers[name].document.close();
        document.layers[name].document.write(message);
        document.layers[name].document.close();
    } else {
        if (document.all) {
            eval("document.all." + name + ".innerHTML='" + message + "'");
        } else {
            document.getElementById(name).innerHTML = message;
        }
    }
}


window.onerror = UtilsLib_ErrorReport;
UtilsLib_init();
Utils_checkBrowserVersion();
