No edit summary
No edit summary
 
(One intermediate revision by the same user not shown)
Line 1: Line 1:
/*jshint smarttabs:true, loopfunc:true,forin:false*/
/* jshint smarttabs:true, loopfunc:true, forin:false */
/*global mw, $ */
/* global mw, $ */
// TODO: make autodate an option in the CiteTemplate object, not a preference
// TODO: make autodate an option in the CiteTemplate object, not a preference


Line 7: Line 7:
// * Remove this once the page is moved to a module 'ext.gadget.refToolbarDialogs' depending on 'ext.gadget.refToolbarBase'
// * Remove this once the page is moved to a module 'ext.gadget.refToolbarDialogs' depending on 'ext.gadget.refToolbarBase'
if (typeof CiteTB === 'undefined') {
if (typeof CiteTB === 'undefined') {
  var CiteTB = {
var CiteTB = {
    "Templates" : {}, // All templates
"Templates": {}, // All templates
    "Options" : {}, // Global options
"Options": {}, // Global options
    "UserOptions" : {}, // User options
"UserOptions": {}, // User options
    "DefaultOptions" : {}, // Script defaults
"DefaultOptions": {}, // Script defaults
    "ErrorChecks" : {} // Error check functions
"ErrorChecks": {} // Error check functions
  };
};
}
}
// Only execute when editing/previewing wikitext pages
// TODO: Remove tests already done by [[MediaWiki:Gadget-refToolbar.js]]
if (
['edit', 'submit'].indexOf( mw.config.get('wgAction') ) !== -1 &&
mw.config.get('wgPageContentModel') === 'wikitext'
) {


// TODO: Move this to [[MediaWiki:Gadget-refToolbarDialogs.css]] and add it to the definition of module 'ext.gadget.refToolbarDialogs'
// TODO: Move this to [[MediaWiki:Gadget-refToolbarDialogs.css]] and add it to the definition of module 'ext.gadget.refToolbarDialogs'
mw.util.addCSS(".cite-form-td {"+
mw.util.addCSS(".cite-form-td {" +
"height: 0 !important;"+
"height: 0 !important;" +
"padding: 0.1em !important;"+
"padding: 0.1em !important;" +
"}");
"}");


// Default options, these mainly exist so the script won't break if a new option is added
// Default options, these mainly exist so the script won't break if a new option is added
CiteTB.DefaultOptions = {
CiteTB.DefaultOptions = {
  "date format" : "<year>-<zmonth>-<zdate>",
"date format": "<year>-<zmonth>-<zdate>",
  "autodate fields" : [],
"autodate fields": [],
  "months" : ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
"months": ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  "modal" : true,
"modal": true,
  "autoparse" : false,
"autoparse": false,
  "expandtemplates": false
"expandtemplates": false
};
};


// Get an option - user settings override global which override defaults
// Get an option - user settings override global which override defaults
CiteTB.getOption = function(opt) {
CiteTB.getOption = function (opt) {
  if (CiteTB.UserOptions[opt] !== undefined) {
if (CiteTB.UserOptions[opt] !== undefined) {
    return CiteTB.UserOptions[opt];
return CiteTB.UserOptions[opt];
  } else if (CiteTB.Options[opt] !== undefined) {
} else if (CiteTB.Options[opt] !== undefined) {
    return CiteTB.Options[opt];
return CiteTB.Options[opt];
  }
}
  return CiteTB.DefaultOptions[opt];
return CiteTB.DefaultOptions[opt];
};
};


CiteTB.init = function() {
CiteTB.init = function () {
  /* Main stuff, build the actual toolbar structure
/* Main stuff, build the actual toolbar structure
  * 1. get the template list, make the dropdown list and set up the template dialog boxes
* 1. get the template list, make the dropdown list and set up the template dialog boxes
  * 2. actually build the toolbar:
* 2. actually build the toolbar:
  *    * A section for cites
*    * A section for cites
  *    ** dropdown for the templates (previously defined)
*    ** dropdown for the templates (previously defined)
  *    ** button for named refs with a dialog box
*    ** button for named refs with a dialog box
  *    ** button for errorcheck
*    ** button for errorcheck
  * 3. add the whole thing to the main toolbar
* 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 = {};
for (var t in CiteTB.Templates) {
var tem = CiteTB.Templates[t];
var sform = CiteTB.escStr(tem.shortform);
var actionobj = {
type: 'dialog',
module: 'cite-dialog-' + sform
};
var dialogobj = {};
dialogobj['cite-dialog-' + sform] = {
resizeme: false,
title: mw.message('cite-dialog-' + sform),
id: 'citetoolbar-' + sform,
init: function () {
},
html: tem.getInitial(),
dialog: {
width: 680,
open: function () {
$(this).html(CiteTB.getOpenTemplate().getForm());
/** @param {jQuery.Event} e */
$('.cite-prev-parse').on('click', function (e) {
e.preventDefault();
CiteTB.prevParseClick();
});
},
buttons: {
'cite-form-submit': function () {
var ref = CiteTB.getRef(false, true);
$(this).dialog('close');
$.wikiEditor.modules.toolbar.fn.doAction($(this).data('context'), {
type: 'encapsulate',
options: {
post: 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();
}
}
}
};
try {
$target.wikiEditor('addDialog', dialogobj);
} catch (e) {
// TypeError: range is null
}
//if (!CiteTB.getOption('modal')) {
//$('#citetoolbar-'+sform).dialog('option', 'modal', false);
//}
temlist[sform] = {label: tem.templatename, action: actionobj};
}
 
var refsection = {
'sections': {
'cites': {
type: 'toolbar',
label: mw.msg('cite-section-label'),
groups: {
'template': {
tools: {
'template': {
type: 'select',
label: mw.msg('cite-template-list'),
list: temlist
}
}
},
'namedrefs': {
label: mw.msg('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/60px-Nuvola_clipboard_lined.svg.png',
section: 'cites',
group: 'namedrefs',
label: mw.msg('cite-named-refs-button')
}
}
},
'errorcheck': {
label: mw.msg('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/60px-Nuvola_apps_korganizer-NO.png',
section: 'cites',
group: 'errorcheck',
label: mw.msg('cite-errorcheck-button')
}
}
}
}
}
}
};


  if (typeof $('div[rel=cites]')[0] !== 'undefined') { // Mystery IE bug workaround
var defaultdialogs = {
    return;
'cite-toolbar-errorcheck': {
  }
title: mw.message('cite-errorcheck-label'),
  $('head').trigger('reftoolbarbase');
id: 'citetoolbar-errorcheck',
  var $target = $('#wpTextbox1');
resizeme: false,
  var temlist = {};
init: function () {
  for (var t in CiteTB.Templates) {
},
    var tem = CiteTB.Templates[t];
html: '<div id="cite-namedref-loading">' +
    var sform = CiteTB.escStr(tem.shortform);
'<img src="//upload.wikimedia.org/wikipedia/commons/4/42/Loading.gif" />' +
    var actionobj = {
'&nbsp;' + mw.messages.get('cite-loading') + '</div>',
      type: 'dialog',
dialog: {
      module: 'cite-dialog-'+sform
width: 550,
    };
open: function () {
    var dialogobj = {};
CiteTB.loadRefs();
    dialogobj['cite-dialog-'+sform] = {
},
      resizeme: false,
buttons: {
      titleMsg: 'cite-dialog-'+sform,
'cite-errorcheck-submit': function () {
      id: 'citetoolbar-'+sform,
var errorchecks = $("input[name='cite-err-test']:checked");
      init: function() {},
var errors = [];
      html: tem.getInitial(),
for (var i = 0; i < errorchecks.length; i++) {
      dialog: {
errors = errors.concat(CiteTB.ErrorChecks[$(errorchecks[i]).val()].run());
        width:680,
}
        open: function() {  
CiteTB.displayErrors(errors);
          $(this).html(CiteTB.getOpenTemplate().getForm());
$(this).dialog('close');
          /** @param {jQuery.Event} e */
},
          $('.cite-prev-parse').on( 'click', function ( e ) {
'wikieditor-toolbar-tool-link-cancel': function () {
            e.preventDefault();
$(this).dialog('close');
            CiteTB.prevParseClick();
}
          });
}
        },
}
        buttons: {
},
          'cite-form-submit': function() {
'cite-toolbar-namedrefs': {
            var ref = CiteTB.getRef(false, true);
title: mw.message('cite-named-refs-title'),
            $(this).dialog( 'close' );
resizeme: false,
            $.wikiEditor.modules.toolbar.fn.doAction( $(this).data( 'context' ), {
id: 'citetoolbar-namedrefs',
              type: 'encapsulate',
html: '<div id="cite-namedref-loading">' +
              options: {
'<img src="//upload.wikimedia.org/wikipedia/commons/4/42/Loading.gif" />' +
                post: ref
'&nbsp;' + mw.messages.get('cite-loading') + '</div>',
              }
init: function () {
            }, $(this) );
},
          },
dialog: {
          'cite-form-showhide': CiteTB.showHideExtra,
width: 550,
          'cite-refpreview': function() { 
open: function () {
            var ref = CiteTB.getRef(false, false);
CiteTB.loadRefs();
            var template = CiteTB.getOpenTemplate();
},
            var div = $("#citetoolbar-"+CiteTB.escStr(template.shortform));
buttons: {
            div.find('.cite-preview-label').show();
'cite-form-submit': function () {
            div.find('.cite-ref-preview').text(ref).show();
var refname = $("#cite-namedref-select").val();
            if (CiteTB.getOption('autoparse')) {
if (refname === '') {
              CiteTB.prevParseClick();
return;
            } else {
}
              div.find('.cite-prev-parse').show();
$(this).dialog('close');
              div.find('.cite-prev-parsed-label').hide();
$.wikiEditor.modules.toolbar.fn.doAction($(this).data('context'), {
              div.find('.cite-preview-parsed').html('');
type: 'encapsulate',
            }       
options: {
          },
post: CiteTB.getNamedRef(refname, true)
          'wikieditor-toolbar-tool-link-cancel': function() {
}
            $(this).dialog( 'close' );
}, $(this));
          },
},
          'cite-form-reset': function() {
'wikieditor-toolbar-tool-link-cancel': function () {
            CiteTB.resetForm();
$(this).dialog('close');
          }
}
        }
}
      }
}
    };
}
    try {
};
        $target.wikiEditor('addDialog', dialogobj);
    } catch (e) {
        // TypeError: range is null
    }
    //if (!CiteTB.getOption('modal')) {
      //$('#citetoolbar-'+sform).dialog('option', 'modal', false);
    //}
    temlist[sform] = {label: tem.templatename, action: actionobj }; 
  }


  var refsection =  {
try {
    'sections': {
$target.wikiEditor('addDialog', defaultdialogs);
      'cites': {
} catch (e) {
        type: 'toolbar',
// error occurred setting up wikieditor.
        labelMsg: 'cite-section-label',
}
        groups: {
$('#citetoolbar-namedrefs').off('dialogopen');
          'template': {
if (!CiteTB.getOption('modal')) {
            tools: {
//$('#citetoolbar-namedrefs').dialog('option', 'modal', false);
              'template': {
//$('#citetoolbar-errorcheck').dialog('option', 'modal', false);
                type: 'select',
mw.util.addCSS(".ui-widget-overlay {" +
                labelMsg: 'cite-template-list',
"display:none !important;" +
                list: temlist
"}");
              }
}
            }
try {
          },
$target.wikiEditor('addToToolbar', refsection);
          'namedrefs': {
} catch (e) {
            labelMsg: 'cite-named-refs-label',
// error occurred setting up wikieditor.
            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;
            }
            $(this).dialog( 'close' );
            $.wikiEditor.modules.toolbar.fn.doAction( $(this).data( 'context' ), {
              type: 'encapsulate',
              options: {
                post: CiteTB.getNamedRef(refname, true)
              }
            }, $(this) );
          },
          'wikieditor-toolbar-tool-link-cancel': function() {
            $(this).dialog( 'close' );
          }                 
        }
      }     
    }
  };
 
  try {
    $target.wikiEditor('addDialog', defaultdialogs);
  } catch (e) {
    // error occurred setting up wikieditor.
  }
  $('#citetoolbar-namedrefs').off('dialogopen');
  if (!CiteTB.getOption('modal')) {
    //$('#citetoolbar-namedrefs').dialog('option', 'modal', false);
    //$('#citetoolbar-errorcheck').dialog('option', 'modal', false);
    mw.util.addCSS(".ui-widget-overlay {"+
    "display:none !important;"+
    "}");
  }
  try {
    $target.wikiEditor('addToToolbar', refsection);
  } catch (e) {
    // error occurred setting up wikieditor.
  }
};
};


// Load local data - messages, cite templates, etc.
// Load local data - messages, cite templates, etc.
$(document).ready( function() {
$(document).ready(function () {
  switch( mw.config.get('wgUserLanguage') ) {
mw.loader.load('/w/index.php?title=MediaWiki:RefToolbarMessages-en.js&action=raw&ctype=text/javascript');
    case 'de': // German
      mw.loader.load('/index.php?title=MediaWiki:RefToolbarMessages-de.js&action=raw&ctype=text/javascript');
      break;
    default: // English
      mw.loader.load('/index.php?title=MediaWiki:RefToolbarMessages-en.js&action=raw&ctype=text/javascript');
  }
});
});


Line 290: Line 280:
// REF FUNCTIONS
// REF FUNCTIONS
// Actually assemble a ref from user input
// Actually assemble a ref from user input
CiteTB.getRef = function(inneronly, forinsert) {
CiteTB.getRef = function (inneronly, forinsert) {
  var i, j, g, group;
var i, j, g, group;
  var template = CiteTB.getOpenTemplate();
var template = CiteTB.getOpenTemplate();
  var templatename = template.templatename;
var templatename = template.templatename;
  var res = '';
var res = '';
  var refobj = {'shorttag':false};
var refobj = {'shorttag': false};
  if (!inneronly) {
if (!inneronly) {
    group = $('#cite-'+CiteTB.escStr(template.shortform)+'-group').val();
group = $('#cite-' + CiteTB.escStr(template.shortform) + '-group').val();
    var refname = $('#cite-'+CiteTB.escStr(template.shortform)+'-name').val();
var refname = $('#cite-' + CiteTB.escStr(template.shortform) + '-name').val();
    res += '<ref';
res += '<ref';
    if (refname) {
if (refname) {
      refname = $.trim(refname);
refname = $.trim(refname);
      res+=' name='+CiteTB.getQuotedString(refname);
res += ' name=' + CiteTB.getQuotedString(refname);
      refobj.refname = refname;
refobj.refname = refname;
    }
}
    if (group) {
if (group) {
      group = $.trim(group);
group = $.trim(group);
      res+=' group='+CiteTB.getQuotedString(group);
res += ' group=' + CiteTB.getQuotedString(group);
      refobj.refgroup = group;
refobj.refgroup = group;
    }
}
    res+='>';
res += '>';
  }
}
  var content ='{{'+templatename;
var content = '{{' + templatename;
  for( g in template.incrementables ) {
for (g in template.incrementables) {
  group = template.incrementables[g];
group = template.incrementables[g];
  for (i=1; i<=group.val; i++) {
for (i = 1; i <= group.val; i++) {
for (j=0; j<group.fields.length; j++) {
for (j = 0; j < group.fields.length; j++) {
  var fieldname = group.fields[j].field;
var fieldname = group.fields[j].field;
  var fieldid = fieldname.replace('<N>', i.toString());
var fieldid = fieldname.replace('<N>', i.toString());
  var field = $('#cite-'+CiteTB.escStr(template.shortform)+'-'+fieldid).val();
var field = $('#cite-' + CiteTB.escStr(template.shortform) + '-' + fieldid).val();
  if (field) {
if (field) {
  content+=' |'+fieldid+'=';
content += ' |' + fieldid + '=';
  content+= $.trim(field);
content += $.trim(field);
  }
}
  }
}
  }
}
  }
}
  for( i=0; i<template.basic.length; i++ ) {
for (i = 0; i < template.basic.length; i++) {
  if (template.basic[i].increment_group) {
if (template.basic[i].increment_group) {
  continue;
continue;
  }
}
    var fieldname = template.basic[i].field;
var fieldname = template.basic[i].field;
    var field = $('#cite-'+CiteTB.escStr(template.shortform)+'-'+fieldname).val();
var field = $('#cite-' + CiteTB.escStr(template.shortform) + '-' + fieldname).val();
    if (field) {
if (field) {
      content+=' |'+fieldname+'=';
content += ' |' + fieldname + '=';
      content+= $.trim(field);
content += $.trim(field);
    }
}
  }
}
  if ($('#cite-form-status').val() !== 'closed') {
if ($('#cite-form-status').val() !== 'closed') {
    for( i=0; i<template.extra.length; i++ ) {
for (i = 0; i < template.extra.length; i++) {
      if (template.extra[i].increment_group) {
if (template.extra[i].increment_group) {
        continue;
continue;
      }
}
      var fieldname = template.extra[i].field;
var fieldname = template.extra[i].field;
      var field = $('#cite-'+CiteTB.escStr(template.shortform)+'-'+fieldname).val();
var field = $('#cite-' + CiteTB.escStr(template.shortform) + '-' + fieldname).val();
      if (field) {
if (field) {
        content+=' |'+fieldname+'=';
content += ' |' + fieldname + '=';
        content+= $.trim(field);
content += $.trim(field);
      }
}
    }
}
  }
}
  content+= '}}';
content += '}}';
  res+=content;
res += content;
  refobj.content = content;
refobj.content = content;
  if (!inneronly) {
if (!inneronly) {
    res+= '</ref>';
res += '</ref>';
  }
}
  if (forinsert) {
if (forinsert) {
    CiteTB.mainRefList.push(refobj);
CiteTB.mainRefList.push(refobj);
  }
}
  return res;
return res;
};
};


// Make a reference to a named ref
// Make a reference to a named ref
CiteTB.getNamedRef = function(refname, forinsert) {
CiteTB.getNamedRef = function (refname, forinsert) {
  if (forinsert) {
if (forinsert) {
    CiteTB.mainRefList.push( {'shorttag':true, 'refname':refname} );
CiteTB.mainRefList.push({'shorttag': true, 'refname': refname});
  }
}
  return '<ref name='+CiteTB.getQuotedString(refname)+' />';
return '<ref name=' + CiteTB.getQuotedString(refname) + ' />';
};
};


// Function to load the ref list
// Function to load the ref list
CiteTB.loadRefs = function() {
CiteTB.loadRefs = function () {
  if (CiteTB.refsLoaded) {
if (CiteTB.refsLoaded) {
    return;
return;
  }
}
  CiteTB.getPageText(CiteTB.loadRefsInternal);
CiteTB.getPageText(CiteTB.loadRefsInternal);
};
};


// Function that actually loads the list from the page text
// Function that actually loads the list from the page text
CiteTB.loadRefsInternal = function(text) {  
CiteTB.loadRefsInternal = function (text) {
  // What this does:            extract first name/group                                    extract second name/group                                          shorttag  inner content
// What this does:            extract first name/group                                    extract second name/group                                          shorttag  inner content
  var refsregex = /< *ref(?: +(name|group) *= *(?:"([^"]*?)"|'([^']*?)'|([^ '"\/\>]*?)) *)? *(?: +(name|group) *= *(?:"([^"]*?)"|'([^']*?)'|([^ '"\/\>]*?)) *)? *(?:\/ *>|>((?:.|\n)*?)< *\/ *ref *>)/gim;
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
// This should work regardless of the quoting used for names/groups and for linebreaks in the inner content
  while (true) {
while (true) {
    var ref = refsregex.exec(text);
var ref = refsregex.exec(text);
    if (ref === null) {
if (ref === null) {
      break;
break;
    }
}
    var refobj = {};
var refobj = {};
    if (ref[9]) { // Content + short tag check
if (ref[9]) { // Content + short tag check
      //alert('"'+ref[9]+'"');
//alert('"'+ref[9]+'"');
      refobj.content = ref[9];  
refobj.content = ref[9];
      refobj.shorttag = false;
refobj.shorttag = false;
    } else {
} else {
      refobj.shorttag = true;
refobj.shorttag = true;
    }
}
    if (ref[1] !== '') { // First name/group
if (ref[1] !== '') { // First name/group
      if (ref[2]) {
if (ref[2]) {
        refobj['ref'+ref[1]] = ref[2];
refobj['ref' + ref[1]] = ref[2];
      } else if (ref[3]) {
} else if (ref[3]) {
        refobj['ref'+ref[1]] = ref[3];
refobj['ref' + ref[1]] = ref[3];
      } else {
} else {
        refobj['ref'+ref[1]] = ref[4];
refobj['ref' + ref[1]] = ref[4];
      }
}
    }
}
    if (ref[5] !== '') { // Second name/group
if (ref[5] !== '') { // Second name/group
      if (ref[6]) {
if (ref[6]) {
        refobj['ref'+ref[5]] = ref[6];
refobj['ref' + ref[5]] = ref[6];
      } else if (ref[7]) {
} else if (ref[7]) {
        refobj['ref'+ref[5]] = ref[7];
refobj['ref' + ref[5]] = ref[7];
      } else {
} else {
        refobj['ref'+ref[5]] = ref[8];
refobj['ref' + ref[5]] = ref[8];
      }
}
    }
}
    CiteTB.mainRefList.push(refobj);
CiteTB.mainRefList.push(refobj);
  }
}
  CiteTB.refsLoaded = true;
CiteTB.refsLoaded = true;
  CiteTB.setupErrorCheck();
CiteTB.setupErrorCheck();
  CiteTB.setupNamedRefs();
CiteTB.setupNamedRefs();
};
};


// AJAX FUNCTIONS
// AJAX FUNCTIONS
// Parse some wikitext and hand it off to a callback function
// Parse some wikitext and hand it off to a callback function
CiteTB.parse = function(text, callback) {
CiteTB.parse = function (text, callback) {
  $.post( mw.util.wikiScript( 'api' ),
$.post(mw.util.wikiScript('api'),
    {action:'parse', title:mw.config.get('wgPageName'), text:text, prop:'text', format:'json'},
{action: 'parse', title: mw.config.get('wgPageName'), text: text, prop: 'text', format: 'json'},
    function(data) {
function (data) {
      var html = data.parse.text['*'];
var html = data.parse.text['*'];
      callback(html);
callback(html);
    },
},
    'json'
'json'
  );
);
};
};


// Use the API to expand templates on some text
// Use the API to expand templates on some text
CiteTB.expandtemplates = function(text, callback) {
CiteTB.expandtemplates = function (text, callback) {
  $.post( mw.util.wikiScript( 'api' ),
$.post(mw.util.wikiScript('api'),
    {action:'expandtemplates', title:mw.config.get('wgPageName'), text:text, format:'json'},
{action: 'expandtemplates', title: mw.config.get('wgPageName'), text: text, format: 'json'},
    function(data) {
function (data) {
      var restext = data.expandtemplates['*'];
var restext = data.expandtemplates['*'];
      callback(restext);
callback(restext);
    },
},
    'json'
'json'
  );
);
};
};


// Function to get the page text
// Function to get the page text
CiteTB.getPageText = function(callback) {
CiteTB.getPageText = function (callback) {
  var section = $("input[name='wpSection']").val();
var section = $("input[name='wpSection']").val();
  if ( section !== '' ) {
if (section !== '') {
    var postdata = {action:'query', prop:'revisions', rvprop:'content', pageids:mw.config.get('wgArticleId'), format:'json'};
var postdata = {
    if (CiteTB.getOption('expandtemplates')) {
action: 'query',
      postdata.rvexpandtemplates = '1';
prop: 'revisions',
    }
rvprop: 'content',
    $.get( mw.util.wikiScript( 'api' ),
pageids: mw.config.get('wgArticleId'),
      postdata,
format: 'json'
      function(data) {
};
        var pagetext = data.query.pages[mw.config.get('wgArticleId').toString()].revisions[0]['*'];
if (CiteTB.getOption('expandtemplates')) {
        callback(pagetext);
postdata.rvexpandtemplates = '1';
      },
}
      'json'
$.get(mw.util.wikiScript('api'),
    );
postdata,
  } else {
function (data) {
    if (CiteTB.getOption('expandtemplates')) {
var pagetext = data.query.pages[mw.config.get('wgArticleId').toString()].revisions[0]['*'];
      CiteTB.expandtemplates($('#wpTextbox1').wikiEditor('getContents').text(), callback);
callback(pagetext);
    } else {
},
      callback($('#wpTextbox1').wikiEditor('getContents').text());
'json'
    }
);
  }
} else {
if (CiteTB.getOption('expandtemplates')) {
CiteTB.expandtemplates($('#wpTextbox1').wikiEditor('getContents').text(), callback);
} else {
callback($('#wpTextbox1').wikiEditor('getContents').text());
}
}
};
};


// Safe version of decodeURIComponent() that doesn't throw exceptions.
// Safe version of decodeURIComponent() that doesn't throw exceptions.
// If the native decodeURIComponent() threw an exception, the original string will be returned.
// If the native decodeURIComponent() threw an exception, the original string will be returned.
CiteTB.safeDecodeURIComponent = function(s) {
CiteTB.safeDecodeURIComponent = function (s) {
try {
try {
s = decodeURIComponent(s);
s = decodeURIComponent(s);
} catch (e) {}
} catch (e) {
}
return s;
return s;
};
/**
* Convert one Citoid result into RefToolbar autofill properties.
*
* The property names must match the "autofillprop" values in
* MediaWiki:RefToolbarConfig.js, not the citation template parameters.
*
* @param {Object} entry One item from the Citoid response body.
* @param {string} tem Target citation template short name, e.g. 'book'.
* @return {Object} Autofill properties; empty if nothing matched.
*/
CiteTB.transformCitoidResponse = function (entry, tem) {
var result = {};
// A pipe ends the template parameter. CiteTB.getRef joins the field
// values into wikitext and does not escape them.
var escapePipes = function (text) {
return typeof text === 'string' ? text.replace(/\|/g, '{{!}}') : text;
};
// Citoid puts the chapter in "title" and the book in "bookTitle". Only
// cite book has a chapter field.
var isBookSection = entry.itemType === 'bookSection' && tem === 'book';
Object.keys(entry).forEach(function (key) {
var value = escapePipes(entry[key]);
// Zotero has one field name for each item type. The /mediawiki/
// format keeps them separate, so each case lists all the names that
// Zotero maps to the same base field.
switch (key) {
case 'publicationTitle':
case 'blogTitle':
case 'bookTitle':
case 'dictionaryTitle':
case 'encyclopediaTitle':
case 'forumTitle':
case 'proceedingsTitle':
case 'programTitle':
case 'websiteTitle':
// RefToolbar maps every containing-work title to journal
if (isBookSection) {
result.title = value;
} else {
result.journal = value;
}
break;
case 'title':
case 'caseName':
case 'nameOfAct':
case 'subject':
if (isBookSection) {
result.chapter = value;
} else {
result.title = value;
}
break;
case 'volume':
case 'codeVolume':
case 'reporterVolume':
result.volume = value;
break;
case 'issue':
result.issue = value;
break;
case 'edition':
// Citoid returns "1st ed"; the templates want "1st".
value = value.split(' edition').join('');
value = value.split(' ed.').join('');
value = value.split(' ed').join('');
result.edition = value;
break;
case 'publisher':
case 'company':
case 'distributor':
case 'institution':
case 'label':
case 'network':
case 'studio':
case 'university':
result.publisher = value;
break;
case 'pages':
case 'codePages':
case 'firstPage':
result.pages = value;
break;
// Citoid can return several identifiers; the templates take one.
case 'ISBN':
result.isbn = escapePipes(Array.isArray(value) ? value[0] : value);
break;
case 'ISSN':
result.issn = escapePipes(Array.isArray(value) ? value[0] : value);
break;
case 'date':
case 'dateDecided':
case 'dateEnacted':
case 'issueDate':
result.date = value;
break;
case 'DOI':
result.doi = value;
break;
case 'language':
result.language = value;
break;
case 'place':
result.location = value;
break;
case 'author':
value.forEach(function (author) {
// Reject name parts that start with a digit. These are
// dates from bad metadata.
var firstName = /^\d/.test(author[0]) ?  '' : escapePipes(author[0]);
var lastName = /^\d/.test(author[1]) ? '' : escapePipes(author[1]);
// Accept an institutional author, which has no first name.
if (lastName) {
if (!result.authors) {
result.authors = [];
}
// CiteTB.autoFill expects [last, first].
result.authors.push([lastName, firstName || '']);
}
});
break;
}
});
return result;
};
};


// Autofill a template from an ID (ISBN, DOI, PMID, URL)
// Autofill a template from an ID (ISBN, DOI, PMID, URL)
CiteTB.initAutofill = function() {
CiteTB.initAutofill = function () {
  var elemid = $(this).attr('id');
var elemid = $(this).attr('id');
  var res = /^cite\-auto\-(.*?)\-(.*)\-(.*)$/.exec(elemid);
var res = /^cite\-auto\-(.*?)\-(.*)\-(.*)$/.exec(elemid);
  var tem = res[1];
if (!res) {
  var field = res[2];
return false;
  var autotype = res[3];
}
  var id = $('#cite-'+tem+'-'+field).val();
var tem = res[1];
  if (!id) {
var field = res[2];
    return false;
var autotype = res[3];
  }
var id = $('#cite-' + tem + '-' + field).val();
  var url = '//reftoolbar.toolforge.org/lookup.php?';
if (!id) {
  // Citoid expects minimally encoded input, so do some speculative decoding here to avoid
return false;
  // 404 fetches. https://phabricator.wikimedia.org/T146539
}
  id = CiteTB.safeDecodeURIComponent(id);
id = CiteTB.safeDecodeURIComponent(id);
  url+=autotype+'='+encodeURIComponent(id);
 
  url+='&template='+encodeURIComponent(tem);
var citoidConfig = mw.config.get('wgCitoidConfig') || {};
  var s = document.createElement('script');
var serviceUrl = citoidConfig.citoidServiceUrl;
  s.setAttribute('src', url);
 
  s.setAttribute('type', 'text/javascript');
if (serviceUrl) {
  document.getElementsByTagName('head')[0].appendChild(s);
(new mw.Api({
  return false;
ajax: {
url: serviceUrl.replace(/\/api$/, '') + '/mediawiki/' + encodeURIComponent(id),
headers: { 'accept-language': mw.config.get('wgContentLanguage') },
timeout: 30 * 1000,
type: 'GET'
}
})).get().then(function (results) {
if (results && results[0]) {
CiteTB.autoFill(CiteTB.transformCitoidResponse(results[0], tem), tem, autotype);
}
});
return false;
}
 
var url = '//reftoolbar.toolforge.org/lookup.php?'
+ autotype + '=' + encodeURIComponent(id)
+ '&template=' + encodeURIComponent(tem);
var s = document.createElement('script');
s.src = url;
s.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(s);
return false;
};
};


// Callback for autofill
// Callback for autofill
//TODO: Autofill the URL, at least for DOI
// TODO: Autofill the URL, at least for DOI
CiteTB.autoFill = function(data, template, type) {
CiteTB.autoFill = function (data, template, type) {
  var cl = 'cite-'+template+'-';
var cl = 'cite-' + template + '-';
  var i,j, coauthors;
var i, j, coauthors;
  $('.'+cl+'title').val(data.title);
$('.' + cl + 'title').val(data.title);
  // Fill in authors
// Fill in authors
  if (data.authors && data.authors.length > 0) {
if (data.authors && data.authors.length > 0) {
  if ($('.'+cl+'last-incr-1').length != 0) {
if ($('.' + cl + 'last-incr-1').length != 0) {
var classes = $('.'+cl+'last-incr-1').eq(0).attr('class').split(/\s+/);
var classes = $('.' + cl + 'last-incr-1').eq(0).attr('class').split(/\s+/);
var group = false;
var group = false;
var patt = /cite-[^-]*?-incr-(.*)/
var patt = /cite-[^-]*?-incr-(.*)/;
for (var c=0; c<classes.length; c++) {
for (var c = 0; c < classes.length; c++) {
if (patt.exec(classes[c])) {
if (patt.exec(classes[c])) {
group = patt.exec(classes[c])[1];
group = patt.exec(classes[c])[1];
break;
break;
}
}
$('.' + cl + 'last-incr-1').val(data.authors[0][0]);
$('.' + cl + 'first-incr-1').val(data.authors[0][1]);
elemid = '#cite-incr-' + template + '-' + group;
for (var i = 2; i < data.authors.length + 1; i++) {
$(elemid).click();
$('.' + cl + 'last-incr-' + i.toString()).val(data.authors[i - 1][0]);
$('.' + cl + 'first-incr-' + i.toString()).val(data.authors[i - 1][1]);
}
} else if ($('.' + cl + 'author-incr-1').length != 0) {
var classes = $('.' + cl + 'author-incr-1').eq(0).attr('class').split(/\s+/);
var group = false;
var patt = /cite-[^-]*?-incr-(.*)/
for (var c = 0; c < classes.length; c++) {
if (patt.exec(classes[c])) {
group = patt.exec(classes[c])[1];
break;
}
}
$('.' + cl + 'author-incr-1').val(data.authors[0].join(', '));
elemid = '#cite-incr-' + template + '-' + group;
for (var i = 2; i < data.authors.length + 1; i++) {
$(elemid).click();
$('.' + cl + 'author-incr-' + i.toString()).val(data.authors[i - 1].join(', '));
}
} else if ($('.' + cl + 'last1').length != 0) {
for (i = 0; data.authors && 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 {
coauthors = [];
for (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 (i = 0; data.authors && i < data.authors.length; i++) {
if ($('.' + cl + 'author' + (i + 1)).length) {
$('.' + cl + 'author' + (i + 1)).val(data.authors[i].join(', '));
} else {
coauthors = [];
for (j = i; j < data.authors.length; j++) {
coauthors.push(data.authors[j].join(', '));
}
$('.' + cl + 'coauthors').val(coauthors.join('; '));
break;
}
}
}
}
} else {
$('.'+cl+'last-incr-1').val(data.authors[0][0])
var authors = [];
$('.'+cl+'first-incr-1').val(data.authors[0][1])
for (i = 0; data.authors && i < data.authors.length; i++) {
elemid = '#cite-incr-'+template+'-'+group;
authors.push(data.authors[i].join(', '));
for (var i=2; i<data.authors.length+1; i++) {
$(elemid).click();
$('.'+cl+'last-incr-'+i.toString()).val(data.authors[i-1][0])
$('.'+cl+'first-incr-'+i.toString()).val(data.authors[i-1][1])
}
  } else if ($('.'+cl+'author-incr-1').length != 0) {
var classes = $('.'+cl+'author-incr-1').eq(0).attr('class').split(/\s+/);
var group = false;
var patt = /cite-[^-]*?-incr-(.*)/
for (var c=0; c<classes.length; c++) {
if (patt.exec(classes[c])) {
group = patt.exec(classes[c])[1];
break;
}
}
$('.' + cl + 'authors').val(authors.join('; '));
}
}
$('.'+cl+'author-incr-1').val(data.authors[0].join(', '))
}
elemid = '#cite-incr-'+template+'-'+group;
 
for (var i=2; i<data.authors.length+1; i++) {
// Format partial dates of the format YYYY-MM, YYYY-MM-XX, or YYYY-MM-DD correctly
$(elemid).click();
if (data.date) {
$('.'+cl+'author-incr-'+i.toString()).val(data.authors[i-1].join(', '))
try {
}
var DT = new Date(data.date);
  } else if ($('.'+cl+'last1').length != 0) {
if (/^\d{4}-\d{2}(-XX)?$/i.test(data.date)) {
for(i=0; data.authors && i<data.authors.length; i++) {
data.date = data.date.replace('-XX', '');
  if ($('.'+cl+'last'+(i+1)).length) {
$('.' + cl + 'date').val(CiteTB.formatDate(DT, false, true));
$('.'+cl+'last'+(i+1)).val(data.authors[i][0]);
} else if (/^\d{4}-\d{2}-\d{2}?/i.test(data.date)) {
$('.'+cl+'first'+(i+1)).val(data.authors[i][1]);
$('.' + cl + 'date').val(CiteTB.formatDate(DT, true, true));
  } else {
} else {
coauthors = [];
$('.' + cl + 'date').val(data.date);
for(j=i; j<data.authors.length; j++) {
  coauthors.push(data.authors[j].join(', '));
}
}
$('.'+cl+'coauthors').val(coauthors.join('; '));
} catch (e) {
break;
  }
}
}
  } else if($('.'+cl+'author1').length !== 0) {
} else {
for(i=0; data.authors && i<data.authors.length; i++) {
$('.' + cl + 'date').val(data.date);
  if ($('.'+cl+'author'+(i+1)).length) {
}
$('.'+cl+'author'+(i+1)).val(data.authors[i].join(', '));
 
  } else {
if (type === 'pmid' || type === 'doi') {
coauthors = [];
$('.' + cl + 'journal').val(data.journal);
for(j=i; j<data.authors.length; j++) {
$('.' + cl + 'volume').val(data.volume);
  coauthors.push(data.authors[j].join(', '));
$('.' + cl + 'issue').val(data.issue);
}
$('.' + cl + 'pages').val(data.pages);
$('.'+cl+'coauthors').val(coauthors.join('; '));
if (type === 'pmid' && data.doi) {
break;
$('.' + cl + 'doi').val(data.doi);
  }
}
}
  } else {
} else if (type === 'isbn') {
var authors = [];
$('.' + cl + 'publisher').val(data.publisher);
for(i=0; data.authors && i<data.authors.length; i++) {
$('.' + cl + 'location').val(data.location);
  authors.push(data.authors[i].join(', '));
$('.' + cl + 'edition').val(data.edition);
} else if (type === 'url') {
$('.' + cl + 'journal').val(data.journal);
$('.' + cl + 'volume').val(data.volume);
$('.' + cl + 'issue').val(data.issue);
$('.' + cl + 'pages').val(data.pages);
$('.' + cl + 'publisher').val(data.publisher);
$('.' + cl + 'edition').val(data.edition);
$('.' + cl + 'isbn').val(data.isbn);
$('.' + cl + 'issn').val(data.issn);
$('.' + cl + 'doi').val(data.doi);
// "en-US" isn't a valid value for the language parameter
if (data.language && data.language !== 'en-US' && data.language !== 'en-GB') {
$('.' + cl + 'language').val(data.language);
}
}
$('.'+cl+'authors').val(authors.join('; '));
$('.' + cl + 'chapter').val(data.chapter);
  }
}
  }
 
  // Format partial dates of the format YYYY-MM, YYYY-MM-XX, or YYYY-MM-DD correctly
  if ( data.date ) {
    try {
      var DT = new Date(data.date);
      if ( /^\d{4}-\d{2}(-XX)?$/i.test(data.date) ) {
        data.date = data.date.replace('-XX','');
        $('.'+cl+'date').val(CiteTB.formatDate(DT, false, true));
      } else if ( /^\d{4}-\d{2}-\d{2}?/i.test(data.date) ) {
        $('.'+cl+'date').val(CiteTB.formatDate(DT, true, true));
      } else {
        $('.'+cl+'date').val(data.date);
      }
    } catch (e) {}
  } else {
    $('.'+cl+'date').val(data.date);
  }
 
  if (type === 'pmid' || type === 'doi') {
    $('.'+cl+'journal').val(data.journal);
    $('.'+cl+'volume').val(data.volume);
    $('.'+cl+'issue').val(data.issue);
    $('.'+cl+'pages').val(data.pages);
    if (type === 'pmid' && data.doi) {
      $('.'+cl+'doi').val(data.doi);
    }
  } else if (type === 'isbn') {
    $('.'+cl+'publisher').val(data.publisher);
    $('.'+cl+'location').val(data.location);
    $('.'+cl+'edition').val(data.edition);
  } else if (type === 'url') {
    $('.'+cl+'journal').val(data.journal);
    $('.'+cl+'volume').val(data.volume);
    $('.'+cl+'issue').val(data.issue);
    $('.'+cl+'pages').val(data.pages);
    $('.'+cl+'publisher').val(data.publisher);
    $('.'+cl+'edition').val(data.edition);
    $('.'+cl+'isbn').val(data.isbn);
    $('.'+cl+'issn').val(data.issn);
    $('.'+cl+'doi').val(data.doi);
    // "en-US" isn't a valid value for the language parameter
    if (data.language && data.language !== 'en-US' && data.language !== 'en-GB') {
    $('.'+cl+'language').val(data.language);
    }
    $('.'+cl+'chapter').val(data.chapter);
  }
};
};


// FORM DIALOG FUNCTIONS
// FORM DIALOG FUNCTIONS
// Add new incrementable fields
// Add new incrementable fields
CiteTB.incrementFields = function() {
CiteTB.incrementFields = function () {
template = CiteTB.getOpenTemplate();
template = CiteTB.getOpenTemplate();
var currentrow = $(this).parents('tr')[0];
var currentrow = $(this).parents('tr')[0];
$(this).prev().css('width', '100%')
$(this).prev().css('width', '100%');
$(this).detach();
$(this).detach();
var elemid = $(this).attr('id');
var elemid = $(this).attr('id');
Line 642: Line 789:
increments = template.incrementables[group];
increments = template.incrementables[group];
fields = increments.fields;
fields = increments.fields;
incrval = increments.val+1;
incrval = increments.val + 1;
template.incrementables[group].val += 1;
template.incrementables[group].val += 1;
trs = template.makeFormInner(fields, false);
trs = template.makeFormInner(fields, false);
trs.reverse();
trs.reverse();
for (var i=0; i<trs.length; i++) {
for (var i = 0; i < trs.length; i++) {
$(currentrow).after(trs[i]);
$(currentrow).after(trs[i]);
}
}
Line 652: Line 799:


// fill the accessdate param with the current date
// fill the accessdate param with the current date
CiteTB.fillAccessdate = function() {
CiteTB.fillAccessdate = function () {
  var elemid = $(this).attr('id');
var elemid = $(this).attr('id');
  var res = /^cite\-date\-(.*?)\-(.*)$/.exec(elemid);
var res = /^cite\-date\-(.*?)\-(.*)$/.exec(elemid);
  var id = res[1];
var id = res[1];
  var field = res[2];
var field = res[2];
  var DT = new Date();
var DT = new Date();
  var datestr = CiteTB.formatDate(DT);
var datestr = CiteTB.formatDate(DT);
  $('#cite-'+id+'-'+field).val(datestr);
$('#cite-' + id + '-' + field).val(datestr);
  return false;
return false;
};
};


CiteTB.formatDate = function(DT, useday, usemonth) {
CiteTB.formatDate = function (DT, useday, usemonth) {
  if (typeof useday == "undefined") {
if (typeof useday == "undefined") {
    useday = true;
useday = true;
  }
}
  if (typeof usemonth == "undefined") {
if (typeof usemonth == "undefined") {
    usemonth = true;
usemonth = true;
  }
}
  var datestr = CiteTB.getOption('date format');
var datestr = CiteTB.getOption('date format');
  var zmonth = '';
var zmonth = '';
  var month = DT.getUTCMonth()+1;
var month = DT.getUTCMonth() + 1;
  if (month < 10) {
if (month < 10) {
    zmonth = "0"+month.toString();
zmonth = "0" + month.toString();
  } else {
} else {
    zmonth = month.toString();
zmonth = month.toString();
  }
}
  month = month.toString();
month = month.toString();
  var zdate = '';
var zdate = '';
  var date = DT.getUTCDate();
var date = DT.getUTCDate();
  if (date < 10) {
if (date < 10) {
    zdate = "0"+date.toString();
zdate = "0" + date.toString();
  } else {
} else {
    zdate = date.toString();
zdate = date.toString();
  }
}
  date = date.toString();
date = date.toString();
  if (useday) {
if (useday) {
    datestr = datestr.replace('<date>', date);
datestr = datestr.replace('<date>', date);
    datestr = datestr.replace('<zdate>', zdate);
datestr = datestr.replace('<zdate>', zdate);
  } else {
} else {
    datestr = datestr.replace('<date>', '');
datestr = datestr.replace('<date>', '');
    datestr = datestr.replace('<zdate>', '');
datestr = datestr.replace('<zdate>', '');
  }
}
  if (usemonth) {
if (usemonth) {
    datestr = datestr.replace('<month>', month);
datestr = datestr.replace('<month>', month);
    datestr = datestr.replace('<zmonth>', zmonth);
datestr = datestr.replace('<zmonth>', zmonth);
    datestr = datestr.replace('<monthname>', CiteTB.getOption('months')[DT.getUTCMonth()]);
datestr = datestr.replace('<monthname>', CiteTB.getOption('months')[DT.getUTCMonth()]);
  } else {
} else {
    datestr = datestr.replace('<month>', '');
datestr = datestr.replace('<month>', '');
    datestr = datestr.replace('<zmonth>', '');
datestr = datestr.replace('<zmonth>', '');
    datestr = datestr.replace('<monthname>', '');
datestr = datestr.replace('<monthname>', '');
  }
}
  datestr = datestr.replace('<year>', DT.getUTCFullYear().toString());
datestr = datestr.replace('<year>', DT.getUTCFullYear().toString());
  return datestr.replace(/^[ \/\-\,\.]*(.*?)[ \/\-\,\.]*$/g, "$1"); // Cleanup any dangling spaces or connectors that might result from omitting date/month
return datestr.replace(/^[ \/\-\,\.]*(.*?)[ \/\-\,\.]*$/g, "$1"); // Cleanup any dangling spaces or connectors that might result from omitting date/month
};
};


// Function called after the ref list is loaded, to actually set the contents of the named ref dialog
// 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
// Until the list is loaded, its just a "Loading" placeholder
CiteTB.setupNamedRefs = function() {
CiteTB.setupNamedRefs = function () {
  var names = [], i;
var names = [], i;
  for( i=0; i<CiteTB.mainRefList.length; i++) {
for (i = 0; i < CiteTB.mainRefList.length; i++) {
    if (!CiteTB.mainRefList[i].shorttag && CiteTB.mainRefList[i].refname) {
if (!CiteTB.mainRefList[i].shorttag && CiteTB.mainRefList[i].refname) {
      names.push(CiteTB.mainRefList[i]);
names.push(CiteTB.mainRefList[i]);
    }
}
  }
}
  var stuff = $('<div>');
var stuff = $('<div>');
  $('#citetoolbar-namedrefs').html( stuff );
$('#citetoolbar-namedrefs').html(stuff);
  if (names.length === 0) {
if (names.length === 0) {
    stuff.html(mw.usability.getMsg('cite-no-namedrefs'));
stuff.html(mw.messages.get('cite-no-namedrefs'));
  } else {
} else {
    stuff.html(mw.usability.getMsg('cite-namedrefs-intro'));
stuff.html(mw.messages.get('cite-namedrefs-intro'));
    var select = $('<select id="cite-namedref-select">');
var select = $('<select id="cite-namedref-select">');
    select.append($('<option value="" />').text(mw.usability.getMsg('cite-named-refs-dropdown')));
select.append($('<option value="" />').text(mw.messages.get('cite-named-refs-dropdown')));
    for(i=0; i<names.length; i++) {
for (i = 0; i < names.length; i++) {
      select.append($('<option />').text(names[i].refname));
select.append($('<option />').text(names[i].refname));
    }
}
    stuff.after(select);
stuff.after(select);
    select.before('<br />');    
select.before('<br />');
    var prevlabel = $('<div id="cite-nref-preview-label" style="display:none;" />').html(mw.usability.getMsg('cite-raw-preview'));
var prevlabel = $('<div id="cite-nref-preview-label" style="display:none;" />').html(mw.messages.get('cite-raw-preview'));
    select.after(prevlabel);
select.after(prevlabel);
    prevlabel.before("<br /><br />");
prevlabel.before("<br /><br />");
    prevlabel.after('<div id="cite-namedref-preview" style="padding:0.5em; font-size:110%" />');
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'));
var parselabel = $('<span id="cite-parsed-label" style="display:none;" />').html(mw.messages.get('cite-parsed-label'));
    $('#cite-namedref-preview').after(parselabel);
$('#cite-namedref-preview').after(parselabel);
    parselabel.after('<div id="cite-namedref-parsed" style="padding-bottom:0.5em; font-size:110%" />');
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" />');
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'));
link.html(mw.messages.get('cite-form-parse'));
    $('#cite-namedref-parsed').after(link);
$('#cite-namedref-parsed').after(link);
   
 
    $("#cite-namedref-select").on( 'change', CiteTB.namedRefSelectClick);
$("#cite-namedref-select").on('change', CiteTB.namedRefSelectClick);
    $('#cite-nref-parse').on( 'click', CiteTB.nrefParseClick);
$('#cite-nref-parse').on('click', CiteTB.nrefParseClick);
  }    
}
};
};


// Function to get the errorcheck form HTML
// Function to get the errorcheck form HTML
CiteTB.setupErrorCheck = function() {
CiteTB.setupErrorCheck = function () {
  var form = $('<div id="cite-errorcheck-heading" />').html(mw.usability.getMsg('cite-errorcheck-heading'));
var form = $('<div id="cite-errorcheck-heading" />').html(mw.messages.get('cite-errorcheck-heading'));
  var ul = $("<ul id='cite-errcheck-list' />");
var ul = $("<ul id='cite-errcheck-list' />");
  var test;
var test;
  for (var t in CiteTB.ErrorChecks) {
for (var t in CiteTB.ErrorChecks) {
    test = CiteTB.ErrorChecks[t];
test = CiteTB.ErrorChecks[t];
    ul.append(test.getRow());
ul.append(test.getRow());
  }
}
  form.append(ul);
form.append(ul);
  $('#citetoolbar-errorcheck').html(form);
$('#citetoolbar-errorcheck').html(form);
};
};


// Callback function for parsed preview
// Callback function for parsed preview
CiteTB.fillNrefPreview = function(parsed) {
CiteTB.fillNrefPreview = function (parsed) {
  $('#cite-parsed-label').show();
$('#cite-parsed-label').show();
  $('#cite-namedref-parsed').html(parsed);
$('#cite-namedref-parsed').html(parsed);
};
};


// Click handler for the named-ref parsed preview
// Click handler for the named-ref parsed preview
CiteTB.nrefParseClick = function() {
CiteTB.nrefParseClick = function () {
  var choice = $("#cite-namedref-select").val();
var choice = $("#cite-namedref-select").val();
  if (choice === '') {
if (choice === '') {
    $('#cite-parsed-label').hide();
$('#cite-parsed-label').hide();
    $('#cite-namedref-parsed').text('');
$('#cite-namedref-parsed').text('');
    return false;
return false;
  }
}
  $('#cite-nref-parse').hide();
$('#cite-nref-parse').hide();
  for( var i=0; i<CiteTB.mainRefList.length; i++) {
for (var i = 0; i < CiteTB.mainRefList.length; i++) {
    if (!CiteTB.mainRefList[i].shorttag && CiteTB.mainRefList[i].refname == choice) {
if (!CiteTB.mainRefList[i].shorttag && CiteTB.mainRefList[i].refname == choice) {
      CiteTB.parse(CiteTB.mainRefList[i].content, CiteTB.fillNrefPreview);
CiteTB.parse(CiteTB.mainRefList[i].content, CiteTB.fillNrefPreview);
      return false;
return false;
    }
}
  }
}
};
};


// Click handler for the named-ref dropdown
// Click handler for the named-ref dropdown
CiteTB.lastnamedrefchoice = '';
CiteTB.lastnamedrefchoice = '';
CiteTB.namedRefSelectClick = function() {
CiteTB.namedRefSelectClick = function () {
  var choice = $("#cite-namedref-select").val();
var choice = $("#cite-namedref-select").val();
  if (CiteTB.lastnamedrefchoice == choice) {
if (CiteTB.lastnamedrefchoice == choice) {
    return;
return;
  }
}
  CiteTB.lastnamedrefchoice = choice;
CiteTB.lastnamedrefchoice = choice;
  $('#cite-parsed-label').hide();
$('#cite-parsed-label').hide();
  $('#cite-namedref-parsed').text('');
$('#cite-namedref-parsed').text('');
  if (choice === '') {
if (choice === '') {
    $('#cite-nref-preview-label').hide();
$('#cite-nref-preview-label').hide();
    $('#cite-namedref-preview').text('');
$('#cite-namedref-preview').text('');
    $('#cite-nref-parse').hide();
$('#cite-nref-parse').hide();
    return;
return;
  }
}
  for( var i=0; i<CiteTB.mainRefList.length; i++) {
for (var i = 0; i < CiteTB.mainRefList.length; i++) {
    if (!CiteTB.mainRefList[i].shorttag && CiteTB.mainRefList[i].refname == choice) {
if (!CiteTB.mainRefList[i].shorttag && CiteTB.mainRefList[i].refname == choice) {
      $('#cite-nref-preview-label').show();
$('#cite-nref-preview-label').show();
      $('#cite-namedref-preview').text(CiteTB.mainRefList[i].content);
$('#cite-namedref-preview').text(CiteTB.mainRefList[i].content);
      if (CiteTB.getOption('autoparse')) {
if (CiteTB.getOption('autoparse')) {
        CiteTB.nrefParseClick();
CiteTB.nrefParseClick();
      } else {
} else {
        $('#cite-nref-parse').show();
$('#cite-nref-parse').show();
      }
}
    }
}
  }
}
};
};


// callback function for parsed preview
// callback function for parsed preview
CiteTB.fillTemplatePreview = function(text) {
CiteTB.fillTemplatePreview = function (text) {
  var template = CiteTB.getOpenTemplate();
var template = CiteTB.getOpenTemplate();
  var div = $("#citetoolbar-"+CiteTB.escStr(template.shortform));
var div = $("#citetoolbar-" + CiteTB.escStr(template.shortform));
  div.find('.cite-prev-parsed-label').show();
div.find('.cite-prev-parsed-label').show();
  div.find('.cite-preview-parsed').html(text);
div.find('.cite-preview-parsed').html(text);
};
};


// Click handler for template parsed preview
// Click handler for template parsed preview
CiteTB.prevParseClick = function() {
CiteTB.prevParseClick = function () {
  var ref = CiteTB.getRef(true, false);
var ref = CiteTB.getRef(true, false);
  var template = CiteTB.getOpenTemplate();
var template = CiteTB.getOpenTemplate();
  var div = $("#citetoolbar-"+CiteTB.escStr(template.shortform));
var div = $("#citetoolbar-" + CiteTB.escStr(template.shortform));
  div.find('.cite-prev-parse').hide();
div.find('.cite-prev-parse').hide();
  CiteTB.parse(ref, CiteTB.fillTemplatePreview);
CiteTB.parse(ref, CiteTB.fillTemplatePreview);
};
};


// Show/hide the extra fields in the dialog box
// Show/hide the extra fields in the dialog box
CiteTB.showHideExtra = function() {
CiteTB.showHideExtra = function () {
  var template = CiteTB.getOpenTemplate();
var template = CiteTB.getOpenTemplate();
  var div = $("#citetoolbar-"+CiteTB.escStr(template.shortform));
var div = $("#citetoolbar-" + CiteTB.escStr(template.shortform));
  var setting = div.find(".cite-form-status").val();
var setting = div.find(".cite-form-status").val();
  if ( setting === 'closed' ) {
if (setting === 'closed') {
    div.find(".cite-form-status").val('open');
div.find(".cite-form-status").val('open');
    div.find('.cite-extra-fields').show(1, function() {
div.find('.cite-extra-fields').show(1, function () {
      // jQuery adds "display:block", which screws things up
// jQuery adds "display:block", which screws things up
      div.find('.cite-extra-fields').attr('style', 'width:100%; background-color:transparent;');  
div.find('.cite-extra-fields').attr('style', 'width:100%; background-color:transparent;');
    });
});
  } else {
} else {
    div.find(".cite-form-status").val('closed');
div.find(".cite-form-status").val('closed');
    div.find('.cite-extra-fields').hide();
div.find('.cite-extra-fields').hide();
  }  
}
};
};


// Resets form fields and previews
// Resets form fields and previews
// Resets form fields and previews
CiteTB.resetForm = function () {
CiteTB.resetForm = function() {
var template = CiteTB.getOpenTemplate();
  var template = CiteTB.getOpenTemplate();
var div = $("#citetoolbar-" + CiteTB.escStr(template.shortform));
  var div = $("#citetoolbar-"+CiteTB.escStr(template.shortform));
div.html(template.getForm());
  div.html(template.getForm());
};
};


// STRING UTILITY FUNCTIONS
// STRING UTILITY FUNCTIONS
// Returns a string quoted as necessary for name/group attributes
// Returns a string quoted as necessary for name/group attributes
CiteTB.getQuotedString = function(s) {
CiteTB.getQuotedString = function (s) {
  var sq = /\'/.test(s); // single quotes
var sq = /\'/.test(s); // single quotes
  var dq = /\"/.test(s); // double quotes
var dq = /\"/.test(s); // double quotes
  if (!sq && !dq) { // Always quotes for non-latin alphabet
if (!sq && !dq) { // Always quotes for non-latin alphabet
    return '"'+s+'"';
return '"' + s + '"';
  } else if (!dq) { // Can use double quotes
} else if (!dq) { // Can use double quotes
    return '"'+s+'"';
return '"' + s + '"';
  } else if (!sq) { // Can use single quotes
} else if (!sq) { // Can use single quotes
    return "'"+s+"'";
return "'" + s + "'";
  } else { // Has double and single quotes
} else { // Has double and single quotes
    s = s.replace(/\"/g, '\'');
s = s.replace(/\"/g, '\'');
    return '"'+s+'"';
return '"' + s + '"';
  }
}
};
};


// Fix up strings for output - capitalize first char, replace underscores with spaces
// Fix up strings for output - capitalize first char, replace underscores with spaces
CiteTB.fixStr = function(s) {
CiteTB.fixStr = function (s) {
  s = s.slice(0,1).toUpperCase() + s.slice(1);
s = s.slice(0, 1).toUpperCase() + s.slice(1);
  s = s.replace('_',' ');
s = s.replace('_', ' ');
  return s;
return s;
};
};


// Escape spaces and quotes for use in HTML classes/ids
// Escape spaces and quotes for use in HTML classes/ids
CiteTB.escStr = function(s) {
CiteTB.escStr = function (s) {
  return s.replace(' ', '-').replace("'", "\'").replace('"', '\"');
return s.replace(' ', '-').replace("'", "\'").replace('"', '\"');
};
};


// MISC FUNCTIONS
// MISC FUNCTIONS
// Determine which template form is open, and get the template object for it
// Determine which template form is open, and get the template object for it
CiteTB.getOpenTemplate = function() {
CiteTB.getOpenTemplate = function () {
  var dialogs = $(".ui-dialog-content.ui-widget-content:visible");
var dialogs = $(".ui-dialog-content.ui-widget-content:visible");
  var templatename = $(dialogs[0]).find(".cite-template").val();
var templatename = $(dialogs[0]).find(".cite-template").val();
  return CiteTB.Templates[templatename];
return CiteTB.Templates[templatename];
};
};


// Display the report for the error checks
// Display the report for the error checks
CiteTB.displayErrors = function(errors) {
CiteTB.displayErrors = function (errors) {
  $('#cite-err-report').remove();
$('#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" />');
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);
$('#editpage-copywarn').before(table);
  var tr;
var tr;
  var tr1 = $('<tr style="width:100%" />');
var tr1 = $('<tr style="width:100%" />');
  var th1 = $('<th style="width:60%; font-size:110%" />').html(mw.usability.getMsg('cite-err-report-heading'));
var th1 = $('<th style="width:60%; font-size:110%" />').html(mw.messages.get('cite-err-report-heading'));
  var th2 = $('<th style="text-align:right; width:40%" />');
var th2 = $('<th style="text-align:right; width:40%" />');
  var im = $('<img />').attr('src', '//upload.wikimedia.org/wikipedia/commons/thumb/5/55/Gtk-stop.svg/20px-Gtk-stop.svg.png');
var 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'));
im.attr('alt', mw.messages.get('cite-err-report-close')).attr('title', mw.messages.get('cite-err-report-close'));
  var ad = $('<a id="cite-err-check-close" />').attr('href', '#');
var ad = $('<a id="cite-err-check-close" />').attr('href', '#');
  ad.append(im);
ad.append(im);
  th2.append(ad);
th2.append(ad);
  tr1.append(th1).append(th2);
tr1.append(th1).append(th2);
  table.append(tr1);
table.append(tr1);
  $('#cite-err-check-close').on('click', function() { $('#cite-err-report').remove(); });
$('#cite-err-check-close').on('click', function () {
  if (errors.length === 0) {
$('#cite-err-report').remove();
    tr = $('<tr style="width:100%;" />');
});
    var td = $('<td style="text-align:center; margin:1.5px;" />').html(mw.usability.getMsg('cite-err-report-empty'));
if (errors.length === 0) {
    tr.append(td);
tr = $('<tr style="width:100%;" />');
    table.append(tr);
var td = $('<td style="text-align:center; margin:1.5px;" />').html(mw.messages.get('cite-err-report-empty'));
   
tr.append(td);
    return;
table.append(tr);
  }
 
  for(var e in errors) {
return;
    var err = errors[e];
}
    tr = $('<tr style="width:100%;" />');
for (var e in errors) {
    var td1 = $('<td style="border: 1px solid black; margin:1.5px; width:60%" />').html(err.err);
var err = errors[e];
    var td2 = $('<td style="border: 1px solid black; margin:1.5px; width:40%" />').html(mw.usability.getMsg(err.msg));
tr = $('<tr style="width:100%;" />');
    tr.append(td1).append(td2);
var td1 = $('<td style="border: 1px solid black; margin:1.5px; width:60%" />').html(err.err);
    table.append(tr);
var td2 = $('<td style="border: 1px solid black; margin:1.5px; width:40%" />').html(mw.messages.get(err.msg));
  }
tr.append(td1).append(td2);
table.append(tr);
}
};
};
 
} // End of code loaded only on edit

Latest revision as of 20:15, 24 September 2026

/* jshint smarttabs:true, loopfunc:true, forin:false */
/* global mw, $ */
// TODO: make autodate an option in the CiteTemplate object, not a preference

// Global object
// TODO:
// * Remove this once the page is moved to a module 'ext.gadget.refToolbarDialogs' depending on 'ext.gadget.refToolbarBase'
if (typeof CiteTB === 'undefined') {
	var CiteTB = {
		"Templates": {}, // All templates
		"Options": {}, // Global options
		"UserOptions": {}, // User options
		"DefaultOptions": {}, // Script defaults
		"ErrorChecks": {} // Error check functions
	};
}

// TODO: Move this to [[MediaWiki:Gadget-refToolbarDialogs.css]] and add it to the definition of module 'ext.gadget.refToolbarDialogs'
mw.util.addCSS(".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 = {};
	for (var t in CiteTB.Templates) {
		var tem = CiteTB.Templates[t];
		var sform = CiteTB.escStr(tem.shortform);
		var actionobj = {
			type: 'dialog',
			module: 'cite-dialog-' + sform
		};
		var dialogobj = {};
		dialogobj['cite-dialog-' + sform] = {
			resizeme: false,
			title: mw.message('cite-dialog-' + sform),
			id: 'citetoolbar-' + sform,
			init: function () {
			},
			html: tem.getInitial(),
			dialog: {
				width: 680,
				open: function () {
					$(this).html(CiteTB.getOpenTemplate().getForm());
					/** @param {jQuery.Event} e */
					$('.cite-prev-parse').on('click', function (e) {
						e.preventDefault();
						CiteTB.prevParseClick();
					});
				},
				buttons: {
					'cite-form-submit': function () {
						var ref = CiteTB.getRef(false, true);
						$(this).dialog('close');
						$.wikiEditor.modules.toolbar.fn.doAction($(this).data('context'), {
							type: 'encapsulate',
							options: {
								post: 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();
					}
				}
			}
		};
		try {
			$target.wikiEditor('addDialog', dialogobj);
		} catch (e) {
			// TypeError: range is null
		}
		//if (!CiteTB.getOption('modal')) {
		//$('#citetoolbar-'+sform).dialog('option', 'modal', false);
		//}
		temlist[sform] = {label: tem.templatename, action: actionobj};
	}

	var refsection = {
		'sections': {
			'cites': {
				type: 'toolbar',
				label: mw.msg('cite-section-label'),
				groups: {
					'template': {
						tools: {
							'template': {
								type: 'select',
								label: mw.msg('cite-template-list'),
								list: temlist
							}
						}
					},
					'namedrefs': {
						label: mw.msg('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/60px-Nuvola_clipboard_lined.svg.png',
								section: 'cites',
								group: 'namedrefs',
								label: mw.msg('cite-named-refs-button')
							}
						}
					},
					'errorcheck': {
						label: mw.msg('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/60px-Nuvola_apps_korganizer-NO.png',
								section: 'cites',
								group: 'errorcheck',
								label: mw.msg('cite-errorcheck-button')
							}
						}
					}
				}
			}
		}
	};

	var defaultdialogs = {
		'cite-toolbar-errorcheck': {
			title: mw.message('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.messages.get('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': {
			title: mw.message('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.messages.get('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;
						}
						$(this).dialog('close');
						$.wikiEditor.modules.toolbar.fn.doAction($(this).data('context'), {
							type: 'encapsulate',
							options: {
								post: CiteTB.getNamedRef(refname, true)
							}
						}, $(this));
					},
					'wikieditor-toolbar-tool-link-cancel': function () {
						$(this).dialog('close');
					}
				}
			}
		}
	};

	try {
		$target.wikiEditor('addDialog', defaultdialogs);
	} catch (e) {
		// error occurred setting up wikieditor.
	}
	$('#citetoolbar-namedrefs').off('dialogopen');
	if (!CiteTB.getOption('modal')) {
		//$('#citetoolbar-namedrefs').dialog('option', 'modal', false);
		//$('#citetoolbar-errorcheck').dialog('option', 'modal', false);
		mw.util.addCSS(".ui-widget-overlay {" +
			"display:none !important;" +
			"}");
	}
	try {
		$target.wikiEditor('addToToolbar', refsection);
	} catch (e) {
		// error occurred setting up wikieditor.
	}
};

// Load local data - messages, cite templates, etc.
$(document).ready(function () {
	mw.loader.load('/w/index.php?title=MediaWiki:RefToolbarMessages-en.js&action=raw&ctype=text/javascript');
});

// Setup the main object
CiteTB.mainRefList = [];
CiteTB.refsLoaded = false;

// REF FUNCTIONS
// Actually assemble a ref from user input
CiteTB.getRef = function (inneronly, forinsert) {
	var i, j, g, group;
	var template = CiteTB.getOpenTemplate();
	var templatename = template.templatename;
	var res = '';
	var refobj = {'shorttag': false};
	if (!inneronly) {
		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 (g in template.incrementables) {
		group = template.incrementables[g];
		for (i = 1; i <= group.val; i++) {
			for (j = 0; j < group.fields.length; j++) {
				var fieldname = group.fields[j].field;
				var fieldid = fieldname.replace('<N>', i.toString());
				var field = $('#cite-' + CiteTB.escStr(template.shortform) + '-' + fieldid).val();
				if (field) {
					content += ' |' + fieldid + '=';
					content += $.trim(field);
				}
			}
		}
	}
	for (i = 0; i < template.basic.length; i++) {
		if (template.basic[i].increment_group) {
			continue;
		}
		var fieldname = template.basic[i].field;
		var field = $('#cite-' + CiteTB.escStr(template.shortform) + '-' + fieldname).val();
		if (field) {
			content += ' |' + fieldname + '=';
			content += $.trim(field);
		}
	}
	if ($('#cite-form-status').val() !== 'closed') {
		for (i = 0; i < template.extra.length; i++) {
			if (template.extra[i].increment_group) {
				continue;
			}
			var fieldname = template.extra[i].field;
			var field = $('#cite-' + CiteTB.escStr(template.shortform) + '-' + fieldname).val();
			if (field) {
				content += ' |' + fieldname + '=';
				content += $.trim(field);
			}
		}
	}
	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) {
	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.util.wikiScript('api'),
		{action: 'parse', title: mw.config.get('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.util.wikiScript('api'),
		{action: 'expandtemplates', title: mw.config.get('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: mw.config.get('wgArticleId'),
			format: 'json'
		};
		if (CiteTB.getOption('expandtemplates')) {
			postdata.rvexpandtemplates = '1';
		}
		$.get(mw.util.wikiScript('api'),
			postdata,
			function (data) {
				var pagetext = data.query.pages[mw.config.get('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());
		}
	}
};

// Safe version of decodeURIComponent() that doesn't throw exceptions.
// If the native decodeURIComponent() threw an exception, the original string will be returned.
CiteTB.safeDecodeURIComponent = function (s) {
	try {
		s = decodeURIComponent(s);
	} catch (e) {
	}
	return s;
};

/**
 * Convert one Citoid result into RefToolbar autofill properties.
 *
 * The property names must match the "autofillprop" values in
 * MediaWiki:RefToolbarConfig.js, not the citation template parameters.
 *
 * @param {Object} entry One item from the Citoid response body.
 * @param {string} tem Target citation template short name, e.g. 'book'.
 * @return {Object} Autofill properties; empty if nothing matched.
 */
CiteTB.transformCitoidResponse = function (entry, tem) {
	var result = {};
	// A pipe ends the template parameter. CiteTB.getRef joins the field
	// values into wikitext and does not escape them.
	var escapePipes = function (text) {
		return typeof text === 'string' ? text.replace(/\|/g, '{{!}}') : text;
	};
	// Citoid puts the chapter in "title" and the book in "bookTitle". Only
	// cite book has a chapter field.
	var isBookSection = entry.itemType === 'bookSection' && tem === 'book';

	Object.keys(entry).forEach(function (key) {
		var value = escapePipes(entry[key]);

		// Zotero has one field name for each item type. The /mediawiki/
		// format keeps them separate, so each case lists all the names that
		// Zotero maps to the same base field.
		switch (key) {
			case 'publicationTitle':
			case 'blogTitle':
			case 'bookTitle':
			case 'dictionaryTitle':
			case 'encyclopediaTitle':
			case 'forumTitle':
			case 'proceedingsTitle':
			case 'programTitle':
			case 'websiteTitle':
				// RefToolbar maps every containing-work title to journal
				if (isBookSection) {
					result.title = value;
				} else {
					result.journal = value;
				}
				break;
			case 'title':
			case 'caseName':
			case 'nameOfAct':
			case 'subject':
				if (isBookSection) {
					result.chapter = value;
				} else {
					result.title = value;
				}
				break;
			case 'volume':
			case 'codeVolume':
			case 'reporterVolume':
				result.volume = value;
				break;
			case 'issue':
				result.issue = value;
				break;
			case 'edition':
				// Citoid returns "1st ed"; the templates want "1st".
				value = value.split(' edition').join('');
				value = value.split(' ed.').join('');
				value = value.split(' ed').join('');
				result.edition = value;
				break;
			case 'publisher':
			case 'company':
			case 'distributor':
			case 'institution':
			case 'label':
			case 'network':
			case 'studio':
			case 'university':
				result.publisher = value;
				break;
			case 'pages':
			case 'codePages':
			case 'firstPage':
				result.pages = value;
				break;
			// Citoid can return several identifiers; the templates take one.
			case 'ISBN':
				result.isbn = escapePipes(Array.isArray(value) ? value[0] : value);
				break;
			case 'ISSN':
				result.issn = escapePipes(Array.isArray(value) ? value[0] : value);
				break;
			case 'date':
			case 'dateDecided':
			case 'dateEnacted':
			case 'issueDate':
				result.date = value;
				break;
			case 'DOI':
				result.doi = value;
				break;
			case 'language':
				result.language = value;
				break;
			case 'place':
				result.location = value;
				break;
			case 'author':
				value.forEach(function (author) {
					// Reject name parts that start with a digit. These are
					// dates from bad metadata.
					var firstName = /^\d/.test(author[0]) ?  '' : escapePipes(author[0]);
					var lastName = /^\d/.test(author[1]) ? '' : escapePipes(author[1]);
					// Accept an institutional author, which has no first name.
					if (lastName) {
						if (!result.authors) {
							result.authors = [];
						}
						// CiteTB.autoFill expects [last, first].
						result.authors.push([lastName, firstName || '']);
					}
				});
				break;
		}
	});

	return result;
};

// Autofill a template from an ID (ISBN, DOI, PMID, URL)
CiteTB.initAutofill = function () {
	var elemid = $(this).attr('id');
	var res = /^cite\-auto\-(.*?)\-(.*)\-(.*)$/.exec(elemid);
	if (!res) {
		return false;
	}
	var tem = res[1];
	var field = res[2];
	var autotype = res[3];
	var id = $('#cite-' + tem + '-' + field).val();
	if (!id) {
		return false;
	}
	id = CiteTB.safeDecodeURIComponent(id);

	var citoidConfig = mw.config.get('wgCitoidConfig') || {};
	var serviceUrl = citoidConfig.citoidServiceUrl;

	if (serviceUrl) {
		(new mw.Api({
			ajax: {
				url: serviceUrl.replace(/\/api$/, '') + '/mediawiki/' + encodeURIComponent(id),
				headers: { 'accept-language': mw.config.get('wgContentLanguage') },
				timeout: 30 * 1000,
				type: 'GET'
			}
		})).get().then(function (results) {
			if (results && results[0]) {
				CiteTB.autoFill(CiteTB.transformCitoidResponse(results[0], tem), tem, autotype);
			}
		});
		return false;
	}

	var url = '//reftoolbar.toolforge.org/lookup.php?'
		+ autotype + '=' + encodeURIComponent(id)
		+ '&template=' + encodeURIComponent(tem);
	var s = document.createElement('script');
	s.src = url;
	s.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 + '-';
	var i, j, coauthors;
	$('.' + cl + 'title').val(data.title);
	// Fill in authors
	if (data.authors && data.authors.length > 0) {
		if ($('.' + cl + 'last-incr-1').length != 0) {
			var classes = $('.' + cl + 'last-incr-1').eq(0).attr('class').split(/\s+/);
			var group = false;
			var patt = /cite-[^-]*?-incr-(.*)/;
			for (var c = 0; c < classes.length; c++) {
				if (patt.exec(classes[c])) {
					group = patt.exec(classes[c])[1];
					break;
				}
			}
			$('.' + cl + 'last-incr-1').val(data.authors[0][0]);
			$('.' + cl + 'first-incr-1').val(data.authors[0][1]);
			elemid = '#cite-incr-' + template + '-' + group;
			for (var i = 2; i < data.authors.length + 1; i++) {
				$(elemid).click();
				$('.' + cl + 'last-incr-' + i.toString()).val(data.authors[i - 1][0]);
				$('.' + cl + 'first-incr-' + i.toString()).val(data.authors[i - 1][1]);
			}
		} else if ($('.' + cl + 'author-incr-1').length != 0) {
			var classes = $('.' + cl + 'author-incr-1').eq(0).attr('class').split(/\s+/);
			var group = false;
			var patt = /cite-[^-]*?-incr-(.*)/
			for (var c = 0; c < classes.length; c++) {
				if (patt.exec(classes[c])) {
					group = patt.exec(classes[c])[1];
					break;
				}
			}
			$('.' + cl + 'author-incr-1').val(data.authors[0].join(', '));
			elemid = '#cite-incr-' + template + '-' + group;
			for (var i = 2; i < data.authors.length + 1; i++) {
				$(elemid).click();
				$('.' + cl + 'author-incr-' + i.toString()).val(data.authors[i - 1].join(', '));
			}
		} else if ($('.' + cl + 'last1').length != 0) {
			for (i = 0; data.authors && 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 {
					coauthors = [];
					for (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 (i = 0; data.authors && i < data.authors.length; i++) {
				if ($('.' + cl + 'author' + (i + 1)).length) {
					$('.' + cl + 'author' + (i + 1)).val(data.authors[i].join(', '));
				} else {
					coauthors = [];
					for (j = i; j < data.authors.length; j++) {
						coauthors.push(data.authors[j].join(', '));
					}
					$('.' + cl + 'coauthors').val(coauthors.join('; '));
					break;
				}
			}
		} else {
			var authors = [];
			for (i = 0; data.authors && i < data.authors.length; i++) {
				authors.push(data.authors[i].join(', '));
			}
			$('.' + cl + 'authors').val(authors.join('; '));
		}
	}

	// Format partial dates of the format YYYY-MM, YYYY-MM-XX, or YYYY-MM-DD correctly
	if (data.date) {
		try {
			var DT = new Date(data.date);
			if (/^\d{4}-\d{2}(-XX)?$/i.test(data.date)) {
				data.date = data.date.replace('-XX', '');
				$('.' + cl + 'date').val(CiteTB.formatDate(DT, false, true));
			} else if (/^\d{4}-\d{2}-\d{2}?/i.test(data.date)) {
				$('.' + cl + 'date').val(CiteTB.formatDate(DT, true, true));
			} else {
				$('.' + cl + 'date').val(data.date);
			}
		} catch (e) {
		}
	} else {
		$('.' + cl + 'date').val(data.date);
	}

	if (type === 'pmid' || type === 'doi') {
		$('.' + cl + 'journal').val(data.journal);
		$('.' + cl + 'volume').val(data.volume);
		$('.' + cl + 'issue').val(data.issue);
		$('.' + cl + 'pages').val(data.pages);
		if (type === 'pmid' && data.doi) {
			$('.' + cl + 'doi').val(data.doi);
		}
	} else if (type === 'isbn') {
		$('.' + cl + 'publisher').val(data.publisher);
		$('.' + cl + 'location').val(data.location);
		$('.' + cl + 'edition').val(data.edition);
	} else if (type === 'url') {
		$('.' + cl + 'journal').val(data.journal);
		$('.' + cl + 'volume').val(data.volume);
		$('.' + cl + 'issue').val(data.issue);
		$('.' + cl + 'pages').val(data.pages);
		$('.' + cl + 'publisher').val(data.publisher);
		$('.' + cl + 'edition').val(data.edition);
		$('.' + cl + 'isbn').val(data.isbn);
		$('.' + cl + 'issn').val(data.issn);
		$('.' + cl + 'doi').val(data.doi);
		// "en-US" isn't a valid value for the language parameter
		if (data.language && data.language !== 'en-US' && data.language !== 'en-GB') {
			$('.' + cl + 'language').val(data.language);
		}
		$('.' + cl + 'chapter').val(data.chapter);
	}
};

// FORM DIALOG FUNCTIONS
// Add new incrementable fields
CiteTB.incrementFields = function () {
	template = CiteTB.getOpenTemplate();
	var currentrow = $(this).parents('tr')[0];
	$(this).prev().css('width', '100%');
	$(this).detach();
	var elemid = $(this).attr('id');
	var res = /^cite\-incr\-(.*?)\-(.*)$/.exec(elemid);
	group = res[2];
	increments = template.incrementables[group];
	fields = increments.fields;
	incrval = increments.val + 1;
	template.incrementables[group].val += 1;
	trs = template.makeFormInner(fields, false);
	trs.reverse();
	for (var i = 0; i < trs.length; i++) {
		$(currentrow).after(trs[i]);
	}
};

// 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();
	var datestr = CiteTB.formatDate(DT);
	$('#cite-' + id + '-' + field).val(datestr);
	return false;
};

CiteTB.formatDate = function (DT, useday, usemonth) {
	if (typeof useday == "undefined") {
		useday = true;
	}
	if (typeof usemonth == "undefined") {
		usemonth = true;
	}
	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();
	if (useday) {
		datestr = datestr.replace('<date>', date);
		datestr = datestr.replace('<zdate>', zdate);
	} else {
		datestr = datestr.replace('<date>', '');
		datestr = datestr.replace('<zdate>', '');
	}
	if (usemonth) {
		datestr = datestr.replace('<month>', month);
		datestr = datestr.replace('<zmonth>', zmonth);
		datestr = datestr.replace('<monthname>', CiteTB.getOption('months')[DT.getUTCMonth()]);
	} else {
		datestr = datestr.replace('<month>', '');
		datestr = datestr.replace('<zmonth>', '');
		datestr = datestr.replace('<monthname>', '');
	}
	datestr = datestr.replace('<year>', DT.getUTCFullYear().toString());
	return datestr.replace(/^[ \/\-\,\.]*(.*?)[ \/\-\,\.]*$/g, "$1"); // Cleanup any dangling spaces or connectors that might result from omitting date/month
};

// 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 = [], i;
	for (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.messages.get('cite-no-namedrefs'));
	} else {
		stuff.html(mw.messages.get('cite-namedrefs-intro'));
		var select = $('<select id="cite-namedref-select">');
		select.append($('<option value="" />').text(mw.messages.get('cite-named-refs-dropdown')));
		for (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.messages.get('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.messages.get('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.messages.get('cite-form-parse'));
		$('#cite-namedref-parsed').after(link);

		$("#cite-namedref-select").on('change', CiteTB.namedRefSelectClick);
		$('#cite-nref-parse').on('click', CiteTB.nrefParseClick);
	}
};

// Function to get the errorcheck form HTML
CiteTB.setupErrorCheck = function () {
	var form = $('<div id="cite-errorcheck-heading" />').html(mw.messages.get('cite-errorcheck-heading'));
	var ul = $("<ul id='cite-errcheck-list' />");
	var test;
	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.html(template.getForm());
};

// STRING UTILITY FUNCTIONS
// Returns a string quoted as necessary for name/group attributes
CiteTB.getQuotedString = function (s) {
	var sq = /\'/.test(s); // single quotes
	var dq = /\"/.test(s); // double quotes
	if (!sq && !dq) { // Always quotes for non-latin alphabet
		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();
	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 tr;
	var tr1 = $('<tr style="width:100%" />');
	var th1 = $('<th style="width:60%; font-size:110%" />').html(mw.messages.get('cite-err-report-heading'));
	var th2 = $('<th style="text-align:right; width:40%" />');
	var im = $('<img />').attr('src', '//upload.wikimedia.org/wikipedia/commons/thumb/5/55/Gtk-stop.svg/20px-Gtk-stop.svg.png');
	im.attr('alt', mw.messages.get('cite-err-report-close')).attr('title', mw.messages.get('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').on('click', function () {
		$('#cite-err-report').remove();
	});
	if (errors.length === 0) {
		tr = $('<tr style="width:100%;" />');
		var td = $('<td style="text-align:center; margin:1.5px;" />').html(mw.messages.get('cite-err-report-empty'));
		tr.append(td);
		table.append(tr);

		return;
	}
	for (var e in errors) {
		var err = errors[e];
		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.messages.get(err.msg));
		tr.append(td1).append(td2);
		table.append(tr);
	}
};