$(function() {
    var productList = [
        {
            ID: "10000",
            Title: "FC Broby - Hættetrøje",
            Price: 375,
            Description: "Super fed hættetrøje i sorte og hvide farver. Skynd dig at bestil den!",
            Picture: "haettetroeje",
            Sizes: [
            "XXL",
            "XL",
            "Large",
            "Medium",
            "Small",
            "12-13 år",
            "10-12 år",
            "8-10 år"]
        },
    {
        ID: "10010",
        Title: "FC Broby - Polo",
        Price: 325,
        Description: "Smart og trendy polo i god kvalitet, med FC Broby logo på brystet.",
        Picture: "polo",
        Sizes: [
            "XXL",
            "XL",
            "Large",
            "Medium",
            "Small",
            "12-13 år",
            "10-12 år",
            "8-10 år"]
    },
    {
        ID: "10020",
        Title: "FC Broby - Spillertrøje",
        Price: 250,
        Description: "Køb din egen personlige FC Broby spillertrøje i nyeste design.",
        Picture: "kamptroeje",
        Sizes: [
            "XXL",
            "XL",
            "Large",
            "Medium",
            "Small",
            "12-13 år",
            "10-12 år",
            "8-10 år"]
    },
    {
        ID: "10025",
        Title: "FC Broby - Spillertrøje m. tryk",
        Price: 400,
        Description: "Køb din egen personlige FC Broby spillertrøje i nyeste design, med navn og nr. efter eget ønske.",
        Picture: "kamptroeje",
        CustomText: "Tekst til tryk..",
        CustomNumber: "Nr.",
        Sizes: [
            "XXL",
            "XL",
            "Large",
            "Medium",
            "Small",
            "12-13 år",
            "10-12 år",
            "8-10 år"]
    },
    {
        ID: "10030",
        Title: "FC Broby - Halstørklæde",
        Price: 100,
        Description: "Et must-have for alle FC Broby-fans, kan bæres af alle i alle aldre.",
        Picture: "halstorklaede"
    },
    {
        ID: "10035",
        Title: "FC Broby - OB - Halstørklæde",
        Price: 125,
        Description: "LIMITED EDITION - Det ultimative samlerobjekt til en fodboldfan. Et eksklusivt og unikt halstørklæde til sommerens kamp imod OB. Begrænset antal, så skynd dig!",
        Picture: "obhalstorklaede"
    },    
    {
        ID: "10040",
        Title: "FC Broby - Hue",
        Price: 100,
        Description: "Hue i klassiske farver, bær den stolt når du støtter din klub.",
        Picture: "hue"
    },
    {
        ID: "10045",
        Title: "FC Broby - Hue & halstørklæde",
        Price: 180,
        Description: "Køb hue og halstørklæde samlet og spar 10%.",
        Picture: "halshue"
    },
    {
        ID: "10050",
        Title: "FC Broby - Cap",
        Price: 150,
        Description: "Super lækker cap med klubbens logo. God kvalitet og perfekt til sommerens kampe.",
        Picture: "cap"
    },    
    {
        ID: "10060",
        Title: "FC Broby - Krus",
        Price: 25,
        Description: "Gør venner, kolleger samt familien misundelige og anskaf dig FC Broby kruset.",
        Picture: "krus"
    },
    {
        ID: "10066",
        Title: "FC Broby - Krus - 6 stk.",
        Price: 120,
        Description: "Anskaf FC Broby krus til venner, kolleger eller familien.",
        Picture: "sekskrus"
    }
    ];

    function updateOrder() {
        $('#order').empty();
        if (order.length > 0) {
            $('#orderTableTemplate').tmpl().appendTo('#order');
            $('#orderTemplate').tmpl(order).appendTo('#orderTable');
            $('#order').append('<button id="clearorderButton" class="ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all"><span class="ui-button-text">Ryd bestilling</span></button>');
            $('#order').append('<button id="orderButton" class="ui-button ui-button-text-only ui-widget ui-state-default ui-corner-all"><span class="ui-button-text">Bestil</span></button>');
            $('html, body').animate({ scrollTop: 0 }, 'slow');
        }
    }

    function orderSum() {
        var index, sum;
        sum = 0;
        for (index = 0; index < order.length; ++index) {
            sum += order[index].Price * order[index].Amount;
        }
        return sum;
    }

    function tilfoej() {
        var ID = $(this).attr('id');
        var selectedSize = $('.productSize' + ID + ' option:selected').val();
        var selectedColor = $('.productColor' + ID + ' option:selected').val();
        var customNumber = $('.productCustomNumber' + ID).val();
        var customText = $('.productCustomText' + ID).val();
        var found = false;

        if (customText === undefined) {
            $.grep(order, function(n) {
                if (n.ID == ID && n.Size == selectedSize && n.Color == selectedColor) {
                    var tmpl_item = $('.orderAmount' + n.ID + (selectedColor === undefined ? '' : n.Color) + (selectedSize === undefined ? '' : n.Size)).tmplItem();
                    tmpl_item.data['Amount'] = (n.Amount * 1) + 1;
                    tmpl_item.update();

                    found = true;
                }
            });
        };

        if (!found) {
            $.grep(productList, function(n) {
                if (n.ID == ID) {
                    order.push({
                        ID: ID,
                        Title: n.Title,
                        Price: n.Price,
                        Color: selectedColor,
                        Size: selectedSize,
                        CustomNumber: customNumber,
                        CustomText: customText,
                        Amount: 1
                    });
                }
            });
        }
        updateOrder();
    }

    if ($('#order').length > 0) {

        $('#order').delegate('input', 'change', function() {
            if (this.value > 0) {
                $.tmplItem(this).data[this.name] = this.value;
            } else {
                $.tmplItem(this).data[this.name] = 0;
            }
            updateOrder();
        });

        $('#productTemplate').tmpl(productList).appendTo('#products');

        $('.productLink').bind('click', tilfoej);

        $("#customText").focus(function() {
            if ($(this).val() == $(this).attr('rel')) {
                $(this).val('');
            }
        });
        $("#customText").blur(function() {
            if ($(this).val() == '')
                $(this).val($(this).attr("rel"));
        });

        $("#customNumber").focus(function() {
            if ($(this).val() == $(this).attr('rel')) {
                $(this).val('');
            }
        });
        $("#customNumber").blur(function() {
            if ($(this).val() == '')
                $(this).val($(this).attr("rel"));
        });

        var order = [];

        updateOrder();

        $('#clearorderButton').live('click', function() {
            order = [];
            $('#order').empty();
        });

        $('#orderButton').live('click', function() {
            $('#finalOrderTemplate').tmpl(order).appendTo('#bestilling');
            $('#bestilling').append('<tr><td colspan="2" id="sum" class="sumLinie">Total:</td><td class="sumLinie right">' + orderSum() + ',-</td></tr>');

            $('#bestillingsform').dialog('open');
        });

        $('#customNumber').keydown(function(event) {
            if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105)) // 0-9 or numpad 0-9
            {
                // check textbox value now and tab over if necessary
            }
            else if (event.keyCode != 8 && event.keyCode != 46 && event.keyCode != 37 && event.keyCode != 39) // not esc, del, left or right
            {
                event.preventDefault();
            }
            // else the key should be handled normally
        });

        $(".jqzoom").jqzoom();
    };

    var name = $('#name'),
        address = $('#address'),
        email = $('#email'),
        phone = $('#phone'),
        allFields = $([]).add(name).add(address).add(email).add(phone),
        tips = $('.validateTips');

    function updateTips(t) {
        tips.text(t).addClass('ui-state-highlight');
        setTimeout(function() {
            tips.removeClass('ui-state-highlight', 1500);
        }, 500);
    }

    function checkLength(o, n, min, max) {
        if (o.val().length > max || o.val().length < min) {
            o.addClass('ui-state-error');
            updateTips('Længden på ' + n + ' skal være mellem ' + min + ' og ' + max + ' tegn.');
            return false;
        } else {
            return true;
        }
    }

    function checkRegexp(o, regexp, n) {
        if (!(regexp.test(o.val()))) {
            o.addClass('ui-state-error');
            updateTips(n);
            return false;
        } else {
            return true;
        }
    }

    if ($('#bestillingsform').length > 0) {

        $('#bestillingsform').dialog({
            autoOpen: false,
            height: 400,
            width: 400,
            modal: true,
            buttons: {
                "Send bestilling": function() {
                    var bValid = true;
                    allFields.removeClass('ui-state-error');

                    bValid = bValid && checkLength(name, "Navn", 5, 30);
                    bValid = bValid && checkLength(address, "Adresse", 5, 30);
                    bValid = bValid && checkLength(email, "E-mail", 6, 80);
                    bValid = bValid && checkLength(phone, "Telefon", 8, 8);

                    bValid = bValid && checkRegexp(name, /[a-zæøå]+$/i, "Navn angives med bogstaverne: a-å.");
                    bValid = bValid && checkRegexp(email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "E-mail angives som eksempelvis fcbroby@fcbroby.dk");
                    bValid = bValid && checkRegexp(phone, /^([0-9])+$/, "Telefon angives med cifrene: 0-9");

                    if (bValid) {
                        $.get('http://fcbroby.dk/fanshop.asp?action=send', {
                            name: name.val(),
                            address: address.val(),
                            email: email.val(),
                            phone: phone.val(),
                            data: $('#bestillingContainer').html()
                        });
                        $('#bestilling').empty();
                        $(this).dialog('close');
                        order = [];
                        $('#order').empty();
                        $('#order').append('<div id="orderConfirmation">Bestillingen er nu afsendt..<br />Du vil modtage en mail når dine varer er klar til afhentning i klubhuset.<br />Bemærk at der er ca. 14 dages leveringstid på spillertrøjer, hættetrøjer samt polotrøjer.<br />Bestillinger er bindende og der betales kontant ved afhentning.</div>');
                        $('html, body').animate({ scrollTop: 0 }, 'slow');
                    }
                }
            },
            close: function() {
                $('#bestilling').empty();
                allFields.val('').removeClass('ui-state-error');
            }
        });
        
    };

});
