/**
 * jQuery plugin: FadeGallery
 * http://www.exalted-web.com/fadegallery/
 *
 * Written by Shay from http://www.exalted-web.com
 * Release date: 28/02/2010
 * Version: 0.2
 *
 * Licensed under the GNU GPL license.
 * http://www.gnu.org/licenses/gpl.txt
 */
(function($) {
    $.fn.gallery = function(options) {
		
        var defaults = {
            FadeIn		: 1000,
            FadeOut		: 1000,
            Delay		: 1000,
            Repeat		: true
        };
        var options = $.extend(defaults, options);
		
        return this.each(function() {
                                              
            var gallery = $(this).children();
            var next_item = 6;
            var hide_item = Math.floor(Math.random()*5);
            var t = setTimeout(Fade, options.Delay);
            var cycled = 0;
	
            function Fade() {
                if(gallery.length > 6){
                    t = clearTimeout();
			
                    if(next_item >= gallery.length) {
                        if(!options.Repeat) {
                            return false;
                        }
                        next_item = 6;
                        hide_item = Math.floor(Math.random()*5);
                        cycled = 1;
                    }
				
                    gallery.eq(hide_item).children().fadeOut(options.FadeOut, function() {
                                        

                        var newImage = gallery.eq(next_item).clone(true).children();
                        var oldImage = gallery.eq(hide_item).clone(true).children();

                        gallery.eq(hide_item).empty().append(newImage).children().attr('style', 'display:none;');
                        ;
                                        
                        gallery.eq(next_item).empty().append(oldImage).children().attr('style', 'display:none;');
                        ;
                                        
                                       
                        gallery.eq(hide_item).children().fadeIn(options.FadeIn, function() {

                            hide_item = Math.floor(Math.random()*5);
                                                
                            if(cycled == 0){
                                next_item++;
                            } else {
                                next_item++;
                                                    
                            }
						

                            if(options.Repeat || next_item < gallery.length) {
                                t = setTimeout(Fade, options.Delay);
                            }
                        });
					
                    });
                                
                }
            }
			
        });
		
    };
})(jQuery);
