/*
 * tms.js
 *
 * Javascript file with functions used by TMS web pages.
 *
 */

// Constants (or pseudo constants)
var DBNull = new Object();

// Variable declarations (values set by TMSWebPage)
var tmsCommonFiles = null;
var tmsNestingLevel = 0;
var tmsIsCommonPage = false;
var tmsOnlyOneSubmit = false;

var tmsIsSubmitted = false;
var tmsPrevDoPostBack = null;

var tmsShowWaitMessageOnSubmit = false;

var tmsPleaseWaitMessage = 'Please Wait';

function tmsNVL(val, def)
{
	if (val == null)
		return def;
	else
		return val;
}

function tmsShowHelp(url)
{
	window.open(url, 'tmsHelpWindow',
		'height=400,width=320,toolbar=no,location=no,menubar=no,status=no');
}

function tmsShowDialogEx(dlgInfo)
{
	if (dlgInfo == null)
		return null;
	var ver = tmsNVL(dlgInfo.DlgVersion, 1);
	var url = tmsCommonFiles +
		'util/DialogBoxHostFrame.aspx?src=' +	escape(dlgInfo.Url);
	dlgInfo.Window = window;
	var dlgArg = ((ver > 1) ? dlgInfo : dlgInfo.Window);
	if (dlgInfo.IsModal)
	{
		var dlgAttr =
			'dialogWidth: ' + tmsNVL(dlgInfo.DlgWidth, 320) + 'px; ' +
			'dialogHeight: ' + tmsNVL(dlgInfo.DlgHeight, 400) + 'px; ' +
			'resizable: No; status: No; help: No; unadorned: Yes;';
		var rv = window.showModalDialog(url, dlgArg, dlgAttr);
	}
	else
	{
		var dlgAttr = 'height=' + tmsNVL(dlgInfo.DlgHeight, 400) + ',' +
					  'width=' + tmsNVL(dlgInfo.DlgWidth, 320) + ',' +
					  'resizable=yes';
		window.open(url, "_blank", dlgAttr);
	}
	if (ver > 1)
	{
		var rs = tmsNVL(dlgInfo.ReturnStatus, 0);
		if ((rs > 0) || (tmsNVL(dlgInfo.NoPostbackOnCancel, false) == false))
		{
			var cmd = tmsNVL(dlgInfo.PostbackCommand, null);
			if (cmd != null)
			{
				eval(cmd);
			}
		}
		return rs;
	}
	return rv;
}

function tmsCloseDialog(status)
{
	var arg = window.dialogArguments;
	if (arg != null)
	{
		if (tmsNVL(arg.DlgVersion, 0) > 1)
		{
			arg.ReturnStatus = status;
		}
	}
	window.returnValue = status;
	window.close();
}

function tmsShowDialog(commonFiles, url, width, height)
{
	window.showModalDialog(
		commonFiles + '/util/DialogBoxHostFrame.aspx?src=' + escape(url), window,
		'dialogWidth: ' + width + 'px; dialogHeight: ' + height + 'px; ' +
		'center: Yes; resizable: No; status: No; help: No; unadorned: Yes;');
}

function tmsOpenDialog(commonFiles, url, width, height)
{
	window.open(
		commonFiles + '/util/DialogBoxHostFrame.aspx?src=' + escape(url), "",
		'width=' + width + ', height=' + height + ', top=100, left=250, screenY=200, screenX=300, scrolling=no, resizable=no, toolbar=0');
}

function tmsPopUp(commonFiles, url, width, height)
{
	window.open(
		commonFiles + '/util/DialogBoxHostFrame.aspx?src=' + escape(url), "",
		'width=' + width + ', height=' + height + ', top=100, left=250, screenY=200, screenX=300, scrolling=yes, resizable=yes, toolbar=1');
}

function tmsPrintReport(commonFiles, url, width, height)
{
	var child = window.open(
		url, "",
		'width=' + 0 + ', height=' + 0 + ', top=0, left=0, screenY=0, screenX=0, scrolling=yes, resizable=yes, toolbar=1');
}

function tmsGetOpener()
{
	var win = null;
	win = window.dialogArguments;
	if (win != null)
		return win;
	win = window.opener;
	if (win != null)
		return win;
	win = window.top.opener;
	if (win != null)
		return win;
	return null;	
}

function tmsPadString(s, length, padChar)
{
	while (s.length < length)
		s = padChar + s;
	return s;
}

function tmsGetShortMonth(month)
{
	switch (Number(month)+1)
	{
		case 1: return 'Jan';
		case 2: return 'Feb';
		case 3: return 'Mar';
		case 4: return 'Apr';
		case 5: return 'May';
		case 6: return 'Jun';
		case 7: return 'Jul';
		case 8: return 'Aug';
		case 9: return 'Sep';
		case 10: return 'Oct';
		case 11: return 'Nov';
		case 12: return 'Dec';
	}
}

function tmsShortMonthToInt(name)
{
	switch (name.toLowerCase())
	{
		case 'jan': return 1;
		case 'feb': return 2;
		case 'mar': return 3;
		case 'apr': return 4;
		case 'may': return 5;
		case 'jun': return 6;
		case 'jul': return 7;
		case 'aug': return 8;
		case 'sep': return 9;
		case 'oct': return 10;
		case 'nov': return 11;
		case 'dec': return 12;
	}
	return 0;
}

function tmsDateToStringDDMMMYYYY(date)
{
	return tmsPadString(date.getDate().toString(), 2, '0') + '/' +
		tmsGetShortMonth(date.getMonth()) + '/' +
		date.getFullYear().toString();
}

function tmsDateToStringDDMMMYYYYHHMMSS(date)
{
	return tmsPadString(date.getDate().toString(), 2, '0') + '/' +
		tmsGetShortMonth(date.getMonth()) + '/' +
		date.getFullYear().toString() + ' ' +
		tmsPadString(date.getHours().toString(), 2, '0') + ':' +
		tmsPadString(date.getMinutes().toString(), 2, '0') + ':' +
		tmsPadString(date.getSeconds().toString(), 2, '0');
}

function tmsStringToDateDDMMMYYYY(str)
{
  return tmsStringToDateAny(str);
}

function tmsStringToDateDDMMYYYY(str)
{
  return tmsStringToDateAny(str);
}

function tmsStringToDateAny(str)
{
  var pattern = /^\s*(\d{1,2})[\/\-](\d{1,2}|\w{3})[\/\-](\d{2,4})\s*$/;
	var result = str.match(pattern);
	if (result == null)
		return null;
	var day = parseInt(result[1], 10);
	var month = ((result[2].length == 3) ?
	  tmsShortMonthToInt(result[2]) : parseInt(result[2], 10)) - 1;
	var year = parseInt(result[3], 10);
	if (year < 100)
	  year = (year < 70) ? 2000 + year : 1900 + year;
	var d = new Date(year, month, day);
	if ((d == null) || (typeof d != 'object') || (d.constructor != Date))
		return null;
  if ((d.getDate() != day) || (d.getMonth() != month) || (d.getFullYear() != year))
    return null;
	return d;
}

function tmsCheckTime(val)
{
  var m = val.match(/^\s*(\d?\d)\:(\d\d)\s*$/)
  if (m == null)
    return null;
  else
  {
    var hh = parseInt(m[1]);
    var mm = parseInt(m[2]);
    if (hh < 24 && mm < 60)
      return ((hh < 10) ? '0' : '') + hh + ':' + ((mm < 10) ? '0' : '') + mm;
    else
      return null;
  }
}
function tmsValidateTime(source, arguments)
{
  var t = tmsCheckTime(arguments.Value);
  arguments.IsValid = (t != null);
  if (t != null)
  {
    document.getElementById(source.controltovalidate).value = t;
  }
}
function tmsValidateCompareGrtDateDDMMMYYYY(source, arguments)
{  
  var d = tmsStringToDateDDMMMYYYY(arguments.Value);
  var c = tmsStringToDateDDMMMYYYY(source.CompareDate); 
  var v = ((d != null) && (d >= c));  
  arguments.IsValid = v;
}

function tmsValidateFutureDateDDMMMYYYY(source, arguments)
{
  var d = tmsStringToDateDDMMMYYYY(arguments.Value);
  arguments.IsValid = ((d != null) && (d > new Date()));  
}

function tmsSetControlValue(ctlId, value)
{
  var ctl = document.getElementById(ctlId);
  ctl.value = value;
  if (ctl.onchange != null)
    ctl.fireEvent('onchange');
}

function tmsStoreClientSideValue(key, val)
{
  if (val == null)
    return;
  var hf = document.getElementById('__TMSClientValues');
  if (hf == null)
    return;
  var s = null;
  if (typeof(val) == 'number')
    s = '#' + val.toString();
  else if (typeof(val) == 'boolean')
    s = '#' + ((val == true) ? '1' : '0');
  else if ((typeof(val) == 'object') && (val.constructor == Date))
    s = '@' + tmsDateToStringDDMMMYYYYHHMMSS(val);
  else
    s = '$' + escape(val.toString());
  if (s != null)
    hf.value += ''+key+'='+s+';';
}

function tmsTogDgTrVis(rowId)
{
  var trs = document.getElementsByName(rowId);
  if ((trs==2)||(trs.length!=2))
    return;
  var tr1 = trs[0];
  var tr2 = trs[1];
  var tog = document.getElementById(rowId + '_tog');
  if ((tr1==null)||(tr2==null)||(tog==null))
    return;
  var dgExp = parseInt(tr1.dgExp, 10);
  if (dgExp==0)
  {
    tr2.style.display='inline';
    tog.value='-';
    tog.title='Collapse';
    tr1.dgExp='1';
  }
  else if (dgExp==1)
  {
    tr2.style.display='none';
    tog.value='+';
    tog.title='Expand';
    tr1.dgExp='0';
  }
}

function tmsDgSubmitHandler()
{
  var dgs = tmsDataGrids;
  if ((dgs==null)||(dgs.length==0))
    return;
  for (i=0;i<dgs.length;i++)
  {
    var hf=document.all.tags('input')[dgs[i].replace('_', ':')];
    var dg=document.all.tags('table')[dgs[i]];
    if ((hf==null)||(dg==null))
      continue;
    if (dg.trackScroll=='1')
      hf.value+='st='+document.getElementById(dgs[i]+'__Scroller').scrollTop+';';
    for (j=0;j<dg.rows.length;j++)
    {
      var tr=dg.rows[j];
      var dgId=parseInt(tr.dgId, 10);
      if (!isFinite(dgId))
        continue;
      var dgExp=parseInt(tr.dgExp, 10);
      if (!isFinite(dgExp))
        continue;
      hf.value+='x'+dgId+'='+dgExp+';';
    }
  }
}

function tmsWebPageSubmitHandler()
{
  if (tmsOnlyOneSubmit)
  {
    if (tmsIsSubmitted)
    {
      alert('Please wait for the current request to complete');
      event.returnValue = false;
      return false;
    }
    tmsIsSubmitted = true;
  }
  if (tmsShowWaitMessageOnSubmit)
  {
    tmsShowWaitMessage();
  }
  return true;
}

function tmsShowWaitMessage()
{
  var div = document.getElementById('__tmsWaitDiv');
  if (div == null)
  {
    div = document.createElement('div');
    div.id = '__tmsWaitDiv';
    div.innerHTML =
      '<center>' +
        '<span  id="__tmsWaitMsg" class="Notes" style="position:relative;top:100px;">' +
          tmsPleaseWaitMessage + '...<span id="__tmsWaitClock" style="font-family:wingdings;font-size:190%;">&#xb7;</span>' +
        '</span>' +
      '</center>';
    div.style.position = 'absolute';
    div.style.top = '0px';
    div.style.left = '0px';
    div.style.width = '100%';
    div.style.height = '100%';
    div.style.cursor = 'wait';
    div.animFunction = function()
    {
      var clk = arguments.callee.div.all['__tmsWaitClock'];
      var timerId = arguments.callee.timerId;
      if (clk==null) {
        if (timerId!=null) {
          clearInterval(timerId);
          arguments.callee.timerId = null;
        }
        return;
      }
      var i = arguments.callee.animIndex;
      i = (i + 1) % 12;
      clk.innerHTML = '&#' + (0xb7+i) + ';';
      arguments.callee.animIndex = i;
    };
    div.animFunction.animIndex = 0;
    div.animFunction.div = div;
    div.animFunction.timerId = null;
    document.body.appendChild(div);
  }
  div.style.display = 'block';
  var msg = div.all['__tmsWaitMsg'];
  msg.style.pixelTop=Math.min((document.body.clientHeight-msg.clientHeight)/3, 120);
  
  if (div.animFunction.timerId == null)
    div.animFunction.timerId = setInterval(div.animFunction, 200);
}

function tmsDoPostBack(eventTarget, eventArgument)
{
  tmsPrevDoPostBack(eventTarget, eventArgument);
}

function tmsAsyncGetData(args)
{
  if (args == null)
    return false;
  var key, arg, callback, callbackArg;
  key = args.Key;
  arg = args.Arg;
  callback = args.Callback;
  callbackArg = args.CallbackArg;
  if (key == null)
    return false;
  key = key.replace(/\s+/g, '');
  if (key.length == 0)
    return false;
  if (arg != null)
    arg = arg.toString();
  if (typeof(callback) != 'function')
    return false;
  if (callbackArg == null)
    callbackArg = null;
  var url = '' + tmsCommonFiles + 'util/AsyncGetData.aspx?key=' + escape(key);
  if (arg != null)
    url += '&arg=' + escape(arg);
  var func = new Function("data", "\
    var userfunc = arguments.callee.UserFunc; \
    var userarg = arguments.callee.UserArg; \
    userfunc({Success:true, Data:data, CallbackArg:userarg});");
  func.UserFunc = callback;
  func.UserArg = callbackArg;
  var iframe = document.createElement('iframe');
  iframe.style.display = 'none';
  iframe.Callback = func;
  iframe.src = url;
  document.body.appendChild(iframe);
}

function tmsShowForgottenPasswordDialog(commonFiles, sessionKey, arg)
{
	tmsShowDialog(commonFiles, 'common/TMSLogin/TMSForgottenPassword.aspx?key=' + sessionKey + '&arg=' + arg, 500, 250);
}

function tmsShowInvalidUserDialog(commonFiles, sessionKey, arg)
{
	tmsShowDialog(commonFiles, 'common/TMSLogin/TMSNotifyInvalidUser.aspx?key=' + sessionKey + '&arg=' + arg, 250, 250);
}

function tmsShowInventoryDialog(url)
{
	window.open(url, 'tmsInvViewWindow',
		'height=600,width=700,toolbar=no,location=no,menubar=no,status=no, scrollbars=yes');
}

function tmsFormatNumber(num, s)
{
  if (num == null)
    return '';
  if ((s == null) || !isFinite(num))
    return num.toString();
  var i = 0;
  var dp = 0;
  i = s.indexOf('.');
  if (i >= 0)
    dp = s.length - i - 1;
  var delimit = (s.indexOf(',') >= 0);
  var ret = num.toFixed(dp);
  if (delimit)
  {
    if (dp > 0) i = ret.indexOf('.'); else i = ret.length;
    var a = ret.substr(0, i);
    var minus = false;
    if ((a.length > 0) && (a.charAt(0)=='-')) { minus=true; a = a.substr(1); }
    var j = a.length;
    while ((j-=3) > 0)
    {
      a = a.substr(0, j) + ',' + a.substr(j);
    }
    ret = (minus ? '-' : '') + a + ret.substr(i);
  }
  return ret;
}

function tmsFixupAnchors()
{
  var anchors = document.all.tags('A');
  for (var i = 0; i < anchors.length; i++)
  {
    var anchor = anchors[i];
    if (anchor.tmsFixedUp == true)
      continue;
    if (anchor.href.match(/^\s*javascript\:/i) != null)
    {
      var code = anchor.href.substr(anchor.href.indexOf(':')+1);
      anchor.attachEvent('onclick', new Function("" + unescape(code) + ";return false;"));
      anchor.tmsFixedUp = true;
    }
  }
}

function tmsGetFocusId()
{
  var ctl = document.activeElement;
  if (ctl == null)
    return null;
  if (ctl.id != null)
    return ctl.id.toString();
  return null;
}

function tmsSetFocusId(id)
{
  if (id == null)
    return;
  id = id.toString();
  var ctl = document.all[id];
  if (ctl == null)
    return;
  if (ctl.focus != null)
    ctl.focus();
  if (ctl.select != null)
    ctl.select();
}

function tmsSetKeepAlive()
{
  var iframe = document.getElementById('__tmsKeepAliveFrame');
  if (iframe == null)
  {
    document.body.onunload = tmsAddToFunc(
      document.body.onunload, "tmsUnsetKeepAlive();", false);
    var arg = escape(document.location.pathname);
    iframe = document.createElement('IFRAME');
    iframe.id = '__tmsKeepAliveFrame';
    iframe.style.display = 'none';
    document.body.appendChild(iframe);
    iframe.src = tmsCommonFiles + 'KeepAlive/KeepAlive.aspx?url=' + arg;
  }  
}

function tmsUnsetKeepAlive()
{
  var iframe = document.getElementById('__tmsKeepAliveFrame');
  if (iframe != null)
  {
    iframe.src = 'about:blank';
    document.body.removeChild(iframe);
  }
}

function tmsAddToFunc(func, code, append)
{
  var s = '';
  if (typeof(func) == "function" )
  {
    s = func.toString();
    s = s.substring(s.indexOf("{") + 1, s.lastIndexOf("}"));
  }
  if (append) s = s + code; else s = code + s;
  return new Function(s);
}

function tmsGetAbsOffsets(ctl)
{
  if (ctl == null)
    return null;
  var x = 0, y = 0, i = 0;
  while ((ctl != null) && (ctl != document.body))
  {
    x += ctl.offsetLeft;
    y += ctl.offsetTop;
    ctl = ctl.offsetParent;
    if (++i > 80)
      return null;
  }
  return {X: x, Y: y};
}

function tmsSetAbsOffsets(ctl, offs)
{
  if (ctl == null)
    return;
  var parOffs = tmsGetAbsOffsets(ctl.offsetParent);
  if (parOffs == null)
    return;
  ctl.style.pixelLeft = offs.X - parOffs.X;
  ctl.style.pixelTop = offs.Y - parOffs.Y;
}

