/* =========================================================

// Date: 2009-02-04
// Firm: O'Berry | Cavanaugh
// Author: Joseph Bergantine
// Mail: jnb@oberrycavanaugh.com
// Web: http://oberrycavanaugh.com

// modification to jquery.innerfade.js (less abstracted for size, less options (no random, no variation in effects), added loop true/false setting) 
// jQuery.innerfade.js was originally created by Torsten Baldes http://medienfreunde.com/lab/innerfade/
// which was based on the work of Matt Oakes http://portfolio.gizone.co.uk/applications/slideshow/
// and Ralf S. Engelschall http://trainofthoughts.org/

// ========================================================= */

(function($) {

    $.fn.gallery = function(options) {
        return this.each(function() {   
            $.gallery(this, options);
        });
    };

    $.gallery = function(container) {
        var settings = {
            'speed':            'slow',
            'timeout':          4000,
            'runningclass':     'gallery',
            'loop':				true
        };
        
        var elements = $(container).children();
        
        if (elements.length > 1) {
            $(container).css('position', 'relative').addClass(settings.runningclass);
            for (var i = 0; i < elements.length; i++) {
                $(elements[i]).css('z-index', String(elements.length-i)).css('position', 'absolute').hide();
            };
            
            setTimeout(function() {
                $.gallery.next(elements, settings, 1, 0);
            }, settings.timeout);
            $(elements[0]).show();
		}
    };

    $.gallery.next = function(elements, settings, current, last) {
        $(elements[last]).fadeOut(settings.speed);
        $(elements[current]).fadeIn(settings.speed, function() {
			$.gallery.removeFilter($(this)[0]);
		});
        
        if (settings.loop === true) {
	        if ((current + 1) < elements.length) {
	            current = current + 1;
	            last = current - 1;
	        } else {
	            current = 0;
	            last = elements.length - 1;
	        }
        } else {
	        if ((current + 1) < elements.length) {
	            current = current + 1;
	            last = current - 1;
	        }
        }
        
        setTimeout((function() {
            $.gallery.next(elements, settings, current, last);
        }), settings.timeout);
    };
    
    $.gallery.removeFilter = function(element) {
		if(element.style.removeAttribute){
			element.style.removeAttribute('filter');
		}
    };

})(jQuery);
