$(function() {
    // the product tabs
    var bumpSize = 10;
    var indentSize = 24;

    function tabClick() {
        var speed = 400;
        var back = $(this), backDepth = back.css('z-index');
        var front = back.siblings(".front"),
            frontDepth = parseInt(front.css('z-index')) + 1;
        var size = back.parent().width();
        var backIndent = parseInt(back.css("left")) - bumpSize;
        // correct animation deviation
        backIndent = Math.round(backIndent/indentSize, 1)*indentSize;

        var ani1 = {left: (size + 20) + 'px'};
        var ani2 = {left: '0px'};
        /*var ani1 = {top: (80 + 20) + 'px', left: '150px'};
        var ani2 = {left: '0px', top: '0px'};*/
        removeTabEvents(back);
        back.animate(ani1, speed, 'easeInQuart', function() {
            front.removeClass("front");
            back.addClass("front").css('z-index', frontDepth);
            back.animate(ani2, speed, 'easeOutQuart', function() {
                front.css("z-index", backDepth).animate({left: backIndent + 'px'}, 200);
                addTabEvents(front);
            });
        });
        if (window.pageTracker)
            window.pageTracker._trackEvent('Produktfane', 'Click', $(this).attr("name"));
    }

    function addTabEvents(jq) {
        jq.click(tabClick);
        jq.hover(function() { $(this).animate({left: '+='+bumpSize+'px'}, 200); },
                 function() { $(this).animate({left: '-='+bumpSize+'px'}, 200); });
    }

    function removeTabEvents(jq) {
        jq.unbind("click").unbind('mouseenter').unbind('mouseleave');
    }


    var tabs = $(".news, .chooser").find(".tab:not(.front)");
    addTabEvents(tabs);

    // load animation on chooser tabs
    tabs.each(function() {
        var depth = parseInt($(this).css("z-index"));
        var indent = (6 - depth) * indentSize;
        $(this).animate({left: indent + "px"}, 500);
    });

    /*
    var unchosenName = $(".chooser .productTypeName").eq(0).text();
    
    $(".chooser .productType").hover(function() {
        var name = $(this).parent().siblings(".productTypeName");
        name.text($(this).attr("name"));
    }, function() {
    });
    
    $(".chooser .productTypes").bind("mouseleave", function() {
        var name = $(this).find(".productTypeName");
        name.text(unchosenName);
    });*/

    
    // sms box
    /*
    $(".smsBox").each(function () {
        var box = $(this),
            email = box.find(".email"),
            arrows = box.find(".arrows");
        
        arrows.click(function (e) {
            e.preventDefault();

            $.cookie("myemail", email.val(), { path: '/', expires: 100 });
            window.location = "/videoer/";
        });
        email.keypress(function (e) {
            if (e.which == 13)
                arrows.click();
        });
        email.labelify();
    });*/

    
    // catalog box
    $('.catalogBox .link').click(function(e) {
        e.preventDefault();
        var iframeUrl = $("a", this).attr("href");

	$('#catalogDialog').modal({
	    close: true,
            overlay: 85,
            persist: true,
	    overlayId: 'videoOverlay',
            containerId: 'catalogModalContainer',
            onOpen: function(dialog) {
                var height = Math.min($(window).height() - 50, 700);
                $("#catalogDialog").css("height", height + "px");
                dialog.overlay.fadeIn(function() {
                    dialog.container.fadeIn(function() {
                        $('#catalogDialog').animate({width: 900}, function() {
                            $(".modalCloseImg").fadeIn();
                            setTimeout(function() {
                                var iframe = '<iframe style="height: ' + (height - 40) + 'px" src="' + iframeUrl + '"></iframe>';
                                $("#catalogDialog").append(iframe);
                            }, 500);
                            
                        });
                    });
                });
            },
            onShow: function() {
            },
            onClose: function() {
                $("#catalogModalContainer iframe").remove();
                $(".modalCloseImg").fadeOut();
                $('#catalogDialog').animate({width: 0}, function() {
                    $("#catalogModalContainer").fadeOut();
                    $.modal.close();
                });

            }
	});

        if (window.pageTracker)
            window.pageTracker._trackPageview('/_/catalog/' + $("a", this).text().replace(/ /g, "") + '/');
    });

    // video player inside the telly
    var tv = $(".tvContainer");
    if (flashembed.isSupported([9, 0]) && videos.length > 0) {
        var currentVideo = videos[0],
            selection = { index: 0, pageSize: 2, videos: [] },
            flowplayerSetup = false;

        function setupFlowplayer(clip) {
            flowplayer("tvVideoPlayer", {
                src: flowplayerFlash,
                wmode: 'opaque'
            }, {
                onFinish: function () { setTimeout(showVideoSelection, 1000); },
                onStop: function () { setTimeout(showVideoSelection, 5000); },
                clip: clip,
                play: {
                    replayLabel: null
                },
                plugins: {
                    controls: {
                        opacity: 0.9,
                        left: 30,
                        width: 482,
                        height: 15,
                        backgroundColor: '#000000',
                        backgroundGradient: "low",
                        volumeSliderColor: '#333333',
                        volumeSliderGradient: "low",
                        progressColor: '#000000',
                        progressGradient: "low",
                        bufferColor: '#111111',
                        buttonColor: "#666666",
                        buttonOverColor: "#999999",
                        scrubberHeightRatio: 1,
                        volumeSliderHeightRatio: 1,
                        time: false,
                        tooltipColor: "#333333"
                    }
                }
            });
        }
        
        // setup video selection
        var boxes = tv.find(".videoSelection .box"),
            boxTop = 52, boxMargin = 6,
            boxLeft = tv.width()/2 - parseInt(("" + boxes.css('width')).replace("px", "")) / 2,
            boxHeight = parseInt(("" + boxes.css('height')).replace("px", ""));
        
        boxes.find(".image").click(function (e) {
            e.preventDefault();
            var id = $(this).parents(".box").get(0).id.substring(1);
            $.each(videos, function (i, video) {
                if (video.id == id) {
                    playVideo(video, true);
                    return false;
                }
            });
        });

        tv.find(".videoSelection .controls .replay").click(function (e) {
            e.preventDefault();
            playVideo(currentVideo, true);
        });

        tv.find(".videoSelection .controls .previous").click(function (e) {
            e.preventDefault();
            changeVideoPage(-1);
        });

        tv.find(".videoSelection .controls .next").click(function (e) {
            e.preventDefault();
            changeVideoPage(1);
        });

        function isActive(button) {
            if (button.hasClass("previous")
                && selection.index - selection.pageSize < 0)
                return false;
            
            if (button.hasClass("next")
                && selection.index + selection.pageSize >= selection.videos.length)
                return false;

            return true;
        }
        
        tv.find(".videoSelection .controls img").hover(function () {
            if (isActive($(this)))
                $(this).animate({ opacity: 0.8 }, 200);
        }, function () {
            if (isActive($(this)))
                $(this).animate({ opacity: 1 }, 200);
        });

        function getPage(page) {
            var res = [];
            for (var i = page; i < selection.videos.length; ++i) {
                res.push('#v' + selection.videos[i].id);
                if (res.length == selection.pageSize)
                    break;
            }
            return res;
        }

        function normalizedPageIndex(index) {
            index = Math.max(0, Math.min(index, selection.videos.length - 1));
            return index = parseInt(Math.floor(index / selection.pageSize) * selection.pageSize);
        }
        
        function changeVideoPage(direction) {
            // check bounds
            var index = normalizedPageIndex(selection.index + direction * selection.pageSize);
            if (index == selection.index)
                return;

            // stop animations
            boxes.stop(true, true);

            // make old boxes disappear
            boxes.filter(getPage(selection.index).join(',')).each(function (i) {
                var sign = direction * ((i % 2) * 2 - 1);
                $(this).animate({ left: "+=" + sign * 500 }, 500,
                                function () { $(this).hide(); });
            });
            
            selection.index = index;

            // make new boxes appear
            var visible = getPage(selection.index), offset = 600;
            for (var i = 0, top = boxTop - offset; i < visible.length; ++i) {
                boxes.filter(visible[i]).css({ top: top, left: boxLeft });
                top += boxHeight + boxMargin;
            }
            
            boxes.filter(visible.join(',')).show().animate({top: "+=" + offset}, { duration: 800, easing: 'easeOutExpo' });

            setControlsState();
        }

        function setControlsState() {
            tv.find(".videoSelection .controls img").each(function () {
                $(this).animate({ opacity: isActive($(this)) ? 1 : 0.5 }, 200);
            });
        }
        
        function showVideoSelection() {
            // guard against double call
            if (tv.find(".videoSelection:hidden").length == 0)
                return;

            if (flowplayer("tvVideoPlayer").getState() == 3) // if playing
                return;
            
            var visible = getPage(selection.index);
            
            boxes.not(visible.join(',')).hide();
            boxes.filter(visible.join(',')).show();
            for (var i = 0, top=boxTop; i < visible.length; ++i) {
                boxes.filter(visible[i]).css({ top: top, left: boxLeft });
                top += boxHeight + boxMargin;
            }
            
            tv.find(".videoSelection").fadeIn(1000);
            setControlsState();
        }

        function setupSelection() {
            var index = $.inArray(currentVideo, videos);
            selection.videos = [];
            $.each(videos, function (i, v) {
                if (v != currentVideo)
                    selection.videos.push(v);
            });
            selection.index = normalizedPageIndex(index);
        }

        function fillInInfo() {
            tv.find(".infoPane").css({ visibility: 'visible' });
            
            if (infoPaneVisible)
                toggleInfoPane();
            
            var html = "",
                c = tv.find("#v" + currentVideo.id).find(".infoContent");
            if (c.length > 0)
                html = c.html();
            tv.find(".infoPane .content").html(html);
        }
        
        function playVideo(video, autoPlay) {
            tv.find(".videoSelection").hide();
            tv.find("#tvVideoPlayer").show();
            currentVideo = video;

            setupSelection();
            fillInInfo();
            
            var clip = {
                url: video.url,
                autoPlay: autoPlay,
                autoBuffering: true,
                scaling: 'fit'
            };
            if (!flowplayerSetup) {
                setupFlowplayer(clip);
                flowplayerSetup = true;
            }
            else
                flowplayer("tvVideoPlayer").play(clip);

            if (autoPlay) {
                if (window.pageTracker)
                    window.pageTracker._trackEvent('Forsidevideo', 'Afspil', video.id);
                $.post(playingVideoUrl, { id: video.id });
            }
        }

        setTimeout(function() {
            var startPlaying = !$.cookie("beenOnFrontPage");
            playVideo(videos[0], startPlaying);
            if (!startPlaying)
                setTimeout(showVideoSelection, 1000);
            $.cookie("beenOnFrontPage", '1');
        }, 750);

        var infoPaneVisible = false,
            infoPaneHeight = tv.find('.infoPane').height();
        function toggleInfoPane() {
            if (!infoPaneVisible
                && tv.find('.infoPane .content .name').length == 0)
                return; // nothing to show
                
            var d = infoPaneHeight;
            if (!infoPaneVisible)
                d = -d;
            infoPaneVisible = !infoPaneVisible;
            tv.find('.infoPane').stop(true, true).animate({ top: "+=" + d }, 300);
        }
        
        tv.find('.infoTab').click(toggleInfoPane);
    }
    else
        tv.find(".showContent").hide();

    $(".chooser .productType img").hover(function () {
        $(this).animate({ opacity: 0.7 }, 200);
    }, function () {
	$(this).animate({ opacity: 1 }, 200);
    });

    // product news cycler
    var productNews = $(".productNewsBox .productNews");
    productNews.css({ display: 'none', visibility: 'visible' });
    var rand = Math.floor(Math.random()*productNews.length);
    $(productNews.get(rand)).show();
    
    $(".productNewsBox .left, .productNewsBox .right").click(function(e) {
        e.preventDefault();
        
        var direction = $(this).hasClass("left") ? -1 : 1;
        var total = productNews.length;
        var i = productNews.index(productNews.filter(":visible").hide());
        var n = (i + direction) % total;
        if (n < 0)
            n = total - 1;
        productNews.filter(":nth(" + n + ")").show().find('.image');
    });

    $(".facebookBox a").click(function() {
        if (window.pageTracker)
            window.pageTracker._trackPageview('/_/facebook/');
    });

    $(".ostriches img").click(function() {
        window.location = "/vind-en-struds/";
    });

    // animate ostriches
    function animateOstrich(config) {
        config.el.animate(config.ani1, 700, "easeOutElastic", function() {
            config.el.animate(config.ani2, 600, "easeOutQuint");
            setTimeout(function() { 
                config.el.animate(config.ani3, 300, "easeInQuint");
                queueOstrichAnimation();
            }, 5000);
        });
    }
    var ostrichConfigs = [{
        el: $(".ostrichLeft"), 
        ani1: {top: "250px", left: "-50px"}, 
        ani2: {left: 0, top: "230px"}, 
        ani3: {left: "-200px", top: "300px"}
    }, {
        el: $(".ostrichRight"), 
        ani1: {top: "150px", right: "-50px"}, 
        ani2: {right: 0, top: "135px"}, 
        ani3: {right: "-200px", top: "200px"}
    }, {
        el: $(".ostrichBottom"), 
        ani1: {bottom: "-50px", left: "650px"}, 
        ani2: {bottom: 0, left: "665px"}, 
        ani3: {bottom: "-200px", left: "600px"}
    }];

    function queueOstrichAnimation() {
        var i = Math.floor(Math.random()*ostrichConfigs.length);
        var config = ostrichConfigs[i];
        var delay = Math.floor(Math.random()*20) + 10;
        setTimeout(function() {
            animateOstrich(config);
        }, delay*1000);
    }
    queueOstrichAnimation();
});
