$(document).ready(function() {
 
  $("#addElement").click( 
      function() { 
          ajaxAddField();
       }
    )
	.after('<img src="/library/images/ajax-loader-sm.gif" class="ajax_loader" style="display:none;" />');
	//.get().css('display','none');		

  $("#removeElement").click(
      function() {
          removeField();
      }
    );
  }
);
 
// Get value of id - integer appended to dynamic form field names and ids
var id = $("#num_students").val();
var is_loading = false;
 
// Retrieve new element's html from controller
function ajaxAddField() {
	if(is_loading==false){
		is_loading = true;
		$('.ajax_loader').css('display','inline');
		$("#num_students").val(++id);
		$.ajax(
			{
				type: "POST",
				url: "/parent-user/user/newfield/format/html",
				data: "id=" + id,
				success: function(newElement) {
					// Insert new element before the Add button
					$("#addElement").parents('li').eq(0).before(newElement);
					$('.ajax_loader').css('display','none');
					is_loading = false;
					}
			}
		);
	}
}
 
function removeField() {
	if(id<2){
		alert('You must enter the ID of at least one student to create a parent account');
		return false;
	}
  // Remove the elements that match the search string.
  $('#student_id_'+id).parents('li').eq(0).remove()

  // Decrement and store id
  $("#num_students").val(--id);
}
