/*  
  Title : Cookie Crumbs
  Author : Tom Coote
  Wedsite : http://www.tomcoote.co.uk
*/

 /**
  * @argument iNumberOfCrumbs - How many crumbs do you want to show on the page, ie the last 5 page views!
  *
  */
function CookieCrumbs(iNumberOfCrumbs) {
    
  var that = {}; 

  /* Private Variables */
  var sCookieCrumbsSeparator = '|',  // The value used to separate each 'link & title' pair in the cookie
    sLinkTitleSeparator = '::';    // The value used to separate link from title for each pair
    /* NOTE: don't use the above values in your page titles */


    /* Private Functions */

  function getCookie(name) {
    var start = document.cookie.indexOf(name + "=");
    var len = start + name.length + 1;

    if ((!start) && (name != document.cookie.substring(0, name.length))) {
      return null;
    }

    if (start == -1) {
      return null;
    }

    var end = document.cookie.indexOf( ";", len );

    if (end == -1) {
      end = document.cookie.length;
    }

    return unescape(document.cookie.substring(len, end));
  }

  function setCookie(name, value, expires, path, domain, secure) {
    var today = new Date();
    today.setTime(today.getTime());

    if (expires) {
      expires = expires * 1000 * 60 * 60 * 24;
    }

    var expires_date = new Date(today.getTime() + (expires));
    
    document.cookie = name+"="+escape(value) +
      ((expires) ? ";expires="+expires_date.toGMTString() : "") + 
      ((path) ? ";path=" + path : ";path=/") +
      ((domain) ? ";domain=" + domain : "") +
      ((secure) ? ";secure" : "");

    return getCookie(name);
  }

  function deleteCookie(name, path, domain) {
    if (getCookie(name)) {
      document.cookie = name + "=" +
      ((path) ? ";path=" + path : "") +
      ((domain) ? ";domain=" + domain : "") +
      ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
    }
  }

  function setLocation(iPos) {
    var sLocation = formatLastPage(document.location.toString());

    if (sLocation.indexOf('?') !== -1) {
      return sLocation + '&ccp=' + iPos;
    }
    else {
      return sLocation + '?ccp=' + iPos;
    }
  }

  function sliceCookie(Cookie) {
    var sLocation = document.location.toString(),
      iPos = -1, sCookies = '', sCrumbTrail = '', i = 0;

    if (sLocation.indexOf('?ccp=') !== -1) {
      sLocation = sLocation.slice(sLocation.indexOf('?ccp=')+5, sLocation.length); // will always be at the end so can use length
      iPos = parseInt(sLocation,10);
    }

    if (sLocation.indexOf('&ccp=') !== -1) {
      sLocation = sLocation.slice(sLocation.indexOf('&ccp=')+5, sLocation.length);
      iPos = parseInt(sLocation,10);
    }
    
    if (iPos === -1) {
      return Cookie;
    }
    else {
      sCookies = Cookie.split(sCookieCrumbsSeparator);

      if (sCookies.length-1 === iPos) {
        return Cookie;
      }

      for (i=0; i < iPos; i++) {
        sCrumbTrail += sCookieCrumbsSeparator + sCookies[i]; 
      }
    }

    sCrumbTrail = (sCrumbTrail === '') ? '||' : sCrumbTrail;
    return setCookie('CookieCrumbs', sCrumbTrail.replace(sCookieCrumbsSeparator,''), 1);
  }

  function formatLastPage(sLastPage) {

    if (sLastPage.indexOf('?ccp=') !== -1) {
      sLastPage = sLastPage.replace(sLastPage.slice(sLastPage.indexOf('?ccp='), sLastPage.length),'');
    }

    if (sLastPage.indexOf('&ccp=') !== -1) {
      sLastPage = sLastPage.replace(sLastPage.slice(sLastPage.indexOf('&ccp='), sLastPage.length),'');
    }

    return sLastPage;
  }

  function canUpdateExistingCookie(sLastPage) {
    if (document.referrer.toString() === document.location.toString()) {
      return false;
    }

    if (document.referrer.toString() === '') {
      return false;
    }

    if (formatLastPage(sLastPage) === document.location.toString()) {
      return false;
    }

    if (formatLastPage(sLastPage) === formatLastPage(document.location.toString())) {
      return false;
    }

    return true;
  }


  /* Public Functions */

  that.GetCrumbs = function() {
    try
    {
      var Cookie = getCookie('CookieCrumbs'),
        sCrumbTrail = '',
        sPageTitle = document.getElementsByTagName('title')[0].innerHTML || '',
        sCookies = '', sTitle = '', sLink = '', i = 0;

      if (document.referrer.toString() === '') {
        Cookie = setCookie('CookieCrumbs', sCookieCrumbsSeparator + setLocation(0) + sLinkTitleSeparator + sPageTitle, 1);
      }
      else if (Cookie !== null) {
        Cookie = sliceCookie(Cookie);  
        sCookies = Cookie.split(sCookieCrumbsSeparator);
        sLastPage = sCookies[sCookies.length-1].split(sLinkTitleSeparator)[0];

        if (canUpdateExistingCookie(sLastPage)) {
          Cookie = setCookie('CookieCrumbs', Cookie + sCookieCrumbsSeparator + setLocation(sCookies.length) + sLinkTitleSeparator + sPageTitle, 1);
        }
      }
      else {
        Cookie = setCookie('CookieCrumbs', sCookieCrumbsSeparator + setLocation(0) + sLinkTitleSeparator + sPageTitle, 1);
      }

      if (Cookie === null) { return ''; } // for browsers that have cookies blocked

      sCookies = Cookie.split(sCookieCrumbsSeparator);
      if (iNumberOfCrumbs === -1) {
        iNumberOfCrumbs = sCookies.length;
      }
      else {
        iNumberOfCrumbs = (sCookies.length < iNumberOfCrumbs) ? sCookies.length : iNumberOfCrumbs;
      }

      for (i=sCookies.length-1; i > sCookies.length-1-iNumberOfCrumbs; i--) {
        if (sCookies[i] !== '') {
          var sLinkTitle = sCookies[i].split(sLinkTitleSeparator);
          sCrumbTrail = '&#62; <a href=\'' + sLinkTitle[0] + '\'>' + sLinkTitle[1] + '</a> ' + sCrumbTrail;
        }
      }

      return sCrumbTrail.replace('&#62; ','');
    }
    catch(err) {
      //return err;  // For debugging
      return '';
    }
  };

  that.DeleteCookieTrail = function() {
    deleteCookie('CookieCrumbs');
  };

    return that;
}
