
var repeatCustomer = false
var lastVisit = 0 // to hold date & time of previous access in GMT milliseconds
var dateAdjustment = 0 // to accommodate date bugs on some platforms

var pageUpdates = new Array("climbLink", "bikeLink", "runLink", "webLink");
var updateTimes = new Array("19 Mar 2007 20:10:00 GMT",
                            "13 Nov 2004 18:21:00 GMT",
                            "22 Feb 2007 18:40:00 GMT",
                            "10 Aug 2004 22:10:00 GMT");



// shared cookie functions
var mycookie = document.cookie;

// read cookie data
function getCookieData(name) 
{
   var label = name + "=";
   var labelLen = label.length;
   var cLen = mycookie.length;
   var i = 0;

   while (i < cLen) 
   {
      var j = i + labelLen;
 
      if (document.cookie.substring(i, j) == label) 
      {
         var cEnd = document.cookie.indexOf(";", j);
         if (cEnd == -1) 
         {
            cEnd = document.cookie.length;
         }
         return unescape(document.cookie.substring(j, cEnd));
      }
      i++;
   }
   return "";
}

// write cookie data
function setCookieData(name, data, expires) 
{
   mycookie = document.cookie = name + "=" + data + "; expires=" + expires;
}

// set dateAdjustment to accommodate Mac bug in Navigator 3
function adjustDate() 
{
   var base = new Date();
   var testDate = base;
   
   testDate = testDate.toLocaleString();
   testDate = new Date(testDate);
   dateAdjustment = testDate.getTime() - base.getTime();
}

// write date of current visit (in GMT time) to cookie
function saveCurrentVisit() 
{
   var visitDate = new Date();
   var nowGMT = visitDate.getTime() - dateAdjustment;
   var expires = nowGMT + (180 * 24 * 60 * 60 *1000);
   
   expires = new Date(expires);
   expires = expires.toGMTString();
   setCookieData("lastVisit", nowGMT, expires);
}


// set up global variables and establish whether user is a newbie
function initialize() 
{
   var lastStoredVisit = getCookieData("lastVisit");
   var nextPrevStoredVisit = getCookieData("nextPrevVisit");
   adjustDate();
   
   if (!lastStoredVisit) 
   {
      // never been here before
      saveCurrentVisit();
      repeatCustomer = false;
   } 
   else 
   {
      // been here before...
      if (!nextPrevStoredVisit) 
      {
         // but first time this session
         // so set cookie only for current session
         setCookieData("nextPrevVisit", lastStoredVisit, "");
         lastVisit = parseFloat(lastStoredVisit);
         saveCurrentVisit();
         repeatCustomer = true;
      } 
      else 
      {
         // back again during this session (perhaps reload or Back)
         lastVisit = parseFloat(nextPrevStoredVisit);
         repeatCustomer = true;
      }
   }
}

initialize();
rw_addEvent(window, "load", updateLinks);

function showLastVisit()
{
  var elem = document.getElementById("lastVisitTime");
  if(elem && (lastVisit > 0))
  {
    var months = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
    var newDate = new Date(lastVisit);
    var t=document.createTextNode("Last visited: " + newDate.getDate() + " " + months[newDate.getMonth()] + " " + newDate.getFullYear())
    elem.replaceChild(t, elem.firstChild);
  }
}

// Updates all span elements with the given id.
function updateLinks()
{
   if(document.getElementById)
   {
      var index;
      for(index = 0; index < pageUpdates.length; index++)
      {
         var item = document.getElementById(pageUpdates[index]);
         if(item)
         {
            var authorDate = new Date(updateTimes[index]);
            var itemUpdated = authorDate.getTime();
            
            if((itemUpdated > lastVisit) && repeatCustomer)
            {
               item.style.color="#f00";
               item.style.fontStyle="italic";
            }
         }
      }
      showLastVisit();
   }
}

function rw_addEvent(element, eventType, func, useCapture)
{
  if (element.addEventListener)
  {
    element.addEventListener(eventType, func, useCapture);
    return true;
  } 
  else if (element.attachEvent)
  {
    var r = element.attachEvent("on"+eventType, func);
    return r;
  } 
  else 
  {
    alert("Handler could not be removed");
  }
}

//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//
// Have the bgr cookie store the info in the following format:
//    "bgrData=year#month#day#start#schedule#direction"
// An example would be:
//    "bgrData=0-5-4-18-19-0"
// When split, the following indices apply:
//		0 year
//    1 month
//    2 day
//    3 start time
//    4 proposed schedule
//    5 direction
// Note that just the indices are stored not the actual values
//
// The function should be called at the end of the calculate function so that
// the data is saved.
//
////////////////////////////////////////////////////////////////////////////////////////

function storeBGRData(bgrForm)
{
   // six month expiry date
   var expDate = new Date();
   expDate.setTime( expDate.getTime() + ( 180 * 24 * 60 * 60 * 1000 ) );
   expDate.toGMTString();   

   var cookieData = bgrForm.year.selectedIndex + "-" + bgrForm.month.selectedIndex + "-" + bgrForm.day.selectedIndex + "-" + bgrForm.startTime.selectedIndex + "-" + bgrForm.schedule.selectedIndex + "-";
   cookieData +=  (bgrForm.direction.selectedIndex == 0) ? "0-" : "1-";
   cookieData +=  bgrForm.routeOpt.selectedIndex;

   document.cookie = "bgrData" + "=" + cookieData + "; expires=" + expDate.toGMTString();
}

// Reads the stored BGR data back.
//
// If the cookie exists then the values it held are used to set up the 
// various fields, otherwise use some sensible defaults.

function getBgrData(bgrForm)
{
   var data = getCookieData("bgrData");
   if(data)
   {
      var bgrCookieData = data.split('-');

      bgrForm.year.selectedIndex = bgrCookieData[0];
      bgrForm.month.selectedIndex = bgrCookieData[1];
      bgrForm.day.selectedIndex = bgrCookieData[2];
      bgrForm.startTime.selectedIndex = bgrCookieData[3];
      bgrForm.schedule.selectedIndex = bgrCookieData[4];
      bgrForm.direction.selectedIndex=bgrCookieData[5];
      
      if(bgrCookieData.length > 6)
      {
        bgrForm.routeOpt.selectedIndex=bgrCookieData[6];
      }
   }
   else
   {
      var now = new Date();
      
      var yearIndex = 0;
      var monthIndex = 5;
      var dayIndex = 19;
      
      if(now.getMonth() > 5)
      {
         yearIndex += 1;
      }
      // Find the closest Saturday to 20th June next year. getDay() returns 0 for 
      // Sunday, ..., 6 for Saturday.
      var tempDate = new Date(yearIndex, monthIndex, dayIndex);
      
      var tempDay = tempDate.getDay();
      if(tempDay != 6)
      {
         if(tempDay < 3)
         {
            dayIndex -= (tempDay + 1);
         }
         else
         {
            dayIndex += (6 - tempDay);
         }
      }
      bgrForm.year.selectedIndex = yearIndex;
      bgrForm.month.selectedIndex=monthIndex;
      bgrForm.day.selectedIndex=dayIndex;
      bgrForm.startTime.selectedIndex = 0;
      bgrForm.schedule.selectedIndex = 0;
      bgrForm.direction.selectedIndex=0;
      bgrForm.routeOpt.selectedIndex=0;
   }
}

// Reads the stored BGR data back.
//
// If the cookie exists then return the user preference for the direction,
// otherwise return clockwise ( zero ).

function getBgrDirection()
{
   var data = getCookieData("bgrData");
   if(data)
   {
      var bgrCookieData = data.split('-');
      return bgrCookieData[5];
   }
   else
   {
      return 0;
   }
}

function getBgrSched()
{
   var data = getCookieData("bgrData");
   if(data)
   {
      var bgrCookieData = data.split('-');
      return bgrCookieData[4]/4;
   }
   else
   {
      return 23.5;
   }
}

function getBgrStart()
{
   var data = getCookieData("bgrData");
   if(data)
   {
      var bgrCookieData = data.split('-');
      return bgrCookieData[3];
   }
   else
   {
      return 0;
   }
}

function getBgrYear()
{
   var data = getCookieData("bgrData");
   if(data)
   {
      var bgrCookieData = data.split('-');
      return parseInt(bgrCookieData[0]);
   }
   else
   {
      return 0;
   }
}


///////////////////////////////////////////////////////////////////////////////////////////////////
//
// Creates a date object that is the date of the attempt. This is the date that the visitor has
// selected or the closest Saturday to the next 20th June.
//
///////////////////////////////////////////////////////////////////////////////////////////////////
function getDateOfAttempt()
{
   var data = getCookieData("bgrData");
   var attemptYear;
   var attemptMonth;
   var attemptDay;

   var now = new Date();
      
   attemptYear = now.getFullYear();
   if(data)
   {
      var bgrCookieData = data.split('-');
      
      attemptMonth = bgrCookieData[1];
      attemptDay   = parseInt(bgrCookieData[2]) + 1;
      if(now.getMonth() > 5)
      {
         attemptYear += 1;
      }
   }
   else
   {
      attemptMonth = 5;
      attemptDay = 20;
      
      if(now.getMonth() > 5)
      {
         attemptYear += 1;
      }
      // Find the closest Saturday to 20th June next year. getDay() returns 0 for 
      // Sunday, ..., 6 for Saturday.
      var tempDate = new Date(attemptYear, attemptMonth, attemptDay);
      
      var tempDay = tempDate.getDay();
      if(tempDay != 6)
      {
         if(tempDay < 3)
         {
            attemptDay -= (tempDay + 1);
         }
         else
         {
            attemptDay += (6 - tempDay);
         }
      }
   }   
   var attemptDate = new Date(attemptYear, attemptMonth, attemptDay);
   return attemptDate;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
//
// Creates a date object that is the date at which serious training should begin.
//
///////////////////////////////////////////////////////////////////////////////////////////////////
function getTrainStart()
{
   var oneMinute = 60 * 1000;
   var oneHour = oneMinute * 60;
   var oneDay = oneHour * 24;
   var oneWeek = oneDay * 7;
   
   var trainStart = new Date();
   var attemptStart = getDateOfAttempt();
   var dateInMs = attemptStart.getTime();
   dateInMs -= (oneWeek * 32);
   
   trainStart.setTime(dateInMs);
   return trainStart;
}

/////////////////////////////////////////////////////////////////////////////
//
//
//
////////////////////////////////////////////////////////////////////////////
function storeNameData(index)
{
   // six month expiry date
   var expDate = new Date();
   expDate.setTime( expDate.getTime() + ( 180 * 24 * 60 * 60 * 1000 ) );
   expDate.toGMTString();   

   var cookieData = index ;

   document.cookie = "nameData" + "=" + cookieData + "; expires=" + expDate.toGMTString();   
}

function getNameData()
{
   var data = getCookieData("nameData");
   if(data)
   {
      var bgrCookieData = data.split('-');
      return bgrCookieData[3];
   }
   else
   {
      return 0;
   }
}

function storeElementWidth()
{
  // six month expiry date
  var w = 0;
  var expDate = new Date();
  expDate.setTime( expDate.getTime() + ( 180 * 24 * 60 * 60 * 1000 ) );
  expDate.toGMTString();  

  if(document.getElementById) 
  {
    var elem = document.getElementById("content");
    w = elem.offsetWidth;
  } 
   
  document.cookie = "elementWidth" + "=" + w + "; expires=" + expDate.toGMTString();   
}

function setBgrMenu(opt)
{
   // one year expiry date
   var expDate = new Date();
   expDate.setTime( expDate.getTime() + ( 365 * 24 * 60 * 60 * 1000 ) );
   expDate.toGMTString();   

   var cookieData = opt ;

   document.cookie = "bgrMenu" + "=" + cookieData + "; expires=" + expDate.toGMTString();   
}

