$(document).ready(function() {
    // Variablen
    formActionUrl = '/ajax/shop.php';
    formActionUrlPaypal = 'https://www.paypal.com/cgi-bin/webscr';
    ppReturnValue = 'http://friesland.cc/ajax/shop.php?action=order%26pp=1%26oid=';
    
    // Gesamtkosten berechnen und anzeigen
    calcTotalCosts(1);
    
    // Form Action setzen
    if ($('.radiopayment:checked').val() == 3) {
        $('#basketForm').get(0).setAttribute('action', formActionUrlPaypal);
        $.get(formActionUrl, {action: 'getOrderId'}, function(data) {
            $('input[name="return"]').val(ppReturnValue+data);
        });
    }

    /**
     * Produktbild ausrichten
     */
    $('.product').each(function(index) {
        iHeightImg  = $(this).children("img").height();
        iHeightDiv  = $(this).children("div.product_container").height();
        if (iHeightImg > iHeightDiv) {
            iDiffImgDiv = iHeightImg-iHeightDiv;
            iMarginTopText = parseInt(iDiffImgDiv/2);
            $(this).children("div.product_container").css('margin-top', iMarginTopText+'px');
        } else {
            iDiffImgDiv = iHeightDiv-iHeightImg;
            iMarginTopText = parseInt(iDiffImgDiv/2);
            $(this).children("img").css('margin-top', iMarginTopText+'px');
        }

    });

    $('.inputNumber').click(function() {
        $(this).select();
    });

    // Anzahl eines Items hochsetzen
    $('.inputNumber').change(function() {
        var aProductId = explode('_', $(this).attr('id'));
        var iItemNumber = $(this).val();

        if (iItemNumber < 0) {
            iItemNumber = 0;
            $(this).val(0);
        }

        if (iItemNumber == 0) {
            $('#bn_'+aProductId[1]+'_'+aProductId[2]).html(0);
            $('#bp_'+aProductId[1]+'_'+aProductId[2]).html(number_format(0, 2, ',', '.'));
        }

        $.getJSON(formActionUrl, {action: 'fillBasket', number: iItemNumber, id: aProductId[1], color: aProductId[2]}, function(data) {
            $.each(data, function(i,item) {
                $('#bn_'+item.id+'_'+item.color).html(item.number);
                $('#bp_'+item.id+'_'+item.color).html(number_format(item.price, 2, ',', '.'));
            });
            
            // Gesamtkosten berechnen und anzeigen
            calcTotalCosts(0);
        });
        
    });

    // Länderauswahl
    $('#selCountry').change(function() {
        var aCountry = explode('_', $(this).val());

        // Payments anzeigen
        if (aCountry[0] != '') {
            $('.payments').css('display', 'table-cell');
        } else {
            $('.payments').hide();
        }

        // Payments
        if (aCountry[0] != 'g1') {
            $('#pay_1').hide();
            $('#payment_1').removeAttr("checked");
        } else {
            $('#pay_1').show();
        }

        // Shipping Costs
        switch (aCountry[0]) {
            case "g1":
                iCosts = 0;
                break;
            case "g2":
                iCosts = 15;
                break;
            case "g3":
                iCosts = 22;
                break;
            case "g4":
                iCosts = 28;
                break;
        }
        $('#shippingcosts').html(number_format(iCosts, 2, ',', '.'));

        // Gesamtkosten berechnen und anzeigen
        calcTotalCosts(0);

        $.get(formActionUrl, {action: 'selCountry', id: aCountry[0]+'_'+aCountry[1], costs: $('#shippingcosts').html()});
    });

    // Payment
    $('.radiopayment').click(function() {
        if ($(this).val() == 1) {
            iCosts = '7,50';
            $('#shippingcosts').html(iCosts);
        } else {
            var aCountry = explode('_', $('#selCountry').val());
            if (aCountry[0] == 'g1') {
                iCosts = '0,00';
                $('#shippingcosts').html(iCosts);
            }
        }

        // Paypal?
        if ($(this).val() == 3) {
            // Neue Action setzen
            $('#basketForm').get(0).setAttribute('action', formActionUrlPaypal);
            $('.submit input[type="image"]').removeClass('hidden');
            $('.submit input[type="submit"]').addClass('hidden');
            $.get(formActionUrl, {action: 'getOrderId'}, function(data) {
                $('input[name="return"]').val(ppReturnValue+data);
            });
        } else {
            $('#basketForm').get(0).setAttribute('action', formActionUrl);
            $('.submit input[type="image"]').addClass('hidden');
            $('.submit input[type="submit"]').removeClass('hidden');
        }

        // Gesamtkosten berechnen und anzeigen
        calcTotalCosts(0);

        $.get(formActionUrl, {action: 'selPayment', id: $(this).val(), costs: $('#shippingcosts').html()});
    });

    /**
     * Formularangaben in Session speichern
     */
    $('.personal').change(function() {
        $.get(formActionUrl, {action: 'saveForm', val: $(this).val(), name: $(this).attr('name')});
    });
    
    /**
     * Newsletter
     */
    $('input[name="newsletter"]').click(function() {
        $.get(formActionUrl, {action: 'selNewsletter', val: $(this).attr('checked')});
    });
    
    /**
     * AGB
     */
    $('input[name="agb"]').click(function() {
        $.get(formActionUrl, {action: 'selAGB', val: $(this).attr('checked')});
    });

    /**
     * Submit abfangen und Bestellformular validieren
     */
    $("form").submit(function() {
        errorCount = 0;

        // Anzahl der Artikel überprüfen
        itemCount = 0;
        $('input[name^="number"]').each(function(index) {
            itemCount = itemCount + parseInt($(this).val());
        });

        if (itemCount < 1) {
            $('input[name^="number"]').addClass('error');
            errorCount++;
        }

        // Alle Pflichtfelder überprüfen
        $('.required').each(function(index) {
            if ($(this).val() == '' || $(this).val() == 'Bitte angeben!') {
                $(this).val('Bitte angeben!');
                $(this).addClass('error');
                errorCount++;
            }
        });

        // Land überprüfen
        if ($('#selCountry').val() == '') {
            $('#selCountry').addClass('error');
        }

        // AGB akzeptiert?
        if (!$('input[name="agb"]').attr('checked')) {
            $('.agbhint').addClass('error');
            errorCount++;
        }

        // Bazahlung ausgewählt?
        checkedPayment = 0;
        $('input[name="payment"]').each(function(index) {
            if ($(this).attr('checked')) {
                checkedPayment++;
            }
        });
        if (checkedPayment != 1) {
            $('label[for^="payment_"]').addClass('error');
            errorCount++;
        }

        // E-Mail-Adresse valide?
        if (!goog.format.EmailAddress.isValidAddress($('input[name="email"]').val())) {
            if ($('input[name="email"]').val() != 'Bitte korrekt angeben!' && $('input[name="email"]').val() != '') {
                $('input[name="email"]').addClass('error');
            } else {
                $('input[name="email"]').val('Bitte korrekt angeben!').addClass('error');
            }
        }

        if (errorCount > 0) return false;
    });

    /* Errors ausblenden */
    $('.required').focus(function() {
        if ($(this).val() == 'Bitte angeben!') {
            $(this).val('').removeClass('error');
        }
    });

    $('#selCountry').change(function() {
        if ($(this).val() != '') {
            $(this).removeClass('error');
        }
    });

    $('input[name="agb"]').click(function() {
        if ($(this).attr('checked')) {
            $('.agbhint').removeClass('error');
        }
    });

    $('input[name="payment"]').click(function() {
        if ($(this).attr('checked')) {
            $('label[for^="payment_"]').removeClass('error');
        }
    });

    $('input[name="email"]').focus(function() {
        if ($(this).val() == 'Bitte korrekt angeben!') {
            $(this).val('').removeClass('error');
        } else {
            $(this).removeClass('error');
        }
    });

    $('input[name^="number"]').click(function() {
        $('input[name^="number"]').removeClass('error');
    });

    /**
     * AGB oder Impressum anzeigen
     */
    $('.nyroModal').nyroModal();


    $('.nyroModalImg').nyroModal({sizes: { initW: 300, initH: 500 }});

    $('.nyroModalPress').nyroModal();



    /**
     * Funktion zur Berechnung der Gesamtkosten
     */
    function calcTotalCosts(iStart) {
        // Gesamtkosten
        fCostsTotal = 0;
        
        // Anzahl
        //fQuantityTotal = 0;

        // Versandkosten
        fCostsTotal = fCostsTotal + parseFloat(str_replace(',', '.', $('#shippingcosts').html()));

        // Artikel
        $('td[id^="bp_"]').each(function(index) {
            tmpPrice = str_replace('.', '', $(this).html());
            tmpPrice = str_replace(',', '.', tmpPrice);

            fCostsTotal = fCostsTotal + parseFloat(tmpPrice);
        });
        
        // Artikelanzahl
        /*$('td[id^="bn_"]').each(function(index) {
            tmpQuantity = $(this).html();

            fQuantityTotal = fQuantityTotal + parseInt(tmpQuantity);
        });*/

        $.get(formActionUrl, {action: 'saveTotal', val: fCostsTotal, start: iStart});
        
        $('#totalcosts').html(number_format(fCostsTotal, 2, ',', '.'));
        $('#ppAmount').val(fCostsTotal);
        //$('#ppQuantity').val(fQuantityTotal);
    }
});

function explode (delimiter, string, limit) {
    // *     example 1: explode(' ', 'Kevin van Zonneveld');
    // *     returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'}
    // *     example 2: explode('=', 'a=bc=d', 2);
    // *     returns 2: ['a', 'bc=d']
    var emptyArray = {
        0: ''
    };

    // third argument is not required
    if (arguments.length < 2 || typeof arguments[0] == 'undefined' || typeof arguments[1] == 'undefined') {
        return null;
    }

    if (delimiter === '' || delimiter === false || delimiter === null) {
        return false;
    }

    if (typeof delimiter == 'function' || typeof delimiter == 'object' || typeof string == 'function' || typeof string == 'object') {
        return emptyArray;
    }

    if (delimiter === true) {
        delimiter = '1';
    }

    if (!limit) {
        return string.toString().split(delimiter.toString());
    } else {
        // support for limit argument
        var splitted = string.toString().split(delimiter.toString());
        var partA = splitted.splice(0, limit - 1);
        var partB = splitted.join(delimiter.toString());
        partA.push(partB);
        return partA;
    }
}

function number_format (number, decimals, dec_point, thousands_sep) {
    // *     example 1: number_format(1234.56);
    // *     returns 1: '1,235'
    // *     example 2: number_format(1234.56, 2, ',', ' ');
    // *     returns 2: '1 234,56'
    // *     example 3: number_format(1234.5678, 2, '.', '');
    // *     returns 3: '1234.57'
    // *     example 4: number_format(67, 2, ',', '.');
    // *     returns 4: '67,00'
    // *     example 5: number_format(1000);
    // *     returns 5: '1,000'
    // *     example 6: number_format(67.311, 2);
    // *     returns 6: '67.31'
    // *     example 7: number_format(1000.55, 1);
    // *     returns 7: '1,000.6'
    // *     example 8: number_format(67000, 5, ',', '.');
    // *     returns 8: '67.000,00000'
    // *     example 9: number_format(0.9, 0);
    // *     returns 9: '1'
    // *    example 10: number_format('1.20', 2);
    // *    returns 10: '1.20'
    // *    example 11: number_format('1.20', 4);
    // *    returns 11: '1.2000'
    // *    example 12: number_format('1.2000', 3);
    // *    returns 12: '1.200'
    // *    example 13: number_format('1 000,50', 2, '.', ' ');
    // *    returns 13: '100 050.00'
    number = (number + '').replace(',', '').replace(' ', '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}

function str_replace (search, replace, subject, count) {
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'
    var i = 0,
        j = 0,
        temp = '',
        repl = '',
        sl = 0,
        fl = 0,
        f = [].concat(search),
        r = [].concat(replace),
        s = subject,
        ra = r instanceof Array,
        sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }

    for (i = 0, sl = s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j = 0, fl = f.length; j < fl; j++) {
            temp = s[i] + '';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length - s[i].length) / f[j].length;
            }
        }
    }
    return sa ? s : s[0];
}
