﻿//Megateaser - Stuart Johnston 03/10/11
(function ($) {

    $.fn.megateaser = function (o) {

        //hide all teasers
        $(o.teaser).hide();

        //Show the first teaser
        $("" + o.teaser + ":first").show();

        //the main event to attach and show a large background image
        $(o.trigger).bind("click", function () {
            $("#megaTeaserController li a").removeClass("current");
            $(this).addClass("current");
            $(o.teaser).hide();
            var image = $(this).next(".teaser").find("img").attr("src");
            $(this).next(".teaser").fadeIn(1500);
            $(o.target).attr("style", "background-image:url(" + image + "); display: none;").fadeIn(1500, function () { moveImage(image) });
            return false;
        });

        //add the background image to the containing div to allow a cross fade
        function moveImage(image) {
            $(o.target).parent().attr("style", "background-image:url(" + image + ");");
        };

        //If the user interacts with the rotator controls stop the rotator
        $(o.trigger).bind("touchstart focus", function () {
            clearInterval(interval);
        });

        //Make the large background image rotate
        var n = 1;
        var numberOfTeasers = $("#megaTeaserController li").length;
        var interval = setInterval(function () { rotate() }, 8000);

        //Start the rotate
        rotate();

        //Main rotate function iterates and fires click events
        function rotate() {
            $("#megaTeaserController li > a").removeClass("current");
            $("#megaTeaserController li:nth-child(" + n + ") > a").trigger("click");
            //If less than total number of teasers then carry on - if not then go back to 1 and start again
            (n < numberOfTeasers) ? n = n + 1 : n = 1;
        };

        //If someone appears to be a keyboard user disable the rotate (tab and right arrow users)
        $('*').live('keypress', function (e) {
            if (e.keyCode == 9 || e.keyCode == 39) {
                clearInterval(interval);
            }
        });

        return this;
    };


})(jQuery);
