  var landscape = true;
  var coursesCookie;
  var settingsCookie;
  var lastId = 0;
  var studentOpened = null;
  var currentCourse = null;
  
  function Course(data) {
    this.id = null;
    this.title = "Class";
    this.goal = 0;
    this.method = $("MethodSelect").options[0].value;
    this.goalType = $("GoalSelect").options[0].value;

    if (data) {
      this.title = data.title;
      this.goal = data.goal;
      this.method = data.method;
      this.goalType = data.goalType;
    }    
  }
  
  function Student(data) {
    this.id = null;
    this.title = "Student";
    this.data = "";
    
    if (data) {
      this.title = data.title;
      this.data = data.data;
    }
    
    this.getData = function() {
      var text = this.data.replace(/\,/g, " ");
      var search = /(\S+\s+)/g;
      var split = text.split(" ");//search.exec(text);
      numbers = [];
      for ( var i = 0; i < split.length; i++) {
        if (split[i].length == 0 || split[i] == " ") {
          continue;
        }  
        var number = parseFloat(split[i]);
        if (!isNaN(number)) {
          numbers.push(number);
        }
      }
      return numbers;
    }  
    
    this.getAverage = function() {
      var numbers = this.getData();
      var sum = 0;
      for ( var i = 0; i < numbers.length; i++) {
        sum += numbers[i];
      }
      if (numbers.length > 0) {
        return sum / numbers.length;
      }
      return 0;
    }
    
    this.getSum = function() {
      var numbers = this.getData();
      var sum = 0;
      for ( var i = 0; i < numbers.length; i++) {
        sum += numbers[i];
      }
      return sum;
    }  

    this.getCount = function() {
      var numbers = this.getData();
      return numbers.length;
    }  
  }
	    
  function setup() {
    landscape = window.innerWidth < window.innerHeight;    
    setTimeout(function() {window.scrollTo(0,1)}, 1);
    $("Loading").style.visibility = "hidden";
    $("List1").innerHTML = "";
    coursesCookie = new Cookie("TeacherCourses");
    if (coursesCookie.get()) {
      var data = eval(coursesCookie.get());
      for (var i = 0; i < data.length; i++) {
      	var id = data[i];
      	if (!id) {
      	  continue;
      	}  
      	if (lastId < id) {
      	  lastId = id;
      	}
        addCourse(data[i]);
      }
      if (data.length == 0) {
        loadDefaults();
      }
    }
    else {
      loadDefaults();
    }
    saveCourses();
    settingsCookie = new Cookie("TeacherSettings");
    if (settingsCookie.get()) {
      try {
        var settings = eval("new Object({" + settingsCookie.get() + "})");
        //$("MethodSelect").value = settings.method;
        //$("GoalSelect").value = settings.goal;
      }
      catch (e) {
        alert(e);
      }  
    }
  }
  
  function loadDefaults() {
    var math = createCourse("Math 8a");
    createCourse("Physics 10b");
  }
  
  function loadStudents(course) {
    $("List2").innerHTML = "";
    studentsCookie = new Cookie("TeacherStudents" + course.id);
    if (studentsCookie.get()) {
      var data = eval(studentsCookie.get());
      for (var i = 0; i < data.length; i++) {
        var id = data[i];
        if (!id) {
          continue;
        }  
        if (lastId < id) {
          lastId = id;
        }
        addStudent(data[i], course);
      }
      if (data.length == 0) {
        loadStudentDefaults();
      }
    }
    else {
      loadStudentDefaults();
    }    
  }
  
  function loadStudentDefaults() {
    var student = createStudent("Student A", currentCourse);
  }
  
  function saveStudent(student) {
    var id = student.id;
    var isNew = !student.id;
    if (isNew) {
      lastId++;
      id = lastId;
      student.id = id;
    }
    var cookie = new Cookie("TeacherStudent" + id);
    var text = "title:'" + encode(student.title) + "'";
    text += ",data:'" + student.data + "'";
    text += ",courseId:" + student.courseId;
    cookie.store(text);
    return id;
  }
  
  function encode(text) {
    text = text.replace(/\n/g, "\\n");
    return text.replace(/\'/g, "\\'");
  }
  
  function addStudent(id, course) {  
    var list = $("List2");
    var li = document.createElement("li");
    li.id = "StudentEntry" + id;                    

    var cookie = new Cookie("TeacherStudent" + id);
    if (cookie.get()) {
      try {
        li.student = eval("new Student(new Object({" + cookie.get() + "}))");
        li.student.id = id;
        li.student.li = li;
        li.student.course = course;
        li.cookie = cookie;
        saveStudent(li.student);
      }
      catch (e) {
        alert(e + " " + cookie.get());
        return;
      }  
    }  
    else {
      return;
    }
    
    list.appendChild(li);
    
    var template = $("StudentTemplate").innerHTML;
    template = template.replace(/\$ID/g, id);
    li.innerHTML = template;
    
    $("StudentTitle" + id).innerHTML = li.student.title + "&nbsp;";
    $("StudentDataEdit" + id).value = li.student.data;
    $("StudentDataName" + id).innerHTML = li.student.title;
    updateStudent(li.student);

    li.studentId = id;
    saveStudents();
  }
  
  function openStudent(student) {
    if (studentOpened == student) {
      closeStudent(studentOpened);
      return;
    }  
    if (studentOpened != null) {
      closeStudent(studentOpened);
    }  
    studentOpened = student;
    $("StudentData" + student.id).style.display = "block";
    window.open("#StudentEntry" + student.id,  "_self");
  }
  
  function closeStudent(student) {
    $("StudentData" + student.id).style.display = "none";
    afterStudentEdit(student);
    window.scrollTo(0,1);                    
  }  

  function afterStudentEdit(student) {  
    student.data = $("StudentDataEdit" + student.id).value;
    saveStudent(student);
    updateStudent(student);
    studentOpened = null;
  }
  
  function updateStudent(student) {
    var goal = currentCourse.goal;
    if (currentCourse.method == "average") {
      student.value = student.getAverage();
      if (student.value == 0) {
        $("StudentValue" + student.id).innerHTML = "-.-";        
      }  
      else {
        $("StudentValue" + student.id).innerHTML = student.value.toFixed(1);
      }
      goal = goal.toFixed(1);
    }
    else {
      student.value = student.getSum();
      $("StudentValue" + student.id).innerHTML = parseInt(student.value);
    }
    $("StudentValue" + student.id).innerHTML = "<b>" + $("StudentValue" + student.id).innerHTML + "</b>";
    $("StudentValue" + student.id).innerHTML = $("StudentValue" + student.id).innerHTML + " (<i>" + student.getCount() + "</i>)";
    if (currentCourse.goalType == "below") {
      student.isGoal = student.value <= goal;
    }
    else {
      student.isGoal = student.value >= goal;
    }
    if (student.isGoal || goal == 0) {
      $("StudentHeader" + student.id).className = "listEntry";
    }
    else {
      $("StudentHeader" + student.id).className = "listEntry listEntryNoGoal";
    }
  }
  
  function reCalc() {
    var goal = parseFloat($("GoalInput").value);
    if (isNaN(goal) || goal < 0) {
      goal = 0;
    }
    currentCourse.goal = goal;
    currentCourse.method = $("MethodSelect").value;
    currentCourse.goalType = $("GoalSelect").value;
    saveCourse(currentCourse);
    var list = $("List2");
    var lis = list.childNodes;
    for (var i = 0; i < lis.length; i++) {
      updateStudent(lis[i].student);
    }
    saveSettings();
  }
  
  function removeStudent(student) {
    var li = student.li;
    if (confirm("Do you really want to remove " + student.title + "?")) {
      li.cookie.remove();
      li.parentNode.removeChild(li);
      saveStudents();
    }
  }
  
  function newStudent() {
    createStudent($("NewInput2").value, currentCourse);
    $("NewInput2").value = "";                    
  }
  
  function createStudent(title, course) {
    student = new Student();
    student.title = title;
    student.courseId = course.id;
    saveStudent(student);
    addStudent(student.id, course);
    return student;
  }
  
  function saveStudents() {
    var data = "[";
    var list = $("List2");
    var lis = list.childNodes;
    for (var i = 0; i < lis.length; i++) {
    	if (i > 0) {
    	  data += ',';
    	} 
    	data += lis[i].studentId;
    }
    data += "]";
    studentsCookie.store(data);
  }
  
  function saveCourse(course) {
    var id = course.id;
    var isNew = !course.id;
    if (isNew) {
      lastId++;
      id = lastId;
      course.id = id;
    }
    var cookie = new Cookie("TeacherCourse" + id);
    var text = "title:'" + encode(course.title) + "'";
    text += ",goal:" + course.goal;
    text += ",method:'" + course.method + "'";
    text += ",goalType:'" + course.goalType + "'";
    cookie.store(text);
    return id;
  }
  
  function addCourse(id) {  
    var list = $("List1");
    var li = document.createElement("li");
    li.id = "CourseEntry" + id;                    

    var cookie = new Cookie("TeacherCourse" + id);
    if (cookie.get()) {
      try {
        li.course = eval("new Course(new Object({" + cookie.get() + "}))");
        li.course.id = id;
        li.course.li = li;
        li.cookie = cookie;
        saveCourse(li.course);
      }
      catch (e) {
        alert(e + " " + cookie.get());
        return;
      }  
    }  
    else {
      return;
    }
    
    list.appendChild(li);
    
    var template = $("CourseTemplate").innerHTML;
    template = template.replace(/\$ID/g, id);
    li.innerHTML = template;
    
    $("CourseTitle" + id).innerHTML = li.course.title + "&nbsp;";

    li.courseId = id;
    saveCourses();
  }
  
  function openCourse(course) {
    currentCourse = course;
    $("GoalInput").value = course.goal;
    $("MethodSelect").value = course.method;
    $("GoalSelect").value = course.goalType;
    loadStudents(course);
    reCalc();
    $("CourseTitle").innerHTML = course.title;
    $("StudentSection").style.display = "block";
    $("Content").style.display = "none";
    window.scrollTo(0, 0);
  }
  
  function closeCourse() {
    $("StudentSection").style.display = "none";
    $("Content").style.display = "block";    
    window.scrollTo(0, 0);
  }
  
  function removeCourse(course) {
    var li = course.li;
    if (confirm("Do you really want to remove " + course.title + "?")) {
      li.cookie.remove();
      li.parentNode.removeChild(li);
      saveCourses();
    }
  }
  
  function newCourse() {
    createCourse($("NewInput1").value);
    $("NewInput1").value = "";                    
  }
  
  function createCourse(title) {
    course = new Course();
    course.title = title;
    saveCourse(course);
    addCourse(course.id);
    return course;
  }
  
  function saveCourses() {
    var data = "[";
    var list = $("List1");
    var lis = list.childNodes;
    for (var i = 0; i < lis.length; i++) {
      if (i > 0) {
        data += ',';
      } 
      data += lis[i].courseId;
    }
    data += "]";
    coursesCookie.store(data);
  }
  
  function saveSettings() {
    var text = "";
    /*
    text += "method:'" + $("MethodSelect").value + "'";
    text += ",goal:'" + $("GoalSelect").value + "'";
    */
    settingsCookie.store(text);
  }
  
  function emailAll() {
    var body = "";
    var list = $("List1");
    var lis = list.childNodes;
    for (var i = 0; i < lis.length; i++) {
      var course = lis[i].course;
      body += course.title + ":<br>";
      var cookie = new Cookie("TeacherStudents" + course.id);
      if (cookie.get()) {
        var data = eval(cookie.get());
        for (var j = 0; j < data.length; j++) {
          var id = data[j];
          if (!id) {
            continue;
          }  
          var cookie2 = new Cookie("TeacherStudent" + id);
          if (cookie2.get()) {
            try {
              var student = eval("new Student(new Object({" + cookie2.get() + "}))");
              body += "&nbsp;&nbsp;" + student.title + ": " + student.data;
              body += " (sum:" + student.getSum() + ", average:" 
                      + student.getAverage().toFixed(1) + ")<br>";
            }
            catch (e) {
              alert(e + " " + cookie2.get());
              return;
            }  
          }  
        }
      }
      body += "<br>";
    }
    //alert(body);
    window.open("mailto:?subject=Grade Book Data&body=" + encodeURIComponent(body), "_self");  
  }

  function tellFriend() {
    var body = "Hi,<br><br>I just stumbled upon this Grade Book iPhone application:" +
        "<br><br>http://www.itunes.com/app/gradebook<br><br>" +
        "Keep and manage the marks and credits of your classes. See either the " +
        "average mark or the sum of the credits per student." +
        "<br><br>Best regards";
    window.open("mailto:?subject=Grade Book on the iPhone&body=" + body, "_self");  
  }

	function orientationChanged() {
    landscape = window.innerWidth < window.innerHeight;
    pause();
    window.scrollTo(0,1);
    updateControlsPosition();
  }
	
  function debug(msg) {
    var e = document.getElementById("Debug");
    e.innerHTML += msg + "<br>";
  }
  
  function $(id) {
    return document.getElementById(id);
  }