﻿$(document).ready(function () {
    var windowWidth = $(window).width();
    var globalSpotlightHeight = $('#spotlightWrapper').height();
    var globalSiteHeight = $('#site').height();
    var globalFooterHeight = $('#globalFooter').height();
    var totalSiteHeight = globalSpotlightHeight + globalSiteHeight + globalFooterHeight;

    //Positions "#wallpaper"
    $('#wallpaper').css({
        'width': windowWidth,
        'height': totalSiteHeight,
        'position': 'absolute',
        'z-index': '1'
    });

    //Positions "#globalWrapper"
    $('#globalWrapper').css({
        'width': windowWidth,
        //'height': totalSiteHeight,
        'position': 'absolute',
        'z-index': '2'
    });

    //Overwriting fallbacks from "wallpaperRotater.css" (JS is enabled by the user)
    $('.wallpaperSelector').css('display', 'block');
    $('#wallpaper').css('display', 'block');
});

//Tooltip
function ShowTooltip(item) {
    var TTwidth = $(item).children('.tooltip').width();
    var TTcalcPos = (72 - TTwidth) / 2;
    $(item).children('.tooltip').css({
        'width': TTwidth,
        'display': 'inline-block',
        'position': 'absolute',
        'left': TTcalcPos + 'px',
        'top': '-37px'
    });
}
function HideTooltip(item) {
    $(item).children('.tooltip').css('display', 'none');
}


var fadeTime = 1800;

//Move Thumb frame
var movement = 92;
function moveFrame(itemNo) {
    var bodyId = $('body').attr('id');
    if (bodyId == "home") {
        $('.thumbIndicator').css('display', 'block').animate({ left: 186 + (itemNo * movement) + 'px' }, fadeTime);
    } else {
        $('.thumbIndicator').css('display', 'block').animate({ left: 296 + (itemNo * movement) + 'px' }, fadeTime);
    }
}

//Rotate Wallpaper
var transisting = false;
var currentWallpaperNo = 0;
function wallpaperChanged(changedToItemNo) {
    var cur = $('#wallpaper img:eq(' + currentWallpaperNo + ')');
    var next = $('#wallpaper img:eq(' + changedToItemNo + ')');
    cur.removeClass('active').css('display', 'none');
    next.removeClass('next').addClass('active');
    currentWallpaperNo = changedToItemNo;

    $('#setText').html(items[changedToItemNo].Text);
    $('.setLogo').attr("src", items[changedToItemNo].LogoUrl);
    $('#setText').css('visibility', '');
    $('.setLogo').css('visibility', '');
    transisting = false;
}

function changeWallpaper(itemNo) {
    if (currentWallpaperNo != itemNo) {
        transisting = true;
        var cur = $('#wallpaper img:eq(' + currentWallpaperNo + ')');
        var next = $('#wallpaper img:eq(' + itemNo + ')');

        $('#setText').css('visibility', 'hidden');
        $('img.setLogo').css('visibility', 'hidden');

        cur.addClass('active').css('opacity', '1').css('display', 'block');
        next.addClass('next').css('opacity', '1').css('display', 'block');
        cur.animate({ 'opacity': 0 }, fadeTime, function () { wallpaperChanged(itemNo); });
    }
}

//Rotate Spotlight
function spotlightChanged(changedToItemNo) {
    var cur = $('.spotlightFade .spotlightContent:eq(' + currentSpotlightNo + ')');
    var next = $('.spotlightFade .spotlightContent:eq(' + changedToItemNo + ')');
    if (currentSpotlightNo >= 0) cur.removeClass('active').css('display', 'none');
    next.addClass('active').removeClass('next');
    currentSpotlightNo = changedToItemNo;
}

var currentSpotlightNo = -1;
function changeSpotlight(itemNo) {

    if (currentSpotlightNo != itemNo) {
        var cur = $('.spotlightFade .spotlightContent:eq(' + currentWallpaperNo + ')');
        var next = $('.spotlightFade .spotlightContent:eq(' + itemNo + ')');
        if (currentSpotlightNo >= 0) {
            cur.addClass('active').css('opacity', '1').css('display', 'block');
            next.addClass('next').css('opacity', '0').css('display', 'block');
        }
        else {
            next.addClass('active').css('opacity', '0').css('display', 'block');
        }
        if (currentSpotlightNo >= 0) cur.animate({ 'opacity': 0 }, fadeTime);
        next.animate({ 'opacity': 1 }, fadeTime, function () { spotlightChanged(itemNo); });
    }
}

// Define Flash-Set object   
function MainstageFlashItem() {
    this.BackgroundImage = "";
    this.ThumbnailImage = "";
    this.ThumbnailImageAltText = "";
    this.LinkUrl = "";
    this.NoFlashImage = "";
    this.FlashUrl = "";
    this.FlashParams = "";
    this.FlashVars = "";
    this.MovieCoverUrl = "";
    this.MovieLabel = "";
    this.MovieLink = "";
    this.LogoUrl = "";
    this.LogoPosition = 0;
    this.Text = "";
    this.TextPosition = 0;

    this.Init = function (BackgroundImage, ThumbnailImage, ThumbnailImageAltText, LinkUrl, NoFlashImage, FlashUrl, FlashParams, FlashVars
                               , MovieCoverUrl
                               , MovieLabel
                               , MovieLink
                               , LogoUrl
                               , LogoPosition
                               , Text
                               , TextPosition) {
       this.BackgroundImage = BackgroundImage;
       this.ThumbnailImage = ThumbnailImage;
       this.ThumbnailImageAltText = ThumbnailImageAltText;
       this.LinkUrl = LinkUrl;
       this.NoFlashImage = NoFlashImage;
       this.FlashUrl = FlashUrl;
       this.FlashParams = FlashParams;
       this.FlashVars = FlashVars;

       this.MovieCoverUrl = MovieCoverUrl;
       this.MovieLabel = MovieLabel;
       this.MovieLink = MovieLink;
       this.LogoUrl = LogoUrl;
       this.LogoPosition = LogoPosition;
       this.Text = Text;
       this.TextPosition = TextPosition;

    };
}

// Vars that should be possible to manipulate from external scripts
var LoopSets = true;
var rotateTime = 8000;
var rotateWaitTime = 1000;


// Internal used Vars
var expectedNumAssets = 0;
var numLoaded = 0;
var currentSetnum = -1;
var items = new Array();
var UseFlash = true;
var currentDisplaySet = -1;
var TimerId = -1;
var SetStates = new Array(10);


// Get reference to Fash-object
function getFlashObject() {
    return swfobject.getObjectById("flashContent");
}

// Handle shift of background image and sliding frame over thumbnails
function ShiftToNextImages(currentDisplaySet) {
    moveFrame(currentDisplaySet);
    changeWallpaper(currentDisplaySet);
}

// Handle shift to other flash and initiate images
function ShiftUsingFlash(currentDisplaySet, force) {
    var flashShiftOk = true;
    if (!force) {
        flashShiftOk = getFlashObject().isReady(); // || (currentDisplaySet == 0);  //showContent(currentDisplaySet);
    }
    else {
        //getFlashObject().forceShowContent(currentDisplaySet);
        flashShiftOk = true;
    }

    if (flashShiftOk) {
        ShiftToNextImages(currentDisplaySet);
        changeSpotlight(currentDisplaySet);
        getFlashObject().showContent("" + currentDisplaySet, fadeTime);
    }

    return flashShiftOk;
}

// Handle shift to other images and mainstage image
function ShiftUsingJS(currentDisplaySet, force) {
    ShiftToNextImages(currentDisplaySet);
    changeSpotlight(currentDisplaySet);
    return true;
}

// Handle shift to other flash-set
function ShiftToSet(currentDisplaySet, force) {
    if (UseFlash) {
        return ShiftUsingFlash(currentDisplaySet, force);
    }
    else {
        return ShiftUsingJS(currentDisplaySet, force);
    }
}

// Handle shift to other next flash-set
function DisplayNextSet() {
    if (LoopSets == true && currentDisplaySet == items.length - 1) {
        currentDisplaySet = -1;
    }
    if (currentDisplaySet < items.length - 1) {
        if (currentDisplaySet < currentSetnum) {
            currentDisplaySet++;
            var Timeout;
            if (SetStates[currentDisplaySet] == 1) {
                // Ok - Next set ready - try displaying it...
                if (ShiftToSet(currentDisplaySet, false)) {
                    Timeout = rotateTime;
                }
                else {
                    // Ok - Flash was not ready to shift to next set - wait 1 sec. and try again !
                    currentDisplaySet--;
                    Timeout = rotateWaitTime;
                }
            }
            else {
                // tried to shift to set that is not ready yet...
                currentDisplaySet--;
                Timeout = rotateWaitTime;
            }
            TimerId = setTimeout("DisplayNextSet();", Timeout);
        }
    }
}

// When loadset is loaded/cached, elements is shown and inserted in containers
function ActivateLoadSet(loadSet) {
    SetStates[currentSetnum] = 1;
    var thumbTag = "";
    thumbTag += "<li class=\"liClass\" onclick=\"ManualShiftToSet(" + currentSetnum + ");\" onmouseover=\"ShowTooltip(this);\" onmouseout=\"HideTooltip(this);\" >";
    thumbTag += "<img src=\"" + loadSet.ThumbnailImage + "\">";
    thumbTag += "<div class=\"tooltip\"><span class=\"label\">" + loadSet.ThumbnailImageAltText + "<i></i></span><span class=\"decor\"></span></div>";

    $('#thumbs').append(thumbTag);

    var wallpTag = "";
    wallpTag += "<img class=\"pngFix\" src=\"" + loadSet.BackgroundImage + "\">";
    $('#wallpaper').append(wallpTag);
    var first = (currentSetnum == 0);
    var display = ((first) ? "block" : "none");


    var linkTag = "";
    if (!UseFlash) {
        linkTag += "<a href=\"" + loadSet.LinkUrl + "\" class=\"spotlightContent\" style=\"display:" + display + ";\">";
        linkTag += "<img class=\"spotlightImg pngFix\" src=\"" + loadSet.NoFlashImage + "\">";
        linkTag += "<img class=\"spotlightLogo pngFix " + loadSet.LogoPosition + "\" src=\"" + loadSet.LogoUrl + "\">";
        linkTag += "<span class=\"spotlightText pngFix " + loadSet.TextPosition + "\">" + loadSet.Text + "</span>";
        if (loadSet.MovieCoverUrl != "") {
            linkTag += "<img class=\"spotlightMovieCover\" title=\"" + loadSet.MovieLabel + "\" onclick=\"" + "document.location = '" + loadSet.MovieLink + "';return false;" + "\" src=\"" + loadSet.MovieCoverUrl + "\"/>";
        }

        linkTag += "</a>";
    }
    else {
        linkTag += "<div class=\"spotlightContent\" style=\"display:" + display + ";\">";
        linkTag += "<a href=\"" + loadSet.LinkUrl + "\" class=\"spotlightLogo " + loadSet.LogoPosition + "\">";
        linkTag += "<img src=\"" + loadSet.LogoUrl + "\">";
        linkTag += "</a>";
        linkTag += "<a href=\"" + loadSet.LinkUrl + "\" class=\"spotlightText " + loadSet.TextPosition + "\">";
        linkTag += "<span>" + loadSet.Text + "</span>";
        linkTag += "</a>";
        linkTag += "</div>";
    }
    $('.spotlightFade').append(linkTag);

}

// Event that fires for each asset, when loaded
function AssetLoaded() {
    numLoaded++;
    if (numLoaded >= expectedNumAssets) {
        ActivateLoadSet(items[currentSetnum]);
        if (currentSetnum == 0)
            DisplayNextSet();
        LoadNextSet();
    }
}

function FlashLoaded() {
    AssetLoaded();
}


function ImgLoaded(img) {
    AssetLoaded();
}

// Event that fires for each asset, when Failed...
function AssetFailed() {
    // To avoid missing loadsets - simulate correct loading...
    AssetLoaded();
}


// Load/Cache asset
function LoadAsset(Url) {
    var objAsset = new Image();
    objAsset.onload = function () { ImgLoaded(Url); }
    objAsset.onabort = AssetFailed;
    objAsset.onerror = AssetFailed;
    objAsset.src = Url;
}

// Trigger Flash to load assets for flashset
function LoadFlash(setIndex) {
    var ok = getFlashObject().loadContent("" + setIndex, items[setIndex], "FlashLoaded");
}

// Handle load of next flashset
function LoadNextSet() {
    currentSetnum++;
    if (currentSetnum < items.length) {
       expectedNumAssets = 4;
       if (items[currentSetnum].LogoUrl == "")
          expectedNumAssets -= 1; 
        SetStates[currentSetnum] = -1;
        numLoaded = 0;
        if (UseFlash)
            LoadFlash(currentSetnum);
        else {
            LoadAsset(items[currentSetnum].NoFlashImage);
            if (items[currentSetnum].MovieCoverUrl != "") {
                expectedNumAssets += 1;
                LoadAsset(items[currentSetnum].MovieCoverUrl);
            }
        }
        LoadAsset(items[currentSetnum].BackgroundImage);
        LoadAsset(items[currentSetnum].ThumbnailImage);
        if (items[currentSetnum].LogoUrl != "")
           LoadAsset(items[currentSetnum].LogoUrl);
     }
     else {
        //No more items to load. If there was only 1 loaded remove the thumbnail list and índicator
        if (items.length <= 1) {
           $("#thumbs").remove();
           $('.thumbIndicator').remove();
           LoopSets = false;
        }
     }
}

// Click-event to
function ManualShiftToSet(setNum) {
    if (transisting)
        return;
    clearTimeout(TimerId);
    ShiftToSet(setNum, true);
    currentDisplaySet = setNum;
}

// Initial function to start (lazy)loading/caching of assets(sets)
function LazyloadMainstageSets() {
    LoadNextSet();
}

// ready counter function, to ensure that all needed parts of the page is ready (Page, Flash-object...)
var CountLoaded = 0;
function PagePartReady() {
    CountLoaded++;
    UseFlash = FlashDetect.installed;
    if (UseFlash == false) {
        CountLoaded++;
    }
    if (CountLoaded == 2) {
        InitMainstageSets();
        //             if (!UseFlash) InjectMovieCover();
        LazyloadMainstageSets();
    }
}

// Fired on event, when page is ready       
function PageLoaded() {
    PagePartReady();
}

// Fired on event, when Flash reports ready...
function flashCallBack() {
    PagePartReady();
}

// Fired on event, when Flash is interacted by the user...
function flashInteract() {
    clearTimeout(TimerId);
}


