User:Karimelbeltagy5/common.js

// /*jslint regexp: true */ /*browser: true*/ /*global $: false, wgNamespaceNumber: false, wgAction: false, mw: false, wgScriptPath: false, wgPageContentLanguage: false, window: false */ if (window.globalTranslatorConfigs === undefined) { var globalTranslatorConfigs = { "homeWiki": window.homeWiki, "fromLang": window.fromLang, "translatorBarFormat": window.translatorBarFormat, "templateTranslatorText": window.templateTranslatorText, "removeLinksAliasesText": window.removeLinksAliasesText, "doneText": window.doneText }; } var translatorConfigs = { "homeWiki": "ar", "fromLang": wgPageContentLanguage, "translatorBarFormat": "$1translate$2 links from $3 to $4", "templateTranslatorText": "Template translation", "removeLinksAliasesText": "Remove Links Aliases", "doneText": "Done!", "enableTemplateTranslation": true, "removeLinksAliases": true }; var enableNeedingShow = false; $.extend(translatorConfigs, globalTranslatorConfigs); // getting the last translator preference from the cookie if ($.cookie("homeWiki") !== null) { translatorConfigs.homeWiki = $.cookie("homeWiki"); } if ($.cookie("fromLang") !== null) { translatorConfigs.fromLang = $.cookie("fromLang"); } // // Regexp.escape from: http://80.68.89.23/2006/Jan/20/escape/ RegExp.escape = function (text) { "use strict"; return text.replace(/[\-\[\]{}*+?.,\\\^$|#\s]/g, "\\$&"); }; function Translator { "use strict"; var translationTextArea, progressCount, itemsCount, ajaxUrl; function getOrigin { var result = window.location.protocol + "//" + window.location.host; if (window.location.port !== "") { result = result + ":" + window.location.port; }       return result; }   function getOriginOfWikiLang(lang) { return getOrigin.replace(wgPageContentLanguage, lang); }   function setAjaxUrl { ajaxUrl = getOriginOfWikiLang(translatorConfigs.fromLang) + wgScriptPath + "/api.php?action=query&prop=langlinks&redirects=&format=json&lllimit=500&titles="; }   function getSelectedTextLinks { // borrowed from: http://stackoverflow.com/questions/4220478 :)       var selection,            selectionAncestor,            range,            allWithinRangeParent,            allSelected,            i,            el;        // if `window.getSelection` is not defined (on IE) return nothing.        if (window.getSelection === undefined) {            return [];        }        selection = window.getSelection;        // if nothing is selected, return empty array        if (selection.isCollapsed) {            return [];        }        range = selection.getRangeAt(0);        selectionAncestor = range.commonAncestorContainer;        if (selectionAncestor.getElementsByTagName === undefined) { // if it is not a formal HTML selection            return [];        }        allWithinRangeParent = selectionAncestor.getElementsByTagName("a");        allSelected = [];        for (i = 0; (el = allWithinRangeParent[i]) !== undefined; i += 1) { // The second parameter says to include the element // even if it's not fully selected if (selection.containsNode(el, true)) { allSelected.push(el); }       }        return allSelected; }   /*jslint unparam: true*/ // I don't want use key parameter in closures! function increaseProgressCount { progressCount = progressCount + 1; $("#translatorProgress").attr("value", progressCount); if (progressCount === itemsCount) { $("#translatorProgress").hide("slow"); $("#translatorStatus").css("font-weight", "bold").text(translatorConfigs.doneText).show("slow"); if (enableNeedingShow) { var linksmap = {}, links = [], i,                   result; $("[style='color: red;']").each(function (k, v) {                   linksmap[$(v).prev.attr('title')] = parseInt(v.innerHTML, 10);                }); for (i in linksmap) { if (linksmap.hasOwnProperty(i)) { links.push([i, linksmap[i]]); }               }                links = links.sort(function (x, y) { return y[1] - x[1]; }); result = links.map(function (x) { return x[0] + '\t' + x[1]; }).join("\n"); $("#translatorPlusText").val('List of unavailable pages on ' + translatorConfigs.homeWiki + '.wiki according to number of interwikis:\n' + result).show; }       }    }    function queryTranslationFromData(data) { var languageLinks, translation; if (data.query === undefined || data.query.pages === undefined) { return null; }       $.each(data.query.pages, function (key, value) { // for retrieving first object index            languageLinks = value.langlinks;        }); if (languageLinks === undefined) { return null; }       $.each(languageLinks, function (key, value) { // we can also use .filter here            if (value.lang === translatorConfigs.homeWiki) {                translation = value["*"];            }        }); return { translation: translation, interwikis: languageLinks.length };   }    /*jslint unparam: false*/ function commonAjaxRunner(title, translatorFunction) { $.ajax({           url: ajaxUrl + encodeURIComponent(title),            complete: function  {                increaseProgressCount;            },            success: function (data) {                var translation = queryTranslationFromData(data);                if (translation !== null) {                    translatorFunction(translation);                }            },            dataType: "jsonp"        }); }   function addTranslationToNode(node, translation) { if (translation.translation !== undefined) { node.after('(' + translation.translation + ')'); } else if (enableNeedingShow === true) { node.after('( ' + translation.interwikis + ' )'); }   }    function translateFromLanguageLinkNode(title, node) { commonAjaxRunner(title, function (translation) {           addTranslationToNode(node, translation);        }); }   // for Links in textareas function addTranslationToTextareaLink(title, translation) { translationTextArea.val(translationTextArea.val.replace( new RegExp("(\\[\\[:?)" + RegExp.escape(title) + "((?:\\|[^\\]]*)?)(\\]\\])"), "$1" + translation + (translatorConfigs.removeLinksAliases ? "" : "$2") + "$3" ));   }    function translateFromLanguageLinks(title) { commonAjaxRunner(title, function (translation) {           if (translation.translation !== undefined) {                addTranslationToTextareaLink(title, translation.translation);            }        }); }   // for s in textareas function addTranslationToTextareaTemplateLink(title, translation) { translationTextArea.val(translationTextArea.val.replace( new RegExp("(\\{\\{\\s*(?:[Tt]emplate:)?)" + RegExp.escape(title) + "([\\n\\|\\}])"), "$1" + translation + "$2" ));   }    function translateFromLanguageTemplateLinks(title) { commonAjaxRunner("Template:" + title, function (translation) {           if (translation.translation !== undefined) {                addTranslationToTextareaTemplateLink(title, translation.translation.replace(/^.*?:/, ""));            }        }); }   function parseUrl(url) { if (url === undefined) { return undefined; }       var match = url.match(/^\/wiki\/([^#]*)/); if (match === null) { match = url.match(/^\/w\/index\.php\?title=([^&#]*).*redlink=1/); }       if (match !== null) { return decodeURI(match[1]); // returns matched text }       return undefined; }   function getLinkTitle(link) { // previously it was link.attr("title") return parseUrl(link.attr("href")); }   this.run = function  { setAjaxUrl; progressCount = 0; itemsCount = 0; $("#translatorStatus").hide(0); $("#translatorProgress").removeAttr("max").removeAttr("value"); var links, templates, i,           title; if (wgAction === "view" || wgAction === "purge" || wgAction === "historysubmit") { links = getSelectedTextLinks; if (links.length === 0) { links = $("#bodyContent a"); }           $(links).filter("a").each(function  {                var iter = $(this),                    title = getLinkTitle(iter);                if (title !== undefined) {                    itemsCount = itemsCount + 1;                    translateFromLanguageLinkNode(title, iter);                }            }); $("#translatorProgress").show.attr("max", itemsCount); } else if (wgAction === "edit" || wgAction === "submit") { $("#wpTextbox2").remove; // remove translation textarea if exists if (translatorConfigs.fromLang === wgPageContentLanguage) { translationTextArea = $("#wpTextbox1").clone.attr({                   "id": "wpTextbox2"                }).css({ // new color for translation textarea                    "background-color": "#CCCEFF"                }).val($("#wpTextbox1").val); // this something that clone must do                $("#wpTextbox1").before(translationTextArea); // put translation textarea before old } else { translationTextArea = $("#wpTextbox1"); }           // for links links = translationTextArea.val.match(/\[\[.*?\]\]/g); templates = translationTextArea.val.match(/\{\{.*?[\n\|\}]/g); itemsCount = -1; if (links !== null) { for (i = 0; i < links.length; i = i + 1) { // equals with title = links[i].replace(/\[\[:?([^\]\|]*)\|?.*?\]\]/g, "$1"); translateFromLanguageLinks(title); }               if (itemsCount === -1) { itemsCount = 0; }               itemsCount = itemsCount + links.length; }           if (templates !== null && translatorConfigs.enableTemplateTranslation === true) { for (i = 0; i < templates.length; i = i + 1) { // equals with title = templates[i].replace(/\{\{\s*(?:[Tt]emplate:)?(.*)\s*[\n\|\}]/g, "$1"); translateFromLanguageTemplateLinks(title); }               if (itemsCount === -1) { itemsCount = 0; }               itemsCount = itemsCount + templates.length; }           if (itemsCount !== -1) { $("#translatorProgress").show.attr("max", itemsCount); }       }    }; } var translator = new Translator; $(function {    "use strict";    function initializeEditorFor(forEditable, inputForEditable, setVariableClosure) {        $(forEditable).click(function (event) { event.preventDefault; $(forEditable).hide; $(inputForEditable).css("width", "2em").show.val($(forEditable).text); });       $(inputForEditable).keyup(function (event) { var selectedLanugage = $(this).val; if (event.keyCode === 13) { $(this).focusout; // on enter } else if (event.keyCode === 27) { $(forEditable).show; // on escape $(inputForEditable).hide.val(selectedLanugage); }       }).focusout(function  { var selectedLanugage = $(this).val; if (/...?/.test(selectedLanugage)) { setVariableClosure(selectedLanugage); $(forEditable).html(selectedLanugage); }           $(forEditable).show; $(inputForEditable).hide; });   }    $("#translatorBar").remove;    var html = ' ' + translatorConfigs.translatorBarFormat;    if (wgAction === "edit" || wgAction === "submit") {        html = html + ' ' + translatorConfigs.templateTranslatorText + ' ';        html = html + ' ' + translatorConfigs.removeLinksAliasesText + ' ';    }    html = html + '  In progress...  ';    html = html.replace('$1', '');    html = html.replace('$2', '+');    html = html.replace('$3', '' + translatorConfigs.fromLang + ''); html = html.replace('$4', '' + translatorConfigs.homeWiki + '</a><input style="display: none" id="translator-to-input">'); $("h1:first").append(html); $("#translator-button").click(function (event) {       event.preventDefault;        translator.run;    }); $("#translator-plus").click(function (event) {       event.preventDefault;        enableNeedingShow = true;        translator.run;    }); initializeEditorFor("#translator-to", "#translator-to-input", function (value) {       translatorConfigs.homeWiki = value;        $.cookie("homeWiki", value);    }); initializeEditorFor("#translator-from", "#translator-from-input", function (value) {       translatorConfigs.fromLang = value;        $.cookie("fromLang", value);    }); $("#enableTemplateTranslation").attr("checked", translatorConfigs.enableTemplateTranslation).click(function {        translatorConfigs.enableTemplateTranslation = this.checked;    }); $("#removeLinksAliases").attr("checked", translatorConfigs.removeLinksAliases).click(function {        translatorConfigs.removeLinksAliases = this.checked;    }); }); mw.loader.load('//meta.wikimedia.org/w/index.php?title=User:Hedonil/XTools/XTools.js&action=raw&ctype=text/javascript'); importScript('Wikipedia:AutoEd/complete.js');