// =================================================================================
//       BODY ONLOAD
// =================================================================================

function doBodyOnload()
{
  hideWaitMessage(); 			// i.e. report page has finished loading
  displayCookie();			// display login information
  window.name = "main";			// set window name, for navigation purposes
}

// =================================================================================
//       COOKIE HANDLING
// =================================================================================

/*
============================================================
============================================================
The rest of this file has not yet been properly documented
Development comments need replacing by proper stuff
============================================================
============================================================
*/
// See PHP code for notes on cookies

// #### this bit should be written via PHP
if (location.hostname == 'localhost') 
{
  $login_cookie_name = 'local=';	// must be 6 chars.
  $login_cookie_path = '; path=/';
  // actually, we probably DONT need a different cookie name to 'login' here.
}
else 
{
  $login_cookie_name = 'login=';
  $login_cookie_path = '; path=/; domain=bcra.org.uk';
  // Use of this domain SHOULD mean we dont need to change name of cookie depending on sub-domain
}

function readCookie()
{
  $s = unescape(document.cookie);
  // window.alert('cookie unescaped to ' + $s);
  // unescaping the cookie changes %2B to + but it does NOT change + to space
  // (unlike PHP's internal action. This means that the split below has to be on '+'
  // and that the cookie name mustnt contain +.  (it wont, but need to note this
  // generally.
  
  pos = $s.indexOf($login_cookie_name);
  if (pos == -1)
  {
    $s = '0';					// login cookie did not exist
  }
  else
  {
    $s = $s.substring(pos + 6);			// locate the login cookie
    pos = $s.search(/;|$/);			// look for its termination, or end-of-string
    $s = $s.substring(0,pos);
  }
  $s = $s.split('+');				// break cookie up at the + symbols
    // cookie comprises four elements
    // If the elts are unset,set them so that login page displays sensible defaults
  if ($s[0] == null) $s[1] = '0';
  if ($s[1] == null) $s[1] = '';
  if ($s[2] == null) $s[2] = '';
  if ($s[3] == null) $s[3] = 'off';
  
  $time = $s[0]; $userid = $s[1]; $passwd = $s[2]; $savelogin = $s[3]; 
  // window.alert('cookie read as ' + $s[0] + ' ' + $s[1] + ' ' + $s[2] + ' ' + $s[3]);
}

// =================================================================================

function logout()
{
  readCookie();  			// extracts $time, $userid, $passwd, $savelogin
  
  if ($time == '0') return;		// dont keep rewriting the cookie if we're logged out
  $time = 0;				// set cookie time to zero
  
  $timeNow = new Date();
  if ($savelogin == 'on')
  { 
    $timeNow.setTime($timeNow.getTime() + 1000 * 86400 * 90); 
    $cookieExpires = "; expires=" + $timeNow.toGMTString();
    }
  else
  { 
    $timeNow.setTime($timeNow.getTime() - 1000 * 86400 * 90); 
    $cookieExpires = "; expires=" + $timeNow.toGMTString();
  }
  
  $login = $login_cookie_name + $time;
  $login += "+" + escape($userid);
  $login += "+" + $passwd;
  $login += "+" + $savelogin;
  $login += $cookieExpires;
  $login += $login_cookie_path;
  
  // we cant escape the whole string cos spaces become %20, not '+'
  // and = becomes %something.  If this was PHP we could URLencode it (IIRC)
  // but PHP does that automatically anyway

  // window.alert('about to write ' + $login);
  document.cookie = $login;
}

// =================================================================================

function timeToLive()
// If the login cookie exists, get 'time' portion and return time till logout.
{
  pos = document.cookie.indexOf($login_cookie_name);
  if (pos == -1)	cookietime = 0; 	// cookie did not exist
  else		cookietime = parseInt(document.cookie.substring(pos + 6));

  timeNow = new Date();
  seconds = Math.floor(timeNow.getTime()/1000);
  // tid = [set from PHP];
  // duration = [set from PHP]
  ttl = cookietime  + tid + duration - seconds;
  return ttl;
}

// =================================================================================

function displayCookie()
// Display some cookie parameters - e.g. time left till logout
// Force a logout if necessary
{
  if ((timeToLive() <= 0) )
  {
    //window.alert('timeToLive() <= 0');
    logout();
    $text = "You are not logged in ";
    $text += "<A HREF=\"../logininfo.html\" ONCLICK=\"return logininfo();\">";
    $text += "<IMG SRC=\"../../graphics/query.png\" ALT=\"Log In\" WIDTH=12 HEIGHT=17 BORDER=0></A>";
    
    timerID = window.setTimeout('displayCookie()', 2000);
    // need this so that we pick up a login as soon as it happens
  }
  else
  {
    //window.alert('timeToLive() > 0');
    timerID = window.setTimeout('displayCookie()', 1000);
    // this executes this fn again; but not if timetoLive() returned <0
    readCookie();
    $text = "You are logged in as <B>" + $userid + "</B>. ";
    $text += timeToLive() + "s&nbsp;remaining. ";
    $text += "<A href=\".\" ONCLICK=\"logout(); return false;\">Log&nbsp;Out</A>.";
  }
  e = document.getElementById('userID');	// use W3C DOM, global e
  if (!e)  e = document.all['userID'];		// Use IE4 DOM
  if (e)
  // if browser is compliant...
  {
    //window.alert('browser compliant');
    //e.style.color = '#FF0000';
    //e.textContent = $text;			// use W3C DOM
    //e.innerText = $text;			// Use IE4 DOM
    e.innerHTML = $text;			// IE DOM but also implemented by NN and Moz
  }
  else
  {
    //window.alert('browser reportinig not compliant');
  }
}

// =================================================================================
//       open a URL or show the login dialogue
// =================================================================================

function makeWindow(w,h,url,name)
// Open a new window resize it and focus on it. 
// Return the window object, which will be false if the window could not be 
// created - e.g. if pop-ups prevented it
{
  aw = w * screen.width;
  ah = h * screen.height;
  // window.alert('aw = ' + aw + '; ah = ' + ah);
  ax = (screen.width-aw)/2;
  ay = (screen.height-ah)/2;
  as = 'height='+ah+',width='+aw+',left='+ax+',screenX='+ax+',top='+ay+',screenY='+ay;
  
  if (typeof a != 'undefined') a.close(); 
  
  // The above is a workaround for browsers (like my config of Firefox) that have a 
  // 'raise or lower windows' option unchecked. In order to ensure that the new window
  // has focus, it is necessary to newly create it, because window.focus() does not 
  // have any effect.

  a = window.open(url, name, as + ',status=yes,resizable=yes,scrollbars=yes');

  a.focus(); // see note above
  return a;  // return the window object
}


// =================================================================================

function openURL(s)
/* This function is called from within the PHP-generated anchor tags, which are of the form:
   <A href="nojscript1v2.html" 
   ONMOUSEOVER="this.href='downloads.html?f=06701'" 
   ONCLICK="return openURL(this.href);">
*/
{
  // if (document.cookie.indexOf('test=123') == -1)
  
  if (document.cookie.search(/(^|;) ?idx=(on|off)/) == -1)
  // use idx=... instead of test=123 just to make the cookie smaller  
  {
    q = window.confirm ('Your browser is reporting that Cookies  \n' +
    			'are not available, so you cannot view   \n' +
    			'the online content. Try refreshing this \n' +
    			'page (Ctrl-r) or, if you wish to view   \n' +
    			'further information about this problem  \n' +
    			'or report a bug click OK.');
    			
    if (!q) return false;
    
    if (document.cookie == '') dc = '[document.cookie is empty]';
    else dc = document.cookie;
    
    q = window.confirm ('If you want to report this as a possible   \n' +
    			'software error, please quote any text that \n' +
    			'appears below.\n\n' + 
    			dc + '\n\n' +
    			'To read some brief info about Cookies \n' +
    			'click OK');
    			
    if (q) location.href = '/nocookies.html';   // !!! Check this works - is URL correct?
    return false;
  }
  
  if (timeToLive() <= 0)
  { 
    q = window.confirm ('You are not logged in. To view online content \n' +
			'you must login using your user name and access code.\n\n' + 
			'Login now?')
    if (!q) return false;  // i.e. dont follow link 
    
    // User wants to login, so attempt to open a new window
    // makeWindow() returns window object. 
    // If window object exists, return false so that the <A> tag link is NOT followed
    // If window object was not created, return true so that we follow the link
    
    usewidth = 5/8; useheight = 9/16;
    q = !makeWindow(usewidth, useheight, s, 'BCRAdownloads');
    
    if (q) { window.alert('DEBUG info: window not created\n\n' +
                          'We would be grateful if you could report \n' +
                          'the circumstances of this error, as its \n' +
                          'proving difficult to fix :-(.'); }
    
    // 20-jan-2008: What's that about?  When is window not created?
        
    return q;
  }
  else 
  {
    return true;
  /*
  we are logged in, so return true so that the link is followed. However, this 
  will not result in a page being displayed because the PDF's "do you want to run or save" box
  will appear instead.
  */
  }
}

// =================================================================================
//       show/hide the Please Wait message
// =================================================================================

function printWaitMessage()
{
  // write the text in white (from within the HTML doc) so it is not visible 
  
  e = document.getElementById('pleasewait');	// use W3C DOM, global e
  if (!e) e = document.all['pleasewait'];	// Use IE4 DOM
  if (e)
  // if browser is compliant, make the text visible
  {
    e.style.color = '#FF0000';
  }
}

// =================================================================================

function hideWaitMessage()  // called from BODY ONLOAD
{
  e = document.getElementById('pleasewait');	// use W3C DOM, global e
  if (!e) e = document.all['pleasewait'];	// Use IE4 DOM
  if (e)
  // if browser is compliant, make the text invisible and over-writable
  {
    e.style.position = 'absolute';	// ie allow text to be overprinted
    e.style.visibility='hidden';	// hide the 'please wait' text
  }
}
