/**
 * Created by dimka on 05.05.17.
 */
;(function() {

    document.addEventListener("DOMContentLoaded", initPlugin);

    var cityObject = {};
    var shippingObject = {};
    var paymentObject = {};
    var contactObject = {};
    var confirmObject = {};

    var requestUrl = '/bnphelper/';

    var form = $("#bnpcheckout-form");


    function initPlugin() {

        fixCartContainer();

        initSteps();

        attachFormSubmit();

        cityObject.init();

        contactObject.attachStreetAutoComplete();
        contactObject.attachLoginCheckbox();
    }


    function attachFormSubmit() {

        $("#bnpcheckout-form").on('submit', function() {

            var url = $(this).attr('action');

            var submitButtonRow = $("#submit-button-row")
            var loaderRow = $("#submit-loader-row");

            submitButtonRow.hide();
            loaderRow.show();

            $.post(url, $(this).serialize()).error(function(response) {

                redirectToStandartCheckout();

            }).success(function(response){

                if(response.status === 'fail') {
                    console.log(response);

                    if(typeof response.errors.email !== undefined) {

                        var emailInput = $("input[name='data[email]']");

                        $("#email-error").find('.text-center').text(response.errors.email);
                        $("#email-error").show();

                        submitButtonRow.show();
                        loaderRow.hide();

                        setTimeout(function() {
                            $("#email-error").find('.text-center').empty();
                            $("#email-error").hide();
                            emailInput.val('');
                            emailInput.focus();
                        }, 2000);

                    } else {
                        redirectToStandartCheckout();
                    }

                    return false;
                }

                window.location = "/checkout/success";

            }).complete(function() {

            });

            return false;
        });
    }

    function redirectToStandartCheckout() {

        $("#submit-loader-row").hide();
        $("#checkout-error").show();

        setTimeout(function() {
            window.location = '/checkout';
        }, 2000);

    }


    /**
     * Убираем крепеж плавающей корзины
     */
    function fixCartContainer() {
        $('#cart').css('position', 'inherit');
    }

    function initSteps() {

        cityObject = new CityStep();
        shippingObject = new ShippingStep();
        paymentObject = new PaymentStep();
        contactObject = new ContactStep();
        confirmObject = new ConfirmStep();
    }

    /**
     * Основной конструктор шагов
     * @param name
     * @constructor
     */
    function Step(name) {
        this.name = name;
        this._containers = {};
    }

    /**
     * Устанавливает контейнеры шага
     */
    Step.prototype.setContainers = function() {

        var stepMainContainer = document.getElementById(this.name + '-step');
        var stepContentContainer = stepMainContainer.getElementsByClassName('bnpcheckout-content')[0];
        var stepLoadingContainer =
            stepMainContainer.getElementsByClassName('bnpcheckout-loading').length
                ? stepMainContainer.getElementsByClassName('bnpcheckout-loading')[0]
                : null;

        this._containers = {
            main: stepMainContainer,
            content: stepContentContainer,
            loading: stepLoadingContainer,
        };
    };

    /**
    * Возвращает все контейнеры
    * @returns {{}|*|{main: Element, content: *, loading: null}}
    */
    Step.prototype.getAll = function() {

        return this._containers;
    };

    /**
    * Показывает Загрузка
    */
    Step.prototype.showLoading = function() {

        if(this._containers['loading']) {
            $(this._containers['loading']).show();
        }
    };

    /**
    * Скрывает Загрузка
    */
    Step.prototype.hideLoading = function() {

        if(this._containers['loading']) {
            $(this._containers['loading']).hide();
        }
    };

    /**
    * Добавляет контент в контейнер контента
    * @param {string} content
    * @param {boolean} show надо ли сразу показать контейнер
    */
    Step.prototype.addContentInContainer = function(content, show) {

        show = show || true;

        var content = content || '';

        $(this._containers['content']).html(content);

        if(show) {
            this.showContent();
        }
    };

    /**
    * Очищает контейнер контента
    */
    Step.prototype.clearContentContainer = function() {
        $(this._containers['content']).empty();
    };

    /**
    * Показывает контейнер контента
    */
    Step.prototype.showContent = function() {
        $(this._containers['content']).show();
    };

    /**
    * Скрывает контейнер контента
    */
    Step.prototype.hideContent = function() {
        $(this._containers['content']).hide();
    };

    Step.prototype.scrollToMainContainer = function() {

        var el = this._containers['main'];

        $('html,body').animate({
                scrollTop: $(el).offset().top},
            'slow');
    };

    /**
     * Шаг Контакт
     * @constructor
     */
    function ContactStep() {
        this.name = 'contact';
        Step.prototype.setContainers.apply(this);
    }

    ContactStep.prototype = Object.create(Step.prototype);
    ContactStep.prototype.constructor = ContactStep;

    /**
     * Автозаполнение улицы
     */
    ContactStep.prototype.attachStreetAutoComplete = function() {

        var self = this;
        var autoCompleteUrl = requestUrl + 'streetAutocomplete';
        var selectUrl = requestUrl + 'setSelectStreet';

        // вешаем автоподстановку
        $("#bnpcheckout-street").autocomplete({

            source: function( request, response ) {
                $.ajax( {
                    url: autoCompleteUrl,
                    dataType: "json",
                    data: {term: request.term},

                    success: function( data ) {

                        if(data.status === 'fail') {
                            console.log(data);
                            return;
                        }

                        response( data.data.sugg );
                    }
                });
            },

            minLength: 2,
            html: true,

            select: function( event, ui ) {
                $.ajax({
                    url: selectUrl,
                    data: {data: ui.item.data, value: ui.item.value},
                    dataType: 'json',
                    type: 'post',

                    success: function(response) {

                        if(typeof response.data.zip !== undefined && response.data.zip !== '') {
                            $("#bnpcheckout-zip").val(response.data.zip);
                        }
                    }
                });
            }
        });
    };

    ContactStep.prototype.attachLoginCheckbox = function() {

        $("#create_user").on('change', function() {

            if($(this).is(':checked')) {
                $('.contact-data-password').show();
                $('.contact-data-password').find('input').attr('disabled', false);
            } else {
                $('.contact-data-password').hide();
                $('.contact-data-password').find('input').attr('disabled', true);
            }

        })

    };

    /**
     * Делает улицу адреса доступной и видимой
     */
    ContactStep.prototype.enabledAddress = function() {

        var container = $(this._containers['content']).find('.contact-data-address');

        container.show();
        container.find('input').attr('disabled', false);
    };

    /**
     * Скрывавет улицу адреса
     */
    ContactStep.prototype.disabledAddress = function() {

        var container = $(this._containers['content']).find('.contact-data-address');

        container.hide();
        container.find('input').attr('disabled', true);
    };

    ContactStep.prototype.disabledZip = function() {

        var container = $(this._containers['content']).find('.contact-data-zip');

        container.hide();
        container.find('input').attr('disabled', true);
    };

    ContactStep.prototype.enabledZip = function() {

        var container = $(this._containers['content']).find('.contact-data-zip');
        container.show();
        container.find('input').attr('disabled', false);
    };

    /**
     * Шаг подтверждения
     * @constructor
     */
    function ConfirmStep() {
        this.name = 'confirm';
        Step.prototype.setContainers.apply(this);
    }

    ConfirmStep.prototype = Object.create(Step.prototype);
    ConfirmStep.prototype.constructor = ConfirmStep;

    /**
     * Меняет название доставки на шаге Подтверждения
     * @param name
     */
    ConfirmStep.prototype.changeDeliveryName = function(name) {

        var container = $(this._containers['content']).find('#confirm-shipping-name');

        container.text(name);
    };

    /**
     * Меняет стоимость доставки на шаге Подтверждения
     * @param cost
     */
    ConfirmStep.prototype.changeDeliveryCost = function (cost) {

        var container = $(this._containers['content']).find('#confirm-shipping-rate');

        container.text(cost);

        this.recalcTotal();
    };

    ConfirmStep.prototype.recalcTotal = function() {

        var container = $(this._containers['content']).find('#confirm-total');

        var total = 0;

        var subtotal = parseFloat($("#confirm-subtotal").data('value'));
        var discount = parseFloat($("#confirm-discount").text());
        var shipping = parseFloat($("#confirm-shipping-rate").text());

        total = Number((subtotal - discount) + shipping).toFixed(2);

        container.text(total);
    };

    /**
     * Конструктор шага Город
     * @constructor
     */
    function CityStep() {
        this.name = 'city';
        Step.prototype.setContainers.apply(this);
    }

    // наследуем от Step
    CityStep.prototype = Object.create(Step.prototype);
    CityStep.prototype.constructor = CityStep;


    /**
     * Инициализация шага
     * @private
     */
    CityStep.prototype.init = function() {

        this._getStepContent();
    };

    CityStep.prototype._getStepContent = function() {

        var url = requestUrl + 'get' + this.name + 'Step';

        var self = this;

        $.post(url).error(function(response) {
            console.log(response);
        }).success(function(response){

            if(response.status === 'fail') {
                console.log(response);
                return;
            }

            if(typeof response.data.html !== 'undefined') {
                self.addContentInContainer(response.data.html);
                self.scrollToMainContainer();
                self._postInit();
            }
        });
    };

    CityStep.prototype._postInit = function() {

        var contentContainer = $(this._containers['content']);

        // инпут города
        this.cityAutocompleteInput = contentContainer.find('#city-autocomplete');

        // кнопка смены города
        this.cityChangeButton = contentContainer.find('.bnp-change-city');

        // отмена смены города
        this.cancelCityEl = contentContainer.find('.bnpcheckout-city-cancel');

        if(this.cityAutocompleteInput.val() !== undefined && this.cityAutocompleteInput.val() !== '') {
            // если город удалось определить и он попал в инпут
            this.setCityInputDisable();
            this.setChangeButtonEnabled();
            shippingObject.getStepContent();
        } else {
            // если город определить не удалось
            this.setCityInputEnable();
            this.setChangeButtonDisabled();
        }

        this._attachHandlers();
    };

    /**
     * Ставит кнопку изменения города в disable
     */
    CityStep.prototype.setChangeButtonDisabled = function() {
        this.cityChangeButton.attr('disabled', true);
        //this.cityChangeButton.css('background-color', '#F2F1F0');
    };

    /**
     * Ставит кнопку изменения города в enable
     */
    CityStep.prototype.setChangeButtonEnabled = function() {
        //this.cityChangeButton.css('background-color', '#D01716');
        this.cityChangeButton.attr('disabled', false);
    };

    /**
     * Делает инпут города доступным
     * @private
     */
    CityStep.prototype.setCityInputEnable = function() {

        if(this.currentCity !== '') {
            this.cityAutocompleteInput.attr('placeholder', this.currentCity);
            this.cancelCityEl.show();
        }

        $(this._containers['content']).find('.help-block').show();

        // очищаем
        this.cityAutocompleteInput.val('');

        // делаем достпуным
        this.cityAutocompleteInput.attr('disabled', false);

        // ставим фокус
        this.cityAutocompleteInput.focus();
    };

    /**
     * Делает инупт города недоступным
     * @private
     */
    CityStep.prototype.setCityInputDisable = function() {

        $(this._containers['content']).find('.help-block').hide();

        this.cityAutocompleteInput.attr('disabled', true);
        this.cityAutocompleteInput.blur();

        this.cancelCityEl.hide();
    };

    /**
     * Вешает обработчики
     * @private
     */
    CityStep.prototype._attachHandlers = function() {

        this.cityChangeButton.on('click', $.proxy(this._onClickChangeCity, this));
        this.cancelCityEl.on('click', $.proxy(this._onCancelChangeCity, this));

        var self = this;
        var autoCompleteUrl = requestUrl + 'cityAutocomplete';
        var selectUrl = requestUrl + 'setSelectCity';

        // вешаем автоподстановку
        this.cityAutocompleteInput.autocomplete({

            source: function( request, response ) {
                $.ajax( {
                    url: autoCompleteUrl,
                    dataType: "json",
                    data: {term: request.term},

                    success: function( data ) {

                        if(data.status === 'fail') {
                            console.log(data);
                            return;
                        }

                        response( data.data.sugg );
                    }
                });
            },

            minLength: 2,
            html: true,

            select: function( event, ui ) {
                // выбор города

                $.ajax({
                    url: selectUrl,
                    data: {data: ui.item.data},
                    dataType: 'json',
                    type: 'post',

                    success: function(response) {

                        self.setCityInputDisable();
                        self.setChangeButtonEnabled();
                        shippingObject.getStepContent();
                    }
                });
            }
        });
    };

    /**
     * Обработка нажатия кнопки смены города
     * @returns {boolean}
     * @private
     */
    CityStep.prototype._onClickChangeCity = function() {

        // запоминаем текущий город
        this.currentCity = this.cityAutocompleteInput.val();

        this.setChangeButtonDisabled();
        this.setCityInputEnable();

        // скрываем шаги
        shippingObject.hideContent();
        paymentObject.hideContent();
        contactObject.hideContent();
        confirmObject.hideContent();

        return false;
    };

    /**
     * Обработка нажатия отмены смены города
     * @returns {boolean}
     * @private
     */
    CityStep.prototype._onCancelChangeCity = function() {

        this.cityAutocompleteInput.val(this.currentCity);
        this.setCityInputDisable();
        this.setChangeButtonEnabled();

        // показываем шаги
        shippingObject.showContent();
        paymentObject.showContent();
        //contactObject.showContent();
        //confirmObject.showContent();

        return false;
    };

    function ShippingStep() {
        this.name = 'shipping';
        Step.prototype.setContainers.apply(this);
    }

    ShippingStep.prototype = Object.create(Step.prototype);
    ShippingStep.prototype.constructor = ShippingStep;


    /**
     * Получаем контент шага Доставка
     */
    ShippingStep.prototype.getStepContent = function() {

        var url = requestUrl + 'get' + this.name + 'Step';

        var self = this;

        // показываем Загрузка
        shippingObject.showLoading();

        cityObject.setChangeButtonDisabled();

        $.post(url).error(function(response) {
            // если ошибка
            console.log(response);
        }).success(function(response){
            // если нет ошибки

            if(response.status === 'fail') {
                // если что-то с ответом

                console.log(response);
                return;
            }

            if(typeof response.data.html !== 'undefined') {
                self.addContentInContainer(response.data.html);
                self.scrollToMainContainer();
                self._postInit();
            }
        }).complete(function() {
            // в любом случае прячем Загрузка
            shippingObject.hideLoading();
            cityObject.setChangeButtonEnabled();
        });
    };

    /**
     * Постинциализация
     * @private
     */
    ShippingStep.prototype._postInit = function() {

        var contentContainer = $(this._containers['content']);

        // радио выбора способа доставки
        this.shippingRadio = contentContainer.find('.shipping-radio');

        // селекторы некоторых плагинов доставки
        this.rateSelectors = contentContainer.find('.shipping-rate-select');

        this._attachRadio();
    };

    /**
     * Обработчик радио кнопок выбора способа доставки
     * @private
     */
    ShippingStep.prototype._attachRadio = function() {

        var self = this;

        this.shippingRadio.on('change', function() {

            contactObject.hideContent();
            confirmObject.hideContent();

            // прячем ВСЕ возможные селекты выбора вариантов доставки
            self.rateSelectors.hide();

            // дисаблим их
            self.rateSelectors.attr('disabled', true);

            // отключаем события
            self.rateSelectors.off();

            // задаем прозрачность для ВСЕХ плагинов доставки
            $('.shipping-cost').addClass('not-active-rate');
            $('.shipping-cost').removeClass('active-rate');
            $('.shipping-row').css('background', 'unset');

            // контейнер ТЕКУЩЕГО плагина доставки
            var currentRateContainer = $(this).closest('.row');
            currentRateContainer.css('background', 'rgba(192,192,192, 0.2)');

            // убираем прозрачность для выбранного способа доставки
            currentRateContainer.find('.shipping-cost').removeClass('not-active-rate');
            currentRateContainer.find('.shipping-cost').addClass('active-rate');

            // селект вариантов доставки
            var currentRateSelector = currentRateContainer.find('.shipping-rate-select');

           /* // проверяем на необходимость адреса
            var need = false;

            var plugin_id = $(this).val();

            // индекс для почты
            if(plugin_id == 27) {
                contactObject.enabledZip();
            } else {
                contactObject.disabledZip();
            }

            if(plugin_id == 30 || plugin_id == 23 || plugin_id == 27) {
                need = true;
            }*/

            if(currentRateSelector.length) {
                // если селект существует
                currentRateSelector.show();
                currentRateSelector.attr('disabled', false);
                self._attachRateSelector(currentRateSelector);

                /*if(currentRateSelector.find('option:selected').val() === 'TO_DOOR_1') {
                    need = true;
                }*/
            } else {
                // если нет селекта - двигаем к оплате
                paymentObject.scrollToMainContainer();
            }

            // подгружаем оплату для способа
            paymentObject.getStepContent();

            /*if(need) {
                contactObject.enabledAddress();
            } else {
                contactObject.disabledAddress();
            }*/

            var rate = parseInt($(this).data('rate'), 10);
            confirmObject.changeDeliveryCost(rate);

            var deliveryName = $(this).data('name');
            confirmObject.changeDeliveryName(deliveryName);
        });
    };

    /**
     * Обработчик селекта выбора варианта доставки
     * @param {jQuery Object} selector
     * @private
     */
    ShippingStep.prototype._attachRateSelector = function (selector) {

        selector.on('change', function() {

            var currentRate = $(this).find('option:selected').data('rate');

            if(currentRate != undefined && currentRate != '') {
                selector.closest('.row').find('.shipping-cost-val').text(currentRate);
                selector.closest('.row').find('.shipping-rate').val(currentRate);
                confirmObject.changeDeliveryCost(currentRate);
            }

            var need = false;

            if($(this).find('option:selected').val() === 'TO_DOOR_137' || $(this).find('option:selected').val() === 'DOOR') {
                need = true;
            }

            if(need) {
                contactObject.enabledAddress();
            } else {
                contactObject.disabledAddress();
            }

        });
    };


    function PaymentStep() {
        this.name = 'payment';
        Step.prototype.setContainers.apply(this);
    }

    PaymentStep.prototype = Object.create(Step.prototype);
    PaymentStep.prototype.constructor = PaymentStep;

    /**
     * Загрузчик контента шага Оплата
     */
    PaymentStep.prototype.getStepContent = function() {

        // пытаемся получить выбранный плагин доставки
        var currentShippingId = $('.shipping-radio:checked').val();

        if(currentShippingId === undefined || currentShippingId === '') {
            console.log('Не удалось получить id плагина доставки');
            return;
        }

        var url = requestUrl + 'get' + this.name + 'Step';

        var self = this;

        paymentObject.showLoading();
        paymentObject.clearContentContainer();

        $.post(url, {shipping_id: currentShippingId}).error(function(response) {
            console.log(response);
        }).success(function(response){

            if(response.status === 'fail') {
                console.log(response);
                return;
            }

            if(typeof response.data.html !== 'undefined') {
                self.addContentInContainer(response.data.html);
                self._attachPaymentRadio();
                self._attachInnAutocomplete();
            }
        }).complete(function() {
            paymentObject.hideLoading();
        });
    };

    PaymentStep.prototype._attachPaymentRadio = function() {

        $('.payment-name input').on('change', function() {
            $('.payment-row').css('background', 'unset');

            var currentPaymentContainer = $(this).closest('.row');
            currentPaymentContainer.css('background', 'rgba(192,192,192, 0.2)');

            if(currentPaymentContainer.find('#payment-rekv').length) {
                $('#payment-rekv').find('input').attr('disabled', false);
                $('#payment-rekv').find('textarea').attr('disabled', false);
                $('#payment-rekv').show();
            } else {
                $('#payment-rekv').find('input').attr('disabled', true);
                $('#payment-rekv').find('textarea').attr('disabled', true);
                $('#payment-rekv').hide();
                contactObject.scrollToMainContainer();
            }

            var currentShippingRadio = $('.shipping-radio:checked');

            var currentShippingId = currentShippingRadio.val();

            var shippingRateId = 0;

            var shippingRateSelect = currentShippingRadio.closest('.shipping-name').find('.shipping-rate-select');


            if(shippingRateSelect.length) {

                shippingRateId = shippingRateSelect.find('option:selected').val();
            } else {

                var tt = currentShippingRadio.closest('.shipping-name').find('input[type="hidden"]');

                if(tt.length) {
                    shippingRateId = tt.val();
                }
            }

            contactObject.disabledZip();
            contactObject.disabledAddress();

            var addressNeeded = false;

            if(currentShippingId == 6) {
                // если курьерка по Питеру

                addressNeeded = true;
            } else if(currentShippingId == 1) {
                // сдэк

                if(shippingRateId == 'TO_DOOR_137') {
                    // курьер
                    addressNeeded = true;
                }
            } else if(currentShippingId == 4) {
                // сдэк

                if(shippingRateId == 'COURIER') {
                    // курьер
                    addressNeeded = true;
                }
            } else if(currentShippingId == 23) {
                // Деловые

                if(shippingRateId == 'DOOR') {
                    // курьер
                    addressNeeded = true;
                }
            } else if(currentShippingId == 10) {
                // Почта

                contactObject.enabledZip();
                addressNeeded = true;
            }

            if(addressNeeded) {
                contactObject.enabledAddress();
            }

            contactObject.showContent();
            confirmObject.showContent();
        });
    };

    PaymentStep.prototype._attachInnAutocomplete = function() {

        var companyAutocomplete = $("#company-autocomplete");

        companyAutocomplete.off();

        var self = this;
        var autoCompleteUrl = requestUrl + 'innAutocomplete';
        var selectUrl = requestUrl + 'setSelectCity';

        // вешаем автоподстановку
        companyAutocomplete.autocomplete({

            source: function( request, response ) {
                $.ajax( {
                    url: autoCompleteUrl,
                    dataType: "json",
                    data: {term: request.term},

                    success: function( data ) {
                        if(data.status === 'fail') {
                            console.log(data);
                            return;
                        }

                        console.log(data);

                        response( data.data.sugg );
                    }
                });
            },

            minLength: 2,
            html: true,

            select: function( event, ui ) {
                // выбор города

                var org = ui.item.data;

                if(ui.item.value) {
                    $("#contact-company").val(ui.item.value);
                }

                if(org.address.value) {
                    $("#contact-uaddress").val(org.address.value);
                }

                if(org.kpp) {
                    $("#contact-kpp").val(org.kpp);
                }

                if(org.inn) {
                    $("#contact-inn").val(org.inn);
                }
            }
        });


    };


})();