//******************************************************************
//* Copyright © 2008 MDi
//*
//* ClientFuncs.js - Created by MGD on 04/21/2008  
//******************************************************************

var crMsg = "Copyright © 2006 by MDi.";

var oBws = new objBrowser();

var screen_width = screen.width;
var screen_height = screen.height;

var imgNumOf = 94;
var sb_Width = 384;
var sb_Pct = (sb_Width/imgNumOf);
var oPBS;
var imgCount = 1;

var gImagePath="";	//** Global variable that must be set at the beginning of client js execution with relative path for image files.
var oReport;
var gRowsPerPage = 0;
var gSortBy = "";

//*************************************************************************************
//** These are the root Input Fieldnames for the Easy Filter By Query 
//   where the User inputs comparison values for the query. They,  more or less,
//   correspond to Columns in the OS Report list. Unfortunetely they are hardcoded at
//   this point, so are the Columns in the report itself. Perhaps in the future
//   I will implement dynamic columns report. Note that the OptiSpool server component
//   object already support a collection of Columns. Below are the corresponding
//   field names in the AS/400 Query function called by objOptiSpool.Execute("QRY-+",QryStr,,"0")
//*************************************************************************************
var anm = ["77","97","117","114","111","32 ","68","117","116","114","97"];
 
/* This Event Handler will prevent the right mouse click from launching the ContextMenu. */
/* Another reason why our application needs to stop this event is that our multi-iFrame navigation logic */
/*  uses the oncontextmenu event to comunicate between parent document and iFrame. So stopping rightclick prevents an undesired effect. */

var mStartPage="";

function getScript(url) {
	var script = document.createElement('script');
	script.type = 'text/javascript';
	script.src = url;
	document.getElementsByTagName("head")[0].appendChild(script);
}

function isIE6Filters() {
   var arVersion = navigator.appVersion.split("MSIE")
   var version = parseFloat(arVersion[1])
   if ((version >= 5.5) && (document.body.filters)) { return true; }
   return false;
}

function correctIEPNG() // correctly handle PNG transparency in Win IE 5.5 & 6.
{
   if (isIE6Filters()) 
   {
        for(var i=0; i<document.images.length; i++)
        {
            var img = document.images[i]
            var imgName = img.src.toUpperCase()
            if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
            {
                var imgID = (img.id) ? "id='" + img.id + "' " : ""
                var imgClass = (img.className) ? "class='" + img.className + "' " : ""
                var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
                var imgStyle = "display:inline-block;" + img.style.cssText 
                if (img.align == "left") imgStyle = "float:left;" + imgStyle
                if (img.align == "right") imgStyle = "float:right;" + imgStyle
                if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
                var strNewHTML = "<span " + imgID + imgClass + imgTitle
                + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
                + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
                + "(src=\'" + img.src + "\', sizingMethod='crop');\"></span>" 
                img.outerHTML = strNewHTML
                i = i-1
            }
        }
   /*          
		for(var i=0; i<arrPanels.length; i++) {
			for(var j=0; j<arrCells.length; j++) {
				var tdId = arrPanels[i] + arrPanelStyles[i] + arrCells[j];
				var oTd = document.getElementById(tdId);
				oTd.background="";
				oTd.style.backgroundRepeat="no-repeat";
				var imgName = "ie6_" + arrPanelStyles[i] + "_" + arrCells[j] + ".png";
				var strNewHTML = "<span id=\"span" + tdId + "\" style=\"" + "width:" + oTd.clientWidth + "px; height:" + oTd.clientHeight + "px; display: inline-block; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'Images/" + imgName + "\', sizingMethod='crop');\"></span>"      
				oTd.innerHTML = strNewHTML;
			}
		}
      */
   }    
}

function set_GlobalVars(formID) {

	var oFrm=get_ElementByID(formID);
	gImagePath=oFrm.ImagesPath.value;
	if (oFrm.txtRowsPerPage!=undefined) gRowsPerPage = oFrm.txtRowsPerPage.value;
	
	if (formID == "frmOptiSpoolID") {
		var oInp = get_ElementByID("optSortByID");
		gSortBy = oInp.value;
	}
}

function closeChildWindows() {

	if (window.document.all("Action").value!="viewdoc" && window.document.title=="OptiView") return false;

	if (window.top.opener.closed == true) {
		window.close(); 
	}
}

function check_ParentFrame() {
	if (window.name != "ifrmMainContent") {
		var sURL = document.location.href;

		sURL = sURL.substr(0,sURL.lastIndexOf("/")) + "/index.htm?startPage=" + document.title;
		document.location.replace(sURL);
	} else {

		var oDiv = get_ElementByID("divLoadingMsg_ID");
    	oDiv.style.visibility="hidden"; 
		var oDiv = get_ElementByID("divPageContent_ID");
    	oDiv.style.visibility="visible"; 
    	oDiv.style.display="block";    	
	}
}

function set_StartPage() {
	var qs = new QueryString();

	mStartPage = qs.get("startPage");

	if (mStartPage.trim() == "") mStartPage = "Home.htm";
	
	var iFrm = get_ElementByID("ifrmMainContent_ID");
    iFrm.style.visibility="visible"; 
	iFrm.src = mStartPage;
}

function start_EventListener() {

	//** Special note: MGD - 08/03/2006 -- I don't like this solution here to close all the child windows of the OptiViewApp parent.
	//                                     For start, this is not a truly event_Listener function. Second, Timers are evil,
	//                                     they still a lot of processing time from the Client CPU. And at last, this solution
	//                                     to close all the child windows of the Main App Interface window, does not provide a
	//                                     realtime feel for the user; when the user closes the Main Interface window, it takes
	//                                     a bit of time for the children to close, that's bad. I am afraid that reducing the time
	//                                     below from 2000 (2 seconds) won't help to improve the feel on closing the child windows and,
	//                                     it will eat-up too much javascript processing power front the rest of the App.
	//                                     In the future I want to replace this functionality with real Events raising and
	//                                     listening.

	window.setTimeout("start_EventListener();",2000);
	closeChildWindows();
}

function QueryString(qs) {
	this.params = {};
	
	if (qs == null) qs = location.href.substring(location.href.lastIndexOf("?")+1, location.href.length);
	if (qs.length == 0) return;

	var args = qs.split('&'); // parse out name/value pairs separated via &
	
// split out each name=value pair
	for (var i = 0; i < args.length; i++) {
		var pair = args[i].split('=');
		var name = decodeURIComponent(pair[0]);
		
		var value = (pair.length==2)
			? decodeURIComponent(pair[1])
			: name;
		
		this.params[name] = value;
	}
}

QueryString.prototype.get = function(key, default_) {
	var value = this.params[key];
	if (value == null || value == undefined) value = "";
	return value;
}

//document.onmousedown = checkRightClick;

document.onhelp = show_Help;

document.onkeydown = getKey;

function getKey(oEvent){

	var keyCode;
	var spcKey="";

	if (oBws.ns4) {
		keyCode = oEvent.which;
		spcKey += oEvent.modifiers & Event.CONTROL_MASK ? 'Ctrl-' : '';
		spcKey += oEvent.modifiers & Event.ALT_MASK ? 'Alt-' : '';
		spcKey += oEvent.modifiers & Event.SHIFT_MASK ? 'Shift-' : '';
		spcKey += keyCode;
	}else{
		keyCode = event.keyCode;
		spcKey += event.ctrlKey ? 'Ctrl-' : '';
		spcKey += event.altKey ? 'Alt-' : '';
		spcKey += event.shiftKey ? 'Shift-' : '';
		spcKey += keyCode;
	}
	
	//*** Lets cancel Alt+LeftArrow and Alt+RightArrow
	if (spcKey=="Alt-37" || spcKey=="Alt-37"){
		event.keyCode = 0;
		event.cancelBubble = true;
		event.returnValue = false;
		return false;
	}
	if (spcKey=="Alt-112") show_About();
	if (keyCode=="27") hide_About();
	
}

function showPage(pageName) {
    var oIfrm = get_ElementByID("ifrmMainContent_ID");
	oIfrm.src = pageName + ".htm";
}

function show_About() {
	var oDiv = get_ElementByID("divAboutPopupID");
	oDiv.style.visibility = "visible";
}

function hide_About() {
	var oDiv = get_ElementByID("divAboutPopupID");
	oDiv.style.visibility = "hidden";
}

function show_author() {
	var oDiv = get_ElementByID("lnk1");
	oDiv.style.visibility = "visible";
	oDiv.innerText = getAuthor();
	oDiv.className = "divHelpBox";
}
function hide_author() {
	var oDiv = get_ElementByID("lnk1");
	oDiv.innerText = "  ";
	oDiv.className = "psedoLink";
}


function show_Help(strBookmark) {

	if (event.type=="help") {
	
		if (event.srcElement.tagName=="APPLET") return false;

		var parentPath = "";
		if (event.srcElement.document.title == "OptiView Login") var parentPath = "OptiView_ASPWebApp/";
		if (event.srcElement.document.title == "OptiSpool Login") var parentPath = "OptiSpool_ASPWebApp/";

		var url = parentPath + "OnlineHelp/index.html"
	
		if (event.srcElement.document.title == "OptiView") var url = parentPath + "OnlineHelp/MainInterface.html";
	
		if (strHelpFile != undefined) var url = parentPath + "OnlineHelp/" + strHelpFile;

		if (strBookmark != undefined) var url = parentPath + "OnlineHelp/" + strBookmark;

		helpWin = window.open(url ,"winOnlineHelp","resizable=yes,width=1024,height=700,top=20,left=15,scrollbars=yes,menubar=no,titlebar=no,toolbar=no,status=No");
		
		helpWin.focus();
		
		event.keyCode = 0;
		event.cancelBubble = true;
		event.returnValue = false;
		return false;
	}
}

//******************************* Sample Code *******************************************
// Tutorial Source: http://www-128.ibm.com/developerworks/web/library/wa-ajaxintro1.html
//
///* Create a new XMLHttpRequest object to talk to the Web server */
//var xmlHttp = false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
//try {
//  xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
//} catch (e) {
//  try {
//    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
//  } catch (e2) {
//    xmlHttp = false;
//  }
//}
//@end @*/
//
//if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
//  xmlHttp = new XMLHttpRequest();
//}
//
//function callServer() {
//  // Get the city and state from the web form
//  var city = document.getElementById("city").value;
//  var state = document.getElementById("state").value;
//  // Only go on if there are values for both fields
//  if ((city == null) || (city == "")) return;
//  if ((state == null) || (state == "")) return;
//
//  // Build the URL to connect to
//  var url = "/scripts/getZipCode.php?city=" + escape(city) + "&state=" + escape(state);
//
//  // Open a connection to the server
//  xmlHttp.open("GET", url, true);
//
//  // Setup a function for the server to run when it's done
//  xmlHttp.onreadystatechange = updatePage;
//
//  // Send the request
//  xmlHttp.send(null);
//}
//
// function updatePage() {
//  if (xmlHttp.readyState == 4) {
//    var response = xmlHttp.responseText;
//    document.getElementById("zipCode").value = response;
//  }
//}
//
//**************************************************************************

function checkRightClick(e) {

	if (oBws.ns4 && e.which > 1) {
		alert(crMsg);
		return false;
	} else if (event.button >1) {
		event.cancelBubble=true;
		alert(crMsg);
		return false;
	}
}

function objBrowser() {
  var agent = navigator.userAgent.toLowerCase();
  this.major = parseInt(navigator.appVersion,10);
  this.minor = parseFloat(navigator.appVersion);
  this.ns = ((agent.indexOf('mozilla')!=-1) && ((agent.indexOf('spoofer')==-1) && (agent.indexOf('compatible') == -1)));
  this.ns2 = (this.ns && (this.major == 3));
  this.ns3 = (this.ns && (this.major == 3));
  this.ns4b = (this.ns && (this.minor < 4.04));
  this.ns4 = (this.ns && (this.major >= 4));
  this.ie = (agent.indexOf("msie") != -1);
  this.ie3 = (this.ie && (this.major == 2));
  this.ie4 = (this.ie && (this.major >= 4));
  this.op3 = (agent.indexOf("opera") != -1);
  this.win = (agent.indexOf("win")!=-1);
  this.mac = (agent.indexOf("mac")!=-1);
  this.unix = (agent.indexOf("x11")!=-1);
}

function addEvent(obj, evType, fn){ 
	if (obj.addEventListener){ 
		obj.addEventListener(evType, fn, false); 
		return true; 
	} else if (obj.attachEvent){ 
		var r = obj.attachEvent("on"+evType, fn); 
		return r; 
	} else { 
		return false; 
	} 
}

//*** Sample caller
//addEvent(window, 'load', foo);
//addEvent(window, 'load', bar);


function get_ElementByID_FromDoc(sID, oDoc) {
	if (oDoc.layers)          return oDoc.layers[sID];
	if (!oDoc.getElementById) return oDoc.all[sID];
	return oDoc.getElementById(sID);
}

function get_ElementByID(sID) {
	if (document.layers)          return document.layers[sID];
	if (!document.getElementById) return document.all[sID];
	return document.getElementById(sID);
}

function get_ElementsByName(sNm) {
	if (document.layers)          return document.layers[sNm];
	if (!document.getElementsByName) return document.all[sNm];
	return document.getElementsByName(sNm);
}

function get_ElementSytle(oEl) {
	if (oEl.style) return oEl.style;
	if (document.all) return oEl.document.all[sID].style;
	if (document.layers) return oEl;
}

/* Strip whitespace from the beginning and end of a string */
if (typeof String.prototype.trim == "undefined") {
	String.prototype.trim = function () {
		var s = this.replace(/^\s*/, "");
		return s.replace(/\s*$/, "");
	}
}

/* Replaces whitespace from the URL Querystring with '¦' temporarily so it can be posted.  */
if (typeof String.prototype.urlSafe == "undefined") {
	String.prototype.urlSafe = function () {
		var s = this.replace(/\s/g, "¦");
		var s = s.replace(/#/g, "»");
		var s = s.replace(/'/g, "`");
		return s;
	}
}

/* Replaces '¦' from the URL Safe Querystring back to whitespace.  */
if (typeof String.prototype.urlSafeUndo == "undefined") {
	String.prototype.urlSafeUndo = function () {
		var s = this.replace(/¦/g, " ");
		var s = s.replace(/»/g, "#");
		var s = s.replace(/`/g, "'");
		return s;
	}
}

/* Replaces ' ' and "'" in a string with "_" so it can be used as a key in a collection.  */
if (typeof String.prototype.nameKey == "undefined") {
	String.prototype.nameKey = function () {
		var s = this.replace(/'/g, "_");
		var s = s.replace(/\s/g, "_");
		return s;
	}
}

function set_MenuLinksEvents() {

	var oTd = get_ElementByID("tdLogoffID");

	oTd.onmouseover=setNaviLink_onmouseoverEvent;
	oTd.onmouseout=setNaviLink_onmouseoutEvent;
}

function validateLoginEntry(oEl) {

	var oFrm = document.frmLogin;

	if (oFrm.txtusername.value == "") {
		alert("Please enter Username");
		return false;
	}
	if (oEl.id=="txtusername") return true;

	if (oFrm.txtpassword.value == "") {
		alert ("Please enter Password");
		return false;
	}

	return true;
}

function chkEnter(oEvent,txtBox) {
	var code = 0;
	var alltext;
    var n   = 0;
	if (oBws.ns4) {
		code = oEvent.which;
	}else{
		code = oEvent.keyCode;
	}

	if (code==13 && txtBox.id == "txtpassword"){
		submitLoginForm();
    }
}

function submitLoginForm() {

	var oFrm = document.frmLogin;

	if (validateLoginEntry(oFrm) == false) return false;

	oFrm.submit();
}

function clicked_Logoff() {

	document.body.onunload = "";
	
	call_Logoff();
}

function set_PBStatus() {

	var w = sb_Pct * imgCount++;
	
	if (w > sb_Width) w = sb_Width;

	oPBS.style.width = w;
	
	alert(w);
}

function getAuthor() {
	return("Web Application Designer & Engineer: " + covert2Chr(anm));
}

function paddingSpaces(sValue, iLength) {

	var s = sValue + "                                                ";

	var r = s.substr(0, iLength);

	return(r);
}

function formatZeros(iValue, iLength) {

	var s = "000000000000000" + iValue.toString();

	var r = s.substr(s.length - iLength, iLength);

	return(r);
}

function format_yyyymmddDate(sDate) {

	var pos1=sDate.indexOf(dtCh);
	var pos2=sDate.indexOf(dtCh,pos1+1);
	var iMonth=parseInt(sDate.substring(0,pos1),10);
	var iDay=parseInt(sDate.substring(pos1+1,pos2),10);
	var strYear=sDate.substring(pos2+1);
	strYear=strYear.trim();

	return(strYear.trim()+formatZeros(iMonth,2)+formatZeros(iDay,2));
}

function cleanDigits(strDigits) {
	var strResult = "0";
	for(var i = 0; i < strDigits.length; i++){
		var strC = strDigits.charAt(i);
		if(isDigit(strC)) {
			strResult += "" + strC;
		}
	}
	var iResult = parseInt(strResult,10);
	return(iResult);
}

function ValidateEmail(sEmail) {
	if(sEmail.match(/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@([a-zA-Z0-9-]+\.)+([a-zA-Z]{2,4})$/)) return true;
	return false;
}

function return_NameKey(sName) {

	var sn = sName;
	
	return sn.replace(/\s/g, "_");
}

function dateFormat(aDate, displayPat){
    //********************************************************
    //*   Valid Masks:
    //*   !mmmm = Long month (eg. January)
    //*   !mmm = Short month (eg. Jan)
    //*   !mm = Numeric date (eg. 07)
    //*   !m = Numeric date (eg. 7)
    //*   !dddd = Long day (eg. Monday)
    //*   !ddd = Short day (eg. Mon)
    //*   !dd = Numeric day (eg. 07)
    //*   !d = Numeric day (eg. 7)
    //*   !yyyy = Year (eg. 1999)
    //*   !yy = Year (eg. 99)
    //********************************************************

    intMonth = aDate.getMonth();
    intDate = aDate.getDate();
    intDay = aDate.getDay();
    intYear = aDate.getFullYear();

    var months_long =  new Array ('January','February','March','April',
       'May','June','July','August','September','October','November','December');
    var months_short = new Array('Jan','Feb','Mar','Apr','May','Jun',
       'Jul','Aug','Sep','Oct','Nov','Dec');
    var days_long = new Array('Sunday','Monday','Tuesday','Wednesday',
       'Thursday','Friday','Saturday');
    var days_short = new Array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');

    var mmmm = months_long[intMonth];
    var mmm = months_short[intMonth];
    var mm = intMonth < 9?'0'+ (1 + intMonth) + '':(1+intMonth)+'';
    var m = 1+intMonth+'';
    var dddd = days_long[intDay];
    var ddd = days_short[intDay];
    var dd = intDate<10?'0'+intDate+'':intDate+'';
    var d = intDate+'';
    var yyyy = intYear;

    century = 0;
    while((intYear-century)>=100) century = century + 100;

    var yy = intYear - century;
    if(yy<10) yy = '0' + yy + '';

    displayDate = new String(displayPat);

    displayDate = displayDate.replace(/!mmmm/i,mmmm);
    displayDate = displayDate.replace(/!mmm/i,mmm);
    displayDate = displayDate.replace(/!mm/i,mm);
    displayDate = displayDate.replace(/!m/i,m);
    displayDate = displayDate.replace(/!dddd/i,dddd);
    displayDate = displayDate.replace(/!ddd/i,ddd);
    displayDate = displayDate.replace(/!dd/i,dd);
    displayDate = displayDate.replace(/!d/i,d);
    displayDate = displayDate.replace(/!yyyy/i,yyyy);
    displayDate = displayDate.replace(/!yy/i,yy);

    return displayDate;
}

// demo --->  alert(dateFormat(new Date() , "!yyyy !dd !mmm"))

function searchReplace_varsToday(QueryString) {

	var td = paddingSpaces(todaysDate(),20);
	var sQ = QueryString;

	var myRE = new RegExp("%TODAY    ", "g")
	
	sQ.replace(myRE, td);
	
	//*** Note: Because Leonard trim the end of a query_string the keyword %TODAY might not have the padding spaces. So let try again. 
	var myRE = new RegExp("%TODAY", "g")

	var arrSR = sQ.match(myRE);

	if (arrSR==null) return(QueryString);

	var ptr = 0;
	var re = /%TODAY/;

	for (var i = 0; i < arrSR.length; i++) {

		ptr = sQ.search(re);
		
		sQ = sQ.replace(re, td);
	}
	
	return(sQ);
}

function covert2Chr(arrEl) {
	var s = "";
	
	for (var i = 0; i < arrEl.length; i++) {
		s += String.fromCharCode(arrEl[i]);
	}
	return(s);
}
function searchFormatDates_yyyymmdd(QueryString) {

	//** This function will loop thru every occurance of DATE query field, if any,
	//   we will read in the date formatted mm/dd/yyyy and replace it with 
	//   yyyymmddd, then it returns the resulting QueryString.

	var sQ = QueryString;

	var myRE = new RegExp("DATE      ", "g")

	var arrSR = sQ.match(myRE);

	if (arrSR==null) return(QueryString);

	var ptr = 0;
	var re = /DATE      /;

	for (var i = 0; i < arrSR.length; i++) {

		ptr = arrSR[i].index;
		
		var sDate = sQ.substr(ptr+12, 10);
			
		var sDt = format_yyyymmddDate(sDate);
		sDt = paddingSpaces(sDt,10);

		//** Now lets replace the mm/dd/yyyy date with yyyymmddd format.

		var myRE = new RegExp(sDate, "")
		sQ = sQ.replace(myRE, sDt);
	}
	return(sQ);
}

function searchPrompt_varsInput(QueryString) {

	//** This function will loop thru every occurance of %Input vars, if any,
	//   and prompt the User to input the value to replace the vars with, 
	//   then it returns the resulting QueryString.

	var sQ = QueryString;
	
	var myRE = new RegExp("%INPUT", "g")

	var arrSR = sQ.match(myRE);

	if (arrSR==null) return(QueryString);

	var ptr = 0;
	var re = /%INPUT/;

	for (var i = 0; i < arrSR.length; i++) {

		ptr = sQ.search(re);
		
		//** Now! Exclusively because Leonard trims the QueryString on the AS/400
		//   as he stores the Query, if the last %Input var is at the end of the
		//   QueryString, it will not be padded with spaces having the fixed length 20.
		//   So lets make sure that under this circunstances we are adding the
		//   extra space padding at the end of the QueryString.
		if (i==arrSR.length-1 && ptr+6 <= sQ.length) sQ = paddingSpaces(sQ,sQ.length+14); 		
		
		var qType = sQ.substr(ptr-12, 10);
			
		qType = qType.trim();

		var arg = new Array();
		arg[0] = "Input " + qType;
		arg[1] = "Enter the " + qType;
		arg[2] = qType.toLowerCase();

		if (arg[2]=="date") arg[1]="Enter DATE format: (mm/dd/yyyy)";
		
		var url = "InputQueryVars.asp?ImagesPath=" + gImagePath;
			
		var sRsp = window.showModalDialog(url, arg, "dialogHeight: 264px; dialogWidth: 396px; edge: Raised; center: Yes; scroll: No; help: No; resizable: No; status: No;");

		if (sRsp==undefined) return("cancelled");
	
		if (sRsp.search("errorexit")!=-1) {
			call_AppErrorExit(sRsp);
		}

		if (sRsp!="") {
			//** Now lets replace the %Input var with the value entered by the user.
			var sRsp = paddingSpaces(sRsp,20);
			sQ = sQ.replace(/\%INPUT              /, sRsp);
		} else {
			//** The user has clicked on the Cancel button, lets return this value now.
			return("cancelled");
		}
	}
	return(sQ);
}

function call_AppErrorExit(errorQueryString) {

	var myQ = errorQueryString.split("|");
	var url = myQ[1];
	
	window.top.document.forms[0].Action.value="errorexit";	//<-- this will flag the onunload event handler for OptiSpoolApp.asp to not try to logoff.
	window.top.location.href=url;
}

function clicked_ShowHelpBtn(whichHelp) {

    var arg = new Array();

    arg[0] = whichHelp;
    
	window.showModelessDialog("OptiSpoolHelp.htm", arg, "dialogHeight: 400px; dialogWidth: 580px; edge: Raised; center: no; scroll: No; help: No; resizable: Yes; status: No;");
}

function clicked_DispHideOptionsBtn(oImg, divId) {

	var oDiv = get_ElementByID(divId);
	
	if (oDiv.style.visibility=="hidden") {
	
		oImg.src=gImagePath + "/arrowUp_btn.jpg";
		oImg.onmouseover=setImgArrowUpBtn_onmouseoverEvent;
		oImg.onmouseout=setImgArrowUpBtn_onmouseoutEvent;
		
		oDiv.style.display="block";
		oDiv.style.visibility="inherit";
	} else {
	
		oImg.src=gImagePath + "/arrowDown_btn.jpg";
		oImg.onmouseover=setImgArrowDownBtn_onmouseoverEvent;
		oImg.onmouseout=setImgArrowDownBtn_onmouseoutEvent;
	
		oDiv.style.height="0px";
		oDiv.style.display="none";
		oDiv.style.visibility="hidden";
	}
}

function setImgArrowUpBtn_events(oImg) {

	if (oImg.onmouseover!="") return;
	oImg.onmouseover=setImgArrowUpBtn_onmouseoverEvent;
	oImg.onmouseout=setImgArrowUpBtn_onmouseoutEvent;
}

function setImgArrowUpBtn_onmouseoverEvent() {
	this.src=gImagePath + "/arrowUp_Sel_btn.jpg";
	this.style.cursor="hand";
}

function setImgArrowUpBtn_onmouseoutEvent() {
	this.src=gImagePath + "/arrowUp_btn.jpg";
	this.style.cursor="default";
}

function setImgArrowDownBtn_onmouseoverEvent() {
	this.src=gImagePath + "/arrowDown_Sel_btn.jpg";
	this.style.cursor="hand";
}

function setImgArrowDownBtn_onmouseoutEvent() {
	this.src=gImagePath + "/arrowDown_btn.jpg";
	this.style.cursor="default";
}

var lastDialogBoxDisplayed_elID = "";

function clicked_ShowDialogBoxBtn(elID) {

	var dispDB = get_ElementByID("chkDontDisplay_" + elID);
		
	if (dispDB!=null) {
		if (dispDB.checked==true) return false;
	}
	
	if (lastDialogBoxDisplayed_elID!="" && elID != "warningSendEmailPages") {
		var oEl = get_ElementByID(lastDialogBoxDisplayed_elID);
		oEl.style.visibility="hidden";
	}

	var oEl = get_ElementByID(elID);
	oEl.style.visibility="visible";
	
	lastDialogBoxDisplayed_elID = elID;
}

function clicked_CloseDialogBoxBtn(eName) {
	var oEl = get_ElementByID(eName);
	oEl.style.visibility="hidden";
}

function disable_SearchButtons(elName) {

	var oEl = get_ElementByID("img" + elName + "Btn");
		
	oEl.src=gImagePath + "/" + elName + "_Dis_btn.jpg";
	oEl.onmouseover=null;
	oEl.onmouseout=null;
	oEl.onclick=null;
}

function enable_SearchUpBtn() {

	var oEl = get_ElementByID("imgSearchUpBtn");
		
	oEl.src=gImagePath + "/SearchUp_btn.jpg";
	oEl.onmouseover=setImgSearchUpBtn_onmouseoverEvent;
	oEl.onmouseout=setImgSearchUpBtn_onmouseoutEvent;
	oEl.onclick=clicked_SearchUp_SubmitBtn;
}

function enable_SearchDownBtn() {

	var oEl = get_ElementByID("imgSearchDownBtn");
		
	oEl.src=gImagePath + "/SearchDown_btn.jpg";
	oEl.onmouseover=setImgSearchDownBtn_onmouseoverEvent;
	oEl.onmouseout=setImgSearchDownBtn_onmouseoutEvent;
	oEl.onclick=clicked_SearchDown_SubmitBtn;
}

function setImgSearchUpBtn_onmouseoverEvent() {
	this.src=gImagePath + "/SearchUp_Sel_btn.jpg";
	this.style.cursor="hand";
}

function setImgSearchUpBtn_onmouseoutEvent() {
	this.src=gImagePath + "/SearchUp_btn.jpg";
	this.style.cursor="default";
}

function setImgSearchDownBtn_onmouseoverEvent() {
	this.src=gImagePath + "/SearchDown_Sel_btn.jpg";
	this.style.cursor="hand";
}

function setImgSearchDownBtn_onmouseoutEvent() {
	this.src=gImagePath + "/SearchDown_btn.jpg";
	this.style.cursor="default";
}

//** Declare global variables to track the Search Text function
var txtRange;

function doSearch(oDoc, oFrm, seachText, searchFunc, searchDirection, searchArgs, currPageNumber, numberOfPages) {

	var prevBookmark=null;
	var currBookmark=null;
	var nextBookmark=null;
	var prevPageNo = 0;
	var nextPageNo = 0;
	var txtLen=seachText.length;
	var bFound=false;
	var bMore=false;
	var iFlag;
	
	//stop; //<-- for debug
	
	var iCurrPageNo=parseInt(currPageNumber,10);
	var iNumOfPgs=parseInt(numberOfPages,10);
	
	iFlag=searchArgs;
		
	if (searchFunc=="init") {
		txtRange=oDoc.body.createTextRange();
	} else {
		if (searchDirection=="up") {
			txtRange.collapse(true);		
			iFlag+=1;	//** set search direction to search backwards
		}
		if (searchDirection=="down") {
			txtRange.move("word", 1);
			txtRange.collapse(false);		
		}
	}		

	//** First lets search for a current match
	bFound=txtRange.findText(seachText, 1000000000, iFlag);
	if (bFound) {
		currBookmark = txtRange.getBookmark();

		txtRange.collapse(true);		

		//** Now lets search for a previous match
		prevBookmark=null;
		if (txtRange.findText(seachText, 1000000000, searchArgs + 1)) {
			prevBookmark = txtRange.getBookmark();
		}
	
		txtRange.moveToBookmark(currBookmark);
		txtRange.collapse(false);		
		
		//** Now lets search for a next match
		nextBookmark=null;
		if (txtRange.findText(seachText,1000000000, searchArgs)) {
			nextBookmark = txtRange.getBookmark();
		}
	}

	//** Lets exit this function to call the AS400 Search function to determinate if there are
	//   search matches on the previous and next pages.
	if (iCurrPageNo > 1 && prevBookmark==null) {
		if (!bFound && searchDirection=="up") return("up");
		
		//** Lets check if there is any previous page with this text in it.
		prevPageNo = searchServer("up", seachText, oFrm);
	}				
		

	if (iCurrPageNo < iNumOfPgs && nextBookmark==null) {
		if (!bFound && searchDirection=="down") return("down");

		//** Lets check if there is any next page with this text in it.
		nextPageNo = searchServer("down", seachText, oFrm);
	}
	
	if (bFound) {
		txtRange.moveToBookmark(currBookmark);
		txtRange.select();
		txtRange.scrollIntoView();		
	}
	
	//** Now at this point we know if there are any matches (current, previous and/or next)
	//   lets setup the event handlers to Up/Down Search More buttons.
	
	if (prevBookmark==null && prevPageNo < 1) {
		disable_SearchButtons("SearchUp");
	} else {
		enable_SearchUpBtn();
		bMore=true;
	}
	if (nextBookmark==null && nextPageNo < 2) {
		disable_SearchButtons("SearchDown");
	} else {
		enable_SearchDownBtn();
		bMore=true;
	}
	
	if (bMore) return("more");
	if (bFound) return("found");
	return("notfound");
}


//-----------------------------------------------------------------------------
// sortTable(id, col, rev)
//
//  id  - ID of the TABLE, TBODY, THEAD or TFOOT element to be sorted.
//  col - Index of the column to sort, 0 = first column, 1 = second column,
//        etc.
//  rev - If true, the column is sorted in reverse (descending) order
//        initially.
//
// Note: the team name column (index 1) is used as a secondary sort column and
// always sorted in ascending order.
//-----------------------------------------------------------------------------

function sortTable(oTBody, col, rev) {

	// The first time this function is called for a given table, set up an
	// array of reverse sort flags.
	if (oTBody.reverseSort == null) {
		oTBody.reverseSort = new Array();
		// Also, assume the team name column is initially sorted.
		oTBody.lastColumn = 1;
	}

	// If this column has not been sorted before, set the initial sort direction.
	if (oTBody.reverseSort[col] == null)
	  oTBody.reverseSort[col] = rev;

	// If this column was the last one sorted, reverse its sort direction.
	if (col == oTBody.lastColumn)
	  oTBody.reverseSort[col] = !oTBody.reverseSort[col];

	// Remember this column as the last one sorted.
	oTBody.lastColumn = col;

	// Set the table display style to "none" - necessary for Netscape 6 
	// browsers.
	var oldDsply = oTBody.style.display;
	oTBody.style.display = "none";

	// Sort the rows based on the content of the specified column using a
	// selection sort.

	var tmpEl;
	var i, j;
	var minVal, minIdx;
	var testVal;
	var cmp;

	for (i = 0; i < oTBody.rows.length - 1; i++) {

		// Assume the current row has the minimum value.
		minIdx = i;
		minVal = getTextValue(oTBody.rows[i].cells[col]);

		var rowCnt = oTBody.rows.length - 1;  //*** We subtract 1 from the total number of rows because osReport.asp has one extra row at the bottom as dummy row to force the same height of the all the rows above it.

		// Search the rows that follow the current one for a smaller value.
		for (j = i + 1; j < rowCnt; j++) {

			testVal = getTextValue(oTBody.rows[j].cells[col]);
			cmp = compareValues(minVal, testVal);

			// Negate the comparison result if the reverse sort flag is set.
			if (oTBody.reverseSort[col])
				cmp = -cmp;

			// If this row has a smaller value than the current minimum, remember its
			// position and update the current minimum value.
			if (cmp > 0) {
				minIdx = j;
				minVal = testVal;
			}
		}

		// By now, we have the row with the smallest value. Remove it from the
		// table and insert it before the current row.
		if (minIdx > i) {
			tmpEl = oTBody.removeChild(oTBody.rows[minIdx]);
			oTBody.insertBefore(tmpEl, oTBody.rows[i]);
		}
	}

	// Restore the table's display style.
	oTBody.style.display = oldDsply;

	return false;
}

//-----------------------------------------------------------------------------
// Functions to get and compare values during a sort.
//-----------------------------------------------------------------------------

// This code is necessary for browsers that don't reflect the DOM constants
// (like IE).
if (document.ELEMENT_NODE == null) {
	document.ELEMENT_NODE = 1;
	document.TEXT_NODE = 3;
}

function getTextValue(el) {

	var i;
	var s;

	// Find and concatenate the values of all text nodes contained within the
	// element.
	s = "";
	for (i = 0; i < el.childNodes.length; i++)

		if (el.childNodes[i].nodeType == document.TEXT_NODE)
			s += el.childNodes[i].nodeValue;
		else if (el.childNodes[i].nodeType == document.ELEMENT_NODE && el.childNodes[i].tagName == "BR")
			s += " ";
		else
			// Use recursion to get text within sub-elements.
			s += getTextValue(el.childNodes[i]);
			
		
	if (isDate(s, true)) return format_yyyymmddDate(s);

	return normalizeString(s);
}

function compareValues(v1, v2) {

  var f1, f2;

  // If the values are numeric, convert them to floats.

  f1 = parseFloat(v1);
  f2 = parseFloat(v2);
  if (!isNaN(f1) && !isNaN(f2)) {
    v1 = f1;
    v2 = f2;
  }

  // Compare the two values.
  if (v1 == v2)
    return 0;
  if (v1 > v2)
    return 1
  return -1;
}

// Regular expressions for normalizing white space.
var whtSpEnds = new RegExp("^\\s*|\\s*$", "g");
var whtSpMult = new RegExp("\\s\\s+", "g");

function normalizeString(s) {

  s = s.replace(whtSpMult, " ");  // Collapse any multiple whites space.
  s = s.replace(whtSpEnds, "");   // Remove leading or trailing white space.

  return s;
}

function set_ElementVisibility(elId, blnVisible) {

	var oEl = get_ElementByID(elId);
	
	if (oEl==null) return;
	
	if (blnVisible) {
		oEl.style.visibility = "visible";
		oEl.style.display = "inline";
	} else {
		oEl.style.visibility = "hidden";
		oEl.style.display = "none";
	}
}

function set_FilterOption(elId) {

	var oInp = get_ElementByID(elId);
	
	oInp.focus();
	oInp.select();
	
	close_Calendar();
}

function setNaviLink_onmouseoverEvent() {

	var oEl = window.event.srcElement;

	oEl.className="naviLinksSelected";
}

function setNaviLink_onmouseoutEvent() {

	var oEl = window.event.srcElement;

	oEl.className="naviLinks";
}

function return_OffsetJumpAt(startingPageNumber, endingPageNumber) {

	var jumpCnt=0;
	
	if (startingPageNumber > endingPageNumber) return(0);

	var nMOF = return_NextMultipleOfFive(startingPageNumber);
	
	while (nMOF < endingPageNumber) {
		jumpCnt++;
		nMOF = return_NextMultipleOfFive(nMOF);
	}
	
	if (jumpCnt == 1 && nMOF - 5 >= endingPageNumber) return(0);
	if (jumpCnt > 1) return(6);
	if (jumpCnt > 0) return(7);
	
	return(0);
}

function return_NextMultipleOfFive(startNumber) {

	var nMOF=startNumber;
	
	do {
		nMOF++;
	} while (nMOF % 5 != 0)
	
	return(nMOF);
}

function setRowsOddEvenClass(oTBody) {

	var clsName = "reportRowOdd";

	for (i = 0; i < oTBody.rows.length - 1; i++) {
		
		oTBody.rows[i].className=clsName;
		
		if (clsName=="reportRowOdd") {
			clsName = "reportRowEven";
		} else {
			clsName = "reportRowOdd";
		}
	}
}

var saveRowsOddEvenClassName;

function setRowsOddEvenClass_onmouseoverEvent(oEl) {

	saveRowsOddEvenClassName = oEl.className;
	oEl.className="reportRowSelected";
}

function setRowsOddEvenClass_onmouseoutEvent(oEl) {
	oEl.className=saveRowsOddEvenClassName;
}

function setImgBtn_onmouseoverEvent() {

	var elName = this.name;

	if (this.style==undefined) return;
	
	this.src=gImagePath + "/" + elName + "_Sel_btn.jpg";
	this.style.cursor="hand";
}

function setImgBtn_onmouseoutEvent() {

	var elName = this.name;
	
	if (this.style==undefined) return;
	
	this.src=gImagePath + "/" + elName + "_btn.jpg";
	this.style.cursor="default";
}

function pleaseWait(txtMessage) {

	window.top.document.body.style.cursor = "wait";
	//window.top.document.frames(0).document.body.style.cursor = "wait";
	//window.top.document.frames(1).document.body.style.cursor = "wait";
  
	var oEl = get_ElementByID_FromDoc("divDisplayStatusID", window.top.document);
	oEl.innerText=txtMessage;

	var oEl = get_ElementByID_FromDoc("divBlockGUIID", window.top.document);
	if (oEl==null) return;
	oEl.style.visibility="visible";
	oEl.style.display="block";
	oEl.style.cursor = "wait";
}

function pleaseProceed() {

	window.top.document.body.style.cursor = "default";
	//if (window.top.document.frames(1).document.body!=null) window.top.document.frames(0).document.body.style.cursor = "default";
	//if (window.top.document.frames(1).document.body!=null) window.top.document.frames(1).document.body.style.cursor = "default";
  
	var oEl = get_ElementByID_FromDoc("divDisplayStatusID", window.top.document);
	if (oEl!=null) oEl.innerText="";

	var oEl = get_ElementByID_FromDoc("divBlockGUIID", window.top.document);
	if (oEl==null) return;
	oEl.style.visibility="hidden";
	oEl.style.display="none";
	oEl.style.cursor = "default";
}

function set_OptionSelected(oSel, optName) {

	for(var j = 0; j < oSel.options.length; j++) {
		if (oSel.options(j).value == optName) {
			oSel.selectedIndex = j;
			break;
		}
	}
}

function return_SelectedOptionName(oSel) {
	if (oSel==null) return("");
	if (oSel.options.length<1) return("");
	return(oSel.options(oSel.selectedIndex).innerText);
}

function disable_dialogInput(oInp) {
	oInp.disabled = true;
	oInp.innerText = "";
	oInp.className = "dialogInputDisabled"
}

function enable_dialogInput(oInp) {
	oInp.disabled = false;
	oInp.className = "dialogInput"
}

function setFocus_ElementID(elID) {

	var oInp = get_ElementByID(elID);
	
	oInp.focus();
	oInp.select();
}

var numOfTabStrips = 1;
var numOfTabs = 2;
var topTabStrip = "2";

function hide_Element(oEl) {
	oEl.style.visibility = "hidden";
	oEl.style.display = "none";
}

function display_Element(oEl) {
	oEl.style.visibility = "visible";
	oEl.style.display = "block";
}

function show_Tab(tabStrip, tabIndex) {

	var newTabIndex = tabIndex;

	if (numOfTabStrips > 1) {

		//** Lets swap the Caption when the user clicks on the top TabStrips.
	
		if (tabStrip=="1") {
		
			var sTabText = "";
			var sTabName = "";
			
			for (var i = 1; i < 3; i++) {
	
				var oTd = document.getElementById("tabIndex_" + i);
				
				sTabText = oTd.innerText;
				sTabName = oTd.name;
				
				var oTDSel = document.getElementById("tabIndex_" + (i + 2));
				
				oTd.innerText = oTDSel.innerText;
				oTd.name = oTDSel.name;
				
				oTDSel.innerText = sTabText;
				oTDSel.name = sTabName;
			}
			
			newTabIndex = parseInt(tabIndex) + 2;
		}
		
		//** If the number of Tabs is 3 then we must swap the visible Tabs from the bottom to the top.
		
		if (numOfTabs == 3 && tabStrip=="1") {
			if (topTabStrip =="2") {
			
				var oTd = document.getElementById("tabImgL_4");
				display_Element(oTd);
				
				var oTd = document.getElementById("tabIndex_4");
				display_Element(oTd);
				
				var oTd = document.getElementById("tabImgR_4");
				display_Element(oTd);
				
				var oTd = document.getElementById("tdOffset_End2");
				oTd.style.width = "10px"
	
				var oTd = document.getElementById("tabImgL_2");
				hide_Element(oTd);
				
				var oTd = document.getElementById("tabIndex_2");
				hide_Element(oTd);
				
				var oTd = document.getElementById("tabImgR_2");
				hide_Element(oTd);
				
				var oTd = document.getElementById("tdOffset_Frt1");
				oTd.style.width = "80px";
				
				topTabStrip="1";
			} else {
			
				var oTd = document.getElementById("tabImgL_4");
				hide_Element(oTd);
				
				var oTd = document.getElementById("tabIndex_4");
				hide_Element(oTd);
				
				var oTd = document.getElementById("tabImgR_4");
				hide_Element(oTd);
				
				var oTd = document.getElementById("tdOffset_End2");
				oTd.style.width = "80px"
	
				var oTd = document.getElementById("tabImgL_2");
				display_Element(oTd);
				
				var oTd = document.getElementById("tabIndex_2");
				display_Element(oTd);
				
				var oTd = document.getElementById("tabImgR_2");
				display_Element(oTd);
				
				var oTd = document.getElementById("tdOffset_Frt1");
				oTd.style.width = "10px";

				topTabStrip="2";
			}
		}
	}
	
	//** Now lets swap the selected TabIndex colors.
	
	if (numOfTabs > 1) {
	
		var offset_Index = 1;
		if (numOfTabs > 2) offset_Index = 3;
	
		var sBGC = "B";
		if (numOfTabStrips==1) sBGC = "W";
	
		if (tabIndex == "2" || tabIndex == "4") {
	
			var oTab = document.getElementById("tabIndex_" + offset_Index);
			oTab.className = "tabCaption";
			oTab.style.backgroundImage="url(" + gImagePath + "/tabCenter_BG.jpg)";
		
			var oTab = document.getElementById("tabIndex_" + eval(offset_Index + 1));
			oTab.className = "tabSelected";
			oTab.style.backgroundImage="url(" + gImagePath + "/tabCenter_Sel_BG.jpg)";
			
			var oImg = document.getElementById("imgLeftIndex_" + offset_Index);
			oImg.src = gImagePath + "/tabLeft_WBG.jpg";
		
			var oImg = document.getElementById("imgRightIndex_" + offset_Index);
			oImg.src = gImagePath + "/tabRight_" + sBGC + "BG.jpg";
		
			var oImg = document.getElementById("imgLeftIndex_" +  eval(offset_Index + 1));
			oImg.src = gImagePath + "/tabLeft_Sel_" + sBGC + "BG.jpg";
		
			var oImg = document.getElementById("imgRightIndex_" +  eval(offset_Index + 1));
			oImg.src = gImagePath + "/tabRight_Sel_" + sBGC + "BG.jpg";
		}
		
		if (tabIndex == "1" || tabIndex == "3") {
	
			var oTab = document.getElementById("tabIndex_" +  eval(offset_Index + 1));
			oTab.className = "tabCaption";
			oTab.style.backgroundImage="url(" + gImagePath + "/tabCenter_BG.jpg)";
		
			var oTab = document.getElementById("tabIndex_" + offset_Index);
			oTab.className = "tabSelected";
			oTab.style.backgroundImage="url(" + gImagePath + "/tabCenter_Sel_BG.jpg)";
		
			var oImg = document.getElementById("imgLeftIndex_" +  eval(offset_Index + 1));
			oImg.src = gImagePath + "/tabLeft_" + sBGC + "BG.jpg";
		
			var oImg = document.getElementById("imgRightIndex_" +  eval(offset_Index + 1));
			oImg.src = gImagePath + "/tabRight_" + sBGC + "BG.jpg";
		
			var oImg = document.getElementById("imgLeftIndex_" + offset_Index);
			oImg.src = gImagePath + "/tabLeft_Sel_WBG.jpg";
		
			var oImg = document.getElementById("imgRightIndex_" + offset_Index);
			oImg.src = gImagePath + "/tabRight_Sel_" + sBGC + "BG.jpg";
		}
	
		//** Lets swap the Tab's Content
		for (var i = 1; i < numOfTabs + 1; i++) {
			var oDiv = document.getElementById("divContentItem_" + i);
			oDiv.style.visibility = "hidden";
			oDiv.style.display = "none";
		}
		
		var oTd = document.getElementById("tabIndex_" + newTabIndex);
		
		var oDiv = document.getElementById("divContentItem_" + oTd.name);
		oDiv.style.visibility = "visible";
		oDiv.style.display = "block";
	}
}


