$(document).ready(function () {
    'use strict';

    Vue.component('form_builder', {
        created: function () {
            if (this.form_id > 0) {
                $.getJSON('/modules/FormBuilder/admin/ajax/get_data.php?form_id=' + this.form_id, function (data) {
                    this.form = data.form;

                    if (this.form.questions.length) {
                        this.active_question = this.form.questions[0].id;
                        this.current_question = this.form.questions[0];
                    }

                    if (this.form.fieldsets.length) {
                        this.active_fieldset = this.form.fieldsets[0].id;
                        this.current_fieldset = this.form.fieldsets[0];
                    }
                    this.empty_question = data.empty_question;
                    this.empty_fieldset = data.empty_fieldset;
                    this.empty_option = data.empty_option;
                    this.loaded = 1;

                }.bind(this));

                this.show_questions = 1;
                this.show_fieldsets = 1;
                this.show_ordering = 1;
            } else {
                this.show_info = 1;
                this.show_settings = 1;
                $.getJSON('/modules/FormBuilder/admin/ajax/get_data.php?get_empty_form=true', function (data) {
                    this.form = data.form;
                    this.empty_question = data.empty_question;
                    this.empty_fieldset = data.empty_fieldset;
                    this.empty_option = data.empty_option;
                    this.empty_email = data.empty_email;
                    this.loaded = 1;

                }.bind(this));
            }

        },
        props: [
            'form_id',
            'current_question',
            'current_fieldset',
            'last_fieldset_id',
            'last_option_id',
            'last_question_id',
            'last_notification_id'
        ],
        data: function () {
            return {
                loaded: 0,
                show_info: 0,
                show_preview: 0,
                show_settings: 0,
                show_questions: 0,
                show_fieldsets: 0,
                show_ordering: 0,
                active_question: 0,
                active_fieldset: 0,
                empty_question: [],
                empty_fieldset: [],
                empty_option: [],
                empty_email: [],
                form: []
            };
        },
        computed: {
            unassigned_questions: function () {
                var questions = [];
                if (this.loaded) {
                    if (this.form.questions.length) {
                        this.form.questions.forEach(function (question) {
                            if (question.fieldset_id == 0) {
                                questions.push(question);
                            }
                        });
                    }
                }
                return questions;
            },

            show_preview: function () {
                if (this.loaded) {
                    return this.form.questions.length && this.form.fieldsets.length;
                }
            },

            hideRegex: function () {
                return this.current_question.type !== 'input' || this.current_question.validate != 'regex';
            },

            showPlaceholder: function () {
                var allowed = [
                    'input',
                    'select',
                    'textarea'
                ];
                return allowed.indexOf(this.current_question.type) !== -1;

            },

            showOptions: function () {
                var allowed = [
                    'checkbox',
                    'radio',
                    'select'
                ];
                return allowed.indexOf(this.current_question.type) !== -1;
            }
        },
        methods: {
            toggleShowInfo: function () {
                if (this.loaded) {
                    this.show_info = !this.show_info;
                }
            },

            toggleShowSettings: function () {
                if (this.loaded) {
                    this.show_settings = !this.show_settings;
                }
            },

            toggleShowQuestions: function () {
                if (this.loaded) {
                    this.show_questions = !this.show_questions;
                }
            },

            toggleShowFieldsets: function () {
                if (this.loaded) {
                    this.show_fieldsets = !this.show_fieldsets;
                }
            },

            toggleShowOrdering: function () {
                if (this.loaded) {
                    this.show_ordering = !this.show_ordering;
                }
            },

            changeQuestion: function (question_id) {
                this.active_question = question_id;
                this.form.questions.forEach(function (question) {
                    if (question.id == this.active_question) {
                        this.current_question = question;
                    }
                }, this);
            },

            changeFieldset: function (fieldset_id) {
                this.active_fieldset = fieldset_id;
                this.form.fieldsets.forEach(function (fieldset) {
                    if (fieldset.id == this.active_fieldset) {
                        this.current_fieldset = fieldset;
                    }
                }, this);
            },


            addNewFieldset: function () {
                var copy = JSON.parse(JSON.stringify(this.empty_fieldset));
                // Assign ID of last (known) fieldset ID
                copy.id = ++this.last_fieldset_id;
                copy.name = 'New Fieldset';
                copy.order = this.form.fieldsets.length;
                this.form.fieldsets.push(copy);
            },

            addNewQuestion: function () {
                var copy = JSON.parse(JSON.stringify(this.empty_question));
                // Assign ID of last (known) question ID
                copy.id = ++this.last_question_id;
                copy.name = 'New Element';
                copy.order = this.form.questions.length;
                this.form.questions.push(copy);
            },

            addNewOption: function () {
                var copy = JSON.parse(JSON.stringify(this.empty_option));
                // Assign ID of last (known) question ID
                copy.id = ++this.last_option_id;
                copy.order = this.current_question.options.length;
                this.current_question.options.push(copy);
            },

            removeQuestion: function (question_id) {
                var vm = this;
                vm.form.questions.forEach(function (question, idx) {
                    if (question.id === question_id) {
                        vm.form.questions.splice(idx, 1);
                    }
                });
            },

            addNewNotificationEmail: function() {
                var copy = JSON.parse(JSON.stringify(this.empty_email));
                copy.id = ++this.last_notification_id;
                console.log(this.current_question.options, this.current_question.notifications);
                this.current_question.notifications.push(copy);
            },

            removeNotificationEmail: function (notification_id) {
                var vm = this;
                vm.current_question.options.forEach(function(notification, idx) {
                   if(notification.id === notification_id) {
                       vm.current_question.options.splice(idx, 1);
                   }
                });
            },

            removeFieldset: function (fieldset_id) {
                var vm = this;
                vm.form.fieldsets.forEach(function (fieldset, idx) {
                    if (fieldset.id === fieldset_id) {
                        vm.form.fieldsets.splice(idx, 1);
                    }
                })
            },

            fieldsetIsEmpty: function (fieldset) {
                return fieldset.questions.length === 0;
            },

            removeOption: function (option_id) {
                var vm = this;
                vm.current_question.options.forEach(function (option, idx) {
                    if (option.id == option_id) {
                        vm.current_question.options.splice(idx, 1);
                    }
                })
            },

            moveQuestionToNewFieldset: function (question_idx, fieldset_id, old_fieldset_id) {
                var question = this.form.questions[question_idx];
                this.form.fieldsets.forEach(function (fieldset) {
                    if (fieldset.id == fieldset_id) {
                        fieldset.questions.push(question);
                    }
                    if (fieldset.id == old_fieldset_id) {
                        fieldset.questions.forEach(function (fieldset_question, idx) {
                            if (fieldset_question.id == question.id) {
                                fieldset.questions.splice(idx, 1);
                            }
                        });
                    }
                });
            },

            saveForm: function () {
                var vm = this;
                this.form.action = 'update';
                $('#message').html('Updating data')
                    .addClass('warning')
                    .show();

                $.ajax({
                    type: 'post',
                    url: '/modules/FormBuilder/admin/ajax/update.php?ajax=true',
                    data: this.form,
                    context: vm,
                    dataType: 'json',
                    success: function (data) {
                        if (data.status === 'Failed') {
                            html = '';
                            var first_error = Object.keys(data.errors).shift();

                            $('html, body').stop(true, true).delay(200).animate({
                                scrollTop: $('#' + first_error).offset().top - 100
                            }, 1000);

                            for (var error_id in data.errors) {
                                html += data.errors[error_id] + '<br />';
                            }
                            $('#message').html(html)
                                .addClass('error');
                        } else {
                            $('#message').html(data.success)
                                .addClass('success');
                            vm.form = data.form;
                        }
                        setTimeout(
                            function () {
                                $('#message').fadeOut()
                                    .removeClass('error')
                                    .removeClass('warning')
                                    .removeClass('success');
                            }, 10000
                        );
                    }
                })
            },

            doPreview: function () {
                var vm = this;
                this.form.action = 'generate_preview';
                $.ajax({
                    type: 'post',
                    url: '/modules/FormBuilder/admin/ajax/update.php?ajax=true',
                    data: this.form,
                    context: vm,
                    dataType: 'json',
                    success: function (data) {
                        if (data.status == 'ok') {
                            $('#previewCallLink').click();
                        }
                    }
                })

            }

        }
    });

    // Datepicket functionality for form expiry
    Vue.directive('date-time-picker', {
        bind: function () {
            var el = $(this.el);

            el.datetimepicker({
                dateFormat: 'yy-mm-dd',
                timeFormat: 'HH:mm:ss'
            });
        }
    });

    // Sortable fieldsets functionality
    Vue.directive('sortable-fieldset', {
        bind: function () {
            var vm = this.vm,
                el = $(this.el);

            el.sortable({
                opacity: 0.6,
                connectWith: ".column",
                handle: ".portletHeader",
                cancel: ".portletDisabled",
                placeholder: "portlet-placeholder",
                cursor: 'move',
                context: vm,
                update: function () {
                    $.each($(".column .portlet"), function (idx) {
                        var fieldset_id = $(this).attr('data-id');
                        vm.form.fieldsets.forEach(function (fieldset) {
                            if (fieldset.id == fieldset_id) {
                                fieldset.order = idx;
                            }
                        });
                    });
                }
            });
        }
    });

    // Sortable questions functionality
    Vue.directive('sortable-question', {
        bind: function () {
            var vm = this.vm,
                el = $(this.el);

            el.sortable({
                opacity: 0.6,
                placeholder: 'ui-state-highlight',
                connectWith: ".sortableQuestions",
                cursor: 'move',
                context: vm,
                update: function () {
                    $.each($(".sortableQuestions div"), function (idx) {
                        var question_id = $(this).attr('data-id'),
                            fieldset_id = $(this).parent().attr('data-fieldset');
                        vm.form.questions.forEach(function (question, question_idx) {
                            if (question.id == question_id) {
                                if (fieldset_id != question.fieldset_id) {
                                    vm.moveQuestionToNewFieldset(question_idx, fieldset_id, question.fieldset_id);
                                }
                                question.order = idx;
                                question.fieldset_id = fieldset_id;
                            }
                        });
                    });
                }
            });
        }
    });

    // Sortable question option functionality
    Vue.directive('sortable-option', {
        bind: function () {
            var vm = this.vm,
                el = $(this.el);

            el.sortable({
                opacity: 0.6,
                placeholder: 'ui-state-highlight',
                cursor: 'move',
                context: vm,
                update: function () {
                    $.each($(".sortable_options div"), function (idx) {
                        var option_id = $(this).attr('data-id');
                        vm.current_question.options.forEach(function (option) {
                            if (option.id == option_id) {
                                option.order = idx;
                            }
                        });
                    });
                }
            });
        }
    });

    Vue.directive('preview-overlay', {
        bind: function () {
            var el = $(this.el);
            el.mtcOverlay({
                content_class: 'formBuilderPreview',
                max_width: 2000,
                margin_vertical: 5,
                margin_horizontal: 5,
            });
        }
    });

    if ($('#formBuilder').length) {
        var form_builder = new Vue({
            el: '#formBuilder'
        });
    }


    $('.toggleResultWrap').on('click', function (e) {
        var results = $(this).next('.resultWrap');
        if (results.is(':visible')) {
            results.stop(true, true).slideUp();
        } else {
            results.stop(true, true).slideDown();
        }
    });

});
