var student;
var studentString;

function mySlice(s, i, j)
{
 if(i < s.length && j <= s.length && i < j)
 {
  var newStr = "";
  for(n = i; n < j; n++)
   newStr += s.charAt(n);
  return newStr;
 }
 else return -1;
}

function getStudent()
{
 index = document.cookie.indexOf('student=');
 if (index == -1) return 0;
 else
 {
  var studentString = mySlice(document.cookie, index+"student='".length, document.cookie.indexOf("'", index+"student='".length));
  student = studentString.split(',');
  return 1;
 }
}

function buildStudent()
{
 studentString = "student='";
 studentString += student[0]
 for(i=1; i<student.length; i++)
  studentString += ',' + student[i];
 studentString += "';";
 var now = new Date();
 now.setTime(now.getTime() + 31 * 24 * 60 * 60 * 1000);
 document.cookie = studentString + " expires=" + now.toGMTString() + "; path=/";
}

function deleteStudent()
{
 if (document && document.cookie)
 {
  document.cookie = "student=; expires=Thu, 01-Jan-70 00:00:01 GMT; path=/";
 }
}

function renameStudent(newname)
{
 if (document && document.cookie)
 {
  getStudent();
  student[0] = newname;
  buildStudent();
 } 
}

function changeScore(quiznum, score)
{
 if (document && document.cookie)
 {
  getStudent();
  student[quiznum] = score;
  buildStudent();
 }
}

function getScore(quiznum)
{
 if (document && document.cookie)
 {
  getStudent();
  if (student.length < quiznum)
   return -2;
  else return student[quiznum];
 }
}

function computeAverage()
{
 if (getScore(1) != '-1' || getScore(2) != '-1' || getScore(3) != '-1' || getScore(4) != '-1')
 {
  tot = 0;
  valid = 0;
  if (getScore(1)!='-1') {tot+=parseInt(getScore(1)); valid++;}
  if (getScore(2)!='-1') {tot+=parseInt(getScore(2)); valid++;}
  if (getScore(3)!='-1') {tot+=parseInt(getScore(3)); valid++;}
  if (getScore(4)!='-1') {tot+=parseInt(getScore(4)); valid++;}
  return Math.round(tot/valid);
 }
 else return "";
}

function newStudent(name)
{
 var now = new Date();
 now.setTime(now.getTime() + 31 * 24 * 60 * 60 * 1000);
 document.cookie = "student='" + name + ",-1,-1,-1'; expires=" + now.toGMTString() + "; path=/";
}
