﻿YUI().use('node', 'anim', 'event', function (Y) {
    var swooshCurrent = 1;
    var swooshPrevious = 0;
    var swooshDelay = 2.5;
    var swooshSpeed = .5;
    var swooshImageCount = 0;
    var imagesLoaded = 0;
    var swooshFadeInSpeed = .2;

    function init() {
        swooshImageCount = Y.all(".swooshViewer .swooshImages img").size();
        Y.all(".swooshViewer .swooshImages img").each(function (n) {
            var image = Y.Node.create('<img>');
            image.on('load', function (evt) {
                imagesLoaded++;
                if (imagesLoaded == swooshImageCount) {
                    swooshStart();
                }
            });
            image.set('src', n.get("src"));
        });
    }

    function swooshStart() {
        Y.all(".swooshViewer .swooshImages img").each(function (n) {
            n.setStyle("display", "inline");
            n.setStyle('opacity', 0.3);
        });
        Y.all(".swooshViewer .swooshImages img").item(1).setStyle('opacity', 1);

        //Y.one(".swooshViewer .swooshLoader").setStyle("display", "none");
        //swooshNext();

        var animShow = new Y.Anim({
            node: '.swooshImages',
            to: { opacity: 1 },
            duration: swooshFadeInSpeed
        });
        animShow.run();

        var animShow2 = new Y.Anim({
            node: '.swooshLoader',
            to: { opacity: 0 },
            duration: swooshFadeInSpeed
        });
        animShow2.run();

        Y.later(swooshSpeed * 1000, this, function () {
            swooshNext();
            Y.one(".swooshViewer .swooshLoader").setStyle("display", "none");
        });
    }

    function swooshNext() {
        //alert(swooshImageCount);
        swooshPrevious = swooshCurrent;

        if (swooshCurrent < swooshImageCount - 2) {
            swooshCurrent++;
        } else {
            swooshCurrent = 1;
        }
        Y.later(swooshDelay * 1000, this, function () {
            swooshTo(swooshCurrent);
            swooshNext();
        });
    }

    function swooshTo(n) {

        // fade out current
        var fadeOut = new Y.Anim({
        node: Y.all(".swooshViewer .swooshImages img").item(swooshPrevious),
        to: { opacity: 0.3 },
        easing: Y.Easing.easeOutStrong,
        duration: swooshSpeed
        });
        fadeOut.run();

        var animShow = new Y.Anim({
            node: '.swooshImages',
            to: { left: (-n * 626 + 230) + "px" },
            easing: Y.Easing.easeOutStrong,
            duration: swooshSpeed
        });
        animShow.run();

        // fade in new
        var fadeIn = new Y.Anim({
            node: Y.all(".swooshViewer .swooshImages img").item(swooshCurrent),
            to: { opacity: 1 },
            easing: Y.Easing.easeOutStrong,
            duration: swooshSpeed
        });
        fadeIn.run();
    }

    Y.on("domready", init);
});
