Jump to content

User:Anomie/util.js

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Anomie (talk | contribs) at 04:54, 15 November 2007 (typo). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
function jsondecode(v){
    try {
        return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u\n\r\t]/.test(v.replace(/"(\\.|[^"\\])*"/g,''))) && eval('('+v+')');
    } catch(e){
        return null;
    }
}

function api(p, cb){
    var uri=wgServer+wgScriptPath+'/api.php?format=json';
    for(var k in p){
        var v=p[k];
        if(typeof(v)=='object' && (v instanceof Array))
            v=v.map(encodeURIComponent).join('|');
        else
            v=encodeURIComponent(v);
        uri+='&'+encodeURIComponent(k)+'='+v;
    }
    
    var x = sajax_init_object();
    if(!x) return false;
    if(typeof(cb)=='function'){
        x.open('GET', uri, true);
        x.onreadystatechange=function(){
            if(x.readyState!=4) return;
            var r=jsondecode(x.responseText);
            if(!r) throw new Error("Could not parse response");
            cb(r);
        };
        x.send(null);
        return true;
    } else {
        x.open('GET', uri, false);
        x.send(null);
        var r=jsondecode(x.responseText);
        if(!r) throw new Error("Could not parse response");
        return r;
    }
}

function isClass(n, c){
	return n.className.match(new RegExp('(^|\\s)'+c+'(\\s|$)'));
}
function addClass(n, c){
	if(!n.isClass(c)) n.className=(n.className=='')?c:(n.className+' '+c);
}
function delClass(n, c){
	var cl=n.className;
	cl=cl.replace(new RegExp('(^|\\s)'+c+'(\\s|$)', 'g'), ' ');
	cl=cl.replace(/\s\s+/g, ' ').replace(/^\s+|\s+$/g, '');
	if(n.className!=cl) n.className=cl;
}