Difference between revisions of "MediaWiki:ImageMapEditor.js"

From KIproBatt Wiki
(import form testwiki.kiprobatt.de)
 
(update from testwiki)
 
Line 14: Line 14:
 
if (mw.config === undefined) mw.config = {};
 
if (mw.config === undefined) mw.config = {};
 
if (mw.config.get === undefined) {
 
if (mw.config.get === undefined) {
mw.config.get = function(key) {
+
    mw.config.get = function(key) {
this[key];
+
        this[key];
};
+
    };
 
}
 
}
 
if (mw.loader === undefined) mw.loader = {};
 
if (mw.loader === undefined) mw.loader = {};
 
if (mw.loader.load === undefined) mw.loader.load = importScriptURI;
 
if (mw.loader.load === undefined) mw.loader.load = importScriptURI;
 
 
/*
 
Constants
 
*/
 
 
var IME_BASE = '//imagemapedit.toolforge.org/';
 
 
var IME_TEMPLATE = IME_BASE + 'template.php';
 
var IME_TRANSLATIONS = IME_BASE + 'translations.php?lang=' + mw.config.get('wgUserLanguage');
 
 
// Scripts to create the circle and polygon images
 
var IME_CIRCLESCRIPT = IME_BASE + 'circle.php';
 
var IME_POLYSCRIPT = IME_BASE + 'poly.php';
 
  
 
/*
 
/*
Line 55: Line 41:
 
Start Initialization if this is an image page and there actually is an image
 
Start Initialization if this is an image page and there actually is an image
 
*/
 
*/
$(document).ready(function(){
+
$(document).ready(function() {
// Determine whether we are on an image page. Namespace must be 6 and action view
+
    // Determine whether we are on an image page. Namespace must be 6 and action view
if (mw.config.get('wgNamespaceNumber')==6 && mw.config.get('wgAction')=='view') {
+
    if (mw.config.get('wgNamespaceNumber') == 6 && mw.config.get('wgAction') == 'view') {
// If we can a div with id file, we initialize
+
 
if (document.getElementById('file')) {
+
        // If we can a div with id file, we initialize
mw.loader.load(IME_TEMPLATE);
+
        if (document.getElementById('file')) {
mw.loader.load(IME_TRANSLATIONS);
+
            $.getScript('//code.jquery.com/ui/1.12.1/jquery-ui.js').done(function() {
ime_init1();
+
                if (mw.config.get('wgUserLanguage') === 'de') {
}
+
                    ime_translations = {
}
+
                        'error_imagenotfound': 'ImageMapEdit: Konnte Bild in der Seitenstruktur nicht finden.',
 +
                        'bottomleft': 'Links unten',
 +
                        'bottomright': 'Rechts unten',
 +
                        'circle': 'circle (Kreis)',
 +
                        'circlechoose1': 'Auswahl mit linker Maustaste',
 +
                        'circlechoose2': 'Auswahl mit rechter Maustaste',
 +
                        'coordinates': 'Koordinaten',
 +
                        'default': 'Standard',
 +
                        'deletearea': 'Ausgewählten Bereich löschen',
 +
                        'deletecoordinates': 'Alle Koordinaten löschen',
 +
                        'editarea': 'Bereich bearbeiten',
 +
                        'generatedwikicode': 'Erstellter Wikicode',
 +
                        'hidetextbox': 'Eingabefeld verstecken',
 +
                        'hidewikicode': 'Wikicode verstecken',
 +
                        'imagedescription': 'Bildbeschreibung',
 +
                        'import': 'Importieren',
 +
                        'importareas': 'Bereiche aus Wikicode importieren',
 +
                        'infolinkposition': 'Position des Info-Links',
 +
                        'linktarget': 'Linkziel',
 +
                        'linktitle': 'Linktitel',
 +
                        'newarea': 'Neuen Bereich erstellen',
 +
                        'nolink': 'Kein Link',
 +
                        'optional': 'optional',
 +
                        'poly': 'poly (Polygon)',
 +
                        'polychoose': 'Hinzufügen neuer Punkte mit linker Maustaste',
 +
                        'position': 'Position',
 +
                        'preferences': 'Allgemeine Einstellungen',
 +
                        'radius': 'Radius',
 +
                        'rect': 'rect (Rechteck)',
 +
                        'rectbottom': 'unten',
 +
                        'rectchoose1': 'Auswahl mit linker Maustaste',
 +
                        'rectchoose2': 'Auswahl mit rechter Maustaste',
 +
                        'rectleft': 'Links',
 +
                        'rectright': 'Rechts',
 +
                        'recttop': 'oben',
 +
                        'showtextbox': 'Eingabefeld anzeigen',
 +
                        'showwikicode': 'Wikicode anzeigen',
 +
                        'topleft': 'Links oben',
 +
                        'topright': 'Rechts oben'
 +
                    };
 +
 
 +
                }
 +
 
 +
                ime_init1();
 +
            });
 +
        }
 +
    }
 
});
 
});
  
Line 71: Line 103:
 
*/
 
*/
 
function ime_htmlNewDiv(id) {
 
function ime_htmlNewDiv(id) {
var div = document.createElement('div');
+
    var div = document.createElement('div');
if (id) div.id = id;
+
    if (id) div.id = id;
return div;
+
    return div;
 
}
 
}
  
Line 83: Line 115:
 
*/
 
*/
 
function ime_init1() {
 
function ime_init1() {
var divFile = document.getElementById('file');
+
    var divFile = document.getElementById('file');
if (!divFile) {
+
    if (!divFile) {
ime_error(ime_translations['error_imagenotfound'] + ' (ime_init1,divFile=null)');
+
        ime_error(ime_translations['error_imagenotfound'] + ' (ime_init1,divFile=null)');
return;
+
        return;
}
+
    }
  
var a = ime_findATag(divFile);
+
    var a = ime_findATag(divFile);
if (!a) {
+
    if (!a) {
ime_error(ime_translations['error_imagenotfound'] + ' (ime_init1,a=null)');
+
        ime_error(ime_translations['error_imagenotfound'] + ' (ime_init1,a=null)');
return;
+
        return;
}
+
    }
  
var img = a.firstChild;
+
    var img = a.firstChild;
if (!img) {
+
    if (!img) {
ime_error(ime_translations['error_imagenotfound'] + ' (ime_init1,img=null)');
+
        ime_error(ime_translations['error_imagenotfound'] + ' (ime_init1,img=null)');
return;
+
        return;
}
+
    }
  
var url = mw.config.get('wgScriptPath') + '/api.php?format=json&action=query&prop=imageinfo&iiprop=size&titles=' + mw.config.get('wgPageName');
+
    var url = mw.config.get('wgScriptPath') + '/api.php?format=json&action=query&prop=imageinfo&iiprop=size&titles=' + mw.config.get('wgPageName');
  
$.get(url, function(data) {
+
    $.get(url, function(data) {
if( typeof data.query.pages != "undefined" ) {
+
        if (typeof data.query.pages != "undefined") {
        imageProperties = data.query.pages[Object.keys(data.query.pages)[0]];
+
            imageProperties = data.query.pages[Object.keys(data.query.pages)[0]];
ime_width = imageProperties.imageinfo[0].width;
+
            ime_width = imageProperties.imageinfo[0].width;
ime_height = imageProperties.imageinfo[0].height;
+
            ime_height = imageProperties.imageinfo[0].height;
  
ime_scale = img.width/ime_width;
+
            ime_scale = img.width / ime_width;
  
// Show 'show ImageMapEdit' button now
+
            // Show 'show ImageMapEdit' button now
var a = document.createElement('a');
+
            var a = document.createElement('a');
a.id = 'imeLink';
+
            a.id = 'imeLink';
a.href = 'javascript:ime_init2()';
+
            a.href = 'javascript:ime_init2()';
a.style.display = 'block';
+
            a.style.display = 'block';
a.appendChild(document.createTextNode('ImageMapEdit >'));
+
            a.appendChild(document.createTextNode('ImageMapEdit >'));
document.getElementById('file').appendChild(a);
+
            document.getElementById('file').appendChild(a);
}
+
        }
});
+
    });
 
}
 
}
  
Line 129: Line 161:
 
function ime_init2() {
 
function ime_init2() {
  
// Remove UI that might interfere with this code
+
    // Remove UI that might interfere with this code
ime_removeOtherUIElements();
+
    ime_removeOtherUIElements();
  
var divFile = document.getElementById('file');
+
    var divFile = document.getElementById('file');
var tempNode = divFile.firstChild;
+
    var tempNode = divFile.firstChild;
var a = ime_findATag(tempNode);
+
    var a = ime_findATag(tempNode);
var img = a.firstChild;
+
    var img = a.firstChild;
  
var divImeContainer = ime_htmlNewDiv('imeContainer');
+
    var divImeContainer = ime_htmlNewDiv('imeContainer');
divImeContainer.style.position = 'relative';
+
    divImeContainer.style.position = 'relative';
  
// Move image from within link to outside
+
    // Move image from within link to outside
a.removeChild(img);
+
    a.removeChild(img);
divFile.insertBefore(divImeContainer,tempNode);
+
    divFile.insertBefore(divImeContainer, tempNode);
divFile.removeChild(tempNode);
+
    divFile.removeChild(tempNode);
// Fix for rtl wikis, thanks to hewiki user "קיפודנחש"
+
    // Fix for rtl wikis, thanks to hewiki user "קיפודנחש"
divFile.style.direction = 'ltr';
+
    divFile.style.direction = 'ltr';
  
img.id = 'imeImg';
+
    img.id = 'imeImg';
img.style.zIndex = 99;
+
    img.style.zIndex = 99;
img.style.border = 'none';
+
    img.style.border = 'none';
img.style.opacity = '0.75';
+
    img.style.opacity = '0.75';
img.style.filter = 'alpha(opacity=75)'; // IE
+
    img.style.filter = 'alpha(opacity=75)'; // IE
  
// Internet Explorer needs this differently
+
    // Internet Explorer needs this differently
if (typeof(navigator.userAgent) != 'undefined' && navigator.userAgent.match('/MSIE/')) {
+
    if (typeof(navigator.userAgent) != 'undefined' && navigator.userAgent.match('/MSIE/')) {
divImeContainer.style.overflow = 'none';
+
        divImeContainer.style.overflow = 'none';
}
+
    } else {
else {
+
        divImeContainer.style.overflow = 'auto';
divImeContainer.style.overflow = 'auto';
+
    }
}
 
  
var divImePreview = ime_htmlNewDiv('imePreview');
+
    var divImePreview = ime_htmlNewDiv('imePreview');
divImePreview.style.position = 'absolute';
+
    divImePreview.style.position = 'absolute';
divImePreview.style.top = '0';
+
    divImePreview.style.top = '0';
divImePreview.style.left = '0';
+
    divImePreview.style.left = '0';
divImePreview.style.width = img.width + 'px';
+
    divImePreview.style.width = img.width + 'px';
divImePreview.style.height = img.height + 'px';
+
    divImePreview.style.height = img.height + 'px';
divImePreview.zIndex = 0;
+
    divImePreview.zIndex = 0;
  
divImeContainer.appendChild(divImePreview);
+
    divImeContainer.appendChild(divImePreview);
divImeContainer.appendChild(img);
+
    divImeContainer.appendChild(img);
  
var divIme = ime_htmlNewDiv('ime');
+
    var divIme = ime_htmlNewDiv('ime');
divFile.appendChild(divIme);
+
    divFile.appendChild(divIme);
  
// Hide the link now
+
    // Hide the link now
document.getElementById('imeLink').style.display = 'none';
+
    document.getElementById('imeLink').style.display = 'none';
  
// Disable image context menu so right click can be used for events
+
    // Disable image context menu so right click can be used for events
img.oncontextmenu = ime_eventDummy;
+
    img.oncontextmenu = ime_eventDummy;
  
  
divIme.innerHTML = ime_templateHtml;
+
    divIme.innerHTML = ime_templateHtml;
  
// Translate texts
+
    // Translate texts
ime_translate();
+
    ime_hideResult();
//A button gets created. On click, it gets the input from the #imeResult ID and posts it on the '/ImageMap' page.  
+
    ime_translate();
//After posting, it forwards the user to the '/ImageMap' page.
+
    //A button gets created. On click, it gets the input from the #imeResult ID and posts it on the '/ImageMap' page.  
var clicked = false;
+
    //After posting, it forwards the user to the '/ImageMap' page.
var btn = document.createElement("button");
+
    var clicked = false;
btn.innerHTML = "Speichern";
+
    var btn = document.createElement("button");
btn.onclick = function () {
+
    btn.innerHTML = "Speichern";
    if ($('#imeResult').length) {
+
    btn.onclick = function() {
    clicked = false;
+
        if ($('#imeResult').length) {
    var rep = $('#imeResult').html();
+
            clicked = false;
    var rep1 = rep.replaceAll("<br>","\n");
+
            var rep = $('#imeResult').html();
    var rep2 = rep1.replaceAll("&lt;","<");
+
            var rep1 = rep.replaceAll("<br>", "\n");
    var rep3 = rep2.replaceAll("&gt;",">");
+
            var rep2 = rep1.replaceAll("&lt;", "<");
    var finalstr = '{{ImageMap |map='+rep3+' }}'
+
            var rep3 = rep2.replaceAll("&gt;", ">");
    var params = {
+
            var finalstr = '{{ImageMap |map=' + rep3 + ' }}'
action: 'edit',
+
            var params = {
title: $('#firstHeading').text()+'/ImageMap',
+
                    action: 'edit',
text: finalstr,
+
                    title: $('#firstHeading').text() + '/ImageMap',
format: 'json'
+
                    text: finalstr,
},
+
                    format: 'json'
api = new mw.Api();
+
                },
 +
                api = new mw.Api();
  
api.postWithToken( 'csrf', params ).done( function ( data ) {
+
            api.postWithToken('csrf', params).done(function(data) {
window.location.replace("/wiki/" + $('#firstHeading').text() + "/ImageMap");
+
                window.location.replace("/wiki/" + $('#firstHeading').text() + "/ImageMap");
});
+
            });
}
+
        }
};
+
    };
document.getElementById("file").appendChild(btn);
+
    document.getElementById("file").appendChild(btn);
  
//A button gets created.  
+
    //A button gets created.  
var but = document.createElement("button");
+
    var but = document.createElement("button");
but.innerHTML = "Laden";
+
    but.innerHTML = "Laden";
but.onclick = function () {
+
    but.onclick = function() {
if(!clicked){    
+
        if (!clicked) {
//Gets the wiki text from the '/ImageMap' page  and imports it.
+
            //Gets the wiki text from the '/ImageMap' page  and imports it.
  
$.getJSON("/w/api.php?action=query&prop=revisions&titles="+$('#firstHeading').text()+"%2FImageMap&rvprop=content&formatversion=2&format=json", async function(data) {
+
            $.getJSON("/w/api.php?action=query&prop=revisions&titles=" + $('#firstHeading').text() + "%2FImageMap&rvprop=content&formatversion=2&format=json", function(data) {
var daten = await data;
+
                var daten = data;
if(daten.query.pages[0].hasOwnProperty("missing")){
+
                if (daten.query.pages[0].hasOwnProperty("missing")) {
if(daten.query.pages[0].missing === true){
+
                    if (daten.query.pages[0].missing === true) {
return;
+
                        return;
}
+
                    }
}
+
                }
var aus = daten.query.pages[0].revisions[0].content;
+
                var aus = daten.query.pages[0].revisions[0].content;
$('textarea[name="importText"]').html(aus);
+
                $('textarea[name="importText"]').html(aus);
ime_importLines();
+
                ime_importLines();
var clear = "";
+
                var clear = "";
$('textarea[name="importText"]').html(clear);
+
                $('textarea[name="importText"]').html(clear);
}).fail(function() {
+
            }).fail(function() {
    return;
+
                return;
});
+
            });
  
//Gets the image width and the image position from the '/ImageMap' page and updates the created ImageMap code.
+
            //Gets the image width and the image position from the '/ImageMap' page and updates the created ImageMap code.
  
$.get("/wiki/" + $('#firstHeading').text() + "/ImageMap", function(data){
+
            $.getJSON("/w/api.php?action=query&prop=revisions&titles=" + $('#firstHeading').text() + "%2FImageMap&rvprop=content&formatversion=2&format=json", function(data) {
var size = $(data).find("img[usemap^='#ImageMap_']");
+
                var data1 = data;
var imgWidth = size.attr("width");
+
                if (data1.query.pages[0].hasOwnProperty("missing")) {
  if($(data).find("div.center").length){
+
                    if (data1.query.pages[0].missing === true) {
$('input#ime_imageDescription').val(imgWidth+'px'+'|zentriert');
+
                        return;
ime_updateResult();
+
                    }
}else if($(data).find("div.floatleft").length){
+
                }
$('input#ime_imageDescription').val(imgWidth+'px'+'|links');
+
                var out = data1.query.pages[0].revisions[0].content;
ime_updateResult();
+
                var patt = /(?<=<imagemap>\n).*/;
}else if($(data).find("div.floatright").length){
+
                var string = out.match(patt) + '';
$('input#ime_imageDescription').val(imgWidth+'px'+'|rechts');
+
                var stringSplit = string.split('|');
ime_updateResult();
+
                var stringJoin = [stringSplit.shift(), stringSplit.join('|')]
}else{if(size.lenght){
+
                $('input#ime_imageDescription').val(stringJoin[1]);
$('input#ime_imageDescription').val(imgWidth+'px');
+
                ime_updateResult();
ime_updateResult();
+
            }).fail(function() {
}
+
                return;
}
+
            });
}).fail(function() {
+
            clicked = true;
    return;
+
        }
});
+
    };
clicked = true;
 
}
 
};
 
  
  
document.getElementById("file").appendChild(but);
+
    document.getElementById("file").appendChild(but);
  
  
Line 275: Line 304:
 
*/
 
*/
 
function ime_translate() {
 
function ime_translate() {
if (ime_translations) {
+
    if (ime_translations) {
for (var i in ime_translations) {
+
        for (var i in ime_translations) {
var elements = ime_getElementsByClassName('ime_t_' + i);
+
            var elements = ime_getElementsByClassName('ime_t_' + i);
if (elements.length > 0) {
+
            if (elements.length > 0) {
var text = ime_translations[i];;
+
                var text = ime_translations[i];;
for (var j=0; j<elements.length; j++) {
+
                for (var j = 0; j < elements.length; j++) {
elements[j].innerHTML = text;
+
                    elements[j].innerHTML = text;
}
+
                }
}
+
            }
}
+
        }
}
+
    }
 
}
 
}
  
Line 292: Line 321:
 
*/
 
*/
 
function ime_getElementsByClassName(className) {
 
function ime_getElementsByClassName(className) {
// Hopefully the browser supports this natively
+
    // Hopefully the browser supports this natively
if (document.getElementsByClassName) {
+
    if (document.getElementsByClassName) {
return document.getElementsByClassName(className);
+
        return document.getElementsByClassName(className);
}
+
    }
  
// Otherwise use the function defined by MediaWiki
+
    // Otherwise use the function defined by MediaWiki
return getElementsByClassName(document,'*',className)
+
    return getElementsByClassName(document, '*', className)
 
}
 
}
  
Line 306: Line 335:
 
*/
 
*/
 
function ime_error(message) {
 
function ime_error(message) {
var jqFile = $('#file');
+
    var jqFile = $('#file');
var jqIme = $('#ime');
+
    var jqIme = $('#ime');
  
if (jqFile.length !== 0) {
+
    if (jqFile.length !== 0) {
var jqImeError = $('<p/>')
+
        var jqImeError = $('<p/>')
.css({
+
            .css({
'color' : 'darkred',
+
                'color': 'darkred',
'background' : 'white',
+
                'background': 'white',
'border' : '1px solid darkred',
+
                'border': '1px solid darkred',
'padding' : '1ex'
+
                'padding': '1ex'
})
+
            })
.text(message)
+
            .text(message)
  
if (jqIme !== 0) {
+
        if (jqIme !== 0) {
jqIme.before(jqImeError);
+
            jqIme.before(jqImeError);
} else {
+
        } else {
jqImeError.appendTo(jqFile);
+
            jqImeError.appendTo(jqFile);
}
+
        }
}
+
    } else {
else {
+
        window.alert(message);
window.alert(message);
+
    }
}
 
 
}
 
}
  
Line 334: Line 362:
 
*/
 
*/
 
function ime_eventDummy(e) {
 
function ime_eventDummy(e) {
e.cancelBubble = true;
+
    e.cancelBubble = true;
return false;
+
    return false;
 
}
 
}
  
Line 341: Line 369:
 
Function to define an object containing rect(angle) coordinates.
 
Function to define an object containing rect(angle) coordinates.
 
*/
 
*/
function ime_RectCoord(x1,y1,x2,y2) {
+
function ime_RectCoord(x1, y1, x2, y2) {
this.left = x1;
+
    this.left = x1;
this.top = y1;
+
    this.top = y1;
this.right = x2;
+
    this.right = x2;
this.bottom = y2;
+
    this.bottom = y2;
 
}
 
}
  
Line 351: Line 379:
 
Function to define an object containing circle coordinates.
 
Function to define an object containing circle coordinates.
 
*/
 
*/
function ime_CircleCoord(x,y,r) {
+
function ime_CircleCoord(x, y, r) {
this.x = x;
+
    this.x = x;
this.y = y;
+
    this.y = y;
this.radius = r;
+
    this.radius = r;
 
}
 
}
  
Line 360: Line 388:
 
Function to define an object containing poly(gon) coordinates.
 
Function to define an object containing poly(gon) coordinates.
 
*/
 
*/
function ime_PolyCoord(x,y,r) {
+
function ime_PolyCoord(x, y, r) {
this.points = Array();
+
    this.points = Array();
 
}
 
}
  
Line 369: Line 397:
 
*/
 
*/
 
function ime_Area(shape) {
 
function ime_Area(shape) {
if (shape=='rect') {
+
    if (shape == 'rect') {
this.shape = 'rect';
+
        this.shape = 'rect';
this.coords = new ime_RectCoord(0,0,0,0);
+
        this.coords = new ime_RectCoord(0, 0, 0, 0);
}
+
    } else if (shape == 'circle') {
else if (shape=='circle') {
+
        this.shape = 'circle';
this.shape = 'circle';
+
        this.coords = new ime_CircleCoord(0, 0, 20);
this.coords = new ime_CircleCoord(0,0,20);
+
    } else {
}
+
        this.shape = 'poly';
else {
+
        this.coords = new ime_PolyCoord();
this.shape = 'poly';
+
    }
this.coords = new ime_PolyCoord();
+
    this.link = '';
}
+
    this.title = '';
this.link = '';
 
this.title = '';
 
 
}
 
}
  
Line 390: Line 416:
 
*/
 
*/
 
function ime_getEvent(e) {
 
function ime_getEvent(e) {
if (e) {
+
    if (e) {
return e;
+
        return e;
}
+
    } else {
else {
+
        return window.event;
return window.event;
+
    }
}
 
 
}
 
}
  
 
function ime_eventGetX(e) {
 
function ime_eventGetX(e) {
if (typeof(e.layerX)!='undefined') {
+
    if (typeof(e.layerX) != 'undefined') {
return Math.round(e.layerX / ime_scale);
+
        return Math.round(e.layerX / ime_scale);
}
+
    }
if (typeof(e.offsetX)!='undefined') {
+
    if (typeof(e.offsetX) != 'undefined') {
return Math.round(e.offsetX / ime_scale);
+
        return Math.round(e.offsetX / ime_scale);
}
+
    } else {
else {
+
        return Math.round(e.x / ime_scale);
return Math.round(e.x / ime_scale);
+
    }
}
 
 
}
 
}
  
 
function ime_eventGetY(e) {
 
function ime_eventGetY(e) {
if (typeof(e.layerY)!='undefined') {
+
    if (typeof(e.layerY) != 'undefined') {
return Math.round(e.layerY / ime_scale);
+
        return Math.round(e.layerY / ime_scale);
}
+
    }
if (typeof(e.offsetY)!='undefined') {
+
    if (typeof(e.offsetY) != 'undefined') {
return Math.round(e.offsetY / ime_scale);
+
        return Math.round(e.offsetY / ime_scale);
}
+
    } else {
else {
+
        return Math.round(e.y / ime_scale);
return Math.round(e.y / ime_scale);
+
    }
}
 
 
}
 
}
  
 
function ime_eventGetButton(e) {
 
function ime_eventGetButton(e) {
if (typeof(e.which)!='undefined') {
+
    if (typeof(e.which) != 'undefined') {
return e.which;
+
        return e.which;
}
+
    } else {
else {
+
        return e.button;
return e.button;
+
    }
}
 
 
}
 
}
  
 
function ime_mouseEventClear() {
 
function ime_mouseEventClear() {
var img = document.getElementById('imeImg');
+
    var img = document.getElementById('imeImg');
img.onmousedown = null;
+
    img.onmousedown = null;
img.style.cursor = '';
+
    img.style.cursor = '';
 
}
 
}
  
 
function ime_mouseEventSet(func) {
 
function ime_mouseEventSet(func) {
var img = document.getElementById('imeImg');
+
    var img = document.getElementById('imeImg');
img.onmousedown = func;
+
    img.onmousedown = func;
img.style.cursor = 'crosshair';
+
    img.style.cursor = 'url("https://testwiki.kiprobatt.de/w/img_auth.php/f/fb/Crosshair.png"), crosshair';
 
}
 
}
  
 
function ime_eventRect(e) {
 
function ime_eventRect(e) {
e = ime_getEvent(e);
+
    e = ime_getEvent(e);
var button = ime_eventGetButton(e);
+
    var button = ime_eventGetButton(e);
if (button==1) {
+
    if (button == 1) {
document.ime.areaRectLeft.value = ime_eventGetX(e);
+
        document.ime.areaRectLeft.value = ime_eventGetX(e);
document.ime.areaRectTop.value = ime_eventGetY(e);
+
        document.ime.areaRectTop.value = ime_eventGetY(e);
}
+
    } else if (button == 2 || button == 3) {
else if (button==2 || button==3) {
+
        document.ime.areaRectRight.value = ime_eventGetX(e);
document.ime.areaRectRight.value = ime_eventGetX(e);
+
        document.ime.areaRectBottom.value = ime_eventGetY(e);
document.ime.areaRectBottom.value = ime_eventGetY(e);
+
    }
}
+
    ime_saveArea();
ime_saveArea();
+
    return false;
return false;
 
 
}
 
}
  
 
function ime_eventCircle(e) {
 
function ime_eventCircle(e) {
e = ime_getEvent(e);
+
    e = ime_getEvent(e);
var button = ime_eventGetButton(e);
+
    var button = ime_eventGetButton(e);
if (button==1) {
+
    if (button == 1) {
document.ime.areaCircleX.value = ime_eventGetX(e);
+
        document.ime.areaCircleX.value = ime_eventGetX(e);
document.ime.areaCircleY.value = ime_eventGetY(e);
+
        document.ime.areaCircleY.value = ime_eventGetY(e);
}
+
    } else if (button == 2 || button == 3) {
else if (button==2 || button==3) {
+
        var a = (ime_eventGetX(e) - parseInt(document.ime.areaCircleX.value));
var a = (ime_eventGetX(e) - parseInt(document.ime.areaCircleX.value));
+
        var b = (ime_eventGetY(e) - parseInt(document.ime.areaCircleY.value));
var b = (ime_eventGetY(e) - parseInt(document.ime.areaCircleY.value));
+
        document.ime.areaCircleRadius.value = Math.round(Math.sqrt(a * a + b * b));
document.ime.areaCircleRadius.value = Math.round(Math.sqrt(a*a + b*b));
+
    }
}
+
    ime_saveArea();
ime_saveArea();
+
    return false;
return false;
 
 
}
 
}
  
 
function ime_eventPoly(e) {
 
function ime_eventPoly(e) {
e = ime_getEvent(e);
+
    e = ime_getEvent(e);
var button = ime_eventGetButton(e);
+
    var button = ime_eventGetButton(e);
if (button==1) {
+
    if (button == 1) {
area = ime_areas[ime_currentlyEditing];
+
        area = ime_areas[ime_currentlyEditing];
area.coords.points.push(ime_eventGetX(e));
+
        area.coords.points.push(ime_eventGetX(e));
area.coords.points.push(ime_eventGetY(e));
+
        area.coords.points.push(ime_eventGetY(e));
ime_saveArea();
+
        ime_saveArea();
}
+
    }
return false;
+
    return false;
 
}
 
}
  
 
function ime_newArea(shape) {
 
function ime_newArea(shape) {
var area = new ime_Area(shape);
+
    var area = new ime_Area(shape);
area.shape = shape;
+
    area.shape = shape;
ime_areas.push(area);
+
    ime_areas.push(area);
  
ime_currentlyEditing = ime_areas.length-1;
+
    ime_currentlyEditing = ime_areas.length - 1;
ime_updateAreas();
+
    ime_updateAreas();
ime_editArea(ime_currentlyEditing);
+
    ime_editArea(ime_currentlyEditing);
autoComplete();
+
    autoComplete();
 
}
 
}
 
//Gets called by ime_newArea() and ime_editArea() functions.
 
//Gets called by ime_newArea() and ime_editArea() functions.
function autoComplete(){
+
function autoComplete() {
const search = document.getElementById('ime_areaLink');
+
    const search = document.getElementById('ime_areaLink');
$('#ime_areaLink').parent('div').addClass('ui-widget');
+
    $('#ime_areaLink').parent('div').addClass('ui-widget');
var firstTimeTrigger = false;
+
    var firstTimeTrigger = false;
var firstTimeTriggerCat = false;
+
    var firstTimeTriggerCat = false;
$('#ime_areaLink').parent('div').addClass('ui-autocomplete');
+
    $('#ime_areaLink').parent('div').addClass('ui-autocomplete');
var searchPages = async (searchText, searchCat) => {  
+
    var searchPages = async (searchText, searchCat) => {
  
var categories;
+
        var categories;
/*When the linkcategory field is empty, this code does the autocomplete in the linktarget field with all pages.*/
+
        /*When the linkcategory field is empty, this code does the autocomplete in the linktarget field with all pages.*/
if(searchCat.length === 0){categories = [];
+
        if (searchCat.length === 0) {
var pages;
+
            categories = [];
if(searchText.length === 0){
+
            var pages;
  pages = [];
+
            if (searchText.length === 0) {
}
+
                pages = [];
else{
+
            } else {
const res = await fetch('/w/api.php?action=pfautocomplete&substr='+ searchText +'&namespace=Main&format=json');
+
                const res = await fetch('/w/api.php?action=pfautocomplete&substr=' + searchText + '&namespace=Main&format=json');
pages = await res.json();
+
                pages = await res.json();
  
var allTitles = pages.pfautocomplete.map(function(item) {
+
                var allTitles = pages.pfautocomplete.map(function(item) {
  return item['title'];
+
                    return item['title'];
});
+
                });
  
$( "#ime_areaLink" ).autocomplete({
+
                $("#ime_areaLink").autocomplete({
      source: allTitles
+
                    source: allTitles
    });
+
                });
$('ul.ui-autocomplete').css('list-style', 'none');
+
                $('ul.ui-autocomplete').css('list-style', 'none');
if(!firstTimeTrigger){
+
                if (!firstTimeTrigger) {
firstTimeTrigger = true;
+
                    firstTimeTrigger = true;
search.dispatchEvent(new Event('input'));
+
                    search.dispatchEvent(new Event('input'));
}
+
                }
}
+
            }
}
+
        } else {
else{ /*When the linkcategory field is not empty, this else is called and at first it creates an autocomplete for the linkcategory field.*/
+
            /*When the linkcategory field is not empty, this else is called and at first it creates an autocomplete for the linkcategory field.*/
var get = await $.getJSON( "/w/api.php?action=query&list=allcategories&format=json");
+
            var get = await $.getJSON("/w/api.php?action=query&list=allcategories&format=json");
var categories = await get.query;
+
            var categories = await get.query;
var allCategories = categories.allcategories.map(function(item) {
+
            var allCategories = categories.allcategories.map(function(item) {
return item['*'];
+
                return item['*'];
});
+
            });
  
$( "#ime_linkCategory" ).autocomplete({
+
            $("#ime_linkCategory").autocomplete({
      source: allCategories
+
                source: allCategories
    });
+
            });
$('ul.ui-autocomplete').css('list-style', 'none');
+
            $('ul.ui-autocomplete').css('list-style', 'none');
if(!firstTimeTriggerCat){
+
            if (!firstTimeTriggerCat) {
firstTimeTriggerCat = true;
+
                firstTimeTriggerCat = true;
category.dispatchEvent(new Event('input'));
+
                category.dispatchEvent(new Event('input'));
}
+
            }
  
  
  
var pages;
+
            var pages;
/*When the linkcategory field is not empty, this code creates an autocomplete for the linktarget field with the given category from the linkcategory field.*/
+
            /*When the linkcategory field is not empty, this code creates an autocomplete for the linktarget field with the given category from the linkcategory field.*/
if(searchText.length === 0){
+
            if (searchText.length === 0) {
  pages = [];
+
                pages = [];
}
+
            } else {
else{
+
                const res = await fetch('/w/api.php?action=pfautocomplete&substr=' + searchText + '&category=' + searchCat + '&namespace=Main&format=json');
const res = await fetch('/w/api.php?action=pfautocomplete&substr='+ searchText + '&category='+ searchCat +'&namespace=Main&format=json');
+
                pages = await res.json();
pages = await res.json();
 
  
var allTitles = pages.pfautocomplete.map(function(item) {
+
                var allTitles = pages.pfautocomplete.map(function(item) {
  return item['title'];
+
                    return item['title'];
});
+
                });
  
$( "#ime_areaLink" ).autocomplete({
+
                $("#ime_areaLink").autocomplete({
      source: allTitles
+
                    source: allTitles
    });
+
                });
$('ul.ui-autocomplete').css('list-style', 'none');
+
                $('ul.ui-autocomplete').css('list-style', 'none');
if(!firstTimeTrigger){
+
                if (!firstTimeTrigger) {
firstTimeTrigger = true;
+
                    firstTimeTrigger = true;
search.dispatchEvent(new Event('input'));
+
                    search.dispatchEvent(new Event('input'));
}
+
                }
}
+
            }
}
+
        }
}
+
    }
  
search.addEventListener('input', () => searchPages(search.value, category.value));
+
    search.addEventListener('input', () => searchPages(search.value, category.value));
  
  
  
//This code creates the input field for the linkcategory.
+
    //This code creates the input field for the linkcategory.
if(!$('#ime_linkCategory').length){
+
    if (!$('#ime_linkCategory').length) {
var br = document.createElement("br");
+
        var br = document.createElement("br");
$('#ime_areaLink').parent().append(br);
+
        $('#ime_areaLink').parent().append(br);
var lbl = document.createElement("label");
+
        var lbl = document.createElement("label");
lbl.setAttribute("for", "ime_linkCategory");
+
        lbl.setAttribute("for", "ime_linkCategory");
lbl.setAttribute("id", "ime_linkCategoryLabel");
+
        lbl.setAttribute("id", "ime_linkCategoryLabel");
$('#ime_areaLink').parent().append(lbl);
+
        $('#ime_areaLink').parent().append(lbl);
var spn = document.createElement("span");
+
        var spn = document.createElement("span");
spn.setAttribute("value", "Linkkategorie");
+
        spn.setAttribute("value", "Linkkategorie");
spn.innerHTML = 'Linkkategorie';
+
        spn.innerHTML = 'Linkkategorie';
document.getElementById("ime_linkCategoryLabel").appendChild(spn);
+
        document.getElementById("ime_linkCategoryLabel").appendChild(spn);
var br1 = document.createElement("br");
+
        var br1 = document.createElement("br");
$('#ime_areaLink').parent().append(br1);
+
        $('#ime_areaLink').parent().append(br1);
var inpt = document.createElement("INPUT");
+
        var inpt = document.createElement("INPUT");
inpt.setAttribute("type", "text");
+
        inpt.setAttribute("type", "text");
inpt.setAttribute("id", "ime_linkCategory");
+
        inpt.setAttribute("id", "ime_linkCategory");
inpt.setAttribute("style","width:10em");
+
        inpt.setAttribute("style", "width:10em");
//document.getElementById("ime_areaLink")[0].appendChild(inpt);
+
        //document.getElementById("ime_areaLink")[0].appendChild(inpt);
$('#ime_areaLink').parent().append(inpt);
+
        $('#ime_areaLink').parent().append(inpt);
}
+
    }
const category = document.getElementById('ime_linkCategory');
+
    const category = document.getElementById('ime_linkCategory');
category.addEventListener('input', () => searchPages(search.value, category.value));
+
    category.addEventListener('input', () => searchPages(search.value, category.value));
 
}
 
}
  
Line 605: Line 624:
  
 
function ime_updateAreas() {
 
function ime_updateAreas() {
ime_updateSelectArea();
+
    ime_updateSelectArea();
ime_updateMap();
+
    ime_updateMap();
ime_updateResult();
+
    ime_updateResult();
 
}
 
}
  
 
function ime_updateResult() {
 
function ime_updateResult() {
var arr = document.ime.imageDescriptionPos;
+
    var arr = document.ime.imageDescriptionPos;
var imageDescriptionPos = arr[0].value;
+
    var imageDescriptionPos = arr[0].value;
for (var i=1; i<arr.length; i++) {
+
    for (var i = 1; i < arr.length; i++) {
if (arr[i].checked) {
+
        if (arr[i].checked) {
imageDescriptionPos = arr[i].value;
+
            imageDescriptionPos = arr[i].value;
break;
+
            break;
}
+
        }
}
+
    }
  
var result = Array();
+
    var result = Array();
result.push('<imagemap>');
+
    result.push('<imagemap>');
result.push(mw.config.get('wgPageName') + '|' + document.ime.imageDescription.value);
+
    result.push(mw.config.get('wgPageName') + '|' + document.ime.imageDescription.value);
result.push('');
+
    result.push('');
for (var i=0; i<ime_areas.length; i++) {
+
    for (var i = 0; i < ime_areas.length; i++) {
var coords = ime_areas[i].coords;
+
        var coords = ime_areas[i].coords;
var s = '';
+
        var s = '';
if (ime_areas[i].shape=='rect') {
+
        if (ime_areas[i].shape == 'rect') {
s = coords.left + ' ' + coords.top + ' ' + coords.right + ' ' + coords.bottom;
+
            s = coords.left + ' ' + coords.top + ' ' + coords.right + ' ' + coords.bottom;
}
+
        } else if (ime_areas[i].shape == 'circle') {
else if (ime_areas[i].shape=='circle') {
+
            s = coords.x + ' ' + coords.y + ' ' + coords.radius;
s = coords.x + ' ' + coords.y + ' ' + coords.radius;
+
        } else if (ime_areas[i].shape == 'poly') {
}
+
            s = coords.points.join(' ');
else if (ime_areas[i].shape=='poly') {
+
        }
s = coords.points.join(' ');
+
        result.push(ime_areas[i].shape + ' ' + s + ' [[' + ime_areas[i].link + (ime_areas[i].title ? '|' + ime_areas[i].title : '') + ']]');
}
+
    }
result.push(ime_areas[i].shape + ' ' + s + ' [[' + ime_areas[i].link + (ime_areas[i].title ? '|' + ime_areas[i].title : '') + ']]');
+
    result.push('');
}
+
    result.push('desc ' + imageDescriptionPos);
result.push('');
+
    result.push('</imagemap>');
result.push('desc ' + imageDescriptionPos);
 
result.push('</imagemap>');
 
  
var preResult = document.getElementById('imeResult');
+
    var preResult = document.getElementById('imeResult');
  
while (preResult.lastChild) {
+
    while (preResult.lastChild) {
preResult.removeChild(preResult.lastChild);
+
        preResult.removeChild(preResult.lastChild);
}
+
    }
  
for (var i=0; i<result.length; i++) {
+
    for (var i = 0; i < result.length; i++) {
preResult.appendChild(document.createTextNode(result[i]));
+
        preResult.appendChild(document.createTextNode(result[i]));
preResult.appendChild(document.createElement('br'));
+
        preResult.appendChild(document.createElement('br'));
}
+
    }
 
}
 
}
  
 
function ime_updateMap() {
 
function ime_updateMap() {
var preview = document.getElementById('imePreview');
+
    var preview = document.getElementById('imePreview');
var img = document.getElementById('imeImg');
+
    var img = document.getElementById('imeImg');
  
// Remove areas from map which are out of range
+
    // Remove areas from map which are out of range
for (var i=0; i<preview.childNodes.length; i++) {
+
    for (var i = 0; i < preview.childNodes.length; i++) {
var child = preview.childNodes[i];
+
        var child = preview.childNodes[i];
var id = parseInt(child.id.substring(10));
+
        var id = parseInt(child.id.substring(10));
if (id>=ime_areas.length) {
+
        if (id >= ime_areas.length) {
preview.removeChild(child);
+
            preview.removeChild(child);
i--;
+
            i--;
}
+
        }
}
+
    }
  
for (var i=0; i<ime_areas.length; i++) {
+
    for (var i = 0; i < ime_areas.length; i++) {
// Get existing DIV
+
        // Get existing DIV
var area = ime_areas[i];
+
        var area = ime_areas[i];
var div = document.getElementById('imePreview' + i);
+
        var div = document.getElementById('imePreview' + i);
  
// If it does not exist exists, create a new one and set style
+
        // If it does not exist exists, create a new one and set style
if (!div) {
+
        if (!div) {
var div = ime_htmlNewDiv('imePreview' + i)
+
            var div = ime_htmlNewDiv('imePreview' + i)
preview.appendChild(div);
+
            preview.appendChild(div);
div.style.zIndex = 0;
+
            div.style.zIndex = 0;
div.style.position = 'absolute';
+
            div.style.position = 'absolute';
div.style.opacity = 0.5;
+
            div.style.opacity = 0.5;
div.style.filter = 'alpha(opacity=50)';
+
            div.style.filter = 'alpha(opacity=50)';
}
+
        }
  
var coords = area.coords;
+
        var coords = area.coords;
if (area.shape == 'rect') {
+
        if (area.shape == 'rect') {
div.className = 'previewRect';
+
            div.className = 'previewRect';
// Only if valid coordinates were given, draw
+
            // Only if valid coordinates were given, draw
if (coords.left<coords.right && coords.top<coords.bottom) {
+
            if (coords.left < coords.right && coords.top < coords.bottom) {
div.style.left = Math.round(ime_scale * coords.left) + 'px';
+
                div.style.left = Math.round(ime_scale * coords.left) + 'px';
div.style.top = Math.round(ime_scale * coords.top) + 'px';
+
                div.style.top = Math.round(ime_scale * coords.top) + 'px';
div.style.width = (Math.round(ime_scale * coords.right) - Math.round(ime_scale * coords.left)) + 'px';
+
                div.style.width = (Math.round(ime_scale * coords.right) - Math.round(ime_scale * coords.left)) + 'px';
div.style.height = (Math.round(ime_scale * coords.bottom) - Math.round(ime_scale * coords.top)) + 'px';
+
                div.style.height = (Math.round(ime_scale * coords.bottom) - Math.round(ime_scale * coords.top)) + 'px';
}
+
            } else {
else {
+
                div.style.left = '0';
div.style.left = '0';
+
                div.style.top = '0';
div.style.top = '0';
+
                div.style.width = '0';
div.style.width = '0';
+
                div.style.height = '0';
div.style.height = '0';
+
            }
}
+
        } else if (area.shape == 'circle') {
}
+
            div.className = 'previewCircle';
else if (area.shape == 'circle') {
+
            div.style.backgroundRepeat = 'no-repeat';
div.className = 'previewCircle';
+
            var left = Math.round(ime_scale * coords.x) - Math.round(ime_scale * coords.radius);
div.style.backgroundRepeat = 'no-repeat';
+
            var top = Math.round(ime_scale * coords.y) - Math.round(ime_scale * coords.radius);
var left = Math.round(ime_scale * coords.x) - Math.round(ime_scale * coords.radius);
+
            var size = Math.round(ime_scale * coords.radius * 2) + 1;
var top = Math.round(ime_scale * coords.y) - Math.round(ime_scale * coords.radius);
 
var size = Math.round(ime_scale * coords.radius * 2) + 1;
 
  
div.style.left = left + 'px';
+
            div.style.left = left + 'px';
div.style.top = top + 'px';
+
            div.style.top = top + 'px';
  
if (left + size > img.width) {
+
            if (left + size > img.width) {
div.style.width = (img.width - left) + 'px';
+
                div.style.width = (img.width - left) + 'px';
}
+
            } else {
else {
+
                div.style.width = size + 'px';
div.style.width = size + 'px';
+
            }
}
 
  
if (top + size > img.height) {
+
            if (top + size > img.height) {
div.style.height = (img.height - top) + 'px';
+
                div.style.height = (img.height - top) + 'px';
}
+
            } else {
else {
+
                div.style.height = size + 'px';
div.style.height = size + 'px';
+
            }
}
+
        } else if (area.shape == 'poly') {
}
+
            // Determine maximum coordinates (this is how big the image is)
else if (area.shape == 'poly') {
+
            div.className = 'previewPoly';
// Determine maximum coordinates (this is how big the image is)
+
            div.style.backgroundRepeat = 'no-repeat';
div.className = 'previewPoly';
 
div.style.backgroundRepeat = 'no-repeat';
 
  
var points = coords.points;
+
            var points = coords.points;
var minX=0; var maxX=0; var minY=0; var maxY=0;
+
            var minX = 0;
if (points.length>0) {
+
            var maxX = 0;
minX = points[0];
+
            var minY = 0;
maxX = points[0];
+
            var maxY = 0;
minY = points[1];
+
            if (points.length > 0) {
maxY = points[1];
+
                minX = points[0];
for (var j=2; j<points.length; j+=2) {
+
                maxX = points[0];
var x = points[j];
+
                minY = points[1];
var y = points[j+1];
+
                maxY = points[1];
if (x<minX) minX = x;
+
                for (var j = 2; j < points.length; j += 2) {
if (x>maxX) maxX = x;
+
                    var x = points[j];
if (y<minY) minY = y;
+
                    var y = points[j + 1];
if (y>maxY) maxY = y;
+
                    if (x < minX) minX = x;
}
+
                    if (x > maxX) maxX = x;
}
+
                    if (y < minY) minY = y;
 +
                    if (y > maxY) maxY = y;
 +
                }
 +
            }
  
div.style.left = Math.round(ime_scale * minX) + 'px';
+
            div.style.left = Math.round(ime_scale * minX) + 'px';
div.style.top = Math.round(ime_scale * minY) + 'px';
+
            div.style.top = Math.round(ime_scale * minY) + 'px';
div.style.width = (Math.round(ime_scale * maxX) - Math.round(ime_scale * minX)) + 'px';
+
            div.style.width = (Math.round(ime_scale * maxX) - Math.round(ime_scale * minX)) + 'px';
div.style.height = (Math.round(ime_scale * maxY) - Math.round(ime_scale * minY)) + 'px';
+
            div.style.height = (Math.round(ime_scale * maxY) - Math.round(ime_scale * minY)) + 'px';
}
+
        }
}
+
    }
  
ime_highlightMap();
+
    ime_highlightMap();
 
}
 
}
  
function ime_highlightMapCircle(div,radius,highlight) {
+
function ime_highlightMapCircle(div, radius, highlight) {
var background = "url('" + IME_CIRCLESCRIPT + '?' + (highlight ? 'active=1&' : '') + 'radius=' + Math.round(ime_scale * radius) + "') no-repeat";
+
    var canvas = document.createElement('canvas');
if (div.style.background != background) {
+
    canvas.width = radius * 2;
div.style.background = background;
+
    canvas.height = radius * 2;
}
+
 
 +
 
 +
 
 +
    var ctx = canvas.getContext("2d");
 +
    ctx.beginPath();
 +
    ctx.arc(radius, radius, radius, 0, 2 * Math.PI);
 +
    if (highlight) {
 +
        ctx.fillStyle = 'red';
 +
        ctx.fill();
 +
        ctx.strokeStyle = 'red';
 +
    } else {
 +
        ctx.fillStyle = 'black';
 +
        ctx.fill();
 +
        ctx.strokeStyle = 'black';
 +
    }
 +
    ctx.stroke();
 +
    ctx.closePath();
 +
 
 +
    var meinBild = canvas.toDataURL('image/png', 1.0);
 +
 
 +
    var background = "url('" + meinBild + "')";
 +
    if (div.style.background != background) {
 +
        div.style.background = background;
 +
        div.style.backgroundRepeat = "no-repeat";
 +
    }
 
}
 
}
  
function ime_highlightMapPoly(div,points,highlight) {
+
function ime_highlightMapPoly(div, points, highlight) {
var minX=0; var minY=0;
+
    var minX = 0;
if (points.length>0) {
+
    var minY = 0;
minX = points[0];
+
    var maxX = 0;
minY = points[1];
+
    var maxY = 0;
for (var j=2; j<points.length; j+=2) {
+
    if (points.length > 0) {
var x = points[j];
+
        minX = points[0];
var y = points[j+1];
+
        minY = points[1];
if (x<minX) minX = x;
+
        for (var j = 2; j < points.length; j += 2) {
if (y<minY) minY = y;
+
            var x = points[j];
}
+
            var y = points[j + 1];
}
+
            if (x < minX) minX = x;
var convpoints = Array();
+
            if (y < minY) minY = y;
for(var j=0; j<points.length; j+=2) {
+
        }
convpoints[j] = Math.round(ime_scale * points[j]) - Math.round(ime_scale * minX);
+
    }
convpoints[j+1] = Math.round(ime_scale * points[j+1]) - Math.round(ime_scale * minY);
+
    if (points.length > 0) {
}
+
        maxX = points[0];
var background = "url('" + IME_POLYSCRIPT + '?' + (highlight ? 'active=1&' : '') + 'coords=' + convpoints.join("|") + "') no-repeat";
+
        maxY = points[1];
if (div.style.background != background) {
+
        for (var j = 2; j < points.length; j += 2) {
div.style.background = background;
+
            var x = points[j];
}
+
            var y = points[j + 1];
 +
            if (x > maxX) maxX = x;
 +
            if (y > maxY) maxY = y;
 +
        }
 +
    }
 +
    var convpoints = Array();
 +
    for (var j = 0; j < points.length; j += 2) {
 +
        convpoints[j] = Math.round(ime_scale * points[j]) - Math.round(ime_scale * minX);
 +
        convpoints[j + 1] = Math.round(ime_scale * points[j + 1]) - Math.round(ime_scale * minY);
 +
    }
 +
    var canvas = document.createElement('canvas');
 +
    canvas.width = maxX + 1;
 +
    canvas.height = maxY + 1;
 +
    var ctx = canvas.getContext("2d");
 +
    if (highlight) {
 +
        ctx.save();
 +
        ctx.beginPath();
 +
        ctx.moveTo(convpoints.shift(), convpoints.shift());
 +
        while (convpoints.length) {
 +
            ctx.lineTo(convpoints.shift(), convpoints.shift());
 +
        }
 +
        ctx.closePath();
 +
        ctx.strokeStyle = 'red';
 +
        ctx.stroke();
 +
        ctx.fillStyle = 'red'
 +
        ctx.fill();
 +
        ctx.closePath();
 +
        ctx.restore();
 +
    } else {
 +
        ctx.save();
 +
        ctx.beginPath();
 +
        ctx.moveTo(convpoints.shift(), convpoints.shift());
 +
        while (convpoints.length) {
 +
            ctx.lineTo(convpoints.shift(), convpoints.shift());
 +
        }
 +
        ctx.closePath();
 +
        ctx.strokeStyle = 'black';
 +
        ctx.stroke();
 +
        ctx.fillStyle = 'black'
 +
        ctx.fill();
 +
        ctx.closePath();
 +
        ctx.restore();
 +
    }
 +
    var meinBild = canvas.toDataURL('image/png', 1.0);
 +
 
 +
    var background = "url('" + meinBild + "')";
 +
 
 +
    if (div.style.background != background) {
 +
        div.style.background = background;
 +
        div.style.backgroundRepeat = "no-repeat";
 +
    }
 
}
 
}
  
 
function ime_highlightMap() {
 
function ime_highlightMap() {
for (var i=0; i<ime_areas.length; i++) {
+
    for (var i = 0; i < ime_areas.length; i++) {
var div = document.getElementById('imePreview' + i);
+
        var div = document.getElementById('imePreview' + i);
var area = ime_areas[i];
+
        var area = ime_areas[i];
if (div && area) {
+
        if (div && area) {
if (i==ime_currentlyEditing) {
+
            if (i == ime_currentlyEditing) {
div.style.opacity = '0.9';
+
                div.style.opacity = '0.9';
div.style.filter = 'alpha(opacity=90)'; // IE
+
                div.style.filter = 'alpha(opacity=90)'; // IE
} else {
+
            } else {
div.style.opacity = '0.75';
+
                div.style.opacity = '0.75';
div.style.filter = 'alpha(opacity=75)'; // IE
+
                div.style.filter = 'alpha(opacity=75)'; // IE
}
+
            }
if (area.shape == 'rect') {
+
            if (area.shape == 'rect') {
var backgroundColor = (i==ime_currentlyEditing) ? 'red' : 'black';
+
                var backgroundColor = (i == ime_currentlyEditing) ? 'red' : 'black';
if (div.style.backgroundColor != backgroundColor) div.style.backgroundColor = backgroundColor;
+
                if (div.style.backgroundColor != backgroundColor) div.style.backgroundColor = backgroundColor;
}
+
            } else if (area.shape == 'circle') {
else if (area.shape == 'circle') {
+
                ime_highlightMapCircle(div, area.coords.radius, (i == ime_currentlyEditing));
ime_highlightMapCircle(div,area.coords.radius,(i==ime_currentlyEditing));
+
            } else if (area.shape == 'poly') {
}
+
                ime_highlightMapPoly(div, area.coords.points, (i == ime_currentlyEditing));
else if (area.shape == 'poly') {
+
            }
ime_highlightMapPoly(div,area.coords.points,(i==ime_currentlyEditing));
+
        }
}
+
    }
}
 
}
 
 
}
 
}
  
 
function ime_updateSelectArea() {
 
function ime_updateSelectArea() {
var selectArea = document.ime.area;
+
    var selectArea = document.ime.area;
  
while (selectArea.childNodes.length>0) {
+
    while (selectArea.childNodes.length > 0) {
selectArea.removeChild(selectArea.lastChild);
+
        selectArea.removeChild(selectArea.lastChild);
}
+
    }
  
for (var i=0; i<ime_areas.length; i++) {
+
    for (var i = 0; i < ime_areas.length; i++) {
var option = document.createElement('option');
+
        var option = document.createElement('option');
var area = ime_areas[i];
+
        var area = ime_areas[i];
option.value = i;
+
        option.value = i;
while (option.childNodes.length>0) {
+
        while (option.childNodes.length > 0) {
option.removeChild(option.lastChild);
+
            option.removeChild(option.lastChild);
}
+
        }
var text = (area.title ? area.title : area.link) + ' [' + area.shape + ']';
+
        var text = (area.title ? area.title : area.link) + ' [' + area.shape + ']';
option.appendChild(document.createTextNode(text));
+
        option.appendChild(document.createTextNode(text));
if (i == ime_currentlyEditing) {
+
        if (i == ime_currentlyEditing) {
option.selected = 'selected';
+
            option.selected = 'selected';
}
+
        }
selectArea.appendChild(option);
+
        selectArea.appendChild(option);
}
+
    }
 
}
 
}
  
 
function ime_editArea(index) {
 
function ime_editArea(index) {
document.getElementById('imeProps').style.display = 'none';
+
    document.getElementById('imeProps').style.display = 'none';
  
var area = ime_areas[index];
+
    var area = ime_areas[index];
  
if (area) {
+
    if (area) {
ime_currentlyEditing = index;
+
        ime_currentlyEditing = index;
  
document.getElementById('imeProps').style.display = '';
+
        document.getElementById('imeProps').style.display = '';
document.getElementById('imePropsRect').style.display = 'none';
+
        document.getElementById('imePropsRect').style.display = 'none';
document.getElementById('imePropsCircle').style.display = 'none';
+
        document.getElementById('imePropsCircle').style.display = 'none';
document.getElementById('imePropsPoly').style.display= 'none';
+
        document.getElementById('imePropsPoly').style.display = 'none';
ime_mouseEventClear();
+
        ime_mouseEventClear();
  
if (area.shape == 'rect') {
+
        if (area.shape == 'rect') {
document.getElementById('imePropsRect').style.display = '';
+
            document.getElementById('imePropsRect').style.display = '';
ime_mouseEventSet(ime_eventRect);
+
            ime_mouseEventSet(ime_eventRect);
}
+
        } else if (area.shape == 'circle') {
else if (area.shape == 'circle') {
+
            document.getElementById('imePropsCircle').style.display = '';
document.getElementById('imePropsCircle').style.display = '';
+
            ime_mouseEventSet(ime_eventCircle);
ime_mouseEventSet(ime_eventCircle);
+
        } else if (area.shape == 'poly') {
}
+
            document.getElementById('imePropsPoly').style.display = '';
else if (area.shape == 'poly') {
+
            ime_mouseEventSet(ime_eventPoly);
document.getElementById('imePropsPoly').style.display = '';
+
        }
ime_mouseEventSet(ime_eventPoly);
 
}
 
  
document.ime.areaLink.value = area.link;
+
        document.ime.areaLink.value = area.link;
document.ime.areaTitle.value = area.title;
+
        document.ime.areaTitle.value = area.title;
  
var coords = area.coords;
+
        var coords = area.coords;
if (area.shape == 'rect') {
+
        if (area.shape == 'rect') {
document.ime.areaRectLeft.value = coords.left;
+
            document.ime.areaRectLeft.value = coords.left;
document.ime.areaRectTop.value = coords.top;
+
            document.ime.areaRectTop.value = coords.top;
document.ime.areaRectRight.value = coords.right;
+
            document.ime.areaRectRight.value = coords.right;
document.ime.areaRectBottom.value = coords.bottom;
+
            document.ime.areaRectBottom.value = coords.bottom;
}
+
        } else if (area.shape == 'circle') {
else if (area.shape == 'circle') {
+
            document.ime.areaCircleX.value = coords.x;
document.ime.areaCircleX.value = coords.x;
+
            document.ime.areaCircleY.value = coords.y;
document.ime.areaCircleY.value = coords.y;
+
            document.ime.areaCircleRadius.value = coords.radius;
document.ime.areaCircleRadius.value = coords.radius;
+
        } else if (area.shape == 'poly') {
}
+
            var propsPolyCoords = document.getElementById('imePropsPolyCoords');
else if (area.shape == 'poly') {
+
            if (propsPolyCoords.childNodes.length > 0) propsPolyCoords.removeChild(propsPolyCoords.lastChild);
var propsPolyCoords = document.getElementById('imePropsPolyCoords');
+
            propsPolyCoords.appendChild(document.createTextNode(area.coords.points.join(", ")));
if (propsPolyCoords.childNodes.length > 0) propsPolyCoords.removeChild(propsPolyCoords.lastChild);
+
        }
propsPolyCoords.appendChild(document.createTextNode(area.coords.points.join(", ")));
 
}
 
  
ime_highlightMap();
+
        ime_highlightMap();
}
+
    }
autoComplete();
+
    autoComplete();
 
}
 
}
  
 
function ime_deletePolyCoords() {
 
function ime_deletePolyCoords() {
ime_areas[ime_currentlyEditing].coords.points = Array();
+
    ime_areas[ime_currentlyEditing].coords.points = Array();
ime_saveArea();
+
    ime_saveArea();
 
}
 
}
  
 
function ime_saveArea() {
 
function ime_saveArea() {
var area = ime_areas[ime_currentlyEditing];
+
    var area = ime_areas[ime_currentlyEditing];
area.link = document.ime.areaLink.value;
+
    area.link = document.ime.areaLink.value;
area.title = document.ime.areaTitle.value;
+
    area.title = document.ime.areaTitle.value;
  
var coords = area.coords;
+
    var coords = area.coords;
if (area.shape=='rect') {
+
    if (area.shape == 'rect') {
coords.left = parseInt(document.ime.areaRectLeft.value);
+
        coords.left = parseInt(document.ime.areaRectLeft.value);
coords.top = parseInt(document.ime.areaRectTop.value);
+
        coords.top = parseInt(document.ime.areaRectTop.value);
coords.right = parseInt(document.ime.areaRectRight.value);
+
        coords.right = parseInt(document.ime.areaRectRight.value);
coords.bottom = parseInt(document.ime.areaRectBottom.value);
+
        coords.bottom = parseInt(document.ime.areaRectBottom.value);
}
+
    } else if (area.shape == 'circle') {
else if (area.shape=='circle') {
+
        if (parseInt(document.ime.areaCircleRadius.value) < 0) document.ime.areaCircleRadius.value = 0;
if (parseInt(document.ime.areaCircleRadius.value) < 0) document.ime.areaCircleRadius.value = 0;
+
        coords.x = parseInt(document.ime.areaCircleX.value);
coords.x = parseInt(document.ime.areaCircleX.value);
+
        coords.y = parseInt(document.ime.areaCircleY.value);
coords.y = parseInt(document.ime.areaCircleY.value);
+
        coords.radius = parseInt(document.ime.areaCircleRadius.value);
coords.radius = parseInt(document.ime.areaCircleRadius.value);
+
    } else if (area.shape == 'poly') {
}
+
        var propsPolyCoords = document.getElementById('imePropsPolyCoords');
else if (area.shape == 'poly') {
+
        if (propsPolyCoords.childNodes.length > 0) propsPolyCoords.removeChild(propsPolyCoords.lastChild);
var propsPolyCoords = document.getElementById('imePropsPolyCoords');
+
        propsPolyCoords.appendChild(document.createTextNode(coords.points.join(", ")));
if (propsPolyCoords.childNodes.length > 0) propsPolyCoords.removeChild(propsPolyCoords.lastChild);
+
    }
propsPolyCoords.appendChild(document.createTextNode(coords.points.join(", ")));
 
}
 
  
ime_updateAreas();
+
    ime_updateAreas();
 
}
 
}
  
 
function ime_deleteArea() {
 
function ime_deleteArea() {
ime_mouseEventClear();
+
    ime_mouseEventClear();
  
// Remove element from ime_areas array
+
    // Remove element from ime_areas array
ime_areas.splice(ime_currentlyEditing,1);
+
    ime_areas.splice(ime_currentlyEditing, 1);
  
// Remove preview div of the deleted area
+
    // Remove preview div of the deleted area
var div = document.getElementById('imePreview' + ime_currentlyEditing);
+
    var div = document.getElementById('imePreview' + ime_currentlyEditing);
if (div) {
+
    if (div) {
div.parentNode.removeChild(div);
+
        div.parentNode.removeChild(div);
}
+
    }
  
// Move ids of preview divs to fill the hole
+
    // Move ids of preview divs to fill the hole
for (var i=ime_currentlyEditing+1; i<ime_areas.length; i++) {
+
    for (var i = ime_currentlyEditing + 1; i < ime_areas.length; i++) {
div = document.getElementById('imePreview' + i);
+
        div = document.getElementById('imePreview' + i);
if (div) {
+
        if (div) {
div.id = 'imePreview' + (i-1);
+
            div.id = 'imePreview' + (i - 1);
}
+
        }
}
+
    }
  
// If we deleted the last area, correct currently editing
+
    // If we deleted the last area, correct currently editing
if (ime_currentlyEditing>=ime_areas.length) {
+
    if (ime_currentlyEditing >= ime_areas.length) {
ime_currentlyEditing = ime_areas.length-1;
+
        ime_currentlyEditing = ime_areas.length - 1;
}
+
    }
  
ime_updateAreas();
+
    ime_updateAreas();
ime_editArea(ime_currentlyEditing);
+
    ime_editArea(ime_currentlyEditing);
 
}
 
}
  
 
function ime_importLines() {
 
function ime_importLines() {
var text = document.ime.importText.value;
+
    var text = document.ime.importText.value;
var lines = text.split("\n");
+
    var lines = text.split("\n");
  
for (var i=0; i<lines.length; i++) {
+
    for (var i = 0; i < lines.length; i++) {
var rectMatch = /rect +(\d+) +(\d+) +(\d+) +(\d+) +\[\[([^|]*)(|(.*))?\]\]/i;
+
        var rectMatch = /rect +(\d+) +(\d+) +(\d+) +(\d+) +\[\[([^|]*)(|(.*))?\]\]/i;
var circleMatch = /circle +(\d+) +(\d+) +(\d+) +\[\[([^|]*)(|(.*))?\]\]/i;
+
        var circleMatch = /circle +(\d+) +(\d+) +(\d+) +\[\[([^|]*)(|(.*))?\]\]/i;
var polyMatch = /poly +(.*?) +\[\[([^|]*)(|(.*))?\]\]/i;
+
        var polyMatch = /poly +(.*?) +\[\[([^|]*)(|(.*))?\]\]/i;
  
var line = lines[i];
+
        var line = lines[i];
  
if (rectMatch.test(line)) {
+
        if (rectMatch.test(line)) {
var results = rectMatch.exec(line);
+
            var results = rectMatch.exec(line);
var area = new ime_Area("rect");
+
            var area = new ime_Area("rect");
area.coords.left = parseInt(results[1]);
+
            area.coords.left = parseInt(results[1]);
area.coords.top = parseInt(results[2]);
+
            area.coords.top = parseInt(results[2]);
area.coords.right = parseInt(results[3]);
+
            area.coords.right = parseInt(results[3]);
area.coords.bottom = parseInt(results[4]);
+
            area.coords.bottom = parseInt(results[4]);
area.link = results[5];
+
            area.link = results[5];
if (results[6]) area.title = results[6].substring(1);
+
            if (results[6]) area.title = results[6].substring(1);
ime_areas.push(area);
+
            ime_areas.push(area);
}
+
        } else if (circleMatch.test(line)) {
else if (circleMatch.test(line)) {
+
            var results = circleMatch.exec(line);
var results = circleMatch.exec(line);
+
            var area = new ime_Area("circle");
var area = new ime_Area("circle");
+
            area.coords.x = parseInt(results[1]);
area.coords.x = parseInt(results[1]);
+
            area.coords.y = parseInt(results[2]);
area.coords.y = parseInt(results[2]);
+
            area.coords.radius = parseInt(results[3]);
area.coords.radius = parseInt(results[3]);
+
            area.link = results[4];
area.link = results[4];
+
            if (results[5]) area.title = results[5].substring(1);
if (results[5]) area.title = results[5].substring(1);
+
            ime_areas.push(area);
ime_areas.push(area);
+
        } else if (polyMatch.test(line)) {
}
+
            var results = polyMatch.exec(line);
else if (polyMatch.test(line)) {
+
            var area = new ime_Area("poly");
var results = polyMatch.exec(line);
+
            area.coords.points = results[1].replace(/ +/, " ").split(" ");
var area = new ime_Area("poly");
+
            for (var j = 0; j < area.coords.points.length; j++) {
area.coords.points = results[1].replace(/ +/," ").split(" ");
+
                area.coords.points[j] = parseInt(area.coords.points[j]);
for (var j=0; j<area.coords.points.length; j++) {
+
            }
area.coords.points[j] = parseInt(area.coords.points[j]);
+
            area.link = results[2];
}
+
            if (results[3]) area.title = results[3].substring(1);
area.link = results[2];
+
            ime_areas.push(area);
if (results[3]) area.title = results[3].substring(1);
+
        }
ime_areas.push(area);
+
    }
}
+
    ime_updateAreas();
}
+
    ime_hideImport();
ime_updateAreas();
+
}
ime_hideImport();
+
 
 +
function ime_showResult() {
 +
    $('#imeResult').show();
 +
    $('#imeResultShow').hide();
 +
    $('#imeResultHide').show();
 +
}
 +
 
 +
function ime_hideResult() {
 +
    $('#imeResult').hide();
 +
    $('#imeResultShow').show();
 +
    $('#imeResultHide').hide();
 
}
 
}
  
 
function ime_showImport() {
 
function ime_showImport() {
$('#imeImport').show();
+
    $('#imeImport').show();
$('#imeImportShow').hide();
+
    $('#imeImportShow').hide();
$('#imeImportHide').show();
+
    $('#imeImportHide').show();
 
}
 
}
  
 
function ime_hideImport() {
 
function ime_hideImport() {
$('#imeImport').hide();
+
    $('#imeImport').hide();
$('#imeImportShow').show();
+
    $('#imeImportShow').show();
$('#imeImportHide').hide();
+
    $('#imeImportHide').hide();
 
}
 
}
  
Line 1,013: Line 1,104:
 
*/
 
*/
 
function ime_removeOtherUIElements() {
 
function ime_removeOtherUIElements() {
// Remove all UI elements of the 'annotations' feature used on Wikimedia
+
    // Remove all UI elements of the 'annotations' feature used on Wikimedia
// Commons.
+
    // Commons.
$('#ImageAnnotationAddButton').remove();
+
    $('#ImageAnnotationAddButton').remove();
 
}
 
}
  
Line 1,022: Line 1,113:
 
*/
 
*/
 
function ime_findATag(node) {
 
function ime_findATag(node) {
// We just look at the first child until there is none or it is an <a> tag
+
    // We just look at the first child until there is none or it is an <a> tag
var a = node;
+
    var a = node;
while (a != null && a.nodeName.toUpperCase() != 'A') {
+
    while (a != null && a.nodeName.toUpperCase() != 'A') {
a = a.firstChild;
+
        a = a.firstChild;
}
+
    }
return a;
+
    return a;
 
}
 
}
 +
 +
 +
var ime_templateHtml = `<form name="ime" action=""> <fieldset style="margin:0.5ex;padding:0 1ex 1ex"> <legend>ImageMapEdit</legend> <fieldset style="float:left;margin:0 0.5ex 0.5ex;padding:0 1ex 1ex"> <legend style="padding:0 0.5ex" class="ime_t_newarea">Create new area</legend> <a href="javascript:ime_newArea('rect')" style="padding:1px;background:white;color:darkblue" class="ime_t_rect">rect(angle)</a> <br /> <a href="javascript:ime_newArea('circle')" style="padding:1px;background:white;color:darkblue" class="ime_t_circle">circle</a> <br /> <a href="javascript:ime_newArea('poly')" style="padding:1px;background:white;color:darkblue" class="ime_t_poly">poly(gon)</a> </fieldset> <fieldset style="float:left;margin:0 0.5ex 0.5ex;padding:0 1ex 1ex"> <legend style="padding:0 0.5ex" class="ime_t_editarea">Edit area</legend> <select name="area" size="10" style="float:left;height:10em;margin:0.5ex;width:10em" onclick="ime_editArea(document.ime.area.selectedIndex)"></select> <div id="imeProps" style="float:left;margin:0.5ex;padding:0 1ex 1ex;display:none"> <div style="float:left;margin:0.5ex;padding:0 1ex 1ex"> <label for="ime_areaLink" class="ime_t_linktarget">Link target</label> <br /> <input id="ime_areaLink" name="areaLink" style="width:10em" onchange="ime_saveArea()" /> <br /> <label for="ime_areaTitle"><span class="ime_t_linktitle">Link title</span> (<span class="ime_t_optional">optional</span>)</label> <br /> <input id="ime_areaTitle" name="areaTitle" style="width:10em" onchange="ime_saveArea()" /> </div> <div id="imePropsRect" style="float:left;margin:0.5ex;padding:0 1ex 1ex;display:none"> <label for="ime_areaRectLeft" class="ime_t_rectleft">Left</label>/<label for="ime_areaRectTop" class="ime_t_recttop">Top</label> <br /> <input id="ime_areaRectLeft" name="areaRectLeft" style="width:4em" onchange="ime_saveArea()" /> <input id="ime_areaRectTop" name="areaRectTop" style="width:4em" onchange="ime_saveArea()" /> <span class="ime_t_rectchoose1">Select with left mouse button</span> <br/> <label for="ime_areaRectRight" class="ime_t_rectright">Right</label>/<label for="ime_areaRectBottom" class="ime_t_rectbottom">Bottom</label> <br /> <input id="ime_areaRectRight" name="areaRectRight" style="width:4em" onchange="ime_saveArea()" /> <input id="ime_areaRectBottom" name="areaRectBottom" style="width:4em" onchange="ime_saveArea()" /> <span class="ime_t_rectchoose2">Select with right mouse button</span> </div> <div id="imePropsCircle" style="float:left;margin:0.5ex;padding:0 1ex 1ex;display:none"> <label class="ime_t_position">Position</label> <br /> <input name="areaCircleX" style="width:4em" onchange="ime_saveArea()" /> <input name="areaCircleY" style="width:4em" onchange="ime_saveArea()" /> <span class="ime_t_circlechoose1">Select with left mouse button</span> <br /> <label for="ime_areaCircleRadius" class="ime_t_radius">Radius</label> <br /> <input id="ime_areaCircleRadius" name="areaCircleRadius" style="width:4em" onchange="ime_saveArea()" /> <span class="ime_t_circlechoose2">Select with right mouse button</span> </div> <div id="imePropsPoly" style="float:left;margin:0.5ex;padding:0 1ex 1ex;display:none"> <label class="ime_t_coordinates">Coordinates</label> <br /> <p id="imePropsPolyCoords" style="font-size:0.8em;max-width:20em;"></p> <a href="javascript:ime_deletePolyCoords()" style="padding:1px;background:white;color:darkblue" class="ime_t_deletecoordinates">Delete all coordinates</a> <br /> <span class="ime_t_polychoose">Add new corner with left mouse button</span> </div> <div style="clear:both"></div> <a href="javascript:ime_deleteArea()" style="padding:1px;background:white;color:darkblue" class="ime_t_deletearea">Delete selected area</a> </div> <div style="clear:both"></div> </fieldset> <div style="clear:both"></div> <fieldset style="margin:0 0.5ex 0.5ex;padding:0 1ex 1ex"> <legend class="ime_t_preferences">General preferences</legend> <div style="float:left;margin-right:1em;"> <label for="ime_imageDescription" class="ime_t_imagedescription">Image description</label> <br /> <input id="ime_imageDescription" name="imageDescription" onchange="ime_updateResult()" /> </div> <div style="float:left"> <label style="display:block" class="ime_t_infolinkposition">Position of information link</label> <div style="float:left"> <input type="radio" name="imageDescriptionPos" value="bottom-left" onchange="ime_updateResult()" checked="checked" id="ime_imageDescriptionPos_bottomleft" /><label for="ime_imageDescriptionPos_bottomleft"><span class="ime_t_bottomleft">Bottom left</span> (<span class="ime_t_default">default</span>)</label> </div> <div style="float:left"> <input type="radio" name="imageDescriptionPos" value="bottom-right" onchange="ime_updateResult()" id="ime_imageDescriptionPos_bottomright" /><label for="ime_imageDescriptionPos_bottomright" class="ime_t_bottomright">Bottom right</label> </div> <div style="float:left"> <input type="radio" name="imageDescriptionPos" value="top-left" onchange="ime_updateResult()" id="ime_imageDescriptionPos_topleft" /><label for="ime_imageDescriptionPos_topleft" class="ime_t_topleft">Top left</label> </div> <div style="float:left"> <input type="radio" name="imageDescriptionPos" value="top-right" onchange="ime_updateResult()" id="ime_imageDescriptionPos_topright" /><label for="ime_imageDescriptionPos_topright" class="ime_t_topright">Top right</label> </div> <div style="float:left"> <input type="radio" name="imageDescriptionPos" value="none" onchange="ime_updateResult()" id="ime_imageDescriptionPos_none" /><label for="ime_imageDescriptionPos_none" class="ime_t_nolink">No link</label> </div> </div> <div style="clear:both"></div> </fieldset> <fieldset style="margin:0.5ex;padding:0 1ex 1ex"> <legend class="ime_t_importareas">Import areas from wikicode</legend> <a href="javascript:ime_showImport()" style="padding:1px;background:white;color:darkblue" id="imeImportShow"><span class="ime_t_showtextbox">Show text box</span> &gt;</a> <a href="javascript:ime_hideImport()" style="padding:1px;background:white;color:darkblue;display:none" id="imeImportHide"><span class="ime_t_hidetextbox">Hide text box</span> &lt;</a> <div id="imeImport" style="display:none"> <textarea name="importText" style="width:100%;margin:0;height:10em;display:block"></textarea> <a href="javascript:ime_importLines()" style="padding:1px;background:white;color:darkblue" class="ime_t_import">Import</a> </div> </fieldset> <fieldset style="margin:0.5ex;padding:0 1ex 1ex"> <legend class="ime_t_generatedwikicode">Generated wikicode</legend> <a href="javascript:ime_showResult()" style="padding:1px;background:white;color:darkblue" id="imeResultShow"><span class="ime_t_showwikicode">Show wikicode</span> &gt;</a> <a href="javascript:ime_hideResult()" style="padding:1px;background:white;color:darkblue;display:none" id="imeResultHide"><span class="ime_t_hidewikicode">Hide wikicode</span> &lt;</a> <div> <code id="imeResult" style="display:block;line-height:1.2em"></code> </div> </fieldset> </fieldset></form>`;

Latest revision as of 17:40, 22 July 2021

/*
	Copyright (c) 2007-2013 Peter Schlömer

	Released under the following licenses (to make reuse in other Wikis
	easier):

	GNU General Public License (GPL), version 2
	GNU Free Documentatin Licence (GFDL), version 1.2 or later
	Creative Commons Attribution ShareAlike (CC-by-sa), version 2 or later
*/

// Compatibility layer for old versions of MediaWiki
if (mw === undefined) mw = {};
if (mw.config === undefined) mw.config = {};
if (mw.config.get === undefined) {
    mw.config.get = function(key) {
        this[key];
    };
}
if (mw.loader === undefined) mw.loader = {};
if (mw.loader.load === undefined) mw.loader.load = importScriptURI;

/*
	Imports
*/

// Default error message, will be overwritten if translation is loaded
var ime_translations = new Array();
ime_translations['error_imagenotfound'] = 'ImageMapEdit: Could not find image in page structure.';

/*
	Global variables
*/
var ime_areas = Array();
var ime_currentlyEditing = -1;
var ime_width;
var ime_height;
var ime_scale;

/*
	Start Initialization if this is an image page and there actually is an image
*/
$(document).ready(function() {
    // Determine whether we are on an image page. Namespace must be 6 and action view
    if (mw.config.get('wgNamespaceNumber') == 6 && mw.config.get('wgAction') == 'view') {

        // If we can a div with id file, we initialize
        if (document.getElementById('file')) {
            $.getScript('//code.jquery.com/ui/1.12.1/jquery-ui.js').done(function() {
                if (mw.config.get('wgUserLanguage') === 'de') {
                    ime_translations = {
                        'error_imagenotfound': 'ImageMapEdit: Konnte Bild in der Seitenstruktur nicht finden.',
                        'bottomleft': 'Links unten',
                        'bottomright': 'Rechts unten',
                        'circle': 'circle (Kreis)',
                        'circlechoose1': 'Auswahl mit linker Maustaste',
                        'circlechoose2': 'Auswahl mit rechter Maustaste',
                        'coordinates': 'Koordinaten',
                        'default': 'Standard',
                        'deletearea': 'Ausgewählten Bereich löschen',
                        'deletecoordinates': 'Alle Koordinaten löschen',
                        'editarea': 'Bereich bearbeiten',
                        'generatedwikicode': 'Erstellter Wikicode',
                        'hidetextbox': 'Eingabefeld verstecken',
                        'hidewikicode': 'Wikicode verstecken',
                        'imagedescription': 'Bildbeschreibung',
                        'import': 'Importieren',
                        'importareas': 'Bereiche aus Wikicode importieren',
                        'infolinkposition': 'Position des Info-Links',
                        'linktarget': 'Linkziel',
                        'linktitle': 'Linktitel',
                        'newarea': 'Neuen Bereich erstellen',
                        'nolink': 'Kein Link',
                        'optional': 'optional',
                        'poly': 'poly (Polygon)',
                        'polychoose': 'Hinzufügen neuer Punkte mit linker Maustaste',
                        'position': 'Position',
                        'preferences': 'Allgemeine Einstellungen',
                        'radius': 'Radius',
                        'rect': 'rect (Rechteck)',
                        'rectbottom': 'unten',
                        'rectchoose1': 'Auswahl mit linker Maustaste',
                        'rectchoose2': 'Auswahl mit rechter Maustaste',
                        'rectleft': 'Links',
                        'rectright': 'Rechts',
                        'recttop': 'oben',
                        'showtextbox': 'Eingabefeld anzeigen',
                        'showwikicode': 'Wikicode anzeigen',
                        'topleft': 'Links oben',
                        'topright': 'Rechts oben'
                    };

                }

                ime_init1();
            });
        }
    }
});

/*
	Create a new div element object with an id.
*/
function ime_htmlNewDiv(id) {
    var div = document.createElement('div');
    if (id) div.id = id;
    return div;
}

/*
	Initialization, part 1: Tries to find image and uses a XMLHttpRequest
	to download information about the image. When this is done (it's an
	asynchronous request) show a link to load the rest of ImageMapEdit
	using ime_init2().
*/
function ime_init1() {
    var divFile = document.getElementById('file');
    if (!divFile) {
        ime_error(ime_translations['error_imagenotfound'] + ' (ime_init1,divFile=null)');
        return;
    }

    var a = ime_findATag(divFile);
    if (!a) {
        ime_error(ime_translations['error_imagenotfound'] + ' (ime_init1,a=null)');
        return;
    }

    var img = a.firstChild;
    if (!img) {
        ime_error(ime_translations['error_imagenotfound'] + ' (ime_init1,img=null)');
        return;
    }

    var url = mw.config.get('wgScriptPath') + '/api.php?format=json&action=query&prop=imageinfo&iiprop=size&titles=' + mw.config.get('wgPageName');

    $.get(url, function(data) {
        if (typeof data.query.pages != "undefined") {
            imageProperties = data.query.pages[Object.keys(data.query.pages)[0]];
            ime_width = imageProperties.imageinfo[0].width;
            ime_height = imageProperties.imageinfo[0].height;

            ime_scale = img.width / ime_width;

            // Show 'show ImageMapEdit' button now
            var a = document.createElement('a');
            a.id = 'imeLink';
            a.href = 'javascript:ime_init2()';
            a.style.display = 'block';
            a.appendChild(document.createTextNode('ImageMapEdit >'));
            document.getElementById('file').appendChild(a);
        }
    });
}

/*
	Initialization, part 2: Triggered by an external link. Does some moving
	around of the image in the logical structure of the page, then hides the
	link and finally puts the HTML code in place.
*/
function ime_init2() {

    // Remove UI that might interfere with this code
    ime_removeOtherUIElements();

    var divFile = document.getElementById('file');
    var tempNode = divFile.firstChild;
    var a = ime_findATag(tempNode);
    var img = a.firstChild;

    var divImeContainer = ime_htmlNewDiv('imeContainer');
    divImeContainer.style.position = 'relative';

    // Move image from within link to outside
    a.removeChild(img);
    divFile.insertBefore(divImeContainer, tempNode);
    divFile.removeChild(tempNode);
    // Fix for rtl wikis, thanks to hewiki user "קיפודנחש"
    divFile.style.direction = 'ltr';

    img.id = 'imeImg';
    img.style.zIndex = 99;
    img.style.border = 'none';
    img.style.opacity = '0.75';
    img.style.filter = 'alpha(opacity=75)'; // IE

    // Internet Explorer needs this differently
    if (typeof(navigator.userAgent) != 'undefined' && navigator.userAgent.match('/MSIE/')) {
        divImeContainer.style.overflow = 'none';
    } else {
        divImeContainer.style.overflow = 'auto';
    }

    var divImePreview = ime_htmlNewDiv('imePreview');
    divImePreview.style.position = 'absolute';
    divImePreview.style.top = '0';
    divImePreview.style.left = '0';
    divImePreview.style.width = img.width + 'px';
    divImePreview.style.height = img.height + 'px';
    divImePreview.zIndex = 0;

    divImeContainer.appendChild(divImePreview);
    divImeContainer.appendChild(img);

    var divIme = ime_htmlNewDiv('ime');
    divFile.appendChild(divIme);

    // Hide the link now
    document.getElementById('imeLink').style.display = 'none';

    // Disable image context menu so right click can be used for events
    img.oncontextmenu = ime_eventDummy;


    divIme.innerHTML = ime_templateHtml;

    // Translate texts
    ime_hideResult();
    ime_translate();
    //A button gets created. On click, it gets the input from the #imeResult ID and posts it on the '/ImageMap' page. 
    //After posting, it forwards the user to the '/ImageMap' page.
    var clicked = false;
    var btn = document.createElement("button");
    btn.innerHTML = "Speichern";
    btn.onclick = function() {
        if ($('#imeResult').length) {
            clicked = false;
            var rep = $('#imeResult').html();
            var rep1 = rep.replaceAll("<br>", "\n");
            var rep2 = rep1.replaceAll("&lt;", "<");
            var rep3 = rep2.replaceAll("&gt;", ">");
            var finalstr = '{{ImageMap |map=' + rep3 + ' }}'
            var params = {
                    action: 'edit',
                    title: $('#firstHeading').text() + '/ImageMap',
                    text: finalstr,
                    format: 'json'
                },
                api = new mw.Api();

            api.postWithToken('csrf', params).done(function(data) {
                window.location.replace("/wiki/" + $('#firstHeading').text() + "/ImageMap");
            });
        }
    };
    document.getElementById("file").appendChild(btn);

    //A button gets created. 
    var but = document.createElement("button");
    but.innerHTML = "Laden";
    but.onclick = function() {
        if (!clicked) {
            //Gets the wiki text from the '/ImageMap' page  and imports it.

            $.getJSON("/w/api.php?action=query&prop=revisions&titles=" + $('#firstHeading').text() + "%2FImageMap&rvprop=content&formatversion=2&format=json", function(data) {
                var daten = data;
                if (daten.query.pages[0].hasOwnProperty("missing")) {
                    if (daten.query.pages[0].missing === true) {
                        return;
                    }
                }
                var aus = daten.query.pages[0].revisions[0].content;
                $('textarea[name="importText"]').html(aus);
                ime_importLines();
                var clear = "";
                $('textarea[name="importText"]').html(clear);
            }).fail(function() {
                return;
            });

            //Gets the image width and the image position from the '/ImageMap' page and updates the created ImageMap code.

            $.getJSON("/w/api.php?action=query&prop=revisions&titles=" + $('#firstHeading').text() + "%2FImageMap&rvprop=content&formatversion=2&format=json", function(data) {
                var data1 = data;
                if (data1.query.pages[0].hasOwnProperty("missing")) {
                    if (data1.query.pages[0].missing === true) {
                        return;
                    }
                }
                var out = data1.query.pages[0].revisions[0].content;
                var patt = /(?<=<imagemap>\n).*/;
                var string = out.match(patt) + '';
                var stringSplit = string.split('|');
                var stringJoin = [stringSplit.shift(), stringSplit.join('|')]
                $('input#ime_imageDescription').val(stringJoin[1]);
                ime_updateResult();
            }).fail(function() {
                return;
            });
            clicked = true;
        }
    };


    document.getElementById("file").appendChild(but);




}

/*
	Translate the user interface to the specified language.
*/
function ime_translate() {
    if (ime_translations) {
        for (var i in ime_translations) {
            var elements = ime_getElementsByClassName('ime_t_' + i);
            if (elements.length > 0) {
                var text = ime_translations[i];;
                for (var j = 0; j < elements.length; j++) {
                    elements[j].innerHTML = text;
                }
            }
        }
    }
}

/*
	Finds all elements in the current document with the specified class.
*/
function ime_getElementsByClassName(className) {
    // Hopefully the browser supports this natively
    if (document.getElementsByClassName) {
        return document.getElementsByClassName(className);
    }

    // Otherwise use the function defined by MediaWiki
    return getElementsByClassName(document, '*', className)
}

/*
	Display an error message, either by putting it on the page or - if the
	place to put it does not exist - by showing an alert box.
*/
function ime_error(message) {
    var jqFile = $('#file');
    var jqIme = $('#ime');

    if (jqFile.length !== 0) {
        var jqImeError = $('<p/>')
            .css({
                'color': 'darkred',
                'background': 'white',
                'border': '1px solid darkred',
                'padding': '1ex'
            })
            .text(message)

        if (jqIme !== 0) {
            jqIme.before(jqImeError);
        } else {
            jqImeError.appendTo(jqFile);
        }
    } else {
        window.alert(message);
    }
}

/*
	Dummy function to intercept events
*/
function ime_eventDummy(e) {
    e.cancelBubble = true;
    return false;
}

/*
	Function to define an object containing rect(angle) coordinates.
*/
function ime_RectCoord(x1, y1, x2, y2) {
    this.left = x1;
    this.top = y1;
    this.right = x2;
    this.bottom = y2;
}

/*
	Function to define an object containing circle coordinates.
*/
function ime_CircleCoord(x, y, r) {
    this.x = x;
    this.y = y;
    this.radius = r;
}

/*
	Function to define an object containing poly(gon) coordinates.
*/
function ime_PolyCoord(x, y, r) {
    this.points = Array();
}

/*
	Function to define an object storing info on a clickable area for the
	imagemap.
*/
function ime_Area(shape) {
    if (shape == 'rect') {
        this.shape = 'rect';
        this.coords = new ime_RectCoord(0, 0, 0, 0);
    } else if (shape == 'circle') {
        this.shape = 'circle';
        this.coords = new ime_CircleCoord(0, 0, 20);
    } else {
        this.shape = 'poly';
        this.coords = new ime_PolyCoord();
    }
    this.link = '';
    this.title = '';
}

/*
	Browser invariant function to get the event "behind" the object passed
	to event handlers.
*/
function ime_getEvent(e) {
    if (e) {
        return e;
    } else {
        return window.event;
    }
}

function ime_eventGetX(e) {
    if (typeof(e.layerX) != 'undefined') {
        return Math.round(e.layerX / ime_scale);
    }
    if (typeof(e.offsetX) != 'undefined') {
        return Math.round(e.offsetX / ime_scale);
    } else {
        return Math.round(e.x / ime_scale);
    }
}

function ime_eventGetY(e) {
    if (typeof(e.layerY) != 'undefined') {
        return Math.round(e.layerY / ime_scale);
    }
    if (typeof(e.offsetY) != 'undefined') {
        return Math.round(e.offsetY / ime_scale);
    } else {
        return Math.round(e.y / ime_scale);
    }
}

function ime_eventGetButton(e) {
    if (typeof(e.which) != 'undefined') {
        return e.which;
    } else {
        return e.button;
    }
}

function ime_mouseEventClear() {
    var img = document.getElementById('imeImg');
    img.onmousedown = null;
    img.style.cursor = '';
}

function ime_mouseEventSet(func) {
    var img = document.getElementById('imeImg');
    img.onmousedown = func;
    img.style.cursor = 'url("https://testwiki.kiprobatt.de/w/img_auth.php/f/fb/Crosshair.png"), crosshair';
}

function ime_eventRect(e) {
    e = ime_getEvent(e);
    var button = ime_eventGetButton(e);
    if (button == 1) {
        document.ime.areaRectLeft.value = ime_eventGetX(e);
        document.ime.areaRectTop.value = ime_eventGetY(e);
    } else if (button == 2 || button == 3) {
        document.ime.areaRectRight.value = ime_eventGetX(e);
        document.ime.areaRectBottom.value = ime_eventGetY(e);
    }
    ime_saveArea();
    return false;
}

function ime_eventCircle(e) {
    e = ime_getEvent(e);
    var button = ime_eventGetButton(e);
    if (button == 1) {
        document.ime.areaCircleX.value = ime_eventGetX(e);
        document.ime.areaCircleY.value = ime_eventGetY(e);
    } else if (button == 2 || button == 3) {
        var a = (ime_eventGetX(e) - parseInt(document.ime.areaCircleX.value));
        var b = (ime_eventGetY(e) - parseInt(document.ime.areaCircleY.value));
        document.ime.areaCircleRadius.value = Math.round(Math.sqrt(a * a + b * b));
    }
    ime_saveArea();
    return false;
}

function ime_eventPoly(e) {
    e = ime_getEvent(e);
    var button = ime_eventGetButton(e);
    if (button == 1) {
        area = ime_areas[ime_currentlyEditing];
        area.coords.points.push(ime_eventGetX(e));
        area.coords.points.push(ime_eventGetY(e));
        ime_saveArea();
    }
    return false;
}

function ime_newArea(shape) {
    var area = new ime_Area(shape);
    area.shape = shape;
    ime_areas.push(area);

    ime_currentlyEditing = ime_areas.length - 1;
    ime_updateAreas();
    ime_editArea(ime_currentlyEditing);
    autoComplete();
}
//Gets called by ime_newArea() and ime_editArea() functions.
function autoComplete() {
    const search = document.getElementById('ime_areaLink');
    $('#ime_areaLink').parent('div').addClass('ui-widget');
    var firstTimeTrigger = false;
    var firstTimeTriggerCat = false;
    $('#ime_areaLink').parent('div').addClass('ui-autocomplete');
    var searchPages = async (searchText, searchCat) => {

        var categories;
        /*When the linkcategory field is empty, this code does the autocomplete in the linktarget field with all pages.*/
        if (searchCat.length === 0) {
            categories = [];
            var pages;
            if (searchText.length === 0) {
                pages = [];
            } else {
                const res = await fetch('/w/api.php?action=pfautocomplete&substr=' + searchText + '&namespace=Main&format=json');
                pages = await res.json();

                var allTitles = pages.pfautocomplete.map(function(item) {
                    return item['title'];
                });

                $("#ime_areaLink").autocomplete({
                    source: allTitles
                });
                $('ul.ui-autocomplete').css('list-style', 'none');
                if (!firstTimeTrigger) {
                    firstTimeTrigger = true;
                    search.dispatchEvent(new Event('input'));
                }
            }
        } else {
            /*When the linkcategory field is not empty, this else is called and at first it creates an autocomplete for the linkcategory field.*/
            var get = await $.getJSON("/w/api.php?action=query&list=allcategories&format=json");
            var categories = await get.query;
            var allCategories = categories.allcategories.map(function(item) {
                return item['*'];
            });

            $("#ime_linkCategory").autocomplete({
                source: allCategories
            });
            $('ul.ui-autocomplete').css('list-style', 'none');
            if (!firstTimeTriggerCat) {
                firstTimeTriggerCat = true;
                category.dispatchEvent(new Event('input'));
            }



            var pages;
            /*When the linkcategory field is not empty, this code creates an autocomplete for the linktarget field with the given category from the linkcategory field.*/
            if (searchText.length === 0) {
                pages = [];
            } else {
                const res = await fetch('/w/api.php?action=pfautocomplete&substr=' + searchText + '&category=' + searchCat + '&namespace=Main&format=json');
                pages = await res.json();

                var allTitles = pages.pfautocomplete.map(function(item) {
                    return item['title'];
                });

                $("#ime_areaLink").autocomplete({
                    source: allTitles
                });
                $('ul.ui-autocomplete').css('list-style', 'none');
                if (!firstTimeTrigger) {
                    firstTimeTrigger = true;
                    search.dispatchEvent(new Event('input'));
                }
            }
        }
    }

    search.addEventListener('input', () => searchPages(search.value, category.value));



    //This code creates the input field for the linkcategory.
    if (!$('#ime_linkCategory').length) {
        var br = document.createElement("br");
        $('#ime_areaLink').parent().append(br);
        var lbl = document.createElement("label");
        lbl.setAttribute("for", "ime_linkCategory");
        lbl.setAttribute("id", "ime_linkCategoryLabel");
        $('#ime_areaLink').parent().append(lbl);
        var spn = document.createElement("span");
        spn.setAttribute("value", "Linkkategorie");
        spn.innerHTML = 'Linkkategorie';
        document.getElementById("ime_linkCategoryLabel").appendChild(spn);
        var br1 = document.createElement("br");
        $('#ime_areaLink').parent().append(br1);
        var inpt = document.createElement("INPUT");
        inpt.setAttribute("type", "text");
        inpt.setAttribute("id", "ime_linkCategory");
        inpt.setAttribute("style", "width:10em");
        //document.getElementById("ime_areaLink")[0].appendChild(inpt);
        $('#ime_areaLink').parent().append(inpt);
    }
    const category = document.getElementById('ime_linkCategory');
    category.addEventListener('input', () => searchPages(search.value, category.value));
}



function ime_updateAreas() {
    ime_updateSelectArea();
    ime_updateMap();
    ime_updateResult();
}

function ime_updateResult() {
    var arr = document.ime.imageDescriptionPos;
    var imageDescriptionPos = arr[0].value;
    for (var i = 1; i < arr.length; i++) {
        if (arr[i].checked) {
            imageDescriptionPos = arr[i].value;
            break;
        }
    }

    var result = Array();
    result.push('<imagemap>');
    result.push(mw.config.get('wgPageName') + '|' + document.ime.imageDescription.value);
    result.push('');
    for (var i = 0; i < ime_areas.length; i++) {
        var coords = ime_areas[i].coords;
        var s = '';
        if (ime_areas[i].shape == 'rect') {
            s = coords.left + ' ' + coords.top + ' ' + coords.right + ' ' + coords.bottom;
        } else if (ime_areas[i].shape == 'circle') {
            s = coords.x + ' ' + coords.y + ' ' + coords.radius;
        } else if (ime_areas[i].shape == 'poly') {
            s = coords.points.join(' ');
        }
        result.push(ime_areas[i].shape + ' ' + s + ' [[' + ime_areas[i].link + (ime_areas[i].title ? '|' + ime_areas[i].title : '') + ']]');
    }
    result.push('');
    result.push('desc ' + imageDescriptionPos);
    result.push('</imagemap>');

    var preResult = document.getElementById('imeResult');

    while (preResult.lastChild) {
        preResult.removeChild(preResult.lastChild);
    }

    for (var i = 0; i < result.length; i++) {
        preResult.appendChild(document.createTextNode(result[i]));
        preResult.appendChild(document.createElement('br'));
    }
}

function ime_updateMap() {
    var preview = document.getElementById('imePreview');
    var img = document.getElementById('imeImg');

    // Remove areas from map which are out of range
    for (var i = 0; i < preview.childNodes.length; i++) {
        var child = preview.childNodes[i];
        var id = parseInt(child.id.substring(10));
        if (id >= ime_areas.length) {
            preview.removeChild(child);
            i--;
        }
    }

    for (var i = 0; i < ime_areas.length; i++) {
        // Get existing DIV
        var area = ime_areas[i];
        var div = document.getElementById('imePreview' + i);

        // If it does not exist exists, create a new one and set style
        if (!div) {
            var div = ime_htmlNewDiv('imePreview' + i)
            preview.appendChild(div);
            div.style.zIndex = 0;
            div.style.position = 'absolute';
            div.style.opacity = 0.5;
            div.style.filter = 'alpha(opacity=50)';
        }

        var coords = area.coords;
        if (area.shape == 'rect') {
            div.className = 'previewRect';
            // Only if valid coordinates were given, draw
            if (coords.left < coords.right && coords.top < coords.bottom) {
                div.style.left = Math.round(ime_scale * coords.left) + 'px';
                div.style.top = Math.round(ime_scale * coords.top) + 'px';
                div.style.width = (Math.round(ime_scale * coords.right) - Math.round(ime_scale * coords.left)) + 'px';
                div.style.height = (Math.round(ime_scale * coords.bottom) - Math.round(ime_scale * coords.top)) + 'px';
            } else {
                div.style.left = '0';
                div.style.top = '0';
                div.style.width = '0';
                div.style.height = '0';
            }
        } else if (area.shape == 'circle') {
            div.className = 'previewCircle';
            div.style.backgroundRepeat = 'no-repeat';
            var left = Math.round(ime_scale * coords.x) - Math.round(ime_scale * coords.radius);
            var top = Math.round(ime_scale * coords.y) - Math.round(ime_scale * coords.radius);
            var size = Math.round(ime_scale * coords.radius * 2) + 1;

            div.style.left = left + 'px';
            div.style.top = top + 'px';

            if (left + size > img.width) {
                div.style.width = (img.width - left) + 'px';
            } else {
                div.style.width = size + 'px';
            }

            if (top + size > img.height) {
                div.style.height = (img.height - top) + 'px';
            } else {
                div.style.height = size + 'px';
            }
        } else if (area.shape == 'poly') {
            // Determine maximum coordinates (this is how big the image is)
            div.className = 'previewPoly';
            div.style.backgroundRepeat = 'no-repeat';

            var points = coords.points;
            var minX = 0;
            var maxX = 0;
            var minY = 0;
            var maxY = 0;
            if (points.length > 0) {
                minX = points[0];
                maxX = points[0];
                minY = points[1];
                maxY = points[1];
                for (var j = 2; j < points.length; j += 2) {
                    var x = points[j];
                    var y = points[j + 1];
                    if (x < minX) minX = x;
                    if (x > maxX) maxX = x;
                    if (y < minY) minY = y;
                    if (y > maxY) maxY = y;
                }
            }

            div.style.left = Math.round(ime_scale * minX) + 'px';
            div.style.top = Math.round(ime_scale * minY) + 'px';
            div.style.width = (Math.round(ime_scale * maxX) - Math.round(ime_scale * minX)) + 'px';
            div.style.height = (Math.round(ime_scale * maxY) - Math.round(ime_scale * minY)) + 'px';
        }
    }

    ime_highlightMap();
}

function ime_highlightMapCircle(div, radius, highlight) {
    var canvas = document.createElement('canvas');
    canvas.width = radius * 2;
    canvas.height = radius * 2;



    var ctx = canvas.getContext("2d");
    ctx.beginPath();
    ctx.arc(radius, radius, radius, 0, 2 * Math.PI);
    if (highlight) {
        ctx.fillStyle = 'red';
        ctx.fill();
        ctx.strokeStyle = 'red';
    } else {
        ctx.fillStyle = 'black';
        ctx.fill();
        ctx.strokeStyle = 'black';
    }
    ctx.stroke();
    ctx.closePath();

    var meinBild = canvas.toDataURL('image/png', 1.0);

    var background = "url('" + meinBild + "')";
    if (div.style.background != background) {
        div.style.background = background;
        div.style.backgroundRepeat = "no-repeat";
    }
}

function ime_highlightMapPoly(div, points, highlight) {
    var minX = 0;
    var minY = 0;
    var maxX = 0;
    var maxY = 0;
    if (points.length > 0) {
        minX = points[0];
        minY = points[1];
        for (var j = 2; j < points.length; j += 2) {
            var x = points[j];
            var y = points[j + 1];
            if (x < minX) minX = x;
            if (y < minY) minY = y;
        }
    }
    if (points.length > 0) {
        maxX = points[0];
        maxY = points[1];
        for (var j = 2; j < points.length; j += 2) {
            var x = points[j];
            var y = points[j + 1];
            if (x > maxX) maxX = x;
            if (y > maxY) maxY = y;
        }
    }
    var convpoints = Array();
    for (var j = 0; j < points.length; j += 2) {
        convpoints[j] = Math.round(ime_scale * points[j]) - Math.round(ime_scale * minX);
        convpoints[j + 1] = Math.round(ime_scale * points[j + 1]) - Math.round(ime_scale * minY);
    }
    var canvas = document.createElement('canvas');
    canvas.width = maxX + 1;
    canvas.height = maxY + 1;
    var ctx = canvas.getContext("2d");
    if (highlight) {
        ctx.save();
        ctx.beginPath();
        ctx.moveTo(convpoints.shift(), convpoints.shift());
        while (convpoints.length) {
            ctx.lineTo(convpoints.shift(), convpoints.shift());
        }
        ctx.closePath();
        ctx.strokeStyle = 'red';
        ctx.stroke();
        ctx.fillStyle = 'red'
        ctx.fill();
        ctx.closePath();
        ctx.restore();
    } else {
        ctx.save();
        ctx.beginPath();
        ctx.moveTo(convpoints.shift(), convpoints.shift());
        while (convpoints.length) {
            ctx.lineTo(convpoints.shift(), convpoints.shift());
        }
        ctx.closePath();
        ctx.strokeStyle = 'black';
        ctx.stroke();
        ctx.fillStyle = 'black'
        ctx.fill();
        ctx.closePath();
        ctx.restore();
    }
    var meinBild = canvas.toDataURL('image/png', 1.0);

    var background = "url('" + meinBild + "')";

    if (div.style.background != background) {
        div.style.background = background;
        div.style.backgroundRepeat = "no-repeat";
    }
}

function ime_highlightMap() {
    for (var i = 0; i < ime_areas.length; i++) {
        var div = document.getElementById('imePreview' + i);
        var area = ime_areas[i];
        if (div && area) {
            if (i == ime_currentlyEditing) {
                div.style.opacity = '0.9';
                div.style.filter = 'alpha(opacity=90)'; // IE
            } else {
                div.style.opacity = '0.75';
                div.style.filter = 'alpha(opacity=75)'; // IE
            }
            if (area.shape == 'rect') {
                var backgroundColor = (i == ime_currentlyEditing) ? 'red' : 'black';
                if (div.style.backgroundColor != backgroundColor) div.style.backgroundColor = backgroundColor;
            } else if (area.shape == 'circle') {
                ime_highlightMapCircle(div, area.coords.radius, (i == ime_currentlyEditing));
            } else if (area.shape == 'poly') {
                ime_highlightMapPoly(div, area.coords.points, (i == ime_currentlyEditing));
            }
        }
    }
}

function ime_updateSelectArea() {
    var selectArea = document.ime.area;

    while (selectArea.childNodes.length > 0) {
        selectArea.removeChild(selectArea.lastChild);
    }

    for (var i = 0; i < ime_areas.length; i++) {
        var option = document.createElement('option');
        var area = ime_areas[i];
        option.value = i;
        while (option.childNodes.length > 0) {
            option.removeChild(option.lastChild);
        }
        var text = (area.title ? area.title : area.link) + ' [' + area.shape + ']';
        option.appendChild(document.createTextNode(text));
        if (i == ime_currentlyEditing) {
            option.selected = 'selected';
        }
        selectArea.appendChild(option);
    }
}

function ime_editArea(index) {
    document.getElementById('imeProps').style.display = 'none';

    var area = ime_areas[index];

    if (area) {
        ime_currentlyEditing = index;

        document.getElementById('imeProps').style.display = '';
        document.getElementById('imePropsRect').style.display = 'none';
        document.getElementById('imePropsCircle').style.display = 'none';
        document.getElementById('imePropsPoly').style.display = 'none';
        ime_mouseEventClear();

        if (area.shape == 'rect') {
            document.getElementById('imePropsRect').style.display = '';
            ime_mouseEventSet(ime_eventRect);
        } else if (area.shape == 'circle') {
            document.getElementById('imePropsCircle').style.display = '';
            ime_mouseEventSet(ime_eventCircle);
        } else if (area.shape == 'poly') {
            document.getElementById('imePropsPoly').style.display = '';
            ime_mouseEventSet(ime_eventPoly);
        }

        document.ime.areaLink.value = area.link;
        document.ime.areaTitle.value = area.title;

        var coords = area.coords;
        if (area.shape == 'rect') {
            document.ime.areaRectLeft.value = coords.left;
            document.ime.areaRectTop.value = coords.top;
            document.ime.areaRectRight.value = coords.right;
            document.ime.areaRectBottom.value = coords.bottom;
        } else if (area.shape == 'circle') {
            document.ime.areaCircleX.value = coords.x;
            document.ime.areaCircleY.value = coords.y;
            document.ime.areaCircleRadius.value = coords.radius;
        } else if (area.shape == 'poly') {
            var propsPolyCoords = document.getElementById('imePropsPolyCoords');
            if (propsPolyCoords.childNodes.length > 0) propsPolyCoords.removeChild(propsPolyCoords.lastChild);
            propsPolyCoords.appendChild(document.createTextNode(area.coords.points.join(", ")));
        }

        ime_highlightMap();
    }
    autoComplete();
}

function ime_deletePolyCoords() {
    ime_areas[ime_currentlyEditing].coords.points = Array();
    ime_saveArea();
}

function ime_saveArea() {
    var area = ime_areas[ime_currentlyEditing];
    area.link = document.ime.areaLink.value;
    area.title = document.ime.areaTitle.value;

    var coords = area.coords;
    if (area.shape == 'rect') {
        coords.left = parseInt(document.ime.areaRectLeft.value);
        coords.top = parseInt(document.ime.areaRectTop.value);
        coords.right = parseInt(document.ime.areaRectRight.value);
        coords.bottom = parseInt(document.ime.areaRectBottom.value);
    } else if (area.shape == 'circle') {
        if (parseInt(document.ime.areaCircleRadius.value) < 0) document.ime.areaCircleRadius.value = 0;
        coords.x = parseInt(document.ime.areaCircleX.value);
        coords.y = parseInt(document.ime.areaCircleY.value);
        coords.radius = parseInt(document.ime.areaCircleRadius.value);
    } else if (area.shape == 'poly') {
        var propsPolyCoords = document.getElementById('imePropsPolyCoords');
        if (propsPolyCoords.childNodes.length > 0) propsPolyCoords.removeChild(propsPolyCoords.lastChild);
        propsPolyCoords.appendChild(document.createTextNode(coords.points.join(", ")));
    }

    ime_updateAreas();
}

function ime_deleteArea() {
    ime_mouseEventClear();

    // Remove element from ime_areas array
    ime_areas.splice(ime_currentlyEditing, 1);

    // Remove preview div of the deleted area
    var div = document.getElementById('imePreview' + ime_currentlyEditing);
    if (div) {
        div.parentNode.removeChild(div);
    }

    // Move ids of preview divs to fill the hole
    for (var i = ime_currentlyEditing + 1; i < ime_areas.length; i++) {
        div = document.getElementById('imePreview' + i);
        if (div) {
            div.id = 'imePreview' + (i - 1);
        }
    }

    // If we deleted the last area, correct currently editing
    if (ime_currentlyEditing >= ime_areas.length) {
        ime_currentlyEditing = ime_areas.length - 1;
    }

    ime_updateAreas();
    ime_editArea(ime_currentlyEditing);
}

function ime_importLines() {
    var text = document.ime.importText.value;
    var lines = text.split("\n");

    for (var i = 0; i < lines.length; i++) {
        var rectMatch = /rect +(\d+) +(\d+) +(\d+) +(\d+) +\[\[([^|]*)(|(.*))?\]\]/i;
        var circleMatch = /circle +(\d+) +(\d+) +(\d+) +\[\[([^|]*)(|(.*))?\]\]/i;
        var polyMatch = /poly +(.*?) +\[\[([^|]*)(|(.*))?\]\]/i;

        var line = lines[i];

        if (rectMatch.test(line)) {
            var results = rectMatch.exec(line);
            var area = new ime_Area("rect");
            area.coords.left = parseInt(results[1]);
            area.coords.top = parseInt(results[2]);
            area.coords.right = parseInt(results[3]);
            area.coords.bottom = parseInt(results[4]);
            area.link = results[5];
            if (results[6]) area.title = results[6].substring(1);
            ime_areas.push(area);
        } else if (circleMatch.test(line)) {
            var results = circleMatch.exec(line);
            var area = new ime_Area("circle");
            area.coords.x = parseInt(results[1]);
            area.coords.y = parseInt(results[2]);
            area.coords.radius = parseInt(results[3]);
            area.link = results[4];
            if (results[5]) area.title = results[5].substring(1);
            ime_areas.push(area);
        } else if (polyMatch.test(line)) {
            var results = polyMatch.exec(line);
            var area = new ime_Area("poly");
            area.coords.points = results[1].replace(/ +/, " ").split(" ");
            for (var j = 0; j < area.coords.points.length; j++) {
                area.coords.points[j] = parseInt(area.coords.points[j]);
            }
            area.link = results[2];
            if (results[3]) area.title = results[3].substring(1);
            ime_areas.push(area);
        }
    }
    ime_updateAreas();
    ime_hideImport();
}

function ime_showResult() {
    $('#imeResult').show();
    $('#imeResultShow').hide();
    $('#imeResultHide').show();
}

function ime_hideResult() {
    $('#imeResult').hide();
    $('#imeResultShow').show();
    $('#imeResultHide').hide();
}

function ime_showImport() {
    $('#imeImport').show();
    $('#imeImportShow').hide();
    $('#imeImportHide').show();
}

function ime_hideImport() {
    $('#imeImport').hide();
    $('#imeImportShow').show();
    $('#imeImportHide').hide();
}

/*
	Remove all UI elements that might interfere with ImageMapEdit.
*/
function ime_removeOtherUIElements() {
    // Remove all UI elements of the 'annotations' feature used on Wikimedia
    // Commons.
    $('#ImageAnnotationAddButton').remove();
}

/*
	Try to find an <a> tag within the specified HTML document node.
*/
function ime_findATag(node) {
    // We just look at the first child until there is none or it is an <a> tag
    var a = node;
    while (a != null && a.nodeName.toUpperCase() != 'A') {
        a = a.firstChild;
    }
    return a;
}


var ime_templateHtml = `<form name="ime" action=""> <fieldset style="margin:0.5ex;padding:0 1ex 1ex"> <legend>ImageMapEdit</legend> <fieldset style="float:left;margin:0 0.5ex 0.5ex;padding:0 1ex 1ex"> <legend style="padding:0 0.5ex" class="ime_t_newarea">Create new area</legend> <a href="javascript:ime_newArea('rect')" style="padding:1px;background:white;color:darkblue" class="ime_t_rect">rect(angle)</a> <br /> <a href="javascript:ime_newArea('circle')" style="padding:1px;background:white;color:darkblue" class="ime_t_circle">circle</a> <br /> <a href="javascript:ime_newArea('poly')" style="padding:1px;background:white;color:darkblue" class="ime_t_poly">poly(gon)</a> </fieldset> <fieldset style="float:left;margin:0 0.5ex 0.5ex;padding:0 1ex 1ex"> <legend style="padding:0 0.5ex" class="ime_t_editarea">Edit area</legend> <select name="area" size="10" style="float:left;height:10em;margin:0.5ex;width:10em" onclick="ime_editArea(document.ime.area.selectedIndex)"></select> <div id="imeProps" style="float:left;margin:0.5ex;padding:0 1ex 1ex;display:none"> <div style="float:left;margin:0.5ex;padding:0 1ex 1ex"> <label for="ime_areaLink" class="ime_t_linktarget">Link target</label> <br /> <input id="ime_areaLink" name="areaLink" style="width:10em" onchange="ime_saveArea()" /> <br /> <label for="ime_areaTitle"><span class="ime_t_linktitle">Link title</span> (<span class="ime_t_optional">optional</span>)</label> <br /> <input id="ime_areaTitle" name="areaTitle" style="width:10em" onchange="ime_saveArea()" /> </div> <div id="imePropsRect" style="float:left;margin:0.5ex;padding:0 1ex 1ex;display:none"> <label for="ime_areaRectLeft" class="ime_t_rectleft">Left</label>/<label for="ime_areaRectTop" class="ime_t_recttop">Top</label> <br /> <input id="ime_areaRectLeft" name="areaRectLeft" style="width:4em" onchange="ime_saveArea()" /> <input id="ime_areaRectTop" name="areaRectTop" style="width:4em" onchange="ime_saveArea()" /> <span class="ime_t_rectchoose1">Select with left mouse button</span> <br/> <label for="ime_areaRectRight" class="ime_t_rectright">Right</label>/<label for="ime_areaRectBottom" class="ime_t_rectbottom">Bottom</label> <br /> <input id="ime_areaRectRight" name="areaRectRight" style="width:4em" onchange="ime_saveArea()" /> <input id="ime_areaRectBottom" name="areaRectBottom" style="width:4em" onchange="ime_saveArea()" /> <span class="ime_t_rectchoose2">Select with right mouse button</span> </div> <div id="imePropsCircle" style="float:left;margin:0.5ex;padding:0 1ex 1ex;display:none"> <label class="ime_t_position">Position</label> <br /> <input name="areaCircleX" style="width:4em" onchange="ime_saveArea()" /> <input name="areaCircleY" style="width:4em" onchange="ime_saveArea()" /> <span class="ime_t_circlechoose1">Select with left mouse button</span> <br /> <label for="ime_areaCircleRadius" class="ime_t_radius">Radius</label> <br /> <input id="ime_areaCircleRadius" name="areaCircleRadius" style="width:4em" onchange="ime_saveArea()" /> <span class="ime_t_circlechoose2">Select with right mouse button</span> </div> <div id="imePropsPoly" style="float:left;margin:0.5ex;padding:0 1ex 1ex;display:none"> <label class="ime_t_coordinates">Coordinates</label> <br /> <p id="imePropsPolyCoords" style="font-size:0.8em;max-width:20em;"></p> <a href="javascript:ime_deletePolyCoords()" style="padding:1px;background:white;color:darkblue" class="ime_t_deletecoordinates">Delete all coordinates</a> <br /> <span class="ime_t_polychoose">Add new corner with left mouse button</span> </div> <div style="clear:both"></div> <a href="javascript:ime_deleteArea()" style="padding:1px;background:white;color:darkblue" class="ime_t_deletearea">Delete selected area</a> </div> <div style="clear:both"></div> </fieldset> <div style="clear:both"></div> <fieldset style="margin:0 0.5ex 0.5ex;padding:0 1ex 1ex"> <legend class="ime_t_preferences">General preferences</legend> <div style="float:left;margin-right:1em;"> <label for="ime_imageDescription" class="ime_t_imagedescription">Image description</label> <br /> <input id="ime_imageDescription" name="imageDescription" onchange="ime_updateResult()" /> </div> <div style="float:left"> <label style="display:block" class="ime_t_infolinkposition">Position of information link</label> <div style="float:left"> <input type="radio" name="imageDescriptionPos" value="bottom-left" onchange="ime_updateResult()" checked="checked" id="ime_imageDescriptionPos_bottomleft" /><label for="ime_imageDescriptionPos_bottomleft"><span class="ime_t_bottomleft">Bottom left</span> (<span class="ime_t_default">default</span>)</label> </div> <div style="float:left"> <input type="radio" name="imageDescriptionPos" value="bottom-right" onchange="ime_updateResult()" id="ime_imageDescriptionPos_bottomright" /><label for="ime_imageDescriptionPos_bottomright" class="ime_t_bottomright">Bottom right</label> </div> <div style="float:left"> <input type="radio" name="imageDescriptionPos" value="top-left" onchange="ime_updateResult()" id="ime_imageDescriptionPos_topleft" /><label for="ime_imageDescriptionPos_topleft" class="ime_t_topleft">Top left</label> </div> <div style="float:left"> <input type="radio" name="imageDescriptionPos" value="top-right" onchange="ime_updateResult()" id="ime_imageDescriptionPos_topright" /><label for="ime_imageDescriptionPos_topright" class="ime_t_topright">Top right</label> </div> <div style="float:left"> <input type="radio" name="imageDescriptionPos" value="none" onchange="ime_updateResult()" id="ime_imageDescriptionPos_none" /><label for="ime_imageDescriptionPos_none" class="ime_t_nolink">No link</label> </div> </div> <div style="clear:both"></div> </fieldset> <fieldset style="margin:0.5ex;padding:0 1ex 1ex"> <legend class="ime_t_importareas">Import areas from wikicode</legend> <a href="javascript:ime_showImport()" style="padding:1px;background:white;color:darkblue" id="imeImportShow"><span class="ime_t_showtextbox">Show text box</span> &gt;</a> <a href="javascript:ime_hideImport()" style="padding:1px;background:white;color:darkblue;display:none" id="imeImportHide"><span class="ime_t_hidetextbox">Hide text box</span> &lt;</a> <div id="imeImport" style="display:none"> <textarea name="importText" style="width:100%;margin:0;height:10em;display:block"></textarea> <a href="javascript:ime_importLines()" style="padding:1px;background:white;color:darkblue" class="ime_t_import">Import</a> </div> </fieldset> <fieldset style="margin:0.5ex;padding:0 1ex 1ex"> <legend class="ime_t_generatedwikicode">Generated wikicode</legend> <a href="javascript:ime_showResult()" style="padding:1px;background:white;color:darkblue" id="imeResultShow"><span class="ime_t_showwikicode">Show wikicode</span> &gt;</a> <a href="javascript:ime_hideResult()" style="padding:1px;background:white;color:darkblue;display:none" id="imeResultHide"><span class="ime_t_hidewikicode">Hide wikicode</span> &lt;</a> <div> <code id="imeResult" style="display:block;line-height:1.2em"></code> </div> </fieldset> </fieldset></form>`;