﻿//PARAMETERS

//this sets the total number of spinners
//this number should match the number of "ul_promobox" lists
//defined in the markup
var numSpinners = 3;
//the root class name of the promo box list, by default it is "ul_promobox". This value requires
//a numeric suffix. For example, in this case, the first <ul> tag should have class="ul_promobox1"
var promoBoxListRootClassName = "ul_promobox";
//the root class name of the promo box image, by default it is "tc-promos-content-img". This does not
//need a numeric suffix at the end of the class name.
var promoBoxImageRootClassName = "tc-promos-content-img";
//the ID of the container that should cause the machine to pause 
//when hovered over
var pauseContainerID = "tc-promos-content";
//sets the number of times the list should be repeated for each subsequent spinner.
//increase this number to cycle through more items before the spinner stops
var imageListMultiplier = 3;
//height, in pixels of each promo image
var promoImageHeight = 80;
//this sets the amount of time (ms) between each spinner stop
var stopInterval = 1500;
//this controls the period of time (ms) between each "lever pull". Note that this
//does not take into account the amount of time it takes for the spinners to complete
//their spinning
var rotationInterval = 8000;
//sets whether the animation should start playing automatically or not
var autoPlay = true;
//tracks whether or not the machine is spinning
var isSpinning = false;
//tracks if the page has been loaded yet
var pageIsLoaded = false;
//tracks state of focus
var isWindowFocused = true;
var firstSpin = true;
var FirstUnfocused = false;

function onBlur() {
    isWindowFocused = false;
    //document.body.className = 'blurred';
};
function onFocus() {
    isWindowFocused = true;
    //document.body.className = 'focused';
};

if (/*@cc_on!@*/false) {
    document.onfocusin = onFocus;
    document.onfocusout = onBlur;
} else {
    window.onfocus = onFocus;
    window.onblur = onBlur;
}

//*******************************************************************************
//Is home page -- defaults to false
var isHomePage = false;
var ForcedFlag = false;
var SpinnerToForce = -1;
if (location.pathname == "/" || location.pathname == "/default.aspx") {
    isHomePage = true;
    time = new Date();
    SpinnerToForce = ((time.getSeconds()) % numSpinners);
}   
//*******************************************************************************

//END PARAMETERS
var imageList = null;
var unshownImageList = null;
//some browsers do not have the indexOf method for Arrays. If that
//is the case, then create it
if (!Array.indexOf) {
    Array.prototype.indexOf = function(obj) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == obj) {
                return i;
            }
        }
        return -1;
    }
}

$(document).ready(function() {
    Init();
});
var timerID = null;

//initializes the spinner control
function Init() {
    imageList = GetImageList();
    unshownImageList = GetImageList();
    GenerateListContent();

    //wait until the page completes loading before starting the 
    //animation
    //    $(window).load(function() {
    if (autoPlay) {
        GenerateNextImageSet();
        //Play();
    }
    pageIsLoaded = true;
    $("#" + pauseContainerID).mouseenter(function() { Stop(); });
    $("#" + pauseContainerID).mouseleave(function() { Play(); });
    //    });
}

//stops playback of the animation. note that this will not pause the animation
//if it is in the middle of a spin, it will let the animation complete then stop
function Stop() {
    window.clearInterval(timerID);
}

//starts playback of the animation
function Play() {
    //timerID = window.setTimeout("GenerateNextImageSet()", rotationInterval);
}

//check if the pass in array has at least enough unique images (amount of numSpinners), return true if it is unique enough
function EnoughUniqueness(array) {
    if (array && array.length >= numSpinners) {
        tempArray = new Array();

        for (i = 0; i < array.length; i++) {
            if (tempArray.indexOf(array[i]) < 0) {

                tempArray.push(array[i]);

                if (tempArray.length == numSpinners)
                    return true;

            }

        }

    }
    else {
        return false;
    }

    if (tempArray.length >= numSpinners) {
        return true;
    }
    else
        return false;

}

//generates and displays the next rotation of images   unshownImageList.length <= numSpinners
function GenerateNextImageSet() {
    //if we've run out of images to display, repopulate the list
    //if the images left has to be more than less than spinner number, or else there is the chance of all are duplicate images
    if (firstSpin && !(isWindowFocused)) {
        isWindowFocused = true;
        FirstUnfocused = true;
    }

    if (isWindowFocused) {

        if (firstSpin) {
            firstSpin = false;
            if (FirstUnfocused) {
                isWindowFocused = false;
            }
        }

        if (!unshownImageList ||
         !EnoughUniqueness(unshownImageList)) {
            unshownImageList = GetImageList();
        }

        var selectedImages = new Array();
        var selectedIndicies = new Array();
        var removeIndicies = new Array();

        //loop over and generate the
        for (i = 0; i < numSpinners; i++) {
            //generate a random number based off of the unused images left
            var currIndex;
            
            if (isHomePage && ForcedFlag == false && i == SpinnerToForce) {
                currIndex = 0;
                //alert();
                
                ForcedFlag = true;
            }
            else {
                var rand = Math.random();
                currIndex = Math.floor(rand * unshownImageList.length);
            }
           
            //add the name of this image
            var currImageObject = unshownImageList[currIndex];
            //if the selectedImages already has the same image as the currimage, then increase i to loop agagin until find different image
            if (selectedImages.indexOf(currImageObject) < 0) {
                selectedImages.push(currImageObject);

                
                //add the index of this item in the standard order list
                selectedIndicies.push(imageList.indexOf(currImageObject));
                //add this index to a list of indicies to be removed if it isn't already present. we only
                //mark them now, so there is a possibility of duplicates to be shown, like a real slot machine
                if (removeIndicies.indexOf(currIndex) < 0) {
                    removeIndicies.push(currIndex);
                }
            }
            else {
                i--;
            }

        }

        removeIndicies.sort();
        //remove images from the unshown list - they will now be displayed
        for (i = removeIndicies.length - 1; i >= 0; i--) {
            var currIndex = removeIndicies[i];
            RemoveArrayElement(unshownImageList, currIndex);
        }
        if (numSpinners > 0)
            isSpinning = true;
        for (i = 0; i < numSpinners; i++) {

            if (i != (numSpinners - 1)) {
                ShowImage(i, selectedIndicies[i]);
            }
            //run the SpinningComplete method after the animation completes if this is the last spinner
            else {
                ShowImage(i, selectedIndicies[i], function() { SpinningComplete(); });
            }
        }
    }
}

//displays an image at the specified index for the specified promo box
function ShowImage(promoBoxIndex, imageIndex, completeFunction) {
    var promoBox = GetPromoBoxByIndex(promoBoxIndex);
    MoveToInitialIndex(promoBoxIndex, promoBox);

    var nextImagePos = GetFirstImagePosition(promoBoxIndex, imageIndex);
    var duration = (promoBoxIndex + 1) * stopInterval;
    promoBox.animate({ "margin-top": nextImagePos + "px" }, duration, null, completeFunction);
}

//runs after the last spinner completes
function SpinningComplete() {
    isSpinning = false;
}

//used for manually spinning the machine, by the user
function PullLever() {
    if (!isSpinning && pageIsLoaded) {
        Stop();
        GenerateNextImageSet();
        Play();
    }
}
// testing hide movie on movie push
function HideTheMovie() { $("#tc-body-content").fadeToggle(400); }

//gets the promo box by index. 0=promobox1, 1=promobox2, etc
function GetPromoBoxByIndex(promoBoxIndex) {
    var boxIdIndex = promoBoxIndex + 1;
    return $("." + promoBoxListRootClassName + boxIdIndex);
}

//moves the margin-top property to the initial index of the image.
function MoveToInitialIndex(promoBoxIndex, promoBox) {
    if (!promoBox)
        promoBox = GetPromoBoxByIndex(promoBoxIndex);

    var currPos = promoBox.css("margin-top");
    var firstImagePos = GetLastImagePosition(promoBoxIndex);
    promoBox.css("margin-top", (firstImagePos) + "px");
}

//Gets the last occurance of the image within the list of images
function GetLastImagePosition(promoBoxIndex, imageIndex, promoBox) {
    var boxIdIndex = promoBoxIndex + 1;
    var imageSetIndex = boxIdIndex * imageListMultiplier;

    if (!promoBox)
        promoBox = GetPromoBoxByIndex(promoBoxIndex);

    if (!imageIndex && imageIndex != 0) {
        var currPos = promoBox.css("margin-top");
        var firstImagePos = Number(currPos.replace("px", "")) % (promoImageHeight * imageList.length)
        imageIndex = -(firstImagePos / promoImageHeight);
    }

    var lastImagePos = -((imageSetIndex - 1) * (imageList.length * promoImageHeight) + (imageIndex * promoImageHeight));
    return lastImagePos;
}

//Gets the first occurance of the image within the list of images
function GetFirstImagePosition(promoBoxIndex, imageIndex, promoBox) {
    if (!promoBox)
        promoBox = GetPromoBoxByIndex(promoBoxIndex);

    if (!imageIndex && imageIndex != 0) {
        var currPos = promoBox.css("margin-top");
        var firstImagePos = Number(currPos.replace("px", "")) % (promoImageHeight * imageList.length)
        imageIndex = -(firstImagePos / promoImageHeight);
    }

    var firstImagePos = -(imageIndex * promoImageHeight);
    return firstImagePos;
}

//currently used only for testing. Moves all spinners to the last index
//of the currently displayed image in the list
function MoveAllToInitialIndex() {
    for (i = 0; i < numSpinners; i++) {
        MoveToInitialIndex(i);
    }
}

//gets an array of all image names defined in the spinner control
function GetImageList() {
    var array = new Array();
    var promoBox1 = GetPromoBoxByIndex(0);
    promoBox1.find("img." + promoBoxImageRootClassName).each(function() { array.push($(this).attr("src")); });
    return array;
}

//populates each spinner with the necessary duplcate sets of images
//needed
function GenerateListContent() {
    var promoBox1 = GetPromoBoxByIndex(0);
    var masterListItems = promoBox1.find("li");
    for (i = 0; i < numSpinners; i++) {
        var currPromoBox = GetPromoBoxByIndex(i);
        for (x = 0; x < (i + 1) * imageListMultiplier; x++) {
            masterListItems.clone().appendTo(currPromoBox);
        }
    }
}

//removes an element from an array at the specified index
function RemoveArrayElement(array, index) {
    if (array.length > index) {
        array.splice(index, 1);
    }
}
function DocumentReadyPromotions() {
    $(".tc-promos-movie-close").click(function() { show_hide_Image(mediaBlockArray, 0); BodyContentMax() });
}

