var FormWizard = function () {

    var form_wizard = $("#form-wizard form");

    return {
        //main function to initiate the module
        init: function () {
            if (!jQuery().bootstrapWizard) {
                return;
            }

            var error = $('.alert-danger', form_wizard);
            var success = $('.alert-success', form_wizard);

            form_wizard.validate({
                onfocusout: false,
                doNotHideMessage: true, //this option enables to show the error/success messages on tab switch.
                errorElement: 'span', //default input error message container
                errorClass: 'help-block help-block-error', // default input error message class
                focusInvalid: false, // do not focus the last invalid input
                errorPlacement: function (error, element) { // render error placement for each input type
                    if( element.parents('.input-daterange-container:first').length > 0 )
                    {
                        if( !element.parents('.input-daterange-container:first').next().hasClass('help-block-error') )
                        {
                            error.insertAfter(element.parents('.input-daterange-container:first'));
                        }
                    }
                    else if( element.parents('.radio-list:first').length > 0)
                    {
                        if( !element.parents('.radio-list:first').next().hasClass('help-block-error') )
                        {
                            error.insertAfter(element.parents('.radio-list:first'));
                        }
                    }
                    else
                    {
                        error.insertAfter(element); // for other inputs, just perform default behavior
                    }
                    //console.log(error.html(1));
                    //if (element.attr("name") == "gender") { // for uniform radio buttons, insert the after the given container
                    //    error.insertAfter("#form_gender_error");
                    //} else if (element.attr("name") == "payment[]") { // for uniform radio buttons, insert the after the given container
                    //    error.insertAfter("#form_payment_error");
                    //} else {
                    //    error.insertAfter(element); // for other inputs, just perform default behavior
                    //}

                },

                invalidHandler: function (event, validator) { //display error alert on form submit
                    success.hide();
                    error.show();
                    Metronic.scrollTo(error, -200);
                    //'this' refers to the form

                    if (FormWizard.validateHidden) {
                        validator.currentElements.each(function(k,v){
                           if ($(v).prop('type') == 'hidden') {
                               showToastrNotification('error', FormWizard.hiddenErrorMessage);
                           }
                        });
                    }
                },

                highlight: function (element) { // hightlight error inputs
                    $(element)
                        .closest('.form-group').removeClass('has-success').addClass('has-error'); // set error class to the control group
                },

                unhighlight: function (element) { // revert the change done by hightlight
                    $(element)
                        .closest('.form-group').removeClass('has-error'); // set error class to the control group
                },

                success: function (label) {
                    if (label.attr("for") == "gender" || label.attr("for") == "payment[]") { // for checkboxes and radio buttons, no need to show OK icon
                        label
                            .closest('.form-group').removeClass('has-error').addClass('has-success');
                        label.remove(); // remove error label here
                    } else { // display success icon for other inputs
                        label
                            .addClass('valid') // mark the current input as valid and display OK icon
                            .closest('.form-group').removeClass('has-error').addClass('has-success'); // set success class to the control group
                    }
                },
                submitHandler: function(form) {
                    $(form).find('button[type="submit"]').prop('disabled', true);
                    form.submit();
                },
                ignore: FormWizard.ignoreValues
            });

            var displayConfirm = function () {
                $('#tab4 .form-control-static', form_wizard).each(function () {
                    var input = $('[name="' + $(this).attr("data-display") + '"]', form);
                    if (input.is(":radio")) {
                        input = $('[name="' + $(this).attr("data-display") + '"]:checked', form);
                    }
                    if (input.is(":text") || input.is("textarea")) {
                        $(this).html(input.val());
                    } else if (input.is("select")) {
                        $(this).html(input.find('option:selected').text());
                    } else if (input.is(":radio") && input.is(":checked")) {
                        $(this).html(input.attr("data-title"));
                    } else if ($(this).attr("data-display") == 'payment') {
                        var payment = [];
                        $('[name="payment[]"]:checked').each(function () {
                            payment.push($(this).attr('data-title'));
                        });
                        $(this).html(payment.join("<br>"));
                    }
                });
            };

            var handleTitle = function (tab, navigation, index) {
                var total = navigation.find('li').length;
                var current = index + 1;
                form_wizard.find('.current-step').text(current);
                jQuery('li', form_wizard).removeClass("done");
                var li_list = navigation.find('li');
                for (var i = 0; i < index; i++) {
                    jQuery(li_list[i]).addClass("done");
                }

                Metronic.scrollTo($('.page-title'));
            };

            form_wizard.bootstrapWizard({
                'nextSelector': '[data-btn-type="back"]',
                'previousSelector': '[data-btn-type="continue"]',
                onTabClick: function (tab, navigation, index, clickedIndex) {

                    FormWizard.onTabClick.dispatch(tab, navigation, index, clickedIndex);

                    if (FormWizard.allowTabClick === false) {
                        return false;
                    }
                },
                onNext: function (tab, navigation, index) {
                    success.hide();
                    error.hide();

                    if (form_wizard.valid() == false || FormWizard.allowNext === false) {
                        return false;
                    }

                    handleTitle(tab, navigation, index);

                    FormWizard.onNext.dispatch(tab, navigation, index);
                },
                onPrevious: function (tab, navigation, index) {
                    success.hide();
                    error.hide();

                    if (FormWizard.allowPrevious === false) {
                        return false;
                    }

                    handleTitle(tab, navigation, index);

                    FormWizard.onPrevious.dispatch(tab, navigation, index);
                },
                onTabShow: function (tab, navigation, index) {
                    var total = navigation.find('li').length;
                    var current = index + 1;
                    var $percent = (current / total) * 100;
                    $('#form-wizard').find('.progress-bar').css({
                        width: $percent + '%'
                    });

                    FormWizard.onChange.dispatch(tab, navigation, index);
                }
            });

            this.bootstrapWizard = form_wizard.data('bootstrapWizard');
            this.form = form_wizard;

            $.validator.addMethod("maxlength", function(value, element) {

                var max = parseInt($(element).attr('maxlength'));

                if (max > 0) {
                    var value = $(element).val().trim();
                    var text = $(element).is('textarea') ? value.replace( /<.*?>|\n/g, '' ) : value;

                    if (text.length > max) {
                        return false;
                    }
                }

                return true;
            });
        },
        onChange: new signals.Signal(),
        onTabClick: new signals.Signal(),
        onNext: new signals.Signal(),
        onPrevious: new signals.Signal(),
        ignoreValues: ':hidden',
        setIgnoreValues: function(v) {
            this.ignoreValues = v;
        },
        validateHidden: false,
        setValidateHidden: function(v) {
            this.validateHidden = v;
        },
        hiddenErrorMessage: '',
        setHiddenErrorMessage: function(v) {
            this.hiddenErrorMessage = v;
        },
        allowTabClick: true,
        allowNext: true,
        allowPrevious: true,
        disableStep: function(step) {
            form_wizard.bootstrapWizard('disable', step-1);
        },
        enableStep: function(step) {
            form_wizard.bootstrapWizard('enable', step-1);
        }
    };
}();
