var fullName = "";
var SQLdate= "yyyy-mm-dd";
var http;

function GetXmlHttpObject() {
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    return new XMLHttpRequest();
    }
  if (window.ActiveXObject) {
    // code for IE6, IE5
    return new ActiveXObject("Microsoft.XMLHTTP");
    }
  alert("Your browser does not support XMLHTTP!");
  return null;
}

function showHint(str) {

  if (str.length==0) { 
    document.getElementById("txtHint").innerHTML="";
    return;
    }

  var hint=GetXmlHttpObject();

  /* setup url */
  var url="gethint.php?q=" + str;

  hint.open("GET",url,false);
  hint.send(null);
  var x = hint.responseText;
  var c = x.charAt(0);
  if(c=="*") { /* Name found */
    var txtOutput = document.getElementById("txt1");
    x = x.slice(1);
    fullName = x;
    txtOutput.value = x;
    document.getElementById("txtHint").innerHTML="";
  }
  else {
    x = "<p>Suggestions :</p>" + x;
    document.getElementById("txtHint").innerHTML=x;
  }
}

function delRec(table, id) {

//alert("delRec(" + table + ", " + id +")");
  var t =
"<center><ul><li><strong><em>Admin Functions</em></strong></li>";
  var d =
"<p><form action =\"ceu.php\" method = \"get\">" +
"  <button type = \"submit\">Cancel Record Delete</button>" +
"</form></p></ul></center>";
  var toc = document.getElementById("toc");
  toc.innerHTML=t+d;


  entry=prompt("Are you sure you want to delete Record: " + id, "no");
  if(entry!='yes') {
    alert("Okay, record will not be deleted... to delete you must enter 'yes'");
    return;
  }

  var sql = "DELETE FROM " + table + " WHERE ID = " + id;
//alert("sql= " + sql);

  var r= modDB(sql);
//alert("r= " + r);
//return;
  if(r!=1) {
    alert("Expected result= 1 but is= " + r);
  }

  toc.innerHTML="";
  var s = "<p>Record: " + id + " was deleted.</p>";
  var c = "<p><form action =\"ceu.php\" method = \"get\">" +
"  <button type = \"submit\">Continue</button>" +
"</form></p></ul></center>";

  var content = document.getElementById("content");
  content.innerHTML=s+c;

}

function addRec() {
  var t =
"<center><ul><li><strong><em>Admin Functions</em></strong></li>" +
"<input type = \"button\" value = \"Start Record Over\"" +
" onclick = \"addRec()\"/>" +
"</p><form action =\"ceu.php\" method = \"get\">" +
"  <button type = \"submit\">Cancel Record Add</button>" +
"</form></p></ul></center>";
  var toc = document.getElementById("toc");
  toc.innerHTML=t;

  var f =
"<fieldset>" +
"<legend>Add A Record</legend>" +
"<p><strong>Note: </strong>Click button to your right to " +
"<em>Cancel Record Add</em> and go back to viewing records.</p>" +
"<p>First enter the Minister's name for whom the record is being made.</p>" +
"Full Name (starting with first name): " +
"<input type=\"text\" id=\"txt1\" onkeyup=\"showHint(this.value)\" ></>" +
"<span id=\"txtHint\"></span>" +
"<p>After Minister's name is entered, Click on why record is being added:</p>" +
"<center>" +
"<input type= \"button\" value= \"Event Study\" onclick= \"addForm('e')\"/>" +
"<input type= \"button\" value= \" Book Study\" onclick= \"addForm('b')\"/>" +
"</center>" +

"</fieldset>";

  var content = document.getElementById("content");
  content.innerHTML=f;
  var txt1 = document.getElementById("txt1");

  txt1.focus();
  txt1.focus(); /* second one is needed so IE will obtain focus */
}

function getDOMvar(id) {
  var x= document.getElementById(id);
  if(x==null) return("Not Applicable");
  return(x.value);
}

function addEmpty(input, entry) {
  if(isEmpty(input)) {
    input = document.getElementById(entry);
    input.focus(); input.focus(); /* twice so IE will hear it */
    return true;
  }
  return false;
}

function chkAdd(t) {
  var i = fullName.lastIndexOf(" ");
  var lastName = fullName.slice(i+1);
  if(t=='b') eventOrBook="book";
  if(t=='e') eventOrBook= "event";
  var title= getDOMvar("title");
  var dateFinished= getDOMvar("dateFinished");
  var bookAuthor= getDOMvar("bookAuthor");
  var locationOrPublisher= getDOMvar("locationOrPublisher");
  var ceuEarned= getDOMvar("ceuEarned");

  /* check for input errors */
  if(addEmpty(title, "title")) return;
  if(addEmpty(dateFinished, "dateFinished")) return;
  if(addEmpty(bookAuthor, "bookAuthor")) return;
  if(addEmpty(locationOrPublisher, "locationOrPublisher")) return;
  if(addEmpty(ceuEarned, "ceuEarned")) return;

  /* fix for possible bad special characters */
  title= replaceBadChars(title);
  bookAuthor= replaceBadChars(bookAuthor);
  locationOrPublisher= replaceBadChars(locationOrPublisher);
  ceuEarned= replaceBadChars(ceuEarned);

  if(isDateError(dateFinished)) {
    x = document.getElementById("dateFinished");
    x.focus(); x.focus(); /* twice so IE will hear it */
    return;
  }

  if(isFloatError(ceuEarned)) {
    alert("CEU(s) Earned can be any number including a decimal point.");
    x = document.getElementById("ceuEarned");
    x.focus(); x.focus(); /* twice so IE will hear it */
    return;
  }

  var sql = "INSERT INTO PETNceu VALUES (null, ";
  sql += "'" + lastName +            "',";
  sql += "'" + fullName +            "',";
  sql += "'" + eventOrBook +         "',";
  sql += "'" + title +               "',";
  sql += "'" + SQLdate +             "',";
  sql += "'" + bookAuthor +          "',";
  sql += "'" + locationOrPublisher + "',";
  sql += "'" + ceuEarned +           "');";

  var r= modDB(sql);
  if(r!=1) {
    alert("Expected result= 1 but is= " + r);
  }
  else {
    addRec();
  }

}

function mkTextIn(prompt, id, size) {
  var x= "<p>" + prompt;
  x+= "<input type = 'text'";
  x+= "id= '" + id + "'";
  x+= "size= '" + size + "'";
  x+= "</p>";
  return(x);
}

function addForm(t) {
  if(fullName=="") {
    alert("You must first enter a Full Name before you can continue.");
    return;
  }
  /* start fieldset and Handle Legend */
  var f = "<fieldset><legend>Enter the ";
  if(t=="e") f+= "Event ";
  if(t=="b") f+= "Book ";
  f+= "information for <strong>" + fullName + 
      "</strong>'s CEU, then press Submit</legend>";

  /* make text inputs */
  if(t=='e') f+= mkTextIn("Event Name: ", "title", "40");
  if(t=='b') f+= mkTextIn("Book Title: ", "title", "40");

  f+= mkTextIn("Date Finished (m/d/y): ", "dateFinished", "12");

  if(t=='b') f+= mkTextIn("Book Author: ", "bookAuthor", "32");

  if(t=='e') f+= mkTextIn("Event Location: ", "locationOrPublisher", "40");
  if(t=='b') f+= mkTextIn("Book Publisher: ", "locationOrPublisher", "40");

  f+= mkTextIn("CEU(s) Earned: ", "ceuEarned", "6");

  /* Submit Button and terminate fieldset */
  f+= "<center><button onclick = \"chkAdd(\'" + t + "\')\">Submit" +
      "</button></center></fieldset>";

  var content = document.getElementById("content");
  content.innerHTML=f;
  var title = document.getElementById("title");
  title.focus();
  title.focus(); /* second one is need for IE to obtain focus */
}

function chgState() {
  if(http.readyState == 4) {
    if(http.status == 200) {
//alert("chgState() alert: " + http.responseText);
    }
    else {
      alert("Error- " + http.status + ": " + http.statusText);
    }
  }
}

function modDB(sql) { /* runs the sql line on the server */
  http = new GetXmlHttpObject();
  if (http==null) {
    alert ("Browser does not support HTTP Request");
    return;
  }
  var url = "modDB.php";
  var sql = "sql=" + sql;

  http.open("POST", url, false);

  //Send the proper header information along with the request
  http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  http.setRequestHeader("Content-length", sql.length);
  http.setRequestHeader("Connection", "close");
  
  http.onreadystatechange = chgState;

  http.send(sql);

  http.onreadystatechange = chgState;
//alert("here 0");
  /* check status */
  if (http.status == 200) {
//alert("here 1");
    return(http.responseText);
  }
  else { /* something went wrong */
//alert("here 2");
    alert("Error- " + http.status + ": " + http.statusText);
    return(null);
  }
//alert("here 3");

}

function login() {
  /* if user's browser cannot communicate via AJAX, no use logging them in */
  var test=GetXmlHttpObject();
  if(test==null) {
    alert("This must be resolved before you can login");
    return;
  }

  var l ="<form action =\"ceu.php\" method = \"post\">";
  l = l + "<fieldset>";
  l = l + "  <p>";
  l = l + "  <input type = \"hidden\"";
  l = l + "    name = \"action\"";
  l = l + "    value = \"l\"";
  l = l + "    checked = \"checked\" />"
  l = l + "  </p>";
  l = l + "Login by entering name and password below...";
  l = l + "  <p>";
  l = l + "  User Name: <input type = \"text\"";
  l = l + "    id = \"who\" name = \"usr\" /> ";
  l = l + "  </p>";
  l = l + "  <p>";
  l = l + "  Password: <input type = \"password\"";
  l = l + "    name = \"pwd\" /> ";
  l = l + "  </p>";
  l = l + "  <button type = \"submit\">then click HERE</button>";
  l = l + "</fieldset>";
  l = l + "</form>";

  var o="content";
  document.getElementById(o).innerHTML=l;
  document.getElementById("toc").innerHTML="";
  document.getElementById("who").select();
}

function isNumeric(c) {
  if(c<'0') return false;
  if(c>'9') return false;

  return true;
}

function firstNonNumeric(d) {
  var l= d.length;
  for(i= 0; i<l; i++) if(!isNumeric(d[i])) return(i);
  return(-1);
}

function lastNonNumeric(d) {
  var l= d.length;
  for(i= l-1; i>0; i--) if(!isNumeric(d[i])) return(i);
  return(-1);
}

function numofNonNumeric(d) {
  var l= d.length;
  var j= 0;
  for(i=0; i<l; i++) {
//alert("d[" + i + "]= " + d[i]);
    if(!isNumeric(d[i])) {
      j++;
    }
  }
  return(j);
}

function isDateError(d) {
  var e1= "The Date must be entered as d/m/y. Thus, is at least five characters long.  An example, 1/2/3 was Jan 2, 2003.";
  var e2= "There should be exactly two non-numeric characters in date.  The format is d/m/y.  For example, 1/1/8 was New Years Day 2008."
  var e3= "The first character in Date must be a month number";
  var e4= "The last character in Date must be a year number";
  var e5= "The day is missing in Date";
  var e6= "The month portion of Date must be between 1 and 12";
  var e7= "The day portion of Date must be between 1 and 31";
  var e8= "A year cannot be entered that is greater than this year";
  var i= parseInt(0);
  var j= parseInt(0);
  var k= parseInt(0);
  var mm= "00";
  var dd= "00";
  var yyyy= "0000";
  var now= new Date();
  var l= d.length; if(l<5) { alert(e1); return true; }

  i= numofNonNumeric(d); if(i!=2) { alert(e2); return true; }

  i= firstNonNumeric(d); if(i<1) { alert(e3); return true; }

  j= lastNonNumeric(d); if((j+1)==l) { alert(e4); return true; }

  if(i==j) { alert(e5); return true; }

  k= d.substring(0, i);
  if((k<1) || k>12) { alert(e6); return true; } 
  mm= k;

  k = d.substring(i+1, j);
  if((k<1) || k>31) { alert(e7); return true; } 
  dd= k;

  yyyy = d.substring(j+1);
  k= parseFloat(yyyy);
  j = now.getFullYear();
  i = j - 2000;
//alert("yyyy= " + yyyy + " k= " + k + " j= " + j + " i= " + i);
  if(k<2000) k= k + 2000.
  if(k>j) { alert(e8); return true; }
  yyyy= k;

  if(mm.length<2) mm= "0" + mm;
  if(dd.length<2) dd= "0" + dd;

  SQLdate= yyyy + "-" + mm + "-" + dd;
  return(false);
}

function isFloatError(f) {
  if (isEmpty(f)) return true;
  var l= f.length;

  for(i=0; i<l; i++) {
    if(!isNumeric(f[i])) {
      if(f[i]!='.') break;
    }
  }
  if(i<l) {
    alert("The entry was not a number: " + f);
    return true;
  }
  return false;
}

function isEmpty(e) {
  var l= e.length;
  if((l==null) || (l==0)) {
    alert("An Entry cannot be left blank (empty).");
    return true;
  }
  return false;
}

function isEntryError(fieldName, newEntry) {
  if(isEmpty(newEntry)) return true;
  if(fieldName=="dateFinished") return(isDateError(newEntry));
  if(fieldName=="ceuEarned") return(isFloatError(newEntry));

  return false;
}

function see(x) {
  var l= x.length;
alert("l= " + l);
  for(i=0; i<l; i++) {
    var c= x.charCodeAt(i);
    alert("x[" + i + "]= " + c);
  }
}

function noLeadingGarbage(x) {
  var l= x.length;

  if(l==0) return(null);
  for(i=0; i<l; i++) if(x.charCodeAt(i)>32) break;
  var y= x.slice(i);
  return(y);
}

function replaceBadChars(x) {
//  var b= "\"'+/<>\\";
//alert(b);
  var b = new Array("\""    , "'"     , "+"     , "/"     ,
                    "<"     , ">"     , "\\"    , "&");
  var r = new Array("%26#34", "%26#39", "%26#43", "%26#47",
                    "%26lt;", "%26gt;", "%26#92", "%26#38" );
//  var r= ",";

  for(i=0; i<b.length; i++) {
    x= x.replace(b[i], r[i]);
  }
  return(x);
}

function modRec(table, fieldName, id, totalID) {
  var docID= fieldName + id;
  docVar= document.getElementById(docID);
  var currentEntry= docVar.innerHTML;
  currentEntry= noLeadingGarbage(currentEntry);
  var newEntry = prompt("Please enter a new value: ", currentEntry);
//see(newEntry);
  if (newEntry == null) return; /* cancel was pressed */
  if (newEntry  == currentEntry) return; /* it was not changed */
  dbEntry= replaceBadChars(newEntry);
//alert("newEntry= " + newEntry);
  if (isEntryError(fieldName, newEntry)) return;

  /* modify DB field */
  var sql= "UPDATE " + table + " SET " + fieldName + " = '";
  if (fieldName=="dateFinished") sql+= SQLdate;
  else sql+= dbEntry;

  sql+= "' WHERE ID = '" + id + "';";
//alert(sql);
  var r= modDB(sql);
  if(r!=1) {
    alert("Expected result= 1 but is= " + r);
    return;
  }

  /* update doc/screen */
  if(fieldName=="ceuEarned") { /* update total if ceuEarned changed */
    var total = document.getElementById(totalID).innerHTML;
    total= parseFloat(total) - parseFloat(currentEntry) + parseFloat(newEntry);
    document.getElementById(totalID).innerHTML= total;
  }

  /* currentEntry with newEntry */
  docVar.innerHTML= newEntry;
} 

  exit(0);
