/*
A wee bit of java script that supports the construction of CVRTI
web pages. 

 tjd
*/

// Site top is the directory containing the top level index.html file.
// Code handles three cases:
// 1 - Page loaded via http url.
// 2 - Page loaded via file url within an svn working copy of the web site.
// 3 - Page loaded via some other file url.
function findSiteTop() {
  var siteTop = null;
  var sl = "/";
  var winMatch = new RegExp("^/?[A-Z]:");
  if (location.pathname.match(winMatch))
    sl = "\\";
  var path = location.pathname.substr(0, location.pathname.lastIndexOf(sl));
  var rootDir = new RegExp("^www-cvrti|^htdocs|^r1|^trunk");
  siteTop="";
  var base = path.substr(path.lastIndexOf(sl) + 1);
  while ((base.match(rootDir) == null) && base != "") {
    siteTop += ".." + sl;
    path = path.substr(0, path.lastIndexOf(sl));
    base = path.substr(path.lastIndexOf(sl)+1);
  }
  if (base == "")
    switch(location.protocol) {
      case "http:":
        siteTop = sl;
	break;
      case "https:":
        siteTop = sl;
	break;
      case "file:":
        siteTop = "http://www.cvrti.utah.edu/";
	break;
    }
  return siteTop;
}

// Insert boilerplate page graphics.
function doPageGraphic() {
  document.write("\
    <img class=\"frame-top\" src=\"", siteTop, "images/top.png\"\
      alt=\"Top-left of page artwork\" usemap=\"#u_of_u_link\" border=\"0\"/>\
    <img class=\"frame-left\" src=\"", siteTop, "images/left.png\"\
      alt=\"Left of page artwork\"/>\
    <map name=\"u_of_u_link\" id=\"u_of_u_link\"/>\
      <area shape=\"rect\" alt=\"Link to U of U\" coords=\"841,14,914,37\" href=\"http://www.utah.edu\" target=\"_self\"/>\
    </map>\
  ");
}

var instituteMenu = [
  {
    id: "institute-label",
    cls: "nav-label",
    text: "Institute"
  },
  {
    id: "home",
    cls: "nav-link",
    url: "index.html",
    text: "Home"
  },
  {
    cls: "nav-link",
    url: "contact/contact.html",
    text: "Contact Info"
  },
  {
    cls: "nav-link",
    url: "personnel/core.html",
    text: "Core"
  },
  {
    cls: "nav-link",
    url: "personnel/personnel.html",
    text: "Personnel"
  },
  {
    cls: "nav-link",
    url: "friends/friends.html",
    text: "Friends"
  },
  {
    cls: "nav-link",
    url: "resources/resources.html",
    text: "Resources"
  },
  {
    cls: "nav-link",
    url: "positions/positions.html",
    text: "Open Positions (0)"
  }
];

var researchMenu = [
  {
    cls: "nav-label",
    text: "Research"
  },
  {
    cls: "nav-link",
    url: "seminars/seminars.html",
    text: "Seminars"
  },
  {
    cls: "nav-link",
    url: "seminars/rip.html",
    text: "Research in Progress<br\ >&nbsp;&nbsp;Seminars"
  },
  {
    cls: "nav-link",
    url: "research/featured/featured.html",
    text: "Featured"
  },
  {
    cls: "nav-link",
    url: "research/wo/wo.html",
    text: "Whole&nbsp;Organ"
  },
  {
    cls: "nav-link",
    url: "research/cell/cell.html",
    text: "Cellular &amp; Molecular"
  },
  {
    cls: "nav-link",
    url: "publications/pubs-index.html",
    text: "Publications"
  }
];

var miscMenu = [
  {
    cls: "nav-label",
    text: "Miscellanea"
  },
  {
    cls: "nav-link",
    url: "whatsnew/whatsnew.html",
    text: "What\'s&nbsp;New"
  },
  {
    id: "about-this-site",
    cls: "nav-link",
    url: "about/about.html",
    text: "About This Site"
  }
];

var computingMenu = [
  {
      cls: "nav-label",
      text: "Computing"
  },
  {
      cls: "nav-link",
      url: "internal/computing/index.html",
      text: "Overview"
  },
  {
      cls: "nav-link",
      url: "internal/computing/osx/index.html",
      text: "OS X"
  },
  {
      cls: "nav-link",
      url: "internal/computing/windows/index.html",
      text: "Windows"
  },
  {
      cls: "nav-link",
      url: "internal/computing/admin/index.html",
      text: "Admin"
  }
];

// Return array representing the page's main nav menu.
function navMenu() {
  var navMenu;
  var visitedInternal = new Cookie(document, "visited_internal", null, "/");
  visitedInternal.load();
  if (visitedInternal.visited == "yes") {
//    navMenu = instituteMenu.concat(researchMenu, miscMenu, computingMenu);
    navMenu = instituteMenu.concat(researchMenu, computingMenu);
  } else
//    navMenu = instituteMenu.concat(researchMenu, miscMenu);
    navMenu = instituteMenu.concat(researchMenu);
  return navMenu;
}

// Insert nav links in a div element.
function doNavLinks() {
  document.write("<div class=\"nav-links\">");
  doBareNavLinks(navMenu());
  document.write("</div>");
}
 
// Generate navigation links from given table.
function doBareNavLinks(nl) {
  if (nl != null) {
    for (var i=0; i<nl.length; ++i) {
      if (nl[i].cls == "nav-label") {
        document.write("<em");
	if (nl[i].id != null)
	  document.write(" id=\"" + nl[i].id + "\"");
	document.write(" class=\"nav-label\">", nl[i].text, "</em>");
      } else if (nl[i].cls == "nav-link") {
        document.write("<a");
	if (nl[i].id != null)
	  document.write(" id=\"" + nl[i].id + "\"");
	document.write(" class=\"nav-link\" href=\"", siteTop + nl[i].url+ "\">" + nl[i].text + "</a>");
      }
    }
  }
}

// Write raw page footer (no surrounding context).
function doBareFooter() {
  document.write("\
    Nora Eccles Harrison Cardiovascular Research and Training\
    Institute<br />University of Utah<br /> 95 S. 2000 E. Salt Lake City, UT\
    84112<br />(801) 581-8183 | <script type=\"text/javascript\">eyeware(\"info\")</script><br />\
  <a href=\"http://www.utah.edu/disclaimer/disclaimer_home.html\">Disclaimer</a>\
  | <a href=\"", siteTop, "about/about.html\">About This Site</a>\
  ");
}

// Write page footer in the context of a "footer" div class.
function doFooterLinks() {
  document.write("<div class=\"footer\">");
  doBareFooter();
  document.write("</div>");
}

// Start page content.
function beginContent() {
  document.write("<div id=\"content\">");
}

// End page content.
function endContent() {
  document.write("</div>");
}

// Write page pre-content stuff.
function preContent() {
  doPageGraphic();
  doNavLinks();
  beginContent();
}

// Write page post-content stuff.
function postContent() {
  doFooterLinks();
  endContent();
}

// Constructor for InternalPage class.  Creates and stores cookie that
// indicates that the user has  visited the internal site.
function InternalPage() {
  var visitedInternal = new Cookie(document, "visited_internal", null, "/");
  visitedInternal.load();
  if (visitedInternal.visited == null) {
    visitedInternal.visited = "yes";
    visitedInternal.store();
  }
}

// Functionality of preContent() and postContent() doesn't change for
// internal pages.
InternalPage.prototype.preContent = preContent;
InternalPage.prototype.postContent = postContent;


/* For every other div element of class divClass, change the div
   element's class to divClass + "-odd".  Used, for instance, in
   alternately highlighting the rows of table.  */
function stripeDivElementsWithClass(divClass) {
  var nodeList = document.body.getElementsByTagName("div");
  var doOddEntry = false;
  for (var i=0; i < nodeList.length; ++i) {
    var element = nodeList.item(i);
    var attrValue = getAttrValue(element,"class");
    if (attrValue != null && attrValue == divClass) {
      if (doOddEntry)
	setClassAttribute(element, divClass + "-odd");
      doOddEntry = !doOddEntry;
    }
  }
}

// ++++++
// The following Cookie class is from "JavaScript-The Definitive Guide",
// by David Flanagan.
function Cookie(document, name, hours, path, domain, secure)
{
    // All the predefined properties of this object begin with '$'
    // to distinguish them from other properties, which are the values to
    // be stored in the cookie
    this.$document = document;
    this.$name = name;
    if (hours)
        this.$expiration = new Date((new Date()).getTime(  ) + hours*3600000);
    else this.$expiration = null;
    if (path) this.$path = path; else this.$path = null;
    if (domain) this.$domain = domain; else this.$domain = null;
    if (secure) this.$secure = true; else this.$secure = false;
}

// This function is the store(  ) method of the Cookie object
Cookie.prototype.store = function (  ) {
  // First, loop through the properties of the Cookie object and
  // put together the value of the cookie. Since cookies use the
  // equals sign and semicolons as separators, we'll use colons
  // and ampersands for the individual state variables we store 
  // within a single cookie value. Note that we escape the value
  // of each state variable, in case it contains punctuation or other
  // illegal characters.
  var cookieval = "";
  for(var prop in this) {
      // Ignore properties with names that begin with '$' and also methods
      if ((prop.charAt(0) == '$') || ((typeof this[prop]) == 'function')) 
	  continue;
      if (cookieval != "") cookieval += '&';
      cookieval += prop + ':' + escape(this[prop]);
  }

  // Now that we have the value of the cookie, put together the 
  // complete cookie string, which includes the name and the various
  // attributes specified when the Cookie object was created
  var cookie = this.$name + '=' + cookieval;
  if (this.$expiration)
      cookie += '; expires=' + this.$expiration.toGMTString(  );
  if (this.$path) cookie += '; path=' + this.$path;
  if (this.$domain) cookie += '; domain=' + this.$domain;
  if (this.$secure) cookie += '; secure';

  // Now store the cookie by setting the magic Document.cookie property
  this.$document.cookie = cookie;
}

// This function is the load(  ) method of the Cookie object
Cookie.prototype.load = function(  ) { 
  // First, get a list of all cookies that pertain to this document
  // We do this by reading the magic Document.cookie property
  var allcookies = this.$document.cookie;
  if (allcookies == "") return false;

  // Now extract just the named cookie from that list
  var start = allcookies.indexOf(this.$name + '=');
  if (start == -1) return false;   // Cookie not defined for this page
  start += this.$name.length + 1;  // Skip name and equals sign
  var end = allcookies.indexOf(';', start);
  if (end == -1) end = allcookies.length;
  var cookieval = allcookies.substring(start, end);

  // Now that we've extracted the value of the named cookie, we
  // must break that value down into individual state variable 
  // names and values. The name/value pairs are separated from each
  // other by ampersands, and the individual names and values are
  // separated from each other by colons. We use the split(  ) method
  // to parse everything.
  var a = cookieval.split('&');    // Break it into an array of name/value pairs
  for(var i=0; i < a.length; i++)  // Break each pair into an array
      a[i] = a[i].split(':');

  // Now that we've parsed the cookie value, set all the names and values
  // of the state variables in this Cookie object. Note that we unescape(  )
  // the property value, because we called escape(  ) when we stored it.
  for(var i = 0; i < a.length; i++) {
      this[a[i][0]] = unescape(a[i][1]);
  }

  // We're done, so return the success code
  return true;
}

// This function is the remove(  ) method of the Cookie object
Cookie.prototype.remove = function(  ) {
  var cookie;
  cookie = this.$name + '=';
  if (this.$path) cookie += '; path=' + this.$path;
  if (this.$domain) cookie += '; domain=' + this.$domain;
  cookie += '; expires=Fri, 02-Jan-1970 00:00:00 GMT';

  this.$document.cookie = cookie;
}
// End of Cookie class.
// ++++++

// Some primitive AJAX stuff

var READY_STATE_UNINITIALIZED = 0;
var READY_STATE_LOADING = 1;
var READY_STATE_LOADED = 2;
var READY_STATE_INTERACTIVE = 3;
var READY_STATE_COMPLETE = 4;

// Return a new XMLHttpRequest object.
function xmlHttpRequestObject() {
    var r;
    if (window.XMLHttpRequest) {
	try {
	    r = new XMLHttpRequest();
	} catch(error) {
	    r = false;
	}
    } else if (window.ActiveXObject) {
        try {
            r = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
            try {
                r = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {
          	r = false;
            }
	}
    }
    return r;
}

// Generate an email link.  Use this function instead of hard coding
// email addresses.  Use of this function assumes email harvesting
// bots don't execute javascript code.
function eyeware(n, d, lt) {
  if (arguments.length < 2 || d == null)
    d = "cvrti&#46;utah&#46;edu";
  var em = n + "&#64;" + d;
  if (arguments.length < 3 || lt == null)
    lt = em;
  document.write("<a href=\"&#109;&#97;&#105;&#108;&#116;&#111;:" + em + "\">" + lt + "</a>")
}

// Initiate a http request.
function ajaxSendRequest(req, url, params, onreadystatechange, method)
{
  if (!method)
    method = "GET";
  if (req) {
    req.onreadystatechange = onreadystatechange;
    req.open(method, url, true);
    req.setRequestHeader("Content-Type", "text/plain");
    req.send(params);
  }
}

function countPageChange()
{}

// Call script to count page hit.
function countPage()
{
  if (location.protocol != "file:") {
    var req = xmlHttpRequestObject();
    var url = location.protocol + "//" + location.host + "/ruby/chits.rb";
    ajaxSendRequest(req, url, "page="+location.pathname, countPageChange, "POST");
  }
}

//countPage();

var siteTop = findSiteTop();

