/******************************************************************************
 * File Name    : ldapsession.js
 * Description  : JavaScript for controling ldap cookie session
 * Author       : Daniel Saw
 * Create Date  : 04/15/04
 *
 * Change History
 *
 *
 *
 * Version 1.0
 *
 * Copyright (c) 1998-2004 @Road, inc. All Rights Reserved.
 *****************************************************************************/

/***************** Start Util Functions  *****************/
var END_OF_INPUT = -1;

var base64Str;

var base64Count;

var defaultTimeout = 7740; // in seconds;

var base64Chars = new Array(
    'A','B','C','D','E','F','G','H',
    'I','J','K','L','M','N','O','P',
    'Q','R','S','T','U','V','W','X',
    'Y','Z','a','b','c','d','e','f',
    'g','h','i','j','k','l','m','n',
    'o','p','q','r','s','t','u','v',
    'w','x','y','z','0','1','2','3',
    '4','5','6','7','8','9','+','/'
);

function urlDecode(str){
    str=str.replace(new RegExp('\+','g'),' ');
    return unescape(str);
}
function urlEncode(str){
    str=escape(str);
    str=str.replace(new RegExp('\+','g'),'%2B');
    return str.replace(new RegExp('%20','g'),'+');
}

function setBase64Str(str){
    base64Str = str;
    base64Count = 0;
}

function readBase64(){
    if (!base64Str) return END_OF_INPUT;
    if (base64Count >= base64Str.length) return END_OF_INPUT;
    var c = base64Str.charCodeAt(base64Count) & 0xff;
    base64Count++;
    return c;
}

function encodeBase64(str){
    setBase64Str(str);
    var result = '';
    var inBuffer = new Array(3);
    var lineCount = 0;
    var done = false;
    while (!done && (inBuffer[0] = readBase64()) != END_OF_INPUT){
        inBuffer[1] = readBase64();
        inBuffer[2] = readBase64();
        result += (base64Chars[ inBuffer[0] >> 2 ]);
        if (inBuffer[1] != END_OF_INPUT){
            result += (base64Chars [(( inBuffer[0] << 4 ) & 0x30) | (inBuffer[1] >> 4) ]);
            if (inBuffer[2] != END_OF_INPUT){
                result += (base64Chars [((inBuffer[1] << 2) & 0x3c) | (inBuffer[2] >> 6) ]);
                result += (base64Chars [inBuffer[2] & 0x3F]);
            } else {
                result += (base64Chars [((inBuffer[1] << 2) & 0x3c)]);
                result += ('=');
                done = true;
            }
        } else {
            result += (base64Chars [(( inBuffer[0] << 4 ) & 0x30)]);
            result += ('=');
            result += ('=');
            done = true;
        }
        lineCount += 4;
        if (lineCount >= 76){
            result += ('\n');
            lineCount = 0;
        }
    }
    return result;
}

function readReverseBase64(){
    if (!base64Str) return END_OF_INPUT;

   var reverseBase64Chars = new Array();
   for (var i=0; i < base64Chars.length; i++){
    reverseBase64Chars[base64Chars[i]] = i;
   }

    while (true){
        if (base64Count >= base64Str.length) return END_OF_INPUT;
        var nextCharacter = base64Str.charAt(base64Count);
        base64Count++;
        if (reverseBase64Chars[nextCharacter]){
            return reverseBase64Chars[nextCharacter];
        }
        if (nextCharacter == 'A') return 0;
    }
}

function ntos(n){
    n=n.toString(16);
    if (n.length == 1) n="0"+n;
    n="%"+n;
    return unescape(n);
}

function decodeBase64(str){
    setBase64Str(str);
    var result = "";
    var inBuffer = new Array(4);
    var done = false;
    while (!done && (inBuffer[0] = readReverseBase64()) != END_OF_INPUT
        && (inBuffer[1] = readReverseBase64()) != END_OF_INPUT){
        inBuffer[2] = readReverseBase64();
        inBuffer[3] = readReverseBase64();
        result += ntos((((inBuffer[0] << 2) & 0xff)| inBuffer[1] >> 4));
        if (inBuffer[2] != END_OF_INPUT){
            result +=  ntos((((inBuffer[1] << 4) & 0xff)| inBuffer[2] >> 2));
            if (inBuffer[3] != END_OF_INPUT){
                result +=  ntos((((inBuffer[2] << 6)  & 0xff) | inBuffer[3]));
            } else {
                done = true;
            }
        } else {
            done = true;
        }
    }
    return result;
}

function setCookieSession(docname,cookiename,cookievalue,cookiepath)
{
  docname.cookie = cookiename + "=" + cookievalue + "; path=" + cookiepath;
}

function getCookieSession(docname,cookiename) {
   var search = cookiename + "="
   if ( docname.cookie.length > 0) { // if there are any cookies
      offset =  docname.cookie.indexOf(search)
      if (offset != -1) { // if cookie exists
         offset += search.length
         // set index of beginning of value
         end =  docname.cookie.indexOf(";", offset)
         // set index of end of cookie value
         if (end == -1)
            end =  docname.cookie.length
         return unescape( docname.cookie.substring(offset, end))
      }
   }
}

function removeCookieSession(docname,cookiename,cookiepath)
{
  docname.cookie = cookiename + "=0; path=" + cookiepath + "; expires=Thu, 01 Jan 1970 00:00:01 GMT";
}
/***************** End Util Functions  *****************/



/***************** Start Timeout Functions  *****************/
function enablecountdown()
{


  if(getCookieSession(document,"AuthorizationCookie") == null)
  {
   location = "/signout.html";
  }
  else
  {
   var timer = 0;

  timer = getCookieSession(document,"TimeoutValue");

  if(getCookieSession(document,"LastAccessTime") != null)
  {
    var tmpTimeout = defaultTimeout * 1000;

    if(getCookieSession(document,"DefaultTimeoutValue") != null)
     tmpTimeout = getCookieSession(document,"DefaultTimeoutValue") * 1000;

    var lastdate = new Date(getCookieSession(document,"LastAccessTime"));
    var curdate = new Date();
    if ( (curdate.getTime() - lastdate.getTime()) > tmpTimeout ) timer = 0;
   }


  if(timer> 0)
  {
    // window.status = "(TEST ONLY) Timeout count down: " + timer + " sec. "; //:::" + (new Date()).getTime();
    timer -= 1;
    setCookieSession(document,"TimeoutValue",timer,"/");
    setCookieSession(document,"LastAccessTime",(new Date()).toString(),"/");
    setTimeout("enablecountdown()",1000);
  }
  else
  {

    var agt=navigator.userAgent.toLowerCase();


   if( (agt.indexOf("msie") != -1) && (getCookieSession(document,"AuthorizationCookie") != null) )
    {

     openTimeoutWin();

     if(getCookieSession(document,"TimeoutLogout") == 1)
     {
     location = "/signout.html";
     }
     else
     {
     resetTimer();
     enablecountdown();
     }

  }
 else
  {
    alert("Your session has expired!\nPress 'OK' to close the application and sign in again.") ;
    location = "/signout.html";
  }


  }

  }

}

function verifyPassword(docname)
{
  var passStr =  getCookieSession(document,"AuthorizationCookie");

  var removeStr = "Basic ";

  if(passStr.indexOf(removeStr) != -1)
  {
  passStr =  passStr.substring(passStr.indexOf(removeStr)+removeStr.length);
  passStr = decodeBase64(passStr);

   if (passStr.indexOf(":") != -1)
   {
    passStr = passStr.substring(passStr.indexOf(":")+1);
   }

  }

  //alert(passStr);

  if(docname.u2.value == passStr)
  {
   return true;
  }
  else
  {
   return false;
  }

}

function openTimeoutWin()	{

	var pos_left = (screen.availWidth - 350)/2;
	var pos_top =  (screen.availHeight - 200)/2;
	var pathStr = "/timeout.html";
	var feat = 'dialogWidth:380px;dialogHeight:250px;resizable:no;status:no;scroll:no;center:yes;unadorned:yes';

	window.showModalDialog(pathStr, self, feat);
}

function disablecountdown()
{
    if(getCookieSession(parent.document,"DefaultTimeoutValue") != null)
    {
     resetTimerParent();
     setTimeout("disablecountdown()",5000);
    }
}

function resetTimer()
{
  setCookieSession(document,"TimeoutValue",getCookieSession(document,"DefaultTimeoutValue"),"/");
  setCookieSession(document,"LastAccessTime",(new Date()).toString(),"/");
}

function resetTimerParent()
{
  setCookieSession(parent.document,"TimeoutValue",getCookieSession(parent.document,"DefaultTimeoutValue"),"/");
  setCookieSession(parent.document,"LastAccessTime",(new Date()).toString(),"/");
}

function displayTimeoutHour()
{
  var units   = Math.round(getCookieSession(document,"DefaultTimeoutValue") / 60);
  var minutes = 0;
  var hours   = 0;

  if(units >= 60)
  {
    hours   =  Math.floor(units / 60) ;
    minutes =  units % 60;
  }
  else
  {
    hours   = 0;
    minutes = units;
  }

  if((hours != 0) && (minutes != 0))
  {
    return hours + " hour" + ((hours > 1) ? "s" : "") + " and " +  minutes + " minute" + ((minutes > 1) ? "s" : "") ;
  }
  else
  if((hours != 0) && (minutes == 0))
  {
    return hours + " hour" + ((hours > 1) ? "s" : "");
  }
  else
  {
    return minutes + " minute" + ((minutes > 1) ? "s" : "");
  }

}


function timeoutEnabled()
{
/*
if(getCookieSession(document,"TimeoutValue")  == null)
  setCookieSession(document,"TimeoutValue",defaultTimeout,"/");
if(getCookieSession(document,"DefaultTimeoutValue")  == null)
  setCookieSession(document,"DefaultTimeoutValue",getCookieSession(document,"TimeoutValue"),"/");

document.onmousemove=resetTimer;
document.onkeydown=resetTimer;
document.onclick=resetTimer;
window.onresize=resetTimer;
window.onmove=resetTimer;
window.onmousemove=resetTimer;

if (window.Event)
{
 document.captureEvents(Event.KEYDOWN);
 document.captureEvents(Event.MOUSEMOVE);
 document.captureEvents(Event.CLICK);

 window.captureEvents(Event.MOUSEMOVE);
 window.captureEvents(Event.MOVE);
 window.captureEvents(Event.RESIZE);
}

enablecountdown();
*/
}

function timeoutDisabled()
{
/*
  disablecountdown();
*/
}
/***************** End Timeout Functions  *****************/




/***************** Start Login/Logout Functions  *****************/
function showInvalidLogin()
{
  var loginStatus = 1;

  if(getCookieSession(document,"LoginStatus") != null)
   loginStatus = getCookieSession(document,"LoginStatus");

   setCookieSession(document,"LoginStatus",1,"/");

  if (loginStatus  == 0)
   return "Invalid user id/password.<br>Please try again:";
  else
   return "";
 }

function loginSession(docname)
{
   setCookieSession(document,"AuthorizationCookie","Basic " + encodeBase64(docname.u1.value + ':' + docname.u2.value),"/");
   setCookieSession(document,"ApplicationName",docname.signon.options[docname.signon.selectedIndex].value,"/");
   setCookieSession(document,"LastAccessTime",(new Date()).toString(),"/");
   setCookieSession(document,"LoginPath",docname.u3.value,"/");
   setCookieSession(document,"LoginStatus",1,"/");

   if(docname.u1.value != "") docname.u1.value = "*****";
   if(docname.u2.value != "") docname.u2.value = "*****";
}

function logoutSession()
{
   removeCookieSession(document,"AuthorizationCookie","/");
   removeCookieSession(document,"ApplicationName","/");
   removeCookieSession(document,"LastAccessTime","/");
   removeCookieSession(document,"LoginPath","/");

   removeCookieSession(document,"JSESSIONID","/apps/");
   removeCookieSession(document,"REMOTE_USER","/");
}
/***************** End Login/Logout Functions  *****************/