/**
* Feedback Class template
*/
(function (root) {

    "use strict";

    /**
     * Common object params
     * @type {Object}
     */
    var common = {
            publicMethods: [],
            className: 'Feedback'
        },

        /**
         * Main constructor
         * @return {Object} - this handle
         */
        Protected = function () {

            var self = this;
            document.addEventListener('DOMContentLoaded', this.init.bind(this));
            return this;
        };


    /**
     * Main prototype
     * @type {Object}
     */
    Protected.prototype = {


        init: function () {

            var self = this;

            Observer.subscribe('loadPage', function () {
                self.setEvents();
            });
        },

        ucFirst: function (string) {
            return string.charAt(0).toUpperCase() + string.slice(1);
        },

        /**
         * Set events to this module.
         * This code fire methods by 'data-action' attribute of '.feedback-module-action' element 
         */
        setEvents: function () {


            // get action element
            var action = document.querySelector('.feedback-module-action'),
                self = this;

            if (action) {

                // try to get attribute
                action = 'action' + this.ucFirst(action.getAttribute('data-action'));

                // fire event action
                this[action] && this[action]();
            }

            this.feedbackForms();

            [].forEach.call(document.querySelectorAll('a[href="#"].feedback'), function (btn) {
                btn.addEventListener('click', function () {
                    self.getForm();
                });
            });
        },

        getForm: function () {

            var self = this;

            Core.blockScreen();
            Core.ajax('/feedback/get-form/', function (json) {
                
                Core.unblockScreen();
                try {
                    var resObj = JSON.parse(json);
                } catch (e) {
                    Core.messageBox('Error');
                    return;
                }

                self.feedbackSplashForm = new JsSplash(resObj.html, {cssClass: 'feedback-js-form'}, function () {
                    self.feedbackForms();
                });

                
            });
        },

        feedbackForms: function () {

            var self = this;

            // validation and send
            [].forEach.call(document.querySelectorAll('.feedback-form form[name="feedback"]'), function (formHandle) {

                new Validator(formHandle, function (err, res) {
                    
                    var errLabel,
                        formData,
                        n;

                    formData = form2object(formHandle, '.', true)

                    Array.prototype.forEach.call(formHandle.querySelectorAll('.validation-error'), function (errLabel) {
                        errLabel.classList.remove('-visible');
                        errLabel.parentNode.querySelector('input.error') && errLabel.parentNode.querySelector('input.error').classList.remove('error');
                    });

                    if (err) {
                        for (n in err) {
                            errLabel = formHandle.querySelector('.validation-error[data-field-name="' + err[n].name + '"]');
                            errLabel.classList.add('-visible');
                            errLabel.innerHTML = err[n].errorText;
                            formHandle.querySelector('input[name="' + err[n].name + '"]').classList.add('error');
                        }

                        return;
                    }


                    Core.blockScreen();
                    Core.ajax('/feedback/send/', formData, function (json) {

                        self.feedbackSplashForm && self.feedbackSplashForm.close();

                        formHandle.reset();
                        Core.unblockScreen();

                        try {
                            var resObj = JSON.parse(json);
                        } catch (e) {
                            Core.messageBox('Error');
                            return;
                        }

                        !!resObj.message && Core.messageBox(resObj.message);
                    });

                }, {onAir: false, showErrors: false});

                

            });
        }
    };

    /**
     * Encapsulation
     * @return {Object} - this handle
     */
    root[common.className] = function () {

        function construct(constructor, args) {

            function Class() {
                return constructor.apply(this, args);
            }
            Class.prototype = constructor.prototype;
            return new Class();
        }

        var original = construct(Protected, arguments),
            Publicly = function () {};
        
        Publicly.prototype = {};
        Array.prototype.forEach.call(common.publicMethods, function (member) {
            Publicly.prototype[member] = function () {
                return original[member].apply(original, arguments);
            };
        });

        return new Publicly(arguments);
    };

}(this));


window.Feedback = new Feedback();