/* reg_script.js javascript suport for reg.php
   Copyright (C) 2009 - 2011  Jeffrey Hennick, o l r e g @ j e f f - h . c o m
   Part of Registration / Administation System. GLP License in ../copyleft.php.
*/
// 12/29/09 Separated out of reg.php.  Jeff Hennick
// 1/3/10 Added close_intro. Comments. Formated for short lines per Ed. JH
// 1/6/10 Use scrollIntoView per Penney's idea. JH
// 1/8/10 clear help prior to verification. JH
// 1/12/10 Separated API and Helper functions; ajaxSubmitForm() was get(). JH
// 1/15/10 focus() to first name. JH
// 1/16/10 added erase to showall(erase). JH
// 2/5/10 Added alert boxes for Levels 1 - 3. JH
// 2/11/10 Added changed_initials(). JH
// 2/19/10 Added skip non numerics if figuring level; added level 0. JH
// 4/10/10 Adding Sections support. JH
// 4/17/10 Added beforeunloading(). JH
// 5/13/10 get_ipa: forms[0] was theform. JH
// 7/16/10 ie workaround for getElementsByName. JH
// 7/23/10 Added term to getPrior.  JH
// 7/25/10 Relaxed email TDN, improved messages. JH
// 8/ 6/10 Fixed changed_initials() so not +=. JH
// 8/22/10 Added async_inc; simplified getPrior. JH
// 9/ 2/10 Added no_typist_init, roundup_mode JH
// 12/18/10 Added reset time to showall, per Russ. JH
//  1/22/11 Lab Assistant was Proctor. JH
//  1/23/11 Fixed for no check boxes on closed sections. JH
//  1/23/11 Added get_transcript to getPrior. JH
//  4/ 1/11 Confirm Roundup; no popup in roundup_mode. JH
//  4/ 6/11 Add digits2 to month. JH
//  4/ 9/11 Add scrolling to movetodone. JH
//  4/17/11 Some "+=" to "+". JH
//  4/25/11 Fixed oops from above. JH
// 11/26/11 Special test of prerequist in CC215. JH
// 11/30/11 Commented out special test. JH

var ipa_val = 'n';   // Instuctor, Lab Assistant, Assistant, or None
// Next two are for checking for prior registration
var namechange = 0;  // Has the name field changed?
var aptchange = 0;   // Has the address field changed?
var phase = 1;       // Fill in; Verify; Send?
var ignore_email = 0; // Option to not test an email address
var no_typist_init = 1; // If typist initials, skip the warning alerts
var roundup_mode = 0; // If 1 clears it all at the end

///////////////  API Functions //////////////////////

function close_intro() { // Actually, hides the introduction overlay
 document.getElementById('intro').style.display = 'none';
 document.getElementById('inner_intro').style.display = 'none';
 // put the cursor in the first name input box
 document.forms[0].Ecom_ShipTo_Postal_Name_First.focus();
}

function jha_alert(txt) { // Special test box
  txt += "<br><br>"
      + "<input type='button' onclick='clear_prq(1)' value=' OK '> &nbsp; "
      + "<input type='button' onclick='clear_prq(2)' value = ' Cancel '>";
 document.getElementById('inner_prq').innerHTML = txt;
 document.getElementById('prq').style.display = 'block';
 document.getElementById('inner_prq').style.display = 'block';
}

function clear_prq(t) {  // Special test end
 document.getElementById('prq').style.display = 'none';
 document.getElementById('inner_prq').style.display = 'none';
 if (t == 1) {
  var o = '';
  for (var i = 0; ; i++) {
   var c = document.getElementById('prqc[' + i + ']');
   if (typeof(c) == 'undefined' || c == null) break;
   o += (c.checked) ? 'Y ' : 'N ';
   o += document.getElementById('prq[' + i + ']').innerHTML + "\n";
  }
//  alert(o); // would add this info to the application
 }
}

function update_tot(obj) {  // Recalcs the total $
 var tot = 0;
 get_ipa(0);
 if (ipa_val == 'n')     // Only non-IPAs are charged
  for (var i = 0; ;i++) {
   if (! document.getElementById('r' + i)) break;   // End
   if (! document.getElementById('i' + i)) continue;   // No check box
   if (! document.getElementById('d' + i)) continue; // No charge
   if (document.getElementById('i' + i).checked) {  // Only what ones checked
     var cost = document.getElementById('d' + i).innerHTML;
     if (cost.substr(0,1) == '$') cost = cost.substr(1); // Strip
     tot += parseFloat(cost);
   }
  }
 else tot = 0;                      // IPA
 document.getElementById('tot').innerHTML = '$' + roundCents(tot) + ' &nbsp;';

 // Give an alert message re: prerequisties based on course level
 // Only if the box is checked -- don't do it if unchecked
 if (obj && no_typist_init && obj.checked && !roundup_mode) { // called by checkbox onchange
  var prq = "\n\nBe sure you have the prerequisites "
            + "to be able to get value from this course."

  // We need the first numeric to get the level of the course
  // so we can give an alert message about the prerequisites
  var course_num = obj.value;
  for (var i = 0; i < course_num.length; i++) {
   // Get each character in order
   var char = course_num.charAt(i);
   // If it is a digit, leave the loop
   if (!((char < '0') || (char > '9'))) break;
  }
  // We have the first digit, now use it
  switch (char) {
   case '0':
    alert( "This is a Level 0 course.\n"
    + "LEVEL 0 is the most basic computer course, "
    + "and is designed for those who have never used a computer.");
    break;
   case '1':
    alert( "This is a Level 1 course.\n"
    + "LEVEL 1 requires little experience, but persons "
    + "taking these courses should have completed "
    + "\nCC001 COMPUTER COLLEGE PREP SCHOOL."
    + prq);
    break;
   case '2':
 ////// Demo special
    var special = (course_num != 'CC215') ? ''
     : "<br><br>Yes<br><input type='checkbox' id='prqc[0]'><span id='prq[0]'>CC101 AFTER PREP SCHOOL BASICS - LEVEL 1 or equivalent experience</span>"
     + "<br><input type='checkbox' id='prqc[1]'><span id='prq[1]'>Some experience with the Internet</span>"
     + "<br><input type='checkbox' id='prqc[2]'><span id='prq[2]'>Google Account</span>"
     ;
special = '';
  //  alert(" This is a Level 2 course.\n"
 //////  Special test version
//    jha_alert(" This is a Level 2 course.\n"
    alert(" This is a Level 2 course.\n"
    + "LEVEL 2 is somewhat more difficult and persons "
    + "taking these courses should have completed a Level 1 course "
    + "or have equivalent experience."
    + prq + special);
 //////
    break;
   case '3':
    alert( "This is a Level 3 course.\n"
    + "LEVEL 3 is a more advanced and complex course and requires that the "
    + "student has significant experience or has completed a Level 2 course "
    + "without experiencing any significant problems."
    + prq);
    break;
   // anything else just drops out with no alert
  }
 }

 return true;
}

function confirm_data() {  // Move on to phase two, Verification
 // Close any open Help block
 close_help();
 if (! DataCheck()) return false; // Data look good to the program?
 for (var i = 0; ; i++) { // Look at each line
  if (! document.getElementById('r' + i)) break;   // End
  else if (! document.getElementById('d' + i))continue; // No charge: Ignore
  else if (! document.getElementById('i' + i) || ! document.getElementById('i' + i).checked)  // No check: Hide
   document.getElementById('r' + i).className = 'noshowit';
  else document.getElementById('r' + i).className = 'showit checked';
 }

 // Hide all the "levels"- etc.-lines
 var s_t = document.getElementsByName('sub_title');
 if (s_t.length > 0) for (var i in s_t) {
  s_t[i].className = 'noshowit';
 }
 else { // ie workaround
  var s_t = document.getElementsByTagName('tr');

  for(var i=0;i<s_t.length;i++) {
   if(s_t[i].getAttribute('name')=='sub_title'){
     s_t[i].className = 'noshowit';
   }
  }
 }

 // Hide all phases and instructions but show #2
 document.getElementById('submit_1').className = 'noshowit';
 document.getElementById('submit_2').className = 'showit';
 document.getElementById('submit_3').className = 'noshowit';
 document.getElementById('submit_4').className = 'noshowit';
 document.getElementById('instructions_1').className = 'noshowit';
 document.getElementById('instructions_2').className = 'showit';

 document.getElementById('you').scrollIntoView(true);
 phase = 2;
 return false;
}

function showall(erase) {   // Move back to phase 1 for another registration
 // Process arg
 erase = (erase != null);
 // Clear the check marks from classes
 for (var i = 0; ; i++) {  // Look at each class row
  if (! document.getElementById('r' + i)) break;   // End
  document.getElementById('r' + i).className = 'showit'; // Reset row to visable
  if (erase) document.getElementById('i' + i).checked = false;  // Uncheck it
 }

 // Show all the "levels"- etc.-lines
 var s_t = document.getElementsByName('sub_title');
 if (s_t.length > 0) for (var i in s_t) {
  s_t[i].className = 'showit';
 }
 else { // ie workaround
  var s_t = document.getElementsByTagName('tr');

  for(var i=0;i<s_t.length;i++) {
   if(s_t[i].getAttribute('name')=='sub_title'){
     s_t[i].className = 'showit';
   }
  }
 }

 // Hide all phases and instructions but show #1
 document.getElementById('submit_1').className = 'showit';
 document.getElementById('submit_2').className = 'noshowit';
 document.getElementById('submit_3').className = 'noshowit';
 document.getElementById('instructions_1').className = 'showit';
 document.getElementById('instructions_2').className = 'noshowit';
 // Clean out first name
 if (erase || roundup_mode) {
  document.getElementById('Ecom_ShipTo_Postal_Name_First').value = '';
  if (roundup_mode || !no_typist_init) { // Clean it all out if "typist"
   document.getElementById('Ecom_ShipTo_Postal_Name_Last').value = '';
   document.getElementById('Ecom_ShipTo_Postal_Street_Line1').value = '';
   document.getElementById('Ecom_ShipTo_Telecom_Phone_Number').value = '';
   document.getElementById('Ecom_ShipTo_Postal_Email').value = '';
  }
 }

  // Reset total $ to zero or current value
 update_tot(); // Reset total $ to zero or current value
  // Reset IPA to None
 var IPAlength = document.forms[0].IPA.length;
 if (erase) {
  for (var i=0; i < IPAlength; i++) {
   document.forms[0].IPA[i].checked = false; // Uncheck them all
  }
  document.forms[0].IPA[IPAlength-1].checked = true; // Check the last: "None"
 }

  // Reset time
 var reg_date = document.getElementById('reg_date');
 var d = new Date();
 var d_t = d.getFullYear() + '-' + digits2((d.getMonth() + 1)) + '-'
         + digits2(d.getDate()) + ' ' + digits2(d.getHours()) + ':'
         + digits2(d.getMinutes());
 reg_date.value = d_t;

  // move cursor to first name
 document.getElementById('you').scrollIntoView(true);
 document.forms[0].Ecom_ShipTo_Postal_Name_First.focus();
 phase = 1;
  // Roundup mode specials
 if (roundup_mode) {
  var rul = (window.location.href.indexOf('?') > 0)
          ? window.location.href
          : window.location.href + '?roundup'
  window.location.href = rul;
 }
}

function get_ipa(update) { // Determine IPA status JS & DOM don't make it easy
 var IPAlength = document.forms[0].IPA.length;
 // Have to look at each
 for (var i=0; i < IPAlength; i++) {
  if (document.forms[0].IPA[i].checked) // This one checked?
    ipa_val = document.forms[0].IPA[i].value; // Found it! set the global value
 }
 if(update) update_tot();  // Update total $
}

function changedname() { // Called onchange of first name
 namechange = 1; // Remember
 if (aptchange) getPrior();  // both have changed: see if this is a duplicate
}

function changedapt() { // Called onchange address
 aptchange = 1;  // Remember
 if (namechange) getPrior(); // both have changed: see if this is a duplicate
}

function priorCheck() {  // Called onload
   // at least some browsers may carry over privious values in a form
 var name = document.getElementById('Ecom_ShipTo_Postal_Name_First').value;
 var addr = document.getElementById('Ecom_ShipTo_Postal_Street_Line1').value;
 if (name != '' && addr != '') getPrior(); // Check out for duplicate
 roundup_mode = (window.location.search.substring(1) == 'roundup');
}

function changed_initials(el_init){ // Called by change in typist's initials
  if (document.getElementById('initials').value.toLowerCase() == 'roundup') {
   document.getElementById('initials').value = '';
   roundup_mode = confirm('Run in "Roundup" Mode?');
  }
  else {
   var el_reg_date = document.getElementById('reg_date');
   el_reg_date.className = ' showit';
   no_typist_init = 0;
  }
}

window.onbeforeunload=beforeunloading;

function beforeunloading() {
 if (phase != 2) return
 var m = "Your Request has not been sent."
  + "\n\nTo send: click 'Cancel' (or 'Stay on this page'),"
  + " below, then the green 'OK Send'.";
 return m;
}


////// from: http://www.captain.at/howto-ajax-form-post-get.php   ///////
   // AJAX equivalent of Form SUBMIT

 var http_request = false;

 function ajaxSubmitForm(obj) { // Called to do the send to action_file
  var getstr = "?";
  for (i=0; i<obj.getElementsByTagName("input").length; i++) {
   switch(obj.getElementsByTagName("input")[i].type) {
    case "text":
    case "hidden":
      getstr += obj.getElementsByTagName("input")[i].name + "=" +
              obj.getElementsByTagName("input")[i].value + "&";
      break;
    case "checkbox":
      if (obj.getElementsByTagName("input")[i].checked
        && obj.getElementsByTagName("input")[i].name != '') {
         getstr += obj.getElementsByTagName("input")[i].name + "="
           + obj.getElementsByTagName("input")[i].value + "&";
         var nam = obj.getElementsByTagName("input")[i].name;
         var num = parseInt(nam.substr(nam.indexOf('[') + 1));
//         getstr += 'sec[' + num + ']=' + document.getElementById('HS' + num).innerHTML + "&";
         if (document.getElementById('HS' + num)) {
           getstr += 'sec[' + num + ']='
                  + document.getElementById('HS' + num).innerHTML + "&";
         }

      }
      break;
    case "radio":
     if (obj.getElementsByTagName("input")[i].checked) {
      getstr += obj.getElementsByTagName("input")[i].name + "="
       + obj.getElementsByTagName("input")[i].value + "&";
      }
      break;
    case "select":
     var sel = obj.getElementsByTagName("input")[i];
     getstr += sel.name + "=" + sel.options[sel.selectedIndex].value + "&";
     break;
   } // switch
  } // for i
  makeRequest(action_file, getstr);
 }

 function makeRequest(url, parameters) {
   http_request = false;
   if (window.XMLHttpRequest) { // Mozilla, Safari,...
    http_request = new XMLHttpRequest();
    if (http_request.overrideMimeType) {
           // set type accordingly to anticipated content type
     //http_request.overrideMimeType('text/xml');
     http_request.overrideMimeType('text/html');
    }
   }
   else if (window.ActiveXObject) { // IE
    try {
      http_request = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e) {
     try {
      http_request = new ActiveXObject("Microsoft.XMLHTTP");
     }
     catch (e) {}
    }
   }
   if (!http_request) {
    alert('Cannot create XMLHTTP instance');
    return false;
   }
   http_request.onreadystatechange = alertContents;
   http_request.open('GET', url + parameters, true);
   http_request.send(null);
 }

 function alertContents() {
  if (http_request.readyState == 4) {
   if (http_request.status == 200) {
    result = http_request.responseText;
    if (result.substr(0,1) == '!') {
     result = result.substr(1);
     movetodone();
     document.getElementById('myspan').innerHTML = result;
    }
    else {
     badtodone();
     document.getElementById('myspanerr').innerHTML = result;
    }
   }
   else alert('There was a problem with the request: !'
             + http_request.status + '!');
  }
 }
////// End of: from: http://www.captain.at/howto-ajax-form-post-get.php  /////

////////////////  Helper Functions ////////////////

 function roundCents(amount) {  // Clean up for display
    var cents = amount * 100;
    cents = Math.round(cents);
    var dol = "" + cents;
    var len = dol.length;
    return (cents == 0) ? "0.00"
          : dol.substring(0, len - 2) + "." + dol.substring(len - 2, len);
 }

  // Add a leading 0 for 2-digit numbers
 function digits2(num) {
  return (num > 9) ? num : '0' + num;
 }

 function trim (str) { // Remove white space from left and right of a string
    // One of the very useful functions left out of Javascript
    // from http://blog.stevenlevithan.com/archives/faster-trim-javascript
  var str = str.replace(/^\s+/, '');  // Replace any white space at left
  var ws = /\s/;
  var i = str.length;
   // Now, look at each char from the right until non blank
  while (ws.test(str.charAt(--i)));
  return str.slice(0, i + 1); // Return stripped string
 }

 function DataCheck() {  // Some simple validity checks on the data
  var err = '';   // Error message
  var emerr = '';  // Error message for possibly malformed email address
  update_tot();     // Calc Total $
  // Some things are required
  if (document.getElementById('Ecom_ShipTo_Postal_Street_Line1').value == '')
     err = "We need your Shell Point Address to register you.";
  if (document.getElementById('Ecom_ShipTo_Postal_Name_First').value == '')
     err = "We need your name to register you.";
  if (document.getElementById('Ecom_ShipTo_Postal_Name_Last').value == '')
     err = "We need your name to register you.";
  // Has any class been selected?
  var atleastone = 0;  // So far none selected
  for (var i = 0; ;i++) { // Look at each class line
   if (! document.getElementById('i' + i))continue; // No check box Ignore
   if (! document.getElementById('d' + i))continue; // No charge: Ignore
   if (document.getElementById('i' + i).checked) { // How about this class?
    atleastone = 1;    // YES! We have one checked
    break;             // Don't bother looking any further
   }
  }

  // So, did we find one checked?
  if (! atleastone) // No, we did not.
   err = "At least one course must be selected (check marked) to register you.";

  // Lets see if the email address, if any, makes sense.
  var em = document.getElementById('Ecom_ShipTo_Postal_Email').value;
  if (!ignore_email && em != '') {
    // We are not ignoreing the email address and, yes there is something
   var pp = em.lastIndexOf('.');  // Position of the last "dot"
   if (pp < 1) err = "Email address appears to be malformed.(No . )"; // No "dot"
   else {  // There is a "dot"
    if (!(pp < em.length - 1)) // is it one of the usual?
      emerr = "Email address appears to be malformed.(Nothing after . )"; // No top domain
    else {
     var pa = em.indexOf('@'); // Does it have an @?
     if (pa==-1) emerr = "Email address appears to be malformed.(No @ )"; // Nope
     else {
       pa = em.indexOf('@', pa+1); // Is there more than one @?
       if (pa>-1) emerr = "Email address appears to be malformed.(More than one @ )"; // Yep
       else {
        if (trim(em).indexOf(' ')>-1) // Does it have any spaces in it?
         emerr = "Email address appears to be malformed.(Includes space.)"; // Spacey
       }
     }
    }
   }
  }
  if (emerr != '') { // There seems to be something wrong with the email address
   // Ask if it is OK
   if(emok = confirm(emerr + ":\n" + em + "\nDo you want to use it anyway?"))
     ignore_email = 1; // So future checking won't be bothered
   else err = emerr;
  }
  if (err == '') { // No problems detected, transfer the total to the form var
   document.getElementById('Ecom_Transaction_Amount').value =
     trim(document.getElementById('tot').innerHTML).substr(1);
   return true; // OK!
  }
  alert(err); // Opps, tell them what we found
  return false; // Not OK
 }

 function movetodone() {   // Move on to phase 3, Done OK!
  // Hide all phases and instructions but show #3
  document.getElementById('submit_1').className = 'noshowit';
  document.getElementById('submit_2').className = 'noshowit';
  document.getElementById('submit_3').className = 'showit';
  document.getElementById('submit_4').className = 'noshowit';
  document.getElementById('instructions_1').className = 'noshowit';
  document.getElementById('instructions_2').className = 'noshowit';

  document.getElementById('you').scrollIntoView(true);
  phase = 3;

  document.getElementById('help_sub_3').scrollIntoView(true);
  return false;
 }

 function badtodone() {  // Move on to phase 4, Done ERROR
  // Hide all phases and instructions but show #4
  document.getElementById('submit_1').className = 'noshowit';
  document.getElementById('submit_2').className = 'noshowit';
  document.getElementById('submit_3').className = 'noshowit';
  document.getElementById('submit_4').className = 'showit';
  document.getElementById('instructions_1').className = 'noshowit';
  document.getElementById('instructions_2').className = 'noshowit';

  document.getElementById('you').scrollIntoView(true);
  phase = 4;
  return false;
 }

 function getPrior() { // Is this a duplicate registration request?
  // We get first name and address as "key"
  var name = document.getElementById('Ecom_ShipTo_Postal_Name_First').value;
  var lname = document.getElementById('Ecom_ShipTo_Postal_Name_Last').value;
  var apt = document.getElementById('Ecom_ShipTo_Postal_Street_Line1').value;
  var email = document.getElementById('Ecom_ShipTo_Postal_Email').value;

  var msgyes = "We already have a registration request from you. ";
  msgyes += "Sending THIS application will TOTALLY ERASE that prior one."
  var msgno = '';

  async_call('getPrior_cb','db_inc.php','sql_is_registered',
              name, apt, term, msgyes, msgno);

  async_write_direct('transcript','db_inc.php','get_transcript',name, lname,
              apt, email);

 }

  // Is this a duplicate registration request call-back
 function getPrior_cb(msg) {
  document.getElementById('prior').innerHTML = msg;
  if (msg) alert(msg);
 }

