//
//  Written by:  Bill Dortch, hIdaho Design <bdortch@netw.com>
//  The following functions are released to the public domain.
//
//
// "Internal" function to 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));
}

//
//  Function to 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;
}

//
//  Function to 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 null as a place holder.  For example, to call SetCookie using name,
//  value and path, you would code:
//
//	SetCookie ("myCookieName", "myCookieValue", null, "/");
//
//  Note that trailing omitted parameters do not require a placeholder.
//
//  To set a secure cookie for path "/myPath", that expires after the
//  current session, you might code:
//
//	SetCookie (myCookieVar, cookieValueVar, null, "/myPath", null, true);
//
function SetCookie (name, value) {
  var argv = SetCookie.arguments;
  var argc = SetCookie.arguments.length;
  var expires = (argc > 2) ? argv[2] : null;
  var path = (argc > 3) ? argv[3] : null;
  var domain = (argc > 4) ? argv[4] : null;
  var secure = (argc > 5) ? argv[5] : false;

  document.cookie = name + "=" + escape(value) +
    ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
    ((path == null) ? "" : ("; path=" + path)) +
    ((domain == null) ? "" : ("; domain=" + domain)) +
    ((secure == true) ? "; secure" : "");
}

//  Function to delete a cookie. (Sets expiration date to current date/time)
//    name - String object containing the cookie name
//
function DeleteCookie (name) {
  var exp = new Date();
  exp.setTime (exp.getTime() - 1);  // This cookie is history
  var cval = GetCookie (name);
  document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}

//  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));
}

//  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>");
}

//  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);
}

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

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

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

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

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

//  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) {
  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;
}

//  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) {
  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 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;
}

//  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, null, "/", "XXX.XXX.XXX");
}

//  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);
  }
}


