$(function () { 

		window.$gallery = { 'el' : $('#masthead-images'), 'period': 4000, 'fadeTime': 750, 'restarter': false, used: 0, max: 2 };

		if ( $('#masthead-images').length > 0 ) {
			$.get( "/masthead_images?", 
				   function(data){
					   var items = data.split("\n");
				   
					   $.each(items, function ( k, v ) {
							   s = '<div class="masthead-image" style="background:url(' + v + '); "></div>';
							   $('#masthead-images').append(s);
						   });

					   $('#masthead-images .masthead-image').hide();
					   $('#masthead-images .masthead-image:first-child').show();
					   $('#masthead-images .masthead-image:first-child').addClass('masthead-image-active');
					   setInterval ( 'MastheadRotate();', 4000 );
					   
				   });
		}

	});



function MastheadRotate() {
 		var e = $('#masthead-images .masthead-image-active').next();
		if ( e.length == 0 ) {
				e = $('#masthead-images .masthead-image:first-child');
		}

		// only rotate a few times before stopping
		window.$gallery.used ++;
		if ( window.$gallery.used > window.$gallery.max ) {
				clearInterval ( window.$gallery.period );
		}

  	$('#masthead-images .masthead-image-active').fadeOut( 1000, function() {
				$('#masthead-images .masthead-image-active').removeClass('masthead-image-active');
				$(e).fadeIn( 1000, function() {
						$(e).show();
				});
		    $(e).addClass('masthead-image-active');
		});
	
} 
