jQuery(function($) {	
  
  // for slideshow, first it adds a class of first
  $('#first_slide:first').addClass('show');
	
  // for tablesortging
  $.tablesorter.defaults.widgets = ['zebra'];
	$("table").tablesorter();
	
	// enable scrolls. a simple magical one liner
  $(".scroll").scrollable({size: 1, loop: true});
  
  slideShow();
  
  $('a#regenerate_teachers_list_in_error_messages').click(function() {
    $('p#teacher_field').show();
  });
  
  // THE FOLLOWING IS TO HIGHLIGHT FLASH MESSAGES
  $('#flash_notice').effect("highlight", {}, 3000);
  $('#flash_alert').effect("highlight", {}, 3000);
  
  // THE FOLLOWING IS TO CLEAR THE TEACHER NAME FIELD WHEN CREATING A NEW TEACHER
  $('#teacher_name_field').click(function() {
    $(this).val('');
  });

  
});

function slideShow() {

	//Set the opacity of all images to 0
	jQuery('#gallery a').css({opacity: 0.0});
	
	//Get the first image and display it (set it to full opacity)
	jQuery('#gallery a:first').css({opacity: 1.0});
		
	//Call the gallery function to run the slideshow, 6000 = change to next image after 6 seconds
	setInterval('gallery()',3000);
	
}

function gallery() {
	
	//if no IMGs have the show class, grab the first image
	var current = (jQuery('#gallery a.show')?  jQuery('#gallery a.show') : jQuery('#gallery a:first'));

	//Get next image, if it reached the end of the slideshow, rotate it back to the first image
	var next = ((current.next().length) ? ((current.next().hasClass('caption'))? jQuery('#gallery a:first') :current.next()) : jQuery('#gallery a:first'));	
		
	//Set the fade in effect for the next image, show class has higher z-index
	next.css({opacity: 0.0})
	.addClass('show')
	.animate({opacity: 1.0}, 1000);

	//Hide the current image
	current.animate({opacity: 0.0}, 1000)
	.removeClass('show');
	
	//Set the opacity to 0 and height to 1px
	jQuery('#gallery .caption').animate({opacity: 0.0}, { queue:false, duration:0 }).animate({height: '1px'}, { queue:true, duration:300 });	
		
}


// ADD AND REMOVE FIELDS FROM RAILSCAST #197
function remove_fields(link) {
  $ = jQuery
  $(link).prev("input[type=hidden]").val("1");
  $(link).closest(".fields").hide();
}

function add_fields(link, association, content) {
  $ = jQuery
  var new_id = new Date().getTime();
  var regexp = new RegExp("new_" + association, "g")
  $(link).parent().before(content.replace(regexp, new_id));
}