var http_request;
var courseid;
var ie6;
var ie7;

function showHideDiv(control) {

  c = getCookie('hideDiv');

  if ((c == null) || (c.replace(/^\s+|\s+$/, '') == '')) {
    ca = new Array();
  } else {
    ca = c.split(' ');
  }

  d = document.getElementsByTagName('div');

  if (control.checked) {
    for (i = 0; i < ca.length; i ++) {
      if (ca[i] == control.id) {
        ca.splice(i, 1);
        break;
      }
    }
  } else {
    inarray = false;
    for (i = 0; i < ca.length; i ++) {
      if (ca[i] == control.id) {
        inarray = true;
        break;
      }
    }
    if (!inarray) {
      ca.push(control.id);
    }
  }

  c = ca.join(' ');
  setCookie('hideDiv', c);

  for (i = 0; i < d.length; i ++){
    classNames = d[i].className.split(' ');
    for (j = 0; j < classNames.length; j ++) {
      if (classNames[j] == control.id) {

        if (control.checked) {
          d[i].style.display = 'block';
        } else {
          d[i].style.display = 'none';
        }
      }
    }
  }
}

function setCookie(name, value) {

	var date = new Date();
	date.setYear(date.getFullYear() + 1);

  var expires = "; expires=" + date.toGMTString();

	document.cookie = name + "=" + value + expires + "; path=/";
}

function getCookie(name) {
	var nameEQ = name + "=";

	ca = document.cookie.split(';');

	for(i = 0; i < ca.length; i++) {
		c = ca[i];

		while (c.charAt(0) == ' ') {
		  c = c.substring(1,c.length);
		}
		if (c.indexOf(nameEQ) == 0) {
		  return c.substring(nameEQ.length,c.length);
		}
	}
	return null;
}

function keyTitles() {

  d = document.getElementsByTagName('div');

  for (i = 0; i < d.length; i ++){
    classNames = d[i].className.split(' ');
    for (j = 0; j < classNames.length; j ++) {
      switch (classNames[j]) {
        case 'c_past':
          d[i].title = 'Course in the past';
        break;
        case 'c_failed':
          d[i].title = 'Course you attended and failed';
        break;
        case 'c_passed':
          d[i].title = 'Course you attended and passed';
        break;
        case 'c_qualif':
          d[i].title = 'Course in the future you are able to attend';
        break;
        case 'c_future':
          d[i].title = 'Course in the future you lack qualifications for';
        break;
        case 'c_attending':
          d[i].title = 'Course you are currently signed up to';
        break;
        case 'c_exped':
          d[i].title = 'Exped';
        break;
        case 'c_expeda':
          d[i].title = 'Exped you are signed up to';
        break;
      }
    }
  }
}

String.prototype.trim = function () {
  return this.replace(/^\s+|\s+$/, '');
}

var attendeeState;

function showAttendees(e, cid, state)
{


  courseid = cid;
  attendeeState = state;

  attendeeView();

  evt = e || window.event;

  windowOC(evt, document.getElementById('attendee'));
}

function cleanupUpload()
{
  if (document.getElementById('attendee')) {
    document.getElementById('a_u_d').style.display = 'none';
    document.getElementById('a_u_s').innerHTML = '';

    document.getElementById('a_upload_f').value = '';

    request = ajaxRequest();
    request.open('POST', 'results.php?do=4', true);
    request.setRequestHeader("Connection", "close");
    request.send(null);
  }
}

function ajaxRequest()
{
  var request = false;
  try {
    request = new XMLHttpRequest();

    //if (request.overrideMimeType) {
     // request.overrideMimeType('text/javascript');
    //}
  } catch (e1) {
    try {
      request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e2) {
      try {
        request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e3) {
        alert("AJAX does not work.");
      }
    }
  }
  return request;
}

function attendeeResultsSubmit()
{
  if (document.getElementById('a_upload_f').value != '') {
    if (!confirm('You have a file selected for upload but you have yet to actually upload it.  If you would like to upload it please hit cancel and do so before you save the results, otherwise hit ok to continue without uploading an attachment.')) {
      return;
    }
  }
  http_request = ajaxRequest();

  inputs = document.getElementById('a_s').getElementsByTagName('input');

  returnarg = 'do=2&courseid=' + courseid;

  for (i = 0; i < inputs.length; i ++) {
    if (inputs[i].type == 'checkbox') {
      if (inputs[i].checked) {
        returnarg = returnarg + '&' + inputs[i].name + '=1';
      }
    }
  }


  http_request.open('POST', 'results.php', false);
  http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  http_request.setRequestHeader("Content-length", returnarg.length);
  http_request.setRequestHeader("Connection", "close");
  http_request.send(returnarg);

  document.getElementById('a_upload').style.display = 'none';
  document.getElementById('a_u_d').style.display = 'none';

  attendeeView();
}

function attendeeView()
{
  windowLoading();

  http_request = ajaxRequest();

  http_request.onreadystatechange = function() { attendeeViewProcess(http_request); };
  http_request.open('POST', 'results.php?do=1&courseid=' + courseid, true);
  http_request.setRequestHeader("Connection", "close");
  http_request.send(null);

}

function attendeeUploadRemove()
{
  cleanupUpload();
  document.getElementById('a_u_d').style.display = 'none';
}

function attendeeUpload()
{
  document.getElementById('a_upload').submit();
  windowLoading();
  attendeeUploadDiv();
  document.getElementById('a_upload_f').value = '';
}

function attendeeUploadDiv()
{
  upload_name = getCookie('upload_name');

  if (upload_name != null) {
    windowLoading();
    document.getElementById('a_u_d').style.display = 'block';
    document.getElementById('a_u_s').innerHTML = upload_name;
  } else {
    window.setTimeout('attendeeUploadDiv();', 500);
  }

}

function attendeeViewProcess(http_request)
{
  //try {
    if (http_request.readyState == 4) {
      if (http_request.status == 200) {
        eval(http_request.responseText);

        windowLoading();

        if (!result) {

          if (!permitted) {
            alert('Sorry, you are not permitted to view this.');
          } else {
            alert('Sorry, there has been an error.');
          }
          windowOC();
          return;
        }

        try {

        if ((attendeeState == 2)) {
          document.getElementById('attendee_help_2').style.display = 'block';
        } else {
          document.getElementById('attendee_help_2').style.display = 'none';
        }

        if ((attendeeState == 1) && !exped && !evt) {
          document.getElementById('attendee_help_1').style.display = 'block';
        } else {
          document.getElementById('attendee_help_1').style.display = 'none';
        }

        } catch (e) {
        }

        if (exped || evt) {
          populateAttendeeOther(document.getElementById("a_s"), 's', 'Attendees');
        } else {
          populateAttendeeStudents(document.getElementById("a_s"));
        }

        populateAttendeeOther(document.getElementById("a_sr"), 'sr', 'Reserve Students');
        populateAttendeeOther(document.getElementById("a_i"), 'i', 'Instructors');
        populateAttendeeOther(document.getElementById("a_ir"), 'ir', 'Reserve Instructors');

        document.getElementById('course_name').innerHTML = course;

        //attendeeUploadDisplay();
      }
    }
  //} catch(e) {
//    alert('Sorry, there has been an unknown error - ' + e.description);
//  }
}

function removeAllChildren(element)
{
  while (element.lastChild) {
    element.removeChild(element.lastChild);
  }
}

function populateAttendeeStudents(s)
{
  removeAllChildren(s);

  if (sSid.length > 0) {

    s.createCaption().innerHTML = 'Students';

    for (i = 0; i < sSid.length; i ++) {
      row = s.insertRow(-1);

      cell = row.insertCell(-1);

      if (ie6 != undefined) { // fix IE's support of :first-child
        cell.className = 'f';
      }

      if (attendeeState == 2) {
        cell.innerHTML = '<span title="Click to remove user from course" class="click" onclick="attendeeRemove(' + sSid[i] + ')">' + sNames[i] + '</span>';
      } else {
        cell.innerHTML = sNames[i];
      }

      if (attendeeState != 2) {

        for (j = 0; j < qualifName.length; j ++) {
          cell = row.insertCell(-1);
          if (attendeeState == 1) {
            cell.innerHTML = '<input type="checkbox" name="result[' + sSid[i] + '][' + qualifId[j] + ']" />';
          } else {
            cell.innerHTML = 'Fail';

            for (k = 0; k < sResult[i].length; k ++) {
              if (sResult[i][k] == qualifId[j]) {
                cell.innerHTML = 'Pass';
              }
            }
          }
        }
      }
    }

    if (attendeeState != 2) {

      head = s.createTHead();
      row = head.insertRow(-1);
      cell = row.insertCell(-1);
      cell.innerHTML = 'Name';

      for (i = 0; i < qualifName.length; i ++) {
        cell = row.insertCell(-1);
        cell.innerHTML = qualifName[i];
      }
    }

    s.style.display = 'block';
  }
}

function populateAttendeeOther(table, what, caption)
{
  while (table.lastChild) {
    table.removeChild(table.lastChild);
  }
  if (eval(what + 'Sid.length') > 0) {

    table.createCaption().innerHTML = caption;

    for (i = 0; i < eval(what + 'Sid.length'); i ++) {
      row = table.insertRow(-1);

      cell = row.insertCell(-1);

      if (ie6 != undefined) { // fix IE's support of :first-child
        cell.className = 'f';
      }

      if (attendeeState == 2) {
        cell.innerHTML = '<span title="Click to remove user from course" class="click" onclick="attendeeRemove(' + eval(what + 'Sid[' + i + ']') + ')">' + eval(what + 'Names[' + i + ']') + '</span>';
      } else {
        cell.innerHTML = eval(what + 'Names[' + i + ']');
      }
    }

    table.style.display = 'block';
  }
}

function attendeeRemove(sid)
{
  if (!confirm("Are you sure you wish to remove this person from the course?")) {
    return false;
  }
  windowLoading();

  http_request = ajaxRequest();

  http_request.onreadystatechange = function() { attendeeRemoveProcess(http_request); };
  http_request.open('POST', 'results.php?do=6&signupid=' + sid, true);
  http_request.setRequestHeader("Connection", "close");
  http_request.send(null);
}

function attendeeRemoveProcess(http_request)
{
  try {
    if (http_request.readyState == 4) {
      if (http_request.status == 200) {
        eval(http_request.responseText);

        if (divClass == null) {
          return;
        }

        if (loggedIn) {
          changeCourseDiv(courseid, divClass, admin, registered, instructor, exped, studentFull, instructorFull, qualified, qualifiedInstructor, reserve);
        }

        windowLoading();
        if (instructor || admin) {
          attendeeView();
        } else {
          windowOC();
        }
      }
    }
  } catch(e) {
    alert('Sorry, an error has occured - ' + e.description);
  }
}

function attendeeAdd(e, cid)
{
  document.getElementById('a_add_cid').value = cid;
  document.getElementById('a_add_n').value = '';

  evt = e || window.event;
  windowOC(evt, document.getElementById('attendee_add'));
  document.getElementById('a_add_n').focus();
}

function attendeeAddSubmit()
{
  windowLoading();

  http_request = ajaxRequest();

  if (document.getElementById('a_add_s').checked) {
    returnarg = 'do=5&courseid=' + document.getElementById('a_add_cid').value + '&username=' + document.getElementById('a_add_n').value;
  } else {
    returnarg = 'do=5&instructor=1&courseid=' + document.getElementById('a_add_cid').value + '&username=' + document.getElementById('a_add_n').value;
  }

  http_request.onreadystatechange = function() { attendeeAddProcess(http_request); };
  http_request.open('POST', 'results.php', true);
  http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  http_request.setRequestHeader("Content-length", returnarg.length);
  http_request.setRequestHeader("Connection", "close");
  http_request.send(returnarg);

}

function attendeeAddProcess(http_request)
{
  try {
    if (http_request.readyState == 4) {
      if (http_request.status == 200) {
        eval(http_request.responseText);

        windowLoading();

        if (result == 'success') {
          windowOC();

          if (loggedIn) {
            changeCourseDiv(document.getElementById('a_add_cid').value, divClass, admin, registered, instructor, exped, studentFull, instructorFull, qualified, qualifiedInstructor, reserve);
          }

          document.getElementById('a_add_n').value = '';
          document.getElementById('a_add_cid').value = '';
          alert('Thank you, the user has now been registered on the course.');
        } else if (result == 'instructor') {
          windowOC();
          document.getElementById('a_add_n').value = '';
          document.getElementById('a_add_cid').value = '';
          alert('The user you have entered is already added as an instructor.');
        } else {
          alert('Sorry, the username you entered cannot be found, please check and try again.');
          document.getElementById('a_add_n').select();
        }
      }
    }
  } catch(e) {
    alert('Sorry, an error has occured - ' + e.description);
  }
}

function courseSignup(e, cid, instructor)
{
  evt = e || window.event;

  windowLoading();

  http_request = ajaxRequest();
  http_request.onreadystatechange = function() { courseSignupProcess(http_request, cid, evt); };

  if (instructor) {
    http_request.open('POST', 'signup.php?instructor=1&courseid=' + cid, true);
  } else {
    http_request.open('POST', 'signup.php?courseid=' + cid, true);
  }

  http_request.setRequestHeader("Connection", "close");
  http_request.send(null);
}

function courseSignupProcess(http_request, cid, evt)
{
  try {
    if (http_request.readyState == 4) {
      if (http_request.status == 200) {
        eval(http_request.responseText);

        windowLoading();

        switch(signupResult) {
          case 'success':
          changeCourseDiv(cid, divClass, admin, registered, instructor, exped, studentFull, instructorFull, qualified, qualifiedInstructor, reserve);
          break;

          case 'reserve':
          changeCourseDiv(cid, divClass, admin, registered, instructor, exped, studentFull, instructorFull, qualified, qualifiedInstructor, reserve);
          alert('Thank you, you are now signed up, however, you have been placed on the reserve list since the course is full.  You will be emailed if a space bcomes available for you.');
          break;

          case 'login':
          alert('Sorry, you must be logged in to sign up or deregister from courses.');
          break;

          case 'started':
          alert('Sorry, the course has already started so you cannot sign up or deregister from it.');
          break;

          case 'prerequisites':
          alert('Sorry, you do not have the required prerequisites to sign up for this course.');
          break;

          case 'deregister':
          document.getElementById('deregister_cid').value = cid;
          windowOC(evt, document.getElementById('deregister'));
          break;

          default:
          alert('Sorry, an unkown error has occured, please contact the administrator.');
        }
      }
    }
  } catch(e) {
    alert('Sorry, an error has occured - ' + e.description);
  }
}

function courseDeregister()
{
  windowLoading();

  http_request = ajaxRequest();

  returnarg = 'do=7&courseid=' + document.getElementById('deregister_cid').value + '&message=' + document.getElementById('message').value;

  http_request.onreadystatechange = function() { courseDeregisterProcess(http_request); };
  http_request.open('POST', 'results.php', true);
  http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  http_request.setRequestHeader("Content-length", returnarg.length);
  http_request.setRequestHeader("Connection", "close");
  http_request.send(returnarg);
}

function courseDeregisterProcess(http_request)
{
  try {
    if (http_request.readyState == 4) {
      if (http_request.status == 200) {

        windowLoading();
        document.getElementById('deregister_cid').value = '';
        windowOC();
        alert('Thank you, your message has now been sent to the adminministrator and they will deal with it as soon as possible.');
      }
    }
  } catch(e) {
    alert('Sorry, an error has occured - ' + e.description);
  }
}

function changeCourseDiv(cid, newClass, admin, registered, instructor, exped, studentFull, instructorFull, qualified, qualifiedInstructor, reserve)
{
  d = document.getElementsByTagName('span');

  for (i = 0; i < d.length; i ++) {
    if (d[i].getAttribute('title') == 'cid') {
      if (d[i].innerHTML == cid) {
        d[i].parentNode.className = newClass;

        changeCourseLinks(d[i].parentNode.getElementsByTagName('div')[0].getElementsByTagName('ul')[0], admin, registered, instructor, exped, studentFull, instructorFull, qualified, qualifiedInstructor, reserve);
      }
    }
  }
  keyTitles();
}

function changeCourseLinks(ul, admin, registered, instructor, exped, studentFull, instructorFull, qualified, qualifiedInstructor, reserve)
{
  var i;

  for (i = 0; i < ul.childNodes.length; i ++) {

    if (ul.childNodes[i].className == 'click') {
      el = ul.childNodes[i];

      switch(el.innerHTML.replace(/\s$/, '')) { // IE smells and adds whitespace onto the end of innerHTML so must trim it off
        case 'Sign Up':
        case 'Deregister':
        case 'Sign Up To Reserve List':

          if (instructor) {
            el.style.display = 'none';
          } else {
            el.style.display = 'list-item';

            if (registered) {
              el.innerHTML = 'Deregister';
            } else {

              if (qualified || exped) {
                if (studentFull) {
                  el.innerHTML = 'Sign Up To Reserve List';
                } else {
                  el.innerHTML = 'Sign Up';
                }
              } else {
                el.style.display = 'none';
              }
            }
          }
        break;

        case 'Sign Up As Instructor':
        case 'Deregister As Instructor':
        case 'Sign Up As Reserve Instructor':

          if (instructor) {
            el.style.display = 'list-item';
            el.innerHTML = 'Deregister As Instructor';
          } else {
            if (qualifiedInstructor && !exped) {
              el.style.display = 'list-item';
              if (instructorFull) {
                el.innerHTML = 'Sign Up As Reserve Instructor';
              } else {
                el.innerHTML = 'Sign Up As Instructor';
              }
            } else {
              el.style.display = 'none';
            }
          }
        break;

        case 'View Attendees':
          if (!admin) {
            if (instructor && !reserve) {
              el.style.display = 'list-item';
            } else {
              el.style.display = 'none';
            }
          }
        break;
      }
    }
  }
}
function qualificationSubmit()
{
  windowLoading();

  http_request = ajaxRequest();

  q = document.getElementById('qids').options;

  returnarg = 'do=8';

  for (i = 0; i < q.length; i ++) {
    if (q[i].selected) {
      returnarg = returnarg + '&qualifs[' + q[i].value + ']=1';
    }
  }


  http_request.onreadystatechange = function() { qualificationSubmitProcess(http_request); };
  http_request.open('POST', 'results.php', true);
  http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  http_request.setRequestHeader("Content-length", returnarg.length);
  http_request.setRequestHeader("Connection", "close");
  http_request.send(returnarg);
}

function qualificationSubmitProcess(http_request)
{
  try {
    if (http_request.readyState == 4) {
      if (http_request.status == 200) {

        eval(http_request.responseText);
      //  alert(http_request.responseText);

        windowOC();
        windowLoading();

        switch(result) {
          case 'success':
            alert('Thank you, your qualifications have now been updated.');
            window.location.reload();
          break;
          case 'moderation':
            alert('Thank you, your qualifiactions have been submitted but require moderation from an administrator before the changes take effect.');
          break;

          default:
          alert('Sorry, the save has failed, please contact the administrator.');
        }
      }
    }
  } catch(e) {
    alert('Sorry, an error has occured - ' + e.description);
  }
}

