/*
 * Base on jQuery Cycle Lite Plugin
 */

(function($){ 
$.fn.html5Gallery = function(options) {
	return this.each(function() {
        options = options || {};
		
		var $cont = $(this);
		var $slides = $cont.children();
        var els = $slides.get();
		
		var opts = $.extend({}, $.fn.html5Gallery.defaults, options || {});
		
		opts.before = opts.before ? [opts.before] : [];
        opts.after = opts.after ? [opts.after] : [];
        opts.after.unshift(function(){ opts.busy=0; });
				
		var first = 0;
		
		opts.slideCount = els.length;
        opts.currSlide = first;
        opts.nextSlide = 1;

		var fx = "fx_"+opts.fx;
		
		$(this).addClass(fx);

		
		$.fn.html5Gallery.init(els, opts);
		
		// fire artificial events
	    var e0 = $slides[first];
	    if (opts.before.length)
	        opts.before[0].apply(e0, [e0, e0, opts]);
	    if (opts.after.length > 1)
	        opts.after[1].apply(e0, [e0, e0, opts]);
		
 		if (opts.timeout)
            this.cycleTimeout = setTimeout(function() {
                $.fn.html5Gallery.go(els,opts)
            }, opts.timeout + (opts.delay||0));
	});
}

$.fn.html5Gallery.init = function(els, opts){		
	$(els[opts.currSlide]).removeClass("first_slide").addClass("current_slide");
	$(els[opts.nextSlide]).addClass("incoming_slide");
}

$.fn.html5Gallery.go = function(els, opts) {

	var p = els[0].parentNode, curr = els[opts.currSlide], next = els[opts.nextSlide];
	
	$(p).find(".outgoing_slide").removeClass("outgoing_slide");	
	$(curr).removeClass("current_slide").addClass("outgoing_slide");
	$(next).removeClass("incoming_slide").addClass("current_slide");
	
	if (opts.before.length)
        $.each(opts.before, function(i,o) { o.apply(next, [curr, next, opts]); });
    var after = function() {
        $.each(opts.after, function(i,o) { o.apply(next, [curr, next, opts]); });
    };
	
	var roll = (opts.nextSlide + 1) == els.length;
    opts.nextSlide = roll ? 0 : opts.nextSlide+1;
    opts.currSlide = roll ? els.length-1 : opts.nextSlide-1;
		
	next = els[opts.nextSlide];
	$(next).addClass("incoming_slide");
	
	if (opts.timeout)
        p.cycleTimeout = setTimeout(function() { $.fn.html5Gallery.go(els,opts) }, opts.timeout + (opts.delay||0));
	
}

$.fn.html5Gallery.defaults = {
	fx: "fade",
	before:        null, 
    after:         null,
    timeout:       2000,
	delay:         0 
};

})(jQuery);
