/**
 * @file
 */

(function ($) {
  // Translation tool functionality.


  Drupal.behaviors.NLexTranslationTool = {
    attach: function (context, settings) {

      // Get the drop down lists from the divs filled by cwcms.
      $('#targetLang').html($('.generatedIndicators').html());
      $('#sourceLang').html($('.generatedSourceLang').html());

      // Toggle translation div.
      $('.toggleBtn').click(function () {
        $(this).toggleClass('btn-grey');
        $('.translate-container').toggle();
      });

      // Get targetLang.
      function getTargetLang(){
        var target = document.getElementById("targetLang");
        return target.value;
      }
      // Get targetLang for doc translation.
      function getTargetLangDoc(){
        var target = document.getElementById("targetLangDoc");
        return target.value;
      }
      var reqForTranslation;
      $('.myCallButton').click(function () {
        myLink = $(this);
        $('#targetLang').attr('disabled', 'disabled');
        myLink.addClass('active');
        myLink.addClass('loading');
        myLink.next('img').show();
        $('.translate-comment.error').hide();
        $('.translate-comment.deficient').hide();
        $('.translate-comment.success').hide();
        $.ajax({
            url: "/n-lex/ajaxcall/translate",
            type: "GET",
            dataType: 'json',
            data: {"targetLang": getTargetLang(),"transDocs":false },
            cache:false
        }).done(function (msg) {
          if (!msg.success) {
            $('.translate-comment.error').show();
            $('.translate-comment.error').html(msg.message);
            $('.myCallButton').removeClass('active');
            $('.myCallButton').next('img').hide();
            $('#targetLang').removeAttr('disabled');
          }
          else {
            $("#response_ids").val(msg.data);
            reqForTranslation = setInterval(callForTranslatedText, 2000);
          }

        }).fail(function (jqXHR, textStatus) {
          myLink.removeClass('loading');
          $('.translate-comment.error').show();
          $('.translate-comment.error').html("Error: " + textStatus);
          $('.myCallButton').removeClass('active');
          $('.myCallButton').next('img').hide();
          $('#targetLang').removeAttr('disabled');
        });
      });
      function callForTranslatedText(){
        $.ajax({
          url: "/n-lex/ajaxcall/getTranslations",
          type: "GET",
          dataType: 'json',
          data: {"response_ids":  $("#response_ids").val() },
          cache:false
        }).done(function (msg) {
          if (msg != null) {
            $('#targetLang').removeAttr('disabled');
            $('.myCallButton').removeClass('active');
            $('.myCallButton').next('img').hide();
            clearInterval(reqForTranslation);
            if (msg.success) {
              $('#resultsTable').replaceWith(msg.data);
              showSuccessMessage();
              $(".transContainerDoc select[name='toLang']").val($("#targetLang").val());
              $(".transContainerDoc select[name='toLang']").change(function() {
                if($(this).val() === ""){
                  $(this).next().attr("disabled", "");
                } else {
                  $(this).next().removeAttr("disabled");
                }
              });
              $('.myCallButton').removeClass('loading');
              if ($('.origRes').length) {
                $('.translate-comment.deficient').show();
                $('.origRes').css("background","rgba(241, 224, 171, 1)");
              }
            }
            else {
              $('.myCallButton').removeClass('loading');
              $('.translate-comment.error').show();
              $('.translate-comment.error').html(msg.message);
            }
          }
        }).fail(function (jqXHR, textStatus) {
          $('.myCallButton').removeClass('active');
          $('.myCallButton').next('img').hide();
          $('#targetLang').removeAttr('disabled');
        });
      }
      var reqForTranslationDocs;
      function callForTranslatedTextDocs(position){
        $.ajax({
          url: "/n-lex/ajaxcall/getTranslationsDocs",
          type: "GET",
          dataType: 'json',
          data: {"response_ids":  $("#response_ids").val(),"position":position },
          cache:false
        }).done(function (msg) {
          if (msg != null) {
            $('#targetLang').removeAttr('disabled');
            $('.myCallButton').removeClass('active');
            $('.myCallButton').next('img').hide();

            clearInterval(reqForTranslationDocs);
            if (msg.success) {
              $('#resultsTable').replaceWith(msg.data);
              showSuccessMessage(position);
              $(".transContainerDoc select[name='toLang']").val($("#targetLang").val());
              $(".transContainerDoc select[name='toLang']").change(function() {
                if($(this).val() === ""){
                  $(this).next().attr("disabled", "");
                } else {
                  $(this).next().removeAttr("disabled");
                }
              });
              $('.myCallButton').removeClass('loading');
              if ($('.origRes').length) {
                $('.translate-comment.deficient').show();
                $('.origRes').css("background","rgba(241, 224, 171, 1)");
              }
            }
            else {
              $('.myCallButton').removeClass('loading');
              $('.translate-comment.error').show();
              $('.translate-comment.error').html(msg.message);
            }
          }
        }).fail(function (jqXHR, textStatus) {
          $('.myCallButton').removeClass('active');
          $('.myCallButton').next('img').hide();
          $('#targetLang').removeAttr('disabled');
        });
      }

      function showSuccessMessage(pos){
        var msg = $('.translSuccessDraft').html();
        var from = $('#sourceLang').find(":selected").text();
        var into = $('#targetLang').find(":selected").text();
        msg = msg.replace('sourceLangFlag',$('#spokenLanguageLbl').html());
        msg = msg.replace('targetLangFlag', into);
        $('.translate-comment.success').show();
        $('.translate-comment.success').html(msg);
        $('.translate-commentDoc'+pos+'.success').show();
        $('.translate-commentDoc'+pos+'.success').html(msg);
        $(".transDoc").click(function(){
          myLink = $(this);
          var pos = $(this).attr("data-pos")
          $('#targetLang').attr('disabled', 'disabled');
          myLink.addClass('active');
          myLink.addClass('loading');
          myLink.next('img').show();
          $('.translate-comment.error').hide();
          $('.translate-comment.deficient').hide();
          $('.translate-comment.success').hide();
          $('.translate-commentDoc'+pos+'.error').hide();
          $('.translate-commentDoc'+pos+'.deficient').hide();
          $('.translate-commentDoc'+pos+'.success').hide();
          $.ajax({
            url: "/n-lex/ajaxcall/translateDoc",
            type: "GET",
            dataType: 'json',
            data: {"targetLang": getTargetLangDoc(), "docPosition":pos },
            cache: false
          }).done(function (msg) {
            if (!msg.success) {
              $('.translate-comment.error').show();
              $('.translate-comment.error').html(msg.message);
              $('.translate-commentDoc'+pos+'.error').show();
              $('.translate-commentDoc'+pos+'.error').html(msg.message);
              $('.transDoc').removeClass('active');
              $('.transDoc').next('img').hide();
              $('#targetLang').removeAttr('disabled');
            } else {

              $("#response_ids").val(msg.data);
              reqForTranslationDocs = setInterval(function(){callForTranslatedTextDocs(pos)}, 2000);
            }

          }).fail(function (jqXHR, textStatus) {
            myLink.removeClass('loading');
            $('.translate-comment.error').show();
            $('.translate-comment.error').html("Error: " + textStatus);
            $('.translate-commentDoc.error').show();
            $('.translate-commentDoc.error').html("Error: " + textStatus);
            $('.transDoc').removeClass('active');
            $('.transDoc').next('img').hide();
            $('#targetLang').removeAttr('disabled');
          });
        });
      }

      /* form page call to translate simlpe text field  */
      var reqForTranslateSearchText;
      $(function () {
        $('#form-search-form #edit-submit-button').click(function () {
          const targetLang = document.getElementById("connector_spoken_lang").value;
          const pageLang = document.getElementById("search_legis_lang").value;
          const translateText = jQuery("[name='SearchLegis_text_input']").val();
          const isTitleOrTextCheckboxChecked = jQuery('#title-position').prop("checked") === true || jQuery('#text-position').prop("checked") === true;
          const searchButtonText = jQuery(this).val();
          if (targetLang !== pageLang && translateText !== '' && isTitleOrTextCheckboxChecked) {
            jQuery(this).addClass('loading');
            jQuery(this).val('');
            jQuery(this).attr('disabled','disabled');
            $.ajax({
              url: "/n-lex/ajaxcall/eurovocTransSingleSearch",
              type: "GET",
              dataType: 'json',
              data: {
                "targetLang": targetLang,
                "corpus": Drupal.settings.nlex_aggr_sch.nlex_search_criteria.corpus,
                "translateText": translateText,
                "pageLang": pageLang
              }
            }).done(function (msg) {
              if (!msg.success || (msg.success && msg.data.titleTranslated === false)) {
                const fieldToShowTranslation = "SearchLegis_text_input";
                const translateformText = jQuery("#edit-searchlegis-text-input").val();
                jQuery.ajax({
                  url: "/n-lex/ajaxcall/translateformtext",
                  type: "GET",
                  dataType: 'json',
                  data: {
                    "targetLang": document.getElementById("connector_spoken_lang").value,
                    "pageLang": document.getElementById("search_legis_lang").value,
                    "translateText": translateformText
                  },
                  cache: false
                }).done(function (msg) {
                  if (msg.success) {
                    jQuery("#response_ids").val(msg.data);
                    reqForTranslation = setInterval(function () {
                      callForTranslatedSearchText(fieldToShowTranslation);
                    }, 2000);
                  }
                }).fail(function (jqXHR, textStatus) {

                });
              } else {
                jQuery("[name='SearchLegis_text_input']").val(msg.data.title)
                jQuery("input[name='checkbobx_choises_input']").each(function () {
                  if (jQuery(this).prop("checked") == true && jQuery(this).attr("id") == "title-position") {
                    jQuery("input[name='SearchLegis_title']").val(msg.data.title);
                  } else if (jQuery(this).prop("checked") == false && jQuery(this).attr("id") == "title-position") {
                    jQuery("input[name='SearchLegis_title']").val("");
                  }
                  if (jQuery(this).prop("checked") == true && jQuery(this).attr("id") == "text-position") {
                    jQuery("input[name='SearchLegis_term1']").val(msg.data.title);
                  } else if (jQuery(this).prop("checked") == false && jQuery(this).attr("id") == "text-position") {
                    jQuery("input[name='SearchLegis_term1']").val("");
                  }
                });
                jQuery('#form-search-form #edit-submit-button').removeClass('loading');
                jQuery('#form-search-form #edit-submit-button').val(searchButtonText);
                jQuery('#form-search-form #edit-submit-button').removeAttr('disabled');
                jQuery("#form-search-form").submit();
              }
            }).fail(function (jqXHR, textStatus) {
              jQuery('#form-search-form #edit-submit-button').removeClass('loading');
              jQuery('#form-search-form #edit-submit-button').val(searchButtonText);
              jQuery('#form-search-form #edit-submit-button').removeAttr('disabled');
            });
          } else {
            jQuery("input[name='checkbobx_choises_input']").each(function () {
              if (jQuery(this).prop("checked") == true && jQuery(this).attr("id") == "title-position") {
                jQuery("input[name='SearchLegis_title']").val(translateText);
              } else if (jQuery(this).prop("checked") == false && jQuery(this).attr("id") == "title-position") {
                jQuery("input[name='SearchLegis_title']").val("");
              }
              if (jQuery(this).prop("checked") == true && jQuery(this).attr("id") == "text-position") {
                jQuery("input[name='SearchLegis_term1']").val(translateText);
              } else if (jQuery(this).prop("checked") == false && jQuery(this).attr("id") == "text-position") {
                jQuery("input[name='SearchLegis_term1']").val("");
              }
            });
            jQuery("#form-search-form").submit();
          }
        });
      });
      // For simple search field.
      function callForTranslatedSearchText(fieldToShowTranslation){
        $.ajax({
          url: "/n-lex/ajaxcall/getSearchTextTranslation",
          type: "GET",
          dataType: 'json',
          data: {"response_ids":  $("#response_ids").val() },
          cache:false,
        }).done(function (msg) {
          if (msg != null) {
            clearInterval(reqForTranslation);
            if (msg.success) {
              $('input[name=' + fieldToShowTranslation + ']').val(msg.data);
              $('input[name=' + fieldToShowTranslation + ']').parent().next().next().toggle();
            }
            jQuery("input[name='checkbobx_choises_input']").each(function(){
              if(jQuery(this).prop("checked") == true && jQuery(this).attr("id") == "title-position") {
                jQuery("input[name='SearchLegis_title']").val(jQuery("input[name='SearchLegis_text_input']").val());
              }else if(jQuery(this).prop("checked") == false && jQuery(this).attr("id") == "title-position") {
                jQuery("input[name='SearchLegis_title']").val("");
              }
              if(jQuery(this).prop("checked") == true && jQuery(this).attr("id") == "text-position") {
                jQuery("input[name='SearchLegis_term1']").val(jQuery("input[name='SearchLegis_text_input']").val());
              }else if(jQuery(this).prop("checked") == false && jQuery(this).attr("id") == "text-position") {
                jQuery("input[name='SearchLegis_term1']").val("");
              }
            });
            jQuery("#form-search-form").submit();
          }
        }).fail(function (jqXHR, textStatus) {

        });
      }
    }
  };
}(jQuery));
