$(document).ready(function () {

    $(".tiptip").tipTip({ maxWidth: "200", edgeOffset: 10 });

    var clickedSubcat = null;
    var sections = [];

    productInitBinding();

    updateBasket();

    function moveDetails(target, event) {
        var contentPos = $("#container").position();
        var left = event.pageX - contentPos.left;
        var top = event.pageY - contentPos.top;

        left += 5;
        top += 5;

        target.css("left", left);
        target.css("top", top);
    }

    $(".tabs-product>li").hover(function () {
        var jq = $(this);
        var showMenuTarget = jq.find("ul");
        showMenuTarget.show();
    },
    function () {
        var jq = $(this);
        var hideMenuTarget = jq.find("ul");
        hideMenuTarget.hide();
    });

    $(".category-header .readmore").click(function (event) {
        event.preventDefault();

        var jq = $(this).next();

        $.blockUI({
            message: jq.html(),
            overlayCSS: { cursor: 'pointer' },
            css: { cursor: 'normal', top: '10%', border: '10px solid #eaeaea', padding: '10px 0', backgroundColor: '#ffffff', width: '600px', 'box-shadow': '1px 1px 17px #000000', '-moz-box-shadow': '1px 1px 17px #000000', '-webkit-box-shadow': '1px 1px 17px #000000' }
        });
        $('.blockOverlay,.closeforgot,.closetext, #close_icon').attr('title', 'Klik for at lukke').click($.unblockUI);
        $('.blockUI.blockMsg').css("left", ($(window).width() - $('.blockUI.blockMsg').width()) / 2 + $(window).scrollLeft() + "px");
    });

    $("#delivery label").click(function (event) {
        var deliveryfield = $(this).prev("input");

        var currentCount = Number($("#packsize").val());
        var freeCount = Number($("#free-count").val());

        if (deliveryfield.val() != "once") {
            if (currentCount % 5 == 0) {
                for (var i = 0; i < freeCount; i++) {
                    $("#pakkemarked-product-holder").append($("<div class='idle-product-slot xtra-product-slot' />"));
                    currentCount++;
                }
            }
        }
        else {
            if (currentCount % 5 > 0) {
                for (var i = 0; i < freeCount; i++) {
                    $("#pakkemarked-product-holder div").last().remove();
                }
                currentCount -= freeCount;
            }
        }
        $("#packsize").val(currentCount);

        setTimeout(function () {
            updatePakkemarkedSelection();

            var areaPressed = $("#delivery [aria-pressed=true]");
            var deliveryfield = areaPressed.prev("input");

            if (deliveryfield.val() != "once") {
                if ($("#RelatedDeliverySubscriptionProduct").val() != "") {
                    window.location.href = $("#RelatedDeliverySubscriptionProduct").val();
                }
            }
            else {
                if ($("#RelatedDeliveryOnceProduct").val() != "") {
                    window.location.href = $("#RelatedDeliveryOnceProduct").val();
                }
            }
        }, 300);
    });

    if ($("#delivery label").length == 1) {

        $("#delivery label").attr("aria-pressed", "true");
        var deliveryfield = $("#delivery label").prev("input");
        deliveryfield.attr("checked", "checked");
    }

    $(".cart-content .product-name").mouseover(function (event) {
        var jq = $(this);
        var details = jq.find(".subproducts");
        details.show();
        moveDetails(details, event);
    });

    $(".cart-content .product-name").mousemove(function (event) {
        var jq = $(this);
        var details = jq.find(".subproducts");
        moveDetails(details, event);
    });

    $(".cart-content .product-name").mouseout(function (event) {
        var jq = $(this);
        var details = jq.find(".subproducts");
        details.hide();
    });

    /*
    var subscriptionUrlParam = $.query.get("subscription");
    if (subscriptionUrlParam != null &&
    subscriptionUrlParam != "") {
    $(".product3 .product-price").hide();
    }
    */

    $("#tips-show-more").click(function (event) {
        event.preventDefault();
        $(this).remove();
        $("#tips-more").show(1000);
    });

    $(".dropdown-box").click(function () {
        var jq = $(this);
        //var list = $("#" + jq.attr("dd"));
        var list = jq.find(".dropdown");
        list.attr("jqforce", "0");
        list.css("position", "absolute");
        //list.css("top", jq.offset().top + jq.height());
        //list.css("left", jq.offset().left);
        list.slideDown('fast').show();

        jq.unbind('hover');
        jq.hover(function () {
        },
        function () {
            $(this).find(".dropdown").slideUp('slow');
        });

        list.find("li div").unbind('click');
        list.find("li div").click(function (event) {
            if (event.stopPropagation) { event.stopPropagation(); } //For 'Good' browsers
            else { event.cancelBubble = true; } //For IE

            $(this).parents(".dropdown").slideUp('slow');
            $(this).parents(".dropdown-box").find(".input-field-content-repeat").html($(this).html());
            $(this).parents(".dropdown").find("input").val($(this).attr("value"));
            $(this).parents(".dropdown").find("input").change();
        });
    });

    // top video
    $("#header-flash").flashembed({
        src: "/img/layout/topvideo.swf",
        wmode: "transparent",
        width: "200",
        height: "149",
        onFail: function () {
            $("#header-flash").html("<img src='/img/layout/topvideo.png' />");
        }
    });

    $("#banner-winner").cycle();

    $("#packsize input, #delivery input").button();

    $("#delivery label[aria-pressed=true]").click();

    if ($(".pakkemarked-id").length == 1) {

        var initProducts = $("#fixedProductsIds").val();

        var args = null;
        var subscriptionId = $.query.get("subscriptionid");
        if (subscriptionId > 0) {
            args = {
                subscriptionId: subscriptionId
            };
        }
        else {
            args = {
                vareid: $(".pakkemarked-id").val()
            };
        }

        if (initProducts.length > 0) {
            /*
            $.ajax({
            type: "POST",
            url: '/ajax/pakkemarked.php?interval=1',
            data: args,
            cache: false,
            success: function (data) {
            if (data != "") {
            var selectedRadio = $("#delivery input[value=" + data + "]");
            selectedRadio.attr("checked", "checked");
            selectedRadio.next("label").click();
            }
            }
            });
            */
            $(".idle-product-slot").remove();
            var products = initProducts.split(",");
            for (var i = 0; i < products.length; i++) {
                var jq = $($(".product" + products[i])[0]);
                jq.find(".btn").click();
            }
        }
        else {
            // init pakkemarked
            $.ajax({
                type: "POST",
                url: '/ajax/pakkemarked.php?r=' + Math.random(),
                data: args,
                cache: false,
                success: function (data) {
                    var productsAdded = 0;
                    if (data != "") {
                        var products = data.split(",");
                        for (var i = 0; i < products.length; i++) {
                            var productData = products[i].split("=");
                            if (productData.length > 1) {
                                selectedTips.push(products[i]);
                            }
                            var jq = $($(".product" + productData[0])[0]);
                            //jq.find(".product-id").val(products[i]);
                            jq.find(".btn").click();
                            //jq.find(".product-id").val(productData[0]);

                            productsAdded++;
                        }

                        $("#subscription-recipe").val(selectedTips.join(","));
                    }

                    if (productsAdded == 0) {
                        updatePakkemarkedSelection();
                    }
                }
            });
            /*
            $.ajax({
            type: "POST",
            url: '/ajax/pakkemarked.php?interval=1',
            data: args,
            success: function (data) {
            if (data != "") {
            var selectedRadio = $("#delivery input[value=" + data + "]");
            selectedRadio.attr("checked", "checked");
            selectedRadio.next("label").click();
            }
            }
            });
            */
        }
    }

    $("ul.tabs").tabs("div.panes > div");
    var api = $("ul.tabs").data("tabs");
    var selectedTips = Array();

    $(".tip-content, .category-header").corner("6px");

    $(".tip-content-expand").click(function (event) {
        event.preventDefault();
        var jq = $(this);
        var itemToExpand = jq.siblings(".tip-content-container");
        var targetHeight = itemToExpand.find("div").height();

        jq.remove();

        itemToExpand.animate({
            height: targetHeight
        },
        1000);
    });

    $("#search-input-text").watermark("Søg her");

    $("#serach-input-submit").click(function (event) {
        var jq = $("#search-input-text");

        if (jq.val() == "" || jq.hasClass("watermark") == true) {
            showInfoBox(jq, "Søgning mangler", "Husk at angive din søgning i søgefeltet");
            event.preventDefault();
        }
    });

    $("#zip-btn").click(function (event) {
        var jq = $("#zip-text");

        if (jq.val() == "" || jq.hasClass("watermark") == true) {
            showInfoBox(jq, "Postnummer mangler", "Husk at angive dit postnummer i feltet");
            event.preventDefault();
            return;
        }

        $("#find-delivery").block({
            message: 'Øjeblik...',
            css: { border: '2px solid #7C865B', top: '44px', top: '32px', width: '125px' }
        });
        $.ajax({
            type: "POST",
            url: "/ajax/deliverydate.php",
            data: ({ Zip: jq.val() }),
            success: function (data) {
                $("#find-delivery-result").removeClass("hidden");
                $("#find-delivery").addClass("hidden");
                $("#find-delivery-result-text").html(data);
                $("#find-delivery").unblock();
            }
        });
    });

    $("#find-delivery-result .close-icon").click(function (event) {
        $("#find-delivery-result").block({
            message: 'Øjeblik...',
            css: { border: '2px solid #7C865B', top: '44px', top: '32px', width: '125px' }
        });
        $.ajax({
            type: "POST",
            url: "/ajax/deliverydate.php",
            data: ({ Zip: '' }),
            success: function (data) {
                $("#find-delivery-result").addClass("hidden");
                $("#find-delivery").removeClass("hidden");
                $("#find-delivery-result").unblock();
            }
        });
    });

    $("#topmenu a").click(function (event) {
        event.preventDefault();
        var jq = $(this);

        var classNames = jq.attr("class").split(" ");
        var className = "";
        for (var i = 0; i < classNames.length; i++) {
            if (classNames[i].substring(0, 7) == "section" || classNames[i].substring(0, 3) == "cat") {
                className = classNames[i];
            }
        }

        // location has has to be main cat
        var locationHash = className;
        if (locationHash.substring(0, 3) != "cat") {
            locationHash = jq.parents(".submenu").siblings("a").attr("class");
        }
        window.location.hash = locationHash;

        if (className.substring(0, 3) == "cat") {
            var cat = className.substring(3);
            // load products
            $.blockUI({ message: null });
            $.ajax({
                url: '/ajax/products.php?cat=' + cat,
                success: function (data) {
                    $('#content-inner').html(data);

                    $("#packsize input, #delivery input").button();

                    productInitBinding();

                    if (clickedSubcat != null) {
                        clickedSubcat.click();
                    }
                    else {
                        $('html, body').animate({
                            scrollTop: 0
                        }, 2000);
                    }
                    fixDivPos();
                    $.unblockUI();
                }
            });
        }
        else {
            clickedSubcat = null;

            fixDivPos();

            var sectionId = className.substring(7);
            var section = $(".sectioncontainer" + sectionId);
            if (section.length == 0) {
                // load the category
                jq.parents(".submenu").prev().click();
                clickedSubcat = jq;
                return;
            }
            $('html, body').animate({
                scrollTop: section.offset().top - 175
            }, 2000);
        }
    });

    /*
    $('#feedback-tab').toggle(function () {
    $(this).animate({ "marginLeft": "-=5px" }, "fast");
    $('#feedback-form').animate({ "marginLeft": "-=0px" }, "fast");
    $(this).animate({ "marginLeft": "+=387px" }, "slow");
    $('#feedback-form').animate({ "marginLeft": "+=390px" }, "slow");
    },
    function () {
    $('#feedback-form').animate({ "marginLeft": "-=390px" }, "slow");
    $(this).animate({ "marginLeft": "-=387px" }, "slow").animate({ "marginLeft": "+=5px" }, "fast");
    });

    $("#closeicon").click(function (event) {
    var submenus = $("#submenus");
    if (submenus.hasClass("sticky") == true) {
    submenus.removeClass("sticky");
    }
    submenus.css("display", "none");
    });
    $(".header a").mouseover(function () {
    var jq = $(this);
    var submenus = $("#submenus");
    if (submenus.hasClass("sticky") == false) {
    submenus.css("display", "block");
    submenus.css("opacity", "0.5");
    submenus.css("filter", "alpha(opacity=50)");
    }
    });
    $(".header a").mouseout(function () {
    var jq = $(this);
    var submenus = $("#submenus");
    if (submenus.hasClass("sticky") == false) {
    submenus.css("display", "none");
    }
    });

    function fixDivPos() {
    var tdoffset = $("#submenus").offset();
    var container = $("#submenucontainer");

    if (tdoffset.top < $(document).scrollTop()) {
    if ($.browser.msie) {
    container.css("top", $(document).scrollTop());
    container.css("left", tdoffset.left + 10);

    container.css("position", "absolute");
    }
    else {
    container.css("position", "fixed");
    }
    }
    else {
    container.css("position", "relative");
    if ($.browser.msie) {
    container.css("top", 0);
    container.css("left", 0);
    }
    }
    }
    */

    function fixDivPos() {
        var scroll = $(document).scrollTop();

        // update header
        var header = $("#header");
        //var scrollStartTarget = 26;
        //var topFix = -8;

        var scrollStartTarget = 0;
        var topFix = 0;

        if ($("#pakkemarked-box").length > 0) {
            header.css("position", "relative");
            header.css("top", "");

            header = $("#pakkemarked-box");
            scrollStartTarget = 270;
            topFix = 0;
        }
        else if ($("#product-list").length == 0) {
            scroll = 0; // simulate top of page all the time
        }


        if (scroll >= scrollStartTarget) {
            // make it scroll
            header.css("position", "fixed");
            header.css("top", topFix + "px");
        }
        else {
            header.css("position", "relative");
            header.css("top", "");
        }

        // update basket
        var basket = $("#basket");
        var basketCopyTarget = $("#basket-copy-target");
        var basketContainer = $("#basket-container");

        var basketOffset = basket.offset().top;
        var basketCopyTargetOffset = basketCopyTarget.offset().top;
        var basketContainerOffset = basketContainer.offset().top;

        if (scroll > basketCopyTargetOffset - 220) {
            basket.css("position", "fixed");
            basket.css("top", "220px");
        }
        else if (scroll > basketContainerOffset - 50) {
            basket.css("position", "absolute");
            basket.css("top", basketCopyTargetOffset);
        }
        else {
            basket.css("position", "static");
            basket.css("top", "");
        }

        if (sections.length > 0) {
            // update active menu item
            var activeSection = sections[0];
            for (var i = 0; i < sections.length; i++) {
                var section = sections[i];
                if (scroll > section.top - 400) {
                    activeSection = section;
                }
            }
            $(".submenu a").removeClass("active");
            var sectionId = activeSection.jq.attr("name").substring(7);
            $(".submenu .section" + sectionId).addClass("active");
        }
    }

    var animatingProducts = 0;
    function addProductToPakkemarked(vareid, image, countfor, altText) {
        var emptySlots = updatePakkemarkedSelection() - animatingProducts;

        if (emptySlots <= 0) {
            alert("Du har ikke plads til flere varer");
            return;
        }
        else if (emptySlots < countfor) {
            alert("Du har ikke plads til denne vare");
            return;
        }
        //animatingProducts += intval(countfor);
        // animate the image placement
        var animateImage = $("<div><img src='" + image.attr("src") + "' /></div>");
        animateImage.css("position", "absolute");
        animateImage.css("z-index", "1000");
        animateImage.css("left", image.offset().left);
        animateImage.css("top", image.offset().top);
        animateImage.appendTo(document.body);
        animateImage.attr("vareid", vareid);
        animateImage.attr("countfor", countfor);
        animateImage.attr("alt", altText);
        animateImage.attr("title", altText);

        animatingProducts += Number(animateImage.attr("countfor"));

        var holder = $("#pakkemarked-product-holder");
        var offset = holder.offset();

        animateImage.animate({ "left": offset.left, "top": offset.top },
                    1000,
                    "linear",
                    function () {
                        var jq = $(this);
                        jq.css("position", "static");
                        jq.css("float", "left");
                        //jq.css("width", "40px");
                        //jq.css("height", "40px");
                        //jq.css("margin", "0 3px 2px 0");
                        if (jq.attr("countfor") > 1 && jq.attr("countfor") % 1 == 0) {
                            jq.addClass("selected-product-slot selected-product-slot" + Number(jq.attr("countfor")));
                        }
                        else if (jq.attr("countfor") % 1 == 0.5) {
                            if (jq.attr("countfor") == 0.5) {
                                jq.addClass("selected-product-slot-half");
                            }
                            else {
                                jq.addClass("selected-product-slot selected-product-slot-half" + Math.floor(Number(jq.attr("countfor"))));
                            }
                        }
                        else {
                            jq.addClass("selected-product-slot");
                        }

                        if (jq.attr("countfor") == 0.5) {
                            jq.prependTo($("#pakkemarked-product-holder"));
                        }
                        else {
                            jq.appendTo($("#pakkemarked-product-holder"));
                        }
                        animatingProducts -= Number(jq.attr("countfor"));
                        updatePakkemarkedSelection();

                        if (pakkemarkedHasUnlimitedSpace() == true) {
                            addProductToBasket(false, jq.attr("vareid"), 1, 0, "");
                        }

                        jq.click(function () {
                            var jq = $(this);
                            var vareid = jq.attr("vareid");

                            var initProducts = $("#fixedProductsIds").val();
                            if (initProducts.length > 0) {
                                return;
                            }

                            if (pakkemarkedHasUnlimitedSpace() == true) {
                                removeProductFromBasket(vareid);
                            }

                            // decrement purchase count
                            var productCountContainer = $(".product-count-id" + vareid);
                            productCountContainerValue = Number($(productCountContainer.get(0)).text());
                            if (productCountContainerValue > 0) {
                                productCountContainerValue--;
                            }
                            productCountContainer.text(productCountContainerValue);

                            $(this).remove();
                            updatePakkemarkedSelection();
                        });
                    });
        animateImage.children(":first").animate({ "width": 40, "height": 40 }, 1000);
    }

    $("#packsize input").change(function () {
        updatePakkemarkedSelection();
    });

    function pakkemarkedGetPackSize() {
        //var maxSelection = $("#packsize input:checked").val();
        var maxSelection = $("#packsize").val();

        if (maxSelection == 0) {
            maxSelection = 10000; // unlimited space
        }

        return maxSelection;
    }

    function pakkemarkedHasUnlimitedSpace() {
        var maxSelection = $("#packsize").val();
        return maxSelection == 0;
    }

    function updatePakkemarkedSelection() {

        var initProducts = $("#fixedProductsIds").val();
        if (initProducts.length > 0) {
            saveDraftPakkemarked([], $(".pakkemarked-id").val());
            return 0;
        }

        if (pakkemarkedHasUnlimitedSpace() == true) {
            return pakkemarkedGetPackSize();
        }
        var maxSelection = pakkemarkedGetPackSize();

        var allPakkemarkedProducts = [];
        var allPakkemarkedProductsTips = [];
        var selectedPakkemarkedCount = 0;
        var halfProducts = 0;

        var allAddedItems = $("#pakkemarked-product-holder div");
        for (var i = 0; i < allAddedItems.length; i++) {
            var jq = $(allAddedItems.get(i));
            if (jq.hasClass("idle-product-slot") == false) {
                allPakkemarkedProducts.push(jq.attr("vareid"));
                allPakkemarkedProductsTips.push(jq.attr("vareid"));
                selectedPakkemarkedCount += Number(jq.attr("countfor"));

                if (jq.attr("countfor") == 0.5) {
                    halfProducts++;
                }

                if (jq.hasClass("selected-product-slot-half") == true) {
                    if (halfProducts % 2 == 0) {
                        jq.addClass("alt");
                    }
                    else {
                        jq.removeClass("alt");
                    }
                }
            }
        }

        $("#pakkemarked-product-holder .idle-product-slot").remove();
        for (var i = maxSelection - selectedPakkemarkedCount; i > 0.5; i--) {
            if (maxSelection % 5 > 0 && i > maxSelection - maxSelection % 5 && $("#free-count").val() > 0) {
                $("#pakkemarked-product-holder").append("<div class='idle-product-slot xtra-product-slot' />");
            }
            else {
                $("#pakkemarked-product-holder").append("<div class='idle-product-slot' />");
            }
        }

        $("#pakkemarked-selection-count").html($.format("{0} af {1}",
            selectedPakkemarkedCount,
            maxSelection));

        var selectedTipsCopy = Array();
        for (var i = 0; i < selectedTips.length; i++) {
            selectedTipsCopy.push(selectedTips[i]);
        }

        for (var i = 0; i < allPakkemarkedProductsTips.length; i++) {
            var removeIndex = -1;
            for (var j = 0; j < selectedTipsCopy.length; j++) {
                var tipData = selectedTipsCopy[j].split("=");
                if (tipData[0] == allPakkemarkedProductsTips[i]) {
                    allPakkemarkedProductsTips[i] += "=" + tipData[1];
                    removeIndex = j;
                    break;
                }
            }

            if (removeIndex != -1) {
                selectedTipsCopy.splice(removeIndex, 1);
            }
        }

        var productData = allPakkemarkedProducts.join(",");
        var productDataTips = allPakkemarkedProductsTips.join(",");

        $("#subscription-varer").val(productData);

        //$("#subscription-recipe").val(selectedTips.join(","));

        $("#pakkemarked-selection").css("display", "block");

        saveDraftPakkemarked(productDataTips, $(".pakkemarked-id").val());

        return maxSelection - selectedPakkemarkedCount;
    }

    function saveDraftPakkemarked(data, pakkemarkedId) {
        var areaPressed = $("#delivery [aria-pressed=true]");
        var deliveryinterval = 0;
        if (areaPressed.length > 0) {
            var deliveryfield = areaPressed.prev("input");
            deliveryfield.attr("checked", "checked");
            deliveryinterval = deliveryfield.val();
        }
        else {
            deliveryinterval = $.ajax({
                type: "POST",
                url: '/ajax/pakkemarked.php?interval=1',
                data: { vareid: $(".pakkemarked-id").val() },
                async: false
            }).responseText;
        }

        var subscriptionId = $.query.get("subscriptionid");
        if (subscriptionId > 0) {
            $.ajax({
                type: "POST",
                url: '/ajax/pakkemarked.php',
                async: false,
                data: { varer: data, vareid: pakkemarkedId, deliveryinterval: deliveryinterval, subscriptionId: subscriptionId }
            });
            return;
        }

        $.ajax({
            type: "POST",
            url: '/ajax/pakkemarked.php',
            async: false,
            data: { varer: data, vareid: pakkemarkedId, deliveryinterval: deliveryinterval, subscriptionId: 0 }
        });
    }

    function productInitBinding() {
        $.ajax({
            url: '/ajax/incompletebox.php',
            success: function (msg) {
                $("#incomplete-box").html(msg);

                $("#cancel-draft-pakkemarked").click(function (event) {
                    event.preventDefault();
                    saveDraftPakkemarked("", 0);
                    $(this).parent().remove();
                });
            }
        });


        $(".product-page #delivery label").click(function (event) {

            var jq = $(this);

            var index = jq.index("#delivery label");

            if (index == 0) {
                addProductToBasket(false, $(".product-id").val(), 1, "", "");
            }
            else {
                $("#delivery input").attr("checked", false);
                $("#delivery input:eq(" + index + ")").attr("checked", true);
                jq.parents("form")[0].submit();
            }

        });

        $(".product-purchase-btn input.btn, .add-to-basket-button-advanced input.btn").click(function (event) {
            var jq = $(this);

            var form = jq.parents('form:first');
            //var vareid = jq.find("product-id").val();
            var vareid = form.find("input[name=id]").val();

            var allowed = $.ajax({
                type: "GET",
                url: '/isproductallowed.php',
                data: { vareid: vareid },
                async: false
            }).responseText;
            if (allowed == 0) {
                event.preventDefault();
                alert("Det er kun tilladt at købe én af denne vare.");
                return;
            }

            var basket = $("#basket");
            var offset = basket.offset();

            //alert(jq.parents(".add-to-basket-button-advanced").length);

            if (jq.parents(".product-purchase-btn-subscription").length > 0) {
                var sourceimg = jq.parents(".product").find(".product-image img");
                var countfor = form.find("input[name=countfor]").val();
                var altText = form.find("div.product_name").text();

                // increment purchase count
                var productCountContainer = $(".product-count-id" + vareid);
                productCountContainerValue = Number($(productCountContainer.get(0)).text());
                if (productCountContainerValue > 0) {
                    productCountContainerValue++;
                }
                else {
                    productCountContainerValue = 1;
                }
                if (productCountContainer.parents(".inspirationbox").length > 0) {
                    productCountContainerValue = 1;
                }
                productCountContainer.text(productCountContainerValue);

                addProductToPakkemarked(vareid, sourceimg, countfor, altText);
                event.preventDefault();
                return false;
            }
            else if (jq.parents(".add-to-basket-button-advanced").length > 0) {
                var emptySlots = updatePakkemarkedSelection()
                if (emptySlots != 0) {
                    alert("Din kasse mangler " + emptySlots + " varer");
                    event.preventDefault();
                    return;
                }

                // get count
                //var deliveryinterval = form.find("input[name=period]:checked").val();
                var deliveryfield = $("#delivery [aria-pressed=true]").prev("input");
                deliveryfield.attr("checked", "checked");
                var deliveryinterval = deliveryfield.val();
                //alert(deliveryinterval);
                if (deliveryinterval != "once") {
                    return;
                }

                var subscriptionid = $.query.get("subscriptionid")
                if (subscriptionid != null && subscriptionid != "") {
                    return;
                }
                event.preventDefault();

                //showOverlay(true);

                var recipe = form.find("input[name=recipe]").val();
                //var recipe = "";
                var count = form.find("input[name=stk]").val();
                var selectedvarer = form.find("#subscription-varer").val();

                if (count == null || isNaN(count) == true) {
                    count = 1;
                }

                // add to basket
                /*
                $.ajax({
                type: "POST",
                url: "/shop.php?action=addAdvanced&id=" + vareid,
                data: ({ stk: count, recipe: recipe, selectedvarer: selectedvarer }),
                async: true,
                success: function (msg) {
                var resp = $.ajax({
                type: "GET",
                url: "/getbasket.php",
                data: ({ "isajax": 1 }),
                async: false
                });
                $("#basketpanel").html(resp.responseText);

                $(copymenusourceid).css("height", $("#basketpanel").height());
                $(copymenutargetid).css("height", $("#basketpanel").height());
                copymenutargetstartyoffset = $("#belowmenutarget").position().top;
                updateBasketMovement(null);
                }
                });
                */

                var initProducts = $("#fixedProductsIds").val();

                if (initProducts.length > 0) {
                    addProductToBasket(false, vareid, count, 0, '');
                }
                else {
                    addProductToBasket(true, vareid, count, recipe, selectedvarer);
                }
                alert("Din vare er nu tilføjet til kurven.");
                window.location.href = "/forside-c-53#section77";
            }
            else {
                event.preventDefault();

                var data = "";
                var loaded = false;

                var subscriptionid2 = $.query.get("subscriptionid");
                if (subscriptionid2 != null && subscriptionid2 != "") {
                    data = $.ajax({
                        type: "POST",
                        url: '/ajax/pakkemarked.php?r=' + Math.random(),
                        data: { subscriptionId: subscriptionid2 },
                        async: false
                    }).responseText;
                    loaded = true;
                }

                // Check if we are adding a product to a mix box
                /*
                var data = "";
                var loaded = false;

                var subscriptionid2 = $.query.get("subscriptionid");
                if (subscriptionid2 != null && subscriptionid2 != "") {
                data = $.ajax({
                type: "POST",
                url: '/ajax/pakkemarked.php',
                data: { subscriptionId: subscriptionid2 },
                async: false
                }).responseText;
                loaded = true;
                }

                var subscriptionId = $.query.get("subscription_id");
                if (loaded == false && subscriptionId != null && subscriptionId != "") {
                data = $.ajax({
                type: "POST",
                url: '/ajax/pakkemarked.php',
                data: { vareid: subscriptionId },
                async: false
                }).responseText;
                loaded = true;
                }

                if (loaded == true) {
                var recipedata2 = 0;
                if (form.find("input[name=recipe]").length > 0) {
                recipedata2 = form.find("input[name=recipe]").val();
                }

                if (data != "") {
                data += "," + jq.attr("alt");
                }
                else {
                data = jq.attr("alt");
                }

                saveDraftPakkemarked(data, subscriptionId);

                window.location = $.query.get("subscription");
                }
                */
                var subscriptionId = $.query.get("subscription_id");
                if (loaded == false && subscriptionId != null && subscriptionId != "") {
                    data = $.ajax({
                        type: "POST",
                        url: '/ajax/pakkemarked.php?r=' + Math.random(),
                        data: { vareid: subscriptionId },
                        async: false
                    }).responseText;
                    loaded = true;
                }

                var recipedata = 0;
                if (form.find("input[name=recipe]").length > 0) {
                    recipedata = form.find("input[name=recipe]").val();
                }

                if (loaded == true) {
                    var varedata = vareid;
                    if (recipedata != 0) {
                        var index = recipedata.indexOf("=");
                        if (index > 0) {
                            varedata += "=" + recipedata.substring(index + 1);
                        }
                    }
                    if (data != "") {
                        data += "," + varedata;
                    }
                    else {
                        data = varedata;
                    }


                    saveDraftPakkemarked(data, subscriptionId);

                    window.location = $.query.get("subscription");
                    return;
                }
                /*
                var subscriptionId = $.query.get("subscription_id");
                if (subscriptionId != null && subscriptionId != "") {
                var data = $.ajax({
                type: "POST",
                url: '/ajax/pakkemarked.php',
                data: { vareid: subscriptionId },
                async: false
                }).responseText;

                if (data != "") {
                data += "," + vareid;
                }
                else {
                data = vareid;
                }

                saveDraftPakkemarked(data, subscriptionId);

                window.location = $.query.get("subscription");
                return;
                }
                */

                // get count
                var count = form.find("input[name=stk]").val();

                // increment purchase count
                var productCountContainer = $(".product-count-id" + vareid);
                productCountContainerValue = Number($(productCountContainer.get(0)).text());
                if (productCountContainerValue > 0) {
                    productCountContainerValue++;
                }
                else {
                    productCountContainerValue = 1;
                }
                productCountContainer.text(productCountContainerValue);

                // add to basket
                /*
                $.ajax({
                type: "POST",
                url: "/shop.php?action=add&id=" + vareid,
                data: ({ stk: count, recipe: recipedata }),
                async: true,
                success: function (msg) {
                var resp = $.ajax({
                type: "GET",
                url: "/getbasket.php",
                data: ({ "isajax": 1 }),
                async: false
                });
                $("#basket").html(resp.responseText);

                //$(copymenusourceid).css("height", $("#basketpanel").height());
                //$(copymenutargetid).css("height", $("#basketpanel").height());
                //copymenutargetstartyoffset = $("#belowmenutarget").position().top;
                //updateBasketMovement(null);
                }
                });
                */
                addProductToBasket(false, vareid, count, recipedata, "");

                var redirectUrlParam = $.query.get("redirect");
                if (redirectUrlParam != null && redirectUrlParam != "") {
                    window.location = redirectUrlParam;
                    return;
                }
            }

            var sourceimg = jq.parents(".product").find(".product-image img");
            //var sourceimg = $("img[vareid='" + vareid + "']");
            var animateImage = $("<div><img src='" + sourceimg.attr("src") + "' /></div>");
            animateImage.css("position", "absolute");
            animateImage.css("left", sourceimg.offset().left);
            animateImage.css("top", sourceimg.offset().top);

            animateImage.appendTo(document.body);

            animateImage.animate({ "left": offset.left, "top": offset.top },
            1000,
            "linear",
            function () {
                $(this).remove();
            });
            animateImage.children(":first").animate({ "width": 0, "height": 0 }, 1000);
        });

        sections = [];
        $(".sectioncontainer").each(function (i, e) {
            var jq = $(this);
            var offset = jq.offset();
            var top = jq.offset().top;
            sections.push({
                jq: jq,
                top: top
            });
        });
    }

    $(window).scroll(function () {
        fixDivPos();
    });
    $(window).resize(function () {
        fixDivPos();
    });

    fixDivPos();


    // tips
    $(".tip-selector").click(function () {
        var jq = $(this);
        var selectedTip = $('img[src$=tip_check_active.gif]');

        /*
        var data = "";
        var loaded = false;

        var subscriptionid2 = $.query.get("subscriptionid");
        if (subscriptionid2 != null && subscriptionid2 != "") {
        data = $.ajax({
        type: "POST",
        url: '/ajax/pakkemarked.php',
        data: { subscriptionId: subscriptionid2 },
        async: false
        }).responseText;
        loaded = true;
        }

        var subscriptionId = $.query.get("subscription_id");
        if (loaded == false && subscriptionId != null && subscriptionId != "") {
        data = $.ajax({
        type: "POST",
        url: '/ajax/pakkemarked.php',
        data: { vareid: subscriptionId },
        async: false
        }).responseText;
        loaded = true;
        }

        if (loaded == true) {
        if (data != "") {
        data += "," + jq.attr("alt");
        }
        else {
        data = jq.attr("alt");
        }

        saveDraftPakkemarked(data, subscriptionId);

        window.location = $.query.get("subscription");
        }
        */

        $(".tip-selector").attr("src", "/img2/tip/tip_check_inactive.gif");

        if (selectedTip.length <= 0 || selectedTip.attr("alt") != jq.attr("alt")) {
            jq.attr("src", "/img2/tip/tip_check_active.gif");

            $("input[name=recipe]").val(jq.attr("alt"));
        }
    });



    var initialTab = window.location.hash;
    if (initialTab != "") {
        if (initialTab == "#tips") {
            api.click(1);
        }
        if (initialTab == "#varedeklaration") {
            api.click(2);
        }
        if (initialTab.substring(0, 8) == "#section" || initialTab.substring(0, 4) == "#cat") {
            $("." + initialTab.substring(1)).click();
        }
    }
});


var rejectedInfoBoxes = Array();
function showInfoBox(target, headline, content) {

    // check if box is rejected
    for (var i = 0; i < rejectedInfoBoxes.length; i++) {
        if (rejectedInfoBoxes[i] == headline) {
            return;
        }
    }

    // create the html
    var html = $.format("<div class='infobox'> \
    <div class='header'>{0}</div> \
    <div class='content'>{1}</div> \
    <div class='close'>Luk besked</div> \
    </div>", headline, content);

    // add to document
    var jq = $(html);
    $(document.body).append(jq);

    // position
    jq.css("top", target.offset().top - jq.height());
    jq.css("left", target.offset().left);

    jq.find("div.close").click(function () {
        // find the holder (jq)
        var holder = $(this).parent("div.infobox");

        // save it to the rejected boxes list
        rejectedInfoBoxes.push(holder.find(".header").html());

        // remove it
        holder.remove();
    });

    jq.pause(5000).animate({ "top": target.offset().top - (30 + jq.height()), opacity: "hide" },
        500,
        "linear",
        function () {
            $(this).remove();
        });


    return jq;
}

$.fn.pause = function (duration) {
    $(this).animate({ dummy: 1 }, duration);
    return this;
};



function addProductToBasket(advanced, vareid, count, recipe, selectedvarer) {
    if (advanced == false) {
        $.ajax({
            type: "POST",
            url: "/shop.php?action=add&id=" + vareid,
            data: ({ stk: count, recipe: recipe }),
            async: false,
            success: function (msg) {
                updateBasket();
            }
        });
    }
    else {
        $.ajax({
            type: "POST",
            url: "/shop.php?action=addAdvanced&id=" + vareid,
            data: ({ stk: count, recipe: recipe, selectedvarer: selectedvarer }),
            async: false,
            success: function (msg) {
                updateBasket();
            }
        });
    }
}

function removeProductFromBasket(vareid) {
    $.ajax({
        type: "POST",
        url: "/shop.php?action=remove&id=" + vareid,
        data: ({ stk: 1 }),
        async: true,
        success: function (msg) {
            updateBasket();
        }
    });
}

function updateBasket() {
    var resp = $.ajax({
        type: "GET",
        url: "/getbasket.php",
        data: ({ "isajax": 1 }),
        async: false
    });
    var basket = $("#basket");
    basket.html(resp.responseText);
    $("#basket-container").css("height", basket.height() + "px");
}

function displayDeliveryDate(target, zipcode) {
    var url_target = "/ajax/deliverydate.php";

    $.ajax({
        type: "POST",
        url: url_target,
        data: ({ Zip: zipcode }),
        success: function (msg) {
            var notice = $(target);

            notice.html(msg);
        }
    });
}

function isValidZip(target, zipcode) {
    var url_target = "/ajax/isvalidzip.php";

    var notice = $(target);

    var resp = $.ajax({
        type: "POST",
        url: url_target,
        data: ({ Zip: zipcode }),
        async: false
    }).responseText;

    notice.html(resp);
}
