// Copyright 2010 John Heminghous
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//
// slideshow - image slideshow
//
// Depends on jQuery.
// Parameters: duration - time to stay on an image (milliseconds)
//             transition - time to fade between images (milliseconds)

jQuery.fn.slideshow = function(parameters)
{
	parameters = parameters || {};
	parameters.duration = parameters.duration || 3000;
	parameters.transition = parameters.transition || 1000;
	
	function initializeTransitions(container, images)
	{
		var index = 1;
		setInterval(
		  function()
	    {
			  if (index == images.length)
			  {
				  index = 0;
			  }
			  var nextImage = new Image();
			  $(nextImage).load(
			    function()
			    {
				    $(container).append(this);
				    $(container).find('img:first').css({'z-index': 1});

				    $(this).css({opacity: 0.0, 'z-index': 2})
				      .animate({opacity: 1.0}, parameters.transition,
				        function()
				        {
						      $(container).find('img:first').remove();
					      })
			    }).attr('src', images[index++])
			      .css({position:'absolute',top:0,left:0,'z-index':3});

		  }, parameters.duration);
	}

	$(this).each(
	  function()
	  {
		  var images = [];
		  $(this).find("a").each(
		    function()
		    {
			    images.push($(this).attr("href"));		
		    });
		  var firstImage = new Image();
		  var container = this;

		  $(this).empty();
		  $(firstImage).attr('src', images[0])
		    .css({position:'absolute',top:0,left:0,'z-index':0})
		    .load(
		      function()
		      {
			      $(container).append(this);
			      initializeTransitions(container, images);
		      });
	  });
}
