/**************************************************
**  EVENT HANDLING INFORMATION                   **
**************************************************/
var skipSettingCookie = false;
function AttachEvent(varEventObject, varEventName, varEventFunction)
{
  if (varEventObject)
  {
    if(varEventObject.addEventListener)
    {
      varEventObject.addEventListener(varEventName, varEventFunction, false);
    }
    else if (varEventObject.attachEvent)
    {
      varEventObject.attachEvent('on' + varEventName, varEventFunction);
    }
  }
}

function SetupCodeAccess()
{
  if ($('frmCodeAccess'))
  {
    AttachEvent($('frmCodeAccess'), 'submit', CheckCodeAccess);
  }
  
  var previousCode = GetCookie();
  if (previousCode.length != 0)
  {
    skipSettingCookie = true;
    $('txtCode').value = previousCode;
    CheckCodeAccess();
  }
}

function CheckCodeAccess()
{
  if ($('txtCode'))
  {
    new Ajax.Request('access.php',
      {
        method: 'post',
        parameters: {ajaxRequested: "true", txtCode: $('txtCode').value},
        onSuccess: ProcessCodeAccessResults,
        onFailure: ShowCodeAccessError
      }
    );
  }
  
  return false;
}

function ProcessCodeAccessResults(requestObj, jsonObj)
{
  if (requestObj.responseText != null
    && requestObj.responseText.toLowerCase().indexOf('http') > -1)
  {
    if (!skipSettingCookie)
    {
      SetCookie($('txtCode').value);
    }
    window.location.href = requestObj.responseText;
  }
  else
  {
    $('frmCodeAccess').submit();
  }
}

function ShowCodeAccessError()
{
}

function GetCookie()
{
  if (document.cookie.length > 0)
  {
    var cookieStart = document.cookie.indexOf("CodeAccess=");
    if (cookieStart != -1)
    {
      var cookieEnd = document.cookie.indexOf(";")
      if (cookieEnd == -1)
      {
        cookieEnd = document.cookie.length;
      }
      
      return unescape(document.cookie.substring(11, cookieEnd));
    }
  }
  
  return "";
}

function SetCookie(varValue)
{
  var expire = new Date();
  expire.setTime(expire.getDate() + 1); // Add one Day
  document.cookie = "CodeAccess=" + escape(varValue) + ";expires=" + expire.toGMTString();
}

AttachEvent(window, 'load', SetupCodeAccess);