function CheckPlatform(){  
 if (navigator.userAgent.indexOf("Mac") != -1){return "mac";}else{return "pc";}
}

function byName(a, b) {
 var anew = a.toLowerCase();
 var bnew = b.toLowerCase();
 if (anew < bnew) return -1;
 if (anew > bnew) return 1;
 return 0;
}
// ThisArray = the array needing sorting
// Indx is the horizontal index needing sorting on
// StrVal indicates if this is a string value you need to sort - true or false
function SortUtil(ThisArray, Indx, StrVal, UpDown){ 
 if (StrVal){
  if (UpDown){
   ThisArray.sort(function(a,b){return byName(b[Indx], a[Indx]);});  
  }else{
   ThisArray.sort(function(a,b){return byName(a[Indx], b[Indx]);});}
 }else{
  if (UpDown){
   ThisArray.sort(function(a,b){ return a[Indx] - b[Indx];});
  }else{
   ThisArray.sort(function(a,b){ return b[Indx] - a[Indx];});
  }  
 }
}

//more simple numerical sorting function
//used for sorting budget arrays in time / expense entry screens
function numberorder(a,b) {
   return a[0] - b[0];
}
  
//returns version of ir
//if not ie returns -1
function WhatVersion() {
var li_val = 0;

   if (document.all) {
      li_val = ScriptEngineMajorVersion();
      li_val += (ScriptEngineMinorVersion()/10);
   }
   else {
      li_val = -1;
   }
   return li_val;
}
// Add Function to resolve ITS527
function RoundNumber(Val,Places) {
// Use toFixed if it Exists - MaB*07/04/08
if ( (isMac != true) && (Val.toFixed))
{
  var num = Val.toFixed(Places);
} else {
  var negchr = Number(Val);
  var temp = Number(Val)
  var nPlace = Math.pow(10,Places);
  var sPlace = '';
  for (var i=0;i<Places;i++) {
    sPlace += '0';
  }
  if (isNaN(temp)) {temp ='0.'+sPlace;}
  else {
    temp = Math.round( (temp*nPlace)+0.001);
    temp = (temp/ nPlace);
  }

  // Test if  The Floating Point Division has returmed more Places
  var X = String(temp).split(".");
  var num = Math.floor(Math.abs(X[0])).toString();

  if ((Number(negchr) < 0) && (Number(num) != 0)){
    num = '-' + num;
  }

  if(Places>0) {
    if (X.length == 1){X[1] = sPlace;}
    else {X[1] += sPlace;}
    num = num + "." + X[1].substring(0,Places);
  }
}
  return Number(num);
}

function FormatMoney(Val, DoComma){
  var negchr = Number(Val);
  if (Val==null){return '&nbsp;'}
  var temp = RoundNumber(Val,2);//(Math.round(Val * 100)) / 100;
  var test = "";
  if (isNaN(temp)) {return 0.00;} else
  {
    var X = String(temp).split(".");
	if (X.length == 1){X[1] = "00";}
	if (X[1].length == 1){X[1] += "0";}
    var num = Math.floor(Math.abs(X[0])).toString();

    if ((num.length > 3) && (DoComma != false)){
	 var Y = reverse(num);
	 Y = Y.match(/\d{1,3}/g); // this is the line where the "-" is getting dropped
	 Y = reverse(Y.join(","));
	 num = Y;
	}
//	alert(negchr + " >>> " +  Val + " >>> " + num + " >>> " + (Number(negchr) < 0) + " >>> " + (Number(num) > 0) + " >> ");
	//if ((Number(negchr) < 0) && (Number(num) != 0)){return "-" + num + "." + X[1];}else{return num + "." + X[1];}
   if (Number(negchr) < 0) {return "-" + num + "." + X[1];}else{return num + "." + X[1];}
  }
}

//nm 15/2/08
//shows values as whole numbers if whole numbers with no decimal i.e 10 instead of 10.00
//or as decimal numbers to two decimal places if decimal part i.e. 10.5 will shows as 10.50
function FormatUnits(Val, DoComma){  
  var negchr = Number(Val);
  if (Val==null){return '&nbsp;'}
  var temp = (Math.round((Val * 100)+0.001)) / 100;
  var test = "";
  var seperator = ".";
  
  if (isNaN(temp)) {return 1;} else 
  {
    var X = String(temp).split(".");
	if (X.length == 1){
      X[1] = "";
      seperator = "";}
	if (X[1].length == 1){X[1] += "0";}
    var num = Math.floor(Math.abs(X[0])).toString();

    if ((num.length > 3) && (DoComma != false)){
	 var Y = reverse(num);
	 Y = Y.match(/\d{1,3}/g); // this is the line where the "-" is getting dropped
	 Y = reverse(Y.join(","));
	 num = Y;
	}
//	alert(negchr + " >>> " +  Val + " >>> " + num + " >>> " + (Number(negchr) < 0) + " >>> " + (Number(num) > 0) + " >> ");	
	//if ((Number(negchr) < 0) && (Number(num) != 0)){return "-" + num + "." + X[1];}else{return num + "." + X[1];}
   if (Number(negchr) < 0) {return "-" + num + seperator + X[1];}else{return num + seperator + X[1];}
  }
}

//format as a whole number
function FormatWholeNumber(Val) {
var li_val = 0;
 
    li_val = Number(Val);
  
    //if number not correct
    if (isNaN(li_val)) { li_val = 0;}
    
    li_val = Math.round(li_val);
    
    return li_val;
}

function reverse(s) {
 if(!s.length) return "";
 var lastchar=s.charAt(s.length-1);
 var allbutlastchar=s.slice(0,-1);
 return lastchar+reverse(allbutlastchar);
}

function GetDateString(){
  var temp = new Date();
  //nm - 14/9/06 - change from getyear to getfullyear
  //to deal with firefox quirk
  var y = temp.getFullYear();
  var m = temp.getMonth()+1;
  var d = temp.getDate();
  var ls_result = "";
  
//  if (document.all.TmShortDateFormat.value != "MM/dd/yyyy") {
  if (getElmById("TmShortDateFormat").value != "MM/dd/yyyy") {
     ls_result = d+"/"+m+"/"+y;}
  else {
     ls_result = m+"/"+d+"/"+y;}
	 
  return ls_result;
}

function FormatDate(Val){
  Val = Val.toString();
  if (Val == '0') 
    {return '&nbsp;'} 
  else 
    {
	if (Val.length == 8) {
  	  if (getElmById("TmShortDateFormat").value != "MM/dd/yyyy") {
	    return Val.substr(6, 2) + "/" + Val.substr(4, 2) + "/" + Val.substr(0, 4);}
  	  else {
	    return Val.substr(4, 2) + "/" + Val.substr(6, 2) + "/" + Val.substr(0, 4);}
	}	
	else { 
  	  if (getElmById("TmShortDateFormat").value != "MM/dd/yyyy") {
	     return Val.substr(0, 2) + "/" + Val.substr(3, 2) + "/" + Val.substr(7, 4);}
  	  else {
	    return Val.substr(0, 2) + "/" + Val.substr(3, 2) + "/" + Val.substr(7, 4);}
	} 
  }
}

function FormatDateFancy(Val){
  YMonth = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
  extrabit = new Array("","st","nd","rd","th","th","th","th","th","th","th","th","th","th","th","th","th","th","th","th","th","st","nd","rd","th","th","th","th","th","th","th","st"); 
 
  Val = Val.toString();
  if (Val == '0') 
    {return '&nbsp;'} 
  else 
  {
     if (getElmById("TmShortDateFormat").value != "MM/dd/yyyy") {
	    return Number(Val.substr(6, 2)) + extrabit[Number(Val.substr(6,2))] + " " + YMonth[Number(Val.substr(4, 2))-1] + " " + Val.substr(0, 4);}
	 else {
	    return YMonth[Number(Val.substr(4, 2))-1] + " " + Number(Val.substr(6, 2)) + extrabit[Number(Val.substr(6,2))] + " " + Val.substr(0, 4);}
  }
}

function GetDate(F1, Action){
  var szUrl = "../calnew.htm";
  var Result = "";
  if (getElmById("TmShortDateFormat").value != "MM/dd/yyyy"){
    Result = F1.value + "/N"; //yep it's english date format
  }else{
    Result = F1.value + "/Y"; //it's american date format
  }
  
  if (isMac || isIE){
    var szFeatures = "dialogWidth:237px;dialogHeight:230px;status:0;help:0;resizable:no;scroll:no";
    Result = window.showModalDialog(szUrl, Result, szFeatures);
    F1.value = Result;
  }else{
    var szFeatures = "height=210px, width=247px, modal=yes, dialog=yes, dependent=yes";
    objDateEdit = F1;
    if (!Action){Action = "";}
    
    if(WindowObjectReference == null || WindowObjectReference.closed) {
      WindowObjectReference = window.open(szUrl+"?"+Result+Action, "_blank", szFeatures);
    } else {
      WindowObjectReference.focus();
    }
    //WindowObjectReference.moveTo(0,0);
  }
}

//nm 3/10/2002
//not the best bit of work i've done - prob needs to be redone
//check that date is not 
function GetDateNotAfterToday(F1)
{
 var szUrl = "../calnew.htm";
// var szFeatures = "dialogWidth:237px;dialogHeight:230px;status:0;help:0;resizable:no;scroll:no";
 var Result = ""; 
// if (document.all.TmShortDateFormat.value != "MM/dd/yyyy") {
 if (getElmById("TmShortDateFormat").value != "MM/dd/yyyy") {
    Result = F1.value + "/N";} //yep it's english date format
 else {
    Result = F1.value + "/Y";} //it's american date format
 //Result = window.showModalDialog(szUrl, Result, szFeatures);
  if (isMac || isIE){
    var szFeatures = "dialogWidth:237px;dialogHeight:230px;status:0;help:0;resizable:no;scroll:no";
    Result = window.showModalDialog(szUrl, Result, szFeatures);
    F1.value = Result;
  }else{
    var szFeatures = "height=210px, width=247px, modal=yes, dialog=yes, dependent=yes";
    objDateEdit = F1;
    window.open(szUrl+"?"+Result, "_blank", szFeatures);
  }
  Result = F1.value;
 var d_now = new Date();
 var ls_year = "";
 var ls_month = "";
 var ls_day = "";
 var li_index = 0;
 var ls_temp = "";
 
 if (getElmById("TmShortDateFormat").value != "MM/dd/yyyy") {
 li_index = parseInt(Result);
 ls_day = String(li_index);
 
 if (li_index < 10) {
    ls_temp = Result.substr(2,Result.length-2);}
 else {
    ls_temp = Result.substr(3,Result.length-3);}

 li_index = parseInt(ls_temp);
 ls_month = String(li_index-1); //months work from 0
 } //close if
 else { //open else
 li_index = parseInt(Result);
 ls_month = String(li_index-1); //moths work from 0
 
 if (li_index < 10) {
    ls_temp = Result.substr(2,Result.length-2);}
 else {
    ls_temp = Result.substr(3,Result.length-3);}

 li_index = parseInt(ls_temp);
 ls_day = String(li_index); 
 } //close else
 
 ls_year = Result.substr(Result.length-4,4);

 var d_there = new Date(ls_year,ls_month,ls_day);

 if (d_there > d_now) {
    alert("Not allowed choose date in future");
    if (getElmById("TmShortDateFormat").value != "MM/dd/yyyy") {
       Result = d_now.getDate() + "/" + String(d_now.getMonth()+1) + "/" + d_now.getFullYear();}
	else {
	   Result = String(d_now.getMonth()+1) + "/" + d_now.getDate() + "/" + d_now.getFullYear();}
 }
 
 F1.value = Result;
}

function GetDOBDate(F1)
{
 //var szUrl = "../calDOB.htm";
 var szUrl = "../calnew.htm"; // MaB*10/07 - Calendar updated for any year!
 var szFeatures = "dialogWidth:237px;dialogHeight:230px;status:0;help:0;resizable:no;scroll:no";
 var Result = "";
 if (getElmById("TmShortDateFormat").value != "MM/dd/yyyy") {
    Result = F1.value + "/N";} //yep it's english date format
 else {
    Result = F1.value + "/Y";} //it's american date format
 // MaB*18/10/06 - Replace call method for FF
 // Result = window.showModalDialog(szUrl, Result, szFeatures);
 // F1.value = Result;
   if (isMac || isIE){
    var szFeatures = "dialogWidth:237px;dialogHeight:230px;status:0;help:0;resizable:no;scroll:no";
    Result = window.showModalDialog(szUrl, Result, szFeatures);
    F1.value = Result;
  }else{
    var szFeatures = "height=210px, width=247px, modal=yes, dialog=yes, dependent=yes";
    objDateEdit = F1;
    window.open(szUrl+"?"+Result, "_blank", szFeatures);
  }
}

//nm - 14/10/08 - old GetHelp function -
//before new help in v 2.2.1
/*function GetHelp(ref){
//  var childWindow = window.open(Arry_Sys_Defs[2]+"tempus pro online help manual.html", "HELP", "status=yes,scrollbars=yes,resizable=yes,menubar=yes,directories=no"); //
  var szUrl = Arry_Sys_Defs[2]+"tempus pro online help manual.html";
  var szFeatures = "status=yes,scrollbars=yes,resizable=yes,menubar=yes,directories=no";
  var childWindow = window.open(szUrl, "HELP", szFeatures);


  childWindow.resizeTo(screen.availWidth, screen.availHeight);
  childWindow.moveTo(0, 0);
  HelpWindow = childWindow;
  HelpPage = ref;
  setTimeout("navigateHelp()", 800);
}*/

function GetHelp(ref){
   HelpPage = ref;
    //
   var szUrl = (Arry_Sys_Defs[2] + '#StartTopic=' + HelpPage); 
   var szFeatures = "status=yes,scrollbars=yes,resizable=yes,menubar=yes,directories=no";
   var HelpWindow = window.open(szUrl, "HELP", szFeatures);

   HelpWindow.resizeTo(screen.availWidth, screen.availHeight);
   HelpWindow.moveTo(0, 0);
}

//ITS*706 - Help Putton Routines
function AddHelpBtn(cnt,Size,Boxed) {
var ls_text = '';
var lsBorder = '';
var lsMouse = '';
if (!cnt) cnt='';
if (!Size) Size=24;
if ((Size != 32) /*&& (Size !=16)*/ ) Size=24;
var iSize = Size + 2;
if (Boxed) {
  lsBorder = 'border:#ffffff 2px outset;';
  lsMouse  = ' onmouseout="this.style.borderStyle =\'outset\'" onmouseover="this.style.borderStyle =\'inset\'"';
}else{
  lsBorder = 'border:2px groove;border-Color:transparent;';
  lsMouse  = ' onmouseout="this.style.borderColor =\'transparent\'" onmouseover="this.style.borderColor =\'#ffffff\'"';
}
var imgDir = Arry_Sys_Defs[0];
  ls_text += '<img id="HelpBtn'+cnt+'" align="middle" valign="middle" alt="Help!" title="Help!" src="'+imgDir+'HelpB_'+Size+'.gif" onclick="javascript:DisplayHelp()" '+lsMouse+' style="cursor:pointer; '+lsBorder+'">&nbsp;';
  return ls_text;
}

function AddHelpDiv(pTop,pRight,Size,Boxed){
var oBodyStyle;
var Result = '';
if (!isMac){ // Not available to MAC
  if (!pTop) pTop =5;
  if (!pRight) pRight=10;
  if (!Size) Size=32;
  if (Boxed==null) Boxed = false;
  if (isMac||isIE){
    var oBodyStyle = document.body.currentStyle;
  }else{
    var oBodyStyle = window.getComputedStyle(document.body, null);
  }
  var marR = pRight + parseInt(oBodyStyle.marginRight);
  var ls_pos = ' top:'+pTop+'px; Right:'+marR+'px;';
  Result = '<div id="divHelp" align="center" title="Help!" style="position:absolute;'+ls_pos+'">'+AddHelpBtn('',Size,Boxed)+'</div>\n';
  }
  return Result;
}

//nm - 14/10/08 - function no longer in use
//before new help in v 2.2.1
function navigateHelp(){
//nm - put this in to allow time for window to open as it takes longer in macs
if (navigator.platform == "MacPPC"){
   alert("Loading Help");}
//   
  if (HelpWindow.frames[1] != null){ // sometimes the frameset is not fully loaded by the time this code is run
    //HelpWindow.frames[1].navigate(Arry_Sys_Defs[2] + HelpPage);
    HelpWindow.frames[1].location = (Arry_Sys_Defs[2] + HelpPage);
    HelpWindow.focus();
  }
}
// Function to Map an Address - MaB*08/04/08
function AddFindMap() {
var imgDir = Arry_Sys_Defs[0];
var MapQuery = Arry_Sys_Defs[4];
var res= '';
if (MapQuery.toUpperCase() != 'NONE') {
  res = '<span style="cursor:pointer;" onclick="MapIt();"><img src="'+imgDir+'find_map.gif" title="Get Map for current Address"></span>';
}
return res;
}

function MapIt() {
var QryAddress = '';
var MapQuery = Arry_Sys_Defs[4];
if (MapQuery == '') {MapQuery =  'http://maps.google.com/maps?q=';}
var res = '';
var oLine;
  for(var i=1;i<5;i++) {
    oLine =getElmById("txtAddress"+i);
    if ((oLine != null ) && (oLine.value != "")) {
      if(QryAddress!="") QryAddress +='+';
      QryAddress += oLine.value;
    }
  }
  oLine =getElmById("txtPostCode");
  if ((oLine != null ) && (oLine.value != "")) {
    if(QryAddress!="") QryAddress +='+';
    QryAddress += oLine.value
  }

  if (QryAddress != '') {
    var CallMap = MapQuery+encodeURI(QryAddress);
    eval("winMap = window.open(CallMap, 'MapIt', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=800,height=600');"); //,left = 0,top = 0
  }
}

// Use Timer to Set focus correcly in FF -MaB
function SetFormFocus(FE){
   //FE.focus()
   setTimeout(function(){FE.focus()}, 10);
   setTimeout(function(){FE.select()}, 15);

}
function IntToHrsMin(Val){
  var h,m;
  var sign = "";
  if (Val==null){return "&nbsp;";}
  if (Val < 0) (sign = '-');
  h = Math.floor(Math.abs(Val / 60) );
  //alert(h);
  m = Math.abs((Val % 60));
   
  //if (h.length == 1) {h = '0' + h}

  if (m.toString().length == 1){m = '0'+m;}
 // if (m == 0) {m = '00'}else{m = m.toString()}
  return sign + Math.floor(h).toString() + ':' + m;
}


//nm - 14/2/06
//this function should not be used
//you should use inttohrsdecx instead
function IntToHrsDec(Val){ 
  var h,m;
  var sign = "";
  if (Val==null){return "&nbsp;";}
  if (Val < 0) (sign = '-');
  h = Math.floor(Math.abs(Val / 60) );
  //alert(h);
  m = Math.abs((Val % 100));

  //if (h.length == 1) {h = '0' + h}

  if (m.toString().length == 1){m = '0'+m;}
 // if (m == 0) {m = '00'}else{m = m.toString()}
  return sign + Math.floor(h).toString() + '.' + m;
}

function IntToHrsDecX(Val){ 
  var h, m;
  var sign = "";
  if (Val==null){return "&nbsp;";}
  if (Val < 0) (sign = '-');
  
  h = Math.floor(Math.abs(Val / 60) );
 
  m = Math.abs((Val % 60));
  m = Math.floor(((m / 60) * 100));

  if (m.toString().length == 0){m = '0.0';}

  return sign + Math.floor(h).toString() + '.' + m;
}

function IntToDays(Val, MinsPDay){
  var d,m,r;
  var sign = "";
  if (Val==null){return "&nbsp;";}
  if (Val < 0) (sign = '-');
  m = MinsPDay;
  d = Math.abs(Val / m);
  d = (Math.round((d*100+0.001)))/100;
  return sign + d;
}

function IntToBoxVals(Val, HrsBox, MinsBox){
  var h,m; 
  h = Math.floor(Val / 60);
  m = Val % 60;
 // alert(h);
 // alert(m);
  if (m.toString().length == 1){m = '0'+m;}
 // if (m == 0) {m = '00'}else{m = m.toString()}
  HrsBox.value = h;
  MinsBox.value = m;
}

function HrsMinsToInt(Val){
  var Tm = Val.split(":");
 // alert(Number(Tm[0] * 60) + Number(Tm[1]));
  return (Number(Tm[0] * 60) + Number(Tm[1]));
}

function BoxValsToInt(HrsBox, MinsBox){
  return (Number(HrsBox.value)*60)+(Number(MinsBox.value));
}

function NumberToPercentage(Val){
  return Math.floor(Val * 100)  + "%";
}

function FormatFloatX(Val,Format){
var ls_formatA = '1';
var ls_formatB = '';

  if (!(isFinite(Val)) || (isNaN(Val))) {
      Val = '0.00';
  }
  else {

   for (var x = 0; x < Format; x++) {
      ls_formatA += '0';
      ls_formatB += '0';
   }

   Format = Number(ls_formatA);  
   Val = (Math.round(Val*Format))/Format;

   //1 - add in .00 if whole number
   //2 - or 0 if .9 sp .90
   var li_pos;
   li_pos = String(Val).indexOf('.');

   if (li_pos == -1) {
      Val = String(Val) + '.00';}
   else if (li_pos != -1) {
     var ls_test = '';
     var li_l = String(Val).length-li_pos;

     ls_test = String(Val).substr(li_pos+1,li_l);

     if (ls_test.length == 1) {
       Val = String(Val) + '0';
     }
   }

  }
  return Val;
}

function Over(T, col){
  T.style.backgroundColor = col;
}
function Out(T, col){
  T.style.backgroundColor = col;
}

function FormatDateTime(Val){ // takes argument of format YYYYMMDDhhmmss and returns datetime string
if (Val != 0) {
var sDate = "";
var sMonth = "";
var sYear = "";
var sTime = "";
var ls_result = "";

if (Val.length != 8) {
   sTime = " " + Val.substr(8,2) + ":" + Val.substr(10,2);}

 sDate = Val.substr(6, 2);
 sMonth = Val.substr(4, 2);
 sYear = Val.substr(0, 4);  

 if (getElmById("TmShortDateFormat").value != "MM/dd/yyyy") {
    ls_result = sDate + '/' + sMonth + '/' + sYear + sTime;}
 else {
    ls_result = sMonth + '/' + sDate + '/' + sYear + sTime;}

}	
return ls_result;
}

function CheckBlankString(Val){
  if (Val == "") {return "&nbsp;";}else{return Val;}
}

function NewShift(Delta, frmAction){
  if (isNaN(Delta)){
    document.forms[0].SelectDate.value = "";
  }else{
    document.forms[0].ShiftDelta.value = Delta;
  }
  document.forms[0].action += frmAction; 
  document.forms[0].submit();
}

function IncYYYYMMDD(YYYYMMDD, Amount){
 var Y = Number(String(YYYYMMDD).substr(0, 4));
 var M = Number(String(YYYYMMDD).substr(4, 2))-1;
 var D = Number(String(YYYYMMDD).substr(6, 2));
 var Dato = new Date(Y, M, D);
 var Dato2 = new Date(86400000*Amount); //one day * Amount
 var Dato3 = new Date(Dato.valueOf()+Dato2.valueOf()); 

//if (getElmById("TmShortDateFormat").value != "MM/dd/yyyy"){
//   return String(Dato3.getDate()) +"/"+ String(Dato3.getMonth()+1) +"/"+ String(Dato3.getFullYear());
// }else{
//   return String(Dato3.getMonth()+1) +"/"+ String(Dato3.getDate()) +"/"+ String(Dato3.getFullYear());
// }
 //format
 D = Dato3.getDate();
 if (D < 10) {
    D = "0" + String(D);}
 else {
    D = String(D);}
 M = Dato3.getMonth()+1;
 if (M < 10) {
    M = "0" + String(M);}
 else {
    M = String(M);}

 if (getElmById("TmShortDateFormat").value != "MM/dd/yyyy"){
   var Dato3 = D +"/"+ M +"/"+ String(Dato3.getFullYear());
 }else{
   var Dato3 = M +"/"+ D +"/"+ String(Dato3.getFullYear());
 }
return Dato3;
}

//nm - does seem to have bug in certain date cases
//currently looking at this 4/12/01
//so not currently using tihs function
function IncYYYYMMDDbyMonth(YYYYMMDD, Amount){
 var Y = Number(String(YYYYMMDD).substr(0, 4));
 var M = Number(String(YYYYMMDD).substr(4, 2))-1;
 var D = Number(String(YYYYMMDD).substr(6, 2));
 var Dato = new Date(Y, M, D);
 M += Amount;
 Dato.setMonth(M);
 //format
 D = Dato.getDate();
 if (D < 10) {
    D = "0" + String(D);}
 else {
    D = String(D);}
 M = Dato.getMonth()+1;
 if (M < 10) {
    M = "0" + String(M);}
 else {
    M = String(M);}
 if (getElmById("TmShortDateFormat").value != "MM/dd/yyyy"){
   var Dato3 = D +"/"+ M +"/"+ String(Dato.getFullYear());
 }else{
   var Dato3 = M +"/"+ D +"/"+ String(Dato.getFullYear());
 }
 return Dato3;
}

function datetoYYYYMMDD(val){
  var DateArry = val.split('/');
  var IResult = "0";
  var EpochYear = 80;
  
  if (DateArry[0].length == 1) {DateArry[0] = "0" + DateArry[0]}
  if (DateArry[1].length == 1) {DateArry[1] = "0" + DateArry[1]}
  
  if (DateArry[2].length == 1) {DateArry[2] = "0" + DateArry[2]}
  if (DateArry[2].length < 4)  {
     if (Number(DateArry[2]) < EpochYear )
       {DateArry[2] = "20" + DateArry[2]}
     else
        {DateArry[2] = "19" + DateArry[2]}
  }
  if (getElmById("TmShortDateFormat").value != "MM/dd/yyyy"){
    IResult = DateArry[2]+DateArry[1]+DateArry[0];
  }else{
    IResult =  DateArry[2]+DateArry[0]+DateArry[1];
  }
  return IResult; 
}

function YYYYMMDDtoDelphiDate(val){
  var nDelphiDateOffset = 25569; // JavaScript dates start at 01/01/1970
  var nYear = Number(String(val).substr(0, 4));
  var nMonth = Number(String(val).substr(4, 2)) - 1;
  var nDay = Number(String(val).substr(6,2));
  var res = new Date(nYear, nMonth, nDay, 12, 0, 0, 0); // add 12 hours to deal with the UTC offset
  return Math.floor(Date.parse(res)/(24*60*60*1000))+nDelphiDateOffset;
}

//nm - 28/05/07
function FormatRemoteDateText(val){ 
  var DateArry = val.split('/');
  var IResult = "0";
  
  //if its blank
  
  if (DateArry[0].length == 1) {DateArry[0] = "0" + DateArry[0];}
  if (DateArry[1].length == 1) {DateArry[1] = "0" + DateArry[1];}
  
  //if year in yy format
  if (DateArry[2].length == 2) {
  //the logic is if it's >= 50 we add in '19'
  //otherwise we add on '20'
  if (Number(DateArry[2]) >= 50) {
     DateArry[2] = '19' + DateArry[2];}
  else {
     DateArry[2] = '20' + DateArry[2];}
  }
  ////////////////
 
  if (getElmById("TmShortDateFormat").value != "MM/dd/yyyy"){
   IResult = DateArry[0]+'/' + DateArry[1] + '/' + DateArry[2];
  }else{
    IResult = DateArry[1]+ '/' + DateArry[0] + '/' + DateArry[2];
  }
  return IResult;
 
}
///

function SelDate(Action){
  document.forms[0].SelectDate.value = FormatDate(document.forms[0].SelectDate.value);
  GetDate(document.forms[0].SelectDate, Action);
  if (isMac || isIE){
    document.forms[0].SelectDate.value = datetoYYYYMMDD(document.forms[0].SelectDate.value);
    NewShift(0, Action);
  }
}

function setReturnDate(Action){
  if (Action){
    objDateEdit.value = datetoYYYYMMDD(DatePickerReturnValue);
    NewShift(0, Action);
  }else{
    objDateEdit.value = DatePickerReturnValue;
    if (objDateEdit.onchange) objDateEdit.onchange();
  }
}

function SelDateP(Action){
  document.forms[0].SelectDateP.value = FormatDate(document.forms[0].SelectDateP.value);
  GetDate(document.forms[0].SelectDateP, Action);
  if (isMac || isIE){
    document.forms[0].SelectDateP.value = datetoYYYYMMDD(document.forms[0].SelectDateP.value);
    NewShift(0, Action);
  }
}

function SelDateOld(Action){
  document.forms[0].SelectDate.value = FormatDateTime(document.forms[0].SelectDate.value);
  GetDate(document.forms[0].SelectDate, Action);
  if (isMac || isIE){
    document.forms[0].SelectDate.value = datetoYYYYMMDD(document.forms[0].SelectDate.value);
    NewShift(0, Action);
  }
}

function EnableAllControls(ThisForm){
  for (var x = 0; x < ThisForm.elements.length ; x++)
  {
   ThisForm.elements[x].disabled = false;
  }
}

function DisbaleAllControls(ThisForm){
 for (var x = 0; x < ThisForm.elements.length ; x++)
 {
  if (ThisForm.elements[x].type != "hidden"){
   ThisForm.elements[x].disabled = true;
  }
 }
}

function GetIndexOf(Sel, Val){
  for (var x=0;x<Sel.length;x++){
    if (Sel.options[x].value == Val){
	  return x;
	}
  }
  return -1;
}

function WriteClient(Details, PName){
  var FPath = getCookie("MSWord");
  var FileObj = new ActiveXObject("Scripting.FileSystemObject");
  if (FPath == null){
    Ex_FileName = prompt("Enter file name",FileObj.GetSpecialFolder(2)+"\\"+PName+".doc");
  }else{
    Ex_FileName = prompt("Enter file name",FPath+PName+".doc");
  }
 
  if (Ex_FileName != null) { //if the person hits cancel
    var WrdApp = new ActiveXObject("Word.Application");
    WrdApp.Documents.Add();
    WrdApp.visible = true;
    var d = new Date();
    var myLetter = WrdApp.ActiveDocument.CreateLetterContent(
      d.toLocaleString(),
      true,
      "",
      1,
      true,
      0,
      2,
      "",
      Details[0][1] + "\n" + Details[0][6] + "\n" + Details[0][7] + "\n" + Details[0][8] + "\n" + Details[0][9] + "\n",
      "Dear " + Details[0][23] + " " + Details[0][24],
      2,
      "",
      "",
      "",
      PName,
      "",
      "",
      "Sender Name",
      "Sincerely yours,",
      "Sender Company",
      "",
      "",
      0);
    WrdApp.ActiveDocument.RunLetterWizard(myLetter, true);
    WrdApp.ActiveDocument.SaveAs(Ex_FileName);
    WrdApp.ActiveDocument.Close();
    WrdApp.Quit(); // release Word (and lock of Normal.dot)
	
	// Re-open document from saved location
    WrdApp = new ActiveXObject("Word.Application");
    WrdApp.visible = true;
	WrdApp.Documents.Open(Ex_FileName);
	
	// set the path cookie
    var Dato = new Date();
    Dato.setYear(Dato.getFullYear() + 1);
	FPath = String(Ex_FileName.substr(0, Ex_FileName.indexOf(PName+".doc")));
	FPath = ReplaceChar(FPath, "\\", "/"); // double \\ required because \ is the JScript "Escape" character
    setCookie("MSWord", FPath, Dato);
    
	// Save document link
	var F = parent.frames.main.document.forms[0];
      var OB = parent.frames.outlookX;
	F.ThisPage.value = Ex_FileName;
	F.action = getElmById("SPath",OB).value + "/AddDocLink";
	F.submit();
  }
}

// IntToHex: converts integers between 0-255 into a two digit hex string.
function IntToHex(n) 
{
	var result = n.toString(16);
	if (result.length==1) result = "0"+result;
	return result;
}

// HexToInt: converts two digit hex strings into integer.
function HexToInt(hex) 
{
	return parseInt(hex, 16); 
}

function AddAmountToColor(Col, Delta){
  return IntToHex(HexToInt(Col) + Delta)
}

function BtnUpNew(Self){
  Self.style.border="#ffffff 2px outset";
}

function BtnDownNew(Self){
  Self.style.border="#ffffff 2px inset";
}

function MouseOut(self){
  self.style.backgroundColor = GridBodyColor;
}
function MouseMove(self){
  self.style.backgroundColor = GridBodyOverColor;  
}
function MseHdrOut(self){
  self.style.backgroundColor = TableHeaderColor;
}
function MseHdrOver(self){
  self.style.backgroundColor = TableHeaderOverColor;
}

function RedoIcon(A,V){
  var F = parent.frames.main;
  if (!(isMac || isIE)){ // note "value" is not a valid attribute of the <img> tag and will only be read in IE (HS)
    V = getElmById(A, F).src.substr(getElmById(A, F).src.length-6, 2);
  }
  
  if (V == "SU"){
    getElmById(A, F).src = Arry_Sys_Defs[0] + "SD.gif";
	getElmById(A, F).value = "SD";
  }else{
    getElmById(A, F).src = Arry_Sys_Defs[0] + "SU.gif";
	getElmById(A, F).value = "SU";
  }
}
 
 function RedoIconX(A,V) {

 var F = parent.frames.outlookX;
 var ls_a = "";
 var ls_b = "";
 
 if (V == "SU") {
    ls_a = "getElmById(A, F).src = '" + Arry_Sys_Defs[0] + "SD.gif';";
	ls_b = "getElmById(A, F).value = 'SD';"}
 else {
    ls_a = "getElmById(A, F).src = '" + Arry_Sys_Defs[0] + "SU.gif';";
	ls_b = "getElmById(A, F).value = 'SU';"}
 
 eval(ls_a);
 eval(ls_b);
 }

function BrightColor(Col){
  return '#' + AddAmountToColor(Col.substr(1,2), + 40) +
               AddAmountToColor(Col.substr(3,2), + 40) +
               AddAmountToColor(Col.substr(5,2), + 40);
}

function RmvFrstChr(Str){
  //alert("X"+Str.substring(1, Str.length)+"X")
  return Str.substring(1, Str.length);    
}

function CapitalizeX(str) {
    var words = str.toLowerCase().split(" ")
    var ans = ""
    for (i=0; i<words.length; ++i) {
        var w = words[i]
        ans += w.charAt(0).toUpperCase() + w.substring(1,(w.length)) + " "
    } return ans
}

function GetMacTopIndex(Arry,Val) {
   var li_val = 0;

   for(var i = 0; i < Arry.length; i++)
   {
	  if (Arry[i][0] == Val) {
	     li_val = i; break;
	  }  
   }
   
   return li_val;
}

//nm - 26/3/03
//if you load values dynamically into an input field in ie macs
//and if the value is a string over 13ish characters this causes it to 
//display it slightly worng - this function tries to fix this once the page has been loaded
function MacRedoValues(ThisForm) {
var ls_temp = "";

//if it's a mac do this
if (navigator.platform == "MacPPC"){
 for (var x = 0; x < ThisForm.elements.length ; x++)
 {
  if (ThisForm.elements[x].type != "hidden")
  {
     if (ThisForm.elements[x].type == "text") { 
        ls_temp = ThisForm.elements[x].value;
	    ThisForm.elements[x].value = "";
	    ThisForm.elements[x].value = ls_temp;
     }
   }
  }
} //end if mac  

}

function RoundNumberX(Val) {
   Val = (Val*100);
   Val = Math.round(Val+0.001);
   Val = (Val / 100);
 return Val;
}

function FormatTwoPlacesOrMore(Val){
  var negchr = Number(Val);
  if (Val==null){return '&nbsp;'}
  var temp = Math.round((Val * 1000000)+0.001) / 1000000;
  var test = "";
  if (isNaN(temp)){
    return 0.00;
  }else{
    var X = String(temp).split(".");
	if (X.length == 1){X[1] = "00";}
	if (X[1].length == 1){X[1] += "0";}
    var num = Math.floor(Math.abs(X[0])).toString();

	if ((Number(negchr) < 0) && (Number(num) != 0)){
	  return "-" + num + "." + X[1];
	}else{
	  return num + "." + X[1];
	}
  }
}

//takes in a date utc string (in string format) and converts it to a string in the format yyyymmdd
function DateFromUTCString(Val) {
   //
   YMonth = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
   
   var ValParts = Val.split(' ');
   var ls_result = "";
   var ls_date = ValParts[2];
   var ls_month = "";
   
   for (var i = 0; i < YMonth.length; i++) { 
      if (ValParts[1] == YMonth[i]) { ls_month = String(i+1);}}
   var ls_year = ValParts[5];
   
   if (ls_date.length == 1) {ls_date = "0" + ls_date;}
   if (ls_month.length == 1) {ls_month = "0" + ls_month;}
   
   ls_result = ls_year + ls_month + ls_date; 

   return ls_result;
   //
}

function FlipEmpName(s){
  var i = s.indexOf(", ");
  if (i > -1){
    return String(s.substr(i+2, s.length) + " " + s.substr(0, i));
  }else{
    return s;	
  }
}

function ReplaceChar(s, oldChar, newChar){
  var res = "";
  for (var i = 0; i < s.length; i++){
    if (s.substr(i, 1) == oldChar){
      s = String(s.substr(0, i) + newChar + s.substr(i+1, s.length));
	}
  }   
  return s;
}

function Trim(orgString){
  return LTrim(RTrim(orgString))
}

function LTrim(orgString){
  return orgString.replace(/^\s+/,'')
}

function RTrim(orgString){
  return orgString.replace(/\s+$/,'')
}

function RemoveFileNameFromPath(DirStr){
  var LastSlash = DirStr.length;
  for (var i = 0; i < DirStr.length; i++){
    if (DirStr.charCodeAt(i) == 92){
	  LastSlash = i;
	}
  }
  if (isNaN(LastSlash)){
    return DirStr;
  }else{
    return DirStr.substr(0, LastSlash);
  }
}

function ClearText(inputObj){
  if ((inputObj.type == "text") && (inputObj.value == "???")){
    inputObj.value = "";  
  }
}

function checkMaxLength(evt,inputObj, maxLength){
var Ret=true;
var evtobj=window.event? event : evt;
var unicode=evtobj.charCode? evtobj.charCode :evtobj.keyCode
 var KeyID = (window.event) ? event.keyCode : evt.which; // evtobj.keyCode;//
 if ((KeyID > 31) ){ // NOT CONTROL KEY
  Ret = (inputObj.value.length < maxLength);
  if (inputObj.value.length > maxLength){
    inputObj.value = inputObj.value.substr(0, maxLength);
  }
 }
 if (!Ret) {window.status = 'Max Length Exceeded ('+maxLength+')';}
 else {window.status = '';}

 return Ret;
}

function RGBColorToHexColor(RGBColorString){
  // converts style from   rgb(r, g, b) [Integer vals]   to   #rrggbb [Hex vals]
  var FirstComma = RGBColorString.indexOf(',');
  var SecondComma = RGBColorString.lastIndexOf(',');
  var iRed = parseInt(RGBColorString.substr(4, (FirstComma-4)));
  var iGreen = parseInt(RGBColorString.substr((FirstComma+2), SecondComma - (FirstComma+2)));
  var iBlue = parseInt(RGBColorString.substr((SecondComma+2), RGBColorString.length - (SecondComma+3)));
  var sHexColor = '#' + IntToHex(iRed) + IntToHex(iGreen) + IntToHex(iBlue);
  return sHexColor;
}
							  
var GridBodyColor = '#E8F4FF';
var TableHeaderColor = '#336699';

for (var i = 0; i < document.styleSheets.length; i++){
  if ((isMac) || (isIE)){
    var myStyle = document.styleSheets[i].rules;
  }else{
    var myStyle = document.styleSheets[i].cssRules;
  }
  for (var j = 0; j < myStyle.length; j++){
    if (myStyle[j].selectorText) { // Check it exists
      if ((myStyle[j].selectorText.toLowerCase() == ".gridbody") || (myStyle[j].selectorText.toLowerCase() == "*.gridbody")){
        GridBodyColor = myStyle[j].style.backgroundColor;
        if (GridBodyColor.substr(0,3) == 'rgb'){
          GridBodyColor = RGBColorToHexColor(myStyle[j].style.backgroundColor);
        }
      }else if (myStyle[j].selectorText.toLowerCase().indexOf(".gridhead") >= 0){
        TableHeaderColor = myStyle[j].style.backgroundColor;
        if (TableHeaderColor.substr(0,3) == 'rgb'){
          TableHeaderColor = RGBColorToHexColor(myStyle[j].style.backgroundColor);
        }
      }
    }
  }
}

var GridBodyOverColor = '#' + AddAmountToColor(GridBodyColor.substr(1,2), - 30) +
                            AddAmountToColor(GridBodyColor.substr(3,2), - 30) +
                            AddAmountToColor(GridBodyColor.substr(5,2), - 30);

var TableHeaderOverColor = '#' + AddAmountToColor(TableHeaderColor.substr(1,2), - 40) +
                            AddAmountToColor(TableHeaderColor.substr(3,2), - 40) +
                            AddAmountToColor(TableHeaderColor.substr(5,2), - 40);

// NOT IN USE //
/*
var TopBodyColor = '#FFFCC0';
var TopBodyOverColor = '#' + AddAmountToColor(GridBodyColor.substr(1,2), - 40) +
							 AddAmountToColor(GridBodyColor.substr(3,2), - 40) +
							 AddAmountToColor(GridBodyColor.substr(5,2), - 40);

var TopHeaderColor = '#CC0033';
var TopHeaderOverColor = '#' + AddAmountToColor(TableHeaderColor.substr(1,2), - 40) +
							   AddAmountToColor(TableHeaderColor.substr(3,2), - 40) +
							   AddAmountToColor(TableHeaderColor.substr(5,2), - 40);
*/
// End NOT IN USE //

var HelpWindow;
var HelpPage;
var DatePickerReturnValue;
var objDateEdit; // object date is to be returned to
var WindowObjectReference = null; // global variable



/*  *  *  *  *  *  *  *  *  *  *  *  *  *  *  XMLHttpRequest  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  */
if (!isMac){
  var requestObj = getRequestObject();
}else{
  var requestObj = null;
}

function getRequestObject(){
  if (!window.XMLHttpRequest){
    return getActiveXRequestObject();
  }else{
    return new XMLHttpRequest();
  }
}

function ajax1(url, vars, callbackFunction){
  if (requestObj){
    requestObj.open("GET", url, true);
    requestObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    requestObj.onreadystatechange = function(){
      if (requestObj.readyState == 4 && requestObj.status == 200){
        if (requestObj.responseText){
          callbackFunction(requestObj.responseText);
        }
      }
    };
    requestObj.send(vars);
  }
}
function ajax(url, vars, callbackFunction){
var requestObj = getRequestObject()
  if (requestObj){
  try {
    requestObj.open("GET", url, true);
    requestObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    requestObj.onreadystatechange = function(){
      if (requestObj.readyState == 4) {
        if ( requestObj.status == 200){
          var sResponse = requestObj.responseText;
          if (sResponse){
            callbackFunction(sResponse);
          }
        }
      }
    };
    requestObj.send(vars);
  } catch(err)
  {
  txt="There was an error on this page.\n\n";
  txt+="Error description: " +  err.name+':' +err.message  + "\n\n";
  txt+="Call URL: " + url + "\n\n";
  txt+="Click OK to continue.\n\n";
  alert(txt);
  }

  }
}

function getActiveXRequestObject(){
  try{ return new ActiveXObject("MSXML3.XMLHTTP"); }catch(e){}
  try{ return new ActiveXObject("MSXML2.XMLHTTP.6.0"); }catch(e){}
  try{ return new ActiveXObject("MSXML2.XMLHTTP.5.0"); }catch(e){}
  try{ return new ActiveXObject("MSXML2.XMLHTTP.4.0"); }catch(e){}
  try{ return new ActiveXObject("MSXML2.XMLHTTP.3.0"); }catch(e){}
  try{ return new ActiveXObject("Msxml2.XMLHTTP"); }catch(e){}
  try{ return new ActiveXObject("Microsoft.XMLHTTP"); }catch(e){}
  /* try{
    // alert("Could not find an XMLHttpRequest alternative.");
    throw new Error("Could not find an XMLHttpRequest alternative.");
    return null;
  }catch(e){}  */
  return null;
}

// pf
function checkNumeric(value){		
  var anum=/(^\d+$)|(^\d+\.\d+$)/;		
  if (anum.test(value))			
     return true;		
  return false; 
}
// readyState 0 = "uninitialized"
// readyState 1 = "loading"
// readyState 2 = "loaded"
// readyState 3 = "interactive"
// readyState 4 = "complete"
// status 200 = "OK"
// status 304 = "Not modified"
// status 404 = "Not found"
// etc.

