// ********************************************************************************************
// *********
// *********  Code to manage LGDGC web site security
// *********
// ********************************************************************************************

var cryptokey = "0i7ythkg" ;
var resetkey  = "00000000" ;
var spamstop = "bl0mil3y" ;
var gResponseText ;
// ********************************************************************************************
// *********
// *********  Check to see if the session cookie has had the 'securetoken' set.  This is done when a person
// *********  logs in successfully to the members section.  (Every page then checks to see if this has been set
// *********  before giving access to a member page)
// *********
// ********************************************************************************************
function checkSecureToken()
{
 var securetoken = getSessionCookie("securetoken") ;
//  alert("Secure Token = " + securetoken) ;
    if (securetoken == cryptokey)
    {
//    alert("Found cookie " + document.cookie ) ;
      return true;
    }
    else
    {
       document.cookie = "";
       window.location.href = "mbr-failaccess.html" ;
       return false ;
    }

}

// ********************************************************************************************
// *********
// *********  Retrieve a value from the session cookie
// *********
// ********************************************************************************************
function getSessionCookie(Name)
{
  var search = Name + "="
  var returnvalue = "";
  if (document.cookie.length > 0) {
    offset = document.cookie.indexOf(search)
    // if cookie exists
    if (offset != -1) {
      offset += search.length
      // set index of beginning of value
      end = document.cookie.indexOf(";", offset);
      // set index of end of cookie value
      if (end == -1) end = document.cookie.length;
      returnvalue=unescape(document.cookie.substring(offset, end))
      }
   }
  return returnvalue;
}

// ********************************************************************************************
// *********
// *********  The purpose of this function is to reset the cookie to an invalid key, to stop people who have
// *********  logged out of LGDGC web site but are still in a browser session to be able to access member pages without logging in again
// *********
// ********************************************************************************************

function invalidateCryptoKey()
{
   document.cookie="securetoken=" + resetkey ;        //   This can be any value, I've put a random value in to make it hard to work out
//   alert("CryptoKey has been reset " + document.cookie ) ;
}



// ********************************************************************************************
// *********
// *********  If a member has previously logged in a browser session and returns to the LGDGC site
// *********  default in this months password.  Note.  This should not work when a browser session has finished.
// *********
// *********
// ********************************************************************************************

function checkSessionStarted()
{
 var securetoken = getSessionCookie("securetoken") ;
//  alert("Secure Token = " + securetoken) ;
    if (securetoken == cryptokey)
    {
        document.getElementById('sitecode').value=sitekey[thismth] ;
    }
}

// ********************************************************************************************
// *********
// *********  This function checks the Members XML file and sees if the Surname and Membership Id check out.
// *********  If they do they are admitted to the site
// *********
// *********
// ********************************************************************************************
function validateUserDetails(surname, memberid, errorFld)
{
   var elmtSurname  = document.getElementById(surname);
   var elmtMemberId = document.getElementById(memberid);
   var elmtError    = document.getElementById(errorFld);

   mySurname  = elmtSurname.value ;
   myMemberId = elmtMemberId.value ;

    // Backdoor access to members area
    if(mySurname == 't3stm0de')
    {
    //  Set a session cookie that can be retrieved to put the members name on the top of the pages
        document.cookie="member=" + 'Test' ;
    //  Set a session cookie with the secure token that is checked on every member page
        document.cookie="securetoken=" + cryptokey ;
        window.location.href = "mbr-newspage.html" ;
        return true ;
    }

    // Do some validation of the details entered before we validate against the membership list
   if(!mySurname && !myMemberId)     //   No details have been entered
    {
      elmtError.innerHTML = '<b>Member message.  You need to enter your <span class=\'red\'>surname</span> and <span class=\'red\'>member no</span>.</b>' ;
      return ;
    }

   if(!mySurname && myMemberId)     //   Surname hasn't been entered
    {
      elmtError.innerHTML = '<b>Member message.  You have not entered your <span class=\'red\'>surname</span>.</b>' ;
      return ;
    }

   if(mySurname && !myMemberId)     //   Member Id hasn't been entered
    {
      elmtError.innerHTML = '<b>Member message.  Your <span class=\'red\'>member no</span> has not been entered.</b>' ;
      return ;
    }

    // Convert the surname to lowercase (It makes it easier to ensure that the surname matches the member list)
    mySurname = mySurname.toLowerCase() ;

    // Now we're sure we have an entry in each of the firelds validate against the membership list
    if(checkMemberDetails(mySurname, myMemberId))
    {
//      alert("Success") ;
        document.cookie="securetoken=" + cryptokey ;
        window.location.href = "mbr-newspage.html" ;
    }
    else
    {
//    The surname and/or member id don't match
      elmtError.innerHTML = '<b class=\'red\'>Member message.  Your log in attempt has failed please check your Surname and Member Id details.</b>' ;
    }

}

// ********************************************************************************************
// *********
// *********  This function checks the Members XML file and sees if the Surname and Membership Id check out.
// *********  If they do they are admitted to the site
// *********
// *********
// ********************************************************************************************
function validateMobileUser(surname, memberid, errorFld)
{
   var elmtSurname  = document.getElementById(surname);
   var elmtMemberId = document.getElementById(memberid);
   var elmtError    = document.getElementById(errorFld);

   mySurname  = elmtSurname.value ;
   myMemberId = elmtMemberId.value ;

    // Backdoor access to members area
    if(mySurname == 't3stm0de')
    {
    //  Set a session cookie that can be retrieved to put the members name on the top of the pages
        document.cookie="member=" + 'Test' ;
    //  Set a session cookie with the secure token that is checked on every member page
        document.cookie="securetoken=" + cryptokey ;
        window.location.href = "mbl-menu.html" ;
        return true ;
    }

    // Do some validation of the details entered before we validate against the membership list
   if(!mySurname && !myMemberId)     //   No details have been entered
    {
      elmtError.innerHTML = '<b>Member message.  You need to enter your <span class=\'red\'>surname</span> and <span class=\'red\'>member no</span>.</b>' ;
      return ;
    }

   if(!mySurname && myMemberId)     //   Surname hasn't been entered
    {
      elmtError.innerHTML = '<b>Member message.  You have not entered your <span class=\'red\'>surname</span>.</b>' ;
      return ;
    }

   if(mySurname && !myMemberId)     //   Member Id hasn't been entered
    {
      elmtError.innerHTML = '<b>Member message.  Your <span class=\'red\'>member no</span> has not been entered.</b>' ;
      return ;
    }

    // Convert the surname to lowercase (It makes it easier to ensure that the surname matches the member list)
    mySurname = mySurname.toLowerCase() ;

    // Now we're sure we have an entry in each of the firelds validate against the membership list
    if(checkMemberDetails(mySurname, myMemberId))
    {
//      alert("Success") ;
        document.cookie="securetoken=" + cryptokey ;
        window.location.href = "mbl-menu.html" ;
    }
    else
    {
//    The surname and/or member id don't match
      elmtError.innerHTML = '<b class=\'red\'>Member message.  Your log in attempt has failed please check your Surname and Member Id details.</b>' ;
    }

}

function checkUserCredentials(surname, memberid, msgFieldId)
// ********************************************************************************************
// *********  This function checks the Members XML file and sees if the Surname and Membership Id check out.
// *********  If they do they are admitted to the members area of the site
// *********  If not an error message is displayed back to the user
// ********************************************************************************************
{
    // Convert the surname to lower case and then compare what the user typed in against the member record
   var elmtSurname  = document.getElementById(surname);
   var elmtMemberId = document.getElementById(memberid);
   var elmtUserMsg  = document.getElementById(msgFieldId);
   mySurname  = elmtSurname.value ;
   myMemberId = elmtMemberId.value ;
    // Backdoor access to members area
    if(mySurname == 't3stm0de')
    {
    //  Set a session cookie that can be retrieved to put the members name on the top of the pages
        document.cookie="lgdgcMbr=" + 'authenticated,Mr,Test,Mode,tester@test.co.uk,01253 t35t3r';
        alert(getSessionCookie('lgdgcMbr')) ;
        document.cookie="mbrForename=" + 'Test' ;
        document.cookie="mbrSurname=" + 'Mode' ;
        document.cookie="mbrEmail=" + 'tester@test.co.uk' ;
        document.cookie="mbrPhone=" + '01253 t35t3r' ;
    //  Set a session cookie with the secure token that is checked on every member page
        document.cookie="securetoken=" + cryptokey ;
        window.location.href = "mbr-newspage.html" ;
        return true ;
    }
    // Do some validation of the details entered before we validate against the membership list
   if(!mySurname && !myMemberId)     //   No details have been entered
    {
      elmtUserMsg.innerHTML = '<b>Member message.  You need to enter your <span class=\'red\'>surname</span> and <span class=\'red\'>member no</span>.</b>' ;
      return false ;
    }
   if(!mySurname && myMemberId)     //   Surname hasn't been entered
    {
      elmtUserMsg.innerHTML = '<b>Member message.  You have not entered your <span class=\'red\'>surname</span>.</b>' ;
      return false ;
    }
   if(mySurname && !myMemberId)     //   Member Id hasn't been entered
    {
      elmtUserMsg.innerHTML = '<b>Member message.  Your <span class=\'red\'>member no</span> has not been entered.</b>' ;
      return false ;
    }
    // Now we're sure we have an entry in each of the fields validate against the membership list
    authenticateUser(mySurname, myMemberId, elmtUserMsg) ;
}

function authenticateUser(surname, memberid, elmtUserMsg)
// ****************************************************************************************************************************
// +++++  Authenticate a user against the membership database using the surname and member id
// +++++
// +++++  If a match is found :
// +++++   - The user is fowarded to the members section of the web site
// +++++   - Some cookies are set up whcih are needed by the members section
// +++++
// +++++  If a match is NOT found :
// +++++   - A message is returned to the log in page
// +++++   - The user is NOT fowarded to the members section of the web site
// +++++
// +++++  Works in conjunction with a server side script - member-authenticate.php
// ****************************************************************************************************************************
{
  var xmlhttp = getXMLHttp();
  xmlhttp.onreadystatechange=function()
  {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
//        alert(xmlhttp.responseText) ;
          var respText = xmlhttp.responseText;
          var responseFields = new Array();
          responseFields = respText.split(",");
//        alert("In authenticateUser() - responseFields[0] = :- \n\n" + responseFields[0]);
          if(responseFields[0] == "authenticated")
          {
          //  Put a success message in the error field in the calling page
              elmtUserMsg.innerHTML = '<b class=\'red\'>Member message.' + responseFields[1] +  'your log in attempt has been successful.</b>' ;
              document.cookie="lgdgcMbr="    + respText ;   // Put the member details in a cookie
          //  Set a session cookie that can be retrieved to put the members name on the top of the pages
              document.cookie="mbrTitle="    + responseFields[3] ;
              document.cookie="mbrForename=" + responseFields[1] ;
              document.cookie="mbrSurname="  + responseFields[2] ;
              document.cookie="mbrEmail="    + responseFields[6] ;
              document.cookie="mbrPhone="    + responseFields[5] ;
          //  Set a session cookie with the secure token that is checked on every member page
              document.cookie="securetoken=" + cryptokey ;
              window.location.href = "mbr-newspage.html" ;
              return ;
          }
          else
          {
          //  The surname and/or member id don't match
          //  Invalidate the session cookie so that member pages can't be accessed
              document.cookie="securetoken=" + resetkey ;
              elmtUserMsg.innerHTML = '<b class=\'red\'>Member message.  Your log in attempt has failed please check your Surname and Member Id details.</b>' ;
              return ;
          }
    }
  }
  var url    = "member-authenticate.php" ;
  var params = "?surname=" + surname + "&idno=" + memberid ;
//  alert(url + params) ;
  xmlhttp.open("GET", url + params, true);
  xmlhttp.send();
}

function checkUserMailId(email, msgField )
//****************************************************************************************************************************
// +++++  Search the member list for the email supplied by the user
// +++++
// +++++  If a match is found :
// +++++   - a response is sent back indicating that a match has been found and we will be sending them an email with their details
// +++++   - an email is sent to them (via the php script)
// +++++
// +++++  If a match is NOT found :
// +++++   - a response is sent back indicating that a match has NOT been found and use an option to call the secretary
// +++++
// +++++  Works in conjunction with a server side script - member-forgotpwd.php
//****************************************************************************************************************************
{
  var mailId      = document.getElementById(email).value ;
  var elmtUserMsg = document.getElementById(msgField) ;
  var xmlhttp = getXMLHttp();
  xmlhttp.onreadystatechange=function()
  {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
     // Let the user know whether or not the operation has been successful
        elmtUserMsg.innerHTML = xmlhttp.responseText ;
        return ;
    }
  }
  var url    = "member-forgotpwd.php" ;
  var params = "?mailid=" + mailId + "&spamstop=" + spamstop ;
  //  alert(url + params) ;
  xmlhttp.open("GET", url + params, true);
  xmlhttp.send();
}

function findMembers( elmtSearchId, elmtFilterId, elmtResultsId )
//****************************************************************************************************************************
// +++++  Search the member list for the surname or part surname supplied by the user
// +++++
// +++++  Return all matches found with their contact details in the form of an html table
// +++++
// +++++  Works in conjunction with a server side script - member-search.php
//****************************************************************************************************************************
{
  var elmtSearchField  = document.getElementById(elmtSearchId);
  var elmtFilterFields = document.getElementsByName(elmtFilterId);
  var elmtResultsField = document.getElementById(elmtResultsId);
  var filterValue = 'All' ;
//  Get the filter value ( All, True (Gents only), False (Ladies only) )
  for (i=0;i<elmtFilterFields.length;i++)
  {
      if (elmtFilterFields[i].checked==true)
      {
        filterValue = elmtFilterFields[i].value ;
        break ;
      }
  }
  var xmlhttp = getXMLHttp();
  xmlhttp.onreadystatechange=function()
  {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
     // Let the user know whether or not the operation has been successful
        elmtResultsField.innerHTML = xmlhttp.responseText ;
        return ;
    }
  }
  var url = "member-search.php" ;
  var params = "?surname=" + elmtSearchField.value + "&filter=" + filterValue ;
//  alert(url + params) ;
  xmlhttp.open("GET", url + params, true);
  xmlhttp.send();
}

function getXMLHttp()
// ****************************************************************************************************************************
// +++++  This is a helper function.  It creates an XMLHttpRequest object and returns it to the calling function.
// +++++  It is cross browser compatible
// ****************************************************************************************************************************
{
  var xmlHttp ;
  try
  {
    //Firefox, Opera 8.0+, Safari
    xmlHttp = new XMLHttpRequest();
  }
  catch(e)
  {
    //Internet Explorer
    try
    {
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e)
    {
      try
      {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch(e)
      {
        alert("Your browser does not support AJAX!") ;
        return false;
      }
    }
  }
  return xmlHttp;
}

