// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

document.observe("dom:loaded", function() {
  var check_boxes = $$('input.registration-status-updater');
  binds_each_status_check_boxes(check_boxes);
});


function binds_each_status_check_boxes(check_boxes){
  check_boxes.each(function (check_box){
    Event.observe(check_box, 'click', function(){
      send_status_update_through_ajax(check_box);
    });
  });
};

function send_status_update_through_ajax(check_box){
  var training_id          = $("training_id").getValue();
  var authenticity_token   = $("authenticity_token").getValue();
  var check_box_info       = check_box.id.split('_');
  var registration_id      = check_box_info[1];
  var parameter_identifier = check_box_info[2];
  var check_box_checked    = check_box.checked;

  new Ajax.Request("/trainings/"+training_id+
                   "/registrations/"+registration_id+
                   "?registration["+parameter_identifier+"]="+check_box_checked+
                   "&authenticity_token="+authenticity_token, {
    method: 'put',
    onSuccess: function(transport){
      var response = transport.responseText.evalJSON();
      if(response.success == false){
        check_box.checked = !check_box_checked;
        alert("We couldn't update the registration, contact the website admin");
      }
    }
  });
};
