
    function preloadImages() {
        var srcs = ["images/top_menu_hover.png"];
        var preload = new Image();

        for (var i = 0; i < srcs.length; i++) {
            preload.src = srcs[i];
        }
    }

    function openWindow(url) {
        var popup = window.open(url, 'win1', 'toolbar=0,location=0,scrollbars=1,width=620,height=400,resizable=1,topmargin=20,align=center');
        popup.focus();
        return false;
    }

    preloadImages();
    // onload
    $(document).ready(function() {
        initPrint();
        initTooltips();
        initDummyForms();
        initMenu();

        initFilter();
        handleSearchCategories();
        hideFormMessages();
        initFormFields();
        initCart();
        initComparison();
        initCustomerForm();
        initOrderForm();
        initProductDeliveryForm();
        initImagePreviews();
    });

    function initPrint() {
        $("#print a").click(function() {
            window.print();
            return false;
        });
    }

    function initTooltips() {
        $("a.tt").click(function() {
            return false;
        });
    }

    function initDummyForms() {
        $("form.no-submit").submit(function() {
            return false;
        });
    }

    function initMenu() {
        $("#category-html").css("display", "none");
        $("ul.jd_menu a.top").click(function() {
            return false;
        });
    }

    function initFilter() {
        $('#filterTitle').click(function() {
            $("#filterBody").slideToggle();
        });
        $('#tooltip-filter').click(function() {
            $("#filterBody").slideToggle();
        });
    }

    function handleSearchCategories() {
        var formField = $("#searchCategory");
        var activeCategory = $(activeSearchCategory);
        activeCategory.addClass("searchCategory");
        activeCategory.css("color", "#FFF");
        $("div.menu_search a").click(function() {
            activeCategory.removeClass("searchCategory");
            activeCategory.css("color", "#ffcc00");
            activeCategory = $(this);
            activeCategory.addClass("searchCategory");
            activeCategory.css("color", "#FFF");

            formField.val(activeCategory.attr("id"));
            return false;
        });
    }

    function hideFormMessages() {
        var messages = $("span#form-messages");
        if (!messages.length) {
            return;
        }
        setTimeout(function() {
            messages.slideUp("slow");
        }, 2000);
    }

    function initFormFields() {
        var els = [
            "input#search",
            "input#login_name",
            "input#login_pass",
        ];
        var texts = [
            "Vyhledávání...",
            "Jméno",
            "Heslo",
        ];

        for (var i = 0; i < els.length; ++i) {
            initFormField(els[i], texts[i]);
        }
    }
    function initFormField(id, text) {
        $(id).blur(function() {
            if (!$(this).val()) {
                $(this).val(text);
            }
        }).focus(function() {
            if ($(this).val() == text) {
                $(this).val("");
            }
        }).blur();
    }

    function initCart() {
        $("a#empty-cart").click(function() {
            return emptyCart();
        });
        $("a.remove-cart").click(function() {
            return removeFromCart();
        });

        var table = $("table#cart");
        if (!table.length) {
            return;
        }
        $("table#cart tr:even").addClass("sive");
        $("table#cart tr:first").removeClass("sive");
        $("table#cart tr:not(:first):not(:last)").hover(function() {
            table.data("bgColor", $(this).css("background-color"));
            $(this).css("background-color", "#DDDDDD");
        }, function() {
            $(this).css("background-color", table.data("bgColor"));
        });

        $("table#cart input.quantity, form#cart-form :checkbox").change(function() {
            disableOrder();
        }).keyup(function() {
            disableOrder();
        });

        $("table#cart :image").click(function() {
            return removeFromCart();
        });
        $("form#cart-form input#empty-cart").click(function() {
            return emptyCart();
        });
        if (!userLogged) {
            $("form#cart-form input#order-button").click(function() {
                return confirm('Opravdu chcete pokračovat v objednávce bez přihlášení/registrace?');
            });
        }
    }
    function disableOrder() {
        $("form#cart-form input#order-button").attr("disabled", "disabled").css("color", "grey").css("cursor", "default")
                .attr("title", "Musíte přepočítat položky ve Vašem nákupním košíku");
    }
    function emptyCart() {
        return confirm('Opravdu chcete vyprázdnit Váš nákupní košík?');
    }
    function removeFromCart() {
        return confirm('Opravdu chcete odebrat danou položku z Vašeho nákupního košíku?');
    }

    function initComparison() {
        $("a#empty-comparison").click(function() {
            return confirm('Opravdu chcete odstranit všechny položky z Vašeho porovnávání?');
        });
        $("a.remove-comparison").click(function() {
            return confirm('Opravdu chcete odebrat danou položku z Vašeho porovnávání?');
        });
        $("a#forbid-comparison").click(function() {
            alert('Pro porovnávání musíte vybrat alespoň 2 položky.');
            return false;
        });
        $(".comparison-type").click(function() {
            return confirm('Opravdu chcete přidat jiný typ produktu pro Vaše porovnávání? Stávající položky budou odstraněny.');
        });
        $(".comparison-replace").click(function() {
            return confirm('Opravdu chcete nahradit první položku Vašeho porovnávání tímto produktem?');
        });
    }

    function initCustomerForm() {
        var form = $("#customerform");
        if (!form.length) {
            return;
        }

        form.find("[name*=delivery_]").keyup(function() {
            copyAddressItem($(this));
        });
        $("#copy-delivery-address").change(function() {
            copyAddress(form);
        });
        copyAddress(form);
    }
    function copyAddressItem(item) {
        if ($("#copy-delivery-address").attr("checked")) {
            $(":input[name='" + item.attr("name").replace(/delivery_/, "") + "']").val(item.val());
        }
    }
    function copyAddress(form) {
        var checked = $("#copy-delivery-address").attr("checked");

        form.find("[name*=delivery_]").each(function() {
            var el = $(":input[name='" + $(this).attr("name").replace(/delivery_/, "") + "']");
            if (checked) {
                el.data("origValue", el.val());
                el.attr("readonly", "readonly").addClass("readonly");
                copyAddressItem($(this));
            } else {
                el.removeAttr("readonly").removeClass("readonly");
                el.val(el.data("origValue"));
            }
        });
    }

    function initOrderForm() {
        // order & product
        $("#order-delivery-payment").click(function() {
            return openWindow($(this).attr("href"));
        });

        var form = $("#orderform");
        if (!form.length) {
            return;
        }

        $("#delivery-osobne").click(function() {
            disablePayment();
        });
        $("#delivery-dopravou").click(function() {
            disablePayment();
        });
        $("#assembly").click(function() {
            handleAssembly();
        });
        disablePayment();
        handleAssembly();

        // links
        $("#order-delivery-price").click(function() {
            return openWindow($(this).attr("href"));
        });
    }
    function disablePayment() {
        var osobne = $("#delivery-osobne").attr("checked");

        var paymentOsobne = $("#payment-osobne");
        var paymentDobirka = $("#payment-dobirka");
        var paymentPrevod = $("#payment-prevod");
        paymentDobirka.removeAttr("disabled");
        paymentOsobne.removeAttr("disabled");

        if (osobne) {
            if (paymentDobirka.attr("checked")) {
                paymentOsobne.attr("checked", "checked");
            }
            paymentDobirka.attr("disabled", "disabled");
        } else {
            if (paymentOsobne.attr("checked")) {
                paymentPrevod.attr("checked", "checked");
            }
            paymentOsobne.attr("disabled", "disabled");
        }
    }
    function handleAssembly() {
        var assembly = $("#assembly");
        if (!assembly.length) {
            return;
        }
        var checked = assembly.attr("checked");
        if (checked) {
            $("#delivery-osobne").attr("checked", "checked");
            $("#delivery-dopravou").attr("disabled", "disabled");
            disablePayment();
        } else {
            $("#delivery-dopravou").removeAttr("disabled");
        }
    }

    function initProductDeliveryForm() {
        var selects = $("#product-delivery-form select");
        if (!selects.length) {
            return;
        }
        var productPayment = $("#product-payment");
        productPayment.copyOptions("#product-payment-copy", "all");
        selects.change(function() {
            var productDelivery = $(this).attr("id") == "product-delivery";
            if (productDelivery) {
                productPayment.removeOption(/./);
                $("#product-payment-copy").copyOptions("#product-payment", "all");
            }
            calculateDeliveryPrice(productDelivery);
        });
        calculateDeliveryPrice(true);
    }
    function calculateDeliveryPrice(forceSelect) {
        var deliveryPrice = $("#delivery-price");

        var productDelivery = $("#product-delivery");
        var productDistrict = $("#product-district");
        var productPayment = $("#product-payment");

        var calculate = false;
        var price = 0;
        switch (productDelivery.val()) {
            case "":
                productDistrict.attr("disabled", "disabled");
                productPayment.attr("disabled", "disabled");
                break;
            case "osobne":
                calculate = true;
                productDistrict.attr("disabled", "disabled");
                productPayment.removeAttr("disabled");
                if (forceSelect) {
                    productPayment.removeOption("dobirka").selectOptions("");
                }
                break;
            case "dopravou":
                productDistrict.removeAttr("disabled");
                if (forceSelect) {
                    productPayment.removeOption("osobne").selectOptions("");
                }
                var district = productDistrict.val();
                if (district) {
                    calculate = true;
                    price += deliveryInfo.weightPrice;
                    if (deliveryInfo.companyKey == "toptrans") {
                        price += deliveryInfo.topTrans[productDistrict.val()];
                    }
                }
                if (calculate) {
                    productPayment.removeAttr("disabled");
                } else {
                    productPayment.attr("disabled", "disabled");
                }
                break;
        }

        switch (productPayment.val()) {
            case "":
                price = 0;
                break;
            case "dobirka":
                if (calculate) {
                    for (var d in deliveryInfo.dobirka) {
                        if (d >= price) {
                            price += deliveryInfo.dobirka[d];
                            break;
                        }
                    }
                }
                break;
        }

        deliveryPrice.find("span").html(Math.ceil(price));
    }

    function initImagePreviews() {
        // product catalog + cart
        addImgPreview("a.imgpreview", "imgPreviewCatalog", "240px", true);
        // product detail
        addImgPreview("a#imgpreview", "imgPreviewDetail", "240px", true);
        // product schemes
        addImgPreview("a.imgscheme", "imgPreviewScheme", "400px", false);
    }
    function addImgPreview(selector, containerId, width, title) {
        var el = $(selector);
        if (!el.length) {
            return;
        }
        el.imgPreview({
            distanceFromCursor : {top : 20, left : 20},
            containerID : containerId,
            srcAttr : "xhref",
            imgCSS : {
                width : width
            },
            onShow : function(link) {
                $(link).stop().animate({opacity : 0.4});
                $("img", this).stop().css({opacity : 0});
                if (title) {
                    $("<span>" + $(link).attr("alt") + "</span>").appendTo(this);
                }
            },
            onLoad: function() {
                $(this).animate({opacity : 1}, 300);
            },
            onHide : function(link) {
                $(link).stop().animate({opacity : 1});
                if (title) {
                    $("span", this).remove();
                }
            }
        });
    }
