$(document).ready(function(){
  var commSelectId = 'community';
  var affSelectId  = 'affiliation';

  $('#' + commSelectId).change(function(e){
    updateAffiliations(commSelectId, affSelectId);
  });

  updateAffiliations(commSelectId, affSelectId, $('#' + affSelectId).attr('default'));
})

function updateAffiliations (commSelectId, affSelectId, defaultAid) {
  var commSelect = $('#' + commSelectId);
  var affSelect  = $('#' + affSelectId);
  var comid      = parseInt(commSelect.val(), 10);
  var oldAid     = parseInt(affSelect.val(), 10);

  if(defaultAid === null){
    defaultAid = -1;
  }

  $.get(
    'Library/xml/user/getAffiliationsByCommunity.php',
    {comid: comid},
    function(xml, textStatus){
      affSelect.empty(); // wipe out all the options
      $('<option value="">Select One...</option>').appendTo(affSelect);
      $(xml).find("och-objects > affiliation").each(function(i){
        var pk         = $(this).find('pk > val').text();
        var name       = $(this).find('name > val').text();
        var optionHTML = $('<option value="' + pk + '">' + name + '</option>');
        optionHTML.appendTo(affSelect);

        if (optionHTML.val() == oldAid || optionHTML.val() == defaultAid)
          optionHTML.attr('selected', 'selected');
      });

      // Select affiliation automatically if only one is available
      if (affSelect.find('option').length == 2) {
        affSelect.find('option:first').remove();
        affSelect.find('option:last').attr('selected', 'selected');
      }
    },
    'xml'
  );
}