/**
 * Used in conjunction with htmk5validator this helper highlights the 
 * tabs with errors en marks incorrect fields.
 * 
 * @author Visual Media
 */

(function($) {

    $(document).ready(function() {


        /**
         * Mark tabs that contains errors
         * 
         * @param {DOMElement} frm       Form to check
         * @param {Boolean}    autofocus Autofocus first tab with erros
         * 
         * @return {undefined}
         */
        var updateTabStatus = function(frm, autofocus) {
            frm.find('a[data-toggle="tab"]').each(function() {
                var tab = $(this);
                var href_re = /#([a-z_0-9]+)$/;
                var href = tab.attr('href');
                if (!href_re.test(href)) {
                    return;
                }
                var id = href_re.exec(href)[1];
                var pane = frm.find('#' + id + '.tab-pane');

                if (pane.find('.has-error').length > 0) {
                    tab.addClass('error').addClass('html5-tab-error');
                } else {
                    tab.removeClass('error').removeClass('html5-tab-error');
                }
            });

            if (autofocus) {
                if (frm.find('a[data-toggle="tab"]').length > 0) {
                    frm.find('a.html5-tab-error').first().tab('show');
                }
            }
        };

        var updateValidationResultStatus = function(frm) {

            frm.find('*[data-validation-result]').each(function() {
                var result_el = $(this),
                    search_el = $('#' + $(this).attr('data-validation-result'));

                if (search_el.find('.has-error').length > 0) {
                    result_el.addClass('error').addClass('html5-error');
                } else {
                    result_el.removeClass('error').removeClass('html5-error');
                }
                
            });

        };


        // Go trough forms to validate
        $('.form-html5-validation').each(function() {

            var frm = $(this);


            // Update tab status on form load
            updateTabStatus(frm, true);
            updateValidationResultStatus(frm);

            frm.attr('novalidate', 'novalidate');

            // Initialize new html5validator version
            $(this).html5validator({
                /**
                 * {@inheritdoc}
                 */
                beforeValidate: function() {
                    frm.triggerHandler('beforeserialize');
                },
                /**
                 * {@inheritdoc}
                 */
                validField: function(field, onsubmit) {
                    var container = field;
                    for (var x = 0; x < 5; x++) {
                        if (container.is('.form-group')) {
                            break;
                        }
                        container = container.parent();
                    }

                    if (container.is('.form-group')) {
                        container.removeClass('html5-error').removeClass('has-error');
                        container.find('.help-block.html5-error-message').remove();
                    }
                    updateTabStatus(frm, false);
                    updateValidationResultStatus(frm);
                    return true;
                },
                /**
                 * {@inheritdoc}
                 */
                inValidField: function(field, message, onsubmit) {
                    if (onsubmit) {
                        var container = field;
                        for (var x = 0; x < 5; x++) {
                            if (container.is('.form-group')) {
                                break;
                            }
                            container = container.parent();
                        }
                        if (container.is('.form-group')) {
                            container.addClass('html5-error').addClass('has-error');

                            if (container.find('.form-error-container').length > 0) {
                                if (container.find('.form-error-container').find('.help-block.html5-error-message').length === 0) {
                                    container.find('.form-error-container').append($('<p class="help-block html5-error-message" />').text(message));
                                }
                            } else {
                                if (container.find('.help-block.html5-error-message').length === 0) {
                                    container.append($('<p class="help-block html5-error-message" />').text(message));
                                }
                            }
                            
                        }
                    }
                    return false;
                },
                /**
                 * {@inheritdoc}
                 */
                beforeSubmit: function(invalid) {
                    updateTabStatus(frm, true);
                    updateValidationResultStatus(frm);
                    if (invalid.length === 0) {
                        return true;
                    }
                    return false;
                },
                requiredSelector: '[required],[data-ckeditor-required]',
                requiredMessage: Translator.trans('validation.required', {}, 'js'),
                requiredGroupMessage: Translator.trans('validation.required_group', {}, 'js'),
                patternMessage: Translator.trans('validation.pattern', {}, 'js'),
                types: {
                    number: {
                        message: Translator.trans('validation.type.number', {}, 'js')
                    },
                    email: {
                        message: Translator.trans('validation.type.email', {}, 'js')
                    },
                    url: {
                        message: Translator.trans('validation.type.url', {}, 'js')
                    },
                    tel: {
                        message: Translator.trans('validation.type.tel', {}, 'js')
                    }
                }

            });
        });
    });

})(jQuery);
