var historyName;
//var cookieName = "page_history";
setCookie("page_history",'');

var cookieName = "page_history_temp";
var cookieInfo;
var arr = new Array();

var MAX_TITLE_LEN = 15;
var MAX_URL_CNT = 5;

function setCookie (name, value){
  document.cookie = name + '=' + escape(value) + ";path=/;"
}

function getCookie(name){
  var search = name + '=';
  if (document.cookie.length>0) {
    offset = document.cookie.indexOf(search);
    if (offset != -1) {
      offset += search.length;
      end = document.cookie.indexOf(';',offset);
      if (end == -1) {
        end = document.cookie.length;
      }
      return unescape(document.cookie.substring(offset,end));
    }
  }
  return null;
}

function showHistory(){
  if(cookieInfo){
    if (isTopPage()) {
      return;
    }
    document.getElementById('header-history').style.marginBottom = '15px';
    arr = cookieInfo .split("|")
    for (var i = 0; i < arr.length; i++) {
      var temp = arr[i].split("::");
      var title = temp[0];
      if(title.length > MAX_TITLE_LEN) title = title.substring(0, MAX_TITLE_LEN) + '...';
      var url = temp[1];
      if(i>0) document.getElementById('header-history').innerHTML += "&nbsp;&gt;&nbsp;";
      document.getElementById('header-history').innerHTML += "<a href=" + url + "><strong>" + nameSafe(title) + "</strong></a>";
    }
  }
}

function nameSafe(name) {
  name = name.replace(/'/g , "&#146;");
  name = name.replace(/"/g , "&#148;");
  name = name.replace(/</g , "&#060;");
  name = name.replace(/>/g , "&#062;");

  return name;
}

function checkHistory(arrLocal){
  for(i=0; i<arrLocal.length; i++) {
    strHistory = arrLocal[i];
    strHistoryName = (strHistory.split("::"))[0];
    var strURL = (strHistory.split("::"))[1];
    if(strHistoryName.indexOf(historyName) > -1 && strHistoryName.length == historyName.length && strURL.length == document.URL.length) {
      return false;
    }
  }
  return true;
}

function isTopPage() {
  var url = document.URL;
  var match = url.match(/http:\/\/[^\/]+\//i);
  if (match != null) {
    url = url.replace(match, "");
  }
  return (url == "") ? true : false;
}

////////////////////////////////////////////////////////////////////////////////

var cookieInfo = getCookie(cookieName);

if(!historyName) {
  if (isTopPage()) {
    historyName = "ホーム";
  } else {
    historyName = document.title.replace(/ - .*/, '');
  }
}

if(cookieInfo){
  arr = cookieInfo .split("|")
  if(historyName != "" && checkHistory(arr)) {
    if(arr.length >= MAX_URL_CNT) {
      arr = (arr.slice(1, MAX_URL_CNT)).concat(new Array(historyName+"::"+document.URL));
    } else {
      arr = arr.concat(new Array(historyName+"::"+document.URL));
    }
    setCookie(cookieName,  (cookieInfo = arr.join("|")));
  }
} else {
  setCookie(cookieName, historyName+"::"+document.URL);
}
