User:JohnSRoberts99/monobook.js

From Wikipedia, the free encyclopedia
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.
/*********************************************************************
**                ***WARNING: GLOBAL GADGET FILE***                 **
**         any changes to this file will affect many users          **
**          please discuss changes on the talk page or at           **
**             [[Wikipedia talk:Gadget]] before editing             **
**     (consider dropping the script author a note as well...)      **
**                                                                  **
**********************************************************************
**             Script:        Drop-down menus                       **
**            Version:        4.51g                                 **
**             Author:        Haza-w                                **
**      Documentation:        [[User:Haza-w/Drop-down menus]]       **
**                                                                  **
*********************************************************************/
 
// "Fail gracefully" if skin not supported
switch (skin) {
    case 'modern': case 'monobook': case 'vector':
 
    // Global variables
    var _cactions = {
        admin: wgUserGroups.join().indexOf('sysop') > -1 ? true : false,
        areqs: [],
        hovms: skin == 'vector' ? 50 : 400,
        menus: [],
        mouse: null,
        pname: encodeURIComponent(mw.config.get('wgPageName')),
        timer: [],
        vectr: skin == 'vector' ? true : false
    };
 
    // Process XMLHttpRequests
    function xhr(request,url,orsc) {
        with (request) {
            open('GET',url,true);
            onreadystatechange = orsc;
            send(null);
        }
    }
 
    // Find absolute position of element
    function findPos(eid,offset) {
        var obj = document.getElementById(eid), pos = [0,0];
        do with (obj) {
            pos[0] += offsetLeft;
            pos[1] += offsetTop;
        } while (obj = obj.offsetParent);
        pos[0] += offset[0]; pos[1] += offset[1];
        return pos;
    }
 
    // Create menu div element
    function createMenu(mid,vectorise,html) {
        var menu = document.createElement('div');
        with (menu) {
            id = 'opt-' + mid;
            className = 'ca-menu';
            style.display = 'none';
        }
        menu.onmouseover = function () {showMenu('opt-'+mid)};
        menu.onmouseout = function () {hideMenu('opt-'+mid)};
 
        var elements = {
            ul: document.createElement('ul'),
            li: null,
            a: null,
            txt: null
        };
        with (elements) {
            for (var i = 0; i < html.length; i++) if (html[i].length) {
                li = document.createElement('li'); li.id = html[i][0];
                a = document.createElement('a'); a.href = html[i][2];
                txt = document.createTextNode(html[i][1]);
                a.appendChild(txt); li.appendChild(a); ul.appendChild(li);
            }
            menu.appendChild(ul);
        }
 
        document.body.appendChild(menu);
        if (vectorise) createTab(mid);
 
        return 'opt-' + mid;
    }
 
    // Create cactions LI tab
    function createTab(mid) {
        var mtitle = mid[0].toUpperCase() + mid.substr(1);
 
        if (_cactions.vectr) {
            var cid = 'p-' + mid;
            var elements = {
                div: document.createElement('div'),
                h5: document.createElement('h5'),
                span: document.createElement('span'),
                a: document.createElement('a'),
                txt: null
            };
            with (elements) {
                div.id = cid;
                div.className = 'vectorMenu extraMenu';
 
                txt = document.createTextNode(mtitle);
                span.appendChild(txt); h5.appendChild(span);
 
                a.href = '#';
                a.onmouseover = function () {showMenu('opt-'+mid,findPos(cid,[0,40]))};
                a.onmouseout = function () {hideMenu('opt-'+mid)};
 
                span = document.createElement('span');
                txt = document.createTextNode(mtitle);
                span.appendChild(txt); a.appendChild(span); h5.appendChild(a);
 
                div.appendChild(h5);
                document.getElementById('right-navigation').insertBefore(div,document.getElementById('p-search'));
            }
        }
        else {
            var cid = 'ca-' + mid;
            var elements = {
                li: document.createElement('li'),
                a: document.createElement('a'),
                txt: document.createTextNode(mtitle)
            };
            with (elements) {
                li.id = cid;
                a.href = '#';
                a.onmouseover = function () {showMenu('opt-'+mid,findPos(cid,[-10,20]))};
                a.onmouseout = function () {hideMenu('opt-'+mid)};
                a.appendChild(txt); li.appendChild(a);
 
                document.getElementById('p-cactions').getElementsByTagName('div')[0].getElementsByTagName('ul')[0].appendChild(li);
            }
        }
    }
 
    // CSS hide elements
    function hideElements(elements,conditionals) {
        if (typeof(conditionals) == 'undefined') {
            for (var i = 0; i < elements.length; i++) if (document.getElementById(elements[i])) document.getElementById(elements[i]).style.display = 'none';
        }
        else for (var i = 0; i < elements.length; i++) if (document.getElementById(elements[i])) {
            document.getElementById(elements[i]).style.display = 'none';
            if (conditionals[i]) document.getElementById(conditionals[i]).style.display = 'none';
        }
    }
 
    // Show/hide menu functions
    function showMenu(mid,pos) {
        with (_cactions) {
            mouse = mid;
            if (pos) for (var i = 0; i < menus.length; i++) {
                if (timer[menus[i]]) {
                    clearTimeout(timer[menus[i]]);
                    timer[menus[i]] = null;
                }
                if (mid.replace(/-[^-]+$/,'') == menus[i]) continue;
                document.getElementById(menus[i]).style.display = 'none';
            }
            if (!timer[mid]) with (document.getElementById(mid).style) {
                display = '';
                if (pos) {
                    left = pos[0]+'px';
                    top = pos[1]+'px';
                }
            }
            else {
                clearTimeout(timer[mid]);
                timer[mid] = null;
            }
        }
    }
    function hideMenu(mid) {
        with (_cactions) {
            if (mid == mouse.replace(/-[^-]+$/,'')) timer[mid] = null;
 
            if (timer[mid]) {
                timer[mid] = null;
                document.getElementById(mid).style.display = 'none';
                if (mid == mouse && mid.search(/opt-.*-/) != -1) document.getElementById(mid.replace(/-[^-]+$/,'')).style.display = 'none';
            }
            else timer[mid] = setTimeout('hideMenu(\''+mid+'\');',hovms);
        }
    }
 
    // Delink element
    function removeLink(eid) {
        var element = document.getElementById(eid);
        if (!element.getElementsByTagName('a').length) return false;
 
        var a = element.getElementsByTagName('a')[0];
        element.appendChild(a.removeChild(a.firstChild));
        element.removeChild(a);
 
        element.className = 'ca-disabled';
    }
 
    // User options hook
    $(function () {
        switch (wgNamespaceNumber) {
            case 2: case 3: _cactions['uname'] = encodeURIComponent(wgTitle.split('/')[0].replace(/ /g,'_'));
        }
        if (wgCanonicalSpecialPageName == 'Contributions') for (var i = 0, hl; hl = document.getElementById('contentSub').getElementsByTagName('a')[i]; i++) {
            if (hl.href.indexOf('user=') > -1) {
                _cactions['uname'] = hl.href.split('user=')[1].split('&amp;')[0];
                break;
            }
        }
 
        if (_cactions.uname) {
            with (_cactions) {
                menus[menus.length] = createMenu('user',true,Array(
                    ['c-u-logs',        'User logs >',      '#']                                                                                                            ,
                    ['c-u-rfx',         'Links to RfX >',   '#']                                                                                                            ,
                    ['c-u-blocks',      'Blocks >',         '#']                                                                                                            ,
                    ['c-u-contribs',    'Contributions',    wgScript+'?title=Special:Contributions/'+uname+'&action=view']                                                  ,
                    ['c-u-editcount',   'Edit count',       '//toolserver.org/~tparis/pcount/index.php?lang=en&wiki=wikipedia&name='+uname.replace(/_/g,'+')]         ,
                    ['c-u-editsum',     'Edit summaries',   '//toolserver.org/~tparis/editsummary/index.php?lang=en&wiki=wikipedia&name='+uname.replace(/_/g,'+')]   ,
                    ['c-u-wcuser',      'Edit analysis',    'http://en.wikichecker.com/user/?l=all&t='+uname]                                                               ,
                    ['c-u-sul',         'SUL status',       '//toolserver.org/~vvv/sulutil.php?user='+uname]                                                           ,
                    ['c-u-subpages',    'Userspace',        wgScript+'?title=Special:PrefixIndex/User:'+uname+'/&action=view']                                              ,
                    ['c-u-email',       'E-mail user',      wgScript+'?title=Special:EmailUser/'+uname+'&action=view']                                                      ,
                    ['c-u-groups',      'User groups',      wgScript+'?title=Special:ListUsers&action=view&limit=1&username='+uname]                                        ,
                    ['c-u-rightslog',   'Rights changes',   wgScript+'?title=Special:Log&action=view&type=rights&page=User:'+uname]
                ));
 
                menus[menus.length] = createMenu('user-logs',false,Array(
                    ['c-ul-logs',       'All user logs',    wgScript+'?title=Special:Log&action=view&user='+uname]              ,
                    ['c-ul-blocks',     'Blocks',           wgScript+'?title=Special:Log&action=view&type=block&user='+uname]   ,
                    ['c-ul-deletes',    'Deletions',        wgScript+'?title=Special:Log&action=view&type=delete&user='+uname]  ,
                    ['c-ul-moves',      'Moves',            wgScript+'?title=Special:Log&action=view&type=move&user='+uname]    ,
                    ['c-ul-patrols',    'Patrols',          wgScript+'?title=Special:Log&action=view&type=patrol&user='+uname]  ,
                    ['c-ul-protects',   'Protections',      wgScript+'?title=Special:Log&action=view&type=protect&user='+uname] ,
                    ['c-ul-uploads',    'Uploads',          wgScript+'?title=Special:Log&action=view&type=upload&user='+uname]  ,
                    ['c-ul-rights',     'User rights',      wgScript+'?title=Special:Log&action=view&type=rights&user='+uname]
                ));
 
                menus[menus.length] = createMenu('user-rfx',false,Array(
                    ['c-ux-rfa',        'RfAs',             wgScript+'?title=Special:PrefixIndex/Wikipedia:Requests_for_adminship/'+uname+'&action=view']       ,
                    ['c-ux-rfb',        'RfBs',             wgScript+'?title=Special:PrefixIndex/Wikipedia:Requests_for_bureaucratship/'+uname+'&action=view']  ,
                    ['c-ux-rfar',       'RfAr',             wgScript+'?title=Wikipedia:Requests_for_arbitration/'+uname+'&action=view']                         ,
                    ['c-ux-rfc',        'RfC',              wgScript+'?title=Wikipedia:Requests_for_comment/'+uname+'&action=view']                             ,
                    ['c-ux-rfcu',       'RfCU',             wgScript+'?title=Wikipedia:Requests_for_checkuser/Case/'+uname+'&action=view']                      ,
                    ['c-ux-spi',        'SPI',              wgScript+'?title=Wikipedia:Sockpuppet_investigations/'+uname+'&action=view']
                ));
 
                menus[menus.length] = createMenu('user-blocks',false,Array(
                    admin?          ['c-ub-block',          'Block user',       wgScript+'?title=Special:BlockIP/'+uname+'&action=view']            :[] ,
                    admin?          ['c-ub-unblock',        'Unblock user',     wgScript+'?title=Special:IPBlockList&action=unblock&ip='+uname]     :[] ,
                                    ['c-ub-ipblock',        'View block',       wgScript+'?title=Special:IPBlockList&action=view&ip='+uname]            ,
                                    ['c-ub-blocklog',       'Block log',        wgScript+'?title=Special:Log&action=view&type=block&page=User:'+uname]
                ));
 
                if (sajax_init_object() && true) {
                    if (uname.search(/(?:\d{1,3}\.){3}\d{1,3}/) == 0) {
                        areqs['ip'] = new sajax_init_object();
                        xhr(areqs['ip'],wgScriptPath+'/api.php?format=json&action=query&list=blocks&bkusers='+uname+'&bkprop=id&xhr='+Math.random(),function () {
                            with (areqs['ip']) if (readyState == 4 && status == 200) {
                                var api = eval('('+responseText+')');
                                if (api.query.blocks.length) {
                                    hideElements(['c-ub-block']);
                                    document.getElementById('c-ub-ipblock').getElementsByTagName('a')[0].style.color = '#EE1111';
                                }
                                else {
                                    hideElements(['c-ub-unblock']);
                                    removeLink('c-ub-ipblock');
                                }
                            }
                        } );
                    }
                    else {
                        areqs['user'] = new sajax_init_object();
                        xhr(areqs['user'],wgScriptPath+'/api.php?format=json&action=query&list=users&ususers='+uname+'&usprop=blockinfo|groups&xhr='+Math.random(),function () {
                            with (areqs['user']) if (readyState == 4 && status == 200) {
                                var api = eval('('+responseText+')');
                                with (api.query.users[0]) {
                                    if (typeof(missing) != 'undefined') hideElements(['ca-user']);
                                    else {
                                        if (typeof(blockedby) != 'undefined') {
                                            hideElements(['c-ub-block']);
                                            document.getElementById('c-ub-ipblock').getElementsByTagName('a')[0].style.color = '#EE1111';
                                        }
                                        else {
                                            hideElements(['c-ub-unblock']);
                                            removeLink('c-ub-ipblock');
                                        }
 
                                        if (typeof(groups) == 'undefined' || groups.join().indexOf('sysop') == -1) hideElements(['c-ul-blocks','c-ul-deletes','c-ul-protects','c-ul-rights']);
                                    }
                                }
                            }
                        } );
 
                        areqs['rfa'] = new sajax_init_object();
                        xhr(areqs['rfa'],wgScriptPath+'/api.php?format=json&action=query&list=allpages&apprefix=Requests_for_adminship%2F'+uname+'&apnamespace=4&aplimit=1&xhr='+Math.random(),function () {
                            with (areqs['rfa']) if (readyState == 4 && status == 200) {
                                var api = eval('('+responseText+')');
                                if (!api.query.allpages.length) removeLink('c-ux-rfa');
                            }
                        } );
 
                        areqs['rfb'] = new sajax_init_object();
                        xhr(areqs['rfb'],wgScriptPath+'/api.php?format=json&action=query&list=allpages&apprefix=Requests_for_bureaucratship%2F'+uname+'&apnamespace=4&aplimit=1&xhr='+Math.random(),function () {
                            with (areqs['rfb']) if (readyState == 4 && status == 200) {
                                var api = eval('('+responseText+')');
                                if (!api.query.allpages.length) removeLink('c-ux-rfb');
                            }
                        } );
 
                        areqs['uspace'] = new sajax_init_object();
                        xhr(areqs['uspace'],wgScriptPath+'/api.php?format=json&action=query&list=allpages&apprefix='+uname+'%2F&apnamespace=2&aplimit=1&xhr='+Math.random(),function () {
                            with (areqs['uspace']) if (readyState == 4 && status == 200) {
                                var api = eval('('+responseText+')');
                                if (!api.query.allpages.length) removeLink('c-u-subpages');
                            }
                        } );
                    }
 
                    areqs['rfx'] = new sajax_init_object();
                    xhr(areqs['rfx'],wgScriptPath+'/api.php?format=json&action=query&titles=Wikipedia:Requests_for_arbitration/'+uname+'|Wikipedia:Requests_for_comment/'+uname+'|Wikipedia:Requests_for_checkuser/Case/'+uname+'|Wikipedia:Sockpuppet_investigations/'+uname+'&letype=block&letitle=User:'+uname+'&prop=info&xhr='+Math.random(),function () {
                        with (areqs['rfx']) if (readyState == 4 && status == 200) {
                            var api = eval('('+responseText+')');
                            for (i in api.query.pages) switch (api.query.pages[i].title.split('/')[0]) {
                                case 'Wikipedia:Requests for arbitration': if (typeof(api.query.pages[i].missing) != 'undefined') removeLink('c-ux-rfar'); break;
                                case 'Wikipedia:Requests for comment': if (typeof(api.query.pages[i].missing) != 'undefined') removeLink('c-ux-rfc'); break;
                                case 'Wikipedia:Requests for checkuser': if (typeof(api.query.pages[i].missing) != 'undefined') removeLink('c-ux-rfcu'); break;
                                case 'Wikipedia:Sockpuppet investigations': if (typeof(api.query.pages[i].missing) != 'undefined') removeLink('c-ux-spi'); break;
                            }
                        }
                    } );
 
                    areqs['ublocks'] = new sajax_init_object();
                    xhr(areqs['ublocks'],wgScriptPath+'/api.php?format=json&action=query&list=logevents&letype=block&letitle=User:'+uname+'&lelimit=1&xhr='+Math.random(),function () {
                        with (areqs['ublocks']) if (readyState == 4 && status == 200) {
                            var api = eval('('+responseText+')');
                            if (!api.query.logevents.length) removeLink('c-ub-blocklog');
                        }
                    } );
                }
                else hideElements(['c-ub-ipblock','c-ul-blocks','c-ul-deletes','c-ul-protects','c-ul-rights']);
            }
 
            hideElements(['t-contributions','t-log','t-emailuser']);
 
            document.getElementById('c-u-logs').onmouseover = function () {showMenu('opt-user-logs',findPos('c-u-logs',[40,0]))};
            document.getElementById('c-u-logs').onmouseout = function () {hideMenu('opt-user-logs')};
            document.getElementById('c-u-logs').style.fontWeight = 'bold';
 
            document.getElementById('c-u-rfx').onmouseover = function () {showMenu('opt-user-rfx',findPos('c-u-rfx',[40,0]))};
            document.getElementById('c-u-rfx').onmouseout = function () {hideMenu('opt-user-rfx')};
            document.getElementById('c-u-rfx').style.fontWeight = 'bold';
            document.getElementById('opt-user-rfx').style.width = '50px';
 
            document.getElementById('c-u-blocks').onmouseover = function () {showMenu('opt-user-blocks',findPos('c-u-blocks',[40,0]))};
            document.getElementById('c-u-blocks').onmouseout = function () {hideMenu('opt-user-blocks')};
            document.getElementById('c-u-blocks').style.fontWeight = 'bold';
 
            if (_cactions.uname.search(/(?:\d{1,3}\.){3}\d{1,3}/) == 0) hideElements(['c-u-logs','c-ux-rfa','c-ux-rfb','c-u-editcount','c-u-editsum','c-u-wcuser','c-u-subpages','c-u-email','c-u-groups','c-u-rightslog']);
        }
    } );
 
    // Page options hook
    $(function () {
        if (!wgCanonicalSpecialPageName) {
            with (_cactions) {
                menus[menus.length] = createMenu('page',true,Array(
                                    ['c-p-logs',        'Page logs >',      '#'],
                    wgArticleId?    ['c-p-history',     'History',          wgScript+'?title='+pname+'&action=history']                     :[] ,
                    wgArticleId?    ['c-p-move',        'Move page',        wgScript+'?title=Special:Movepage/'+pname+'&action=view']       :[] ,
                    !vectr?         ['c-p-watch',       'Watch page',       wgScript+'?title='+pname+'&action=watch']                       :[] ,
                    !vectr?         ['c-p-unwatch',     'Unwatch page',     wgScript+'?title='+pname+'&action=unwatch']                     :[] ,
                    admin?          ['c-p-protect',     'Protect page',     wgScript+'?title='+pname+'&action=protect']                     :[] ,
                    admin?          ['c-p-unprotect',   'Unprotect page',   wgScript+'?title='+pname+'&action=unprotect']                   :[] ,
                    admin?          ['c-p-delete',      'Delete page',      wgScript+'?title='+pname+'&action=delete']                      :[] ,
                    admin?          ['c-p-undelete',    'Undelete page',    wgScript+'?title=Special:Undelete/'+pname+'&action=view']       :[] ,
                    wgArticleId?    ['c-p-diff',        'Latest diff',      wgScript+'?title='+pname+'&action=view&diff='+wgCurRevisionId]  :[] ,
                    wgArticleId?    ['c-p-editzero',    'Edit intro',       wgScript+'?title='+pname+'&action=edit&section=0']              :[] ,
                    wgArticleId?    ['c-p-wcpage',      'Page analysis',    'http://en.wikichecker.com/article/?a='+pname]                  :[] ,
                                    ['c-p-purge',       'Purge cache',      wgScript+'?title='+pname+'&action=purge']
                ));
 
                menus[menus.length] = createMenu('page-logs',false,Array(
                                                ['c-pl-logs',       'All page logs',    wgScript+'?title=Special:Log&action=view&page='+pname]                  ,
                                                ['c-pl-deletes',    'Deletion log',     wgScript+'?title=Special:Log&type=delete&page='+pname]                  ,
                                                ['c-pl-moves',      'Move log',         wgScript+'?title=Special:Log&action=view&type=move&page='+pname]        ,
                    wgArticleId?                ['c-pl-patrols',    'Patrol log',       wgScript+'?title=Special:Log&action=view&type=patrol&page='+pname]  :[] ,
                                                ['c-pl-protects',   'Protection log',   wgScript+'?title=Special:Log&action=view&type=protect&page='+pname]     ,
                    wgNamespaceNumber == 6?     ['c-pl-uploads',    'Upload log',       wgScript+'?title=Special:Log&action=view&type=upload&page='+pname]  :[]
                ));
            }
 
            hideElements(['ca-protect','ca-unprotect','ca-delete','ca-undelete','ca-history','ca-move'],['c-p-unprotect','c-p-protect','c-p-undelete','p-c-delete']);
            if (!_cactions.vectr) hideElements(['ca-watch','ca-unwatch'],['c-p-unwatch','c-p-watch']);
 
            document.getElementById('c-p-logs').onmouseover = function () {showMenu('opt-page-logs',findPos('c-p-logs',[40,0]))};
            document.getElementById('c-p-logs').onmouseout = function () {hideMenu('opt-page-logs')};
            document.getElementById('c-p-logs').style.fontWeight = 'bold';
        }
    } );
}

/**
 * Action link: Purge (Action menu)
 *
 * @source: http://www.mediawiki.org/wiki/Snippets/Purge_action
 * @rev: 5
 */
$( function() {
    if ( !$( '#ca-purge' ).length && mw.config.get( 'wgIsArticle' ) ) {
        mw.util.addPortletLink(
            'p-cactions',
            mw.util.getUrl( mw.config.get( 'wgPageName' ) ) + '?action=purge',
            mw.config.get( 'skin' ) == 'vector' ? 'Purge' : '*',
            'ca-purge',
            'Purge the server cache of this page',
            '*'
        );
    }
});

// Add [[WP:Reflinks]] launcher in the toolbox on left
$(function () {
 mw.util.addPortletLink(
  "p-tb",     // toolbox portlet
  "http://toolserver.org/~dispenser/cgi-bin/webreflinks.py/" + wgPageName
   + "?client=script&citeweb=on&overwrite=&limit=20&lang=" + wgContentLanguage,
  "Reflinks"  // link label
)});


importScript('User:Anomie/ajaxpreview.js'); // Linkback: [[User:Anomie/ajaxpreview.js]]

importScript('User:Anomie/reftooltip.js'); // Linkback: [[User:Anomie/reftooltip.js]]

LinkClassifierOnDemand=true;
importScript('User:Anomie/linkclassifier.js'); // Linkback: [[User:Anomie/linkclassifier.js]]
importStylesheet('User:Anomie/linkclassifier.css'); // Linkback: [[User:Anomie/linkclassifier.css]]
$(function(){
    mw.util.addPortletLink('p-cactions', 'javascript:LinkClassifier.onDemand()', 'linkclassifier');
});

importScript('User:AzaToth/twinkle.js');


// Todo: make autodate an option in the CiteTemplate object, not a preference
 
// Global object
if (typeof CiteTB == 'undefined') {
  var CiteTB = {
    "Templates" : {}, // All templates
    "Options" : {}, // Global options
    "UserOptions" : {}, // User options
    "DefaultOptions" : {}, // Script defaults
    "ErrorChecks" : {} // Error check functions
  };
}
 
// only load on edit, unless its a user JS/CSS page
if ((wgAction == 'edit' || wgAction == 'submit') && !((wgNamespaceNumber == 2 || wgNamespaceNumber == 4) &&
  (wgPageName.indexOf('.js') != -1 || wgPageName.indexOf('.css') != -1 ))) {
 
appendCSS(".cite-form-td {"+
"height: 0 !important;"+
"padding: 0.1em !important;"+
"}");  
 
// Default options, these mainly exist so the script won't break if a new option is added
CiteTB.DefaultOptions = {
  "date format" : "<year>-<zmonth>-<zdate>",
  "autodate fields" : [],
  "months" : ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  "modal" : true,
  "autoparse" : false,
  "expandtemplates": false
};
// Get an option - user settings override global which override defaults
CiteTB.getOption = function(opt) {
  if (CiteTB.UserOptions[opt] != undefined) {
    return CiteTB.UserOptions[opt];
  } else if (CiteTB.Options[opt] != undefined) {
    return CiteTB.Options[opt];
  }
  return CiteTB.DefaultOptions[opt];
}
 
CiteTB.init = function() {
  /* Main stuff, build the actual toolbar structure
   * 1. get the template list, make the dropdown list and set up the template dialog boxes
   * 2. actually build the toolbar:
   *    * A section for cites
   *    ** dropdown for the templates (previously defined)
   *    ** button for named refs with a dialog box
   *    ** button for errorcheck
   * 3. add the whole thing to the main toolbar
  */
 
  if (typeof $('div[rel=cites]')[0] != 'undefined') { // Mystery IE bug workaround
    return;
  }
  $('head').trigger('reftoolbarbase');
  var $target = $('#wpTextbox1');
  var temlist = {};
  var d = new Date();
  var start = d.getTime();
  for (var t in CiteTB.Templates) {
  	var tem = CiteTB.Templates[t];
    sform = CiteTB.escStr(tem.shortform);
    var actionobj = { 
      type: 'dialog',
      module: 'cite-dialog-'+sform
    };
    var dialogobj = {};
    dialogobj['cite-dialog-'+sform] = {
      resizeme: false,
      titleMsg: 'cite-dialog-'+sform, 
      id: 'citetoolbar-'+sform,
      init: function() {}, 
      html: tem.getInitial(), 
      dialog: {
        width:675,
        open: function() { 
          $(this).html(CiteTB.getOpenTemplate().getForm());
          $('.cite-prev-parse').bind( 'click', CiteTB.prevParseClick);
        },
        beforeclose: function() {
          CiteTB.resetForm();
        },
        buttons: {
          'cite-form-submit': function() {
            $.wikiEditor.modules.toolbar.fn.doAction( $(this).data( 'context' ), {
              type: 'encapsulate',
              options: {
                peri: ' '
              }
            }, $(this) );
            var ref = CiteTB.getRef(false, true);
            $(this).dialog( 'close' );
            $.wikiEditor.modules.toolbar.fn.doAction( $(this).data( 'context' ), {
              type: 'encapsulate',
              options: {
                pre: ref
              }
            }, $(this) );
          },
          'cite-form-showhide': CiteTB.showHideExtra,
          'cite-refpreview': function() {   
            var ref = CiteTB.getRef(false, false);
            var template = CiteTB.getOpenTemplate();
            var div = $("#citetoolbar-"+CiteTB.escStr(template.shortform));
            div.find('.cite-preview-label').show();
            div.find('.cite-ref-preview').text(ref).show();
            if (CiteTB.getOption('autoparse')) {
              CiteTB.prevParseClick();
            } else {
              div.find('.cite-prev-parse').show();
              div.find('.cite-prev-parsed-label').hide();
              div.find('.cite-preview-parsed').html('');
            }         
          },
          'wikieditor-toolbar-tool-link-cancel': function() {
            $(this).dialog( 'close' );
          },
          'cite-form-reset': function() {
            CiteTB.resetForm();
          }
        }
      } 
    };
    $target.wikiEditor('addDialog', dialogobj);
    if (!CiteTB.getOption('modal')) {
      //$('#citetoolbar-'+sform).dialog('option', 'modal', false);
    }
    temlist[sform] = {label: tem.templatename, action: actionobj };  
  }
 
  var refsection =  {
    'sections': {
      'cites': { 
        type: 'toolbar', 
        labelMsg: 'cite-section-label',
        groups: { 
          'template': {
            tools: {
              'template': {
                type: 'select',
                labelMsg: 'cite-template-list',
                list: temlist
              } 
            }
          },
          'namedrefs': {
            labelMsg: 'cite-named-refs-label',
            tools: {
              'nrefs': {
                type: 'button',
                action: {
                  type: 'dialog',
                  module: 'cite-toolbar-namedrefs'
                },
                icon: '//upload.wikimedia.org/wikipedia/commons/thumb/b/be/Nuvola_clipboard_lined.svg/22px-Nuvola_clipboard_lined.svg.png',
                section: 'cites',
                group: 'namedrefs',
                labelMsg: 'cite-named-refs-button'
              }
            }
          },
          'errorcheck': {
            labelMsg: 'cite-errorcheck-label',
            tools: {
              'echeck': {
                type: 'button',
                action: {
                  type: 'dialog',
                  module: 'cite-toolbar-errorcheck'           
                },
                icon: '//upload.wikimedia.org/wikipedia/commons/thumb/a/a3/Nuvola_apps_korganizer-NO.png/22px-Nuvola_apps_korganizer-NO.png',
                section: 'cites',
                group: 'errorcheck',
                labelMsg: 'cite-errorcheck-button'
              }
            }
          }
        } 
      } 
    } 
  };
 
  var defaultdialogs = { 
    'cite-toolbar-errorcheck': {
      titleMsg: 'cite-errorcheck-label',
      id: 'citetoolbar-errorcheck',
      resizeme: false,
      init: function() {},
      html: '<div id="cite-namedref-loading">'+
        '<img src="//upload.wikimedia.org/wikipedia/commons/4/42/Loading.gif" />'+
        '&nbsp;'+mw.usability.getMsg('cite-loading')+'</div>',
      dialog: {
        width:550,
        open: function() { 
          CiteTB.loadRefs();
        },
        buttons: {
          'cite-errorcheck-submit': function() {
            var errorchecks = $("input[name='cite-err-test']:checked");
            var errors = [];
            for (var i=0; i<errorchecks.length; i++) {
              errors = errors.concat(CiteTB.ErrorChecks[$(errorchecks[i]).val()].run());
            }
            CiteTB.displayErrors(errors);
            $(this).dialog( 'close' );                      
          },
          'wikieditor-toolbar-tool-link-cancel': function() {
            $(this).dialog( 'close' );
          }
        }
      }
    },
    'cite-toolbar-namedrefs': {
      titleMsg: 'cite-named-refs-title',
      resizeme: false,
      id: 'citetoolbar-namedrefs',
      html: '<div id="cite-namedref-loading">'+
        '<img src="//upload.wikimedia.org/wikipedia/commons/4/42/Loading.gif" />'+
        '&nbsp;'+mw.usability.getMsg('cite-loading')+'</div>',
      init: function() {},
      dialog: {
        width: 550,
        open: function() { 
          CiteTB.loadRefs();
        },
        buttons: {
          'cite-form-submit': function() {
            var refname = $("#cite-namedref-select").val();
            if (refname == '') {
              return;
            }
            $.wikiEditor.modules.toolbar.fn.doAction( $(this).data( 'context' ), {
              type: 'encapsulate',
              options: {
                peri: ' '
              }
            }, $(this) );
            $(this).dialog( 'close' );
            $.wikiEditor.modules.toolbar.fn.doAction( $(this).data( 'context' ), {
              type: 'encapsulate',
              options: {
                pre: CiteTB.getNamedRef(refname, true)
              }
            }, $(this) );
          },
          'wikieditor-toolbar-tool-link-cancel': function() {
            $(this).dialog( 'close' );
          }                   
        }
      }      
    }
  };
 
  $target.wikiEditor('addDialog', defaultdialogs);
  $('#citetoolbar-namedrefs').unbind('dialogopen');
  if (!CiteTB.getOption('modal')) {
    //$('#citetoolbar-namedrefs').dialog('option', 'modal', false);
    //$('#citetoolbar-errorcheck').dialog('option', 'modal', false);
    appendCSS(".ui-widget-overlay {"+
    "display:none !important;"+
    "}");  
  }
  $target.wikiEditor('addToToolbar', refsection);
} 
 
// Load local data - messages, cite templates, etc.
$(document).ready( function() {
  switch( wgUserLanguage ) {
    case 'de': // German
      var RefToolbarMessages = importScript('MediaWiki:RefToolbarMessages-de.js');
      break;
    default: // English
      var RefToolbarMessages = importScript('MediaWiki:RefToolbarMessages-en.js');
  }
});
 
// Setup the main object
CiteTB.mainRefList = [];
CiteTB.refsLoaded = false;
 
// REF FUNCTIONS
// Actually assemble a ref from user input
CiteTB.getRef = function(inneronly, forinsert) {
  var template = CiteTB.getOpenTemplate();
  var templatename = template.templatename;
  var res = '';
  var refobj = {'shorttag':false};
  if (!inneronly) {
    var group = $('#cite-'+CiteTB.escStr(template.shortform)+'-group').val();
    var refname = $('#cite-'+CiteTB.escStr(template.shortform)+'-name').val();
    res += '<ref';
    if (refname) {
      refname = $.trim(refname);
      res+=' name='+CiteTB.getQuotedString(refname);
      refobj.refname = refname;
    }
    if (group) {
      group = $.trim(group);
      res+=' group='+CiteTB.getQuotedString(group);
      refobj.refgroup = group;
    }
    res+='>';
  }
  var content ='{{'+templatename;
  for( var i=0; i<template.basic.length; i++ ) {
    var fieldname = template.basic[i].field;
    var field = $('#cite-'+CiteTB.escStr(template.shortform)+'-'+fieldname).val();
    if (field) {
      content+='|'+fieldname+'=';
      content+= $.trim(field.replace("|", "{{!}}"));
    }
  }
  if ($('#cite-form-status').val() != 'closed') {
    for( var i=0; i<template.extra.length; i++ ) {
      var fieldname = template.extra[i].field;
      var field = $('#cite-'+CiteTB.escStr(template.shortform)+'-'+fieldname).val();
      if (field) {
        content+='|'+fieldname+'=';
        content+= $.trim(field.replace("|", "{{!}}"));
      }
    }
  }
  content+= '}}';
  res+=content;
  refobj.content = content;
  if (!inneronly) {
    res+= '</ref>';
  }
  if (forinsert) {
    CiteTB.mainRefList.push(refobj);
  }
  return res;
}
 
// Make a reference to a named ref
CiteTB.getNamedRef = function(refname, forinsert) {
  var inner = 'name=';
  if (forinsert) {
    CiteTB.mainRefList.push( {'shorttag':true, 'refname':refname} );
  }
  return '<ref name='+CiteTB.getQuotedString(refname)+' />';  
}
 
// Function to load the ref list
CiteTB.loadRefs = function() {
  if (CiteTB.refsLoaded) {
    return;
  }
  CiteTB.getPageText(CiteTB.loadRefsInternal);
}
 
// Function that actually loads the list from the page text
CiteTB.loadRefsInternal = function(text) { 
  // What this does:             extract first name/group                                     extract second name/group                                          shorttag   inner content
  var refsregex = /< *ref(?: +(name|group) *= *(?:"([^"]*?)"|'([^']*?)'|([^ '"\/\>]*?)) *)? *(?: +(name|group) *= *(?:"([^"]*?)"|'([^']*?)'|([^ '"\/\>]*?)) *)? *(?:\/ *>|>((?:.|\n)*?)< *\/ *ref *>)/gim
  // This should work regardless of the quoting used for names/groups and for linebreaks in the inner content  
  while (true) {
    var ref = refsregex.exec(text);
    if (ref == null) {
      break;
    }
    var refobj = {};
    if (ref[9]) { // Content + short tag check
      //alert('"'+ref[9]+'"');
      refobj['content'] = ref[9]; 
      refobj['shorttag'] = false;
    } else {
      refobj['shorttag'] = true;
    }
    if (ref[1] != '') { // First name/group
      if (ref[2]) {
        refobj['ref'+ref[1]] = ref[2];
      } else if (ref[3]) {
        refobj['ref'+ref[1]] = ref[3];
      } else {
        refobj['ref'+ref[1]] = ref[4];
      }
    }
    if (ref[5] != '') { // Second name/group
      if (ref[6]) {
        refobj['ref'+ref[5]] = ref[6];
      } else if (ref[7]) {
        refobj['ref'+ref[5]] = ref[7];
      } else {
        refobj['ref'+ref[5]] = ref[8];
      }
    }
    CiteTB.mainRefList.push(refobj);
  }
  CiteTB.refsLoaded = true;
  CiteTB.setupErrorCheck();
  CiteTB.setupNamedRefs()
}
 
// AJAX FUNCTIONS
// Parse some wikitext and hand it off to a callback function
CiteTB.parse = function(text, callback) {
  $.post( mw.config.get('wgServer')+mw.config.get('wgScriptPath')+'/api.php',
    {action:'parse', title:wgPageName, text:text, prop:'text', format:'json'},
    function(data) {
      var html = data['parse']['text']['*'];
      callback(html);
    },
    'json'
  );  
}
 
// Use the API to expand templates on some text
CiteTB.expandtemplates = function(text, callback) {
  $.post( mw.config.get('wgServer')+mw.config.get('wgScriptPath')+'/api.php',
    {action:'expandtemplates', title:wgPageName, text:text, format:'json'},
    function(data) {
      var restext = data['expandtemplates']['*'];
      callback(restext);
    },
    'json'
  );
}
 
// Function to get the page text
CiteTB.getPageText = function(callback) {
  var section = $("input[name='wpSection']").val();
  if ( section != '' ) {
    var postdata = {action:'query', prop:'revisions', rvprop:'content', pageids:wgArticleId, format:'json'};
    if (CiteTB.getOption('expandtemplates')) {
      postdata['rvexpandtemplates'] = '1';
    }
    $.get( mw.config.get('wgServer')+mw.config.get('wgScriptPath')+'/api.php',
      postdata,
      function(data) {
        var pagetext = data['query']['pages'][wgArticleId.toString()]['revisions'][0]['*'];
        callback(pagetext);
      },
      'json'
    );
  } else {
    if (CiteTB.getOption('expandtemplates')) {
      CiteTB.expandtemplates($('#wpTextbox1').wikiEditor('getContents').text(), callback);
    } else {
      callback($('#wpTextbox1').wikiEditor('getContents').text());
    }
  }
}
 
// Autofill a template from an ID (ISBN, DOI, PMID)
CiteTB.initAutofill = function() {
  var elemid = $(this).attr('id');
  var res = /^cite\-auto\-(.*?)\-(.*)\-(.*)$/.exec(elemid);
  var tem = res[1];
  var field = res[2];
  var autotype = res[3];
  var id = $('#cite-'+tem+'-'+field).val();
  if (!id) {
    return false;
  }
  var url = 'http://toolserver.org/~alexz/ref/lookup.php?';
  url+=autotype+'='+encodeURIComponent(id);
  url+='&template='+encodeURIComponent(tem);
  var s = document.createElement('script');
  s.setAttribute('src', url);
  s.setAttribute('type', 'text/javascript');
  document.getElementsByTagName('head')[0].appendChild(s);
  return false;
}
 
// Callback for autofill
//TODO: Autofill the URL, at least for DOI
CiteTB.autoFill = function(data, template, type) {
  var cl = 'cite-'+template+'-';
  $('.'+cl+'title').val(data.title);
  if ($('.'+cl+'last1').length != 0) {
    for(var i=0; i<data.authors.length; i++) {
	  if ($('.'+cl+'last'+(i+1)).length) {
	     $('.'+cl+'last'+(i+1)).val(data.authors[i][0]);
		 $('.'+cl+'first'+(i+1)).val(data.authors[i][1]);
	  } else {
	    var coauthors = [];
	    for(var j=i; j<data.authors.length; j++) {
		  coauthors.push(data.authors[j].join(', '));
		}
		$('.'+cl+'coauthors').val(coauthors.join('; '));
		break;
	  }
	}
  } else if($('.'+cl+'author1').length != 0) {
    for(var i=0; i<data.authors.length; i++) {
	  if ($('.'+cl+'author'+(i+1)).length) {
	     $('.'+cl+'author'+(i+1)).val(data.authors[i].join(', '));
	  } else {
	    var coauthors = [];
	    for(var j=i; j<data.authors.length; j++) {
		  coauthors.push(data.authors[j].join(', '));
		}
		$('.'+cl+'coauthors').val(coauthors.join('; '));
		break;
	  }
	}
  } else {
    var authors = [];
	for(var i=0; i<data.authors.length; i++) {
	  authors.push(data.authors[i].join(', '));
	}
	$('.'+cl+'authors').val(authors.join('; '));
  }  
  if (type == 'pmid' || type == 'doi') {
    if (type == 'doi') {
      var DT = new Date(data.date);
      $('.'+cl+'date').val(CiteTB.formatDate(DT));
    } else {
      $('.'+cl+'date').val(data.date);
    }
    $('.'+cl+'journal').val(data.journal);
    $('.'+cl+'volume').val(data.volume);
    $('.'+cl+'issue').val(data.issue);
    $('.'+cl+'pages').val(data.pages);
  } else if (type == 'isbn') {
    $('.'+cl+'publisher').val(data.publisher);
    $('.'+cl+'location').val(data.location);
    $('.'+cl+'year').val(data.year);
    $('.'+cl+'edition').val(data.edition);
  }
}
 
// FORM DIALOG FUNCTIONS
// fill the accessdate param with the current date
CiteTB.fillAccessdate = function() {
  var elemid = $(this).attr('id');
  var res = /^cite\-date\-(.*?)\-(.*)$/.exec(elemid);
  var id = res[1];
  var field = res[2];
  var DT = new Date();
  datestr = CiteTB.formatDate(DT);
  $('#cite-'+id+'-'+field).val(datestr);
  return false;
}
 
CiteTB.formatDate = function(DT) {
  var datestr = CiteTB.getOption('date format');
  var zmonth = '';
  var month = DT.getUTCMonth()+1;
  if (month < 10) {
    zmonth = "0"+month.toString();
  } else {
    zmonth = month.toString();
  }
  month = month.toString();
  var zdate = '';
  var date = DT.getUTCDate();
  if (date < 10) {
    zdate = "0"+date.toString();
  } else {
    zdate = date.toString();
  }
  date = date.toString()
  datestr = datestr.replace('<date>', date);
  datestr = datestr.replace('<month>', month);
  datestr = datestr.replace('<zdate>', zdate);
  datestr = datestr.replace('<zmonth>', zmonth);
  datestr = datestr.replace('<monthname>', CiteTB.getOption('months')[DT.getUTCMonth()]);
  datestr = datestr.replace('<year>', DT.getUTCFullYear().toString());
  return datestr;
}
 
// Function called after the ref list is loaded, to actually set the contents of the named ref dialog
// Until the list is loaded, its just a "Loading" placeholder
CiteTB.setupNamedRefs = function() {
  var names = []
  for( var i=0; i<CiteTB.mainRefList.length; i++) {
    if (!CiteTB.mainRefList[i].shorttag && CiteTB.mainRefList[i].refname) {
      names.push(CiteTB.mainRefList[i]);
    }
  }
  var stuff = $('<div />')
  $('#citetoolbar-namedrefs').html( stuff );
  if (names.length == 0) {
    stuff.html(mw.usability.getMsg('cite-no-namedrefs'));
  } else {
    stuff.html(mw.usability.getMsg('cite-namedrefs-intro'));
    var select = $('<select id="cite-namedref-select">');
    select.append($('<option value="" />').text(mw.usability.getMsg('cite-named-refs-dropdown')));
    for(var i=0; i<names.length; i++) {
      select.append($('<option />').text(names[i].refname));
    }
    stuff.after(select);
    select.before('<br />');      
    var prevlabel = $('<div id="cite-nref-preview-label" style="display:none;" />').html(mw.usability.getMsg('cite-raw-preview'));
    select.after(prevlabel);
    prevlabel.before("<br /><br />");
    prevlabel.after('<div id="cite-namedref-preview" style="padding:0.5em; font-size:110%" />');
    var parselabel = $('<span id="cite-parsed-label" style="display:none;" />').html(mw.usability.getMsg('cite-parsed-label'));
    $('#cite-namedref-preview').after(parselabel);
    parselabel.after('<div id="cite-namedref-parsed" style="padding-bottom:0.5em; font-size:110%" />');
    var link = $('<a href="#" id="cite-nref-parse" style="margin:0 1em 0 1em; display:none; color:darkblue" />');
    link.html(mw.usability.getMsg('cite-form-parse'));
    $('#cite-namedref-parsed').after(link);
 
    $("#cite-namedref-select").bind( 'change', CiteTB.namedRefSelectClick);
    $('#cite-nref-parse').bind( 'click', CiteTB.nrefParseClick);
  }      
}
 
// Function to get the errorcheck form HTML
CiteTB.setupErrorCheck = function() {
  var form = $('<div id="cite-errorcheck-heading" />').html(mw.usability.getMsg('cite-errorcheck-heading'));
  var ul = $("<ul id='cite-errcheck-list' />");
  for (var t in CiteTB.ErrorChecks) {
    test = CiteTB.ErrorChecks[t];
    ul.append(test.getRow());
  }
  form.append(ul);
  $('#citetoolbar-errorcheck').html(form);
}
 
// Callback function for parsed preview
CiteTB.fillNrefPreview = function(parsed) {
  $('#cite-parsed-label').show();
  $('#cite-namedref-parsed').html(parsed);
}
 
// Click handler for the named-ref parsed preview
CiteTB.nrefParseClick = function() {
  var choice = $("#cite-namedref-select").val();
  if (choice == '') {
    $('#cite-parsed-label').hide();
    $('#cite-namedref-parsed').text('');
    return false;
  }
  $('#cite-nref-parse').hide();
  for( var i=0; i<CiteTB.mainRefList.length; i++) {
    if (!CiteTB.mainRefList[i].shorttag && CiteTB.mainRefList[i].refname == choice) {
      CiteTB.parse(CiteTB.mainRefList[i].content, CiteTB.fillNrefPreview);
      return false;
    }
  }  
}
 
// Click handler for the named-ref dropdown
CiteTB.lastnamedrefchoice = '';
CiteTB.namedRefSelectClick = function() {
  var choice = $("#cite-namedref-select").val();
  if (CiteTB.lastnamedrefchoice == choice) {
    return;
  }
  CiteTB.lastnamedrefchoice = choice;
  $('#cite-parsed-label').hide();
  $('#cite-namedref-parsed').text('');
  if (choice == '') {
    $('#cite-nref-preview-label').hide();
    $('#cite-namedref-preview').text('');
    $('#cite-nref-parse').hide();
    return;
  }
  for( var i=0; i<CiteTB.mainRefList.length; i++) {
    if (!CiteTB.mainRefList[i].shorttag && CiteTB.mainRefList[i].refname == choice) {
      $('#cite-nref-preview-label').show();
      $('#cite-namedref-preview').text(CiteTB.mainRefList[i].content);
      if (CiteTB.getOption('autoparse')) {
        CiteTB.nrefParseClick();
      } else {
        $('#cite-nref-parse').show();
      }
    }
  }
}
 
// callback function for parsed preview
CiteTB.fillTemplatePreview = function(text) {
  var template = CiteTB.getOpenTemplate();
  var div = $("#citetoolbar-"+CiteTB.escStr(template.shortform));
  div.find('.cite-prev-parsed-label').show();
  div.find('.cite-preview-parsed').html(text);
}
 
// Click handler for template parsed preview
CiteTB.prevParseClick = function() {
  var ref = CiteTB.getRef(true, false);
  var template = CiteTB.getOpenTemplate();
  var div = $("#citetoolbar-"+CiteTB.escStr(template.shortform));
  div.find('.cite-prev-parse').hide();
  CiteTB.parse(ref, CiteTB.fillTemplatePreview);
}
 
// Show/hide the extra fields in the dialog box
CiteTB.showHideExtra = function() {
  var template = CiteTB.getOpenTemplate();
  var div = $("#citetoolbar-"+CiteTB.escStr(template.shortform));
  var setting = div.find(".cite-form-status").val();
  if ( setting == 'closed' ) {
    div.find(".cite-form-status").val('open');
    div.find('.cite-extra-fields').show(1, function() {
      // jQuery adds "display:block", which screws things up
      div.find('.cite-extra-fields').attr('style', 'width:100%; background-color:transparent;'); 
    });
  } else {
    div.find(".cite-form-status").val('closed')
    div.find('.cite-extra-fields').hide();
  } 
}
 
// Resets form fields and previews
CiteTB.resetForm = function() {
  var template = CiteTB.getOpenTemplate();
  var div = $("#citetoolbar-"+CiteTB.escStr(template.shortform));
  div.find('.cite-preview-label').hide();
  div.find('.cite-ref-preview').text('').hide();
  div.find('.cite-prev-parsed-label').hide();
  div.find('.cite-preview-parsed').html('');
  div.find('.cite-prev-parse').hide();
  var id = CiteTB.escStr(template.shortform);
  $('#citetoolbar-'+id+' input[type=text]').val('');
}
 
// STRING UTILITY FUNCTIONS
// Returns a string quoted as necessary for name/group attributes
CiteTB.getQuotedString = function(s) {
  var sp = /\s/.test(s); // spaces
  var sq = /\'/.test(s); // single quotes
  var dq = /\"/.test(s); // double quotes
  if (!sp && !sq && !dq) { // No quotes necessary
    return s;
  } else if (!dq) { // Can use double quotes
    return '"'+s+'"';
  } else if (!sq) { // Can use single quotes
    return "'"+s+"'";
  } else { // Has double and single quotes
    s = s.replace(/\"/g, '\"');
    return '"'+s+'"';
  }
} 
// Fix up strings for output - capitalize first char, replace underscores with spaces
CiteTB.fixStr = function(s) {
  s = s.slice(0,1).toUpperCase() + s.slice(1);
  s = s.replace('_',' ');
  return s;
}
// Escape spaces and quotes for use in HTML classes/ids
CiteTB.escStr = function(s) {
  return s.replace(' ', '-').replace("'", "\'").replace('"', '\"');
}
 
// MISC FUNCTIONS
// Determine which template form is open, and get the template object for it
CiteTB.getOpenTemplate = function() {
  var dialogs = $(".ui-dialog-content.ui-widget-content:visible");
  var templatename = $(dialogs[0]).find(".cite-template").val();
  var template = null;
  return CiteTB.Templates[templatename];
}
 
// Display the report for the error checks
CiteTB.displayErrors = function(errors) {
  $('#cite-err-report').remove();
  var table = $('<table id="cite-err-report" style="width:100%; border:1px solid #A9A9A9; background-color:#FFEFD5; padding:0.25em; margin-top:0.5em" />');
  $('#editpage-copywarn').before(table);
  var tr1 = $('<tr style="width:100%" />');
  var th1 = $('<th style="width:60%; font-size:110%" />').html(mw.usability.getMsg('cite-err-report-heading'));
  var th2 = $('<th style="text-align:right; width:40%" />');
  im = $('<img />').attr('src', '//upload.wikimedia.org/wikipedia/commons/thumb/5/55/Gtk-stop.svg/20px-Gtk-stop.svg.png');
  im.attr('alt', mw.usability.getMsg('cite-err-report-close')).attr('title', mw.usability.getMsg('cite-err-report-close'));
  var ad = $('<a id="cite-err-check-close" />').attr('href', '#');
  ad.append(im);
  th2.append(ad);
  tr1.append(th1).append(th2);
  table.append(tr1);
  $('#cite-err-check-close').bind('click', function() {  $('#cite-err-report').remove(); });
  if (errors.length == 0) {
    var tr = $('<tr style="width:100%;" />');
    var td = $('<td style="text-align:center; margin:1.5px;" />').html(mw.usability.getMsg('cite-err-report-empty'));
    tr.append(td);
    table.append(tr);
 
    return;
  }
  for(var e in errors) {
    var err = errors[e];
    var tr = $('<tr style="width:100%;" />');
    var td1 = $('<td style="border: 1px solid black; margin:1.5px; width:60%" />').html(err.err);
    var td2 = $('<td style="border: 1px solid black; margin:1.5px; width:40%" />').html(mw.usability.getMsg(err.msg));
    tr.append(td1).append(td2);
    table.append(tr);
  }
}
 
} // End of code loaded only on edit