/**
 * jQuery.simple_slideshow
 * Written by Michael Kerr (mike AT onlysport DOT co DOT nz)
 * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
 * Date: 2009/11/02
 *
 * @author Michael Kerr
 * @version 0.0.1
 *
 **/

(function($) {

	$.fn.simple_slideshow = function( options )
	{
		if (! this.length) return false;

		var _ss = $.data(this[0], 'simple_slideshow');
		if (_ss) { return _ss; }

		_ss = new $.simple_slideshow( this[0], options );

		$.data(this[0], 'simple_slideshow', _ss);

		return _ss;
	};

	$.simple_slideshow = function( lmnt, options )
	{
		this.$lmnt = $(lmnt);
		this.opts = $.extend({}, $.simple_slideshow.defaults, options);

		this.init();
	};

	$.extend($.simple_slideshow,
	{
		version: '0.0.1',

		defaults:
		{
			autostart: true,
			timer: null,
			default_options: null,
			text: ''
		},

		setDefaults: function( settings )
		{
			$.extend( $.simple_slideshow.defaults, settings );
		},

		prototype:
		{
			init: function ()
			{
				this.opts.self = this;

				if ( this.opts.autostart ) this.start();
			},

			start: function ()
			{
				$t = this;
				if ( $t.$lmnt.find('.aacms_slide').length > 1 )	$t.switch_frame();
			},

			switch_frame: function()
			{
				$t = this;

				var _timer = $.data( $t.$lmnt[0], 'timer' );

				if (!_timer) _timer = { tick: 0 };
				_timer.element = $t;

				if ( _timer.tick > 0)
				{
					var _active = _timer.element.$lmnt.find( '.aacms_slide .slide-active' );
					
					//_active.css({ height: 300, width: 300, opacity: 1 });
					if ( _active.length == 0 ) _active = _timer.element.$lmnt.find( '.aacms_slide:last' );

					// use this to pull the tts in the order they appear in the markup
					var _next = _active.next().length ? _active.next() : _timer.element.$lmnt.find( '.aacms_slide:first' );

					_next.width( _next.parent().innerWidth( true ) );
					_next.height( _next.parent().innerHeight( true ) );

					_active.addClass('slide-last-active');

					_next.css({ opacity: 0.0 })
						.addClass( 'slide-active' )
						.animate({ opacity: 1.0 }, 1000, function() {
							_active.removeClass( 'slide-active slide-last-active' );
						});
				}

				setTimeout( function() { _timer.element.switch_frame(); }, 4000 );

				_timer.tick++;
				$.data(_timer.element.$lmnt[0], 'timer', _timer);
			}
		}
	});

 })(jQuery);
 
 $(function() 
{
	setTimeout( function() 
	{  

		// Find all slideshows on the page and feed them to the simple slideshow jquery plugin.
		$('.aacms_slideshow').each(function( indx, lmnt )
		{
			$(this).simple_slideshow( { name: indx } );
		});

	}, 4000 );


});
