//  copyright: 


(function() {
    const textarea = document.getElementById("bar");

    const replacements = [
[/’/g, "\'"],
[/a/g, "ا"],
[/اا/g, "آ"],
[/[āâ]/g, "آ"],
[/b/g, "ب"],
[/B/g, "ب"],

[/ب'/g, "پ"],
[/p/g, "پ"],
[/P/g, "پ"],

	
[/t/g, "ت"],
[/ت'/g, "ث"],
[/c/g, "ج"],
[/C/g, "ج"],

[/ج'/g, "چ"],
[/ç/g, "چ"],
[/Ç/g, "چ"],
[/H/g, "ح"],
[/ح'/g, "خ"],
[/x/g, "خ"],
[/K/g, "خ"],
[/d/g, "د"],
[/د'/g, "ذ"],
[/r/g, "ر"],
[/R/g, "ر"],

[/z/g, "ز"],
[/ر'/g, "ز"],
[/ز'/g, "ژ"],
[/j/g, "ژ"],
[/J/g, "ژ"],
	

[/s/g, "س"],
[/س'/g, "ش"],
[/ş/g, "ش"],
[/Ş/g, "ش"],		
[/S/g, "ص"],
[/ص'/g, "ض"],
[/D/g, "ض"],
[/T/g, "ط"],
[/ط'/g, "ظ"],
[/Z/g, "ظ"],
[/G/g, "ع"],
[/O/g, "ع"],
[/o/g, "ع"],

[/ع'/g, "غ"],
[/ğ/g, "غ"],
[/Ğ/g, "غ"],
	

[/f/g, "ف"],
[/F/g, "ف"],

[/q/g, "ق"],
[/Q/g, "ق"],

	

[/k/g, "ك"],
[/ك'/g, "ڭ"],
[/g/g, "گ"],
[/G/g, "گ"],

	
	
[/ñ/g, "ڭ"],
[/N/g, "ڭ"],
[/l/g, "ل"],
[/L/g, "ل"],
	
[/m/g, "م"],
[/M/g, "م"],

[/n/g, "ن"],
[/h/g, "ه"],
[/ه'/g, "ة"],
[/[wvouûöü]/g, "و"],
[/[yiîı]/g, "ی"],
[/ی'/g, "ي"], // à retirer
[/-/g, "ء"],
[/وءء/g, "ؤ"],
[/يءء/g, "ئ"],
[/اءء/g, "إ"],
[/I/g, "إ"],
[/A/g, "إ"],
[/ءا/g, "أ"],
[/_/g, "ـ"],

[/\//g, "\u200c"],
[/X/g, "\u200c"],

[/\?/g, "؟"],
[/;/g, "؛"],
[/,/g, "،"],
[/0/g, "۰"],
[/1/g, "۱"],
[/2/g, "۲"],
[/3/g, "۳"],
[/4/g, "۴"],
[/5/g, "۵"],
[/6/g, "۶"],
[/7/g, "۷"],
[/8/g, "۸"],
[/9/g, "۹"],
];

    const transform = (txt) => {
        let result = txt;
        for (const [regex, replacement] of replacements) {
            result = result.replace(regex, replacement);
        }
        return result;
    };

    textarea.addEventListener("input", (e) => {
        const start = textarea.selectionStart;
        const end = textarea.selectionEnd;
        const scrollTop = textarea.scrollTop;

        const originalText = textarea.value;

        if (start === 0 && end === originalText.length) {
            textarea.value = transform(originalText);
            textarea.selectionStart = 0;
            textarea.selectionEnd = textarea.value.length;
        }
        else {
            textarea.value = transform(originalText);

            let beforeCursorOriginal = originalText.substring(0, start);
            beforeCursorOriginal = transform(beforeCursorOriginal);
            textarea.selectionStart = textarea.selectionEnd = beforeCursorOriginal.length;
        }

        textarea.scrollTop = scrollTop;
    });


    textarea.addEventListener("keydown", (e) => {
        if (e.ctrlKey || e.metaKey) {
            return;
        }
    });

})();