
/*********************************************************************
 *                                                                   *
 * Copyright (C) LANSA Group. All rights reserved                    *
 *                                                                   *
 *********************************************************************/

/*               Rlse &                                                      */
/* Flag Reason   Level  Date   Pgmr       Comments                           */
/* ---- -------- ------ ------ ---------- ---------------------------------- */
/* $A1=          VRM123 040830 JPS        Fix a zoom bug.                    */
/* $A2           VRM123 050131 WMJB       Incorrect variable name            */
/* $A3=          VRM123 050217 FS         Fix a crash happend on XP SP2      */
/* $A4=          VRM123 050301 FS         Change auto scale on page with HTML*/
/* $A5=          VRM123 050302 WMJB       Read login URL preferences         */
/* $A6=          VRM123 050302 WMJB       Prevent error from missing images  */
/* $A7=          VRM123 050302 WMJB       Make transactions easier to copy   */
/* $A8=          VRM123 050302 WMJB       move popup position vals into skin */
/* $A9=          VRM123 050302 WMJB       Measure the border of term_holder  */
/* $B0=          VRM123 050516 FS         Resize HTML when win size changed  */
/* $BA=          VRM130 060428 wmjb       changes for removal of header frame*/
/* $BB           VRM130 060428 wmjb       fixed login screen size problem    */
/* $B3=          VRM130 060508 FS         Initialise auto GUI menu.          */
/* $B4=          VRM130 060508 FS         Fix a focus issue.                 */
/* $B5=          VRM130 060525 FS         Don't scale images by "auto" mode. */
/* $B6=          VRM130 060614 FS         Fix a screen size issue with print.*/
/* $B7=          VRM130 060717 FS         Add system name on title bar.      */
/* $B8=          VRM130 060802 WMJB       Externalise error messages	     */
/* $B9=          VRM131 070530 FS         Fix a DBCS layout issue on IE7.    */
/* $C0=          VRM131 070605 FS         Fix input field width being narrow.*/
/*                      081412 SHC        Merged $B9 in 131 from $B9 in 130  */
/*                      081412 SHC        Merged $C0 in 131 from $C0 in 130  */
/*                                                                           */
/* Change activity detail:                                                   */
/*  A1 - Zoom factor wasn't being set and causing zoom troubles.             */
/*  A2 - Changed wsLoginName to tsLoginName                                  */
/*  A3 - If you enable popup blocker in your IE(XP SP2 version), you maybe   */
/*       get null from window.open().So we need tell the return value is null*/
/*       or not.                                                             */
/*  A4 - Page with HTML automatically is shown on 100% if the current scale  */
/*       is auto scale.                                                      */
/*  A5 - Many lines added to read and set the login preferences set in the   */
/*       URL by the user.						     */
/*  A6 - Many small changes to prevent javascript errors stopping the terminal */
/* 	 from loading. For example if an image object is not present in another */
/*       file in the skin.						     */
/*  A7 - Removed the header from the "View Transaction". Makes saving them   */
/*       easier.							     */
/*  A8 - popx and popy vals added to showpopup function. Now values can be   */
/*       set from the ts_frame.html file so that this file doesn't nee to be */
/*       customised.							     */
/*  A9 - Change CalcZoom() to incorporate the border value of term_holder    */
/*  B4 - If a html element which is out of view get focus before term frame  */
/*       is fully loaded, the layout will be crappy.                         */

var zoom_scale = 1;
var term_x = 0;
var term_y = 0;
var sInfo = "";
var browser_ok = false;
var xml_ok = false;
var xsl_ok = false;
var msIE = false;
var msIEver = 0;
var bHTMLPage = false;			/*@A4A*/

// @A5A - new variable names added below
var usrref = "";
var reconref = false;
var scrnref = "";
var devref = "";
var pgmref = "";
var mnuref = "";
var curlibref = "";
var passref = "";
var encryptref = false;
var autologinref = false;

function getParam(pname,loc)  // url parameter reader
{
  if (!loc){
		loc = parent.window.location;

  	}
	var s = loc.search;

	if (s.length <= 1) return null;
	var srch= new RegExp(".*"+pname+"=([^\f\n\r\t&]*)");

	var tgt = s.match(srch);
	if (!tgt) return null;

	if (tgt[1]) {
		return tgt[1];
	}
	else {
  	return "";
  }
}

//The following function has been changed to check if stylesheet selected is different from current PTF1AX0017 (Apr 04)
var currentStyle = dflt_css;
var zoomFactor = 1;   // This variable duplicates zoom_scale. Use zoom_scale instead.
function SetTermStyle(cssref)  // called to set stylesheet
{
  if(cssref!=currentStyle)
  {
  	Terminal.document.getElementById('Display').style.display = "none"; //hide to stop flashes ... redisplay in OnTermSize().
  	if(!loginShow) zoomFactor = Terminal.document.body.style.zoom; //only set this value if not on the login screen...
  	ApplyZoom(1);
	Terminal.SetStyle(mybase+cssref);
	showCursorTest();
	currentStyle = cssref;
	Terminal.document.getElementById('Display').style.display="inline";
  }
  oPopup.hide();
}

var throbbing;

function SetThrob(bOn)
{
  if (bOn == throbbing) return; else throbbing = bOn;

  if (bOn) {
  	Terminal.document.body.style.cursor = "wait";
  	document.body.style.cursor = "wait";
  	// @A6C - add the try to stop potential errors
  	try{
  		parent.tsheaderbar.throbber0.style.display = "none";
  		parent.tsheaderbar.throbber1.style.display="inline";
  	}
  	catch(e){
  		throbber0.style.display = "none"; // @BAA
  		throbber1.style.display="inline"; // @BAA

  		}


  }
  else {
  	Terminal.document.body.style.cursor = "default";
  	document.body.style.cursor = "default";
  	// @A6C - add the try to stop potential errors
  	try{
  		parent.tsheaderbar.throbber1.style.display = "none";
  		parent.tsheaderbar.throbber0.style.display="inline";
  	}
  	catch(e){
  		throbber1.style.display = "none"; // @BAA
  		throbber0.style.display="inline"; // @BAA
  		}

  }
}

function OnSkinLoad()
{
  var termfrm = document.getElementById("TermFrame");

  var termref = getParam("terminal");
  if (!termref) termref = dflt_term;  /*** default terminal - set at top ***/

  var cssref = getParam("cssref");
  if (cssref == null) cssref = dflt_css_loc;  /*** default CSS - set at top ***/ //line changed to reflect dflt name change PTF1AX0017 (Apr 04)

  var loginref = getParam("login");
  if (loginref == null) loginref = dflt_login;  /*** custom login page - set at top ***/

  var dbg = getParam("debug");

  // @A5A below - New parameters for login field names etc.
  usrref = getParam("user");
  reconref = getParam("reconnect");
  scrnref = getParam("screentype");
  devref = getParam("device");
  pgmref = getParam("program");
  mnuref = getParam("menu");
  curlibref = getParam("curlib");
  passref = getParam("pwd");
  encryptref = getParam("encrypt");
  autologinref = getParam("signon");

  if (offline) { // we get no params anyway
      termref = "/ts/terminal.xml";   // NOT axests/terminal !!
      cssref = dflt_css_loc; 		//line changed to reflect dflt name change PTF1AX0017 (Apr 04)
      dbg = null;
  }
  InitTermSize();
  IndicateScale();

  //Taken out of this release... choosing a language from the menu does nothing for this release...
  //if(langlist == false) {
  //  LanguageXML.ondatasetcomplete = loadLanguages;
  // }

  var qdata="";
  if (cssref) qdata += "cssref="+cssref+"&";
  if (loginref) qdata += "login="+loginref+"&";
  if (dbg) qdata +="debug="+dbg+"&";

  var termloc = document.frames['TermFrame'].document.location;
	var termfil = termloc.pathname.match(/[^\\\/]*$/)[0];
  if (termfil == "loading.html") {// initial load
     termfrm.src=termref+"?"+qdata;
  }
  else { // it's a refresh
    //@A5A below - Resets the login values if refresh button is pressed.
    autologinref=false; //So that autologin only works on the initial load.
    setLoginPrefs();
  }
}

//function changed to change states of zoom buttons PTF1AX0017 (Apr 04)
function EnableMenus(stat)
{
   //var itm = document.getElementById("footer_bar");
   //if (itm) itm.disabled = (stat < 0);

   var items = document.getElementsByName("sessitem");
   var i;
   for (i=0;i<items.length;++i) items[i].disabled = (stat < 0) && (stat != -999); // allowed for err

   if (oPopup && oPopup.document) {
      items = oPopup.document.getElementsByName("sessitem");
      for (i=0;i<items.length;++i) items[i].disabled = (stat < 0) && (stat != -999); // allowed for err
   }

   itm = document.getElementById("slScale");
   if (itm) itm.disabled = (stat < 0);

   itm = document.getElementById("zoomIn");
   if (itm) itm.disabled = (stat < 0);

   //itm = document.getElementById("zoomFit");    @BAD - removed for 130
   //if (itm) itm.disabled = (stat < 0);	@BAD - removed for 130

   //itm = document.getElementById("unZoom");	@BAD - removed for 130
   //if (itm) itm.disabled = (stat < 0);	@BAD - removed for 130

   itm = document.getElementById("zoomOut");
   if (itm) itm.disabled = (stat < 0);

}

//function changed to change states of zoom buttons PTF1AX0017 (Apr 04)
function EnableButtons(stat)
{
  if(stat < 0)
  {
	if(loginShow==false)
	{
		zoomIn0.style.display = "none";
		zoomIn1.style.display = "inline";	zoomIn.style.cursor = "default";
		//zoomFit0.style.display = "none";	@BAD - removed for 130
		//zoomFit1.style.display = "inline";	@BAD - removed for 130
		//zoomFit.style.cursor = "default";	@BAD - removed for 130
		zoomOut0.style.display = "none";
		zoomOut1.style.display = "inline";	zoomOut.style.cursor = "default";
		//unZoom0.style.display = "none";	@BAD - removed for 130
		//unZoom1.style.display = "inline";	@BAD - removed for 130
		//unZoom.style.cursor = "default";	@BAD - removed for 130
	}
 }
  else {
  	if(loginShow==true)
	{
		zoomIn0.style.display = "inline";	zoomIn.style.cursor = "hand";
		zoomIn1.style.display = "none";
		//zoomFit0.style.display = "inline"; 	@BAD - removed for 130
		//zoomFit.style.cursor = "hand";	@BAD - removed for 130
		//zoomFit1.style.display = "none";	@BAD - removed for 130
		zoomOut0.style.display = "inline";	zoomOut.style.cursor = "hand";
		zoomOut1.style.display = "none";
		//unZoom0.style.display = "inline";	@BAD - removed for 130
		//unZoom.style.cursor = "hand";		@BAD - removed for 130
		//unZoom1.style.display = "none";	@BAD - removed for 130
	}
  }

}

/** terminal callback **/
function OnTermLoaded(bOk)
{
   var itm = document.getElementById("display");
   if (itm) itm.disabled = !bOk;
   itm = document.getElementById("session");
   if (itm) itm.disabled = !bOk;
   itm = document.getElementById("OVR"); //new for PTF 1AX0012 (feb 04)
   if (itm) itm.disabled = !bOk;

  SetKeyMap(key_map); //Sets the default key_map when terminal has loaded...
}

/** terminal callback **/
function OnStatusChange(stat)
{
   if (!Terminal.AXES.RAMP_TSInterface) window.status=Terminal.StatusMessage[stat];
   EnableMenus(stat);
   //EnableKeyFrame(stat); //If the parent is in the tab frame! @A6C - removed. Hurts if not tabs are present
   EnableButtons(stat);
   SetThrob(stat > 0);
}
/** terminal callback **/
function OnCancel()
{
  if (parent.top.window.opener)
  {
  	parent.top.window.close();
  }
  else {
    var canref = getParam("cancel");
    if (canref) window.navigate(canref);
  }
}

var sized=false;
/** terminal callback **/
//function changed to set zoom after stylesheet change PTF1AX0017 (Apr 04)
function OnTermSize(xpix, ypix)
{
  term_x = xpix;
  term_y = ypix;

  if (!sized) {
    if (window.opener) { // i'm a popup
      SizeWindowToTerm();
    }

    sized = true;
  }

  if(!loginShow){
  	if (auto_mode){SetZoom("auto")}
  	else {SetZoom(zoom_scale);} //zoom_fit @A1C. use zoom_scale instead of zoomFactor.
  }

  Terminal.document.getElementById('Display').style.display="inline";
}


function InitTermSize()
{
   if (window.opener) { // i'm a popup
      SizeWindowToTerm();
   }
}

function SizeWindowToTerm()
{

  var term = document.getElementById("term_holder");
  var sh = term.scrollHeight;
  var sw =  term.scrollWidth;
  var cw = term.clientWidth;
  var ch = term.clientHeight;
  var dx = sw - cw;
  var dy = sh - ch;

  var scrW = screen.width - window.screenLeft;
  var scrH = screen.height - window.screenTop;

  if ((document.body.offsetWidth + dx ) > scrW) dx = scrW - document.body.offsetWidth;
  if ((document.body.offsetHeight + dy ) > scrH) dy = scrH - document.body.offsetHeight;

  window.resizeBy(dx, dy);


}
function term_holder_height() // expression for term_holder height
{
   var itm = document.getElementById("ContentDiv");
   var ypix= itm.clientHeight;

   var cc = itm.children;
   for (var i=0;i<cc.length;++i) {
      itm = cc[i];
      if ((itm.tagName =="DIV") && (itm.id != "term_holder"))  ypix -= itm.offsetHeight;
   }

   return ypix;
}

function TermFrame_height()
{
   var ypix = Math.ceil(term_y * zoom_scale);

   var trm = document.getElementById("term_holder");
   if (trm.clientHeight > ypix) ypix=trm.clientHeight;
   return ypix;
}


function TermFrame_width()
{
   var xpix = Math.ceil(term_x * zoom_scale);
   var trm = document.getElementById("term_holder");
   if (trm.clientWidth > xpix) xpix=trm.clientWidth;
   return xpix;
}

function SetZoom(z)
{
  var zs = zoom_scale;

  switch(z) {
  case '-':
  case '+':
    auto_mode = false;
    if (zs<=0.1 || zs>5) zs=1.0;
    zs *= (z=='+') ? 1.05 : 0.95;
    break;
  case '*': //try constructions added to stop script error if terminal hasn't loaded.. PTF1AX0017
    try {
    	auto_mode = false;
    	var tx = Terminal.TermW();
    	var ty = Terminal.TermH();
    	zs = CalcZoom(tx,ty);
    	}
    catch(e){break;}
    break;
   case 'auto':
   try {
    auto_mode = true;
    if (!bHTMLPage)             /*@A4A*/
    {                           /*@A4A*/
       var tx = Terminal.TermW();
       var ty = Terminal.TermH();
       zs = CalcZoom(tx,ty);
    }                           /*@A4A*/
    else
       zs = 1;                  /*@A4A*/
    }
    catch(e){break;}
    break;
  default:
    zs = z;
    auto_mode = false;
  }
  ApplyZoom(zs) ;
  IndicateScale();
  document.recalc();
}

//function changed to change states of zoom buttons PTF1AX0017 (Apr 04)
function IndicateScale()
{
  if(auto_mode||((loginZoom=='auto')&&loginShow))
  {
	document.getElementById("optMenuBar").value = zoom_scale;
  	document.getElementById("optMenuBar").innerText = "- Auto -";
  	document.getElementById("optMenuBar").selectedIndex = 0;
  }
  else{
  	document.getElementById("optMenuBar").value = zoom_scale;
  	document.getElementById("optMenuBar").innerText = Math.round(zoom_scale * 100) + "%";
  	document.getElementById("slScale").selectedIndex = 0;
  }
}



function CalcZoom(tx, ty)
{
   var itm = document.getElementById("term_holder");
   // @A9C - Two lines changed to measure border of term_holder.
   var xx = itm.clientWidth - parseInt(itm.style.borderLeftWidth) - parseInt(itm.style.borderLeftWidth);
   var yy = term_holder_height() - parseInt(itm.style.borderTopWidth) - parseInt(itm.style.borderBottomWidth);
   //The 1 stops the scroll bar appearing every now and then.

   var z1 = xx / tx;
   var z2 = yy / ty;
   return (z1 < z2) ? z1 : z2;
}


function ApplyZoom(z)
{
  try {
  	Terminal.document.body.style.zoom = zoom_scale = z;
  	if (!loginShow)                /*@B5A*/
  	   Terminal.SetImageZoom(z);   /*@B5A*/
  	showCursorTest();
  	}
  catch(e){}
}

/* function added to stop focus issue if terminal frame hasn't loaded. @B4C*/
function showCursorTest()
{
	try
	{
	   var trmframe = Terminal.frameElement;
	   var cursorobj = Terminal.Cursor;
	   if (cursorobj && trmframe)
	   {
	      if (cursorobj.hItm && cursorobj.hItm.offsetTop > trmframe.offsetHeight)
	      {
	         trmframe.onload = showCursorTest;
	         return;
	      }
	      else
	         trmframe.onload = "";
	   }
	   Terminal.ShowCursor();
	}
	catch(e){}
}
/* @B4C End */

function getBrowserInfo()
{

  var sN   = window.navigator.appName;
  var sV   = window.navigator.appVersion;
  var sMV  = window.navigator.appMinorVersion;
  var sUA  = window.navigator.userAgent;
  var sP   = window.navigator.platform;
  var sCPU = window.navigator.cpuClass;


  var ie_ix = sUA.search("MSIE ");
  if (ie_ix>=0) {
  	msIE = true;
  	var s1 = sUA.substring(ie_ix+5,sUA.indexOf(";",ie_ix+5));
  	msIEver = new Number(s1);
  }

  var sInfo = "{****** Browser Information ******}\n" +
              "appName     ='"+sN+"'\n" +
              "appVersion  ='"+sV+"'\n" +
              "appMinorV   ='"+sMV+"'\n" +
              "userAgent   ='"+sUA+"'\n" +
              "platform    ='"+sP+"'\n" +
              "cpuClass    ='"+sCPU+"'\n" ;


  if (msIE && (msIEver >= 5.0)) {
    var sIEver = oClientCaps.getComponentVersion ("{89820200-ECBD-11CF-8B85-00AA005B4383}","componentid");
    var sMSVMver = oClientCaps.getComponentVersion("{08B0E5C0-4FCB-11CF-AAA5-00401C608500}","ComponentID");
    var sDHTMLver = oClientCaps.getComponentVersion("{9381D8F2-0288-11D0-9501-00AA00B911A5}","ComponentID");

    sInfo += "IE Version no. ='"+msIEver+"'\n";
    sInfo += "IE Version str ='"+sIEver+"'\n";
  }

  sInfo +=   "Script Engine  =" +getScriptEngineInfo() + "\n";

 return sInfo;
}


function getScriptEngineInfo()
{
   var s;
   if (msIE && ScriptEngine && ScriptEngineMajorVersion &&
        ScriptEngineMinorVersion && ScriptEngineBuildVersion) {
       s = ""; // Build string with necessary info.
       s += ScriptEngine() + " Version ";
       s += ScriptEngineMajorVersion() + ".";
       s += ScriptEngineMinorVersion() + ".";
       s += ScriptEngineBuildVersion();
       return(s);
   }
   else return "no script engine info";

}


function getXMLInfo()
{
   var s = "{****** XML Processor ******}\n";
   var xml_ok = false;

   var itm = document.frames["Terminal"];
   if (!itm) return s + "Cannot find 'Terminal' iframe";

  var doc = itm.document;
  if (!doc) return s + "cannot find Terminal.document";
  s += "Terminal location ='"+doc.location+"'\n"

  var xdoc = doc.XMLDocument;
  if (!xdoc) return s + "cannot find Terminal.document.XMLDocument";

  var imp1 = xdoc.implementation;
  if (!imp1) {
    s += "cannot find Terminal.document.XMLDocument.implementation\n";
  }
  else {
    s += "XML 1.0    = '"+imp1.hasFeature("XML", "1.0")+"'\n" +
             "DOM 1.0    = '"+imp1.hasFeature("DOM", "1.0")+"'\n" +
             "MS-DOM 1.0 = '"+imp1.hasFeature("MS-DOM", "1.0")+"'\n";
  }


  var xsdoc = doc.XSLDocument;
  if (!xsdoc) return s + "cannot find Terminal.document.XSLDocument";


  var  hitm = doc.getElementById("compoundID");
  if (hitm) do {
    hitm = doc.getElementById("xslVer");
    if (!hitm)  break;
    s += "XSL Processor Version    : "+hitm.innerText +"\n";

    hitm = doc.getElementById("msxslVer");
    if (!hitm) break;
    s += "MS XSL Processor Version : "+hitm.innerText;
    xml_ok = true;
  } while (false);

  if (!xml_ok) {
    s += "XSL Expansion apperars to have failed";
  }
  return s;
}


function getTermXML()
{
   var s = "{****** aXes TS Terminal XML ******}\n";

   var itm = document.frames["Terminal"];
   if (!itm) return s + "Cannot find 'Terminal' iframe";

  var doc = itm.document;
  if (!doc) return s + "cannot find Terminal.document";
  s += "{*** Terminal location ='"+doc.location+"' ***}\n"

  var xdoc = doc.XMLDocument;
  if (!xdoc) return s + "cannot find Terminal.document.XMLDocument";

  return s + xdoc.xml;
}


function getTermTransform()
{
   var s = "{****** aXes TS Terminal Transform ******}\n";

   var itm = document.frames["Terminal"];
   if (!itm) return s + "Cannot find 'Terminal' iframe";

  var doc = itm.document;
  if (!doc) return s + "cannot find Terminal.document";
  s += "{*** Terminal location ='"+doc.location+"' ***}\n"

  var xmldoc = doc.XMLDocument;
  if (!xmldoc) return s + "cannot find Terminal.document.XMLDocument";

  var xsldoc = doc.XSLDocument;
  if (!xsldoc) return s + "cannot find Terminal.document.XSLDocument";

  try {
      s += xmldoc.transformNode(xsldoc);
   } catch (e) {
      s += "Error in Terminal XSL Transform : '"+e.description+"'";
   }
   return s;
}


function getTermHTML()
{
   var s = "{****** aXes TS Terminal HTML ******}\n";

   var itm = document.frames["Terminal"];
   if (!itm) return s + "Cannot find 'Terminal' iframe";

  var doc = itm.document;
  if (!doc) return s + "cannot find Terminal.document";
  s += "{*** Terminal location ='"+doc.location+"' ***}\n"

  return s + doc.body.innerHTML;
}


function getTxXML()
{
   var s = "{****** aXes TS Transaction XML ******}\n";

   var itm = document.frames["Terminal"];
   if (!itm) return s + "Cannot find 'Terminal' iframe";

   var doc = itm.document;
   if (!doc) return s + "cannot find Terminal.document";
   s += "{*** Terminal location ='"+doc.location+"' ***}\n"

   var itm = doc.frames["TxFrame"];
   if (!itm) return s + "Cannot find 'TxFrame' iframe in Terminal";

   var doc = itm.document;
   if (!doc) return s + "cannot find TxFrame.document";
   s += "{*** TX location ='"+doc.location+"' ***}\n"

   var xmldoc = doc.XMLDocument;
   if (!xmldoc) return s + "cannot find TxFrame.document.XMLDocument";

   return xmldoc.xml;  // @A7C - "s + " removed
}

function getTxHTML()
{
   var s = "{****** aXes TS Transaction HTML ******}\n";
   var itm = document.frames["Terminal"];
   if (!itm) return s + "Cannot find 'Terminal' iframe";

   var doc = itm.document;
   if (!doc) return "cannot find Terminal.document";
   s += "{*** Terminal location ='"+doc.location+"' ***}\n"

   var itm = doc.frames["TxFrame"];
   if (!itm) return s + "Cannot find 'TxFrame' iframe in Terminal";

   var doc = itm.document;
   if (!doc) return s + "cannot find TxFrame.document";
   s += "{*** TX location ='"+doc.location+"' ***}\n"

  return s + doc.body.innerHTML;
}

function getTermLog()
{
   var s = "{****** aXes TS Terminal Log ******}\n";

   var itm = document.frames["Terminal"];
   if (!itm) return s + "Cannot find 'Terminal' iframe";

   if (!itm.GetBrowserLogString) return s + "Cannot find 'Terminal' log functions";

   var log = itm.GetBrowserLogString();
   if (!log) return s + "Cannot find 'Terminal' log";

   return s + log;
}
var diag_body = "<body style='font:x-small \"Verdana\";'>"+
                "<input type='button' value='Copy to Clipboard' "+
                " onclick='window.clipboardData.setData(\"Text\",document.getElementById(\"x\").innerText)'" +
                "></button>" +
                "<input type='button' value='Close window' onclick='window.close()' ></button>" +
                "<br />" +
                "<div id='x'>" +
                "<nobr id='prompt'>working...</nobr><br />" +
                "<nobr id='binfo'></nobr><br />" +
                "<nobr id='xinfo'></nobr><br />" +
                "<nobr id='log'></nobr><br />" +
                "<div id='tx'></div><br />" +
                "<nobr id='txh'></nobr><br />" +
                "<nobr id='termx'></nobr><br />" +
                "<nobr id='termh'></nobr><br />" +
                "<nobr id='termt'></nobr><br />" +
                "</div></body>";

function showAllDiags()
{
  var srcwin = window.open("about:blank","","resizable=yes,scrollbars=yes,menubar=yes");
  srcwin.document.write("<html><title>aXes TS Diagnostics - All</title>" + diag_body + "</html>\n");

  srcwin.document.getElementById("prompt").innerText = "";
  srcwin.document.getElementById("binfo").innerText = getBrowserInfo() + "\n";
  srcwin.document.getElementById("xinfo").innerText = getXMLInfo() + "\n";
  srcwin.document.getElementById("log").innerHTML = getTermLog() + "\n";
  srcwin.document.getElementById("tx").innerText = getTxXML() + "\n";
  srcwin.document.getElementById("txh").innerText = getTxHTML() + "\n";
  srcwin.document.getElementById("termx").innerText = getTermXML() + "\n";
  srcwin.document.getElementById("termh").innerText = getTermHTML() + "\n";
  srcwin.document.getElementById("termt").innerText = getTermTransform() + "\n";
  oPopup.hide();
}


function showTX()
{
  var srcwin = window.open("about:blank","","resizable=yes,scrollbars=yes,menubar=yes");
  if (!srcwin)                                /*@A3A*/
  {                                           /*@A3A*/
      alert("Popup window is blocked.");      /*@A3A*/
      return;                                 /*@A3A*/
  }                                           /*@A3A*/
  srcwin.document.write("<html><title>aXes TS Diagnostics - Transaction XML</title>" + diag_body + "</html>\n");

  srcwin.document.getElementById("prompt").innerText = "";
  srcwin.document.getElementById("tx").innerText = getTxXML();
  oPopup.hide();
}

function showLog()
{
  var srcwin = window.open("about:blank","","resizable=yes,scrollbars=yes,menubar=yes");
  srcwin.document.write("<html><title>aXes TS Diagnostics - Terminal Log</title>" + diag_body + "</html>\n");

  srcwin.document.getElementById("prompt").innerHTML = "";
  srcwin.document.getElementById("log").innerHTML = getTermLog();
  oPopup.hide();
}

function showTermXML()
{
  var srcwin = window.open("about:blank","","resizable=yes,scrollbars=yes,menubar=yes");
  srcwin.document.write("<html><title>aXes TS Diagnostics - Terminal XML</title>" + diag_body + "</html>\n");

  srcwin.document.getElementById("prompt").innerText = "";
  srcwin.document.getElementById("termx").innerText = getTermXML();
  oPopup.hide();
}

function showTermHTML()
{
  var srcwin = window.open("about:blank","","resizable=yes,scrollbars=yes,menubar=yes");
  srcwin.document.write("<html><title>aXes TS Diagnostics - Terminal HTML</title>" + diag_body + "</html>\n");

  srcwin.document.getElementById("prompt").innerText = "";
  srcwin.document.getElementById("termh").innerText = getTermHTML();
  oPopup.hide();
}

function showTermTransform()
{
  var srcwin = window.open("about:blank","","resizable=yes,scrollbars=yes,menubar=yes");
  srcwin.document.write("<html><title>aXes TS Diagnostics - Terminal XSL Tansform</title>" + diag_body + "</html>\n");

  srcwin.document.getElementById("prompt").innerText = "";
  srcwin.document.getElementById("termt").innerText = getTermTransform();
  oPopup.hide();
}


function showDiags()
{
  return showAllDiags();
}

function VTLogOff()
{
  if (confirm("Disable Host Trace ?"))
   { Terminal.SendLogCmd(0);
   	VTLogBool = false;
   }
}

function VTLogOn()
{
  if (confirm("Enable Host Trace (SEVERE PERFORMANCE IMPACT) ?"))
   { Terminal.SendLogCmd(1);
   	VTLogBool = true;
   }
}

function VTLogOnOff()
{
	if(VTLogBool)
	{
		VTLogOff();
	}
	else{
		VTLogOn();
	}

}

function VTLogClear()
{
  if (confirm("Clear Host Trace ?"))
    Terminal.SendLogCmd(2)
}

function showVTLog()
{
  var logURL = Terminal.GetLogUrl();
  if (logURL && logURL.length) {
    var srcwin = window.open(logURL,"_blank","resizable=yes,scrollbars=yes,menubar=yes");
  }
  else {
    alert("no log url");
  }
  oPopup.hide();
}


var oPopup = window.createPopup();


function MyStyleTable()   // this lets us copy styles to popup!
{
  var s = "<table><style>\n";
  var ss = document.styleSheets[0];
  if (ss) for (var i=0;i<ss.rules.length;++i) {
    var r=ss.rules[i];
    s += r.selectorText+"{"+r.style.cssText+"}\n";
  }
  var mystyle = document.getElementsByTagName("style");
  if (mystyle) for (var i = 0;i<mystyle.length;++i) {
    s += mystyle[i].innerHTML+"\n";
  }

  s += "</style></table>\n";
  return s;
}

function hidePopup()
{
    oPopup.hide();
}

function showPopup(contentID, posID,popWidth,maxHgt)
{
    var pbody = oPopup.document.body;
    pbody.style.visibility="hidden";
    pbody.style.background="transparent";

    var ContentHTML = contentID + "HTML";
    var baseEl = document.getElementById(posID);

    var popel = document.getElementById(ContentHTML);
    pbody.innerHTML = MyStyleTable() + popel.outerHTML;

    popel = oPopup.document.getElementById(ContentHTML);
    popel.style.display="block";

    var h = maxHgt ? maxHgt : 20;
    oPopup.show(-4,19,popWidth,h,baseEl);

/* all this code chunk does is get border widths */
    var itm = oPopup.document.getElementById(ContentHTML+"inner");
    var itm_hgt = itm.scrollHeight;
    var itm_hx = itm.offsetHeight - itm.clientHeight; // itm border hgt
    var pitm = itm.parentElement;
    while (pitm && (pitm != pbody) ) {
      var hx = (pitm.offsetHeight - pitm.clientHeight); // itm border hgt
      itm_hx += hx; // itm border hgt
      pitm = pitm.parentElement;
    }

     oPopup.hide();
    var hgt = itm_hgt + itm_hx + 1;
    if (maxHgt && maxHgt< hgt)  {
      itm.style.overflowY = "scroll";
      hgt=maxHgt;
    }
    // popx and popy added to remove the x and y pos settings from this script and into ts_frame.html
    try{popx = xpos;}		// @A8A
    catch(e){popx = -4;}	// @A8A
    try{popy = ypos;}		// @A8A
    catch(e){popy = 19;}	// @A8A

    pbody.style.visibility="visible";
    if (Terminal && Terminal.guiRules)      /*@B3 AutoGUI skin*/
       Terminal.guiRules.initialGUIPopup(); /*@B3 AutoGUI skin*/
    oPopup.show(popx, popy, popWidth, hgt, baseEl);	// @A8C
}

function aboutPopup(menuID, popWidth)
{
    var ContentHTML = menuID + "HTML";
    document.getElementById("appVer").innerText = Terminal.AppVersion();

    oPopup.document.body.innerHTML =
MyStyleTable()+document.getElementById(ContentHTML).innerHTML;
    oPopup.show(150, 150, popWidth, 220, document.body);
}

// New script function included in PTF 1AX0012 (feb 04)
function SetOVR()
{
	var b = Terminal.CheckOverwrite();
	if(b!=OVR_bool)
	{
		//if(OVR_bool) alert('Overwrite mode on');
		OVR_bool = Terminal.ChangeOverwrite();
	}

	ovrEl = document.getElementById('OVR')
	if(OVR_bool) //overwrite mode
	{
		ovrEl.innerText = "OVR";
	}
	else //insert mode
	{
		ovrEl.innerText = "INS";
	}

}

// New script function included in PTF 1AX0012 (feb 04)
function ChangeOVR()
{
	if((Terminal.document.activeElement.id.indexOf("ifld")!=-1)||(Terminal.document.activeElement.id.indexOf("login")!=-1))
	{				//its some kind of input field.
		OVR_bool = Terminal.ChangeOverwrite();
		ovrEl = document.getElementById('OVR');
		if(OVR_bool) //overwrite mode
		{
			ovrEl.innerText = "OVR";
		}
		else //insert mode
		{
			ovrEl.innerText = "INS";
		}
	}
	else {} //the insert key was struck on a text object...not an insert field.
}

// New script function included in PTF 1AX0012 (feb 04)
function TrapKeyDown()
{
 if(window.event.keyCode==0x2D)
  {
  	Terminal.KillEvent(window.event);
  	ChangeOVR();
  	return 0;
  }
}

/*lines added to force 100% zoom at login page PTF1AX0017 (apr 04)*/
var loginZoom = 1;
var loginShow = false;
var restartFlag = false; //To stop restart forcing 100% zoom
function loginSize(bPrint) // Forces login screen to load at 100%   /*@B6C*/
{
	if(!restartFlag)
	{
	  loginZoom = auto_mode ? "auto" : optMenuBar.value;
	  zoomFactor = loginZoom;
	  if (!bPrint)        /*@B6A*/
	     ApplyZoom(1);
	  auto_mode = false;
	  Terminal.AXES.Utils.getTopAxesFrame().document.title = Terminal.SystemName + " - " + "aXesTS";   /*@B7C*/
	  loginShow = true;
	  //sent DBCS alignment changes back to axtx.mjs - showlogin()
	  restartFlag=true;
	  itm = Terminal.document.getElementById('Display'); //@BBA - window size set in login xml
	  if (!bPrint)        /*@B6A*/
	  {                   /*@B6A*/
	    itm.style.height = 300;				//@BBA - window size set in login xml
	    itm.style.width = 500;				//@BBA - window size set in login xml
	  }                   /*@B6A*/
	}
}

function logoutSize() //Returns screen size to as before the login page was shown.
{
	//first... hide the advanced login panel, and anything that has selection lists..they get corrupted by the zoom.
	//objSelect = Terminal.document.getElementById('loginScreentype');
	//vDevice = objSelect.options[objSelect.selectedIndex].innerText;
	Terminal.document.getElementById("advanced").style.display = "none";
	Terminal.document.getElementById("advancedButton").innerHTML = "Advanced";
	if(loginZoom == "auto") auto_mode = true;
	SetZoom(loginZoom);
	loginShow = false;
	Terminal.AXES.Utils.getTopAxesFrame().document.title = Terminal.SystemName + " - " + Terminal.DeviceName + " - " + Terminal.tsLoginName + " - " + Terminal.JobNum; //@A2C Changed to tsLoginName /*@B7C*/
	Terminal.document.body.style.layoutGridMode = "char"; //Turns on DBCS alignment correction.
	Terminal.document.body.style.layoutGridChar = "auto";
	/*if (Terminal.Cursor && Terminal.Cursor.xGrid > 0)*/     /*@B9A*//*@C0D*/
	/*   Terminal.document.body.style.layoutGridChar =  Terminal.Cursor.xGrid;*/ /*@B9A*//*@C0D*/
	Terminal.document.body.style.layoutGridType = "strict";
	restartFlag=false;
}

//Function added to allow 100% login scaling - see body tags onresize... PTF0017 (May 04)
function SetLoginZoom()
{
	var tx = Terminal.TermW();
    	var ty = Terminal.TermH();
    	zs = CalcZoom(tx,ty);
    	Terminal.document.body.style.display = "none";
	ApplyZoom(zs);
	document.recalc();
	ApplyZoom(1);
	document.recalc();
	Terminal.document.body.style.display = "block";
	showCursorTest();
}


function playAlert()
{
	document.getElementById('sound1').src="error.wav";
}

//Add Message function displays a text message in the select box under the fkeys...and moves previous messages
//down the list.
function newMessage(txt)
{
	playAlert();
	msgSelect = document.getElementById('msgbar');
	if(txt!=null)
	{
		msgSelect.disabled = false; //enable the select box.
		i=msgSelect.options.length;
		msgSelect.options[i]= new Option("");
		i++;
		while(i>1)
		{
			msgSelect.options[i-1].text = msgSelect.options[i-2].text;
			/*if(msgSelect.options.length%2)
			{
				msgSelect.options[i-1].className = (i%2) ?  "low" : "low"  ; //can have alternating colours..
			}
			else
			{
				msgSelect.options[i-1].className = (i%2) ?  "low" : "low"  ; //can also be ugly
			}*/
			i--;
		}
		msgSelect.options[0].text = txt;
		//msgSelect.options[0].className = (msgSelect.options.length%2) ? "high" : "low";
		msgSelect.options[0].className = "low";
		//change the background colour of the box.
		//msgSelect.className = "msg_enabled";

	}

}
function ClearMessages()
{
	msgSelect = document.getElementById('msgbar');
	msgSelect.options.length = 0;
	msgSelect.className = "msg_disabled";
	msgSelect.disabled = true;
}
function showKeyMap(obj)
{
  //  alert( "show" ) ;
	xmldoc=Terminal.currentKeyXML();
	xsldoc=document.getElementById('KeyMapXSL').XMLDocument;
	htmldoc = document.getElementById('keymapHTMLinner');

	KeyMapXSL.readyState.toString().match("interactive|complete");
	htmldoc.innerHTML = document.getElementById('keymaps').innerHTML + xmldoc.transformNode(xsldoc.documentElement);
	if(obj) obj.className = "popupSelected";


	showPopup('keymap','keyboard',300,400);

}

function SetKeyMap(mapref)  // called to set keymap
{
  //  alert( "set km: " + mapref );
  newref = "/ts/" + mapref;
  Terminal.LoadKeyMap(newref);
  key_map = mapref;
  oPopup.hide();

}

//This function loads the languages from the file LanguageList.xml
//This function has been disabled until a future release.
var langlist = false;
function loadLanguages()
{
	lg_xmldoc=document.getElementById("LanguageXML").XMLDocument;
	lgNode = lg_xmldoc.documentElement;
	optionNode = lgNode.firstChild;
	langHTML = document.getElementById('languageHTMLinner').innerHTML;
	while(optionNode)
	{
		txt_1 = '<a href="#" name="sessitem" class="popup_item" hidefocus="true" onfocus="this.blur()" onclick="setLang(';
		txt_2 = "'"+ optionNode.attributes.getNamedItem('value').nodeValue + "'";
		txt_3 = txt_1 + txt_2 + ')" >';
		langHTML = langHTML + txt_3 + optionNode.firstChild.nodeValue + '</a>'
		optionNode= optionNode.nextSibling;

	}
	document.getElementById('languageHTMLinner').innerHTML = langHTML;
	langlist=true;
}

function setLang(lng)
{
	//this function will send a command to the host with the selected language.
	//The value of the current language will be returned to it??
	//It will then set the value of the current language in the language popup menu.
	alert("Send command to Terminal - " + lng);

}
/* @A6C - function removed. It did nothing anyway.
function EnableKeyFrame(stat)
{
	if(stat< 0 || loginShow)
	{
		parent.tabset.disableKeymapFrame();
	}
	else
	{
		parent.tabset.enableKeymapFrame();
	}

}
*/
function doRefresh()
{
	if(!loginShow)
	{	try{ Terminal.SendRefresh()}
		catch(e) {}
	}

	showCursorTest();
}
function doCancel()
{
	if(!loginShow)
	{	try{ Terminal.ClickSyskey(6)}
		catch(e) {}
	}

	showCursorTest();
}
function PrintTerminal()
{
	Terminal.document.title = Terminal.AXES.Utils.getTopAxesFrame().document.title;
	Terminal.print();
}
function beforePrint()
{
	loginSize(true);     /*@B6C*/
}
function afterPrint()
{
	logoutSize();
}
function holdKeystroke(evt)
{
	Terminal.KillEvent(evt);
	newMessage(Terminal.axMessage["keyFocus"]); //@B8C
	showCursorTest();
}
// @A5A - Function added to set login preferences
function setLoginPrefs()
{
	Terminal.enableLoginFields();
	if(usrref) Terminal.loginUser.value = usrref;
	if(reconref=="true") {Terminal.loginReopen.checked = true;}
	else {Terminal.loginReopen.checked = false;}
	//wrkstation type is set by the host. Or by SetLoginVals() in axes_login.xml

	if(devref) Terminal.loginDevice.value = devref;
	if(pgmref) Terminal.loginPgm.value = pgmref;
	if(mnuref) Terminal.loginMenu.value = mnuref;
	if(curlibref) Terminal.loginCurlib.value = curlibref;
	if((encryptref=="true")&&passref)
	{
		unencryptPwd();
	}
	else if(passref)
	{
		Terminal.loginPwd.value = passref;
	}

	if(autologinref =="true") Terminal.SendLogin();


	autologinref=false; //So that autologin only works on the initial load

}

// @A5A - Function added to decrypt password created by Command.html in the development kit.
function unencryptPwd()
{
	var bpi = "31415926535897932384626433832795028841971693993751058209749445923078164062";
	var es = Terminal.ARC4decrypt(bpi, passref,Terminal.MD5s);

	Terminal.loginPwd.value = es;
}

// @A5A function to reset prefs if changed by user
function resetVals()
{
	usrref 	= Terminal.loginUser.value;
	reconref 	= Terminal.loginReopen.checked;
	devref		= Terminal.loginDevice.value;
	pgmref		= Terminal.loginPgm.value;
	curlibref	= Terminal.loginCurlib.value;
	mnuref		= Terminal.loginMenu.value;
	passref		= "";

	screenSelect = Terminal.loginScreentype;
	scrnref		= screenSelect.options[screenSelect.selectedIndex].value;

}

// @B0A function to auto scale html.
function resize()             /*@B0A*/
{                             /*@B0A*/
   try                        /*@B0A*/
   {                          /*@B0A*/
	 Terminal.resizeHTML();   /*@B0A*/
   }                          /*@B0A*/
   catch (e)                  /*@B0A*/
   {                          /*@B0A*/
   }                          /*@B0A*/
}                             /*@B0A*/
