var TranslateForm = (function(){

    var translateInternalLinks = function(content, targetLocale) {
        var el       = $('<div></div>').html(content);
        targetLocale = targetLocale.toLocaleLowerCase();

        $(el).find('a').each(function() {
            var elData = $(this).data();

            for (var key in elData) {
                if (elData.hasOwnProperty(key)) {
                    var matches = /^intlLinks([a-z|A-z]{2})$/.exec(key);

                    if (matches !== null && matches[1]) {
                        if (matches[1].toLocaleLowerCase() === targetLocale) {
                            $(this).attr('href', elData[key]);
                        }
                    }
                }
            }
        });

        return el.html();
    };

    var _resetTabs = function() {
        $('[href="#translateForm"]').trigger('click');
    };

    var _init = function(entityClass, entityId){
        // Update buttons events
        $('[data-action="translate-update-inputs"]').on('click',function(e){
            e.preventDefault();
            var locale = $(this).data("locale");

            var value  = $('[data-type="title"][data-locale="'+locale+'"').val();

            if (value) {
                ComitiumUtils.populateValueToElements(value, [
                    $('[name$="[metadata][metaTitle]"][data-locale="'+locale+'"'),
                    $('[data-type="og-title"][data-locale="'+locale+'"'),
                    $('[data-type="social-title"][data-locale="'+locale+'"')
                ]);
            }
        });

        $('[data-action="translate-update-open-graph"]').on('click',function(e){
            e.preventDefault();

            var locale = $(this).data("locale");

            var title  = $('[name$="[metadata][metaTitle]"][data-locale="'+locale+'"').val();
            var description  = $('[name$="[metadata][metaDescription]"][data-locale="'+locale+'"').val();

            if (title) {
                ComitiumUtils.populateValueToElements(title, [
                    $('[data-type="og-title"][data-locale="'+locale+'"')
                ]);
            }

            if (description) {
                ComitiumUtils.populateValueToElements(description, [
                    $('[data-type="og-description"][data-locale="'+locale+'"')
                ]);
            }
        });

        $('#translate-locale-selector').on('change',function(e){
            var code = $(this).val();
            if (code) {
                $('.translations').hide();
                $('[data-code="' + code + '"]').show();
            } else {
                $('.translations').hide();
            }
        });

        $('[data-edit-url]','#translateForm').each(function(k,v){

            var _this  = $(this);

            _this.on('click', function(e){
                e.preventDefault();

                var url   = _this.data('edit-url') + _this.attr('href');
                var _form = $('form');

                var _modal = window.bootstrap.createModal().show(
                    Translator.trans('translate.modal.from_translate.title'),
                    Translator.trans('translate.modal.from_translate.message'),
                    Translator.trans('translate.modal.from_translate.submit')
                );

                var $dismissButton = $('<button></button>', {
                    'class': 'btn defaultBtn',
                    'id' : 'dismiss-translate',
                    'text' : Translator.trans('translate.modal.from_translate.dismiss')
                });

                $dismissButton.insertAfter(_modal.find('[data-btn-type="cancel"]'));

                _modal.find('[data-btn-type="cancel"], .close').on('click', function (e) {
                    _resetTabs();
                });

                _modal.find('#dismiss-translate').on('click', function (e) {
                    $('.cs-module-spinner').show();
                    formChange.offCheckEvent();
                    BlockContent.unBlockContent(entityClass, entityId);
                    window.location.href = url;
                });

                _modal.find('[data-btn-type="save"]').on('click', function (e) {
                    if (_form.valid()) {
                        var _submit = $(e.target);

                        _submit.addClass('disabled');

                        $.ajax({
                            url: _form.attr('action'),
                            method: _form.attr('method'),
                            data: _form.serialize(),
                            beforeSend: function() {
                                $('.cs-module-spinner').show();
                            },
                            success: function () {
                                formChange.offCheckEvent();
                                BlockContent.unBlockContent(entityClass, entityId);
                                window.location.href = url;
                            },
                            error: function (response) {

                                _resetTabs();

                                showToastrNotification('error', response.responseJSON.message);

                                _modal.find('[data-dismiss="modal"]').trigger('click');

                                $('.cs-module-spinner').hide();
                            }
                        });
                    }
                });
            });
        });

        $('[data-action="init-translate"]').on('click', function(e){
            e.preventDefault();

            var translator        = new CsTranslator();
            var localeDestination = $('#locale_select select').val();
            var localeSource      = $('#default_locale').val();

            var data = {
                localeSource: localeSource,
                localeDestination: localeDestination,
                data: buildData(localeDestination)
            };

            translator.initTranslation(data,
                function(response, error, jqXHR){
                    if (jqXHR.status == 204) {
                        showToastrNotification('warning', Translator.trans('translate.messages.empty_translation'));
                    } else {
                        showToastrNotification('success', Translator.trans('translate.messages.success_translation'));

                        $.each(response, function(k,v){
                            var isFieldValue  = k.match(/CS_FIELD_VALUE_.+/g);
                            var isSlug  = k.match(/_slug$/g);
                            var isMetaTitle  = k.match(/_metaTitle/g);
                            var node;

                            if (isSlug) {
                                return;
                            }

                            if (isFieldValue != null) {
                                var identity = isFieldValue[0].replace('CS_FIELD_VALUE_', '');

                                if (identity) {
                                    node = $('[data-field-identity="'+identity+'"]', '[data-code="'+localeDestination+'"]');
                                }

                            } else {
                                node = $('#' + k, '[data-code="'+localeDestination+'"]')
                            }

                            if (node.val() == '') {
                                var nodeId = node.attr('id');
                                var outputState;
                                var isCKEditor = CKEDITOR.instances[nodeId];

                                var isMetaKeyWord = k.match(/metadata_metaKeywords$/g);

                                if (isMetaKeyWord != null) {
                                    outputState = checkOutputFormat(v, isCKEditor);

                                    if (outputState.errors === true) {
                                        displaySpellCheckerErrors(node);
                                    }

                                    node.importTags(outputState.value);
                                } else {
                                    outputState = checkOutputFormat(v, isCKEditor);

                                    if (outputState.errors === true) {
                                        displaySpellCheckerErrors(node);
                                    }

                                    outputState.value = translateInternalLinks(outputState.value, localeDestination);

                                    if (isCKEditor) {
                                        CKEDITOR.instances[nodeId].setData(outputState.value);

                                    }

                                    node.val(outputState.value);
                                }

                                if (isMetaTitle) {
                                    node.trigger("change");
                                }
                            }
                        });

                    }

                    $('.cs-module-spinner').hide();
                },
                function(response, error, jqXHR){
                    // Show error if is needed here
                },
                function(){
                    $('.cs-module-spinner').show();
                });
        });
    };

    var buildData = function(code) {
        var data = {};
        var destination = $('[data-code="'+code+'"]').attr('id');
        var match   = destination.match(/langs_./g);

        $('.translateTab-origin').find('input,textarea').each(function(){
            var originId   = $(this).attr('id');
            var key = '';

            if (originId) {
                var isFieldValue = originId.match(/.fieldValues./g);

                if (isFieldValue != null) {
                    var identity = $(this).data('field-identity');

                    if (identity) {
                        key = 'CS_FIELD_VALUE_' + $(this).data('field-identity');
                    }

                } else {

                    if (match != null) {
                        key = originId.replace(/langs_./g, match[0]);
                    }
                }

                var value = $(this).val();

                if (value != '' && key != '') {
                    data[key] = value;
                }
            }

        });

        return data;
    };

    var checkOutputFormat = function(value, isCkEditor) {

        var status = {
            errors: false,
            value : value
        };

        if (isCkEditor) {
            return status;
        }

        if (value.match(/(.+)?<font color="#(([0-9a-fA-F]{2}){3}|([0-9a-fA-F]){3})">.+\<\/font\>(.+)?/)) {
            status.errors = true;

            value = value.replace(/<font color="#(([0-9a-fA-F]{2}){3}|([0-9a-fA-F]){3})">/gi, "");
            value = value.replace(/\<\/font\>/gi, "");

            status.value = value;
        }

        if (value.match(/(.+)?<span style="color:(green|red|yellow)">.+\<\/span\>(.+)?/)) {
            status.errors = true;

            value = value.replace(/<span style="color:(green|red|yellow)">/gi, "");
            value = value.replace(/\<\/span\>/gi, "");

            status.value = value;
        }

        return status;
    };

    var displaySpellCheckerErrors = function(node) {
        var spellCheckNode = node.parents('[data-action="spell_text"]');

        if (spellCheckNode) {
            SpellText.displayResult(spellCheckNode, "error");
        }
    };

    return {
      init: function(entityClass, entityId){
          _init(entityClass, entityId);
      }
    };
})();
