
//
// Responses
//

function returnNewSub() {

  var request = returnNewSub.reqObj;

  if (request.readyState == 4) {
    if (request.status == 200) {

		  var mytext = request.responseText;

        if (mytext == '0') {
          alert("ERROR! There was a problem attempting to save new subcategory:\nYou have been logged out or there was a problem with the category listing.  Please try again.");
        } else if (mytext == '1') {
          alert("The subcategory you are trying to add already exists!  Please select the existing subcategory from the pulldown.");
        } else {

  		    var jsonObject = eval('(' + request.responseText + ')');

	       var newObj         = $(jsonObject.new_id);
          var newButtonObj   = newObj.nextSibling;
          var newForm        = newObj.parentNode;
          var parentObj      = newForm.parentNode;
          var previousSelect = newForm.previousSibling;

          var parent_id = previousSelect.previousSibling.options[previousSelect.previousSibling.selectedIndex].value;
		    var new_category_id = jsonObject.category_id;

	       // remove "new" elements
	       parentObj.removeChild(newForm);

	       // add new category to last select
	       var theOption;
	       // TODO: this seems to have problems in Safari Windows
	       var numOptions = previousSelect.options.length;
	           theOption = new Option(jsonObject.category_name,jsonObject.category_id);
	       previousSelect.options[numOptions] = theOption;
	       previousSelect.selectedIndex = numOptions;
	       previousSelect.onchange();

		    // update recursive array
		    // TODO: this is hard-coded
		    if (!categoryChildren[parent_id]) categoryChildren[parent_id] = new Array;
		    categoryChildren[parent_id][new_category_id] = jsonObject.category_name;
		    categoryParents[new_category_id] = parent_id;

        }

    } else {
      alert("ERROR! There was a problem attempting to save new subcategory:\nCould not find the required AJAX file.  Please try again.");
    }

  }
  return true;

}