// The document ready event.

var Rotator;

$(function () {
    Rotator = function (curContentID, random, selectBoxID, autoRotate) {
        // Define fields
        this.curContentID = curContentID;
        this.content = new Array();
        this.selectBox = $("#" + selectBoxID);
        this.autoRotate = autoRotate;
        this.random = false;
        this.preventRotation = false;
        this.curTimer = null;
        this.doneLoading = false;

        var rotator = this;

        this.init = function (id, content1ID, content2ID, duration) {
            var element1 = $("#" + content1ID);
            var element2 = $("#" + content2ID);

            // Setup the mouse over and out event for
            // primary panel to prevent rotation on mouse over.
            element1.mouseover(function () { rotator.preventRotation = true; });
            element1.mouseout(function () { rotator.preventRotation = false; });

            // Setup the mouse over and out event for
            // secondary panel to prevent rotation on mouse over.
            element2.mouseover(function () { rotator.preventRotation = true; });
            element2.mouseout(function () { rotator.preventRotation = false; });

            // Setup the mouse over and out event for
            // the square changes to prevent rotation on mouse over.
            this.selectBox.children().mouseover(function () { rotator.preventRotation = true; });
            this.selectBox.children().mouseout(function () { rotator.preventRotation = false; });

            // Setup the square select change event.
            this.selectBox.children().click(function () {
                // Clear the current timeout to
                // prevent any sudden rotations.
                clearTimeout(rotator.curTimer);

                // Make sure that the mouseover
                // event do not prevent the rotation.
                rotator.preventRotation = false;

                // Stop all animations.
                $("#" + id).children().stop(true, true);

                // Get the id of the clicked square.
                rotator.curContentID = $(this).attr("id").match(/\d+$/)[0];

                // Rotate the image depending on the current visiblity.
                if (element1.is(":visible"))
                    rotator.ensureImageLoad(element1, element2);
                else
                    rotator.ensureImageLoad(element2, element1);

                // Display a loading sequence - wait for a second, the content may be in
                // the browser cache and there is no need to display a loading sequence.
                setTimeout(function () { rotator.ShowLoading($(this)); }, 1000);
            });

            // Error handling.
            window.onerror = function (errorMsg) {
                // Internet Explorer throws a error eventhough the script works.
                // Hide this error from the user, but show all other cases.
                if (errorMsg.indexOf('start.0') > 0)
                    return true;
                else
                    return false;
            }

            // Set the first timeout, when the first roteter content is loaded.
            $(window).load(function () {
                // Set the first rotation
                // if auto rotate is true.
                if (rotator.autoRotate)
                    setTimeout(function () {
                        rotator.rotateContent($("#" + content1ID), $("#" + content2ID));
                    }, duration);
            });

        }

        // Loading handling.
        this.ShowLoading = function (pnlContentSquare) {
            // If the panel is loading (images),
            // then animate the selected content square.
            if (!this.doneLoading) {
                // Animate background-color change.
                pnlContentSquare.stop().animate({ backgroundColor: "rgb(230,235,239) /* pantone 295 C 10% */" }, "normal", function () {
                    // Animate background-color change.
                    pnlContentSquare.stop().animate({ backgroundColor: "rgb(5,55,98) /* pantone 295 C */" }, "normal", function () {
                        // Repeat.
                        rotator.ShowLoading(pnlContentSquare);
                    });
                });
            }
        }

        this.rotateContent = function (element1, element2) {
            // If the rotator is random, then
            // generate a random content id.
            if (this.random) {
                // Save the current content id for compare.
                var compareContentID = this.curContentID;

                // Generate a random id until the id is different from the current content id.
                while (compareContentID == this.curContentID)
                    this.curContentID = Math.floor(Math.random() * this.content.length);
            }
            else {
                // If the rotator is not random, then
                // just change to the next content id.
                this.curContentID = (this.curContentID + 1) % this.content.length;
            }

            // Rotate the image depending on the current visiblity.
            if (element1.is(":visible"))
                this.ensureImageLoad(element1, element2);
            else
                this.ensureImageLoad(element2, element1);
        }

        this.ensureImageLoad = function (pnlFadeOut, pnlFadeIn) {
            // Set the loading status to false = nothing is done.
            this.doneLoading = false;

            // Set the panel content.
            pnlFadeIn.html(this.content[this.curContentID][0]);

            // Count the images in the panel.
            var imgInPanel = pnlFadeIn.children("img").length;

            // If any images exist, then we need for
            // them to load before making the rotation.
            if (imgInPanel > 0) {
                // Create a variable for loaded image count.
                var imgLoaded = 0;

                // Function that trigger every image is loaded.
                pnlFadeIn.children("img").load(function () {
                    // Add one to count.
                    imgLoaded++;

                    // Verify that all images are loaded.
                    if (imgLoaded == imgInPanel) {
                        // We are done loading.
                        rotator.doneLoading = true;

                        // Rotate the panels.
                        rotator.rotatePanel(pnlFadeOut, pnlFadeIn);
                    }
                })
                // If the images is in the browser cache, they do not trigger the load event - this make sure it does!
                .each(function () { if (this.complete) $(this).trigger("load"); });
            }
            else
                this.rotatePanel(pnlFadeOut, pnlFadeIn)
        }

        this.rotatePanel = function (pnlFadeOut, pnlFadeIn) {
            if (this.preventRotation == true)
                this.curTimer = setTimeout(function () { rotator.rotatePanel(pnlFadeOut, pnlFadeIn); }, 4000);
            else {
                // Clear the current timeout to
                // prevent any sudden rotations.
                clearTimeout(this.curTimer);

                // Change the squares.
                this.selectBox.children().attr("class", "rotator_select");
                this.selectBox.children("[id$=ID" + this.curContentID + "]").attr("class", "rotator_selected");

                // Fade out the panel.
                pnlFadeOut.fadeOut('normal', function () {
                    // Fade in the panel when
                    // the other panel is hidden.
                    pnlFadeIn.fadeIn('normal', function () {
                        // Set timeout to next rotation, when the current
                        // panel is visible, but only if the auto rotate is true.
                        if (rotator.autoRotate == true)
                            rotator.curTimer = setTimeout(function () {
                                rotator.rotateContent(pnlFadeOut, pnlFadeIn);
                            }, rotator.content[rotator.curContentID][1]);
                    });
                });
            }
        }
    }
});
