/**
 *  pagehistory.js
 *
 *  Manages the page history list.
 *
 *  @author   StijnW <Stijn.de.Witt@gx.nl>
 *  @date     2007/01/30
 *
 *  Copyright 2007 (c) by <GX> Creative Online Development B.V
 *  All rights reserved.
 *  GX: Open For Business
 *
 *  USAGE:
 *  -----
 *  At the top of your page (preferably in the head section of the document),
 *  create an instance of the PageHistory 'class'. Pass your current page as a
 *  parameter if it should be included in the list (it will only show up in 
 *  the next request):
 *
 *  <head>
 *    <script type="text/javascript" src="pagehistory.js"></script>
 *    <script type="text/javascript">
 *      var pageHistory = new PageHistory(
 *          new Page("My Page", "/mypage.html", "Click to go to my page"));
 *    </script>
 *
 *  At the position in your document where you want the history list to 
 *  appear, place an HTML element with a unique id:
 *
 *  <ul class="pageHistory" id="pageHistoryList">
 *    <!-- populated from javascript -->
 *  </ul>
 *
 *  At the bottom of your document, preferably just before the end of the body
 *  section, call the PageHistory member function populateList, passing the
 *  id of your element and the item HTML as a pattern:
 *
 *    <script type="text/javascript">
 *      pageHistory.populateList("pageHistoryList", 
 *          "<li><a href=\"@url@\" id=\"item@idx@\" title="@hint@">@title@</a></li>");
 *    </script>
 *  </body>
 *
 *  You can use the following pattern parameters in your HTML pattern:
 *  @title@ = Title of the page
 *  @url@   = URL of the page
 *  @hint@  = Popup hint for the page
 *  @idx@   = Index of the current item in the list
 *  
 *  IMPLEMENTATION DETAILS:
 *  ----------------------
 *  The page history is stored in a clientside cookie in a 
 *  String of the following format:
 *  <page>]|[<page>]|[<page>
 *  The string ']|[' is used as a separator. 
 *  <page> is itself an encoded string with this format:
 *  <title>}|{<url>}|{<hint>
 *  The string '}|{' is used as a separator.
 *  Example:
 *  "Home}|{/web/show/id=12345}|{Back to the homepage]|[Shop}|{/web/show/id=23456}|{Visit our shop"
 */

var PAGEHISTORY_COOKIE = "PAGEHISTORY";
var PAGEHISTORY_NOTITLE = "Geen titel";
var PAGEHISTORY_NOURL = "#";
var PAGEHISTORY_SEP_PAGE = "]|[";
var PAGEHISTORY_SEP_PART = "}|{";
var PAGEHISTORY_MAXPAGES = 3;

/**
 *  Constructor for the Page 'class'
 *
 *  @param  title   Title of the page
 *  @param  url     URL of the page. Use relative URL's whenever possible.
 *  @param  hint    Popup hint for the page.
 *
 *  Examples:
 *    var page = new Page("My Page", "/mypage.html");
 *    var page = new Page("My Page", "/mypage.html", "Click here");
 */
function Page(title, url, hint)
{
  this.title = title;
  if (this.title == null)
    this.title = PAGEHISTORY_NOTITLE;
  this.url = url;
  if (this.url == null)
    this.url = PAGEHISTORY_NOURL;
  this.hint = hint;

  this.toString = Page_toString;
}

function Page_toString()
{
  return this.title + PAGEHISTORY_SEP_PART + this.url + 
      (this.hint != null ? PAGEHISTORY_SEP_PART + this.hint : "");
}

/**
 *  Constructor for the PageHistory 'class'
 *
 *  @param  currentPage   A Page with the title and URL of the current page
 *                        if it should be added to the page history list, or 
 *                        null if it does not have to be added.
 *  @param  maxPages      Maximum number of pages to keep in the history list.
 *
 *  Examples:
 *    var pageHistory = new PageHistory(new Page("my page", "/mypage.html"));
 *    var pageHistory = new PageHistory(null);
 *    var pageHistory = new PageHistory();
 *    var myPage = new Page("my page", "/mypage.html", "Click here");
 *    var pageHistory = new PageHistory(myPage);
 */
function PageHistory(currentPage, maxPages)
{
  this.pages = new Array();
  this.currentPage = currentPage;

  this.maxPages = PAGEHISTORY_MAXPAGES;
  if (maxPages != null)
    this.maxPages = maxPages;

  // Alias methods
  this.loadPageHistory = PageHistory_loadPageHistory;
  this.savePageHistory = PageHistory_savePageHistory;
  this.toString = PageHistory_toString;
  this.populateList = PageHistory_populateList;

  // Load page history from cookie
  this.loadPageHistory(PAGEHISTORY_COOKIE);
  // The pagehistory is loaded. Now immediately save it. This
  // wil store our currentPage in the list if it was set, so it
  // will be available in the next request.
  this.savePageHistory(PAGEHISTORY_COOKIE);
}


function PageHistory_toString()
{
  var result = "";
  var maxPages = this.maxPages;
  if (this.currentPage != null)
  {
    // Check if the current page is already in the list
    var isInList = false;
    for (var i=0; i<this.pages.length; i++)
      if (this.pages[i].url == this.currentPage.url)
        isInList = true;

    // Only add the current page if it's not in the list already
    if (! isInList)
    {
      maxPages -= 1;
      result += this.currentPage;
    }
  }

  for (var i=0; (i<this.pages.length) && (i<maxPages); i++)
  {
    var page = this.pages[i];
    if (result != "")
      result += PAGEHISTORY_SEP_PAGE;
    result += page;
  }
  return result;
}


/**
 *  Populates the page history list with one item for each page in the list.
 *
 *  @param  listId        The id of the HTML element that should be populated.
 *                        Does not necesarilly have to be a list element.
 *  @param  itemPattern   A pattern that defines how the list items will be
 *                        created, pattern parameters will automatically be
 *                        filled in for you. Available parameters:
 *                            @title@ = Title of the page
 *                            @url@   = URL of the page
 *                            @hint@  = Popup hint for the page
 *                            @idx@   = Index of the current item in the list
 *                        
 *  Examples: 
 *    var pattern = "<li><a href=\"@url@\" id=\"item@idx@\" title="@hint@">@title@</a></li>";
 *    pageHistory.populateList("myHistoryList", pattern);
 *
 */
function PageHistory_populateList(listId, itemPattern)
{
  if ((listId == null) || (itemPattern == null))
    return false;

  list = document.getElementById(listId);
  if (list)
  {
    var html = "";
    for (var i=0; i<this.pages.length; i++)
    {
      var item = itemPattern;
      item = item.replace(/@title@/g, this.pages[i].title);
      item = item.replace(/@url@/g, this.pages[i].url);
      if (this.pages[i].hint != null)
        item = item.replace(/@hint@/g, this.pages[i].hint);
      else
        item = item.replace(/@hint@/g, "");
      item = item.replace(/@idx@/g, i);
      html += item + "\n";
    }
    list.innerHTML = html;
  }
}

/**
 *  Loads the page history from a cookie.
 *
 *  @param  cookieName  The name of the cookie to load from.
 */
function PageHistory_loadPageHistory(cookieName)
{
  var cookieValue = null;

  // Code 'borrowed' from Quirksmode.org, thanks Peter-Paul Koch!
  // http://www.quirksmode.org/js/cookies.html
  var nameEQ = 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 = unescape(c.substring(nameEQ.length, c.length));
      break;
    }
  }

  if (cookieValue != null)
  {
    pagesStrings = cookieValue.split(PAGEHISTORY_SEP_PAGE);
    for (var i=0; i<pagesStrings.length; i++)
    {
      pageString = pagesStrings[i];
      pageParts = pageString.split(PAGEHISTORY_SEP_PART);
      if (pageParts.length >= 2)
      {
        pageTitle = pageParts[0];
        pageUrl = pageParts[1];
        pageHint = null;
        if (pageParts.length == 3)
          pageHint = pageParts[2];
          
        this.pages[this.pages.length] = new Page(pageTitle, pageUrl, pageHint);
      }
    }
  }
}  

/**
 *  Saves the page history to a cookie.
 *
 *  @param  cookieName  The name of the cookie to save to.
 */
function PageHistory_savePageHistory(cookieName)
{
  document.cookie = cookieName + "=" + escape(this.toString()) + "; path=/";
}
