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

    var module = {};

    module.updateCheckboxes = function () {
        $.each($('.checkbox'), function () {
            if ($(this).find('input').prop('checked')) {
                $(this).find('.check').addClass('active');
            }
        });
    };

    module.handleChosen = function () {
        var $selects = $('select');
        $selects.chosen({
            disable_search: true,
            placeholder_text_single: 'wybierz',
            width: '100%'
        });
    };

    module.detectIE = function () {
        var ua = window.navigator.userAgent;

        var msie = ua.indexOf('MSIE ');
        if (msie > 0) {
            // IE 10 or older => return version number
            return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
        }

        var trident = ua.indexOf('Trident/');
        if (trident > 0) {
            // IE 11 => return version number
            var rv = ua.indexOf('rv:');
            return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
        }

        var edge = ua.indexOf('Edge/');
        if (edge > 0) {
            // IE 12 => return version number
            return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
        }

        // other browser
        return false;
    };

    $(document).ready(function () {
        var $header = $('#header'),
            $hintPopup = $('#hint-popup'),
            $subpage = $('.subpage'),
            $subpageCalculator = $('#subpage-calculator'),
            isMobileSize = $(window).width() <= 1140;

        module.handleChosen();

        function setSubpageTopWidth() {
            var $top = $subpage.find('> .subpage-top > .inner');
            $top.css('width', $(window).width()).show();
        }

        setSubpageTopWidth();

        function handleTopSlider() {
            var $slider = $('.top-slider');
            var $ul = $slider.find('ul');
            $slider.find('ul').slick({
                prevArrow: $slider.find('.prev-arrow'),
                nextArrow: $slider.find('.next-arrow'),
                infinite: true,
                slidesToShow: 1,
                slidesToScroll: 1,
                autoplay: true,
                swipe: false,
                autoplaySpeed: 5000,
                speed: 1000,
                responsive: [
                    {
                        breakpoint: 1140,
                        settings: {
                            swipe: true
                        }
                    },
                    {
                        breakpoint: 769,
                        settings: {
                            arrows: $ul.attr('data-no-arrows'),
                            swipe: true
                        }
                    }
                ]
            });
        }

        handleTopSlider();

        function handleHintContent() {
            if (typeof hints == 'undefined') {
                return;
            }

            $.each($('a[data-hint-name]'), function () {
                var name = $(this).data('hint-name');
                var content = hints[name];

                if (content.length) {
                    $(this).attr('data-hint', content);
                } else {
                    $(this).remove();
                }
            });
        }

        handleHintContent();

        function handleHintPopup() {
            $(document).off('click', '[data-hint]');
            $(document).off('mouseenter', '[data-hint]');
            $(document).off('mouseleave', '[data-hint]');

            var eventType = isMobileSize ? 'click' : 'mouseenter';
            $(document).on(eventType, '[data-hint]', function () {
                $hintPopup.stop(true, true);
                var $inner = $hintPopup.find('.inner');

                $inner.css({
                    'max-width': $(window).width() < 400 ? $(window).width() - 40 : ''
                });

                var $text = $hintPopup.find('.text');
                $text.html($(this).data('hint'));
                $hintPopup.fadeIn(300);

                if (!isMobileSize) {
                    $inner.css({
                        'top': $(this).offset().top - $inner.outerHeight() / 2 + $(this).outerHeight() / 2,
                        'left': $(this).offset().left + 14 + 20
                    });
                } else {
                    if($(window).width() < 400) {
                        $inner.css({
                            'top': $(this).offset().top - $inner.outerHeight() - 14,
                            'left': $(window).width() / 2 - $inner.outerWidth() / 2
                        });
                    } else {
                        $inner.css({
                            'top': $(this).offset().top - $inner.outerHeight() - 14,
                            'left': $(this).offset().left - $inner.outerWidth() / 2 + $(this).outerWidth() / 2
                        });
                    }
                }
            });

            if(!isMobileSize) {
                $(document).on('mouseleave', '[data-hint]', function () {
                    $hintPopup.fadeOut(300);
                });
            } else {
                $(document).on('click', '#hint-popup .close', function () {
                    $hintPopup.fadeOut(300);
                });
            }


            $hintPopup.hide();
        }

        handleHintPopup();

        $(document).on('click', '.checkbox .check', function () {
            var $input = $(this).parent().find('input');

            if ($input.attr('disabled')) {
                return;
            }

            $(this).toggleClass('active');


            $(this).find('input').prop('checked', function (index, attr) {
                return !attr;
            });
            $input.change();
        });

        module.updateCheckboxes();

        function handleSubpageCalculatorDropdowns() {
            var $selects = $subpageCalculator.find('select');

            $selects.on('chosen:showing_dropdown', function (evt, params) {
                var $obj = $(evt.target).next().find('.chosen-results');
                $obj.mCustomScrollbar();

                if ($(this).attr('id') == 'order_loading') {
                    var plGroup = $obj.find("li.group-result:contains('Polska')");
                    plGroup.append('<span class="export">export</span>')

                    var chinaGroup = $obj.find("li.group-result:contains('Chiny')");
                    chinaGroup.append('<span class="export">import</span>')
                }
            });

            $selects.on('chosen:hiding_dropdown', function (evt, params) {
                var $obj = $(evt.target).next().find('.chosen-results');
                $obj.mCustomScrollbar('destroy');
            });
        }

        handleSubpageCalculatorDropdowns();

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

        handleSubpageCalculatorUnitsChosen();

        function handleSubpageCalculatorCubic() {
            var $cubicCalculatorOpenButton = $subpageCalculator.find('.cubic');
            var $cubicCalculator = $subpageCalculator.find('.cubic-calculator');

            $cubicCalculatorOpenButton.click(function () {
                $cubicCalculator.fadeToggle(300);
            });

            $cubicCalculator.find('button').click(function () {
                var result = 1;
                $.each($cubicCalculator.find('input'), function () {
                    result *= parseFloat($(this).val().replace(',', '.')  / 100);
                });

                result = Math.round(result * 1000) / 1000;

                $subpageCalculator.find('[data-cubic-result]').val(result).change();
                $cubicCalculator.fadeOut(300);
            });

            $(document).click(function (e) {
                var $target = $(e.target);
                if (
                    !$target.closest($cubicCalculatorOpenButton).length && !$target.closest($cubicCalculator).length

                ) {
                    $cubicCalculator.fadeOut(300);
                }
            })

            $('form[name="order"]').on('keyup keypress', function(e) {
                var code = e.keyCode || e.which;
                if (code == 13) {
                    e.preventDefault();
                    return false;
                }
            });
        }

        handleSubpageCalculatorCubic();

        function handleSubpageCalculatorVolumeUnit() {
            $subpageCalculator.find('.volume .unit').click(function () {
                var $input = $(this).parent().find('> input');
                $input.focus().val($input.val());
            });
        }

        handleSubpageCalculatorVolumeUnit();

        function handleMenu() {
            var $toggle = $header.find('.toggle'),
                $sidebar = $header.find('.sidebar');

            //toggle
            $toggle.click(function () {
                $sidebar.toggleClass('pin');
            });

            //hide on document click
            $(document).click(function (e) {
                var $target = $(e.target);
                if (
                    !$target.closest($sidebar).length && !$target.closest($toggle).length
                ) {
                    $sidebar.removeClass('pin');
                }
            });

            function checkScroll() {
                if($toggle.is(':visible') && $(window).height() < 430) {
                    $sidebar.addClass('scrollable');
                } else {
                    $sidebar.removeClass('scrollable');
                }
            }

            checkScroll();
            $(window).resize(checkScroll);
        }

        handleMenu();

        function handleSymfonyCalculator() {
            if (!$('[data-symfony-calculator]').length) {
                return;
            }

            var connections,
                cost,
                $orderLoading = $('#order_loading'),
                $orderUnloading = $('#order_unloading'),
                $orderLoadingCopy = $('#order_loadingCopy'),
                $orderUnloadingCopy = $('#order_unloadingCopy'),
                $orderVolume = $('#order_volume'),
                $orderWeight = $('#order_weight'),
                $costValue = $('#cost-value'),
                unloadingsClone = $orderUnloading.clone();

            if($orderLoadingCopy.val() && $orderUnloadingCopy.val()) {
                $orderLoading.val($orderLoadingCopy.val());
                $orderLoading.trigger('chosen:updated');
                $orderUnloading.val($orderUnloadingCopy.val());
                $orderUnloading.trigger('chosen:updated');
            }

            // get all possible connections
            $.get(connectionsUrl, function (response) {
                connections = response;

                updateCost();
                updateUnloadingsPorts();
            });

            // remove unused unloading for selected loading
            function updateUnloadingsPorts() {
                var loadingId = $orderLoading.val(),
                    unloadingId = $orderUnloading.val(),
                    unloadingsToLeft = unloadingsClone.clone(),
                    unloadings = [];

                if (!loadingId) {
                    return;
                }

                // find used unloadings
                $.each(connections, function () {
                    if (this.l == loadingId) {
                        unloadings.push(this.u);
                    }
                });

                // remove unused unloadings
                $.each(unloadingsToLeft.find('option'), function () {
                    if ($(this).val() && unloadings.indexOf(parseInt($(this).val())) < 0) {
                        $(this).remove();
                    }
                });

                // remove empty optgroup
                $.each(unloadingsToLeft.find('optgroup'), function () {
                    if (!$(this).find('option').length) {
                        $(this).remove();
                    }
                });

                // set clone html to select field
                $orderUnloading.html(unloadingsToLeft.html());
                $orderUnloading.trigger('chosen:updated');

                if (unloadingId) {
                    $orderUnloading.val(unloadingId);
                    $orderUnloading.trigger('chosen:updated');
                }

                updateCost();
            }

            $orderLoading.change(function () {
                updateUnloadingsPorts();
                $orderLoadingCopy.val($orderLoading.val());
            });

            $orderUnloading.change(function () {
                updateCost();
                $orderUnloadingCopy.val($orderUnloading.val());
            });

            $orderVolume.keyup(function () {
                updateCost();
                showKonteneryButton();
            });

            $orderVolume.change(function () {
                updateCost();
                showKonteneryButton();
            });

            $orderWeight.keyup(function () {
                updateCost();
            });

            $orderWeight.change(function () {
                updateCost();
                showKonteneryButton();
            });

            function showKonteneryButton() {
                var volume = parseFloat($orderVolume.val().replace(',', '.'));
                var weight = parseFloat($orderWeight.val().replace(',', '.'));

                if(volume >= 15 || weight >= 15000) {
                    $subpageCalculator.addClass('kontenery');
                } else {
                    $subpageCalculator.removeClass('kontenery');
                }
            }

            function updateCost() {
                $.each(connections, function () {
                    if (this.l == $orderLoading.val() && this.u == $orderUnloading.val()) {
                        cost = this.c;
                    }
                });

                var volume = $orderVolume.val() ? $orderVolume.val() : $orderVolume.attr('placeholder');
                var weight = $orderWeight.val() ? $orderWeight.val() : $orderWeight.attr('placeholder');

                volume = parseFloat(volume.replace(',', '.'));
                weight = parseFloat(weight) / 1000;

                if (!$orderLoading.val() || !$orderUnloading.val() || !volume || !weight) {
                    $costValue.html('0');
                    return;
                }

                if (volume <= 1 && weight <= 1) {
                    $costValue.html(cost);
                    return;
                }

                $costValue.html(Math.floor(cost * (volume > weight ? volume : weight)));
            }

            function isOnlyNumber($input) {
                var val = $input.val();
                if(val == 0) {
                    val = $input.attr('placeholder');
                }
                val = val.replace(',', '.');
                return val == parseFloat(val);
            }

            var formSubmitted = false;
            $('form[name=order]').submit(function () {
                var $that = $(this);
                var success = true;
                var $weightInput = $(this).find('#weight'),
                    $volumeInput = $(this).find('#order_volume');

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

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

                $.each($(this).find('select[required]'), function () {
                    if (!$(this).val()) {
                        $(this).closest('.form-group').addClass('error');
                        success = false;
                    } else {
                        $(this).closest('.form-group').removeClass('error');
                    }
                });

                if(!isOnlyNumber($weightInput)) {
                    $weightInput.closest('.form-group').addClass('error');
                    success = false;
                } else {
                    $weightInput.closest('.form-group').removeClass('error');
                }

                if(!isOnlyNumber($volumeInput)) {
                    $volumeInput.closest('.form-group').addClass('error');
                    success = false;
                } else {
                    $volumeInput.closest('.form-group').removeClass('error');
                }

                if (success) {
                    if($weightInput.val() == 0) {
                        $weightInput.val($weightInput.attr('placeholder')).keyup();
                    }

                    if($volumeInput.val() == 0) {
                        $volumeInput.val($volumeInput.attr('placeholder'));
                    }

                    $.post(symfonyCalculatorUrl, $(this).serialize(), function (response) {
                        if (response != '//not-valid//') {
                            if(App.Partial.detectIE()) {
                                $that.removeClass('sending');
                            }
                            $that.attr('data-success', true);
                            $that.submit();
                        }
                    });
                } else {
                    formSubmitted = false;
                    $that.removeClass('sending');
                }

                return false;
            });

            function handleUnitsChange() {
                var $weight = $('form[name=order] #weight');
                $weight.keyup(function () {
                    var unit = $(this).parent().find('#unit').val();
                    changeOrderWeight(unit);
                });

                $('form[name=order] #unit').change(function () {
                    var unit = $(this).val();
                    changeOrderWeight(unit);
                });

                function changeOrderWeight(unit) {
                    var conversion = unit === 'kg' ? 1 : 0.45359237;
                    var weight = $weight.val() ? $weight.val() : $weight.attr('placeholder');
                    weight = parseFloat(weight.replace(',', '.'));
                    $orderWeight.val(weight * conversion).change();
                    console.log(unit, weight, weight * conversion)
                }
            }

            handleUnitsChange();
        }

        handleSymfonyCalculator();

        function handleCookiesBar() {
            var $cookies = $('#cookies');

            if (!getCookie('show_cookie_bar')) {
                $cookies.show();
            }

            $cookies.find('.close').click(function () {
                $cookies.hide();
                setCookie('show_cookie_bar', 'true', 100);
            });

            function setCookie(cname, cvalue, exdays) {
                var d = new Date();
                d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
                var expires = "expires=" + d.toUTCString();
                document.cookie = cname + "=" + cvalue + "; " + expires;
            }

            function getCookie(cname) {
                var name = cname + "=";
                var ca = document.cookie.split(';');
                for (var i = 0; i < ca.length; i++) {
                    var c = ca[i];
                    while (c.charAt(0) == ' ') c = c.substring(1);
                    if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
                }
                return "";
            }
        };

        handleCookiesBar();

        $(window).resize(function () {
            setSubpageTopWidth();
            isMobileSize = $(window).width() <= 1140;
            handleHintPopup();
        });
    });

    $.extend({
        redirectPost: function (location, args) {
            var form = '';
            $.each(args, function (key, value) {
                value = value.split('"').join('\"')
                form += '<input type="hidden" name="' + key + '" value="' + value + '">';
            });
            $('<form action="' + location + '" method="POST">' + form + '</form>').appendTo($(document.body)).submit();
        }
    });

    return module;

}(jQuery));