googlud / hi to mi - translate manga

// ==UserScript==
// @name         hi to mi - translate manga
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You

// @license MIT

// @match        https://hitomi.la/reader/*

// @grant        none
// ==/UserScript==

(function ($) {

  function onValueChange($input, callback) {
    var input = $($input).get(0);

    if (!input) {
      return
    }

    var last_input_value = input.value;
    setInterval(function () {
      var new_value = input.value;

      if (last_input_value != new_value) {
        last_input_value = new_value;
        callback(new_value);
      }

    }, 50);
  }

  function getLang() {
    return localStorage.trans_lang || 'ko';
  }

  function setLang(lang) {
    return localStorage.trans_lang = lang;
  }

  setInterval(function () {
    console.log('working...')

    if ($('#current_lang').length) {
      $('#current_lang').text(getLang());
    }

    if ($('.lang_btn').length == 0) {
      console.log('bind!')
      var ko_lang_btn = $('<button class="lang_btn" data-sl="ko">Korean</button>');
      var cn_lang_btn = $('<button class="lang_btn" data-sl="zh-CN">Chines</button>');
      var ja_lang_btn = $('<button class="lang_btn" data-sl="ja">Japenese</button>');
      var current_lang = $('<div id="current_lang">' + getLang() + '</div>');

      $(current_lang).insertAfter('.ocrext-ocr-output');
      $(ko_lang_btn).insertAfter('.ocrext-grid-message');
      $(cn_lang_btn).insertAfter('.ocrext-grid-message');
      $(ja_lang_btn).insertAfter('.ocrext-grid-message');

      $('.lang_btn').click(function () {
        var source_lang = $(this).data('sl');
        setLang(source_lang);
        $('#current_lang').text(getLang());
      })

      onValueChange($('.ocrext-ocr-message.ocrext-result'), function (text) {
        if (text) {
          var popup = window.open(
            "https://translate.google.com/?text=" + text + "&sl=" + getLang() + "&tl=en",
            "google_translate_window",
            "width=500, height=200, top=500, left=900, scrollbars=yes"
          );

          $('.ocrext-title a[title="Close"]').get(0).click();

        }
      })
    }

  }, 1000)
})(jQuery);