function isEmpty(o) {
    for (var i in o)
        return false;

    return true;
}

function overlapping(a, b) {
    for (var i = 0; i < a.length; ++i)
        if ($.inArray(a[i], b) != -1)
            return true;

    return false;
}


function popupVideoPlayer(videoUrl, videoId) {
    var flow = null;
    $('#videoDialog').modal({
        close: true,
        overlay: 85,
        persist: true,
        overlayId: 'videoOverlay',
        onShow: function() {
            $("#videoDialog").addClass("reset");
            
            $(".modalCloseImg").fadeIn(300);
            if (flashembed.isSupported([9, 0])) {
                flowplayer("videoPlayer").play({
                    url: videoUrl,
                    scaling: "fit"
                });
            }
        },
        onClose: function() {
            if (flashembed.isSupported([9, 0]))
                $f().unload();
            $(".modalCloseImg").hide();

            $.modal.close();
            if (window.location.hash)
                window.location.hash = "none";
        }
    });

    if (window.pageTracker)
        window.pageTracker._trackEvent('Produktsidevideo', 'Afspil', videoId);
    $.post(playingVideoUrl, { id: videoId });
}

$(function () {
    /*
    $(document).find("img[src*=.png]").each(function() {
	//alert("w " + $(this).width() + " h " + $(this).height());
    });
    */
    
    // menu
    function setupMenu() {
        var options = 300;//{ queue: true, duration: 500 };
        var menu = $("#top .menu"), items = menu.find(".middle");
        var currentPageItem = items.filter(".active");

        items.each(function () {
            $(this).data('state', $(this).hasClass("active") ? "active" : "inactive");
        });

        function activateItem(item) {
            hovers(item).fadeOut(1);
            
            // make sure the hover to the left looks OK
            var rightHover = item.prev().find('.rightHover');
            if (rightHover.length > 0) {
                var src = rightHover.attr("src")
                if (src.indexOf('right-active') == -1)
                    rightHover.attr("src", src.replace("right.", "right-active."));
            }

            var index = items.index(item);

            // activate item
            if (item.data("state") != "active") {
                //console.log("activating", item.find('a').text())
                item.data("state", "active");

                // the algorithm goes like this: make sure the right image
                // is on top, then fade it in
                var prev = item.prev(), next = item.next();
                if (prev.hasClass("left"))
                    prev.find('.active').fadeIn(options);
                else
                    prev.find('.rightActive').hide().css('z-index', 1).fadeIn(options);
                
                if (next.hasClass("right"))
                    next.find('.active').fadeIn(options);
                else {
                    next.find('.leftActive').hide();
                    next.find('.rightActive').css('z-index', -1);
                    next.find('.leftActive').fadeIn(options);
                }
                item.animate({'backgroundColor': "#f78501"}, options);
            }

            // deactive the others
            items.each(function (i) {
                var otherItem = $(this);
                if (otherItem.data("state") == "active" && i != index) {
                    //console.log("deactivating", otherItem.find('a').text())
                    
                    otherItem.data("state", "inactive");

                    var prev = otherItem.prev(), next = otherItem.next(),
                        activeToTheRight = i + 1 == index,
                        activeToTheLeft = i - 1 == index;

                    if (prev.hasClass("left"))
                        prev.find('.active').fadeOut(options);
                    else
                        prev.find('.rightActive').fadeOut(options);
                
                    if (next.hasClass("right"))
                        next.find('.active').fadeOut(options);
                    else
                        next.find('.leftActive').fadeOut(options);
                    
                    otherItem.animate({'backgroundColor': "#fff"}, options);
                }
            });
        }

        menu.find(".middle a").click(function (e) {
            $(this).blur();
        });

        menu.find(".middle").click(function (e) {
            e.preventDefault();

            var item = $(this);
            
            activateItem(item);
            setTimeout(function () {
                window.location = item.find("a").attr("href");
            }, 500);
        });

        function hovers(element) {
            return element.find(".hover")
            .add(element.prev().find(".leftHover"))
            .add(element.next().find(".rightHover"));
        }
        
        menu.find(".middle").hoverIntent(function () {
            if ($(this).data("state") == "inactive")
                hovers($(this)).fadeOut(200);
        }, function () {
            if ($(this).data("state") == "inactive")
                hovers($(this)).fadeIn(200);
        });
    }

    setupMenu();

    // actually this shouldn't be necessary, but IE doesn't quite get
    // that the link is on top of everything
    $(".oneBigLink").click(function () {
        window.location.href = $(this).find("a").attr('href');
    });
    
    $("a.submit").click(function (e) {
        e.preventDefault();
        $(this).parents("form").submit();
    });

    // reseller box
    $(".resellerBox").each(function () {
        var box = $(this),
            zipcodeBox = box.find(".zipcode"),
            arrows = box.find(".arrows");
        
        arrows.click(function (e) {
            e.preventDefault();

            var zip = $.trim(zipcodeBox.val());
            if (/^\d\d\d\d$/.test(zip))
                window.location = "/forhandlere/#zipcode=" + zip;
            else
                zipcodeBox.val("ugyldigt postnummer");
        });
        zipcodeBox.keypress(function (e) {
            if (e.which == 13)
                arrows.click();
        });
        zipcodeBox.labelify();
        zipcodeBox.click(function (e) {
            $(this).val("");
        });
    });

    // videos
    /*
    function setupCompetitionBox(video_id) {
        var box = $("#videoInfoBox");
        var emailTo = $("#id_receiver", box),
            nameTo = $("#id_receiver_name", box),
            emailFrom = $("#id_sender", box),
            nameFrom = $("#id_sender_name", box),
            finish = $(".finish a", box);

        $("#id_video", box).val(video_id);

        $(".field", box).labelify();

        var emailCookie = $.cookie("myemail");
        if (emailCookie) {
            emailFrom.val(emailCookie);
        }
        var nameCookie = $.cookie("myname");
        if (nameCookie) {
            nameFrom.val(nameCookie);
        }
        finish.click(function (e) {
            e.preventDefault();
            $.cookie("myemail", emailFrom.val(), { path: '/', expires: 100 });
            $.cookie("myname", nameFrom.val(), { path: '/', expires: 100 });
            $("#competitionForm", box).ajaxSubmit({
                success: function(response) {
                    $(".competitionBox", box).html(response);
                    $("input", box).ifixpng();
                    setupCompetitionBox(video_id);
                }});
        });
        
        $("#competitionForm", box).bind("submit", function(e) {
            e.preventDefault();
            finish.click();
        });
    }
    
    function resetCompetitionBox(videoId) {
        $(".competitionBox").load("/competition/send/");
    }*/

    if (flashembed.isSupported([9, 0])) {
        $("#videoPlayer").text(".").css({ color: "#000" });
        flowplayer("videoPlayer", 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"
                }
            }
        });
    }
        
    $('.video').click(function() {
        var url = $(this).attr("name"), id = $(this).attr("alt");
        popupVideoPlayer(url, id);
        return false;
    });

    var IE6 = $.browser.msie && ("" + $.browser.version).charAt(0) == '6';
    
    if (!IE6) {
        $(".lightbox-enabled").click(function (e) {
            e.preventDefault();
            $(this).lightbox({ start: true, events: false });
        });
    }

    // PNG  hacking
    function replacePngWithGif(elements) {
        elements.each(function () {
            var src = $(this).attr('src'), gifsrc = src.replace('.png', '.gif');
            if (src != gifsrc)
                $(this).attr('src', gifsrc); 
        });       
    }
    
    if (IE6)
        replacePngWithGif($("img[src*=button-]"));

    if ($.browser.msie && (("" + $.browser.version).charAt(0) == '7' ||
                           ("" + $.browser.version).charAt(0) == '8'))
        replacePngWithGif($(".productGrid .left img,.productGrid .right img, " +
                            ".products .left img,.products .right img"));
    
    $.ifixpng($("#blankPixel").attr("src"));
    $('img[src*=.png], input[src*=.png], .wideBox, .resellerBox .zipcode, .smsBox .email, #frontpage .tv, .videoOverview .tv, #frontpage .tv .videos .video, #frontpage .resellerLogin input, #frontpage .news .body, .linkPage .linkSidebar, .shoppingListPage .leftSidebar, .shoppingListPage .shoppingListBox, .productOverview .leftSidebar .leftSearchForm, .productOverview .leftSidebar .resellerInfoBox, .videoOverview .leftSidebar .leftSearchForm, #resellers .mainBox, #resellers .mapBox .zipcodeInput .zipcode, .videoInTv, #videoInfoBox .field, #frontpage .catalogBox a').ifixpng();

    // opacity hacking
    $("#frontpage .tv .videoSelection .box").css('opacity', 0.95);
    $("#frontpage .tv .videoSelectionBackground").css('opacity', 0.8);
    $("#frontpage .tv .infoPane .content").css('opacity', 0.9);
});

var qtipProductTypeStyle = {
    position: {
        corner: {
            target: 'topMiddle',
            tooltip: 'bottomMiddle'
        }
    },

    style: {
        width: {max: 170},
        background: '#000',
        color: '#fefefe',
        textAlign: 'center',
        border: {
            width: 1,
            radius: 3,
            color: '#fff'
        },
        tip: {
            corner: 'bottomMiddle',
            color: '#fff',
            size: {
                x: 10,
                y : 6
            }
        },
        name: 'dark'
    }
};

