﻿var FmaIsMuted = false;
var initialLoad = true;

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) {
        $("#muteButton").removeClass("muteOffFma");
        $("#muteButton").addClass("muteOnFma");
    }
    else {
        $("#muteButton").removeClass("muteOnFma");
        $("#muteButton").addClass("muteOffFma");
    }
}

function getFmaIsMuted() {
    if (initialLoad) {
        initialLoad = false;
        
        try{       
            FmaIsMuted = checkCookie();
        }catch(e){FmaIsMuted = false;}
    }
    return FmaIsMuted;
};

function setFmaIsMuted(isMuted) {
    FmaIsMuted = isMuted;
    writeCookie();
    toggleMuteButton();
    muteFmas();
}

function muteFmas() {
    try {
        var flash = document.getElementById("flash_fma");

        flash.setVolume(FmaIsMuted);
    } catch (exp) { }
}

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 preloadAssets() {
//    for (var z = 0; z < fmas.length; z++) {
//        if (fmas[z].toLowerCase().indexOf('image') > 0) {
//            $("#holder").image(fmas[z]);
//        }

//        if (fmas[z].toLowerCase().indexOf('swf') > 0) {
//            $("#holder").flash({ src: fmas[z], width: 0, height: 0, flashvars: { wmode: 'opaque', quality: 'high', allowScriptAccess: 'always'} }, { version: 9 });
//        }
//    }
//    
//    $("#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);
        });
    }

    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)
        }, o || {});

        return this.each(function() {// Returns the element collection. Chainable.

            if (fmas.length < 1) {
                return;
            }

            var running = false, animCss = o.vertical ? "top" : "left", sizeCss = o.vertical ? "height" : "width";
            var div = $(this), ul = $("ul", div), tLi = $("li", ul), tl = tLi.size(), v = o.visible;

            preloadAssets();

            initializeMuting();

            if (o.circular) {
                ul.prepend("<li><div id='prependedOne' class='divfma' style='width:980px;height:350px;'></div></li>")
                    .append("<li><div id='appendedOne' class='divfma' style='width:980px;height:350px;'></div></li>");

                o.start += v;
            }

            var li = $("li", ul), itemLength = li.size(), 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').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').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 (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').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);
                        $('#divFMAPager').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 so = new SWFObject(fmas[currentfma - 1], "flash_fma", "980", "350", "9.0.16.0", "#FFFFFF", true);
                            so.addParam("quality", "high");
                            so.addParam("wmode", "opaque");
                            so.addParam("allowscriptaccess", "always");
                            so.addParam("name", "flash_fma");
                            so.write($(li[curr].firstChild).attr('id'));
                        } else if (fmas[currentfma - 1].toLowerCase().indexOf('image') > 0) {
                            $(li[curr].firstChild).image(fmas[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);