﻿var regions = {};

$(document).ready(function () {
    setUpVideoPlayers();
    setUpImagePlayers();
    setUpScrollingHeadlines();
});

function detectIsHtmlFive() {
    var deviceAgent = navigator.userAgent.toLowerCase();
    var agentID = deviceAgent.match(/(iphone|ipod|ipad|safari)/);

    if (agentID) {
        if (deviceAgent.match(/(chrome)/)) {
            return false;
        } else {
            return true;
        }
    }

    return false;
}

function detectIsIPadOrAndroid() {
    var deviceAgent = navigator.userAgent.toLowerCase();
    var agentID = deviceAgent.match(/(iphone|ipod|ipad|android)/);

    if (agentID) {
       return true;
    }

    return false;
}

var iPadVideoTimeout;
var iPadVideoCount = 1;

function setUpVideoPlayers() {
    if (typeof setUpBalloons == "function") {
        setUpBalloons();
    }

    //if the browser is Safari, like on an ipad or iphone, use the native MP4 video
    //playing capabilities.  Otherwise, use Flash.
    if (detectIsHtmlFive()) {
        if (detectIsIPadOrAndroid()) {
            $("#home-canvas .video-region .video-player video").remove();
            iPadChangeVideo();
        } else {
            $("#home-canvas .video-region .video-player video").each(function () {
                var regionID = $(this).parent().attr("id");

                regions[regionID] = 1;

                $(this).bind('ended', videoPlayerEnded);
                $(this).css("display", "none");
            });

            $("#home-canvas .video-region .video-player video:first-child").each(function () {
                $(this).css("display", "block");
                this.play();
            });
        }
    } else {
        //we're using the flash player.  assemble the playlists from the html in the region <div>
        $("#home-canvas .video-region:first-child").each(function () {
            var videoPlayerDiv = $(this).find(".video-player");
            var videoPlayerDivID = $(videoPlayerDiv).attr("id");
            var videoRegionID = $(videoPlayerDiv).parent().parent().attr("id");
            var width = $(this).width();
            var height = $(this).height();

            //find the region's playlist and turn it into a comma-delimited string.
            var playlist = [];
            var titles = [];
            var links = [];
            var descriptions = [];

            $(this).find(".playlist li").each(function () {
                playlist.push($(this).find(".video").text());
                titles.push($(this).find(".title").text());
                links.push($(this).find(".link").text());
                descriptions.push($(this).find(".description").text());
            });

            var flashVars = {};
            flashVars["width"] = width;
            flashVars["height"] = height;
            flashVars["videos"] = playlist.join("|");
            flashVars["titles"] = titles.join("|");
            flashVars["links"] = links.join("|");
            flashVars["descriptions"] = descriptions.join("|");
            flashVars["regionID"] = videoRegionID;
            flashVars["onchange"] = "changeVideoLink";

            swfobject.embedSWF("/flash/HomePageVideoPlayer.swf", videoPlayerDivID, width, height, "10.0.0", null, flashVars, { wmode: "transparent" }, false);
        });
    }
}

function changeVideoLink(regionID, playlistIndex) {
    var playlistEntry = $("#" + regionID + " .playlist li:nth-child(" + (playlistIndex + 1) + ")");
    var videoLink = $("#" + regionID + " .callout");
    var title = $(playlistEntry).find(".title").text();
    var desc = $(playlistEntry).find(".description").text();
    var url = $(playlistEntry).find(".link").text();

    $(videoLink).find(".title").text(title);
    $(videoLink).find(".subtitle").text(desc);
    $(videoLink).attr("href", url);

    //alert(regionID + " " + playlistIndex);
}

function videoPlayerEnded(evt) {
    evt.target.pause();
    //find the region this video was in.
    var regionID = $(evt.target).parent().attr("id");

    var currentVideoIndex = regions[regionID];

    var totalVideosInRegion = $("#" + regionID + " video").size();
    var nextVideoIndex = currentVideoIndex + 1;

    if (nextVideoIndex > totalVideosInRegion) {
        nextVideoIndex = 1;
    }

    regions[regionID] = nextVideoIndex;

    var nextPlayer = $("#" + regionID + " video")[nextVideoIndex - 1];

    var playlistItem = $("#video-region-1 .playlist li:nth-child(" + nextVideoIndex + ")");
    var title = $(playlistItem).find(".title").text();
    var description = $(playlistItem).find(".description").text();
    var link = $(playlistItem).find(".link").text();
    var target = $(playlistItem).find(".target").text();
    var overlay = $("#region-1-link");

    $(overlay).attr("href", link).attr("target", target);
    $(overlay).find(".title").text(title);
    $(overlay).find(".subtitle").text(description);

    //show and play next player.
    $(nextPlayer).attr("style", "z-index: 10;");
    //hide/rewind current player
    $(evt.target).attr("style", "z-index: 9;");
    evt.target.currentTime = 0;
    nextPlayer.play();

    changeVideoLink(regionID, nextVideoIndex);
}

function iPadChangeVideo() {
    var playlistItem = $("#video-region-1 .playlist li:nth-child(" + iPadVideoCount + ")");
    var imgSrc = $(playlistItem).find(".thumbnail").text();
    var newImg = $("#video-region-1 .video-player img[src='" + imgSrc + "']");

    if ($("#video-region-1 .video-player .current-image").size() > 0) {
        var oldImg = $("#video-region-1 .video-player .current-image");
        $(oldImg).removeClass("current-image");

        $(oldImg).animate({
            left: "-560px"
        }, 500, 'easeInBack');
    }

    var title = $(playlistItem).find(".title").text();
    var description = $(playlistItem).find(".description").text();
    var link = $(playlistItem).find(".link").text();
    var target = $(playlistItem).find(".target").text();
    var overlay = $("#region-1-link");

    $(overlay).attr("href", link).attr("target", target);
    $(overlay).find(".title").text(title);
    $(overlay).find(".subtitle").text(description);

    $(newImg).css("left", "560px");
    $(newImg).addClass("current-image");
    $(newImg).animate({
        left: "0px"
    }, 500, 'easeInBack', function () {
        incrementIPadVideoCountAndSetTimeout();
    });
}

function incrementIPadVideoCountAndSetTimeout() {
    var totalItems = $("#video-region-1 .playlist li").size();
    iPadVideoCount++;

    if (iPadVideoCount > totalItems) {
        iPadVideoCount = 1;
    }

    iPadVideoTimeout = setTimeout(iPadChangeVideo, 5000);
}

var scrolls = {};

function setUpScrollingHeadlines() {
    $("#home-canvas .text-region").each(function () {
        var scrollID = $(this).attr("id");
        scrolls[scrollID] = { current: 0 };

        scrollHeadlines(scrollID, true);
    });
}

function scrollHeadlines(scrollID, initial) {
    var currentHeadlineIndex = scrolls[scrollID]["current"];

    var nextHeadlineIndex = scrolls[scrollID]["current"] + 1;
    var totalHeadlines = $("#" + scrollID + " .scroll li").size();

    if (nextHeadlineIndex > totalHeadlines) {
        nextHeadlineIndex = 1;
    }

    scrolls[scrollID]["current"] = nextHeadlineIndex;

    var nextHeadline = $("#" + scrollID + " .scroll li:nth-child(" + nextHeadlineIndex + ")")[0];
    var currentHeadline = $("#" + scrollID + " .scroll li:nth-child(" + currentHeadlineIndex + ")")[0];

    var headlineWidth = $(nextHeadline).innerWidth();
    var headlineHeight = $(nextHeadline).innerHeight();

    var headlineColor = $(nextHeadline).find(".background-color").text();
    var headlineTop = $(nextHeadline).position().top;

    $("#" + scrollID).animate({
        width: headlineWidth + "px",
        height: headlineHeight + "px",
        backgroundColor: "#" + headlineColor
    }, 500);

    $("#" + scrollID + " .scroll").animate({
        top: "-" + headlineTop + "px"
    }, 500);

   scrolls[scrollID]["timeout"] = setTimeout(function () { scrollHeadlines(scrollID); }, 5000);

}

var slideshows = {};

function setUpImagePlayers() {
    var directions = ["left", "right", "up", "down"];
    $("#home-canvas .images-region .callout-hover").fadeOut();
    $("#home-canvas .video-region .callout-hover").fadeOut();
    $("#home-canvas .video-region").each(function () {
        var slideshowID = $(this).attr("id");
        $("#" + slideshowID).find(".callout-hover-content .title").text($("#" + slideshowID).find(".playlist li:first .title").text());
        $("#" + slideshowID).find(".callout-hover-content .subtitle").text($("#" + slideshowID).find(".playlist li:first .description").text());
    });

    $("#home-canvas .images-region").each(function () {
        var slideshowID = $(this).attr("id");
        $("#" + slideshowID).find(".callout-hover-content .title").text($("#" + slideshowID).find(".playlist li:first .title").text());
        $("#" + slideshowID).find(".callout-hover-content .subtitle").text($("#" + slideshowID).find(".playlist li:first .description").text());

        if ($(this).find(".playlist li").size() > 1) {
            var randDirection = Math.floor(Math.random() * directions.length);
            var directionClass = directions[randDirection];

            $(this).addClass("scroll-" + directionClass);

            directions.splice(randDirection, 1);

            slideshows[slideshowID] = { current: 1, direction: "scroll-" + directionClass };

            scrollSlideshow(slideshowID, true);
        }
    });

    $("#home-canvas .images-region a").mouseenter(function () {
        var slideshowID = $(this).parent().parent().attr("id");
        if (slideshows[slideshowID] !== undefined) {
            if (slideshows[slideshowID]["timeout"]) {
                clearTimeout(slideshows[slideshowID]["timeout"]);
            }
        }
        $(this).find(".callout-hover").fadeIn();
    }).mouseleave(function () {
        if ($(this).parent().parent().find(".playlist li").size() > 1) {
            var slideshowID = $(this).parent().parent().attr("id");
            scrollSlideshow(slideshowID, true);
        }
        $(this).find(".callout-hover").fadeOut();
    });

    $("#home-canvas .video-region a").mouseenter(function () {
        $(this).find(".callout-hover").fadeIn();

        if (detectIsIPad()) {
            clearTimeout(iPadVideoTimeout);
        }
    }).mouseleave(function () {
        $(this).find(".callout-hover").fadeOut();

        if (detectIsIPad()) {
            setTimeout(iPadChangeVideo, 5000);
        }
    });
}

function scrollSlideshow(slideshowID, initial) {
    var randTime = (Math.random() * 3000) + 5000;
    if (initial) {
        slideshows[slideshowID]["timeout"] = setTimeout(function () { scrollSlideshow(slideshowID); }, randTime);
    } else {
        var currentImageIndex = slideshows[slideshowID]["current"];
        var nextImageIndex = currentImageIndex + 1;
        var totalImages = $("#" + slideshowID).find(".playlist li").size();
        var direction = slideshows[slideshowID]["direction"];

        if (nextImageIndex > totalImages) {
            nextImageIndex = 1;
        }

        var nextImagePlaylist = $("#" + slideshowID + " .playlist li:nth-child(" + nextImageIndex + ")")[0];

        var currentImage = $("#" + slideshowID + " .current-image a img");
        $(currentImage).addClass("old");

        //add new image
        $("#" + slideshowID + " .current-image a").append('<img class="new" src="" alt="" style="visibility: hidden;" />');

        slideshows[slideshowID]["current"] = nextImageIndex;

        var newImage = $("#" + slideshowID + " .current-image a .new");
        $(newImage).bind('load', slideshowTransition);

        $(newImage).attr("src", $(nextImagePlaylist).find(".image").text());

        $("#" + slideshowID).find(".callout-hover-content .title").text($(nextImagePlaylist).find(".title").text());
        $("#" + slideshowID).find(".callout-hover-content .subtitle").text($(nextImagePlaylist).find(".description").text());
        $("#" + slideshowID).find(".current-image a").attr("href", $(nextImagePlaylist).find(".link").text());
        $("#" + slideshowID).find(".current-image a").attr("target", $(nextImagePlaylist).find(".target").text());

        slideshows[slideshowID]["timeout"] = setTimeout(function () { scrollSlideshow(slideshowID); }, randTime);
    }
}

function slideshowTransition(evt) {
    var newImage = $(evt.currentTarget);
    $(newImage).unbind('load', slideshowTransition);

    var oldImage = $(newImage).parent().find(".old");
    var slideshowID = $(newImage).parent().parent().parent().attr("id");
    var direction = slideshows[slideshowID]["direction"];

    var startTop = 0;
    var startLeft = $("#" + slideshowID).width();

    var oldTop = 0;
    var oldLeft = -($(oldImage).width());

    if (direction == "scroll-right") {
        startLeft = -($(newImage).width());

        oldTop = 0;
        oldLeft = $(oldImage).width();
    } else if (direction == "scroll-up") {
        startLeft = 0;
        startTop = $("#" + slideshowID).height();

        oldTop = -($(oldImage).height());
        oldLeft = 0;
    } else if (direction == "scroll-down") {
        startLeft = 0;
        startTop = -($(newImage).height());

        oldTop = $(oldImage).height();
        oldLeft = 0;
    }

    $(newImage).css("top", startTop + "px");
    $(newImage).css("left", startLeft + "px");
    $(newImage).css("visibility", "visible");

    $(newImage).animate({
        left: 0 + "px",
        top: 0 + "px"
    }, 500, 'easeInBack');

    $(oldImage).animate({
        left: oldLeft + "px",
        top: oldTop + "px"
    }, 500, 'easeInBack', function () {
        cleanUpSlideshow($(oldImage)[0]);
    });
}

function cleanUpSlideshow(oldImg) {
    //alert(evt);
    var oldImage = $(oldImg);

    $(oldImage).parent().find(".new").removeClass("new");

    $(oldImage).remove();
}



