﻿/*
* Andrew J Wright : 22 Nov 2010
*
*/

(function ($) {

    $.ioFlow = function (options) {
        var opts = $.extend({}, $.ioFlow.defaults, options),
			cur = 0,
			timer,
			active = false;

        if (opts.slideDeck === '') return false;

        var slides = $(opts.slideDeck),
			count = slides.length;

        var curtain = $('<div id="ioFlow-curtain"/>');

        slides.parent().append(curtain);

        /*
        * move the slideshow to the index passed
        */
        var _toIndex = function (index) {
            if (index >= 0 && index < count) { /* within range */
                active = true;
                $('#ioFlow-curtain').fadeIn(opts.aniDuration, opts.easing, function (e) {
                    slides.hide();
                    $(slides[index]).show(1);
                    if (opts.controls !== '') {
                        $(opts.controls)
						.removeClass('selected')
						.eq(index)
						.addClass('selected');
                    }
                }).fadeOut(opts.aniDuration, opts.easing, function () {
                    active = false;
                    dotimer();
                });
            }
        };

        /* //////////////// */
        var doPrev = function () {
            if (!active) {
                cur--;
                cur = cur < 0 ? (cur + count) : cur;
                _toIndex(cur);
            }
        };
        /* //////////////// */
        var doNext = function () {
            if (!active) {
                cur++;
                _toIndex(cur % count);
            }
        };
        var doIndex = function (x) {
            if (!active) {
                cur = x;
                _toIndex(cur);
            }
        };
        /* //////////////// */
        var dotimer = function (x) {
            if (timer != null)
                clearInterval(timer);

            timer = setInterval(function () {
                doNext();
            }, opts.showtime);

        }

        if (opts.controls !== '') {
            /* //////////////// */
            $(opts.controls).each(function (i) {
                $(this).click(function (e) {
                    e.preventDefault();
                    doIndex(i);
                });
            });
        }

        _toIndex(0); // start it off!

        return this; // allow for chaining
    };


    $.ioFlow.defaults = {
        slideDeck: '',
        controls: '',
        easing: "swing",
        aniDuration: 800,
        showtime: 5000
    };

})(jQuery);

$(function () {
    $.ioFlow({
        slideDeck: '.tierOneAds > a',
        controls: '.tierOneAds > .controls a'
    });
});
