/*
 * A script for file inclusion, based on the one developed by kenpoco.
 * cf. http://d.hatena.ne.jp/kenpoco/20080501/1209636103
 *
 * usage:
 * <div>
 *    <script type="text/javascript" >
 *      include("./file_to_be_included", "root_directory_path");
 *    </script>
 * </div>
 *
 * A file "file_to_be_included" is included into the location where
 * the script is invoked. A key word 'ROOTDIR' in the file is replaced
 * with a string given by "root_directory_path".
 *
 * example:
 * <div>
 *    <script type="text/javascript" >
 *      include("../header.html", "..");
 *    </script>
 * </div>
 *
 */


function include(filename, rootdir, afterfunc) {

  include.seq = (include.seq)? include.seq + 1: 1;

  var id = new Date().getTime() + "-" + include.seq;
  var inc = document.createElement("iframe");

  inc.id = "inc-" + id;
  inc.src = filename;
  inc.style.display = "none";
  document.write("<span id=\"" + id + "\"></span>");
    
  var incfunc = function() {
    
    var s = (function() {
      var suffix = (n = filename.lastIndexOf(".")) >= 0 ? filename.substring(n): "default";
      if (suffix == ".html") return inc.contentWindow.document.body.innerHTML;
      if (suffix == ".txt") return inc.contentWindow.document.body.firstChild.innerHTML;
      if (suffix == "default") return inc.contentWindow.document.body.innerHTML;
    })();

    s = s.replace(/ROOTDIR/g, rootdir);

    var span = document.getElementById(id);

    var insertBeforeHTML = function(htmlStr, refNode) {
      if (document.createRange) {
        var range = document.createRange();
        range.setStartBefore(refNode);
        refNode.parentNode.insertBefore(range.createContextualFragment(htmlStr), refNode);
      } else {
        refNode.insertAdjacentHTML('BeforeBegin', htmlStr);
      }
    };

    insertBeforeHTML(s.split("&gt;").join(">").split("&lt;").join("<"), span);
    document.body.removeChild(inc);
    span.parentNode.removeChild(span);
    if (afterfunc) afterfunc();
  };

  if (window.attachEvent) {
    window.attachEvent('onload', 
      function() {
        document.body.appendChild(inc); 
        inc.onreadystatechange = function() { if (this.readyState == "complete") incfunc(); };
      });
  }
  else {
    document.body.appendChild(inc);
    inc.onload = incfunc;
  }
}

function ShowHideDiv(boxid, btnname) {
    var btnobj = document.getElementsByName(btnname).item(0);
    var targetobjs = document.getElementById(boxid);
    if (targetobjs.style.display != "none") {
        targetobjs.style.display = "none";
        btnobj.childNodes[0].nodeValue = "show";
    }
    else {
        targetobjs.style.display = "";
        btnobj.childNodes[0].nodeValue = "hide";
    }
}

