$.extend($.easing, {
    // plot [0:1] exp(-((x - 0.5)*pi*1.5)**2)*sin(x * 2 * pi * (10 + 2))*10 + x
    shakeIt: function(x, n, firstNum, diff ) {
        var e = 1.5 * Math.PI * (x - 0.5), noPeaks = 1, scaling = 2;
            wavelet = Math.exp(- e * e) * Math.sin(x * 2 * Math.PI * (noPeaks + 2));
	return firstNum + diff * (wavelet * scaling + x);
    }
});
        
$(function () {
    function setupProductSelector() {
        var scrollButtons = $(".products .left,.products .right");
        var offset = 0, pageSize = 4, total = $(".products .product").length;
        
        function getDirection(button) {
            if (button.hasClass("left"))
                return -1;
            else
                return 1;
        }

        function isActive(button) {
            var d = getDirection(button);
            return (d < 0 && offset > 0) || (d > 0 && offset + pageSize < total);
        }

        function setButtonActivity() {
            scrollButtons.each(function () {
                var button = $(this);
                var opacity = isActive(button) ? 1 : 0.6;
                button.animate({ opacity: opacity }, 1000);
            });
        }
        
        function scrollProducts(dir) {
            var oldOffset = offset;
            offset += dir * pageSize;
            if (offset > total - pageSize)
                offset = total - pageSize;
            if (offset < 0)
                offset = 0;

            var delta = $(".products .window").width() * (oldOffset - offset) / pageSize;
            
            $(".products .container").animate({ left: '+=' + delta}, { duration: 800, easing: 'easeOutBounce'});

            setButtonActivity();
        }

        scrollButtons.hover(function () {
            if (isActive($(this)))
                $(this).animate({ opacity: 0.85 }, 200);
        }, function () {
            if (isActive($(this)))
                $(this).animate({ opacity: 1 }, 200);
        }).click(function () {
            var button = $(this);
            if (!isActive(button))
                return;

            button.animate({ opacity: 1 }, 100).animate({ opacity: 1}, 200).animate({ opacity: 0.8 }, 400);

            scrollProducts(getDirection($(this)));
        });

        setButtonActivity();
    }

    function setupVideoSelector() {
        var videos = $(".videoWindow img"), offset = 0, total = videos.length,
            playButton = $(".playVideo"), reshowPlayTimer = null, hoveringPlay = false;
        
        function getDirection(button) {
            if (button.hasClass("previousVideo"))
                return -1;
            else
                return 1;
        }

        function tickleTv() {
            var img = videos.eq(offset);
            if (img.is(':animated'))
                return;
            img.css('opacity', 0.5).animate({ opacity: 1 }, 400, "shakeIt");
        }

        $(".previousVideo,.nextVideo").click(function () {
            var d = getDirection($(this));
            var oldOffset = offset;
            offset += d;
            if (offset > total - 1)
                offset = total - 1;
            if (offset < 0)
                offset = 0;

            if (offset == oldOffset)
                return;

            videos.eq(oldOffset).animate({ opacity: 0 }, 500, "easeInBounce", function () {
                $(this).hide();
                videos.eq(offset).css({ opacity: 0 }).show()
                    .animate({ opacity: 1 }, 300, "easeOutBounce");
            });
        }).hover(function () {
            playButton.fadeOut(200);
            hoveringPlay = true;
            tickleTv();
        }, function () {
            hoveringPlay = false;
            if (!reshowPlayTimer)
                reshowPlayTimer = setTimeout(function () {
                    if (!hoveringPlay)
                        playButton.fadeIn(200);
                    reshowPlayTimer = null;
                }, 400);
        });

        // playing videos
        if (flashembed.isSupported([9, 0])) {
            $("#bentVideoPlayer").text(".").css({ color: "#000" });
            flowplayer("bentVideoPlayer", flowplayerFlash, {
                play: {
                    replayLabel: "Afspil igen"
                },
                plugins: {
                    controls: {
                        opacity: 0.9,
                        height: 15,
                        backgroundColor: '#000000',
                        backgroundGradient: "none",
                        volumeSliderColor: '#000000',
                        volumeSliderGradient: "low",
                        progressColor: '#000000',
                        progressGradient: "low",
                        bufferColor: '#111111',
                        buttonColor: "#666666",
                        buttonOverColor: "#999999",
                        scrubberHeightRatio: 1,
                        volumeSliderHeightRatio: 1,
                        time: false,
                        tooltipColor: "#333333"
                    }
                }
            });
        }
        
        playButton.click(function () {
            var v = videos.eq(offset), url = v.attr('name'), id = v.attr('alt');

            $('#bentVideoDialog').modal({
                close: true,
                closeClass: 'modalCloseImg',
                overlay: 85,
                persist: true,
                overlayId: 'videoOverlay',
                onShow: function() {
                    var dialog = $("#bentVideoDialog");
                    dialog.addClass("reset");

                    dialog.find(".modalCloseImg").hover(
                        function () {
                            $(this).animate({ opacity: 1 }, 100);
                        },
                        function () {
                            $(this).animate({ opacity: 0.01 }, 100);
                        }).css({ opacity: 0.01, visibility: "visible" });

                    var channels = dialog.find('.channel'),
                        knobs = dialog.find('.knob'),
                        videos = $(".videoWindow img"),
                        activeChannel;

                    setActive(1);
                    
                    function setActive(c) {
                        activeChannel = c;
                        channels.find('img.active').removeClass('active');
                        channels.filter('#chan' + c).find('img').addClass("active");

                        knobs.css({ visibility: 'hidden'});
                        knobs.filter('img[src*="-' + c + '."]').css({ visibility: 'visible'});

                        if (c - 1 < videos.length
                            && flashembed.isSupported([9, 0])) {
                            flowplayer("bentVideoPlayer").play({
                                url: videos.eq(c - 1).attr('name'),
                                scaling: "fit"
                            });

                            // tracking
                            var videoId = videos.eq(c - 1).attr('alt');
                            if (window.pageTracker)
                                window.pageTracker._trackEvent('Bølle Bent-video', 'Afspil', videoId);
                            $.post(playingVideoUrl, { id:  videoId});
                        }
                    }

                    channels.hover(function () {
                        $(this).find('img').addClass("hovered");
                    }, function (){
                        $(this).find('img').removeClass("hovered");
                    }).click(function (e) {
                        e.preventDefault();
                        setActive(this.id.substring(4));
                    });

                    dialog.find('.knobArea').click(function (e) {
                        e.preventDefault();
                        
                        ++activeChannel;
                        if (activeChannel > 13)
                            activeChannel = 1;
                        
                        setActive(activeChannel);
                    });
                    
                    if (flashembed.isSupported([9, 0])) {
                        flowplayer("bentVideoPlayer").play({
                            url: url,
                            scaling: "fit"
                        });
                    }
                },
                onClose: function() {
                    if (flashembed.isSupported([9, 0]))
                        $f().unload();
                    
                    $.modal.close();
                    if (window.location.hash)
                        window.location.hash = "none";
                }
            });
        });
    }

    setupVideoSelector();
    setupProductSelector();

    // movable gun
    $(".gun").mouseover(function () {
        if ($(this).is(':animated'))
            return;
        $(this)
            .animate({ top: '-=1'}, 50)
            .animate({ left: '-=1'}, 20)
            .animate({ top: '+=1'}, 30)
            .animate({ top: '-=6'}, 50)
            .animate({ top: '+=6'}, 50)
            .animate({ left: '+=2'}, 50)
            .animate({ top: '-=1'}, 20)
            .animate({ top: '+=1'}, 10)
            .animate({ left: '-=1'}, 20)
        ;
    });
});

$(window).load(function () {
    $(".bullyBent").css({ visibility: 'visible' });
    
    setTimeout(function () {
        var offsets = {
            // left side
            'knald': { top: -10, left: -100 },
            'box': { top: -10, left: -100 },
            'gun': { top: 50, left: -100 },
            // right side
            'pol2': { top: -30, left: 140 },
            'pol1': { top: -10, left: 100 },
            'bomb': { top: 100, left: 100 },
            'spark': { top: 100, left: 80 }
        }

        function relative(o, dir) {
            var res = {};
            for (var a in o)
                res[a] = dir + o[a];
            return res;
        }

        var easing = "easeOutElastic";
        
        $(".bgKnald").animate(relative(offsets.knald, '+='), 500, easing);
        $(".bgBox").animate(relative(offsets.box, '+='), 800, easing);
        $(".bgGun").animate(relative(offsets.gun, '+='), 300, easing);
        $(".bgPol2").animate(relative(offsets.pol2, '+='), 1000, easing);
        $(".bgPol1").animate(relative(offsets.pol1, '+='), 500, easing);
        $(".bgBomb").animate(relative(offsets.bomb, '+='), 700, easing);
        $(".bgSpark").animate(relative(offsets.spark, '+='), 300, easing);

        setTimeout(function () {
            // add .bgSpark to ensure it is first in the stacking order
            $(".bgSpark, .bg").each(function () {
                var e = $(this), o = null;
                for (var a in offsets) {
                    if (e.hasClass('bg' + a.charAt(0).toUpperCase() + a.substring(1))) {
                        o = offsets[a];
                        break;
                    }
                }

                if (!o)
                    return;

                // make a dummy event div to capture mouseover events
                var d = $("<div>")
                    .width(e.width()).height(e.height())
                    .css({
                        position: 'absolute',
                        left: e.css('left'),
                        top: e.css('top'),
                        backgroundImage: "url(images/blank.gif)"
                    });
                $(".content").after(d);
                d.mouseover(function () {
                    if (e.is(':animated'))
                        return;

                    e.animate(relative(o, '-='), 300).animate(relative(o, '+='), 700 + parseInt(Math.random() * 300), easing);
                    
                });
            });
        }, 1100);
    }, 1000);
});
