/**
 *  Apply personalization clientside using cookies.
 *
 *  Copyright (c) 2007 by <GX> creative online development B.V.
 *  All rights reserved.
 *
 *  <GX>: Open for business
 *  http://gx.nl/
 *
 *  Contains code by Jonathan Snook (http://www.snook.ca/jonathan),
 *  Robert Nyman (http://www.robertnyman.com) and Peter-Paul Koch
 *  (http://www.quirksmode.org/js/cookies.html), thanks for sharing!
 *
 *  @author   StijnW <Stijn.de.Witt@gx.nl>
 *  @date     2007/02/16
 *  @desc     Site20 - Restyle KPN.com
 *
 *  @author   StijnW <Stijn.de.Witt@gx.nl>
 *  @date     2007/06/04
 *  @desc     KPN-1357 [8742]
 *						Added field type to allow checking for user type
 *
 *  @author   StijnW <Stijn.de.Witt@gx.nl>
 *  @date     2007/06/29
 *  @desc     KPN-1368 [8842]
 *						Added calls to encode- / decodeURIComponent to 
 *						encode/decode UTF-8 chars
 *
 *  USAGE
 *
 *  1. Create an instance of the WebUser javascript 'class' at the top of your 
 *     document (in the head section):
 *
 *       <script type="text/javascript">
 *         var webUser = new WebUser();
 *       </script>
 *     </head>
 *
 *  2. Mark HTML elements that should be (in)visible only when the user is 
 *     logged in with the WEBUSER_LOGGEDIN_CLASS or WEBUSER_NOTLOGGEDIN_CLASS:
 *
 *     <body>
 *       <form name="login" class="webUser-notLoggedIn">
 *         ...
 *       </form>
 *
 *  3. Use special WebUser attribute marker comments within your HTML to have
 *     certain attributes of the logged-in webuser filled in there. Only marker
 *     comments within elements with WEBUSER_LOGGEDIN_CLASS will be filled in.
 *
 *     <div class="webUser-loggedIn">
 *       Thanks for logging in, <!-- [webUser.name] -->.<br />
 *       You are registered as <!-- [webUser.initials] --> <!-- [webUser.surname] -->.
 *     </div>
 *
 *  4. Add a call to applyPersonalization at the bottom of your document
 *     (just before the close of the body tag):
 *
 *       <script type="text/javascript">
 *         webUser.applyPersonalization();
 *       </script>
 *     </body>
 *  
 *  MARKER COMMENTS
 *
 *  The following marker comments are available:
 *
 *  <!-- [webUser.id] -->
 *  <!-- [webUser.name] -->
 *  <!-- [webUser.title] -->
 *  <!-- [webUser.initials] -->
 *  <!-- [webUser.middlename] -->
 *  <!-- [webUser.surname] -->
 *  <!-- [webUser.gender] -->
 *  <!-- [webUser.type] -->
 */

var WEBUSER_COOKIENAME = "userinfo";
var WEBUSER_LOGGEDIN_CLASS = "webUser-loggedIn";
var WEBUSER_NOTLOGGEDIN_CLASS = "webUser-notLoggedIn";


function WebUser()
{
  this.isLoggedIn = WebUser_isLoggedIn;
  this.isNotLoggedIn = WebUser_isNotLoggedIn;
  this.load = WebUser_load;
  this.save = WebUser_save;
  this.applyPersonalization = WebUser_applyPersonalization;

  this.id = -1;
  this.name = null;
  this.title = null;
  this.initials = null;
  this.middlename = null;
  this.surname = null;
  this.gender = -1;
  this.type = -1;

  this.load();
}


function WebUser_isLoggedIn()
{
  return ((this.name != null) && (this.id != -1));
}


function WebUser_isNotLoggedIn()
{
  return ((this.name == null) || (this.id == -1));
}


function WebUser_load()
{
  // cookieFormat:  user_id=<userId>#user_name=<userName>#title=<title>#initials=<initials>#surname=<surname>#gender=<gender>
  // eg:            "user_id=234#user_name=PietJ#title=ing#initials=P.W.H.#surname=Joosten#gender=0"
  //                "user_id=345#user_name=RitaV#title=drs#initials=R.#surname=Verdonk#gender=1"
  var cookieValue = null;

  // Code 'borrowed' from Quirksmode.org, thanks Peter-Paul Koch!
  // http://www.quirksmode.org/js/cookies.html
  var nameEQ = WEBUSER_COOKIENAME + "=";
  var cookies = document.cookie.split(';');
  for(var i=0; i<cookies.length; i++) 
  {
    var c = cookies[i];

    while (c.charAt(0) == ' ')
      c = c.substring(1, c.length);

    if (c.indexOf(nameEQ) == 0) 
    {
      cookieValue = decodeURIComponent(c.substring(nameEQ.length, c.length));
      break;
    }
  }

  if (cookieValue != null)
  {
    var values = cookieValue.split("#");

    for (var i=0; i<values.length; i++)
    {
      var nameValuePair = values[i].split("=");
      if (nameValuePair.length == 2)
      {
        var attrName = nameValuePair[0];
        var attrValue = nameValuePair[1];

        if (attrName == "user_id")
          this.id = parseInt(attrValue);
        else if (attrName == "user_name")
          this.name = attrValue;
        else if (attrName == "title")
          this.title = attrValue;
        else if (attrName == "initials")
          this.initials = attrValue;
        else if (attrName == "middlename")
          this.middlename = attrValue;
        else if (attrName == "surname")
          this.surname = attrValue;
        else if (attrName == "gender")
          this.gender = parseInt(attrValue);
        else if (attrName == "user_type")
          this.type = parseInt(attrValue);
      }
    }
  }
}


function WebUser_save()
{
  // cookieFormat:  user_id=<userId>#user_name=<userName>#title=<title>#initials=<initials>#surname=<surname>#gender=<gender>
  // eg:            "user_id=234#user_name=PietJ#title=ing#initials=P.W.H.#surname=Joosten#gender=0"
  //                "user_id=345#user_name=RitaV#title=drs#initials=R.#surname=Verdonk#gender=1"
  var payload = "";
  payload += "user_id=" + (this.id != -1 ? this.id : "");
  payload += "#user_name=" + (this.name != null ? this.name : "");
  payload += "#title" + (this.title != null ? this.title : "");
  payload += "#initials=" + (this.initials != null ? this.initials : "");
  payload += "#surname=" + (this.surname != null ? this.surname : "");
  payload += "#gender=" + (this.gender != -1 ? this.gender : "");
  payload += "#user_type=" + (this.type != -1 ? this.type : "");
  payload += "#middlename=" + (this.middlename != null ? this.middlename : "");

  document.cookie = WEBUSER_COOKIENAME + "=" + encodeURIComponent(payload) + "; path=/";
}


function WebUser_applyPersonalization()
{
  if (this.isLoggedIn()) 
  {
    // First, find all elements in the current document with
    // class="${WEBUSER_NOTLOGGEDIN_CLASS}" and hide them
    var notLoggedInElems = getElementsByClassName(document, "*", WEBUSER_NOTLOGGEDIN_CLASS);
    for (var i=0; i<notLoggedInElems.length; i++)
      notLoggedInElems[i].style.display = "none";

    // Next, find all elements in the current document with 
    // class="${WEBUSER_LOGGEDIN_CLASS}" and show them.
    var loggedInElems = getElementsByClassName(document, "*", WEBUSER_LOGGEDIN_CLASS);
    for (var i=0; i<loggedInElems.length; i++)
      loggedInElems[i].style.display = "block";

    // Now replace any occurances of "<!-- [webUser.<attribute>] -->" markers 
    // within the loggedInElems with the correct attribute of the logged in user.
    for (var i=0; i<loggedInElems.length; i++)
    {
      loggedInElems[i].innerHTML = loggedInElems[i].innerHTML.
          replace(/<!-- \[webUser\.name\] -->/g, this.name);

      loggedInElems[i].innerHTML = loggedInElems[i].innerHTML.
          replace(/<!-- \[webUser\.id\] -->/g, this.id);

      loggedInElems[i].innerHTML = loggedInElems[i].innerHTML.
          replace(/<!-- \[webUser\.title\] -->/g, 
          this.title == null ? "" : this.title);

      loggedInElems[i].innerHTML = loggedInElems[i].innerHTML.
          replace(/<!-- \[webUser\.initials\] -->/g, 
          this.initials == null ? "" : this.initials);

      loggedInElems[i].innerHTML = loggedInElems[i].innerHTML.
          replace(/<!-- \[webUser\.middlename\] -->/g, 
          this.middlename == null ? "" : this.middlename);

      loggedInElems[i].innerHTML = loggedInElems[i].innerHTML.
          replace(/<!-- \[webUser\.surname\] -->/g, 
          this.surname == null ? "" : this.surname);

      loggedInElems[i].innerHTML = loggedInElems[i].innerHTML.
          replace(/<!-- \[webUser\.gender\] -->/g, 
          this.gender == -1 ? "" : this.gender);

      loggedInElems[i].innerHTML = loggedInElems[i].innerHTML.
          replace(/<!-- \[webUser\.type\] -->/g, 
          this.type == -1 ? "" : this.type);
    }
  }
  else // not logged in
  {
    // First, find all elements in the current document with 
    // class="${WEBUSER_LOGGEDIN_CLASS}" and hide them.
    var loggedInElems = getElementsByClassName(document, "*", WEBUSER_LOGGEDIN_CLASS);
    for (var i=0; i<loggedInElems.length; i++)
      loggedInElems[i].style.display = "none";

    // Next, find all elements in the current document with
    // class="${WEBUSER_NOTLOGGEDIN_CLASS}" and show them
    var notLoggedInElems = getElementsByClassName(document, "*", WEBUSER_NOTLOGGEDIN_CLASS);
    for (var i=0; i<notLoggedInElems.length; i++)
      notLoggedInElems[i].style.display = "block";
  }
}


/*
    Written by Jonathan Snook, http://www.snook.ca/jonathan
    Add-ons by Robert Nyman, http://www.robertnyman.com
    http://www.robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/
*/
function getElementsByClassName(oElm, strTagName, strClassName){
    var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    strClassName = strClassName.replace(/\-/g, "\\-");
    var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
    var oElement;
    for(var i=0; i<arrElements.length; i++){
        oElement = arrElements[i];      
        if(oRegExp.test(oElement.className)){
            arrReturnElements.push(oElement);
        }   
    }
    return (arrReturnElements);
}

