//  ==================================================================	
//	TILT Scripts
//	
//	Originally written by Bill Dortch, hIdaho Design <bdortch@netw.com>
//	Modified by Moira Burke <mburke@pcc.edu>
//	
//  ==================================================================


//  ==================================================================
//	COOKIES
//  ==================================================================

//  ------------------------------------------------------------------
// 	checkCookies
//
// 	Make sure cookies are readable and writeable
function checkCookies() {
	setCookie("cookiesEnabled", true);
	var contents = false;
	contents = getCookie("cookiesEnabled");
	
	if( contents ) { 
		DeleteCookie("cookiesEnabled");
		return true;
	}
	else { return false; }
}


//  ------------------------------------------------------------------
// 	getCookieVal
//
// 	Return the decoded value of a cookie
function getCookieVal (offset) {
  var endstr = document.cookie.indexOf (";", offset);
  if (endstr == -1)
    endstr = document.cookie.length;
  return unescape(document.cookie.substring(offset, endstr));
}


//  ------------------------------------------------------------------
//	getCookie
//
// 	Return the value of the cookie specified by "name".
//    name - String object containing the cookie name.
//    returns - String object containing the cookie value, or null if the cookie does not exist.
function getCookie (name) {
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;

  while (i < clen) {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg) {
		return getCookieVal (j);
	}
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break; 
  }
  return null;
}


//  ------------------------------------------------------------------
//	setCookie
//	
//	Create or update a cookie.
//    name - String object object containing the cookie name.
//    value - String object containing the cookie value.  May contain any valid string characters.
//    [expires] - Date object containing the expiration data of the cookie.  If omitted or null, expires the cookie at the end of the current session.
//    [path] - String object indicating the path for which the cookie is valid. If omitted or null, uses the path of the calling document.
//    [domain] - String object indicating the domain for which the cookie is valid.  If omitted or null, uses the domain of the calling document.
//    [secure] - Boolean (true/false) value indicating whether cookie transmission requires a secure channel (HTTPS).  
//
// 	The first two parameters are required.  The others, if supplied, must
// 	be passed in the order listed above.  To omit an unused optional field,
// 	use "" as a place holder.  
function setCookie (name, value) {

  var argv = setCookie.arguments;
  var argc = setCookie.arguments.length;
  var expires = (argc > 2) ? argv[2] : null;
  var path = "/";
  //var path = (argc > 3) ? argv[3] : null;
  var domain = (argc > 4) ? argv[4] : null;
  var secure = (argc > 5) ? argv[5] : false;

 var newcookie =  name + "=" + escape(value) +
    ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
    ((path == null) ? "" : ("; path=" + path)) +
    ((domain == null) ? "" : ("; domain=" + domain)) +
    ((secure == true) ? "; secure" : "");

document.cookie = newcookie;
	
}

//  ------------------------------------------------------------------
// 	deleteCookie
//
// 	Delete a cookie. (Sets expiration date to current date/time)
//    name - String object containing the cookie name
function DeleteCookie(name) {
  var expiration = new Date();
  expiration.setTime (expiration.getTime() - 100);  // This cookie is history
  setCookie(name,"", expiration);
}

//  ------------------------------------------------------------------
//	setQuizCookie
//
//  Function to set a quiz cookie
//    name - name of cookie
//    elem - Form element array
//    num  - Number of correct answers
function setQuizCookie(name, elem) {
  var c_val = "";               // Cookie value string

  for (i=0; i < elem.length-1; i++)	// Ignore submit button element
    if (elem[i].checked) {
      if (c_val != "")
        c_val += "&";
      c_val += (elem[i].name + ':' + elem[i].value);
    }

  return (name + '=' + escape(c_val));
}


//  ------------------------------------------------------------------
//	printCookies
//
//  Function to print all cookies
//
function printCookies(out) {
  var cookies = document.cookie.split(';');

  for (i=0; i < cookies.length; i++)
    if (cookies[i].indexOf("undefined") == -1)
      out.writeln(unescape(cookies[i]) + "<BR>");
}


//  ------------------------------------------------------------------
//	trimCookie
//
//  Function trimming last subvalue from a cookie value
//    name	- Cookie name string
//    value	- Cookie value string
//
function trimCookie(name, value) {
  var index = value.lastIndexOf('&');
  var newVal = value.substring(0, index);

  setCookie(name, newVal);
}

//  ------------------------------------------------------------------
//	resetQuizCookies
//
//  Function resets quiz cookies to zero-length strings
//    end	- End quiz cookie
function resetQuizCookies(mod, end) {
  var root = "m" + mod + "q"
  var cookie;

  for (i = 1; i <= end; i++) {
    cookie = root + i;
    setCookie(cookie, "");
  }

  setCookie("ans", "");
  setCookie("last", "");	// Reset last visited question to null
}


//  ------------------------------------------------------------------
//	getSubValue
//
//  Function to extract subvalue from a multi-value cookie
//    cookieName	- Name of multi-value cookie
//    subname		- Name to subvalue
function getSubValue(cookieName, subname) {
	
  var cookie = getCookie(cookieName);
	
  if (cookie != null) {
    var subValueArray = cookie.split(",");
    subname += "=";

    for (i=0; i < subValueArray.length; i++) {
      var strIndex = subValueArray[i].indexOf(subname);
      if (strIndex != -1)
	return subValueArray[i].substring(strIndex + subname.length);
    }
  }
  return null;
}

//  ------------------------------------------------------------------
//	setSubValue
//
//  Function to add subvalue to a cookie
//    cookieName	- Name of cookie
//    subname   	- Name of subvalue
//    subvalue		- Subvalue
function setSubValue(cookieName, subname, subvalue) {

  var cookie = getCookie(cookieName);
  var subval = subname + "=" + subvalue;

  if (getSubValue(cookieName, subname) != null) {
    cookie = cutSubValue(cookie, subname);
  }
  if (cookie != null && cookie != "") {
    cookie += ("," + subval);
  }
  else {	
	cookie = subval; 
  }

  if (cookieName != "reg") {  setCookie(cookieName, cookie); }
  else {  setCookie(cookieName, cookie); }
}

//  ------------------------------------------------------------------
//	cutSubValue
//
//  Function to cut subvalue from a cookie
//    cookie    - Cookie value
//    subname   - Name of subvalue to cut
function cutSubValue(cookie, subname) {
  var from = cookie.indexOf(subname + "=");
  var to = cookie.indexOf(",", from);

  if (from > 0 && cookie.indexOf(",", from-1) == from-1)
    from--;

  if (to == -1)
    return cookie.substring(0, from);
  else {
    var begin = cookie.substring(0, from);
    var end = cookie.substring(to, cookie.length);
    return (begin + end);
  }
}




//  ==================================================================
//	QUIZ-RELATED PRINT FUNCTIONS
//  ==================================================================


//  ------------------------------------------------------------------
//	printPercent
//
//  Function to print colorful percent
//    out  	- Document output reference
//    percent	- Percentage value
function printPercent(out, percent) {
  if (percent > 75)
    out.write("<FONT color=\"green\">");
  else if (percent > 50)
    out.write("<FONT color=\"orange\">");
  else
    out.write("<FONT color=\"red\">");

  out.write(percent + "%</FONT>\n</TR>\n");
}

//  ------------------------------------------------------------------
//	printQuizInfo
//
//  Function to print quiz question results
//    out	- Document output reference
//    prob	- Number of problem
//    total	- Total # of possible correct answers
//    returns	- Number of correct answers for this problem
function printQuizInfo(out, prob, total) {
	//alert("in printQuizInfo: " + out + " " + prob + " " + total);
  var ques, correctAns, wrongAns, percent;
  var cookie = "q" + prob;

  out.write("<TR>\n  <TD align=\"left\">" + prob + "\n" +
	"  <TD align=\"center\">");

  correctAns = parseInt(getSubValue("ans", cookie));
  out.write(correctAns + "\n  <TD align=\"center\">");

  wrongAns = total - correctAns;
  out.write(wrongAns + "\n  <TD align=\"right\">");

  percent = Math.round((correctAns / total) * 100);
  printPercent(out, percent);

  return correctAns;
}

//  ------------------------------------------------------------------
//	printQuizTotal
//
//  Function to print quiz totals
//    out	- Document output reference
//    total	- Total # of questions in quiz
//    right	- # of questions answered right
function printQuizTotal(out, total, right) {
	//alert("in printQuizTotal.  out=" + out + ", total=" + total + ", right=" + right);
  var percent;

  out.write("<TR>\n  <TH align=\"left\">Total\n  <TD align=\"center\">");
  out.writeln(right);

  out.write("  <TD align=\"center\">");
  out.writeln(total-right);

  out.write("  <TD align=\"right\">");
  percent = Math.round((right / total) * 100);
  printPercent(out, percent);
}




function Perform(func, modnum) {
  if (func == "retake") {
    resetQuizCookies(modnum, 9);	
    top.document.location = "quiz.htm";
  }
  else if (func == "print") {
 	if ((navigator.appVersion.indexOf("Mac")!=-1) && ((navigator.appVersion.toLowerCase().indexOf('msie')!=-1) || (navigator.appVersion.toLowerCase().indexOf('safari')!=-1)) ) {
		alert("Sometimes this button doesn't work on Macs.  \n\n If it doesn't print, try File > Print instead.");
	}	
	window.print();
  }
}


function isValidEmail(str) {

   return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
 }
 
function checkValues(emailto, emailfrom, fullname) {
	
	if ( (emailto.indexOf(".") > 2) && (emailto.indexOf("@") > 0) ) {
		if ( (emailfrom.indexOf(".") > 2) && (emailfrom.indexOf("@") > 0) ) {
			if ( fullname.length > 2 ) {
			document.emailform.submit();
			return true;
			}
			else { 
				alert("You must include your full name.");
				return false;
			}
		}
		else {
			if (emailfrom.length < 1) { alert("You must include your email address."); }
			else {	alert("Please check this address: My email: " + emailfrom); }
			return false;
		}
	}
	else {
		if (emailto.length < 1) { alert(" You must include an address to send mail to."); }
		else { alert("Please check this address: To: " + emailto); }
		return false;
	}
}





//  ==================================================================
//	CHECK BROWSER REQUIREMENTS
//  ==================================================================


//  ------------------------------------------------------------------
//	checkBrowserRequirements
//
//	Determines whether browser is sufficient to run TILT -- brings up
//  warning for IE 2 or Netscape 3.  Assumes all future browsers will work.
//
// 	Based on JavaScript Browser Sniffer
// 	Eric Krok, Andy King, Michel Plungjan Jan. 31, 2002
// 	see http://www.webreference.com/ for more information
function checkBrowserRequirements() {

	// convert all characters to lowercase to simplify testing
    var agt=navigator.userAgent.toLowerCase();
    var appVer = navigator.appVersion.toLowerCase();

    var is_minor = parseFloat(appVer);
    var is_major = parseInt(is_minor);

    // Note: On IE, start of appVersion returns 3 or 4
    // which supposedly is the version of Netscape it is compatible with.
    // So we look for the real version further on in the string.

    var iePos  = appVer.indexOf('msie');
    if (iePos !=-1) {
       is_minor = parseFloat(appVer.substring(iePos+5,appVer.indexOf(';',iePos)))
       is_major = parseInt(is_minor);
    }

    var is_gecko = ((navigator.product)&&(navigator.product.toLowerCase()=="gecko"))?true:false;
    var is_gver  = 0;
    if (is_gecko) is_gver=navigator.productSub;

    var is_moz   = ((agt.indexOf('mozilla/5')!=-1) && (agt.indexOf('spoofer')==-1) &&
                    (agt.indexOf('compatible')==-1) && (agt.indexOf('opera')==-1)  &&
                    (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1)     &&
                    (is_gecko) && 
                    ((navigator.vendor=="")||(navigator.vendor=="Mozilla")));
    if (is_moz) {
       var is_moz_ver = (navigator.vendorSub)?navigator.vendorSub:0;
       if(!(is_moz_ver)) {
           is_moz_ver = agt.indexOf('rv:');
           is_moz_ver = agt.substring(is_moz_ver+3);
           is_paren   = is_moz_ver.indexOf(')');
           is_moz_ver = is_moz_ver.substring(0,is_paren);
       }
       is_minor = is_moz_ver;
       is_major = parseInt(is_moz_ver);
    }

    var is_nav  = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
                && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)
                && (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1)
                && (!(is_moz)));
				
    // Netscape6 is mozilla/5 + Netscape6
    // Mozilla/5.0 (Windows; U; Win98; en-US; m18) Gecko/20001108 Netscape6/6.0
    // Changed this to use navigator.vendor/vendorSub - dmr 060502   
    // var nav6Pos = agt.indexOf('netscape6');
    // if (nav6Pos !=-1) {
    if ((navigator.vendor)&&
        ((navigator.vendor=="Netscape6")||(navigator.vendor=="Netscape"))&&
        (is_nav)) {
       is_major = parseInt(navigator.vendorSub);
       // here we need is_minor as a valid float for testing. We'll
       // revert to the actual content before printing the result. 
       is_minor = parseFloat(navigator.vendorSub);
    }

	var is_opera = (agt.indexOf("opera") != -1);
    /*var is_opera2 = (agt.indexOf("opera 2") != -1 || agt.indexOf("opera/2") != -1);
    var is_opera3 = (agt.indexOf("opera 3") != -1 || agt.indexOf("opera/3") != -1);
    var is_opera4 = (agt.indexOf("opera 4") != -1 || agt.indexOf("opera/4") != -1);
    var is_opera5 = (agt.indexOf("opera 5") != -1 || agt.indexOf("opera/5") != -1);
    var is_opera6 = (agt.indexOf("opera 6") != -1 || agt.indexOf("opera/6") != -1); 
    var is_opera5up = (is_opera && !is_opera2 && !is_opera3 && !is_opera4);
    var is_opera6up = (is_opera && !is_opera2 && !is_opera3 && !is_opera4 && !is_opera5); */

    var is_nav2 = (is_nav && (is_major == 2));
    var is_nav3 = (is_nav && (is_major == 3));
    /*
	var is_nav4 = (is_nav && (is_major == 4));
    var is_nav4up = (is_nav && is_minor >= 4);  
                                                
    var is_navonly      = (is_nav && ((agt.indexOf(";nav") != -1) ||
                          (agt.indexOf("; nav") != -1)) );

    var is_nav6   = (is_nav && is_major==6);    
    var is_nav6up = (is_nav && is_minor >= 6) 

    var is_nav5   = (is_nav && is_major == 5 && !is_nav6); // checked for ns6
    var is_nav5up = (is_nav && is_minor >= 5);

    var is_nav7   = (is_nav && is_major == 7);
    var is_nav7up = (is_nav && is_minor >= 7);
*/
    var is_ie   = ((iePos!=-1) && (!is_opera));
	var is_ie2	= (is_ie && (is_major < 3));
    var is_ie3  = (is_ie && (is_major < 4));
/*
    var is_ie4   = (is_ie && is_major == 4);
    var is_ie4up = (is_ie && is_minor >= 4);
    var is_ie5   = (is_ie && is_major == 5);
    var is_ie5up = (is_ie && is_minor >= 5);
    
    var is_ie5_5  = (is_ie && (agt.indexOf("msie 5.5") !=-1)); 
    var is_ie5_5up =(is_ie && is_minor >= 5.5);                
	
    var is_ie6   = (is_ie && is_major == 6);
    var is_ie6up = (is_ie && is_minor >= 6);
	
	*/
	// For future browser compatibility, returns true unless we know it's an old browser
	// (Only Netscape 2, Netscape 3, and IE 2 are bad)
	return ( is_nav2 || is_nav3 || is_ie2 ) ? "false" : "true";
		
 } // browserOK
 
 


