/*
  Author: Thomas Steinmetz
  
  - Listen to the collegeLocation select box, on change to a real state call getList();
  - getList() .post() to a php file to get JSON request.
    - Parse JSON and build up the options for the schoolList select box
    
  - Note: a bug happens on sites that include this script without those two select boxes
          where the .post() sitll fires for some reason and brings back nothing (Which is correct)
          which is why I put in the ' if(res.length > 10) { ... } ' code so that IE does not
          display an error

*/

$(function(){
  $("#schoolList").append("<option value=''>Select a State</option>");
  $('#schoolList').attr("disabled", true); 
  if($("#collegeLocation").val() != "")
    getList();

  $("#collegeLocation").change(function(){ 
    if($("#collegeLocation").val() != "")
      getList();
    else
    {
      $("#schoolList").find('option').remove().end();
      $("#schoolList").append("<option>Select a State</option>");
      $('#schoolList').attr("disabled", true);
    }
  });
});

getList = function() {
  var schoolList = $("#schoolList");
  $(schoolList).find('option').remove().end();
  $(schoolList).append("<option value=''>Select School</option>"); 
  var state = $("#collegeLocation").val();
	var xzdf  = $("#xzdf").val();
	var site  = document.domain;	
  var http  = "http://";
  
  if (site.substring(0,7) == "secure.")
    http = "https://";
  
  $.post(http + site + "/schoolPicker/class.getCollegeListJq.php?state=" + state + "&xzdf=" + xzdf, function(res){ 
    if(res.length > 10) // Make sure we have a legit response
    {
      res = eval("(" + res + ")");
  
      for (id in res) { 
        
        var school = res[id];
        
        if (typeof school == "object") {
          $(schoolList).append("<option value='" + id + "'>" + school.name + "</opton>");
        }
      }
      
      // Select previous school
      $("#schoolList option[value='" + postSchoolList + "']").attr('selected', 'selected');
      $('#schoolList').attr("disabled", false); 
    }
  });
}