window.App = window.App || {};
window.App.Calculator = (function ($) {
    'use strict';

    $(document).ready(function () {
        var $calculator = $('#calculator'),
            $voucher = $calculator.find('.voucher'),
            $summation = $calculator.find('.summation'),
            $discount = $summation.find('.discount'),
            $sum = $summation.find('.sum .cost .amount'),
            $conversion = $summation.find('.sum .conversion .amount');

        function updateVars() {
            $voucher = $calculator.find('.voucher');
            $summation = $calculator.find('.summation');
            $discount = $summation.find('.discount');
            $sum = $summation.find('.sum .cost .amount');
            $conversion = $summation.find('.sum .conversion .amount');
        }

        if (!$calculator.length) {
            return;
        }

        function handleTransportCheckbox() {
            $(document).on('change', '[data-transport-checkbox]', function () {
                $calculator.find('.transport').slideToggle(400, function() {
                    if(!$('[data-transport-checkbox]').prop('checked')) {
                        $(this).find('input').val('');
                    }
                });
            });
        }

        handleTransportCheckbox();

        function handleTransportQuantityChosen() {
            var $select = $calculator.find('.quantity select');
            $select.on('change', function (evt, params) {
                $(this).find('option[value=' + params.selected + ']').prependTo($(this));
                $(this).trigger('chosen:updated');
            });
        }

        handleTransportQuantityChosen();

        function handleVoucherCheck() {
            $(document).on('click', '.check-voucher', function () {
                $.post(voucherCheckUrl, {voucher: $('#order_voucher').val()}, function (response) {
                    var sum = $summation.data('connection-cost') + $summation.data('transport-cost');

                    if (response.success) {
                        $voucher.removeClass('wrong').addClass('success');

                        var discount = Math.round($summation.data('connection-cost') * response.value / 100);
                        $discount.find('.amount').html(discount);
                        $discount.show();
                        sum -= discount;
                    } else {
                        $voucher.removeClass('success').addClass('wrong');
                        $discount.hide();
                    }

                    $sum.html(Math.floor(sum));
                    $conversion.html(Math.floor(sum * $summation.data('exchange-rate')));
                }, 'json');
            });
        }

        handleVoucherCheck();

        function checkVoucher() {
            $('#order_voucher').keyup();
        }

        function handleFormSubmit() {
            var formSubmitted = false;
            $(document).on('submit', 'form[name=order]', function () {
                var $that = $(this);

                if ($that.attr('data-success')) {
                    return true;
                }

                if (formSubmitted) {
                    return false;
                } else {
                    formSubmitted = true;
                    $that.addClass('sending');
                }

                var url = $that.data('step') == 1 ? symfonyCalculatorSecondUrl : symfonyCalculatorThirdUrl;

                $.post(url, $(this).serialize(), function (response) {
                    if(App.Partial.detectIE()) {
                        $that.removeClass('sending');
                    }

                    if (response.indexOf('//not-valid//') === -1) {
                        if ($that.data('step') == 1) {
                            $that.attr('data-success', true);
                            $that.submit();
                        } else {
                            var x = $('#order_email').val();
//                            console.log(x);
//                            if(x!=''){
//                                $.redirectPost(calculatorSuccess, {cs: 'true', email: x});
//                            }
//                            else
                            var array = {cs: 'true', email: x};
                            $.redirectPost(calculatorSuccess, array);
                        }
                    } else {
                        response = response.replace('//not-valid//', '');

                        if ($that.data('step') == 1) {
                            response = response.replace('//second-step-url//', calculatorThirdWpUrl);
                            $calculator.find('.content').replaceWith(response);

                            //show transport if selected
                            if ($calculator.find('#order_transport').val()) {
                                $calculator.find('.transport').show();
                            }
                        } else {
                            response = response.replace('//rules-url//', rulesLink);
                            $calculator.find('.content').replaceWith(response);
                            updateVars();
                            checkVoucher();
                        }

                        App.Partial.updateCheckboxes();
                        App.Partial.handleChosen();
                        formSubmitted = false;
                        $that.removeClass('sending');
                    }
                });

                return false;
            });
        }

        handleFormSubmit();

        function scrollToOneThirdOfSlider() {
            var slider = $calculator.find('.subpage-top');
            $(window).scrollTop(slider.offset().top + slider.height() / 3);
        }

        scrollToOneThirdOfSlider();

    });
}(jQuery));