dojo.require("dojo.parser");
dojo.require("dijit.form.FilteringSelect");
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.layout.ContentPane");

var sortOrder = 0;
var countryID = null;
var stateID = null;

dojo.addOnLoad( function() {
   countryID = "${fieldValue(bean:studentList,field:'currCountryID')}";
   stateID = "${fieldValue(bean:studentList,field:'currStateID')}";
   var countryDropdown = dijit.byId("countryDropdown");
   countryDropdown.setValue(countryID);
});

function setTopSelectValue(pDropdown, pUrl) {
   dojo.xhrGet( {
      // Location of the HTML content we want to grab
      url : pUrl,
      timeout : 20000,

      // Called when the page loaded successfully
      load : function(data) {
         pDropdown.setValue(data);
      },

      // Called if there was an error (such as a 404 response)
      error : function(data) {
         console.error('Error: ', data);
      }
   });
}

function newCountry(value) {
   if (value == undefined) {
      console.debug("newCountry Selected but value is undefined");
      return;
   }
   var stateDropdown = dijit.byId("stateDropdown");
   // console.debug("newCountry Selected (" + countryID + ", " + value + ")");
   if (countryID == value) {
      stateDropdown.setValue(stateID);
   } else {
      var url = "statesInCountry?countryID=" + value;
      var newStates = new dojo.data.ItemFileReadStore( {
         url : url
      });
      stateDropdown.store = newStates;
      setTopSelectValue(stateDropdown,
            "/awb/student/possibleCountryChange?countryID=" + value);
      countryID = value;
   }
}

function newStudList(pParams) {
   console.debug("pParams =  " + pParams);
   var sortParam = "&order=" + (sortOrder == 0 ? "asc" : "desc");
   var localParams = pParams + sortParam;
   sortOrder = sortOrder == 0 ? 1 : 0;
   dojo.xhrGet( {
      // Location of the HTML content we want to grab
      url : "newStudentList?" + localParams,
      timeout : 20000,

      // Called when the page loaded successfully
      load : function(data) {
         dojo.byId('studList').innerHTML = data;
      },

      // Called if there was an error (such as a 404 response)
      error : function(data) {
         console.error('Error: ', data);
      }
   });
}
function newState(value) {
   if (value == undefined) {
      console.debug("newState Selected but value is undefined");
      return;
   }
   // console.debug("newState Selected "+value);
   sortOrder = 0; // Always start with default when changing state
   newStudList("stateID=" + value);
}
