/**
 * Michael D. Miller's Javascript for the Vascular Network Toolkit
 **/

/* Write in headers the CSS alternatives */
function displayCSS() {
  var fullCSS = false;
  var browserVersion = parseInt(navigator.appVersion);

  /* check if your browser can even handle multiple style sheets */
  if (navigator.appName == "Netscape" && browserVersion >= 5)
     fullCSS = true;
  else if (navigator.appName == "Opera" && browserVersion >= 9) 
     fullCSS = true;
  else if (navigator.appName == "Microsoft Internet Explorer" && browserVersion >= 4) 
     fullCSS = true;

  /* if it can, we'll check for cookies and write the alternate sheets */
  if (fullCSS) {
     var cookieName = "vnt_style";
     window.onload = function(onLoadOpenCSS) {
       var cookie = getCookie(cookieName);
       var styleTitle = cookie ? cookie : getPreferredStyleSheet();
       setActiveStyleSheet(styleTitle);
       // this is one nasty hack :-/
       // but I can't think of anything clever ;;
       if (document.URL == "http://www2.truman.edu/~mdm162/vnt/contact.html")
         onRefreshDisplayCorrectly(document.forms[0]);

     }
     /* when leaving the site, save whatever style setting you have chosen */
     window.onunload = function(onUnloadSaveCSS) {
       var styleTitle = getActiveStyleSheet();
       createCookie(cookieName, styleTitle, 7);
     }
     /* write the alternate style sheets. the first one is hardcoded in every page for validation */
     //document.writeln("  <link rel='stylesheet' href='96dpi.css' title='Vasculature 96 DPI' type='text/css' />");
     document.writeln("  <link rel='alternate stylesheet' href='120dpi.css' title='Vasculature 120 DPI' type='text/css' />");
     document.writeln("  <link rel='alternate stylesheet' href='deep_blue.css' title='Deep Blue' type='text/css' />");
  }
}


/* Display the last modified date. */
function displayLastModified() {
  var theDay="";
  var theMonth="";
  var theyear="";
  var myDate;;

  if (0 == Date.parse(document.lastModified)) {
     document.writeln("<p>Javascript could not parse the last modified date of this website.</p>");
     return;
  }
  myDate = new Date(Date.parse(document.lastModified));
  var dayNumber = myDate.getDate();
  var myday= myDate.getDay();
  var mymonth = myDate.getMonth();
  theyear = myDate.getYear();
  /* some browsers report the year as 106, others as 2006. correct for this discrepancy */
  if (theyear < 2000)
     theyear += 1900;
  /* figure out what word day it is */
  theDay = myday;
  if(myday == 0)
     theDay = "Sunday";
  else if(myday == 1)
     theDay = "Monday";
  else if(myday == 2)
     theDay = "Tuesday";
  else if(myday == 3)
     theDay = "Wednesday";
  else if(myday == 4)
     theDay = "Thursday";
  else if(myday == 5)
     theDay = "Friday";
  else if(myday == 6)
     theDay = "Saturday";

  /* figure out what word month it is */
  if(mymonth == 0)
     theMonth = "January";
  else if(mymonth == 1)
     theMonth = "February";
  else if(mymonth == 2)
     theMonth = "March";
  else if(mymonth == 3)
     theMonth = "April";
  else if(mymonth == 4)
     theMonth = "May";
  else if(mymonth == 5)
     theMonth = "June";
  else if(mymonth == 6)
     theMonth = "July";
  else if(mymonth == 7)
     theMonth = "August";
  else if(mymonth == 8)
     theMonth = "September";
  else if(mymonth == 9)
     theMonth = "October";
  else if(mymonth == 10)
     theMonth = "November";
  else if(mymonth == 11)
     theMonth = "December";

  /* write it out in pretty syntax */
  document.writeln("<p>Last updated: ", theDay, ", ", theMonth, " ", dayNumber, ", ", theyear, ".</p>");
  return;
}

/* Bookmarks for multiple browsers */
function addToBookmarks() {

  
var url="http://www2.truman.edu/~mdm162/vnt/index.html";
  
var title="Vascular Network Toolkit";

  if (window.sidebar) { /* Mozilla */
     window.sidebar.addPanel(title,url,"");
  }  else if (window.external) { /* IE */
     
window.external.AddFavorite(url, title);
  }
  return;
}


function linkAddToBookmarks() {
  if (window.sidebar) { /* Mozilla Firefox*/
     document.writeln("<p><a href='javascript:addToBookmarks()'>Bookmark the Vascular Network Toolkit</a></p>")
  }  else if (window.external) { /* IE */
     document.writeln("<p><a href='javascript:addToBookmarks()'>Bookmark the Vascular Network Toolkit</a></p>")
  } else if (window.opera) { /* Opera */
     document.writeln("<p>Bookmark this site by: <em>Bookmarks -> Add bookmark</em> or press <b>Ctrl+D</b>(T?).</p>")
  }
  return;
}

function displayBrowserInfo() {
  var theAgent = navigator.userAgent;
  var browser = "";
  var ieLocation = theAgent.indexOf("MSIE");
  var operaLocation = theAgent.indexOf("Opera");
  var firefoxLocation = theAgent.indexOf("Firefox");
  var mozillaLocation = theAgent.indexOf("Mozilla");
  var fullVersion  = 0.0;
  var majorVersion = 0;
  var knownBrowser = false;
  if (ieLocation != -1) {
     // you're using IE!
     fullVersion  = parseFloat(theAgent.substring(ieLocation+5)); // skip over the MSIE_ part and get the version
     // I could either convert to an int (and round down automatically) or
     majorVersion = parseInt(""+fullVersion);
     browser = "Internet Explorer";
     knownBrowser = true;
  } else if (operaLocation != -1) {
     fullVersion  = parseFloat(theAgent.substring(operaLocation+6)); // skip over the Opera/ part and get the version
     majorVersion = parseInt(""+fullVersion);
     browser = "Opera";
     knownBrowser = true;
  } else if (firefoxLocation != -1) {
     fullVersion  = parseFloat(theAgent.substring(firefoxLocation+8)); // skip over the Firefox/ part and get the version
     majorVersion = parseInt(""+fullVersion);
     browser = "Mozilla Firefox";
     knownBrowser = true;
  } else if (mozillaLocation != -1) {
     fullVersion  = parseFloat(theAgent.substring(mozillaLocation+8)); // skip over the Mozilla/ part and get the version
     majorVersion = parseInt(""+fullVersion); // convert to a string and parse int (which I do)
     browser = "Mozilla";
     knownBrowser = true;
  } else {
     // I have no idea what browser you're using
     fullVersion = navigator.appVersion;
     majorVersion = navigator.appVersion;
     browser = navigator.appName;
     knownBrowser = false;
  }
  if (knownBrowser) {
     document.writeln("<ul>");
     if (browser == "Internet Explorer")
       document.writeln("<li id='iconie'>");
     else if (browser == "Opera")
       document.writeln("<li id='iconop'>");
     else if (browser == "Mozilla Firefox")
       document.writeln("<li id='iconff'>");
     else if (browser == "Mozilla")
       document.writeln("<li id='iconmz'>");
  } else {
     document.writeln("<p>");
  }
     document.writeln("", browser, " ", fullVersion, " detected.");
  if (knownBrowser) {
     document.writeln("</li></ul>");
  } else {
     document.writeln("</p>");
  }
}

/* Cookie Manipulation */
/* these cookie functions are modifications from ones in the public domain */

function createCookie(name,value,expiration) {
  /* the expiration date is multiplied by 1000 milliseconds * 60 seconds * 60 minutes * 24 hours, ie, in terms of days */
  if (expiration) {
     expiration *= 24*60*60*1000;
  }

  var date = new Date();
  date.setTime(date.getTime()+expiration);
  var expires = "; expires="+date.toGMTString();
  document.cookie = name+"="+value+expires+"; path=/~mdm162/vnt/";
}

/* this function was pretty much straight stolen from http://www.dustindiaz.com/top-ten-javascript */
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 ) );
}


/* set the cookie to expire yesterday. hopefully that's not some error code or infinity or something */
function eraseCookie(name) {
  createCookie(name,"",-1);
}

/* I think this was from http://www.dustindiaz.com/top-ten-javascript .. I don't use it. I don't use eraseCookie either :-) but just in case... */
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';
}

/**
 * Live Stylesheet swapping
 * - the idea came from my own work
 * but the implementation came from 
 * http://alistapart.com/stories/alternate/
 * So in other words, I couldn't have done it without them,
 * and I learned how to turn off entire style sheets thanks
 * to them.
 **/
function setActiveStyleSheet(title) {
  var i, a, main;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
     if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
        a.disabled = true;
        if(a.getAttribute("title") == title)
           a.disabled = false;
     }
  }
}

function getActiveStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
  if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled)
     return a.getAttribute("title");
  }
  return null;
}

function getPreferredStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
     if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("rel").indexOf("alt") == -1 && a.getAttribute("title"))
        return a.getAttribute("title");
  }
  return null;
}

/* depending on whether cookies are enabled or not, behave differently */
function displayCSSMenu() {
  if (document.cookie) {
     document.writeln("<ul id='cssmenu'>");
     document.writeln("<li><a href='#' onclick=\"setActiveStyleSheet('Vasculature 96 DPI'); return false;\">Vasculature 96 DPI</a></li>");
     document.writeln("<li><a href='#' onclick=\"setActiveStyleSheet('Vasculature 120 DPI'); return false;\">Vasculature 120 DPI</a></li>");
     document.writeln("<li><a href='#' onclick=\"setActiveStyleSheet('Deep Blue'); return false;\">Deep Blue</a></li>");
     document.writeln("</ul>");
  } else {
     document.writeln("<ul id='cssmenu'>");
     document.writeln("<li>You don't have</li>");
     document.writeln("<li>cookies enabled.</li>");
     document.writeln("<li>No CSS options!</li>");
     document.writeln("</ul>");
  }
}

/**
 * Form Validation
 * 
 * my download and contact forms both need validation to various degrees
 **/

// processes the form and determines if it is valid
function validateDownloadForm(downloadForm) {
  if (isInvalidName(downloadForm.fullname.value))
     return false;
  if (isInvalidEmail(downloadForm.email1.value))
     return false;
  if (isInvalidEmailMatch(downloadForm.email1.value, downloadForm.email2.value))
     return false;
  // implied else
  // document.write("<p>The form was valid! Dr. Garvey hasn't taught me how to send e-mail with forms yet ;;</p>");
  // document.close();
  return false;
}

// processes the form and determines if it is valid
function validateContactForm(contactForm) {
  if (isInvalidName(contactForm.fullname.value))
     return false;
  if (isInvalidCountry(contactForm.country.value))
     return false;
  if (isInvalidEmail(contactForm.email1.value))
     return false;
  if (isInvalidEmailMatch(contactForm.email1.value, contactForm.email2.value))
     return false;
  if (isInvalidOtherUse(contactForm.usetype,contactForm.useother.value))
     return false;
  if (isInvalidOtherContact(contactForm.contacttype,contactForm.contactother.value))
     return false;

  // implied else
  //document.write("<p>The form was valid! Dr. Garvey hasn't taught me how to send e-mail with forms yet ;;</p>");
  //document.close();
  return true;
}

/**
 * This regular expression should be a bit more complex/complete. Here are my cite/site references for deciding on my rules.
 * http://www.ietf.org/rfc/rfc2822.txt
 * http://www.icann.org/tlds/
 **/
function isInvalidEmail(email) {
  // I never used match in my homework, and in my homework I only declared RegExp
  // so I'm going to try to do this differently
  // accept just about any crazy thing for the username
  // (including .@whatever)
  // be a little more specific about domain names.. I've read that it's common practice that only 37 characters are allowed [a-z0-9-]
  // but I must be careful to allow subdomains!
  // be VERY specific that it ends in a valid ICANN certified domain.
  var addressParts = email.match(/^([a-z0-9._!#$%+-]+)@([a-z0-9-]+([.][a-z0-9-]+)*)[.]([a-z]{2}|com|edu|gov|int|mil|net|org|aero|biz|coop|museum|name|info|pro|arpa)$/i);
  // my goal for this e-mail address verifier is to be very lenient. it should accept some pretty weird addresses like ...@---.com which may actually be technically be valid
  // I figure since I [hopefully] will be dealing with people from other countries,
  // they will have weird things I won't expect so I should have this lenient stance

  if (addressParts == null) {
     alert("You did not provide a valid e-mail address.\nPlease retype both and try again.");
     return true;
  }
  // implied else
  /* done debugging, this displays the pieces! very cool
  alert("E-mail success!\nThe e-mail you gave broke down as:");
  for (var i in addressParts) {
     alert(addressParts[i]);
  }
  */
  // note this is a 'negative' function so a valid result is false
  return false;
}

// I merely want to check if it's a valid name with title
function isInvalidName(name) {
  // I want to capture full names with titles.. so I'm expecting at least some letters and then some whitespace/nonletters and then some letters again
  // and I'm expecting this to happen at least once, but preferably more than once.
  var nameParts = name.match(/\w+(\W+\w+)+/);
  var badwordFilter = name.search(/poop|pee|darn|dang|shoot|crap|elephantiasis/i);
  if (badwordFilter != -1) {
     alert("You entered a bad word in the name field.\nPlease be nice, my Javascript is very sensitive. That was mean. ;;\n");
     return true;
  }
  if (nameParts == null) {
     alert("You did not provide a valid name with title.\nPlease put some sort of period or space between your title and your name and try again.");
     return true;
  }
  // implied else
  // note this is a 'negative' function so a valid result is false
  return false;
}

// this function is simple, all it checks is if the two are the same.
// since this is a 'negative' function, if they are the same, then it returns false
// if they are different, it returns true
function isInvalidEmailMatch(emailA, emailB) {
  if (emailA == emailB)
     return false;
  // they were different
  alert("You did not provide identical e-mail addresses.\nPlease recheck both and try again.");
  return true;
}

// is this a blank string? only need to check if it's empty or not
// actually, I'll be a little more complicated than that, but not too much!
function isInvalidCountry (country) {
  // basically just like full name, only 'extra stuff' is optional. just require SOMETHING! very minimal and accepting
  var countryParts = country.match(/\w+(\W+\w+)*/);
  if (countryParts != null)
     return false;

  // implied all else
  // remember, these are negative functions
  alert("You did not provide a country name. Please don't fear!\nThe author is merely curious about the reach of his work.");
  return true;
}

// if the 'other use type' field was enabled, then make sure the user put something
function isInvalidOtherUse (radioButton, otherUse) {
  // make sure the user even clicked other!
  for (var i=0; i < radioButton.length; i++) {
    if (radioButton[i].checked && radioButton[i].value!="other")
       return false;
  }
  var otherUseParts = otherUse.match(/\w+(\W+\w+)*/);
  if (otherUseParts != null)
     return false;

  // implied all else
  // remember, these are negative functions
  alert("You specified 'other' for use, but did not elaborate.\nPlease enter something brief and try again.");
  return true;
}

// if the 'other contact type' field was enabled, then make sure the user put something
function isInvalidOtherContact (radioButton, otherContact) {
  // make sure the user even clicked other!
  for (var i=0; i < radioButton.length; i++) {
    if (radioButton[i].checked && radioButton[i].value!="other")
       return false;
  }
  var otherContactParts = otherContact.match(/\w+(\W+\w+)*/);
  if (otherContactParts != null)
     return false;

  // implied all else
  // remember, these are negative functions
  alert("You specified 'other' for contact reason, but did not elaborate.\nPlease enter something brief and try again.");
  return true;
}


/**
 * While the creation of this method and it's similar method, toggleTypeOther
 * was based off of Dr. Garvey's example http://vh216602.truman.edu/agarvey/cs315/recipe08_10.html
 * the research on how to script it was done firstly in the book.
 * I cite my page numbers where applicable.
 **/
function toggleContactOther(anEvent) {
  if (!anEvent) {
     // this may be different than null
     alert("anEvent was nonexistant");
     return;
  }
  if (anEvent == null) {
     alert("anEvent was null");
     return;
  }

  var theTarget;
  if (anEvent.target) // DOM (page 230)
     theTarget = anEvent.target;
  else if (anEvent.srcElement) // IE (page 232)
     theTarget = anEvent.srcElement;

  var optionalField = document.getElementById("OtherContact");
  if (theTarget.id == "contactTypeO")
      optionalField.style.display = "inline";
  else
      optionalField.style.display = "none";  
  return;
}

// as directly above
function toggleTypeOther(anEvent) {
  if (!anEvent) {
     // this may be different than null
     alert("anEvent was nonexistant");
     return;
  }
  if (anEvent == null) {
     alert("anEvent was null");
     return;
  }

  var theTarget;
  if (anEvent.target) // DOM (page 230)
     theTarget = anEvent.target;
  else if (anEvent.srcElement) // IE (page 232)
     theTarget = anEvent.srcElement;

  var optionalField = document.getElementById("OtherUse");
  if (theTarget.id == "useTypeO")
      optionalField.style.display = "inline";
  else
      optionalField.style.display = "none";  
  return;
}

/**
 * if you refresh the page with the 'Other' option clicked, the other field disappears
 * but it remembers your preference for the 'Other' to remain clicked
 * so this function's purpose is to turn on 'other' text fields if they're supposed to
 * be on when a page is first loading.. specifically because of a refresh
 * Note: Dr. Garvey, your example doesn't do this :-p
 **/
function onRefreshDisplayCorrectly(contactForm) {
  
  // one at a time, let's do 'use' first
  var radioButton = contactForm.usetype;
  var optionalField = document.getElementById("OtherUse");
  for (var i=0; i < radioButton.length; i++) {
     if (radioButton[i].checked && radioButton[i].value=="other")
        optionalField.style.display = "inline";
  }

  // now do 'contact'
  radioButton = contactForm.contacttype;
  optionalField = document.getElementById("OtherContact");
  for (var i=0; i < radioButton.length; i++) {
     if (radioButton[i].checked && radioButton[i].value=="other")
        optionalField.style.display = "inline";
  }
  
}
