﻿var FmaIsMuted = false;
var initialLoad = true;
var fmaTimerPaused = false;
var fmaImages = [];
var currFmaSwf = '';

function checkCookie()
{
    var muted = false;
    var cookie_name = "isMuted";
    var cookie = document.cookie.indexOf(cookie_name);

    if (cookie > -1)
    {
        var nameValueList = document.cookie.split(';');

        for (var item = 0; item < nameValueList.length; item++)
        {
            var nameValue = nameValueList[item].split('=');

            if (nameValue[0].replace(' ', '') == 'isMuted')
            {
                if (nameValue[1] == 'true')
                {
                    muted = true;
                }
                else
                {
                    muted = false;
                }
            }
        }
    }
    else
    {
        muted = false;
    }

    return muted;
};

function toggleMuteButton()
{
    if (getFmaIsMuted() == true)
    {
        $("#mediaCarouselMuteButton").addClass("muteButtonOn");
    }
    else
    {
        $("#mediaCarouselMuteButton").removeClass("muteButtonOn");
    }
}

function getFmaIsMuted()
{
    if (initialLoad)
    {
        initialLoad = false;

        try
        {
            FmaIsMuted = checkCookie();
        }
        catch (e)
        {
            FmaIsMuted = false;
        }
    }
    return FmaIsMuted;
}

function setFmaIsMuted(isMuted)
{
    FmaIsMuted = isMuted;
    writeCookie();
    toggleMuteButton();
    SetCurrentFmaMutedState();
}

function SetCurrentFmaMutedState()
{
    if (currFmaSwf.length > 0)
    {
        try
        {
            var flash = document.getElementById(currFmaSwf);

            if (flash.setVolume != null)
            {
                flash.setVolume(getFmaIsMuted());
            }
        }
        catch (e)
        {
        }
    }
}

function initializeMuting()
{
    try
    {
        FmaIsMuted = checkCookie();
    }
    catch (e)
    {
        FmaIsMuted = false;
    }

    toggleMuteButton();
}

function writeCookie()
{
    document.cookie = "isMuted=" + String(FmaIsMuted) + "; expires=Wednesday, 01-Aug-2040 08:00:00 GMT; path=/;";
}

// Functions to assess weighting of media items
function ServerProbability(id, high, low)
{
    this.high = high;
    this.low = low;
}

function getWeighted(weights)
{
    var min = 0;
    var max = min;
    var winnerWeight = 1;

    var probabilities = [];

    for (var i = 0; i < weights.length; i++)
    {
        var sp = new ServerProbability(0, 0);

        sp.low = max;
        sp.high = max + weights[i];

        probabilities[i] = sp;

        // add this to the probability objectsk
        max += weights[i];
    }

    // now we should have a complete array of probability objects for the assets
    // generate a random value in the correct range (between 0 and sum)
    var randomValue = Math.floor(Math.random() * (max - min)) + min;

    for (var j = 0; j < probabilities.length; j++)
    {
        if ((randomValue <= probabilities[j].high) && (randomValue >= probabilities[j].low))
        {
            // get the new asset Id
            winnerWeight = j + 1;
            break;
        }
    }

    return winnerWeight;
}

function preloadImages()
{
    for (var z = 0; z < fmas.length; z++)
    {
        if (fmas[z].toLowerCase().indexOf('image_') > 0)
        {
            var img = new Image();
            img.src = fmas[z];
            fmaImages[z] = img;
            $("#holder").image(fmas[z]);
        }
        else if (fmas[z].toLowerCase().indexOf('swf') > 0)
        {
            var imageSrc = 'http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif';

            if (fmas[z].toLowerCase().indexOf('alternateimage') > 0)
            {
                imageSrc = fmas[z];
            }

            var img = new Image();
            img.src = imageSrc;
            fmaImages[z] = img;
            $("#holder").image(fmas[z]);
        }
    }

    $("#holder").ready(function() { document.getElementById("divfmaContainer").className = "carouselLoadedState"; });
}

//http://www.gmarwaha.com/jquery/jcarousellite/js/jcarousellite_1.0.1.min.js
/**
* jCarouselLite - jQuery plugin to navigate images/any content in a carousel style widget.
* @requires jQuery v1.2 or above http://gmarwaha.com/jquery/jcarousellite/
* Copyright (c) 2007 Ganeshji Marwaha (gmarwaha.com)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Version: 1.0.1
* Note: Requires jquery 1.2 or above from version 1.0.1
*/
(function($)
{
    // Compliant with jquery.noConflict()
    // allows dynamic injection of images
    $.fn.image = function(src)
    {
        return this.each(function()
        {
            var i = new Image();
            i.src = src;

            this.appendChild(i);
        });
    }

    $.fn.precachedImage = function(imgIndex)
    {
        return this.each(function()
        {
            this.appendChild(fmaImages[imgIndex]);
        });
    }

    var fadeTimeout;
    var navTimeout;

    $.fn.jCarouselLite = function(o)
    {
        o = $.extend(
        {
            btnPrev: null
            , btnNext: null
            , btnGo: null
            , mouseWheel: false
            , auto: null
            , speed: 0
            , easing: null
            , vertical: false
            , circular: true
            , visible: 1
            , start: 0
            , scroll: 1
            , beforeStart: null
            , afterEnd: null
            , weightedStart: getWeighted(fmaweights)
            , defaultWidth: 0
            , defaultHeight: 0
            , fixedHeight: true
        }, o || {});

        return this.each(function()
        {
            // Returns the element collection. Chainable.
            if (fmas.length < 1)
            {
                return;
            }

            var running = false;
            var animCss = o.vertical ? "top" : "left";
            var sizeCss = o.vertical ? "height" : "width";
            var div = $(this);
            var ul = $("ul", div);
            var tLi = $("li", ul);
            var tl = tLi.size();
            var v = o.visible;

            preloadImages();

            initializeMuting();

            if (o.circular && fmas.length > 1)
            {
                ul.prepend("<li><div id='prependedOne' class='divfma' style='width:" + o.defaultWidth + "px;height:1px;'></div></li>")
                    .append("<li><div id='appendedOne' class='divfma' style='width:" + o.defaultWidth + "px;height:1px;'></div></li>");

                o.start += v;
            }

            var li = $("li", ul);
            var itemLength = li.size();
            var curr = o.start;
            div.css("visibility", "visible");

            li.css({ overflow: "hidden", float: o.vertical ? "none" : "left" });
            ul.css({ margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1" });
            div.css({ overflow: "hidden", position: "relative", "z-index": "0", left: "0px" });

            var liSize = o.vertical ? height(li) : width(li);   // Full li size(incl margin)-Used for animation
            var ulSize = liSize * itemLength;                   // size of full ul(total length, not just for the visible items)
            var divSize = liSize * v;                           // size of entire div(total length for just the visible items)

            //li.css({ width: li.width(), height: li.height() });
            ul.css(sizeCss, ulSize + "px").css(animCss, -(curr * liSize));

            div.css(sizeCss, divSize + "px");                     // Width of the DIV. length of visible images

            //first load : reset all divs and load first fma
            $('#fmaul div').html('');  //reset all divs
            var ginterval;

            if (fmas.length > 1)
            {
                ginterval = fmaintervals[o.start]; //load first

                if (o.btnPrev)
                    $(o.btnPrev).click(function()
                    {
                        clearTimeout(fadeTimeout);
                        clearTimeout(navTimeout);
                        if (fmas.length > 1)
                        {
                            $('#fmaul div').stop(true,true).fadeOut(1000);
                            fadeTimeout = setTimeout(function() { navigate(curr - o.scroll); }, 1000);
                        }
                        return;

                    });

                if (o.btnNext)
                    $(o.btnNext).click(function()
                    {
                        clearTimeout(fadeTimeout);
                        clearTimeout(navTimeout);
                        if (fmas.length > 1)
                        {
                            $('#fmaul div').stop(true,true).fadeOut(1000);
                            fadeTimeout = setTimeout(function() { navigate(curr + o.scroll); }, 1000);
                        }
                        return;
                    });

                if (o.auto)
                {
                    navigate(o.weightedStart);
                }
            }
            else
            {
                go(0);
            }

            function vis()
            {
                return li.slice(curr).slice(0, v);
            };

            function navigate(curr)
            {
                document.getElementById("divfmaContainer").className = "carouselLoadedState";
                clearTimeout(fadeTimeout);
                clearTimeout(navTimeout);

                if (!fmaTimerPaused)
                {
                    if (curr > fmas.length)
                    {
                        curr = 1;
                    }
                    else if (curr <= 0)
                    {
                        curr = fmas.length;
                    }

                    if (fmas.length > 1)
                    {
                        go(curr);

                        ginterval = fmaintervals[curr - 1];
                        //set the timer to display the next media item
                        fadeTimeout = setTimeout(function() { $('#fmaul div').stop(true,true).fadeOut(1000); }, (ginterval - 1000));
                        navTimeout = setTimeout(function() { navigate(curr + o.scroll) }, ginterval);
                    }
                    else
                    {
                        clearTimeout(fadeTimeout);
                        go(curr + o.scroll);
                    }
                }
            };

            function go(to)
            {
                $('#fmaul div').fadeIn();

                if (!running)
                {
                    if (o.beforeStart)
                        o.beforeStart.call(this, vis());

                    if (o.circular)
                    { // If circular we are in first or last, then goto the other end
                        if (to <= o.start - v - 1)
                        {           // If first, then goto last
                            ul.css(animCss, -((itemLength - (v * 2)) * liSize) + "px");
                            // If "scroll" > 1, then the "to" might not be equal to the condition; it can be lesser depending on the number of elements.
                            curr = to == o.start - v - 1 ? itemLength - (v * 2) - 1 : itemLength - (v * 2) - o.scroll;
                            clearTimeout(navTimeout);
                            navTimeout = setTimeout(function() { navigate(curr + o.scroll) }, ginterval);
                        }
                        else if (to >= itemLength - v + 1)
                        { // If last, then goto first
                            ul.css(animCss, -((v) * liSize) + "px");
                            // If "scroll" > 1, then the "to" might not be equal to the condition; it can be greater depending on the number of elements.
                            curr = to == itemLength - v + 1 ? v + 1 : v + o.scroll;
                            clearTimeout(navTimeout);
                            navTimeout = setTimeout(function() { navigate(curr + o.scroll) }, ginterval);
                        }
                        else curr = to;

                        //find the current fma to load
                        var currentfma = to;

                        if (currentfma <= 0)
                        {
                            currentfma = fmas.length + to;
                        }
                        //$('#divFMAPager').html('current li #: ' + curr + ' fma: - ' + currentfma + ' of ' + fmas.length);
                        $('#mediaCarouselPageText').html(currentfma + ' of ' + fmas.length);
                        $('#fmaul div').html('');  //reset all divs

                        // decide whether we want to load flash or image
                        if (fmas[currentfma - 1].toLowerCase().indexOf('swf') > 0)
                        {
                            var currHeight = o.fixedHeight ? o.defaultHeight : fmaheights[curr];
                            $('div', li[curr]).css({ width: o.defaultWidth + "px", height: currHeight + "px" });
                            $('#T01AdserverContainer').css("height", currHeight + "px");
                            $('#divfmaContainer').css("height", currHeight + "px");
                            $('#fmaul').css("height", currHeight + "px");

                            var playerVersion = swfobject.getFlashPlayerVersion();
                            if (playerVersion.major != 0)
                            {
                                var swfID = $('div', li[curr]).attr('id').replace("divfma", "fmaswf"); //.replace("prependedOne", "fmaswfPrepend").replace("appendedOne", "fmaswfAppend");
                                var swfObj = new SWFObject(fmas[currentfma - 1].replace("_alternateimage.arox", ".arox"), swfID, o.defaultWidth, currHeight, "9.0.16.0", "#FFFFFF", true);
                                swfObj.addParam("quality", "high");
                                swfObj.addParam("wmode", "opaque");
                                swfObj.addParam("allowscriptaccess", "always");
                                swfObj.addParam("name", swfID);
                                swfObj.addParam("flashvars", fmaflashvars[currentfma - 1]);
                                swfObj.write($('div', li[curr]).attr('id'));
                                currFmaSwf = swfID;
                                SetCurrentFmaMutedState();
                            }
                            else if (fmas[currentfma - 1].toLowerCase().indexOf('alternateimage') > 0)
                            {
                                $('div', li[curr]).unbind('click');
                                $('div', li[curr]).css("cursor", "auto");

                                $('div', li[curr]).precachedImage(currentfma - 1);
                                if (fmalinks[curr] != '')
                                {
                                    $('div', li[curr]).css("cursor", "pointer");
                                    $('div', li[curr]).bind('click', function() { window.location = fmalinks[currentfma - 1]; });
                                }
                            }
                            else
                            {
                                var getFlashHtml = '<h2>This content requires Flash</h2>'
                                                 + '<p>To view this content, you need the latest version of the Adobe Flash Player</p>'
                                                 + '<a href="http://www.adobe.com/go/getflashplayer/" target="_blank" class="linkPlain">'
                                                 + '<img border="0" src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif">'
                                                 + '</a>';
                                $('div', li[curr]).html(getFlashHtml);
                            }
                        }
                        else if (fmas[currentfma - 1].toLowerCase().indexOf('image_') > 0)
                        {
                            var currHeight = o.fixedHeight ? o.defaultHeight : fmaheights[curr];
                            $('div', li[curr]).css({ width: o.defaultWidth + "px", height: currHeight + "px" });
                            $('#T01AdserverContainer').css("height", currHeight + "px");
                            $('#fmaul').css("height", currHeight + "px");
                            $('#divfmaContainer').css("height", currHeight + "px");

                            $('div', li[curr]).unbind('click');
                            $('div', li[curr]).css("cursor", "auto");

                            if (fmalinks[curr] != '')
                            {
                                $('div', li[curr]).css("cursor", "pointer");
                                $('div', li[curr]).bind('click', function() { window.location = fmalinks[currentfma - 1]; });
                            }

                            $('div', li[curr]).precachedImage(currentfma - 1);
                        }
                    }
                    else
                    { // If non-circular and to points to first or last, we just return. - not used 
                        if (to < 0 || to > itemLength - v) return;
                        else curr = to;
                    }   // If neither overrides it, the curr will still be "to" and we can proceed.

                    running = true;

                    ul.animate(
                            animCss == "left" ? { left: -(curr * liSize)} : { top: -(curr * liSize) }, o.speed, o.easing,
                            function()
                            {
                                if (o.afterEnd)
                                {
                                    o.afterEnd.call(this, vis());
                                }

                                running = false;
                            }
                     );
                }
                return false;
            };
        });
    };

    function css(el, prop)
    {
        return parseInt($.css(el[0], prop)) || 0;
    };

    function width(el)
    {
        return el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
    };

    function height(el)
    {
        return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
    };

})(jQuery);

