Greasy Fork

Greasy Fork is available in English.

TW Gold Jobs Finder (More Languages)

Shows a list of all silver and gold jobs!

当前为 2015-06-23 提交的版本,查看 最新版本

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Userscripts ,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name TW Gold Jobs Finder (More Languages)
// @namespace TomRobert
// @author Macabre2077 (updated by Tom Robert)
// @description Shows a list of all silver and gold jobs!
// @include http*://*.the-west.*/game.php*
// @version 1.04
// @grant none
// ==/UserScript==
// translation: Did97(Russian), tw81(Italian), Jakovlev(Hungarian), realfan2002(Romanian), Vebuus(Polish), Ilja Iljic(Czech), pepe100(Spanish), Tom Robert(German & French), Elly Siranno(Portuguese)
(function (fn) {
  var script = document.createElement('script');
  script.setAttribute('type', 'application/javascript');
  script.textContent = '(' + fn + ')();';
  document.body.appendChild(script);
  document.body.removeChild(script);
}) (function () {
  GoldJobs = {
    version: '1.04',
    name: 'Gold Jobs Finder',
    author: 'Macabre2077 (updated by Tom Robert)',
    minGame: '2.05',
    maxGame: Game.version.toString(),
    website: 'http://greasyfork.icu/scripts/7226',
    updateUrl: 'https://raw.githack.com/TomRobert/tw/master/sU.js',
    updateAd: 'http://adf.ly/1J00Xr',
    toLoad: 0,
    loaded: 0,
    xMax: 181,
    yMax: 79,
    blockMaxLength: 300,
    dataLoaded: false,
    silverJobBbColor: '#708090',
    goldJobBbColor: '#AB9930',
    preferences: {
      jobName: '',
      showSilver: true,
      showGold: true,
      sortByName: 0,
      sortByDistance: 1
    },
    hiddenImageOpacity: 0.35,
    shownImageOpacity: 1,
    bestJobTime: 0
  };
  langs = {
    en_US: {
      language: 'None (English)',
      ApiGui: 'This script adds a button on the right side, where you can load all the silver and gold jobs.<br>So they can be easily found on the map.',
      contact: 'Contact',
      jobName: 'Job name',
      distanceTime: 'Travel time',
      showJob: 'Show',
      title: 'Gold And Silver Jobs',
      loading: 'Loading...',
      exportButtonTitle: 'Export',
      generatedBy: 'Generated by TW Gold Jobs Finder',
      generatedByBb: '[i][url=' + GoldJobs.website + ']Generated by TW Gold Jobs Finder[/url][/i]',
      goback: 'Go back',
      bbCode: 'BB code',
      enqueue: 'Enqueue',
      openWindowTitle: 'Open window',
      refreshTitle: 'Refresh',
      feedbackTitle: 'Send feedback',
      feedbackWindowTitle: 'Gold Jobs Feedback',
      feedbackDescription: 'If you have encountered any bugs or have ideas how to improve this script, describe them.. in English, German or French please..',
      update: 'Update',
      updateAvailable: 'A new version of the script is available',
    },
    ru_RU: {
      language: 'Russian (русский)',
      ApiGui: 'Этот скрипт добавляет кнопку справа, с помощью которой Вы можете посмотреть все серебрянные и золотые работы.<br>Это поможет найти их на карте.',
      contact: 'Контакты',
      jobName: 'Работа',
      distanceTime: 'Расстояние',
      showJob: 'Показать',
      title: 'Золотые и серебряные работы',
      loading: 'Загрузка...',
      exportButtonTitle: 'Экспорт',
      generatedByBb: '[i][url=' + GoldJobs.website + ']Получено с помощью TW Gold Jobs Finder[/url][/i]',
      goback: 'Назад',
      bbCode: 'BB-код',
      enqueue: 'Начать',
      openWindowTitle: 'Открыть окно',
      refreshTitle: 'Обновить данные',
      feedbackTitle: 'Обратная связь',
      feedbackWindowTitle: 'Gold Jobs, обратная связь',
      feedbackDescription: 'Если Вы нашли баг, или у Вас есть идеи по улучшению скрипта, свяжитесь со мной',
      update: 'Обновление',
      updateAvailable: 'Доступно обновление скрипта',
    },
    it_IT: {
      language: 'Italian (italiano)',
      ApiGui: 'This script adds a button on the right side, where you can load all the silver and gold jobs.<br>So they can be easily found on the map.',
      contact: 'Contatto',
      jobName: 'Nome lavoro',
      distanceTime: 'Tempo di viaggio',
      showJob: 'Mostra',
      title: 'Lavoro Oro e Argento',
      loading: 'Caricamento in corso ... Ci vorrà un po \'',
      exportButtonTitle: 'Esportazione',
      generatedByBb: '[i][url=' + GoldJobs.website + ']Generato da TW Gold Jobs Finder[/url][/i]',
      goback: 'Di ritorno',
      bbCode: 'BB code',
      enqueue: 'Inizia',
      openWindowTitle: 'Aperto',
      refreshTitle: 'Aggiornare dati',
      feedbackTitle: 'Invia feedback',
      feedbackWindowTitle: 'Gold Jobs Feedback',
      feedbackDescription: 'Se avete riscontrato qualche bug o avete idee su come migliorare questo script, vi prego di descriverle .. in inglese, tedesco o francese per favore.',
      update: 'Atualizar',
      updateAvailable: 'Script aggiornamento disponibile',
    },
    hu_HU: {
      language: 'Hungarian (Magyar)',
      ApiGui: 'This script adds a button on the right side, where you can load all the silver and gold jobs.<br>So they can be easily found on the map.',
      contact: 'Érintkezés',
      jobName: 'Munka neve',
      distanceTime: 'Menetidő',
      showJob: 'Mutatás',
      title: 'Arany és ezüst munkák',
      loading: 'Kis türelmet, töltés alatt...',
      exportButtonTitle: 'Export',
      generatedByBb: '[i][url=' + GoldJobs.website + ']TW Gold Jobs Finder által létrehozva[/url][/i]',
      goback: 'Vissza',
      bbCode: 'BB kód',
      enqueue: 'Kezdés',
      openWindowTitle: 'Megnyitás',
      refreshTitle: 'Frissítés',
      feedbackTitle: 'Visszajelzés küldése',
      feedbackWindowTitle: 'Gold Jobs visszajelzés',
      feedbackDescription: 'Ha találkoztál hibákkal (bug), vagy javaslatod lenne a szkript bővítéséhez írd le őket. Értek angolul, németül és franciául.',
      update: 'Frissítés',
      updateAvailable: 'Egy új változata a script elérhető',
    },
    ro_RO: {
      language: 'Romanian (român)',
      ApiGui: 'This script adds a button on the right side, where you can load all the silver and gold jobs.<br>So they can be easily found on the map.',
      contact: 'Contact',
      jobName: 'Denumirea muncii',
      distanceTime: 'Distanţa',
      showJob: 'Arată',
      title: 'Munci aurii şi argintii',
      loading: 'Se încarcă... Poate dura ceva timp!',
      exportButtonTitle: 'Export',
      generatedByBb: '[i][url=' + GoldJobs.website + ']Generat cu TW Gold Jobs Finder[/url][/i]',
      goback: 'Înapoi',
      bbCode: 'BB code',
      enqueue: 'Start',
      openWindowTitle: 'Deschide',
      refreshTitle: 'Reîmprospăta',
      feedbackTitle: 'Trimite feedback',
      feedbackWindowTitle: 'Gold Jobs Feedback',
      feedbackDescription: 'If you have encountered any bugs or have ideas how to improve this script, describe them.. in English, German or French please..',
      update: 'Actualizare',
      updateAvailable: 'O nouă versiune este disponibilă',
    },
    pl_PL: {
      language: 'Polish (polski)',
      ApiGui: 'This script adds a button on the right side, where you can load all the silver and gold jobs.<br>So they can be easily found on the map.',
      contact: 'Kontakt',
      jobName: 'Nazwa pracy',
      distanceTime: 'Dystans',
      showJob: 'Pokaż',
      title: 'Złote i srebrne prace',
      loading: 'Ładowanie... To zajmie moment',
      exportButtonTitle: 'Eksport',
      generatedByBb: '[i][url=' + GoldJobs.website + ']Stworzone przez TW Gold Jobs Finder[/url][/i]',
      goback: 'Z Powrotem',
      bbCode: 'BB code',
      enqueue: 'Startuj',
      openWindowTitle: 'Otwierać',
      refreshTitle: 'Odświeżanie danych',
      feedbackTitle: 'Wysłać opinię',
      feedbackWindowTitle: 'Gold Jobs Opinię',
      feedbackDescription: 'If you have encountered any bugs or have ideas how to improve this script, describe them.. in English, German or French please..',
      update: 'Aktualizacja',
      updateAvailable: 'Nowa wersja skryptu jest dostępna',
    },
    cs_CZ: {
      language: 'Czech (čeština)',
      ApiGui: 'This script adds a button on the right side, where you can load all the silver and gold jobs.<br>So they can be easily found on the map.',
      contact: 'Kontakt',
      jobName: 'Práce',
      distanceTime: 'Vzdálenost',
      showJob: 'Ukaž',
      title: 'Zlaté a stříbrné práce',
      loading: 'Nahrávám...',
      exportButtonTitle: 'Export',
      generatedByBb: '[i][url=' + GoldJobs.website + ']Generated by TW Gold Jobs Finder[/url][/i]',
      goback: 'Zpět',
      bbCode: 'BB code',
      enqueue: 'Zadat',
      openWindowTitle: 'Otevřít okno',
      refreshTitle: 'Obnovit',
      feedbackTitle: 'Pošli zpětnou vazbu',
      feedbackWindowTitle: 'Gold Jobs Feedback',
      feedbackDescription: 'Pokud jste nalezli bug nebo máte nápad na zlepšení skriptu, napište je..v angličtině, němčině nebo francouzštině prosím..',
      update: 'Aktualizovat',
      updateAvailable: 'Nová verze skriptu je k dispozici',
    },
    es_ES: {
      language: 'Spanish (español)',
      ApiGui: 'This script adds a button on the right side, where you can load all the silver and gold jobs.<br>So they can be easily found on the map.',
      contact: 'Contacto',
      jobName: 'Nombre Trabajo',
      distanceTime: 'Tiempo viaje',
      showJob: 'Mostrar',
      title: 'Trabajos con Bonus Oro y Plata',
      loading: 'Cargando...',
      exportButtonTitle: 'Exportación',
      generatedByBb: '[i][url=' + GoldJobs.website + ']Generado por TW Gold Jobs Finder[/url][/i]',
      goback: 'De regreso',
      bbCode: 'BB code',
      enqueue: 'Poner en cola',
      openWindowTitle: 'Abrir ventana',
      refreshTitle: 'Refrescar',
      feedbackTitle: 'Enviar comentarios',
      feedbackWindowTitle: 'Gold Jobs comentarios',
      feedbackDescription: 'Si ha encontrado algún error o tiene ideas de cómo mejorar este script, descríbalos.. por favor en inglés, alemán o francés..',
      update: 'Actualización',
      updateAvailable: 'Una nueva versión está disponible',
    },
    de_DE: {
      language: 'German (Deutsch)',
      ApiGui: 'Das Script fügt am rechten Rand einen Button hinzu, wo man alle Gold- und Silber-Arbeiten laden kann.<br>So findet man sie ganz einfach auf der Karte.',
      contact: 'Kontakt',
      jobName: 'Arbeit',
      distanceTime: 'Distanz',
      showJob: 'Zeigen',
      title: 'Gold und Silber Arbeiten',
      loading: 'Laden...',
      exportButtonTitle: 'Exportieren',
      generatedByBb: '[i][url=' + GoldJobs.website + ']Gefunden mit TW Gold Jobs Finder[/url][/i]',
      goback: 'Zurück',
      bbCode: 'BB Code',
      enqueue: 'Einstellen',
      openWindowTitle: 'Fenster öffnen',
      refreshTitle: 'Aktualisieren',
      feedbackTitle: 'Feedback',
      feedbackWindowTitle: 'Gold Jobs Feedback',
      feedbackDescription: 'Falls du auf Fehler gestossen bist oder Ideen hast, wie man das Script verbessern könnte, kannst du mich kontaktieren.',
      update: 'Update',
      updateAvailable: 'Für das Script ist eine neue Version erhältlich',
    },
    fr_FR: {
      language: 'French (français)',
      ApiGui: 'Avec ce script, tu peux voir une liste de tous les travaux argentés et dorés.<br>Comme ça il est très facile de trouve les travaux de bonus sur le Mini-map.',
      contact: 'Contact',
      jobName: 'Travail',
      distanceTime: 'Distance',
      showJob: 'Montre',
      title: 'Travaux argentés et dorés',
      loading: 'Chargement en cours...',
      exportButtonTitle: 'Exportation',
      generatedByBb: '[i][url=' + GoldJobs.website + ']Trouvé avec TW Gold Jobs Finder[/url][/i]',
      goback: 'De retour',
      bbCode: 'BB code',
      enqueue: 'Commencer',
      openWindowTitle: 'Ouvrir la fenêtre',
      refreshTitle: 'Rafraîchir',
      feedbackTitle: 'Contact',
      feedbackWindowTitle: 'Gold Jobs Contact',
      feedbackDescription: 'Si tu as trouvé un bug ou si tu as des idées pour améliorer le script, contactez-moi.',
      update: 'Mise à jour',
      updateAvailable: 'Une nouvelle version du script est disponible',
    },
    pt_BR: {
      language: 'Portuguese (português)',
      ApiGui: 'Este Script faz uma busca automãtica e em tempo real de todos os Trabalhos com Bônus Ouro ou Prata em todo o Mundo.',
      contact: 'Contato com Autor',
      jobName: 'Nome do Job',
      distanceTime: 'Distância',
      showJob: 'Show',
      title: 'Gold And Silver Jobs',
      loading: 'Procurando Jobs Ouro/Prata',
      exportButtonTitle: 'Exportar',
      generatedBy: 'Generated by TW Gold Jobs Finder',
      generatedByBb: '[i][url=' + GoldJobs.website + ']Generated by TW Gold Jobs Finder[/url][/i]',
      goback: 'Go back',
      bbCode: 'BB code',
      enqueue: 'Iniciar Job',
      openWindowTitle: 'Procurar Jobs',
      refreshTitle: 'Atualizar Lista',
      feedbackTitle: 'Suporte',
      feedbackWindowTitle: 'Suporte Gold Job 2015',
      feedbackDescription: 'Aqui vc encontra os meios de comunicação com o supporte do Script, pode reportar um erro, fazer uma crítica ou dar sugestões',
      update: 'Update',
      updateAvailable: 'A new version of the script is available',
    },
  };
  langs.pt_PT = langs.pt_BR;
  GJlang = langs.hasOwnProperty(Game.locale) ? langs[Game.locale] : langs.en_US;
  var GoldJobsApi = TheWestApi.register('GoldJobs', GoldJobs.name, GoldJobs.minGame, GoldJobs.maxGame, GoldJobs.author, GoldJobs.website);
  GoldJobsApi.setGui('<br><i>Language detected: </i>' + GJlang.language + '<br><br>' + GJlang.ApiGui + '<br><br><i>' + GoldJobs.name + ' v' + GoldJobs.version + '</i>');
  GoldJobs.parseWholeMap = function (tiles, onLoad) {
    this.loaded = 0;
    var x,
    y;
    var arr = [
    ];
    var currentBlock = 0;
    var currentBlockLength = 0;
    for (x in tiles) {
      for (y in tiles[x]) {
        if (isNaN(x) || isNaN(y)) {
          continue;
        }
        if (currentBlockLength === 0) {
          arr[currentBlock] = [
          ];
        }
        arr[currentBlock].push([parseInt(x),
        parseInt(y)]);
        if (++currentBlockLength == this.blockMaxLength) {
          currentBlock++;
          currentBlockLength = 0;
        }
      }
    }
    var i,
    to = arr.length;
    this.toLoad = to;
    for (i = 0; i < to; i++) {
      Map.Data.Loader.load(arr[i], function () {
        GoldJobs.loaded++;
        if (GoldJobs.loaded == GoldJobs.toLoad) {
          onLoad();
        }
      });
    }
  };
  GoldJobs.getJobIcon = function (jobId, x, y, shortname, gold) {
    var pos = {
      'x': x,
      'y': y
    };
    var t = gold ? 'gold' : 'silver';
    return '<div class="job" style="left: 0; top: 0; position: relative;"><div  onclick="javascript:Map.JobHandler.openJob(' + jobId + ',{x:' + x + ',y:' + y + '})" class="featured ' + t + '"></div>' + this.getGotoIcon(x, y) + '<img src="../images/jobs/' + shortname + '.png" class="job_icon"></div>';
  };
  GoldJobs.getGotoIcon = function (x, y) {
    return '<div class="centermap" onclick="javascript:Map.center(' + x + ',' + y + ');"style="position: absolute;background-image: url(\'../images/map/icons/instantwork.png\');width: 20px;height: 20px;top: 0;right: 3px;cursor: pointer;"></div>';
  };
  GoldJobs.getBestJobTime = function () {
    var list = JobList.getDurations();
    var maxTime = 0;
    for (var name in list) {
      if (list[name].requirement <= Character.level && list[name].duration > maxTime) {
        maxTime = list[name].duration;
      }
    }
    GoldJobs.bestJobTime = maxTime;
  };
  GoldJobs.getEnqueueButton = function (jobId, x, y) {
    var job = JobList.getJobById(jobId);
    var canDo = job.canDo();
    if (GoldJobs.bestJobTime === 0) {
      GoldJobs.getBestJobTime();
    }
    var duration = GoldJobs.bestJobTime;
    var b = this.gui.makeButton(GJlang.enqueue, function () {
      TaskQueue.add(new TaskJob(jobId, x, y, duration));
    });
    b.setWidth(100);
    if (!canDo) b.disable();
    return b.getMainDiv();
  };
  GoldJobs.addColumnsCss = function () {
    $('.goldenJobs .jobIcon').css('width', '60px');
    $('.goldenJobs .jobName').css('width', '140px');
    $('.goldenJobs .startJob').css('width', '100px');
    $('.goldenJobs .distanceTime').css('width', '60px');
    $('.goldenJobs .row').css('height', '56px');
    $('.goldenJobs .row').css('background', 'none');
    $('.goldenJobs .row_head .jobName').css('width', '135px');
    $('.goldenJobs .row_head .distanceTime').css('width', '95px');
    $('.goldenJobs .row_head .startJob').css('width', '0px');
    $('.goldenJobs .tfoot .jobIcon').css('width', '100%');
    $('.goldenJobs .tfoot').css('height', '35px');
    $('.goldenJobs').find('.tw2gui_scrollpane').css('height', '280px');
  };
  GoldJobs.calculateDistance = function (jobX, jobY) {
    var to = {
      x: jobX,
      y: jobY
    };
    return Map.calcWayTime(Character.position, to);
  };
  GoldJobs.addEventListener = function (event, callback) {
    if (EventHandler.hasOwnProperty('add')) {
      EventHandler.add(event, callback);
    } else {
      EventHandler.listen(event, callback);
    }
  };
  GoldJobs.openWindow = function () {
    var content = $('<div class=\'jobwindow\'/>');
    var table = this.makeJobsTable(this.preferences.jobName, this.preferences.showSilver, this.preferences.showGold, this.preferences.sortByName, this.preferences.sortByDistance);
    var win = wman.open('goldenJobs').setResizeable(true).setMinSize(450, 475).setSize(450, 475).setMiniTitle(GJlang.title);
    content.append(table.getMainDiv());
    win.appendToContentPane(content);
    this.addColumnsCss();
    this.addFilterEvent();
    this.addHeaderEvents();
    this.addEventListener('position_change', GoldJobs.refreshWindow);
  };
  GoldJobs.buildFooter = function (chosenJobName) {
    var footer = $('<div class="goldjobs_table_foot" style="margin-top: 3px"><span id="gj_job_search" style="position: relative; top: 0px; "/><span id="gj_share" style="position: absolute;top: 3px;right: 7px;"/></div>');
    var exportButton = this.gui.makeButton(GJlang.exportButtonTitle, function () {
      var jobName = $('#gj_job_search_textfield').val();
      var jobs = GoldJobs.jobsDataToString(jobName);
      GoldJobs.showExportWindow(jobs, false);
    }).setWidth(100);
    var textfield = this.gui.makeTextfield('gj_job_search_textfield').setSize(18).setWidth(137);
    var clearImage = $('<img/>', {
      src: '../images/chat/servicegrade_traitor.png',
      click: function () {
        $('#gj_job_search_textfield').val('');
        $('#gj_job_search_textfield').change();
      },
      css: {
        filter: 'grayscale(100%)',
        '-webkit-filter': 'grayscale(100%)',
        '-moz-filter': 'grayscale(100%)',
        '-o-filter': 'grayscale(100%)',
        position: 'absolute',
        top: '-1px',
        left: '130px'
      }
    });
    $('#gj_job_search', footer).append(textfield.getMainDiv());
    $('#gj_share', footer).append(exportButton.getMainDiv());
    $('#gj_job_search span.tw2gui_textfield span', footer).append('<span class=\'placeholder\' style=\'font-weight: lighter;color: #333;position: absolute;left: 12px; top: 1px;\'>' + GJlang.jobName + '</span>');
    var placeholder = $('#gj_job_search .placeholder', footer);
    placeholder.after(clearImage);
    placeholder.click(function () {
      $('#gj_job_search_textfield', footer).focus();
    });
    $('#gj_job_search_textfield', footer).focus(function () {
      placeholder.hide();
    });
    $('#gj_job_search_textfield', footer).focusout(function () {
      if ($('#gj_job_search_textfield').val() == '') {
        placeholder.show();
      }
    });
    if (chosenJobName !== undefined && chosenJobName !== '') {
      $('#gj_job_search_textfield', footer).val(chosenJobName);
      $('#gj_job_search_textfield', footer).focus();
    }
    return footer;
  };
  GoldJobs.getJobIconHeaderCell = function (showGold, showSilver) {
    var hiddenImageOpacity = this.hiddenImageOpacity;
    var shownImageOpacity = this.shownImageOpacity;
    return '<img src="../images/jobs/featured/goldjob.png" style="width: 15px; opacity: ' + (showGold ? shownImageOpacity : hiddenImageOpacity) + '; " onclick="javascript:GoldJobs.onJobIconFilterClick(&quot;gold&quot;, $(this))">+\t\t\t\t<img src="../images/jobs/featured/silverjob.png" style="width: 15px; opacity: ' + (showSilver ? shownImageOpacity : hiddenImageOpacity) + '; " onclick="javascript:GoldJobs.onJobIconFilterClick(&quot;silver&quot;, $(this))">';
  };
  GoldJobs.onJobIconFilterClick = function (type, element) {
    var hiddenImageOpacity = this.hiddenImageOpacity;
    var shownImageOpacity = this.shownImageOpacity;
    var disabled = ($(element).css('opacity') != shownImageOpacity);
    if (type == 'gold') {
      this.preferences.showGold = disabled;
    } else {
      this.preferences.showSilver = disabled;
    }
    $(element).css('opacity', (disabled ? hiddenImageOpacity : shownImageOpacity));
    this.refreshWindow();
  };
  GoldJobs.getAllTiles = function (callback) {
    Ajax.get('map', 'get_minimap', {
    }, function (r) {
      if (r.error) {
        console.log(r.error);
        return;
      }
      var result = [
      ];
      var jobGroups = r.job_groups,
      i,
      j;
      for (i in jobGroups) {
        for (j in jobGroups[i]) {
          var coords = jobGroups[i][j];
          var xTile = Math.floor(coords[0] / Map.tileSize);
          var yTile = Math.floor(coords[1] / Map.tileSize);
          if (!result.hasOwnProperty(xTile)) {
            result[xTile] = {
            };
          }
          result[xTile][yTile] = 1;
        }
      }
      GoldJobs.tilesWithJobs = result;
      callback();
    });
  };
  GoldJobs.getFilteredData = function (chosenJobName, showSilver, showGold, sortByName, sortByDistance) {
    chosenJobName = chosenJobName.toLowerCase();
    var jobs = Map.JobHandler.Featured;
    var k,
    jobId,
    job,
    t,
    j;
    var result = [
    ];
    for (k in jobs) {
      var jobPlace = jobs[k];
      for (jobId in jobPlace) {
        job = JobList.getJobById(jobId);
        j = jobPlace[jobId];
        if ((j.silver && !showSilver) || (j.gold && !showGold)) {
          continue;
        }
        if (chosenJobName !== '' && job.name.toLowerCase().indexOf(chosenJobName) < 0) {
          continue;
        }
        result.push({
          jobId: jobId,
          x: j.x,
          y: j.y,
          name: job.name,
          shortname: job.shortname,
          gold: j.gold,
          distance: this.calculateDistance(j.x, j.y)
        });
      }
    }
    var nameSortFunctionReversed = function (o1, o2) {
      var t1 = o1.name.toUpperCase();
      var t2 = o2.name.toUpperCase();
      return (t1 > t2) ? - 1 : (t1 < t2) ? 1 : 0;
    };
    var distanceSortFunctionReversed = function (o1, o2) {
      var t1 = parseInt(o1.distance);
      var t2 = parseInt(o2.distance);
      return (t1 > t2) ? - 1 : (t1 < t2) ? 1 : 0;
    };
    var nameSortFunction = function (o1, o2) {
      var t1 = o1.name.toUpperCase();
      var t2 = o2.name.toUpperCase();
      return (t1 < t2) ? - 1 : (t1 > t2) ? 1 : 0;
    };
    var distanceSortFunction = function (o1, o2) {
      var t1 = o1.distance;
      var t2 = o2.distance;
      return (t1 < t2) ? - 1 : (t1 > t2) ? 1 : 0;
    };
    if (sortByName !== 0) {
      if (sortByName == 1) {
        result.sort(nameSortFunction);
      } else {
        result.sort(nameSortFunctionReversed);
      }
    } else if (sortByDistance !== 0) {
      if (sortByDistance == 1) {
        result.sort(distanceSortFunction);
      } else {
        result.sort(distanceSortFunctionReversed);
      }
    }
    return result;
  };
  GoldJobs.makeJobsTable = function (chosenJobName, showSilver, showGold, sortByName, sortByDistance) {
    chosenJobName = chosenJobName || '';
    var arrow_desc = '&nbsp;<img src="../images/window/jobs/sortarrow_desc.png"/>';
    var arrow_asc = '&nbsp;<img src="../images/window/jobs/sortarrow_asc.png"/>';
    var footer = this.buildFooter(chosenJobName);
    var table = this.gui.makeTable();
    var data = this.getFilteredData(chosenJobName, showSilver, showGold, sortByName, sortByDistance);
    var k,
    j;
    table.addColumn('jobIcon', 'jobIcon').addColumn('jobName', 'jobName').addColumn('distanceTime', 'distanceTime').addColumn('startJob', 'startJob').appendToCell('head', 'jobIcon', this.getJobIconHeaderCell(showGold, showSilver)).appendToCell('head', 'jobName', GJlang.jobName + (sortByName == 1 ? arrow_asc : sortByName == - 1 ? arrow_desc : '')).appendToCell('head', 'distanceTime', GJlang.distanceTime + (sortByDistance == 1 ? arrow_asc : sortByDistance == - 1 ? arrow_desc : '')).appendToCell('head', 'startJob', '');
    $.each(data, function (k, j) {
      table.appendRow().appendToCell( - 1, 'jobIcon', GoldJobs.getJobIcon(j.jobId, j.x, j.y, j.shortname, j.gold)).appendToCell( - 1, 'jobName', j.name).appendToCell( - 1, 'distanceTime', j.distance.formatDuration()).appendToCell( - 1, 'startJob', GoldJobs.getEnqueueButton(j.jobId, j.x, j.y));
    });
    table.appendToFooter('jobIcon', footer);
    return table;
  };
  GoldJobs.refreshWindow = function () {
    GoldJobs.preferences.jobName = $('#gj_job_search_textfield').val();
    var newTable = GoldJobs.makeJobsTable(GoldJobs.preferences.jobName, GoldJobs.preferences.showSilver, GoldJobs.preferences.showGold, GoldJobs.preferences.sortByName, GoldJobs.preferences.sortByDistance);
    $('.goldenJobs .fancytable').remove();
    $('.jobwindow').prepend(newTable.getMainDiv());
    GoldJobs.addColumnsCss();
    GoldJobs.addFilterEvent();
    GoldJobs.addHeaderEvents();
    $('#gj_job_search_textfield').focus();
    var val = $('#gj_job_search_textfield').val();
    $('#gj_job_search_textfield').val('');
    $('#gj_job_search_textfield').val(val);
  };
  GoldJobs.addFilterEvent = function () {
    var f = function () {
      if (GoldJobs.filterTimeout !== undefined) {
        clearTimeout(GoldJobs.filterTimeout);
      }
      GoldJobs.filterTimeout = setTimeout(function () {
        GoldJobs.refreshWindow();
      }, 500);
    };
    $('#gj_job_search_textfield').keypress(f);
    $('#gj_job_search_textfield').change(f);
  };
  GoldJobs.addHeaderEvents = function () {
    $('.goldenJobs .row_head .jobName').click(function () {
      GoldJobs.preferences.sortByName = GoldJobs.preferences.sortByName == 1 ? - 1 : 1;
      GoldJobs.preferences.sortByDistance = 0;
      GoldJobs.refreshWindow();
    });
    $('.goldenJobs .row_head .distanceTime').click(function () {
      GoldJobs.preferences.sortByName = 0;
      GoldJobs.preferences.sortByDistance = GoldJobs.preferences.sortByDistance == 1 ? - 1 : 1;
      GoldJobs.refreshWindow();
    });
  };
  GoldJobs.getMessageDialog = function (text, type, title) {
    title = title || '';
    if (type == 'warning') {
      type = west.gui.Dialog.SYS_WARNING;
    }
    if (type == 'question') {
      type = west.gui.Dialog.SYS_QUESTION;
    }
    return new west.gui.Dialog(text, title, type);
  };
  GoldJobs.getSelectBox = function () {
    var onLoad = function () {
      GoldJobs.openWindow();
      GoldJobs.dataLoaded = true;
    };
    var listener = function (k) {
      switch (k) {
        case 'feedback':
          GoldJobs.openFeedbackWindow();
          break;
        case 'open':
          if (!GoldJobs.hasOwnProperty('tilesWithJobs')) {
            new UserMessage(GJlang.loading, UserMessage.TYPE_HINT).show();
            GoldJobs.getAllTiles(function () {
              GoldJobs.parseWholeMap(GoldJobs.tilesWithJobs, onLoad);
            });
          } else {
            onLoad();
          }
          break;
        case 'refresh':
          new UserMessage(GJlang.loading, UserMessage.TYPE_HINT).show();
          if (!GoldJobs.hasOwnProperty('tilesWithJobs')) {
            GoldJobs.getAllTiles(function () {
              GoldJobs.parseWholeMap(GoldJobs.tilesWithJobs, onLoad);
            });
          } else {
            GoldJobs.parseWholeMap(GoldJobs.tilesWithJobs, onLoad);
          }
          break;
      }
    };
    this.selectBox = this.gui.makeSelectbox().setWidth(150).addListener(listener).addItem('open', GJlang.openWindowTitle).addItem('refresh', GJlang.refreshTitle).addItem('feedback', GJlang.feedbackTitle);
    return this.selectBox;
  };
  GoldJobs.toggleSelectbox = function () {
    var wrapPosition = GoldJobs.selectBox.divWrap.position();
    var isShown = (wrapPosition.left !== 0 && wrapPosition.top !== 0);
    if (isShown) {
      GoldJobs.selectBox.hide();
    } else {
      GoldJobs.selectBox.show();
    }
  };
  GoldJobs.init = function () {
    var menuimage = 'data:image/png;base64,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';
    var selectbox = this.getSelectBox();
    var div = $('<div class="ui_menucontainer" />');
    var link = $('<div id="GoldJobsmenu" class="menulink" onclick="GoldJobs.toggleSelectbox();" title="' + GoldJobs.name + '" />').css('background-image', 'url(' + menuimage + ')').css('background-position', '0px 0px').mouseenter(function () {
      $(this).css('background-position', '-25px 0px');
    }).mouseleave(function () {
      $(this).css('background-position', '0px 0px');
    });
    $('#ui_menubar').append((div).append(link).append('<div class="menucontainer_bottom" />'));
    this.setSelectboxPosition(div);
  };
  GoldJobs.setSelectboxPosition = function (nextTo) {
    var p = $(nextTo).offset();
    p.left -= GoldJobs.selectBox.divMain.width() + 150 + 15;
    GoldJobs.selectBox.divWrap.offset(p);
    GoldJobs.selectBox.divWrap.css('position', 'absolute');
  };
  GoldJobs.jobsDataToString = function (chosenJobName) {
    chosenJobName = chosenJobName.toLowerCase();
    var str = '';
    var jobs = Map.JobHandler.Featured;
    var k,
    jobId,
    job,
    t,
    j;
    for (k in jobs) {
      var jobPlace = jobs[k];
      for (jobId in jobPlace) {
        job = JobList.getJobById(jobId);
        if (chosenJobName !== '' && job.name.toLowerCase().indexOf(chosenJobName) < 0) continue;
        j = jobPlace[jobId];
        t = j.gold ? 'gold' : 'silver';
        str += job.name + '; ' + t + '; ' + j.x + '-' + j.y + '; ' + jobId + '\n';
      }
    }
    return str;
  };
  GoldJobs.jobsDataToBbString = function (chosenJobName) {
    chosenJobName = chosenJobName.toLowerCase();
    var str = '';
    var jobs = Map.JobHandler.Featured;
    var k,
    jobId,
    job,
    color,
    j;
    for (k in jobs) {
      var jobPlace = jobs[k];
      for (jobId in jobPlace) {
        job = JobList.getJobById(jobId);
        if (chosenJobName !== '' && job.name.toLowerCase().indexOf(chosenJobName) < 0) continue;
        j = jobPlace[jobId];
        color = j.gold ? GoldJobs.goldJobBbColor : GoldJobs.silverJobBbColor;
        str += '[img]https://www.the-west.ru/images/jobs/' + job.shortname + '.png[/img][b][color=' + color + ']' + job.name + '[/color][/b] (' + j.x + '; ' + j.y + ')' + '\n';
      }
    }
    return str;
  };
  GoldJobs.showExportWindow = function (jobs, isBb) {
    var textarea = '<textarea style="height: 100px; width: 400px; background-color: transparent; border-width: 0px;" onclick="$(this).select()">' + jobs + '</textarea>';
    var md = GoldJobs.getMessageDialog(GJlang.exportButtonTitle, '', textarea);
    var jobName = $('#gj_job_search_textfield').val();
    if (isBb) {
      md.addButton(GJlang.goback, function () {
        var jobs = GoldJobs.jobsDataToString(jobName);
        GoldJobs.showExportWindow(jobs, false);
      });
    } else {
      md.addButton(GJlang.bbCode, function () {
        var jobs = GoldJobs.jobsDataToBbString(jobName);
        GoldJobs.showExportWindow(jobs + GJlang.generatedByBb, true);
      });
    }
    md.addButton('ok').show();
  };
  GoldJobs.openFeedbackWindow = function () {
    var content = $('<div id=\'feedback_window_div\'/>');
    var win = wman.open('goldenJobsFeedback').setSize(550, 350).setMiniTitle(GJlang.feedbackWindowTitle).setTitle(GJlang.feedbackWindowTitle);
    content.append('<br>' + GJlang.feedbackDescription + '<br><br><br><b>' + GJlang.contact +
    ':</b><ul style="margin-left:15px;"><li>Send a message to <a target=\'_blanck\' href="http://om.the-west.de/west/de/player/?ref=west_invite_linkrl&player_id=647936&world_id=13&hash=7dda">Tom Robert on German world Arizona</a></li>' +
    '<li>Contact me on <a target=\'_blanck\' href="http://greasyfork.icu/forum/messages/add/Tom Robert">Greasy Fork</a></li>' +
    '<li>Message me on one of these The West Forum:<br>/ <a target=\'_blanck\' href="https://forum.the-west.de/private.php?do=newpm&u=24502">deutsches Forum</a> / ' +
    '<a target=\'_blanck\' href="https://forum.the-west.net/private.php?do=newpm&u=37219">English forum</a> / <a target=\'_blanck\' href="https://forum.the-west.pl/private.php?do=newpm&u=32083">forum polski</a> / ' +
    '<a target=\'_blanck\' href="https://forum.the-west.es/private.php?do=newpm&u=13770">foro español</a> /<br>/ <a target=\'_blanck\' href="https://forum.the-west.ru/private.php?do=newpm&u=27430">Русский форум</a> / ' +
    '<a target=\'_blanck\' href="https://forum.the-west.fr/private.php?do=newpm&u=17783">forum français</a> / <a target=\'_blanck\' href="https://forum.the-west.it/private.php?do=newpm&u=14287">forum italiano</a> / ' +
    '<a target=\'_blanck\' href="https://forum.beta.the-west.net/private.php?do=newpm&u=4072">beta forum</a> /<br>I will get an e-mail when you sent me the message <img src="../images/chat/emoticons/smile.png"></li></ul>');
    win.appendToContentPane(content);
  };
  GoldJobs.addNotification = function (title, jobId, jobX, jobY) {
    var n = new OnGoingEntry();
    n.init('', function () {
      Map.JobHandler.openJob(jobId, {
        x: jobX,
        y: jobY
      });
    }, 1);
    n.setTooltip('<b>' + title + '</b>', true);
    WestUi.NotiBar.add(n);
    var icon = JobList.getJobById(jobId).shortname;
    $(n.getMainDiv()).find('.image').css({
      'background-image': 'url(../images/jobs/' + icon + '.png)',
      'background-position': '-11px -9px'
    });
  };
  GoldJobs.gui = {
  };
  GoldJobs.gui.init = function () {
    GoldJobs.gui.makeButton = function (caption, callback) {
      return new west.gui.Button(caption, callback);
    };
    GoldJobs.gui.makeTextfield = function (id) {
      return new west.gui.Textfield(id);
    };
    GoldJobs.gui.makeTable = function () {
      return new west.gui.Table();
    };
    GoldJobs.gui.makeSelectbox = function () {
      return new west.gui.Selectbox();
    };
  };
  GoldJobs.Updater = function () {
    $.getScript(GoldJobs.updateUrl, function () {
      if (scriptUpdate.GoldJobs > GoldJobs.version) {
        var updateMessage = new west.gui.Dialog(GJlang.update + ': ' + GoldJobs.name, GJlang.updateAvailable + ': v' + scriptUpdate.GoldJobs, west.gui.Dialog.SYS_WARNING).addButton(GJlang.update, function () {
          updateMessage.hide();
          window.open(GoldJobs.updateAd);
        }).addButton(GJlang.update + ' [NoAds]', function () {
          updateMessage.hide();
          location.href = GoldJobs.website + '/code.user.js';
        }).addButton('cancel').show();
      }
    });
  };
  $(document).ready(function () {
    try {
      GoldJobs.gui.init();
      GoldJobs.init();
      setTimeout(GoldJobs.Updater, 6000);
    } catch (e) {
      console.log(e.stack);
    }
  });
});