MediaWiki:Gadget-RefToolbarNew.js: Revizyonlar arasındaki fark

Vikipedi, özgür ansiklopedi
İçerik silindi İçerik eklendi
Krenair (mesaj | katkılar)
Maintenance: mw:RL/MGU / mw:RL/JD - phab:T169385 - deprecated in jQuery 3.0
Güncelleme
1. satır: 1. satır:
var numforms = 0;
/*jshint smarttabs:true, loopfunc:true,forin:false*/
var wikEdAutoUpdateUrl;
/*global mw, $, importScript */
var citeUserDateFormat;
// TODO: make autodate an option in the CiteTemplate object, not a preference
var refTagURL;
var defaultRefTagURL = '//reftag.appspot.com/';
var refToolDebug;


String.prototype.trim = function() {
// Global object
return this.replace(/^\s+|\s+$/g,"");
// 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
};
}


function refbuttons() {
// Only execute on edit, unless it is a user JS/CSS page
if (mw.toolbar && document.getElementById('toolbar') ) {
// TODO: Remove tests already done by [[MediaWiki:Gadget-refToolbar.js]]
var button = document.createElement('a');
if (
button.href = "javascript:easyCiteMain()";
( mw.config.get('wgAction') === 'edit' || mw.config.get('wgAction') === 'submit' ) &&
button.title = "Insert Citation";
( ( mw.config.get('wgNamespaceNumber') !== 2 && mw.config.get('wgNamespaceNumber') !== 4 ) ||
button.className = "mw-toolbar-editbutton";
( mw.config.get('wgPageName').indexOf('.js') === -1 && mw.config.get('wgPageName').indexOf('.css') === -1 ) )
var buttonimage = document.createElement('img');
) {
buttonimage.src = "//upload.wikimedia.org/wikipedia/commons/e/ea/Button_easy_cite.png";
buttonimage.alt = "Insert Citation";
button.appendChild(buttonimage);
var toolbar = document.getElementById('toolbar');
if (navigator.userAgent.indexOf('MSIE') == -1) {
toolbar.appendChild(button);
var citemain = document.createElement('div');
citemain.style.display = 'none';
citemain.style.margin = '0 0 6px';
citemain.style.clear = 'both';
citemain.style.height = 'auto';
citemain.setAttribute('Id', 'citeselect');
citemain.appendChild( addOption("citeWeb()", "Web") );
citemain.appendChild( addOption("citeNews()", "News") );
citemain.appendChild( addOption("citeBook()", "Book") );
citemain.appendChild( addOption("citeJournal()", "Journal") );
citemain.appendChild( addOption("citeNamedRef()", "Named references") );
citemain.appendChild( addOption("dispErrors()", "Error check") );
citemain.appendChild( addOption("showMore()", "More") );
citemain.appendChild( addOption("hideInitial()", "Cancel") );


var citemore = document.createElement('div');
// TODO: Move this to [[MediaWiki:Gadget-refToolbarDialogs.css]] and add it to the definition of module 'ext.gadget.refToolbarDialogs'
citemore.style.display = 'none';
mw.util.addCSS(".cite-form-td {"+
citemore.setAttribute('Id', 'citemore');
"height: 0 !important;"+
citemore.appendChild( addOption("citeEncyclopedia()", "Encyclopedia") );
"padding: 0.1em !important;"+
citemore.appendChild( addOption("citePressRelease()", "Press release") );
"}");
citemore.appendChild( addOption("citeMap()", "Map") );
citemore.appendChild( addOption("showRefSectionOptions()", "Ref Section") );
citemain.appendChild(citemore);


$( citemain ).insertAfter( $( toolbar ) );
// Default options, these mainly exist so the script won't break if a new option is added
}
CiteTB.DefaultOptions = {
else {
"date format" : "<year>-<zmonth>-<zdate>",
toolbar.appendChild(button);
"autodate fields" : [],
var citeselect = document.createElement('div');
"months" : ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
citeselect.id = 'citeselect';
"modal" : true,
citeselect.style.display = "none";
"autoparse" : false,
citeselect.innerHTML = '<input type="button" value="Web" onclick="citeWeb()" />'+
"expandtemplates": false
'<input type="button" value="News" onclick="citeNews()" />'+
};
'<input type="button" value="Book" onclick="citeBook()" />'+
'<input type="button" value="Journal" onclick="citeJournal()" />'+
'<input type="button" value="Named references" onclick="citeNamedRef()" />'+
'<input type="button" value="Error check" onclick="dispErrors()" />'+
'<input type="button" value="More" onclick="showMore()" />'+
'<input type="button" value="Cancel" onclick="hideInitial()" />'+
'<div id="citemore" style="display:none">\
<input type="button" value="Encyclopedia" onclick="citeEncyclopedia()" />\
<input type="button" value="Press release" onclick="citePressRelease()" />\
<input type="button" value="Map" onclick="citeMap()" />\
<input type="button" value="Ref Section" onclick="showRefSectionOptions()" />\
</div>';
document.getElementById('editform').insertBefore(citeselect, document.getElementById('editform').firstChild ) ;
}
var reftoolformarea = document.createElement( 'span' );
reftoolformarea.id = 'refToolFormArea';
document.getElementById('citeselect').appendChild( reftoolformarea );
}
if (typeof EditTools == "object") {
var placeholder = document.getElementById("editpage-specialchars");
EditTools.createEditTools (placeholder);
}
}


function addOption(script, text) {
// Get an option - user settings override global which override defaults
var option = document.createElement('input');
CiteTB.getOption = function(opt) {
option.setAttribute('type', 'button');
if (CiteTB.UserOptions[opt] !== undefined) {
option.setAttribute('onclick', script);
return CiteTB.UserOptions[opt];
option.setAttribute("value", text);
} else if (CiteTB.Options[opt] !== undefined) {
return CiteTB.Options[opt];
return option;
}

function hideInitial() {
document.getElementById('citeselect').style.display = 'none';
oldFormHide();
}

function oldFormHide() {
//if (numforms != 0) {
// document.getElementById('citediv'+numforms).style.display = 'none';
//}
document.getElementById('refToolFormArea').innerHTML = '';
if (document.getElementById('errorform') !== null) {
document.getElementById('citeselect').removeChild(document.getElementById('errorform'));
}
}
}
return CiteTB.DefaultOptions[opt];
};


function easyCiteMain() {
CiteTB.init = function() {
document.getElementById('citeselect').style.display = '';
/* Main stuff, build the actual toolbar structure
document.getElementById('citemore').style.display = 'none';
* 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
*/


function showMore() {
if (typeof $('div[rel=cites]')[0] !== 'undefined') { // Mystery IE bug workaround
document.getElementById('citemore').style.display = '';
return;
}

var months = ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'];
var citeGlobalDateFormat = "<date> <monthname> <year>";
function getTime() {
var datestr = '';
if (citeUserDateFormat) {
datestr = citeUserDateFormat;
} else {
datestr = citeGlobalDateFormat;
}
}
var DT = new Date();
$('head').trigger('reftoolbarbase');
var $target = $('#wpTextbox1');
var zmonth = '';
var temlist = {};
var month = DT.getUTCMonth()+1;
for (var t in CiteTB.Templates) {
if (month < 10) {
var tem = CiteTB.Templates[t];
zmonth = "0"+month.toString();
} else {
var sform = CiteTB.escStr(tem.shortform);
zmonth = month.toString();
var actionobj = {
type: 'dialog',
module: 'cite-dialog-'+sform
};
var dialogobj = {};
dialogobj['cite-dialog-'+sform] = {
resizeme: false,
titleMsg: 'cite-dialog-'+sform,
id: 'citetoolbar-'+sform,
init: function() {},
html: tem.getInitial(),
dialog: {
width:675,
open: function() {
$(this).html(CiteTB.getOpenTemplate().getForm());
/** @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();
}
}
}
};
$target.wikiEditor('addDialog', dialogobj);
//if (!CiteTB.getOption('modal')) {
//$('#citetoolbar-'+sform).dialog('option', 'modal', false);
//}
temlist[sform] = {label: tem.templatename, action: actionobj };
}
}
month = month.toString();
var zdate = '';
var date = DT.getUTCDate();
if (date < 10) {
zdate = "0"+date.toString();
} else {
zdate = date.toString();
}
date = date.toString();
datestr = datestr.replace('<date>', date);
datestr = datestr.replace('<month>', month);
datestr = datestr.replace('<zdate>', zdate);
datestr = datestr.replace('<zmonth>', zmonth);
datestr = datestr.replace('<monthname>', months[DT.getUTCMonth()]);
datestr = datestr.replace('<year>', DT.getUTCFullYear().toString());
return (datestr);
}


function lastNameToRefname() {
var refsection = {
//Note: This only works if field 'refname' comes after field 'last', but it always does
'sections': {
var lastName;
'cites': {
var fields = document.getElementById('citediv'+numforms).getElementsByTagName('input');
type: 'toolbar',
for (var i=0; i<fields.length; i++) {
labelMsg: 'cite-section-label',
groups: {
if(fields[i].id == 'last') {
'template': {
lastName = fields[i].value;
}
tools: {
'template': {
else if(fields[i].id == 'refname') {
fields[i].value = lastName.replace(/^\s*(.*?)\s*$/, "$1");
type: 'select',
return;
labelMsg: 'cite-template-list',
list: temlist
}
}
},
'namedrefs': {
labelMsg: 'cite-named-refs-label',
tools: {
'nrefs': {
type: 'button',
action: {
type: 'dialog',
module: 'cite-toolbar-namedrefs'
},
icon: '//upload.wikimedia.org/wikipedia/commons/thumb/b/be/Nuvola_clipboard_lined.svg/22px-Nuvola_clipboard_lined.svg.png',
section: 'cites',
group: 'namedrefs',
labelMsg: 'cite-named-refs-button'
}
}
},
'errorcheck': {
labelMsg: 'cite-errorcheck-label',
tools: {
'echeck': {
type: 'button',
action: {
type: 'dialog',
module: 'cite-toolbar-errorcheck'
},
icon: '//upload.wikimedia.org/wikipedia/commons/thumb/a/a3/Nuvola_apps_korganizer-NO.png/22px-Nuvola_apps_korganizer-NO.png',
section: 'cites',
group: 'errorcheck',
labelMsg: 'cite-errorcheck-button'
}
}
}
}
}
}
};
var defaultdialogs = {
'cite-toolbar-errorcheck': {
titleMsg: 'cite-errorcheck-label',
id: 'citetoolbar-errorcheck',
resizeme: false,
init: function() {},
html: '<div id="cite-namedref-loading">'+
'<img src="//upload.wikimedia.org/wikipedia/commons/4/42/Loading.gif" />'+
'&nbsp;'+mw.usability.getMsg('cite-loading')+'</div>',
dialog: {
width:550,
open: function() {
CiteTB.loadRefs();
},
buttons: {
'cite-errorcheck-submit': function() {
var errorchecks = $("input[name='cite-err-test']:checked");
var errors = [];
for (var i=0; i<errorchecks.length; i++) {
errors = errors.concat(CiteTB.ErrorChecks[$(errorchecks[i]).val()].run());
}
CiteTB.displayErrors(errors);
$(this).dialog( 'close' );
},
'wikieditor-toolbar-tool-link-cancel': function() {
$(this).dialog( 'close' );
}
}
}
},
'cite-toolbar-namedrefs': {
titleMsg: 'cite-named-refs-title',
resizeme: false,
id: 'citetoolbar-namedrefs',
html: '<div id="cite-namedref-loading">'+
'<img src="//upload.wikimedia.org/wikipedia/commons/4/42/Loading.gif" />'+
'&nbsp;'+mw.usability.getMsg('cite-loading')+'</div>',
init: function() {},
dialog: {
width: 550,
open: function() {
CiteTB.loadRefs();
},
buttons: {
'cite-form-submit': function() {
var refname = $("#cite-namedref-select").val();
if (refname === '') {
return;
}
$(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' );
}
}
}
}
}
};
$target.wikiEditor('addDialog', defaultdialogs);
$('#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;"+
"}");
}
}
}
$target.wikiEditor('addToToolbar', refsection);
};


function setAccessDateToday() {
// Load local data - messages, cite templates, etc.
$(document).ready( function() {
document.getElementById('accessdate').value = getTime();
/* var fields = document.getElementById('citediv'+numforms).getElementsByTagName('input');
switch( mw.config.get('wgUserLanguage') ) {
for (var i=0; i<fields.length; i++) {
case 'de': // German
if(fields[i].id == 'accessdate') {
importScript('MediaWiki:RefToolbarMessages-de.js');
break;
fields[i].value = getTime();
default: // Turkish
return;
}
importScript('MediaWiki:RefToolbarMessages-tr.js');
}
}
*/
});
}


function getLastName(authornum) {
// Setup the main object
if (/\S/.test(document.getElementById('last'+authornum).value)) {
CiteTB.mainRefList = [];
return document.getElementById('last'+authornum).value;
CiteTB.refsLoaded = false;
}

else {
// REF FUNCTIONS
var author = document.getElementById('author'+authornum).value;
// Actually assemble a ref from user input
var match = /(\S+)\s*$/.exec(author);
CiteTB.getRef = function(inneronly, forinsert) {
if (match) {
var i;
return match[1];
var template = CiteTB.getOpenTemplate();
var templatename = template.templatename;
var res = '';
var refobj = {'shorttag':false};
if (!inneronly) {
var group = $('#cite-'+CiteTB.escStr(template.shortform)+'-group').val();
var refname = $('#cite-'+CiteTB.escStr(template.shortform)+'-name').val();
res += '<ref';
if (refname) {
refname = $.trim(refname);
res+=' name='+CiteTB.getQuotedString(refname);
refobj.refname = refname;
}
}
if (group) {
else {
group = $.trim(group);
return '';
res+=' group='+CiteTB.getQuotedString(group);
refobj.refgroup = group;
}
}
res+='>';
}
}
}
var content ='{{'+templatename;

for( g in template.incrementables ) {
function makeRefname() {
group = template.incrementables[g];
var refname;
for (i=1; i<=group.val; i++) {
if (document.getElementById('last1')) {
for (j=0; j<group.fields.length; j++) {
refname = document.getElementById('last1').value + document.getElementById('last2').value;
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);
}
}
}
}
}
else{
for( i=0; i<template.basic.length; i++ ) {
refname = document.getElementById('last').value;
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') {
if (/\S/.test(refname)) {
var date = document.getElementById('date').value;
for( i=0; i<template.extra.length; i++ ) {
var match = /[0-9]{4}/.exec(date);
if (template.extra[i].increment_group) {
continue;
if (match) {
}
refname += match[0];
var fieldname = template.extra[i].field;
var field = $('#cite-'+CiteTB.escStr(template.shortform)+'-'+fieldname).val();
if (field) {
content+='|'+fieldname+'=';
content+= $.trim(field);
}
}
}
}
}
else {
content+= '}}';
refname = document.getElementById('title').value;
res+=content;
refobj.content = content;
if (!inneronly) {
res+= '</ref>';
}
}
document.getElementById('refname').value = refname;
if (forinsert) {
}
CiteTB.mainRefList.push(refobj);
}
return res;
};


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


function citeNewsWeb(templatename) {
// Function to load the ref list
oldFormHide();
CiteTB.loadRefs = function() {
var template = templatename;
if (CiteTB.refsLoaded) {
return;
var legend;
if (template == "cite web") {
legend = "Cite web source";
} else {
legend = "Cite news source";
}
}
var newtime = getTime();
CiteTB.getPageText(CiteTB.loadRefsInternal);
numforms++;
};
var form = '<div id="citediv'+numforms+'">'+
'<fieldset><legend>'+legend+'</legend>'+
'<table cellspacing="5">'+
'<input type="hidden" value="'+template+'" id="template">'+
'<tr><td width="120"><label for="url">&nbsp;URL: </label></td>'+
'<td width="400"><input type="image" src="//upload.wikimedia.org/wikipedia/commons/6/62/Arrow_out_condensed.png" tabindex=1 alt="Fetch" title="' + ((template == 'cite news') ? 'For a New York Times article URL, fetch article data and fill in the fields. For other URLs, fetch the page title.' : 'Fetch the page title. Irrelevant parts often have to be removed manually afterwards.') + '" onClick="pullURL(); return false;" style="float:right"><span style="display: block;overflow: hidden;"><input type="text" tabindex=1 style="width:97%" id="url"></span></td>'+
'<td width="120"><label for="title">&nbsp;Title: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="title"></td></tr>'+
'<tr><td width="120"><label for="last">&nbsp;Last name: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="last"></td>'+
'<td width="120"><label for="first">&nbsp;First name: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="first"></td></tr>'+
'<tr><td width="120"><label for="coauthors">&nbsp;Coauthors: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="coauthors"></td>'+
'<td width="120"><label for="date">&nbsp;Publication date: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="date"></td></tr>'+
'<tr><td width="120"><label for="work">&nbsp;' + ((template == 'cite news') ? 'Newspaper' : 'Work') + ': </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="work"></td>'+
'<td width="120"><label for="publisher">&nbsp;Publisher: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="publisher"></td></tr>'+
'<tr><td width="120"><label for="pages">&nbsp;Pages: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="pages"></td>'+
'<td width="120"><label for="language">&nbsp;Language: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="language"></td></tr>'+
'<tr><td width="120"><label for="accessdate">&nbsp;Access date: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="accessdate" value="'+ newtime +'"></td>'+
'<td width="120"><label for="location">&nbsp;Location: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="location"></td></tr>';
if (template == 'cite web') {
form += '<tr><td width="120"><label for="archiveurl">&nbsp;Archive URL: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="archiveurl"></td>'+
'<td width="120"><label for="archivedate">&nbsp;Archive date: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="archivedate"></td></tr>';
}
form += '<tr><td width="120"><label for="refname">&nbsp;Reference name: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:60%" id="refname"><input type="button" value="<Last name" onClick="lastNameToRefname()"></td></tr>'+
'</table>'+
' <input type="button" value="Add citation" onClick="addcites()">'+
' <input type="button" value="Preview citation" onClick="previewCitationDefault()"> \
<img id="progress" src="//upload.wikimedia.org/wikipedia/commons/5/59/RefToolbar_spinning_throbber.gif" style="visibility: hidden" />'+
'<input type="checkbox" tabindex=1 name="verbose" id="verbose" value="verbose"><label for="verbose">Vertical form</label>'+
'<span style="float:right"><a href="//en.wikipedia.org/wiki/Template:'+template.replace(/ /g, '_')+'" target="_blank">[Template documentation]</a></span>'+
'</fieldset><span id="previewSpan"></span></div>';
document.getElementById('refToolFormArea').innerHTML = form;
}

function citeBook() {
oldFormHide();
var template = "cite book";
numforms++;
var form = '<div id="citediv'+numforms+'">'+
'<fieldset><legend>Cite book source</legend>';


form += '<table cellspacing="5" width="100%"> \
// Function that actually loads the list from the page text
<tr><td><label for="title">Title: </label></td> \
CiteTB.loadRefsInternal = function(text) {
<td colspan=5><input type="text" tabindex=1 style="width:100%" id="title"></td></tr>';
// What this does: extract first name/group extract second name/group shorttag inner content
for (var i=1;i<=3;i++) {
var refsregex = /< *ref(?: +(name|group) *= *(?:"([^"]*?)"|'([^']*?)'|([^ '"\/\>]*?)) *)? *(?: +(name|group) *= *(?:"([^"]*?)"|'([^']*?)'|([^ '"\/\>]*?)) *)? *(?:\/ *>|>((?:.|\n)*?)< *\/ *ref *>)/gim;
var i_str = i == 1 ? '': ' '+i;
// This should work regardless of the quoting used for names/groups and for linebreaks in the inner content
form += '<tr> \
while (true) {
<td width="130"><label for="last'+i+'">Author'+i_str+' last&nbsp;name: </label></td> \
var ref = refsregex.exec(text);
<td><input type="text" tabindex=1 style="width:100%" id="last'+i+'"></td> \
if (ref === null) {
<td><label for="first'+i+'">&nbsp;first&nbsp;name: </label></td> \
break;
<td><input type="text" tabindex=1 style="width:100%" id="first'+i+'"></td> \
}
<td><label for="authorlink'+i+'">&nbsp;Authorlink: </label></td> \
var refobj = {};
<td><input type="text" tabindex=1 style="width:100%" id="authorlink'+i+'"> \
if (ref[9]) { // Content + short tag check
<!--<a id="authorLinkAnchor'+i+'"><img id="authorLinkButton'+i+'" src="static/progress.gif" border="0" style="visibility: hidden" /></a> \
//alert('"'+ref[9]+'"');
<a href="//en.wikipedia.org/wiki/%s" target="_blank"><img id="authorTryLink'+i+'" src="static/external.png" border="0" style="visibility: hidden" /></a> --> \
refobj.content = ref[9];
</td> \
refobj.shorttag = false;
</tr>';
} 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);
}
}
form += '<tr><td><label for="coauthors">Coauthors: </label></td> \
CiteTB.refsLoaded = true;
<td><input type="text" tabindex=1 style="width:100%" id="coauthors"></td> \
CiteTB.setupErrorCheck();
<td><label for="editor">&nbsp;Editor: </label></td> \
CiteTB.setupNamedRefs();
<td><input type="text" tabindex=1 style="width:100%" id="editor"></td> \
};
<td><label for="others">&nbsp;Others: </label></td> \
<td><input type="text" tabindex=1 style="width:100%" id="others"></td></tr> \
</table> \
<table cellspacing="5" width="100%"> \
<tr><td width="130"><label for="publisher">Publisher: </label></td> \
<td><input type="text" tabindex=1 style="width:100%" id="publisher"></td> \
<td><label for="location">&nbsp;Location: </label></td> \
<td><input type="text" tabindex=1 style="width:100%" id="location"></td></tr> \
\
<tr><td><label for="date">Publication&nbsp;date or&nbsp;year: </label></td> \
<td><input type="text" tabindex=1 style="width:140px" id="date"> \
<input id="dmy" name="dateformat" value="dmy" type="radio" tabindex=1 onclick="reformatDates()"><label for="dmy">dmy</label> \
<input id="mdy" name="dateformat" value="mdy" type="radio" tabindex=1 onclick="reformatDates()"><label for="mdy">md, y</label> \
<input id="ymd" name="dateformat" value="ymd" type="radio" tabindex=1 onclick="reformatDates()"><label for="ymd">y-m-d</label> \
</td> \
<td><label for="edition">&nbsp;Edition: </label></td> \
<td><input type="text" tabindex=1 style="width:100%" id="edition"></td></tr> \
\
<tr><td><label for="series">Series: </label></td> \
<td><input type="text" tabindex=1 style="width:100%" id="series"></td> \
<td><label for="volume">&nbsp;Volume: </label></td> \
<td><input type="text" tabindex=1 style="width:100%" id="volume"></td></tr> \
\
<tr><td><label for="pages">Page number(s):</label></td> \
<td><input type="text" tabindex=1 style="width:100%" id="pages" name="pages" onFocus="this.style.backgroundColor=\'\';"></td> \
<td><label for="chapter">&nbsp;Chapter: </label></td> \
<td><input type="text" tabindex=1 style="width:100%" id="chapter"></td></tr> \
\
<tr><td><label for="isbn">ISBN: </label></td> \
<td><input type="image" src="//upload.wikimedia.org/wikipedia/commons/6/62/Arrow_out_condensed.png" tabindex=1 alt="Fetch" title="Fill in citation data based on ISBN from Diberri\'s tool." onClick="pullISBN(); return false;" style="float:right"><span style="display: block;overflow: hidden;"><input type="text" tabindex=1 style="width:97%" id="isbn"></span></td> \
<td><label for="language">&nbsp;Language: </label></td> \
<td><input type="text" tabindex=1 style="width:100%" id="language"></td></tr> \
\
<tr><td><label for="url">URL: </label></td> \
<td><input type="image" src="//upload.wikimedia.org/wikipedia/commons/6/62/Arrow_out_condensed.png" tabindex=1 alt="Fetch" title="Fill in citation data based on a Google Books URL." onClick="pullJs(); return false;" style="float:right"><span style="display: block;overflow: hidden;"><input type="text" tabindex=1 style="width:97%" id="url"></span></td> \
<td><label for="accessdate">&nbsp;Access&nbsp;date:</label></td> \
<td><input type="text" tabindex=1 style="width:100%" id="accessdate"></td></tr> \
\
<tr><td><label for="otherfields">Other&nbsp;fields:</label></td> \
<td><input type="text" tabindex=1 style="width:100%" id="otherfields"></td> \
<td><label for="refname">&nbsp;Ref&nbsp;name: </label></td> \
<td><input type="text" tabindex=1 style="width:100%" id="refname"></td> \
</tr> \
</table> \
\
<input type="radio" tabindex=1 name="template" id="cite_book" value="cite_book" checked="1"><label for="cite_book">\{\{cite book}}</label> <sup><a href="//en.wikipedia.org/wiki/Template:Cite_book" target="_blank">[doc]</a></sup> \
<input type="radio" tabindex=1 name="template" id="citation" value="citation"><label for="citation">\{\{citation}}</label> <sup><a href="//en.wikipedia.org/wiki/Template:Citation" target="_blank">[doc]</a></sup> \
<input type="radio" tabindex=1 name="template" id="plain" value="plain"><label for="plain">plain wikicode (experimental)</label> \
<input type="checkbox" tabindex=1 name="verbose" id="verbose" value="verbose"><label for="verbose">Vertical form</label> \
<input type="checkbox" tabindex=1 name="extraparams" id="extraparams" value="extraparams"><label for="extraparams">Extra parameters</label> \
<br /><input type="button" value="Add citation" onClick="makeCiteBook()"> \
<input type="button" value="Preview citation" onClick="previewCitationBook()"> \
<img id="progress" src="//upload.wikimedia.org/wikipedia/commons/5/59/RefToolbar_spinning_throbber.gif" style="visibility: hidden" /> \
\
</fieldset><span id="previewSpan"></span></div>';
document.getElementById('refToolFormArea').innerHTML = form;
}


function citeJournal() {
// AJAX FUNCTIONS
oldFormHide();
// Parse some wikitext and hand it off to a callback function
var template = "cite journal";
CiteTB.parse = function(text, callback) {
numforms++;
$.post( mw.util.wikiScript( 'api' ),
var form = '<div id="citediv'+numforms+'">'+
{action:'parse', title:mw.config.get('wgPageName'), text:text, prop:'text', format:'json'},
'<fieldset><legend>Cite journal</legend>'+
function(data) {
'<table cellspacing="5">'+
var html = data.parse.text['*'];
'<input type="hidden" value="'+template+'" id="template">'+
callback(html);
'<tr><td width="120"><label for="last">&nbsp;Last name: </label></td>'+
},
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="last"></td>'+
'json'
'<td width="120"><label for="first">&nbsp;First name: </label></td>'+
);
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="first"></td></tr>'+
};
'<tr><td width="120"><label for="coauthors">&nbsp;Coauthors: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="coauthors"></td>'+
'<td width="120"><label for="date">&nbsp;Publication date: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="date"></td></tr>'+
'<tr><td width="120"><label for="title">&nbsp;Title: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="title"></td>'+
'<td width="120"><label for="journal">&nbsp;Journal: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="journal"></td></tr>'+
'<tr><td width="120"><label for="publisher">&nbsp;Publisher: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="publisher"></td>'+
'<td width="120"><label for="location">&nbsp;Location: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="location"></td></tr>'+
'<tr><td width="120"><label for="volume">&nbsp;Volume: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="volume"></td>'+
'<td width="120"><label for="issue">&nbsp;Issue: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="issue"></td></tr>'+
'<tr><td width="120"><label for="pages">&nbsp;Pages: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="pages"></td>'+
'<td width="120"><label for="issn">&nbsp;ISSN: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="issn"></td></tr>'+
'<tr><td width="120"><label for="oclc">&nbsp;OCLC: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="oclc"></td>'+
'<td width="120"><label for="doi">&nbsp;DOI: </label></td>'+
'<td width="400"><input type="image" src="//upload.wikimedia.org/wikipedia/commons/6/62/Arrow_out_condensed.png" tabindex=1 alt="Fetch" title="Fetch citation data for a DOI from crossref.org and fill in the other fields." onClick="pullDOI(); return false;" style="float:right"><span style="display: block;overflow: hidden;"><input type="text" tabindex=1 style="width:97%" id="doi"></span></td></tr>'+
'<tr><td width="120"><label for="pmid">&nbsp;PMID: </label></td>'+
'<td width="400"><input type="image" src="//upload.wikimedia.org/wikipedia/commons/6/62/Arrow_out_condensed.png" tabindex=1 alt="Fetch" title="Fetch citation data for a PMID" onClick="pullPMID(); return false;" style="float:right;visibility:hidden"><span style="display: block;overflow: hidden;"><input type="text" tabindex=1 style="width:97%" id="pmid"></span></td>'+
'<td width="120"><label for="quote">&nbsp;Quote: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="quote"></td></tr>'+
'<tr><td width="120"><label for="url">&nbsp;URL: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="url"></td>'+
'<td width="120"><label for="accessdate">&nbsp;Access date: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="accessdate"></td></tr>'+
'<tr><td width="120"><label for="language">&nbsp;Language: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="language"></td>'+
'<td width="120"><label for="refname">&nbsp;Reference name: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:60%" id="refname"><input type="button" value="<Last name" onClick="lastNameToRefname()"></td></tr>'+
'</table>'+
'<input type="button" value="Add citation" onClick="addcites()">'+
' <input type="button" value="Preview citation" onClick="previewCitationDefault()"> \
<img id="progress" src="//upload.wikimedia.org/wikipedia/commons/5/59/RefToolbar_spinning_throbber.gif" style="visibility: hidden" />'+
'<input type="checkbox" tabindex=1 name="verbose" id="verbose" value="verbose"><label for="verbose">Vertical form</label>'+
'<span style="float:right"><a href="//en.wikipedia.org/wiki/Template:'+template.replace(/ /g, '_')+'" target="_blank">[Template documentation]</a></span>'+
'</fieldset><span id="previewSpan"></span></div>';
document.getElementById('refToolFormArea').innerHTML = form;
}


function citeEncyclopedia() {
// Use the API to expand templates on some text
oldFormHide();
CiteTB.expandtemplates = function(text, callback) {
var template = "cite encyclopedia";
$.post( mw.util.wikiScript( 'api' ),
numforms++;
{action:'expandtemplates', title:mw.config.get('wgPageName'), text:text, format:'json'},
var form = '<div id="citediv'+numforms+'">'+
function(data) {
'<fieldset><legend>Cite encyclopedia source</legend>'+
var restext = data.expandtemplates['*'];
'<table cellspacing="5">'+
callback(restext);
'<input type="hidden" value="'+template+'" id="template">'+
},
'<tr><td width="120"><label for="last">&nbsp;Last name: </label></td>'+
'json'
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="last"></td>'+
);
'<td width="120"><label for="first">&nbsp;First name: </label></td>'+
};
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="first"></td></tr>'+
'<tr><td width="120"><label for="coauthors">&nbsp;Coauthors: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="coauthors"></td>'+
'<td width="120"><label for="editors">&nbsp;Editors: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="editors"></td></tr>'+
'<tr><td width="120"><label for="title">&nbsp;Entry title: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="title"></td>'+
'<td width="120"><label for="encyclopedia">&nbsp;Encyclopedia: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="encyclopedia"></td></tr>'+
'<tr><td width="120"><label for="publisher">&nbsp;Publisher: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="publisher"></td>'+
'<td width="120"><label for="location">&nbsp;Location: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="location"></td></tr>'+
'<tr><td width="120"><label for="year">&nbsp;Year: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="year"></td>'+
'<td width="120"><label for="volume">&nbsp;Volume: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="volume"></td></tr>'+
'<tr><td width="120"><label for="pages">&nbsp;Pages: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="pages"></td>'+
'<td width="120"><label for="isbn">&nbsp;ISBN: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="isbn"></td></tr>'+
'<tr><td width="120"><label for="url">&nbsp;URL: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="url"></td>'+
'<td width="120"><label for="accessdate">&nbsp;Access date: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="accessdate"></td></tr>'+
'<tr><td width="120"><label for="language">&nbsp;Language: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="language"></td>'+
'<td width="120"><label for="refname">&nbsp;Reference name: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="refname"></td></tr>'+
'</table>'+
'<input type="button" value="Add citation" onClick="addcites()">'+
' <input type="button" value="Preview citation" onClick="previewCitationDefault()"> \
<img id="progress" src="//upload.wikimedia.org/wikipedia/commons/5/59/RefToolbar_spinning_throbber.gif" style="visibility: hidden" />'+
'<input type="checkbox" tabindex=1 name="verbose" id="verbose" value="verbose"><label for="verbose">Vertical form</label>'+
'<span style="float:right"><a href="//en.wikipedia.org/wiki/Template:'+template.replace(/ /g, '_')+'" target="_blank">[Template documentation]</a></span>'+
'</fieldset><span id="previewSpan"></span></div>';
document.getElementById('refToolFormArea').innerHTML = form;
}


function citePressRelease() {
// Function to get the page text
oldFormHide();
CiteTB.getPageText = function(callback) {
var section = $("input[name='wpSection']").val();
var template = "cite press release";
numforms++;
if ( section !== '' ) {
var form = '<div id="citediv'+numforms+'">'+
var postdata = {action:'query', prop:'revisions', rvprop:'content', pageids:mw.config.get('wgArticleId'), format:'json'};
'<fieldset><legend>Cite press release</legend>'+
if (CiteTB.getOption('expandtemplates')) {
'<table cellspacing="5">'+
postdata.rvexpandtemplates = '1';
'<input type="hidden" value="'+template+'" id="template">'+
'<tr><td width="120"><label for="title">&nbsp;Title: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="title"></td>'+
'<td width="120"><label for="publisher">&nbsp;Publisher: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="publisher"></td></tr>'+
'<tr><td width="120"><label for="date">&nbsp;Date: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="date"></td>'+
'<td width="120"><label for="language">&nbsp;Language: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="language"></td></tr>'+
'<tr><td width="120"><label for="url">&nbsp;URL: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="url"></td>'+
'<td width="120"><label for="accessdate">&nbsp;Access date: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="accessdate" value="'+ getTime() +'"></td></tr>'+
'<tr><td width="120"><label for="refname">&nbsp;Reference name: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="refname"></td></tr>'+
'</table>'+
'<input type="button" value="Add citation" onClick="addcites()">'+
' <input type="button" value="Preview citation" onClick="previewCitationDefault()"> \
<img id="progress" src="//upload.wikimedia.org/wikipedia/commons/5/59/RefToolbar_spinning_throbber.gif" style="visibility: hidden" />'+
'<input type="checkbox" tabindex=1 name="verbose" id="verbose" value="verbose"><label for="verbose">Vertical form</label>'+
'<span style="float:right"><a href="//en.wikipedia.org/wiki/Template:'+template.replace(/ /g, '_')+'" target="_blank">[Template documentation]</a></span>'+
'</fieldset><span id="previewSpan"></span></div>';
document.getElementById('refToolFormArea').innerHTML = form;
}

function citeMap() {
oldFormHide();
var template = "cite map";
numforms++;
var form = '<div id="citediv'+numforms+'">'+
'<fieldset><legend>Cite map</legend>'+
'<table cellspacing="5">'+
'<input type="hidden" value="'+template+'" id="template">'+
'<tr><td width="120"><label for="publisher">&nbsp;Publisher: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="publisher"></td>'+
'<td width="120"><label for="title">&nbsp;Title: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="title"></td></tr>'+
'<tr><td width="120"><label for="url">&nbsp;URL: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="url"></td>'+
'<td width="120"><label for="accessdate">&nbsp;Access date: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="accessdate"></td></tr>'+
'<tr><td width="120"><label for="edition">&nbsp;Edition: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="edition"></td>'+
'<td width="120"><label for="date">&nbsp;Date or year: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="date"></td></tr>'+
'<tr><td width="120"><label for="cartography">&nbsp;Cartography: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="cartography"></td>'+
'<td width="120"><label for="scale">&nbsp;Scale: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="scale"></td></tr>'+
'<tr><td width="120"><label for="series">&nbsp;Series: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="series"></td>'+
'<td width="120"><label for="page">&nbsp;Page: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="page"></td></tr>'+
'<tr><td width="120"><label for="section">&nbsp;Section: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="section"></td>'+
'<td width="120"><label for="inset">&nbsp;Inset: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="inset"></td></tr>'+
'<tr><td width="120"><label for="isbn">&nbsp;ISBN: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="isbn"></td>'+
'<td width="120"><label for="refname">&nbsp;Reference name: </label></td>'+
'<td width="400"><input type="text" tabindex=1 style="width:100%" id="refname"></td></tr>'+
'</table>'+
'<input type="button" value="Add citation" onClick="addcites()">'+
' <input type="button" value="Preview citation" onClick="previewCitationDefault()"> \
<img id="progress" src="//upload.wikimedia.org/wikipedia/commons/5/59/RefToolbar_spinning_throbber.gif" style="visibility: hidden" />'+
'<input type="checkbox" tabindex=1 name="verbose" id="verbose" value="verbose"><label for="verbose">Vertical form</label>'+
'<span style="float:right"><a href="//en.wikipedia.org/wiki/Template:'+template.replace(/ /g, '_')+'" target="_blank">[Template documentation]</a></span>'+
'</fieldset><span id="previewSpan"></span></div>';
document.getElementById('refToolFormArea').innerHTML = form;
}

function showRefSectionOptions() {
oldFormHide();
var template = "cite encyclopedia";
numforms++;
var form = '<div id="citediv'+numforms+'">'+
'<fieldset><legend>Add references section</legend>\
Headline:<br />\
<input id="references" name="headline" type="radio" tabindex=1 checked="checked"><label for="references">== References ==</label><br /> \
<input id="notes" name="headline" type="radio" tabindex=1><label for="notes">== Notes ==</label><br /> \
Type:<br /> \
<input id="type-references" name="type" type="radio" tabindex=1><label for="type-references">&lt;references/&gt;</label><br /> \
<input id="type-reflist" name="type" type="radio" tabindex=1 checked="checked"><label for="type-reflist">\{\{Reflist}}</label><br /> \
<input id="type-reflist2" name="type" type="radio" tabindex=1><label for="type-reflist2">\{\{Reflist|2}}</label><br /> \
<input type="checkbox" tabindex=1 id="ldr"><label for="ldr">List-defined references</label> (<a href="//en.wikipedia.org/wiki/Wikipedia:Footnotes#List-defined_references" target="_blank">Info 1</a>, <a href="//en.wikipedia.org/wiki/Help:Footnotes#List-defined_references" target="_blank">Info 2</a>)<br />\
<input type="button" value="Add references section" onClick="addRefSection()">'+
'</fieldset></div>';
document.getElementById('citeselect').innerHTML += form;
}

function makeCiteCode() {
cites = document.getElementById('citediv'+numforms).getElementsByTagName('input');
var template = '';
var citebegin = '<ref';
var citename = '';
var citeinner = '';
for (var i=0; i<cites.length; i++) {
var citeid = cites[i].id;
var citevalue = cites[i].value;
citevalue = citevalue.trim(); //Trim leading and trailing whitespace
if (citeid == "verbose") {
if (cites[i].checked) {
citeinner = citeinner.replace(/\|/g, "\n|");
}
}
}
else if (citevalue !== '' && cites[i].type !== 'button' && cites[i].type !== 'image') {
$.get( mw.util.wikiScript( 'api' ),
if (citeid === "refname") {
postdata,
citebegin += ' name="' + citevalue + '"';
function(data) {
}
var pagetext = data.query.pages[mw.config.get('wgArticleId').toString()].revisions[0]['*'];
callback(pagetext);
else if (citeid == "template") {
citename = '>\{\{' + citevalue;
},
'json'
template = citevalue;
);
}
} else {
else {
if (CiteTB.getOption('expandtemplates')) {
if (citeid === "pages") {
if (citevalue.match(/^\w+$/) && template != 'cite encyclopedia') {
CiteTB.expandtemplates($('#wpTextbox1').wikiEditor('getContents').text(), callback);
citeid = "page"; //Use page= instead of pages= if only one page. Makes p. 5 instead of pp. 5.
} else {
}
callback($('#wpTextbox1').wikiEditor('getContents').text());
else {
citevalue = citevalue.replace(/-/g, "–"); //Replace hyphens with en dashes [[WP:ENDASH]]
}
}
else if (citeid == "date" && citevalue.match(/^\d\d\d\d$/)) {
citeid = "year"; // Use year= instead of date= if only the year is specified
}
citeinner += "|" + citeid + "=" + citevalue;
}
}
}
}
}
cite = citebegin + citename + citeinner + "}}</ref>";
};
return cite;
}


function addcites(template) {
// Autofill a template from an ID (ISBN, DOI, PMID)
var cite = makeCiteCode();
CiteTB.initAutofill = function() {
var elemid = $(this).attr('id');
$("#wpTextbox1").focus();
insertTags(cite, '', '');
var res = /^cite\-auto\-(.*?)\-(.*)\-(.*)$/.exec(elemid);
//document.getElementById('citediv'+numforms).style.display = 'none';
var tem = res[1];
oldFormHide();
var field = res[2];
}
var autotype = res[3];
var id = $('#cite-'+tem+'-'+field).val();
if (!id) {
return false;
}
var url = '//tools.wmflabs.org/reftoolbar/lookup.php?';
url+=autotype+'='+encodeURIComponent(id);
url+='&template='+encodeURIComponent(tem);
var s = document.createElement('script');
s.setAttribute('src', url);
s.setAttribute('type', 'text/javascript');
document.getElementsByTagName('head')[0].appendChild(s);
return false;
};


function addRefSection() {
// Callback for autofill
var wikicode = "\n";
//TODO: Autofill the URL, at least for DOI
if (document.getElementById('references').checked) {
CiteTB.autoFill = function(data, template, type) {
wikicode += "== References ==\n";
var cl = 'cite-'+template+'-';
}
var i,j, coauthors;
else if (document.getElementById('notes').checked) {
$('.'+cl+'title').val(data.title);
wikicode += "== Notes ==\n";
if ($('.'+cl+'last-incr-1').length != 0) {
}
var classes = $('.'+cl+'last-incr-1').eq(0).attr('class').split(/\s+/);
else {alert('No headline selected!');}
var group = false;
var patt = /cite-[^-]*?-incr-(.*)/
if (document.getElementById('type-references').checked) {
for (var c=0; c<classes.length; c++) {
if (patt.exec(classes[c])) {
if (document.getElementById('ldr').checked) {
wikicode += "<references>\n\n</references>\n";
group = patt.exec(classes[c])[1];
}
break;
else {
}
wikicode += "<references/>\n";
}
$('.'+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 (document.getElementById('type-reflist').checked || document.getElementById('type-reflist2').checked) {
} else if($('.'+cl+'author1').length !== 0) {
var col2 = document.getElementById('type-reflist2').checked ? '|2' : '' ;
for(i=0; data.authors && i<data.authors.length; i++) {
if (document.getElementById('ldr').checked) {
if ($('.'+cl+'author'+(i+1)).length) {
wikicode += "\{\{Reflist" + col2 + "|refs=\n\n}}\n";
$('.'+cl+'author'+(i+1)).val(data.authors[i].join(', '));
}
} else {
else {
coauthors = [];
wikicode += "\{\{Reflist" + col2 + "}}\n";
for(j=i; j<data.authors.length; j++) {
coauthors.push(data.authors[j].join(', '));
}
}
$('.'+cl+'coauthors').val(coauthors.join('; '));
break;
}
}
}
else {alert('No type selected!');}
$("#wpTextbox1").focus();
insertTags(wikicode, '', '');
document.getElementById('citediv'+numforms).innerHTML = '';
}

function getNamedRefs(calls) {
if (typeof(wikEdUseWikEd) != 'undefined') {
if (wikEdUseWikEd == true) {
WikEdUpdateTextarea();
}
}
text = document.getElementById('wpTextbox1').value;
var regex;
if (calls) {
regex = /< *?ref +?name *?= *?(('([^']*?)')|("([^"]*?)")|([^'"\s]*?[^\/]\b)) *?\/ *?>/gi //'
} else {
} else {
regex = /< *?ref +?name *?= *?(('([^']*?)')|("([^"]*?)")|([^'"\s]*?[^\/]\b)) *?>/gi //'
var authors = [];
for(i=0; data.authors && i<data.authors.length; i++) {
authors.push(data.authors[i].join(', '));
}
$('.'+cl+'authors').val(authors.join('; '));
}
}
var namedrefs = new Array();
if (type === 'pmid' || type === 'doi') {
var i=0;
if (data.fulldate || !$('.'+cl+'month').length) {
var DT = new Date(data.date);
var nr=true;
do {
var useday = /\d{4}-\d{2}-\d{2}/.test(data.date);
var usemonth = /\d{4}-\d{2}/.test(data.date);
ref = regex.exec(text);
if(ref != null){
$('.'+cl+'date').val(CiteTB.formatDate(DT, useday, usemonth));
if (ref[5]) {
} else if (!data.fulldate && $('.'+cl+'month').length && $('.'+cl+'year').length) {
namedrefs[i] = ref[5];
if (data.month) { // lookup.php sets month to false if it isn't provided
} else if (ref[3]) {
$('.'+cl+'month').val( CiteTB.getOption('months')[parseInt(data.month)-1] );
namedrefs[i] = ref[3];
} else {
namedrefs[i] = ref[6];
}
}
$('.'+cl+'year').val(data.year);
i++;
} else {
} else {
nr=false;
$('.'+cl+'date').val(data.date);
}
}
} while (nr==true);
$('.'+cl+'journal').val(data.journal);
return namedrefs;
$('.'+cl+'volume').val(data.volume);
}
$('.'+cl+'issue').val(data.issue);

$('.'+cl+'pages').val(data.pages);
function citeNamedRef() {
} else if (type === 'isbn') {
var namedrefs = getNamedRefs(false);
$('.'+cl+'publisher').val(data.publisher);
if (namedrefs == '') {
$('.'+cl+'location').val(data.location);
oldFormHide();
$('.'+cl+'year').val(data.year);
numforms++;
$('.'+cl+'edition').val(data.edition);
var out = '<div id="citediv'+numforms+'"><fieldset>'+
'<legend>References in text</legend>There are no named refs (<tt>&lt;ref name="Name"&gt;</tt>) in the text</fieldset></div>';
document.getElementById('citeselect').innerHTML += out;
}
}
else {
};
oldFormHide();
numforms++;
var form = '<div id="citediv'+numforms+'">'+
'<fieldset><legend>References in article</legend>'+
'<table cellspacing="5">'+
'<tr><td><label for="namedrefs">&nbsp;Named references in text</label></td>'+
'<td><select name="namedrefs" id="namedrefs">';
for (var i=0;i<namedrefs.length;i++) {
form+= '<option value="'+namedrefs[i]+'">'+namedrefs[i]+'</option>';
}
form+= '</select>'+
'</td></tr></table>'+
'<input type="button" value="Add citation" onClick="addnamedcite()">'+
'</fieldset></div>';
document.getElementById('citeselect').innerHTML += form;
}
}


function addnamedcite() {
// FORM DIALOG FUNCTIONS
var name = document.getElementById('citediv'+numforms).getElementsByTagName('select')[0].value;
// Add new incrementable fields
var ref = '<ref name="'+name+'" />';
CiteTB.incrementFields = function() {
$("#wpTextbox1").focus();
template = CiteTB.getOpenTemplate();
insertTags(ref, '', '');
var currentrow = $(this).parents('tr')[0];
document.getElementById('citediv'+numforms).style.display = 'none';
$(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]);
}
};


function getAllRefs() {
// fill the accessdate param with the current date
if (typeof(wikEdUseWikEd) != 'undefined') {
CiteTB.fillAccessdate = function() {
if (wikEdUseWikEd == true) {
var elemid = $(this).attr('id');
WikEdUpdateTextarea();
var res = /^cite\-date\-(.*?)\-(.*)$/.exec(elemid);
var id = res[1];
}
}
var field = res[2];
var DT = new Date();
var text = document.getElementById('wpTextbox1').value;
var regex = /< *?ref( +?name *?= *?(('([^']*?)')|("([^"]*?)")|([^'"\s]*?[^\/]\b)))? *?>((.|\n)*?)< *?\/? *?ref *?>/gim //"
var datestr = CiteTB.formatDate(DT);
var allrefs = new Array();
$('#cite-'+id+'-'+field).val(datestr);
var i=0;
var nr=true;
do {
ref = regex.exec(text);
if(ref != null){
if (ref[0].search(/[^\s]{150}/) != -1) {
ref[0] = ref[0].replace(/\|([^\s])/g, "| $1");
}
ref[0] = ref[0].replace(/</g, "&lt;");
ref[0] = ref[0].replace(/>/g, "&gt;");
allrefs[i] = ref[0];
i++;
} else {
nr=false;
}
} while (nr==true);
return allrefs;
}

function NRcallError(namedrefs, refname) {
for (var i=0; i<namedrefs.length; i++) {
if (namedrefs[i] == refname) {
return true;
}
}
return false;
return false;
};
}


function errorCheck() {
CiteTB.formatDate = function(DT, useday, usemonth) {
var allrefs = getAllRefs();
if (typeof useday == "undefined") {
var allrefscontent = new Array();
useday = true;
var samecontentexclude = new Array();
var sx=0;
var templateexclude = new Array();
var tx=0;
var skipcheck = false;
var namedrefcalls = getNamedRefs(true);
for (var i=0; i<allrefs.length; i++) {
allrefscontent[i] = allrefs[i].replace(/&lt; *?ref( +?name *?= *?(('([^']*?)')|("([^"]*?)")|([^'"\s]*?[^\/]\b)))? *?&gt;((.|\n)*?)&lt; *?\/? *?ref *?&gt;/gim, "$8"); //"
}
}
var namedrefs = getNamedRefs(false);
if (typeof usemonth == "undefined") {
usemonth = true;
var errorlist = new Array();
var q=0;
var unclosed = document.getElementById('unclosed').checked;
var samecontent = document.getElementById('samecontent').checked;
var templates = document.getElementById('templates').checked;
var repeated = document.getElementById('repeated').checked;
var undef = document.getElementById('undef').checked;
for (var i=0; i<allrefs.length; i++) {
if (allrefs[i].search(/&lt; *?\/ *?ref *?&gt;/) == -1 && unclosed) {
errorlist[q] = '<tr><td width="75%"><tt>'+allrefs[i]+'</tt></td>';
errorlist[q] += '<td width="25%">Unclosed <tt>&lt;ref&gt;</tt> tag</td></tr>';
q++;
}
if (samecontent) {
for (var d=0; d<samecontentexclude.length; d++) {
if (allrefscontent[i] == samecontentexclude[d]) {
skipcheck = true;
}
}
var p=0;
while (p<allrefs.length && !skipcheck) {
if (allrefscontent[i] == allrefscontent[p] && i != p) {
errorlist[q] = '<tr><td width="75%"><tt>'+allrefscontent[i]+'</tt></td>';
errorlist[q] += '<td width="25%">Multiple refs contain this content, a <a href="//en.wikipedia.org/wiki/Wikipedia:Footnotes#Naming_a_ref_tag_so_it_can_be_used_more_than_once">named reference</a> should be used instead</td></tr>';
q++;
samecontentexclude[sx] = allrefscontent[i]
sx++;
break;
}
p++;
}
skipcheck=false;
}
if (templates) {
if (allrefscontent[i].search(/\{\{cite/i) == -1 && allrefscontent[i].search(/\{\{citation/i) == -1 && allrefscontent[i].search(/\{\{Comic (book|strip) reference/i) == -1 && allrefscontent[i].search(/\{\{Editorial cartoon reference/i) == -1 && allrefscontent[i].search(/\{\{harv/i) == -1) {
for (var x=0; x<templateexclude.length; x++) {
if (allrefscontent[i] == templateexclude[x]) {
skipcheck = true;
}
}
if (!skipcheck) {
errorlist[q] = '<tr><td width="75%"><tt>'+allrefs[i]+'</tt></td>';
errorlist[q] += '<td width="25%">Does not use a <a href="//en.wikipedia.org/wiki/Wikipedia:Citation_templates">citation template</a></td></tr>';
q++;
templateexclude[tx] = allrefscontent[i];
tx++;
}
skipcheck = false;
}
}
}
}
if (repeated) {
var datestr = CiteTB.getOption('date format');
var zmonth = '';
var repeatnameexclude = new Array();
var rx=0;
var month = DT.getUTCMonth()+1;
if (month < 10) {
for (var k=0; k<namedrefs.length; k++) {
for (var d=0; d<repeatnameexclude.length; d++) {
zmonth = "0"+month.toString();
if (namedrefs[k] == repeatnameexclude[d]) {
} else {
zmonth = month.toString();
skipcheck = true;
}
}
var z=0;
while (z<namedrefs.length && !skipcheck) {
if (namedrefs[k] == namedrefs[z] && k != z) {
errorlist[q] = '<tr><td width="75%"><tt>'+namedrefs[k]+'</tt></td>';
errorlist[q] += '<td width="25%">Multiple references are given the same <a href="//en.wikipedia.org/wiki/Wikipedia:Footnotes#Naming_a_ref_tag_so_it_can_be_used_more_than_once">name</a></td></tr>';
q++;
repeatnameexclude[rx] = namedrefs[z];
rx++;
break;
}
z++;
}
skipcheck = false;
}
}
}
if (undef) {
month = month.toString();
var zdate = '';
var undefexclude = new Array();
var ux=0;
var date = DT.getUTCDate();
if (date < 10) {
for (var p=0; p<namedrefcalls.length; p++) {
for (var d=0; d<undefexclude.length; d++) {
zdate = "0"+date.toString();
if (allrefscontent[i] == undefexclude[d]) {
skipcheck = true;
}
}
if (!skipcheck) {
if (!NRcallError(namedrefs, namedrefcalls[p])) {
errorlist[q] = '<tr><td width="75%"><tt>'+namedrefcalls[p]+'</tt></td>';
errorlist[q] += '<td width="25%">A <a href="//en.wikipedia.org/wiki/Wikipedia:Footnotes#Naming_a_ref_tag_so_it_can_be_used_more_than_once">named reference</a> is used but not defined</td></tr>';
q++;
undefexclude[ux] = namedrefs[p];
ux++;
}
}
skipcheck = false;
}
}
if (q > 0) {
return errorlist;
} else {
} else {
zdate = date.toString();
return 0;
}
}
}
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 dispErrors() {
// Function called after the ref list is loaded, to actually set the contents of the named ref dialog
oldFormHide();
// Until the list is loaded, its just a "Loading" placeholder
var form = '<div id="errorform"><fieldset>'+
CiteTB.setupNamedRefs = function() {
'<legend>Error checking</legend>'+
var names = [], i;
'<b>Check for:</b><br/>'+
for( i=0; i<CiteTB.mainRefList.length; i++) {
'<input type="checkbox" id="unclosed" /> Unclosed <tt>&lt;ref&gt;</tt> tags<br/>'+
if (!CiteTB.mainRefList[i].shorttag && CiteTB.mainRefList[i].refname) {
'<input type="checkbox" id="samecontent" /> References with the same content<br/>'+
names.push(CiteTB.mainRefList[i]);
'<input type="checkbox" id="templates" /> References not using a <a href="//en.wikipedia.org/wiki/Wikipedia:Citation_templates">citation template</a><br/>'+
'<input type="checkbox" id="repeated" /> Multiple references with the same name<br/>'+
'<input type="checkbox" id="undef" /> Usage of undefined named references<br/>'+
'<input type="button" id="errorchecksubmit" value="Check for selected errors" onclick="doErrorCheck()"/>'+
'</fieldset></div>';
document.getElementById('citeselect').innerHTML += form;
}

function doErrorCheck() {
var errors = errorCheck();
document.getElementById('citeselect').removeChild(document.getElementById('errorform'));
if (errors == 0) {
if (numforms != 0) {
document.getElementById('citediv'+numforms).style.display = 'none';
}
}
numforms++;
out = '<div id="citediv'+numforms+'"><fieldset>'+
'<legend>Error checking</legend>No errors found.</fieldset></div>';
document.getElementById('citeselect').innerHTML += out;
}
}
else {
var stuff = $('<div>');
if (numforms != 0) {
$('#citetoolbar-namedrefs').html( stuff );
document.getElementById('citediv'+numforms).style.display = 'none';
if (names.length === 0) {
stuff.html(mw.usability.getMsg('cite-no-namedrefs'));
} else {
stuff.html(mw.usability.getMsg('cite-namedrefs-intro'));
var select = $('<select id="cite-namedref-select">');
select.append($('<option value="" />').text(mw.usability.getMsg('cite-named-refs-dropdown')));
for(i=0; i<names.length; i++) {
select.append($('<option />').text(names[i].refname));
}
}
stuff.after(select);
numforms++;
form = '<div id="citediv'+numforms+'">'+
select.before('<br />');
'<fieldset><legend>Error checking</legend>'+
var prevlabel = $('<div id="cite-nref-preview-label" style="display:none;" />').html(mw.usability.getMsg('cite-raw-preview'));
'<table border="1px">';
select.after(prevlabel);
for (var i=0; i<errors.length; i++) {
prevlabel.before("<br /><br />");
form+=errors[i];
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'));
form+= '</table>'+
$('#cite-namedref-preview').after(parselabel);
'</fieldset></div>';
parselabel.after('<div id="cite-namedref-parsed" style="padding-bottom:0.5em; font-size:110%" />');
document.getElementById('citeselect').innerHTML += form;
var link = $('<a href="#" id="cite-nref-parse" style="margin:0 1em 0 1em; display:none; color:darkblue" />');
link.html(mw.usability.getMsg('cite-form-parse'));
$('#cite-namedref-parsed').after(link);
$("#cite-namedref-select").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.usability.getMsg('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);
};


function makeBookCitationCode(callback) {
// Callback function for parsed preview
var cite = '<ref';
CiteTB.fillNrefPreview = function(parsed) {
var refname = document.getElementById('refname').value;
$('#cite-parsed-label').show();
if (/\S/.test(refname)) {
$('#cite-namedref-parsed').html(parsed);
cite += ' name="' + refname + '"';
};

// 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();
cite += '>\{\{';
for( var i=0; i<CiteTB.mainRefList.length; i++) {
if (document.getElementById('cite_book').checked || document.getElementById('plain').checked) {
if (!CiteTB.mainRefList[i].shorttag && CiteTB.mainRefList[i].refname == choice) {
cite += 'cite book';
CiteTB.parse(CiteTB.mainRefList[i].content, CiteTB.fillNrefPreview);
}
return false;
else if (document.getElementById('citation').checked) {
cite += 'citation';
}
else {alert('No template selected.');}
var authorcite = '';
var prevauthor = 0;
for (var i=3;i>=1;i--) {
//var author = document.getElementById('author' + i).value;
var last = document.getElementById('last' + i).value;
var first = document.getElementById('first' + i).value;
var authorlink = document.getElementById('authorlink' + i).value;
if (i==1 && !prevauthor) { i = ''; }
if (/\S/.test(authorlink)) {
authorcite = '|authorlink' + i + '=' + authorlink + authorcite;
}
}
if (/\S/.test(last)) {
}
authorcite = '|last' + i + '=' + last + '|first' + i + '=' + first + authorcite;
};
prevauthor = 1;
}
/*else if (/\S/.test(author)) {
authorcite = '|author' + i + '=' + author + authorcite;
prevauthor = 1;
}*/
}
cite += authorcite;


var simplefields = ["coauthors", "editor", "others", "title", "url", "accessdate","edition","series","volume","date","publisher","location","language","isbn","pages","chapter"];
// Click handler for the named-ref dropdown
for (var i=0;i<simplefields.length;i++) {
CiteTB.lastnamedrefchoice = '';
var fieldname = simplefields[i];
CiteTB.namedRefSelectClick = function() {
var value = document.getElementById(fieldname).value;
var choice = $("#cite-namedref-select").val();
if (CiteTB.lastnamedrefchoice == choice) {
if (/\S/.test(value) || fieldname == "title") {
if (fieldname == "pages") {
return;
if (/^\w+$/.test(value)) {
fieldname = "page"; //Use page= instead of pages= if only one page. Makes p. 5 instead of pp. 5.
}
else {
value = value.replace(/-/g, "–"); //Replace hyphens with en dashes [[WP:ENDASH]]
value = value.replace(/,\s*\s?/g, ", "); //One space after each comma
}
}
else if (fieldname == "date" && /^\d\d\d\d$/.test(value)) {
fieldname = "year"; // Use year= instead of date= if only the year is specified
}
cite += '|' + fieldname + '=' + value;
}
}
}
CiteTB.lastnamedrefchoice = choice;

$('#cite-parsed-label').hide();
var otherfields = document.getElementById('otherfields').value;
$('#cite-namedref-parsed').text('');
if (choice === '') {
if (/\S/.test(otherfields)) {
$('#cite-nref-preview-label').hide();
cite += '|' + otherfields;
$('#cite-namedref-preview').text('');
$('#cite-nref-parse').hide();
return;
}
}
for( var i=0; i<CiteTB.mainRefList.length; i++) {
if (document.getElementById('extraparams').checked) {
if (!CiteTB.mainRefList[i].shorttag && CiteTB.mainRefList[i].refname == choice) {
cite += '|authormask=';
$('#cite-nref-preview-label').show();
if (!document.getElementById('citation').checked) {
$('#cite-namedref-preview').text(CiteTB.mainRefList[i].content);
cite += '|trans_title=';
if (CiteTB.getOption('autoparse')) {
}
CiteTB.nrefParseClick();
} else {
cite += '|format=';
$('#cite-nref-parse').show();
cite += '|origyear=';
cite += '|oclc=';
cite += '|doi=';
cite += '|bibcode=';
cite += '|id=';
if (/\S/.test(document.getElementById('chapter').value)) {
if (!document.getElementById('citation').checked) {
cite += '|trans_chapter=';
}
cite += '|chapterurl=';
}
cite += '|quote=';
cite += '|laysummary=';
cite += '|laydate=';
}

cite += "}}</ref>";
if (document.getElementById('plain').checked) {
var match = /^(.*?)(\{\{.*}})(.*?)$/.exec(cite);
if (match) {
var citebeg = match[1];
var citemid = match[2];
var citeend = match[3];
citemid = citemid.replace(/cite book/, "Vancite book");
//alert(citebeg + ':::' + citemid + ':::' + citeend);
//document.getElementById('fullcite').value = 'Updating...';
var url = 'api.php?action=expandtemplates&format=xml&text=' + encodeURIComponent(citemid);
document.getElementById('progress').style.visibility = "visible";
var xmlhttpExpand = new XMLHttpRequest();
xmlhttpExpand.onreadystatechange=function() {
if(xmlhttpExpand.readyState==4) {
if(xmlhttpExpand.status==200) {
document.getElementById('progress').style.visibility = "hidden";
var xmlDoc=xmlhttpExpand.responseXML.documentElement;
var expanded = xmlDoc.getElementsByTagName("expandtemplates")[0].textContent;
if (expanded == undefined) {
expanded = xmlDoc.getElementsByTagName("expandtemplates")[0].childNodes[0].nodeValue;
}
expanded = expanded.replace(/<span.*?>/ig, '');
expanded = expanded.replace(/<\/span>/ig, '');
expanded = expanded.replace(/<nowiki\/?>/ig, '');
expanded = expanded.replace(/\&\#32\;/ig, ' ');
expanded = expanded.replace(/\&\#59\;/ig, ';');
expanded = expanded.replace(/\&\#91\;/ig, '[');
expanded = expanded.replace(/\&\#93\;/ig, ']');
plaincite = citebeg + expanded + citeend;
//alert(plaincite);
callback(plaincite);
}
else
alert('The query returned an error.');
}
}
}
xmlhttpExpand.open("GET",url,true);
xmlhttpExpand.send(null);
}
}
else {alert('Error A1');}
}
}
else {
};
if (document.getElementById('verbose').checked) {
cite = cite.replace(/\|/g, "\n|");
}
callback(cite);
}
}


// callback function for parsed preview
function makeCiteBook() {
CiteTB.fillTemplatePreview = function(text) {
makeBookCitationCode(function(cite) {
$("#wpTextbox1").focus();
var template = CiteTB.getOpenTemplate();
insertTags(cite, '', '');
var div = $("#citetoolbar-"+CiteTB.escStr(template.shortform));
if (!refToolDebug) { oldFormHide(); }
div.find('.cite-prev-parsed-label').show();
});
div.find('.cite-preview-parsed').html(text);
};
}


function formatDate(datein, dateformat) {
// Click handler for template parsed preview
if (dateformat == '') {return (datein);}
CiteTB.prevParseClick = function() {
datein = datein.replace(/^\s*(.*?)\s*$/, "$1"); //Trim whitespace
var ref = CiteTB.getRef(true, false);
var template = CiteTB.getOpenTemplate();
var year = -1;
var month = -1;
var div = $("#citetoolbar-"+CiteTB.escStr(template.shortform));
var date = -1;
div.find('.cite-prev-parse').hide();
var match = /^(\d\d\d\d)-(\d\d?)(-(\d\d?))?$/.exec(datein);
CiteTB.parse(ref, CiteTB.fillTemplatePreview);
if(match) {
};
//alert(' match[1]=' + match[1] + ' match[2]=#' + match[2] + '# match[3]=' + match[3] + ' match[4]=' + match[4] );
year = parseInt(match[1], 10); //10 forces decimal conversion
month = parseInt(match[2], 10);
if (match[4]) {
date = parseInt(match[4], 10);
}
}
else if (/^\d\d? \w+ \d\d\d\d$/.test(datein) || /^\w+ \d\d?, \d\d\d\d$/.test(datein)) {
var DT = new Date(datein);
year = DT.getUTCFullYear();
month = DT.getUTCMonth()+1;
date = DT.getUTCDate()+1;
}
else if (datein == 'today') {
var DT = new Date();
year = DT.getUTCFullYear();
month = DT.getUTCMonth()+1;
date = DT.getUTCDate();
}
else {return (datein);}
//alert('datein=' + datein + ', y=' + year + ', m=' + month + ', d=' + date);


var zmonth = '';
// Show/hide the extra fields in the dialog box
if (month < 10) {
CiteTB.showHideExtra = function() {
var template = CiteTB.getOpenTemplate();
zmonth = "0"+month.toString();
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 {
} else {
zmonth = month.toString();
div.find(".cite-form-status").val('closed');
}
div.find('.cite-extra-fields').hide();
month = month.toString();
}
var zdate = '';
};
if (date > -1) {
if (date < 10) {
zdate = "0"+date.toString();
} else {
zdate = date.toString();
}
date = date.toString()
}
else { date = ''; }
var datestr = dateformat;
datestr = datestr.replace('<date>', date);
datestr = datestr.replace('<month>', month);
datestr = datestr.replace('<zdate>', zdate);
datestr = datestr.replace('<zmonth>', zmonth);
datestr = datestr.replace('<monthname>', months[month-1]);
datestr = datestr.replace('<year>', year.toString());
datestr = datestr.replace(/\s+/, ' ').replace(/^\s+/, '').replace(/(\D),/, '$1').replace(/-$/, '');
return (datestr);
}


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


function getDateFormat() {
// STRING UTILITY FUNCTIONS
var dateformat = '';
// Returns a string quoted as necessary for name/group attributes
if (document.getElementById('dmy')){
CiteTB.getQuotedString = function(s) {
if (document.getElementById('dmy').checked) {dateformat = '<date> <monthname> <year>'}
var sp = /\s/.test(s); // spaces
else if (document.getElementById('mdy').checked) {dateformat = '<monthname> <date>, <year>'}
var sq = /\'/.test(s); // single quotes
else if (document.getElementById('ymd').checked) {dateformat = '<year>-<zmonth>-<zdate>'}
var dq = /\"/.test(s); // double quotes
}
if (!sp && !sq && !dq) { // No quotes necessary
else if (citeUserDateFormat) {
return s;
dateformat = citeUserDateFormat;
} else if (!dq) { // Can use double quotes
} else {
return '"'+s+'"';
dateformat = citeGlobalDateFormat;
} else if (!sq) { // Can use single quotes
}
return "'"+s+"'";
return (dateformat);
} else { // Has double and single quotes
}
s = s.replace(/\"/g, '\"');
return '"'+s+'"';
}
};


function reformatDates() {
// Fix up strings for output - capitalize first char, replace underscores with spaces
var dateformat = getDateFormat();
CiteTB.fixStr = function(s) {
//alert(':' + dateformat + ':');
s = s.slice(0,1).toUpperCase() + s.slice(1);
document.getElementById('accessdate').value = formatDate(document.getElementById('accessdate').value, dateformat);
s = s.replace('_',' ');
document.getElementById('date').value = formatDate(document.getElementById('date').value, dateformat);
return s;
//document.getElementById('dateformat_hidden').value = getDateFormatShort();
};
}


/*function updateGetButton() {
// Escape spaces and quotes for use in HTML classes/ids
document.getElementById('urlget').disabled = document.getElementById('url').value == '';
CiteTB.escStr = function(s) {
}*/
return s.replace(' ', '-').replace("'", "\'").replace('"', '\"');
};


function preview(wikitext) {
// MISC FUNCTIONS
document.getElementById('progress').style.visibility = "visible";
// Determine which template form is open, and get the template object for it
wikitext += '<references />';
CiteTB.getOpenTemplate = function() {
var url = "api.php?action=parse&format=xml&prop=text&text=" + encodeURIComponent(wikitext);
var dialogs = $(".ui-dialog-content.ui-widget-content:visible");
var xmlhttp = new XMLHttpRequest();
var templatename = $(dialogs[0]).find(".cite-template").val();
xmlhttp.onreadystatechange = function () {
return CiteTB.Templates[templatename];
if (xmlhttp.readyState==4) {
};
if(xmlhttp.status==200) {
document.getElementById('progress').style.visibility = "hidden";
var xmlDoc=xmlhttp.responseXML.documentElement;
var previewHTML = xmlDoc.getElementsByTagName("text")[0].textContent;
if (previewHTML == undefined) {
previewHTML = xmlDoc.getElementsByTagName("text")[0].childNodes[0].nodeValue;
}
//alert(previewHTML);
previewHTML = previewHTML.replace(/href="\//gi, 'href="//en.wikipedia.org/');
document.getElementById('previewSpan').innerHTML = '<fieldset><legend>Citation preview</legend>' + previewHTML + '</fieldset>';
}
else
alert('The query returned an error.');
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send(null)
}


function previewCitationBook() {
// Display the report for the error checks
makeBookCitationCode(preview);
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" />');
function previewCitationDefault() {
$('#editpage-copywarn').before(table);
var wikitext = makeCiteCode();
var tr;
preview(wikitext);
var tr1 = $('<tr style="width:100%" />');
}
var th1 = $('<th style="width:60%; font-size:110%" />').html(mw.usability.getMsg('cite-err-report-heading'));

var th2 = $('<th style="text-align:right; width:40%" />');
function pullJs() {
var im = $('<img />').attr('src', '//upload.wikimedia.org/wikipedia/commons/thumb/5/55/Gtk-stop.svg/20px-Gtk-stop.svg.png');
var book_url = document.getElementById('url').value;
im.attr('alt', mw.usability.getMsg('cite-err-report-close')).attr('title', mw.usability.getMsg('cite-err-report-close'));
if (book_url) {
var ad = $('<a id="cite-err-check-close" />').attr('href', '#');
document.getElementById('progress').style.visibility = "visible";
ad.append(im);
var book_url_enc = encodeURIComponent(book_url);
th2.append(ad);
if(!refTagURL) {refTagURL = defaultRefTagURL;}
tr1.append(th1).append(th2);
var baseurl = refTagURL + 'googlebooksjs.py';
table.append(tr1);
var url = baseurl + '?book_url=' + book_url_enc + '&callback=setFormValues';
$('#cite-err-check-close').on('click', function() { $('#cite-err-report').remove(); });
/*var script = document.createElement("script");
if (errors.length === 0) {
script.setAttribute("src",url);
tr = $('<tr style="width:100%;" />');
script.setAttribute("type","text/javascript");
var td = $('<td style="text-align:center; margin:1.5px;" />').html(mw.usability.getMsg('cite-err-report-empty'));
document.body.appendChild(script);*/
tr.append(td);
JsonRequest(url);
table.append(tr);
}else{
alert('No URL.');
return;
}
}
}
for(var e in errors) {

var err = errors[e];
function pullISBN() {
tr = $('<tr style="width:100%;" />');
var isbn = document.getElementById('isbn').value;
var td1 = $('<td style="border: 1px solid black; margin:1.5px; width:60%" />').html(err.err);
isbn = isbn.replace(/[^0-9]/g,""); //Digits only
var td2 = $('<td style="border: 1px solid black; margin:1.5px; width:40%" />').html(mw.usability.getMsg(err.msg));
if (isbn) {
tr.append(td1).append(td2);
document.getElementById('progress').style.visibility = "visible";
table.append(tr);
if(!refTagURL) {refTagURL = defaultRefTagURL;}
}
var baseurl = refTagURL + 'getdiberri.py';
};
var url = baseurl + '?isbn=' + isbn + '&callback=useDiberriData';
/*var script = document.createElement("script");
} // End of code loaded only on edit
script.setAttribute("src",url);
script.setAttribute("type","text/javascript");
document.body.appendChild(script);*/
JsonRequest(url);
}else{
alert('No ISBN.');
}
}

function pullDOI() {
var doi = document.getElementById('doi').value;
if (doi) {
document.getElementById('progress').style.visibility = "visible";
if(!refTagURL) {refTagURL = defaultRefTagURL;}
var baseurl = refTagURL + 'doifetchjs.py';
var url = baseurl + '?doi=' + encodeURIComponent(doi) + '&callback=useDoiData';
JsonRequest(url);
}else{
alert('No DOI.');
}
}

function pullPMID() {
alert('Not implemented yet...');
/*var doi = document.getElementById('doi').value;
if (doi) {
document.getElementById('progress').style.visibility = "visible";
if(!refTagURL) {refTagURL = defaultRefTagURL;}
var baseurl = refTagURL + 'doifetchjs.py';
var url = baseurl + '?doi=' + encodeURIComponent(doi) + '&callback=useDoiData';
JsonRequest(url);
}else{
alert('No DOI.');
}*/
}

function pullURL() {
var url = document.getElementById('url').value;
if (url) {
document.getElementById('progress').style.visibility = "visible";
if(!refTagURL) {refTagURL = defaultRefTagURL;}
var baseurl = refTagURL + 'urlfetchjs.py';
var url = baseurl + '?url=' + encodeURIComponent(url) + '&callback=useUrlData';
JsonRequest(url);
}else{
alert('No URl.');
}
}

function JsonRequest(url) {
//importScriptURI(url) //Bad: does not import the same script more than once
var script = document.createElement("script");
script.setAttribute("src",url);
script.setAttribute("type","text/javascript");
//document.body.appendChild(script);
document.getElementsByTagName('head')[0].appendChild(script);
}

function setFormValues(bookdata) {
document.getElementById('progress').style.visibility = "hidden";
//alert(bookdata);
//alert(bookdata.page);
if (bookdata.title.length != 0) { document.getElementById('title').value = bookdata.title; }
if (bookdata.isbn.length != 0) { document.getElementById('isbn').value = bookdata.isbn; }
if (bookdata.publisher.length != 0) { document.getElementById('publisher').value = bookdata.publisher; }
if (bookdata.pages.length != 0) {
document.getElementById('pages').value = bookdata.pages;
document.getElementById('pages').style.backgroundColor = '#FFFF99';
}
if (bookdata.url.length != 0) { document.getElementById('url').value = bookdata.url; }
if (bookdata.date.length != 0) { document.getElementById('date').value = bookdata.date; }

for (var i=0;i<bookdata.authors.length && i<=2;i++) {
authorn = i+1;
var author = bookdata.authors[i];
var match = /(.+)\s+(.+)/.exec(author);
if (match) {
document.getElementById('first' + authorn).value = match[1];
document.getElementById('last' + authorn).value = match[2];
}
else {
document.getElementById('last' + authorn).value = author;
}
}
document.getElementById('coauthors').value = bookdata.authors.splice(3).join(', ')
setAccessDateToday()
makeRefname()
}

function useDiberriData(bookdata) {
document.getElementById('progress').style.visibility = "hidden";
if (bookdata.title.length != 0) { document.getElementById('title').value = bookdata.title; }
if (bookdata.isbn.length != 0) { document.getElementById('isbn').value = bookdata.isbn; }
if (bookdata.publisher.length != 0) { document.getElementById('publisher').value = bookdata.publisher; }
if (bookdata.location.length != 0) { document.getElementById('location').value = bookdata.location; }
if (bookdata.year.length != 0) { document.getElementById('date').value = bookdata.year; }
if (bookdata.authors.length != 0) {
authors = bookdata.authors.split(';', 4);
for (var i=0;i<authors.length && i<=2;i++) {
authorn = i+1;
nameparts = authors[i].split(',', 2);
document.getElementById('last' + authorn).value = nameparts[0].trim();
if (nameparts.length == 2) {
document.getElementById('first' + authorn).value = nameparts[1].trim();
}
}
if (authors[3]) { document.getElementById('coauthors').value = authors[3].trim(); }
}
makeRefname()
}

function useDoiData(bookdata) {
document.getElementById('progress').style.visibility = "hidden";
if (bookdata.title) { document.getElementById('title').value = bookdata.title; }
//if (bookdata.isbn.length != 0) { document.getElementById('isbn').value = bookdata.isbn; }
//if (bookdata.publisher.length != 0) { document.getElementById('publisher').value = bookdata.publisher; }
//if (bookdata.location.length != 0) { document.getElementById('location').value = bookdata.location; }
if (bookdata.year) { document.getElementById('date').value = bookdata.year; }
if (bookdata.issn) { document.getElementById('issn').value = bookdata.issn; }
if (bookdata.journal) { document.getElementById('journal').value = bookdata.journal; }
if (bookdata.volume) { document.getElementById('volume').value = bookdata.volume; }
if (bookdata.issue) { document.getElementById('issue').value = bookdata.issue; }
if (bookdata.pages) { document.getElementById('pages').value = bookdata.pages; }

if (bookdata.authors) {
var coauthors = [];
for (var i=0;i<bookdata.authors.length;i++) {
var authorn = i+1;
var author = bookdata.authors[i];
if (authorn == 1) {
if (author.last) { document.getElementById('last').value = author.last.trim(); }
if (author.first) { document.getElementById('first').value = author.first.trim(); }
}
else {
var authorparts = [];
if (author.first) { authorparts.push( author.first.trim() ); }
if (author.last) { authorparts.push( author.last.trim() ); }
coauthors.push(authorparts.join(' '));
}
}
if (coauthors[0]) { document.getElementById('coauthors').value = coauthors.join(', '); }
}
makeRefname();
}

function useUrlData(data) {
document.getElementById('progress').style.visibility = "hidden";
if (data.title) { document.getElementById('title').value = data.title; }
if (data.work) { document.getElementById('work').value = data.work; }
if (data.page) { document.getElementById('pages').value = data.page; }
if (data.date) {
document.getElementById('date').value = formatDate(data.date, getDateFormat());
}
/*if (data.author) {
var authors = data.author.replace(/ [Aa]nd /, ', ');
var match = /(.+),\s*(.+)/.exec(authors);
var firstauthor = '';
if (match) {
firstauthor = match[1];
var coauthors = match[2];
document.getElementById('coauthors').value = coauthors;
}
else {
firstauthor = data.author;
}
var match = /(.+)\s+(.+)/.exec(firstauthor);
if (match) {
document.getElementById('first').value = match[1];
document.getElementById('last').value = match[2];
}
else {
document.getElementById('last').value = author;
}
}*/
if (data.authors) {
var coauthors = [];
for (var i=0;i<data.authors.length;i++) {
var authorn = i+1;
var author = data.authors[i];
if (authorn == 1) {
var match = /(.+)\s+(.+)/.exec(author);
if (match) {
document.getElementById('first').value = match[1].trim();
document.getElementById('last').value = match[2].trim();
}
else {
document.getElementById('last').value = author.trim();
}
}
else {
coauthors.push(author);
}
}
if (coauthors[0]) { document.getElementById('coauthors').value = coauthors.join(', '); }
}
}

$( refbuttons );

Sayfanın 13.48, 11 Temmuz 2018 tarihindeki hâli

var numforms = 0;
var wikEdAutoUpdateUrl;
var citeUserDateFormat;
var refTagURL;
var defaultRefTagURL = '//reftag.appspot.com/';
var refToolDebug;

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
};

function refbuttons() {
  if (mw.toolbar && document.getElementById('toolbar') ) {
    var button = document.createElement('a');
    button.href = "javascript:easyCiteMain()";
    button.title = "Insert Citation";
    button.className = "mw-toolbar-editbutton";
    var buttonimage = document.createElement('img');
    buttonimage.src = "//upload.wikimedia.org/wikipedia/commons/e/ea/Button_easy_cite.png";
    buttonimage.alt = "Insert Citation";
    button.appendChild(buttonimage);
    var toolbar = document.getElementById('toolbar');
    if (navigator.userAgent.indexOf('MSIE') == -1) {
      toolbar.appendChild(button);
      var citemain = document.createElement('div');
      citemain.style.display = 'none';
      citemain.style.margin = '0 0 6px';
      citemain.style.clear = 'both';
      citemain.style.height = 'auto';
      citemain.setAttribute('Id', 'citeselect');
      citemain.appendChild( addOption("citeWeb()", "Web") );
      citemain.appendChild( addOption("citeNews()", "News") );
      citemain.appendChild( addOption("citeBook()", "Book") );
      citemain.appendChild( addOption("citeJournal()", "Journal") );
      citemain.appendChild( addOption("citeNamedRef()", "Named references") );
      citemain.appendChild( addOption("dispErrors()", "Error check") );
      citemain.appendChild( addOption("showMore()", "More") );
      citemain.appendChild( addOption("hideInitial()", "Cancel") );

      var citemore = document.createElement('div');
      citemore.style.display = 'none';
      citemore.setAttribute('Id', 'citemore');
      citemore.appendChild( addOption("citeEncyclopedia()", "Encyclopedia") );
      citemore.appendChild( addOption("citePressRelease()", "Press release") );
      citemore.appendChild( addOption("citeMap()", "Map") );
      citemore.appendChild( addOption("showRefSectionOptions()", "Ref Section") );
      citemain.appendChild(citemore);

      $( citemain ).insertAfter( $( toolbar ) );
    }
    else {
      toolbar.appendChild(button);
      var citeselect = document.createElement('div');
      citeselect.id = 'citeselect';
      citeselect.style.display = "none";
      citeselect.innerHTML = '<input type="button" value="Web" onclick="citeWeb()" />'+
      '<input type="button" value="News" onclick="citeNews()" />'+
      '<input type="button" value="Book" onclick="citeBook()" />'+
      '<input type="button" value="Journal" onclick="citeJournal()" />'+
      '<input type="button" value="Named references" onclick="citeNamedRef()" />'+
      '<input type="button" value="Error check" onclick="dispErrors()" />'+
      '<input type="button" value="More" onclick="showMore()" />'+
      '<input type="button" value="Cancel" onclick="hideInitial()" />'+
      '<div id="citemore" style="display:none">\
      <input type="button" value="Encyclopedia" onclick="citeEncyclopedia()" />\
      <input type="button" value="Press release" onclick="citePressRelease()" />\
      <input type="button" value="Map" onclick="citeMap()" />\
      <input type="button" value="Ref Section" onclick="showRefSectionOptions()" />\
      </div>';
      document.getElementById('editform').insertBefore(citeselect, document.getElementById('editform').firstChild ) ;
    }
    var reftoolformarea = document.createElement( 'span' );
    reftoolformarea.id = 'refToolFormArea';
    document.getElementById('citeselect').appendChild( reftoolformarea );
  }
  if (typeof EditTools == "object") {
    var placeholder = document.getElementById("editpage-specialchars");
    EditTools.createEditTools (placeholder);
  }
}

function addOption(script, text) {
  var option = document.createElement('input');
  option.setAttribute('type', 'button');
  option.setAttribute('onclick', script);
  option.setAttribute("value", text);
  return option;
}

function hideInitial() {
  document.getElementById('citeselect').style.display = 'none';
  oldFormHide();
}

function oldFormHide() {
  //if (numforms != 0) {
  //  document.getElementById('citediv'+numforms).style.display = 'none';
  //}
  document.getElementById('refToolFormArea').innerHTML = '';
  if (document.getElementById('errorform') !== null) {
    document.getElementById('citeselect').removeChild(document.getElementById('errorform'));
  }
}

function easyCiteMain() {
  document.getElementById('citeselect').style.display = '';
  document.getElementById('citemore').style.display = 'none';
}

function showMore() {
	document.getElementById('citemore').style.display = '';
}

var months = ['January', 'February', 'March', 'April', 'May', 'June',
  'July', 'August', 'September', 'October', 'November', 'December'];
var citeGlobalDateFormat = "<date> <monthname> <year>";
function getTime() {
  var datestr = '';
  if (citeUserDateFormat) {
    datestr = citeUserDateFormat;
  } else {
    datestr = citeGlobalDateFormat;
  }
  var DT = new Date();
  var zmonth = '';
  var month = DT.getUTCMonth()+1;
  if (month < 10) {
    zmonth = "0"+month.toString();
  } else {
    zmonth = month.toString();
  }
  month = month.toString();
  var zdate = '';
  var date = DT.getUTCDate();
  if (date < 10) {
    zdate = "0"+date.toString();
  } else {
    zdate = date.toString();
  }
  date = date.toString();
  datestr = datestr.replace('<date>', date);
  datestr = datestr.replace('<month>', month);
  datestr = datestr.replace('<zdate>', zdate);
  datestr = datestr.replace('<zmonth>', zmonth);
  datestr = datestr.replace('<monthname>', months[DT.getUTCMonth()]);
  datestr = datestr.replace('<year>', DT.getUTCFullYear().toString());
  return (datestr);
}

function lastNameToRefname() {
  //Note: This only works if field 'refname' comes after field 'last', but it always does
  var lastName;
  var fields = document.getElementById('citediv'+numforms).getElementsByTagName('input');
  for (var i=0; i<fields.length; i++) {
    if(fields[i].id == 'last') {
      lastName = fields[i].value;
    }
    else if(fields[i].id == 'refname') {
      fields[i].value = lastName.replace(/^\s*(.*?)\s*$/, "$1");
      return;
    }
  }
}

function setAccessDateToday() {
  document.getElementById('accessdate').value = getTime();
/*  var fields = document.getElementById('citediv'+numforms).getElementsByTagName('input');
  for (var i=0; i<fields.length; i++) {
    if(fields[i].id == 'accessdate') {
      fields[i].value = getTime();
      return;
    }
  }
*/
}

function getLastName(authornum) {
  if (/\S/.test(document.getElementById('last'+authornum).value)) {
    return document.getElementById('last'+authornum).value;
  }
  else {
    var author = document.getElementById('author'+authornum).value;
    var match = /(\S+)\s*$/.exec(author);
    if (match) {
      return match[1];
    }
    else {
      return '';
    }
  }
}

function makeRefname() {
  var refname;
  if (document.getElementById('last1')) {
    refname = document.getElementById('last1').value + document.getElementById('last2').value;
  }
  else{
	refname = document.getElementById('last').value;
  }
  if (/\S/.test(refname)) {
    var date = document.getElementById('date').value;
    var match = /[0-9]{4}/.exec(date);
    if (match) {
      refname += match[0];
    }
  }
  else {
    refname = document.getElementById('title').value;
  }
  document.getElementById('refname').value = refname;
}

function citeWeb() {
  citeNewsWeb("cite web");
}
function citeNews() {
  citeNewsWeb("cite news");
}

function citeNewsWeb(templatename) {
  oldFormHide();
  var template = templatename;
  var legend;
  if (template == "cite web") {
    legend = "Cite web source";
  } else {
    legend = "Cite news source";
  }
  var newtime = getTime();
  numforms++;
  var form = '<div id="citediv'+numforms+'">'+
    '<fieldset><legend>'+legend+'</legend>'+
    '<table cellspacing="5">'+
    '<input type="hidden" value="'+template+'" id="template">'+
    '<tr><td width="120"><label for="url">&nbsp;URL: </label></td>'+
      '<td width="400"><input type="image" src="//upload.wikimedia.org/wikipedia/commons/6/62/Arrow_out_condensed.png" tabindex=1 alt="Fetch" title="' + ((template == 'cite news') ? 'For a New York Times article URL, fetch article data and fill in the fields. For other URLs, fetch the page title.' : 'Fetch the page title. Irrelevant parts often have to be removed manually afterwards.') + '" onClick="pullURL(); return false;" style="float:right"><span style="display: block;overflow: hidden;"><input type="text" tabindex=1 style="width:97%" id="url"></span></td>'+
    '<td width="120"><label for="title">&nbsp;Title: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="title"></td></tr>'+
    '<tr><td width="120"><label for="last">&nbsp;Last name: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="last"></td>'+
    '<td width="120"><label for="first">&nbsp;First name: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="first"></td></tr>'+
    '<tr><td width="120"><label for="coauthors">&nbsp;Coauthors: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="coauthors"></td>'+
    '<td width="120"><label for="date">&nbsp;Publication date: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="date"></td></tr>'+
    '<tr><td width="120"><label for="work">&nbsp;' + ((template == 'cite news') ? 'Newspaper' : 'Work') + ': </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="work"></td>'+
    '<td width="120"><label for="publisher">&nbsp;Publisher: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="publisher"></td></tr>'+
    '<tr><td width="120"><label for="pages">&nbsp;Pages: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="pages"></td>'+
    '<td width="120"><label for="language">&nbsp;Language: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="language"></td></tr>'+
    '<tr><td width="120"><label for="accessdate">&nbsp;Access date: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="accessdate" value="'+ newtime +'"></td>'+
    '<td width="120"><label for="location">&nbsp;Location: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="location"></td></tr>';
  if (template == 'cite web') {
    form += '<tr><td width="120"><label for="archiveurl">&nbsp;Archive URL: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="archiveurl"></td>'+
    '<td width="120"><label for="archivedate">&nbsp;Archive date: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="archivedate"></td></tr>';
  }
  form += '<tr><td width="120"><label for="refname">&nbsp;Reference name: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:60%" id="refname"><input type="button" value="<Last name" onClick="lastNameToRefname()"></td></tr>'+
    '</table>'+
    ' <input type="button" value="Add citation" onClick="addcites()">'+
	' <input type="button" value="Preview citation" onClick="previewCitationDefault()"> \
	<img id="progress" src="//upload.wikimedia.org/wikipedia/commons/5/59/RefToolbar_spinning_throbber.gif" style="visibility: hidden" />'+
    '<input type="checkbox" tabindex=1 name="verbose" id="verbose" value="verbose"><label for="verbose">Vertical form</label>'+
    '<span style="float:right"><a href="//en.wikipedia.org/wiki/Template:'+template.replace(/ /g, '_')+'" target="_blank">[Template documentation]</a></span>'+
    '</fieldset><span id="previewSpan"></span></div>';
   document.getElementById('refToolFormArea').innerHTML = form;
}

function citeBook() {
  oldFormHide();
  var template = "cite book";
  numforms++;
  var form = '<div id="citediv'+numforms+'">'+
    '<fieldset><legend>Cite book source</legend>';

  form += '<table cellspacing="5" width="100%"> \
	<tr><td><label for="title">Title: </label></td> \
	<td colspan=5><input type="text" tabindex=1 style="width:100%" id="title"></td></tr>';
  for (var i=1;i<=3;i++) {
    var i_str = i == 1 ? '': ' '+i;
    form += '<tr> \
		<td width="130"><label for="last'+i+'">Author'+i_str+' last&nbsp;name: </label></td> \
		<td><input type="text" tabindex=1 style="width:100%" id="last'+i+'"></td> \
		<td><label for="first'+i+'">&nbsp;first&nbsp;name: </label></td> \
		<td><input type="text" tabindex=1 style="width:100%" id="first'+i+'"></td> \
		<td><label for="authorlink'+i+'">&nbsp;Authorlink: </label></td> \
		<td><input type="text" tabindex=1 style="width:100%" id="authorlink'+i+'"> \
		<!--<a id="authorLinkAnchor'+i+'"><img id="authorLinkButton'+i+'" src="static/progress.gif" border="0" style="visibility: hidden" /></a> \
		<a href="//en.wikipedia.org/wiki/%s" target="_blank"><img id="authorTryLink'+i+'" src="static/external.png" border="0" style="visibility: hidden" /></a> --> \
		</td> \
		</tr>';
  }
  form += '<tr><td><label for="coauthors">Coauthors: </label></td> \
	<td><input type="text" tabindex=1 style="width:100%" id="coauthors"></td> \
	<td><label for="editor">&nbsp;Editor: </label></td> \
	<td><input type="text" tabindex=1 style="width:100%" id="editor"></td> \
	<td><label for="others">&nbsp;Others: </label></td> \
	<td><input type="text" tabindex=1 style="width:100%" id="others"></td></tr> \
	</table> \
	<table cellspacing="5" width="100%"> \
	<tr><td width="130"><label for="publisher">Publisher: </label></td> \
	<td><input type="text" tabindex=1 style="width:100%" id="publisher"></td> \
	<td><label for="location">&nbsp;Location: </label></td> \
	<td><input type="text" tabindex=1 style="width:100%" id="location"></td></tr> \
	\
	<tr><td><label for="date">Publication&nbsp;date or&nbsp;year: </label></td> \
	<td><input type="text" tabindex=1 style="width:140px" id="date"> \
	<input id="dmy" name="dateformat" value="dmy" type="radio" tabindex=1 onclick="reformatDates()"><label for="dmy">dmy</label> \
	<input id="mdy" name="dateformat" value="mdy" type="radio" tabindex=1 onclick="reformatDates()"><label for="mdy">md, y</label> \
	<input id="ymd" name="dateformat" value="ymd" type="radio" tabindex=1 onclick="reformatDates()"><label for="ymd">y-m-d</label> \
	</td> \
	<td><label for="edition">&nbsp;Edition: </label></td> \
	<td><input type="text" tabindex=1 style="width:100%" id="edition"></td></tr> \
	\
	<tr><td><label for="series">Series: </label></td> \
	<td><input type="text" tabindex=1 style="width:100%" id="series"></td> \
	<td><label for="volume">&nbsp;Volume: </label></td> \
	<td><input type="text" tabindex=1 style="width:100%" id="volume"></td></tr> \
	\
	<tr><td><label for="pages">Page number(s):</label></td> \
	<td><input type="text" tabindex=1 style="width:100%" id="pages" name="pages" onFocus="this.style.backgroundColor=\'\';"></td> \
	<td><label for="chapter">&nbsp;Chapter: </label></td> \
	<td><input type="text" tabindex=1 style="width:100%" id="chapter"></td></tr> \
	\
	<tr><td><label for="isbn">ISBN: </label></td> \
	<td><input type="image" src="//upload.wikimedia.org/wikipedia/commons/6/62/Arrow_out_condensed.png" tabindex=1 alt="Fetch" title="Fill in citation data based on ISBN from Diberri\'s tool." onClick="pullISBN(); return false;" style="float:right"><span style="display: block;overflow: hidden;"><input type="text" tabindex=1 style="width:97%" id="isbn"></span></td> \
	<td><label for="language">&nbsp;Language: </label></td> \
	<td><input type="text" tabindex=1 style="width:100%" id="language"></td></tr> \
	\
	<tr><td><label for="url">URL: </label></td> \
	<td><input type="image" src="//upload.wikimedia.org/wikipedia/commons/6/62/Arrow_out_condensed.png" tabindex=1 alt="Fetch" title="Fill in citation data based on a Google Books URL." onClick="pullJs(); return false;" style="float:right"><span style="display: block;overflow: hidden;"><input type="text" tabindex=1 style="width:97%" id="url"></span></td> \
	<td><label for="accessdate">&nbsp;Access&nbsp;date:</label></td> \
	<td><input type="text" tabindex=1 style="width:100%" id="accessdate"></td></tr> \
	\
	<tr><td><label for="otherfields">Other&nbsp;fields:</label></td> \
	<td><input type="text" tabindex=1 style="width:100%" id="otherfields"></td> \
	<td><label for="refname">&nbsp;Ref&nbsp;name: </label></td> \
	<td><input type="text" tabindex=1 style="width:100%" id="refname"></td> \
	</tr> \
	</table> \
	\
	<input type="radio" tabindex=1 name="template" id="cite_book" value="cite_book" checked="1"><label for="cite_book">\{\{cite book}}</label> <sup><a href="//en.wikipedia.org/wiki/Template:Cite_book" target="_blank">[doc]</a></sup> \
	<input type="radio" tabindex=1 name="template" id="citation" value="citation"><label for="citation">\{\{citation}}</label> <sup><a href="//en.wikipedia.org/wiki/Template:Citation" target="_blank">[doc]</a></sup> \
	<input type="radio" tabindex=1 name="template" id="plain" value="plain"><label for="plain">plain wikicode (experimental)</label> \
	<input type="checkbox" tabindex=1 name="verbose" id="verbose" value="verbose"><label for="verbose">Vertical form</label> \
	<input type="checkbox" tabindex=1 name="extraparams" id="extraparams" value="extraparams"><label for="extraparams">Extra parameters</label> \
	<br /><input type="button" value="Add citation" onClick="makeCiteBook()"> \
	<input type="button" value="Preview citation" onClick="previewCitationBook()"> \
	<img id="progress" src="//upload.wikimedia.org/wikipedia/commons/5/59/RefToolbar_spinning_throbber.gif" style="visibility: hidden" /> \
	\
 	</fieldset><span id="previewSpan"></span></div>';
   document.getElementById('refToolFormArea').innerHTML = form;
}

function citeJournal() {
  oldFormHide();
  var template = "cite journal";
  numforms++;
  var form = '<div id="citediv'+numforms+'">'+
    '<fieldset><legend>Cite journal</legend>'+
    '<table cellspacing="5">'+
    '<input type="hidden" value="'+template+'" id="template">'+
    '<tr><td width="120"><label for="last">&nbsp;Last name: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="last"></td>'+
    '<td width="120"><label for="first">&nbsp;First name: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="first"></td></tr>'+
    '<tr><td width="120"><label for="coauthors">&nbsp;Coauthors: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="coauthors"></td>'+
    '<td width="120"><label for="date">&nbsp;Publication date: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="date"></td></tr>'+
    '<tr><td width="120"><label for="title">&nbsp;Title: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="title"></td>'+
    '<td width="120"><label for="journal">&nbsp;Journal: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="journal"></td></tr>'+
    '<tr><td width="120"><label for="publisher">&nbsp;Publisher: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="publisher"></td>'+
    '<td width="120"><label for="location">&nbsp;Location: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="location"></td></tr>'+
    '<tr><td width="120"><label for="volume">&nbsp;Volume: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="volume"></td>'+
    '<td width="120"><label for="issue">&nbsp;Issue: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="issue"></td></tr>'+
    '<tr><td width="120"><label for="pages">&nbsp;Pages: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="pages"></td>'+
    '<td width="120"><label for="issn">&nbsp;ISSN: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="issn"></td></tr>'+
    '<tr><td width="120"><label for="oclc">&nbsp;OCLC: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="oclc"></td>'+
    '<td width="120"><label for="doi">&nbsp;DOI: </label></td>'+
      '<td width="400"><input type="image" src="//upload.wikimedia.org/wikipedia/commons/6/62/Arrow_out_condensed.png" tabindex=1 alt="Fetch" title="Fetch citation data for a DOI from crossref.org and fill in the other fields." onClick="pullDOI(); return false;" style="float:right"><span style="display: block;overflow: hidden;"><input type="text" tabindex=1 style="width:97%" id="doi"></span></td></tr>'+
    '<tr><td width="120"><label for="pmid">&nbsp;PMID: </label></td>'+
      '<td width="400"><input type="image" src="//upload.wikimedia.org/wikipedia/commons/6/62/Arrow_out_condensed.png" tabindex=1 alt="Fetch" title="Fetch citation data for a PMID" onClick="pullPMID(); return false;" style="float:right;visibility:hidden"><span style="display: block;overflow: hidden;"><input type="text" tabindex=1 style="width:97%" id="pmid"></span></td>'+
    '<td width="120"><label for="quote">&nbsp;Quote: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="quote"></td></tr>'+
    '<tr><td width="120"><label for="url">&nbsp;URL: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="url"></td>'+
    '<td width="120"><label for="accessdate">&nbsp;Access date: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="accessdate"></td></tr>'+
    '<tr><td width="120"><label for="language">&nbsp;Language: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="language"></td>'+
    '<td width="120"><label for="refname">&nbsp;Reference name: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:60%" id="refname"><input type="button" value="<Last name" onClick="lastNameToRefname()"></td></tr>'+
    '</table>'+
    '<input type="button" value="Add citation" onClick="addcites()">'+
	' <input type="button" value="Preview citation" onClick="previewCitationDefault()"> \
	<img id="progress" src="//upload.wikimedia.org/wikipedia/commons/5/59/RefToolbar_spinning_throbber.gif" style="visibility: hidden" />'+
    '<input type="checkbox" tabindex=1 name="verbose" id="verbose" value="verbose"><label for="verbose">Vertical form</label>'+
    '<span style="float:right"><a href="//en.wikipedia.org/wiki/Template:'+template.replace(/ /g, '_')+'" target="_blank">[Template documentation]</a></span>'+
    '</fieldset><span id="previewSpan"></span></div>';
   document.getElementById('refToolFormArea').innerHTML = form;
}

function citeEncyclopedia() {
  oldFormHide();
  var template = "cite encyclopedia";
  numforms++;
  var form = '<div id="citediv'+numforms+'">'+
    '<fieldset><legend>Cite encyclopedia source</legend>'+
    '<table cellspacing="5">'+
    '<input type="hidden" value="'+template+'" id="template">'+
    '<tr><td width="120"><label for="last">&nbsp;Last name: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="last"></td>'+
    '<td width="120"><label for="first">&nbsp;First name: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="first"></td></tr>'+
    '<tr><td width="120"><label for="coauthors">&nbsp;Coauthors: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="coauthors"></td>'+
    '<td width="120"><label for="editors">&nbsp;Editors: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="editors"></td></tr>'+
    '<tr><td width="120"><label for="title">&nbsp;Entry title: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="title"></td>'+
    '<td width="120"><label for="encyclopedia">&nbsp;Encyclopedia: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="encyclopedia"></td></tr>'+
    '<tr><td width="120"><label for="publisher">&nbsp;Publisher: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="publisher"></td>'+
    '<td width="120"><label for="location">&nbsp;Location: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="location"></td></tr>'+
    '<tr><td width="120"><label for="year">&nbsp;Year: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="year"></td>'+
    '<td width="120"><label for="volume">&nbsp;Volume: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="volume"></td></tr>'+
    '<tr><td width="120"><label for="pages">&nbsp;Pages: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="pages"></td>'+
    '<td width="120"><label for="isbn">&nbsp;ISBN: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="isbn"></td></tr>'+
    '<tr><td width="120"><label for="url">&nbsp;URL: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="url"></td>'+
    '<td width="120"><label for="accessdate">&nbsp;Access date: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="accessdate"></td></tr>'+
    '<tr><td width="120"><label for="language">&nbsp;Language: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="language"></td>'+
    '<td width="120"><label for="refname">&nbsp;Reference name: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="refname"></td></tr>'+
    '</table>'+
    '<input type="button" value="Add citation" onClick="addcites()">'+
	' <input type="button" value="Preview citation" onClick="previewCitationDefault()"> \
	<img id="progress" src="//upload.wikimedia.org/wikipedia/commons/5/59/RefToolbar_spinning_throbber.gif" style="visibility: hidden" />'+
    '<input type="checkbox" tabindex=1 name="verbose" id="verbose" value="verbose"><label for="verbose">Vertical form</label>'+
    '<span style="float:right"><a href="//en.wikipedia.org/wiki/Template:'+template.replace(/ /g, '_')+'" target="_blank">[Template documentation]</a></span>'+
    '</fieldset><span id="previewSpan"></span></div>';
   document.getElementById('refToolFormArea').innerHTML = form;
}

function citePressRelease() {
  oldFormHide();
  var template = "cite press release";
  numforms++;
  var form = '<div id="citediv'+numforms+'">'+
    '<fieldset><legend>Cite press release</legend>'+
    '<table cellspacing="5">'+
    '<input type="hidden" value="'+template+'" id="template">'+
    '<tr><td width="120"><label for="title">&nbsp;Title: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="title"></td>'+
    '<td width="120"><label for="publisher">&nbsp;Publisher: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="publisher"></td></tr>'+
    '<tr><td width="120"><label for="date">&nbsp;Date: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="date"></td>'+
    '<td width="120"><label for="language">&nbsp;Language: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="language"></td></tr>'+
    '<tr><td width="120"><label for="url">&nbsp;URL: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="url"></td>'+
    '<td width="120"><label for="accessdate">&nbsp;Access date: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="accessdate" value="'+ getTime() +'"></td></tr>'+
    '<tr><td width="120"><label for="refname">&nbsp;Reference name: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="refname"></td></tr>'+
    '</table>'+
    '<input type="button" value="Add citation" onClick="addcites()">'+
	' <input type="button" value="Preview citation" onClick="previewCitationDefault()"> \
	<img id="progress" src="//upload.wikimedia.org/wikipedia/commons/5/59/RefToolbar_spinning_throbber.gif" style="visibility: hidden" />'+
    '<input type="checkbox" tabindex=1 name="verbose" id="verbose" value="verbose"><label for="verbose">Vertical form</label>'+
    '<span style="float:right"><a href="//en.wikipedia.org/wiki/Template:'+template.replace(/ /g, '_')+'" target="_blank">[Template documentation]</a></span>'+
    '</fieldset><span id="previewSpan"></span></div>';
   document.getElementById('refToolFormArea').innerHTML = form;
}

function citeMap() {
  oldFormHide();
  var template = "cite map";
  numforms++;
  var form = '<div id="citediv'+numforms+'">'+
    '<fieldset><legend>Cite map</legend>'+
    '<table cellspacing="5">'+
    '<input type="hidden" value="'+template+'" id="template">'+
    '<tr><td width="120"><label for="publisher">&nbsp;Publisher: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="publisher"></td>'+
    '<td width="120"><label for="title">&nbsp;Title: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="title"></td></tr>'+
    '<tr><td width="120"><label for="url">&nbsp;URL: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="url"></td>'+
    '<td width="120"><label for="accessdate">&nbsp;Access date: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="accessdate"></td></tr>'+
    '<tr><td width="120"><label for="edition">&nbsp;Edition: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="edition"></td>'+
    '<td width="120"><label for="date">&nbsp;Date or year: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="date"></td></tr>'+
    '<tr><td width="120"><label for="cartography">&nbsp;Cartography: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="cartography"></td>'+
    '<td width="120"><label for="scale">&nbsp;Scale: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="scale"></td></tr>'+
    '<tr><td width="120"><label for="series">&nbsp;Series: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="series"></td>'+
    '<td width="120"><label for="page">&nbsp;Page: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="page"></td></tr>'+
    '<tr><td width="120"><label for="section">&nbsp;Section: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="section"></td>'+
    '<td width="120"><label for="inset">&nbsp;Inset: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="inset"></td></tr>'+
    '<tr><td width="120"><label for="isbn">&nbsp;ISBN: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="isbn"></td>'+
    '<td width="120"><label for="refname">&nbsp;Reference name: </label></td>'+
      '<td width="400"><input type="text" tabindex=1 style="width:100%" id="refname"></td></tr>'+
    '</table>'+
    '<input type="button" value="Add citation" onClick="addcites()">'+
	' <input type="button" value="Preview citation" onClick="previewCitationDefault()"> \
	<img id="progress" src="//upload.wikimedia.org/wikipedia/commons/5/59/RefToolbar_spinning_throbber.gif" style="visibility: hidden" />'+
    '<input type="checkbox" tabindex=1 name="verbose" id="verbose" value="verbose"><label for="verbose">Vertical form</label>'+
    '<span style="float:right"><a href="//en.wikipedia.org/wiki/Template:'+template.replace(/ /g, '_')+'" target="_blank">[Template documentation]</a></span>'+
    '</fieldset><span id="previewSpan"></span></div>';
   document.getElementById('refToolFormArea').innerHTML = form;
}

function showRefSectionOptions() {
  oldFormHide();
  var template = "cite encyclopedia";
  numforms++;
  var form = '<div id="citediv'+numforms+'">'+
    '<fieldset><legend>Add references section</legend>\
	Headline:<br />\
	<input id="references" name="headline" type="radio" tabindex=1 checked="checked"><label for="references">== References ==</label><br /> \
	<input id="notes" name="headline" type="radio" tabindex=1><label for="notes">== Notes ==</label><br /> \
	Type:<br /> \
	<input id="type-references" name="type" type="radio" tabindex=1><label for="type-references">&lt;references/&gt;</label><br /> \
	<input id="type-reflist" name="type" type="radio" tabindex=1 checked="checked"><label for="type-reflist">\{\{Reflist}}</label><br /> \
	<input id="type-reflist2" name="type" type="radio" tabindex=1><label for="type-reflist2">\{\{Reflist|2}}</label><br /> \
	<input type="checkbox" tabindex=1 id="ldr"><label for="ldr">List-defined references</label> (<a href="//en.wikipedia.org/wiki/Wikipedia:Footnotes#List-defined_references" target="_blank">Info 1</a>, <a href="//en.wikipedia.org/wiki/Help:Footnotes#List-defined_references" target="_blank">Info 2</a>)<br />\
    <input type="button" value="Add references section" onClick="addRefSection()">'+
 '</fieldset></div>';
   document.getElementById('citeselect').innerHTML += form;
}

function makeCiteCode() {
  cites = document.getElementById('citediv'+numforms).getElementsByTagName('input');
  var template = '';
  var citebegin = '<ref';
  var citename = '';
  var citeinner = '';
  for (var i=0; i<cites.length; i++) {
    var citeid = cites[i].id;
    var citevalue = cites[i].value;
    citevalue = citevalue.trim();    //Trim leading and trailing whitespace
    if (citeid == "verbose") {
	  if (cites[i].checked) {
	    citeinner = citeinner.replace(/\|/g, "\n|");
	  }
    }
    else if (citevalue !== '' && cites[i].type !== 'button' && cites[i].type !== 'image') {
      if (citeid === "refname") {
        citebegin += ' name="' + citevalue + '"';
      }
      else if (citeid == "template") {
        citename = '>\{\{' + citevalue;
        template = citevalue;
      }
      else {
        if (citeid === "pages") {
          if (citevalue.match(/^\w+$/) && template != 'cite encyclopedia') {
            citeid = "page";    //Use page= instead of pages= if only one page. Makes p. 5 instead of pp. 5.
          }
          else {
            citevalue = citevalue.replace(/-/g, "–");    //Replace hyphens with en dashes [[WP:ENDASH]]
          }
        }
        else if (citeid == "date" && citevalue.match(/^\d\d\d\d$/)) {
          citeid = "year";  // Use year= instead of date= if only the year is specified
        }
        citeinner += "|" + citeid + "=" + citevalue;
      }
    }
  }
  cite = citebegin + citename + citeinner + "}}</ref>";
  return cite;
}

function addcites(template) {
  var cite = makeCiteCode();
  $("#wpTextbox1").focus();
  insertTags(cite, '', '');
  //document.getElementById('citediv'+numforms).style.display = 'none';
  oldFormHide();
}

function addRefSection() {
	var wikicode = "\n";
	if (document.getElementById('references').checked) {
		wikicode += "== References ==\n";
	}
	else if (document.getElementById('notes').checked) {
		wikicode += "== Notes ==\n";
	}
	else {alert('No headline selected!');}
	
	if (document.getElementById('type-references').checked) {
		if (document.getElementById('ldr').checked) {
			wikicode += "<references>\n\n</references>\n";
		}
		else {
			wikicode += "<references/>\n";
		}
	}
	else if (document.getElementById('type-reflist').checked || document.getElementById('type-reflist2').checked) {
		var col2 = document.getElementById('type-reflist2').checked ? '|2' : '' ;
		if (document.getElementById('ldr').checked) {
			wikicode += "\{\{Reflist" + col2 + "|refs=\n\n}}\n";
		}
		else {
			wikicode += "\{\{Reflist" + col2 + "}}\n";
		}
	}
	else {alert('No type selected!');}
	$("#wpTextbox1").focus();
	insertTags(wikicode, '', '');
	document.getElementById('citediv'+numforms).innerHTML = '';
}

function getNamedRefs(calls) {
  if (typeof(wikEdUseWikEd) != 'undefined') {
    if (wikEdUseWikEd == true) {
      WikEdUpdateTextarea();
    }
  }
  text = document.getElementById('wpTextbox1').value;
  var regex;
  if (calls) {
    regex = /< *?ref +?name *?= *?(('([^']*?)')|("([^"]*?)")|([^'"\s]*?[^\/]\b)) *?\/ *?>/gi //'
  } else {
    regex = /< *?ref +?name *?= *?(('([^']*?)')|("([^"]*?)")|([^'"\s]*?[^\/]\b)) *?>/gi //'
  }
  var namedrefs = new Array();
  var i=0;
  var nr=true;
  do {
    ref = regex.exec(text);
    if(ref != null){
      if (ref[5]) {
        namedrefs[i] = ref[5];
      } else if (ref[3]) {
        namedrefs[i] = ref[3];
      } else {
        namedrefs[i] = ref[6];
      }
      i++;
    } else {
      nr=false;
    }
  } while (nr==true);
  return namedrefs;
}

function citeNamedRef() {
  var namedrefs = getNamedRefs(false);
  if (namedrefs == '') {
    oldFormHide();
    numforms++;
    var out = '<div id="citediv'+numforms+'"><fieldset>'+
      '<legend>References in text</legend>There are no named refs (<tt>&lt;ref name="Name"&gt;</tt>) in the text</fieldset></div>';
    document.getElementById('citeselect').innerHTML += out;
  }
  else {
    oldFormHide();
    numforms++;
    var form = '<div id="citediv'+numforms+'">'+
      '<fieldset><legend>References in article</legend>'+
      '<table cellspacing="5">'+
      '<tr><td><label for="namedrefs">&nbsp;Named references in text</label></td>'+
            '<td><select name="namedrefs" id="namedrefs">';
    for (var i=0;i<namedrefs.length;i++) {
      form+= '<option value="'+namedrefs[i]+'">'+namedrefs[i]+'</option>';
    }
    form+= '</select>'+
      '</td></tr></table>'+
      '<input type="button" value="Add citation" onClick="addnamedcite()">'+
      '</fieldset></div>';
     document.getElementById('citeselect').innerHTML += form;
  }
}

function addnamedcite() {
  var name = document.getElementById('citediv'+numforms).getElementsByTagName('select')[0].value;
  var ref = '<ref name="'+name+'" />';
  $("#wpTextbox1").focus();
  insertTags(ref, '', '');
  document.getElementById('citediv'+numforms).style.display = 'none';
}

function getAllRefs() {
  if (typeof(wikEdUseWikEd) != 'undefined') {
    if (wikEdUseWikEd == true) {
      WikEdUpdateTextarea();
    }
  }
  var text = document.getElementById('wpTextbox1').value;
  var regex = /< *?ref( +?name *?= *?(('([^']*?)')|("([^"]*?)")|([^'"\s]*?[^\/]\b)))? *?>((.|\n)*?)< *?\/? *?ref *?>/gim //"
  var allrefs = new Array();
  var i=0;
  var nr=true;
  do {
    ref = regex.exec(text);
    if(ref != null){
      if (ref[0].search(/[^\s]{150}/) != -1) {
        ref[0] = ref[0].replace(/\|([^\s])/g, "| $1");
      }
      ref[0] = ref[0].replace(/</g, "&lt;");
      ref[0] = ref[0].replace(/>/g, "&gt;");
      allrefs[i] = ref[0];
      i++;
    } else {
      nr=false;
    }
  } while (nr==true);
  return allrefs;
}

function NRcallError(namedrefs, refname) {
  for (var i=0; i<namedrefs.length; i++) {
    if (namedrefs[i] == refname) {
      return true;
    }
  }
  return false;
}

function errorCheck() {
  var allrefs = getAllRefs();
  var allrefscontent = new Array();
  var samecontentexclude = new Array();
  var sx=0;
  var templateexclude = new Array();
  var tx=0;
  var skipcheck = false;
  var namedrefcalls = getNamedRefs(true);
  for (var i=0; i<allrefs.length; i++) {
    allrefscontent[i] = allrefs[i].replace(/&lt; *?ref( +?name *?= *?(('([^']*?)')|("([^"]*?)")|([^'"\s]*?[^\/]\b)))? *?&gt;((.|\n)*?)&lt; *?\/? *?ref *?&gt;/gim, "$8");  //"
  }
  var namedrefs = getNamedRefs(false);
  var errorlist = new Array();
  var q=0;
  var unclosed = document.getElementById('unclosed').checked;
  var samecontent = document.getElementById('samecontent').checked;
  var templates = document.getElementById('templates').checked;
  var repeated = document.getElementById('repeated').checked;
  var undef = document.getElementById('undef').checked;
  for (var i=0; i<allrefs.length; i++) {
    if (allrefs[i].search(/&lt; *?\/ *?ref *?&gt;/) == -1 && unclosed) {
      errorlist[q] = '<tr><td width="75%"><tt>'+allrefs[i]+'</tt></td>';
      errorlist[q] += '<td width="25%">Unclosed <tt>&lt;ref&gt;</tt> tag</td></tr>';
      q++;
    }
    if (samecontent) {
      for (var d=0; d<samecontentexclude.length; d++) {
        if (allrefscontent[i] == samecontentexclude[d]) {
          skipcheck = true;
        }
      }
      var p=0;
      while (p<allrefs.length && !skipcheck) {
        if (allrefscontent[i] == allrefscontent[p] && i != p) {
          errorlist[q] = '<tr><td width="75%"><tt>'+allrefscontent[i]+'</tt></td>';
          errorlist[q] += '<td width="25%">Multiple refs contain this content, a <a href="//en.wikipedia.org/wiki/Wikipedia:Footnotes#Naming_a_ref_tag_so_it_can_be_used_more_than_once">named reference</a> should be used instead</td></tr>';
          q++;
          samecontentexclude[sx] = allrefscontent[i]
          sx++;
          break;
        }
        p++;
      }
     skipcheck=false;
    }
    if (templates) {
      if (allrefscontent[i].search(/\{\{cite/i) == -1 && allrefscontent[i].search(/\{\{citation/i) == -1 && allrefscontent[i].search(/\{\{Comic (book|strip) reference/i) == -1 && allrefscontent[i].search(/\{\{Editorial cartoon reference/i) == -1 && allrefscontent[i].search(/\{\{harv/i) == -1) {
        for (var x=0; x<templateexclude.length; x++) {
          if (allrefscontent[i] == templateexclude[x]) {
            skipcheck = true;
          }
        }
        if (!skipcheck) {
          errorlist[q] = '<tr><td width="75%"><tt>'+allrefs[i]+'</tt></td>';
          errorlist[q] += '<td width="25%">Does not use a <a href="//en.wikipedia.org/wiki/Wikipedia:Citation_templates">citation template</a></td></tr>';
          q++;
          templateexclude[tx] = allrefscontent[i];
          tx++;
        }
        skipcheck = false;
      }
    }
  }
  if (repeated) {
    var repeatnameexclude = new Array();
    var rx=0;
    for (var k=0; k<namedrefs.length; k++) {
      for (var d=0; d<repeatnameexclude.length; d++) {
        if (namedrefs[k] == repeatnameexclude[d]) {
          skipcheck = true;
        }
      }
      var z=0;
      while (z<namedrefs.length && !skipcheck) {
        if (namedrefs[k] == namedrefs[z] && k != z) {
          errorlist[q] = '<tr><td width="75%"><tt>'+namedrefs[k]+'</tt></td>';
          errorlist[q] += '<td width="25%">Multiple references are given the same <a href="//en.wikipedia.org/wiki/Wikipedia:Footnotes#Naming_a_ref_tag_so_it_can_be_used_more_than_once">name</a></td></tr>';
          q++;
          repeatnameexclude[rx] = namedrefs[z];
          rx++;
          break;
        }
        z++;
      }
     skipcheck = false;
    }
  }
  if (undef) {
    var undefexclude = new Array();
    var ux=0;
    for (var p=0; p<namedrefcalls.length; p++) {
      for (var d=0; d<undefexclude.length; d++) {
        if (allrefscontent[i] == undefexclude[d]) {
          skipcheck = true;
        }
      }
      if (!skipcheck) {
        if (!NRcallError(namedrefs, namedrefcalls[p])) {
          errorlist[q] = '<tr><td width="75%"><tt>'+namedrefcalls[p]+'</tt></td>';
          errorlist[q] += '<td width="25%">A <a href="//en.wikipedia.org/wiki/Wikipedia:Footnotes#Naming_a_ref_tag_so_it_can_be_used_more_than_once">named reference</a> is used but not defined</td></tr>';
          q++;
          undefexclude[ux] = namedrefs[p];
          ux++;
        }
      }
      skipcheck = false;
    }
 }
  if (q > 0) {
    return errorlist;
  } else {
    return 0;
  }
}

function dispErrors() {
  oldFormHide();
  var form = '<div id="errorform"><fieldset>'+
    '<legend>Error checking</legend>'+
    '<b>Check for:</b><br/>'+
    '<input type="checkbox" id="unclosed" /> Unclosed <tt>&lt;ref&gt;</tt> tags<br/>'+
    '<input type="checkbox" id="samecontent" /> References with the same content<br/>'+
    '<input type="checkbox" id="templates" /> References not using a <a href="//en.wikipedia.org/wiki/Wikipedia:Citation_templates">citation template</a><br/>'+
    '<input type="checkbox" id="repeated" /> Multiple references with the same name<br/>'+
    '<input type="checkbox" id="undef" /> Usage of undefined named references<br/>'+
    '<input type="button" id="errorchecksubmit" value="Check for selected errors" onclick="doErrorCheck()"/>'+
    '</fieldset></div>';
  document.getElementById('citeselect').innerHTML += form;
}

function doErrorCheck() {
  var errors = errorCheck();
  document.getElementById('citeselect').removeChild(document.getElementById('errorform'));
  if (errors == 0) {
    if (numforms != 0) {
      document.getElementById('citediv'+numforms).style.display = 'none';
    }
    numforms++;
    out = '<div id="citediv'+numforms+'"><fieldset>'+
      '<legend>Error checking</legend>No errors found.</fieldset></div>';
    document.getElementById('citeselect').innerHTML += out;
  }
  else {
    if (numforms != 0) {
      document.getElementById('citediv'+numforms).style.display = 'none';
    }
    numforms++;
    form = '<div id="citediv'+numforms+'">'+
      '<fieldset><legend>Error checking</legend>'+
      '<table border="1px">';
    for (var i=0; i<errors.length; i++) {
      form+=errors[i];
    }
    form+= '</table>'+
      '</fieldset></div>';
     document.getElementById('citeselect').innerHTML += form;
  }
}

function makeBookCitationCode(callback) {
  var cite = '<ref';
  var refname = document.getElementById('refname').value;
  if (/\S/.test(refname)) {
    cite += ' name="' + refname + '"';
  }
  cite += '>\{\{';
  
  if (document.getElementById('cite_book').checked || document.getElementById('plain').checked) {
    cite += 'cite book';
  }
  else if (document.getElementById('citation').checked) {
    cite += 'citation';
  }
  else {alert('No template selected.');}
  
  var authorcite = '';
  var prevauthor = 0;
  for (var i=3;i>=1;i--) {
    //var author = document.getElementById('author' + i).value;
    var last = document.getElementById('last' + i).value;
    var first = document.getElementById('first' + i).value;
    var authorlink = document.getElementById('authorlink' + i).value;
    if (i==1 && !prevauthor) { i = ''; }
    if (/\S/.test(authorlink)) {
      authorcite = '|authorlink' + i + '=' + authorlink + authorcite;
    }
    if (/\S/.test(last)) {
      authorcite = '|last' + i + '=' + last + '|first' + i + '=' + first + authorcite;
      prevauthor = 1;
    }
    /*else if (/\S/.test(author)) {
      authorcite = '|author' + i + '=' + author + authorcite;
      prevauthor = 1;
    }*/
  }
  cite += authorcite;

  var simplefields = ["coauthors", "editor", "others", "title", "url", "accessdate","edition","series","volume","date","publisher","location","language","isbn","pages","chapter"];
  for (var i=0;i<simplefields.length;i++) {
    var fieldname = simplefields[i];
    var value = document.getElementById(fieldname).value;
    if (/\S/.test(value) || fieldname == "title") {
      if (fieldname == "pages") {
        if (/^\w+$/.test(value)) {
          fieldname = "page";    //Use page= instead of pages= if only one page. Makes p. 5 instead of pp. 5.
        }
        else {
          value = value.replace(/-/g, "–");      //Replace hyphens with en dashes [[WP:ENDASH]]
          value = value.replace(/,\s*\s?/g, ", ");  //One space after each comma
        }
      }
      else if (fieldname == "date" && /^\d\d\d\d$/.test(value)) {
        fieldname = "year";  // Use year= instead of date= if only the year is specified
      }
      cite += '|' + fieldname + '=' + value;
    }
  }
 

  var otherfields = document.getElementById('otherfields').value;
  if (/\S/.test(otherfields)) {
    cite += '|' + otherfields;
  }
  
  if (document.getElementById('extraparams').checked) {
    cite += '|authormask=';
    if (!document.getElementById('citation').checked) {
      cite += '|trans_title=';
    }
    cite += '|format=';
    cite += '|origyear=';
    cite += '|oclc=';
    cite += '|doi=';
    cite += '|bibcode=';
    cite += '|id=';
    if (/\S/.test(document.getElementById('chapter').value)) {
      if (!document.getElementById('citation').checked) {
        cite += '|trans_chapter=';
      } 
      cite += '|chapterurl=';
    }
    cite += '|quote=';
    cite += '|laysummary=';
    cite += '|laydate=';
  }

  cite += "}}</ref>";
  
  
  if (document.getElementById('plain').checked) {
    var match = /^(.*?)(\{\{.*}})(.*?)$/.exec(cite);
    if (match) {
      var citebeg = match[1];
      var citemid = match[2];
      var citeend = match[3];
      citemid = citemid.replace(/cite book/, "Vancite book");
      //alert(citebeg + ':::' + citemid + ':::' + citeend);
      //document.getElementById('fullcite').value = 'Updating...';
      var url = 'api.php?action=expandtemplates&format=xml&text=' + encodeURIComponent(citemid);
      document.getElementById('progress').style.visibility = "visible";
      var xmlhttpExpand = new XMLHttpRequest();
      xmlhttpExpand.onreadystatechange=function() {
		if(xmlhttpExpand.readyState==4) {	  
			if(xmlhttpExpand.status==200) {
				document.getElementById('progress').style.visibility = "hidden";
				var xmlDoc=xmlhttpExpand.responseXML.documentElement;
				var expanded = xmlDoc.getElementsByTagName("expandtemplates")[0].textContent;
				if (expanded == undefined) {
					expanded = xmlDoc.getElementsByTagName("expandtemplates")[0].childNodes[0].nodeValue;
				}
				expanded = expanded.replace(/<span.*?>/ig, '');
				expanded = expanded.replace(/<\/span>/ig, '');
				expanded = expanded.replace(/<nowiki\/?>/ig, '');
				expanded = expanded.replace(/\&\#32\;/ig, ' ');
				expanded = expanded.replace(/\&\#59\;/ig, ';');
				expanded = expanded.replace(/\&\#91\;/ig, '[');
				expanded = expanded.replace(/\&\#93\;/ig, ']');
				
				plaincite = citebeg + expanded + citeend;
				//alert(plaincite);
				callback(plaincite);
			}
			else
				alert('The query returned an error.');
		}
      }
      xmlhttpExpand.open("GET",url,true);
      xmlhttpExpand.send(null);
    }
    else {alert('Error A1');}
  }
  else {
    if (document.getElementById('verbose').checked) {
      cite = cite.replace(/\|/g, "\n|");
    }
    callback(cite);
  }
}

function makeCiteBook() {
  makeBookCitationCode(function(cite) { 
    $("#wpTextbox1").focus();
    insertTags(cite, '', ''); 
    if (!refToolDebug) { oldFormHide(); }
  });
}

function formatDate(datein, dateformat) {
  if (dateformat == '') {return (datein);}
  datein = datein.replace(/^\s*(.*?)\s*$/, "$1");  //Trim whitespace
  var year = -1;
  var month = -1;
  var date = -1;
  var match = /^(\d\d\d\d)-(\d\d?)(-(\d\d?))?$/.exec(datein);
  if(match) {
    //alert(' match[1]=' + match[1] + ' match[2]=#' + match[2] + '# match[3]=' + match[3] + ' match[4]=' + match[4]  );
    year = parseInt(match[1], 10);	//10 forces decimal conversion
    month = parseInt(match[2], 10);
    if (match[4]) {
      date = parseInt(match[4], 10);
    }
  }
  else if (/^\d\d? \w+ \d\d\d\d$/.test(datein) || /^\w+ \d\d?, \d\d\d\d$/.test(datein)) {
    var DT = new Date(datein);
    year = DT.getUTCFullYear();
    month = DT.getUTCMonth()+1;
    date = DT.getUTCDate()+1;
  }
  else if (datein == 'today') {
    var DT = new Date();
    year = DT.getUTCFullYear();
    month = DT.getUTCMonth()+1;
    date = DT.getUTCDate();
  }
  else {return (datein);}
  //alert('datein=' + datein + ', y=' + year + ', m=' + month + ', d=' + date);

  var zmonth = '';
  if (month < 10) {
    zmonth = "0"+month.toString();
  } else {
    zmonth = month.toString();
  }
  month = month.toString();
  var zdate = '';
  if (date > -1) {
    if (date < 10) {
      zdate = "0"+date.toString();
    } else {
      zdate = date.toString();
    }
    date = date.toString()
  }
  else { date = ''; }
  
  var datestr = dateformat;
  datestr = datestr.replace('<date>', date);
  datestr = datestr.replace('<month>', month);
  datestr = datestr.replace('<zdate>', zdate);
  datestr = datestr.replace('<zmonth>', zmonth);
  datestr = datestr.replace('<monthname>', months[month-1]);
  datestr = datestr.replace('<year>', year.toString());
  datestr = datestr.replace(/\s+/, ' ').replace(/^\s+/, '').replace(/(\D),/, '$1').replace(/-$/, '');
  return (datestr);
}


function getDateFormat() {
	var dateformat = '';
	if (document.getElementById('dmy')){
		if (document.getElementById('dmy').checked) {dateformat = '<date> <monthname> <year>'}
		else if (document.getElementById('mdy').checked) {dateformat = '<monthname> <date>, <year>'}
		else if (document.getElementById('ymd').checked) {dateformat = '<year>-<zmonth>-<zdate>'}
	}
	else if (citeUserDateFormat) {
		dateformat = citeUserDateFormat;
	} else {
		dateformat = citeGlobalDateFormat;
	}
	return (dateformat);
}

function reformatDates() {
  var dateformat = getDateFormat();
  //alert(':' + dateformat + ':');
  document.getElementById('accessdate').value = formatDate(document.getElementById('accessdate').value, dateformat);
  document.getElementById('date').value = formatDate(document.getElementById('date').value, dateformat);
  //document.getElementById('dateformat_hidden').value = getDateFormatShort();
}

/*function updateGetButton() {
	document.getElementById('urlget').disabled = document.getElementById('url').value == '';
}*/

function preview(wikitext) {
    document.getElementById('progress').style.visibility = "visible";
    wikitext += '<references />';
    var url = "api.php?action=parse&format=xml&prop=text&text=" + encodeURIComponent(wikitext);
    var xmlhttp = new XMLHttpRequest();
	xmlhttp.onreadystatechange = function () {
		if (xmlhttp.readyState==4) {
			if(xmlhttp.status==200) {
				document.getElementById('progress').style.visibility = "hidden";
				var xmlDoc=xmlhttp.responseXML.documentElement;
				var previewHTML = xmlDoc.getElementsByTagName("text")[0].textContent;
				if (previewHTML == undefined) {
					previewHTML = xmlDoc.getElementsByTagName("text")[0].childNodes[0].nodeValue;
				}
				//alert(previewHTML);
				previewHTML = previewHTML.replace(/href="\//gi, 'href="//en.wikipedia.org/');
				document.getElementById('previewSpan').innerHTML = '<fieldset><legend>Citation preview</legend>' + previewHTML + '</fieldset>';
			}
			else
				alert('The query returned an error.');
		}
    };
    xmlhttp.open("GET", url, true);
    xmlhttp.send(null)
}

function previewCitationBook() {
  makeBookCitationCode(preview);
}

function previewCitationDefault() {
	var wikitext = makeCiteCode();
	preview(wikitext);
}

function pullJs() {
	var book_url = document.getElementById('url').value;
   	if (book_url) {
		document.getElementById('progress').style.visibility = "visible";
		var book_url_enc = encodeURIComponent(book_url);
		if(!refTagURL) {refTagURL = defaultRefTagURL;}
		var baseurl = refTagURL + 'googlebooksjs.py';
		var url = baseurl + '?book_url=' + book_url_enc + '&callback=setFormValues';
		/*var script = document.createElement("script");        
		script.setAttribute("src",url);
		script.setAttribute("type","text/javascript");                
		document.body.appendChild(script);*/
		JsonRequest(url);
	}else{
		alert('No URL.');
	}
}

function pullISBN() {
	var isbn = document.getElementById('isbn').value;
	isbn = isbn.replace(/[^0-9]/g,"");	//Digits only
   	if (isbn) {
		document.getElementById('progress').style.visibility = "visible";
		if(!refTagURL) {refTagURL = defaultRefTagURL;}
		var baseurl = refTagURL + 'getdiberri.py';
		var url = baseurl + '?isbn=' + isbn + '&callback=useDiberriData';
		/*var script = document.createElement("script");
		script.setAttribute("src",url);
		script.setAttribute("type","text/javascript");
		document.body.appendChild(script);*/
		JsonRequest(url);
	}else{
		alert('No ISBN.');
	}
}

function pullDOI() {
	var doi = document.getElementById('doi').value;
   	if (doi) {
		document.getElementById('progress').style.visibility = "visible";
		if(!refTagURL) {refTagURL = defaultRefTagURL;}
		var baseurl = refTagURL + 'doifetchjs.py';
		var url = baseurl + '?doi=' + encodeURIComponent(doi) + '&callback=useDoiData';
		JsonRequest(url);
	}else{
		alert('No DOI.');
	}
}

function pullPMID() {
	alert('Not implemented yet...');
	/*var doi = document.getElementById('doi').value;
   	if (doi) {
		document.getElementById('progress').style.visibility = "visible";
		if(!refTagURL) {refTagURL = defaultRefTagURL;}
		var baseurl = refTagURL + 'doifetchjs.py';
		var url = baseurl + '?doi=' + encodeURIComponent(doi) + '&callback=useDoiData';
		JsonRequest(url);
	}else{
		alert('No DOI.');
	}*/
}

function pullURL() {
	var url = document.getElementById('url').value;
   	if (url) {
		document.getElementById('progress').style.visibility = "visible";
		if(!refTagURL) {refTagURL = defaultRefTagURL;}
		var baseurl = refTagURL + 'urlfetchjs.py';
		var url = baseurl + '?url=' + encodeURIComponent(url) + '&callback=useUrlData';
		JsonRequest(url);
	}else{
		alert('No URl.');
	}
}

function JsonRequest(url) {
	//importScriptURI(url)  //Bad: does not import the same script more than once
	var script = document.createElement("script");        
	script.setAttribute("src",url);
	script.setAttribute("type","text/javascript");                
	//document.body.appendChild(script);
	document.getElementsByTagName('head')[0].appendChild(script);
}

function setFormValues(bookdata) {
	document.getElementById('progress').style.visibility = "hidden";
	//alert(bookdata);
	//alert(bookdata.page);
	if (bookdata.title.length != 0) { document.getElementById('title').value = bookdata.title; }
	if (bookdata.isbn.length != 0) { document.getElementById('isbn').value = bookdata.isbn; }
	if (bookdata.publisher.length != 0) { document.getElementById('publisher').value = bookdata.publisher; }
	if (bookdata.pages.length != 0) { 
		document.getElementById('pages').value = bookdata.pages; 
		document.getElementById('pages').style.backgroundColor = '#FFFF99';
	}
	if (bookdata.url.length != 0) { document.getElementById('url').value = bookdata.url; }
	if (bookdata.date.length != 0) { document.getElementById('date').value = bookdata.date; }

	for (var i=0;i<bookdata.authors.length && i<=2;i++) {
		authorn = i+1;
  		var author = bookdata.authors[i];
  		var match = /(.+)\s+(.+)/.exec(author);
		if (match) {
			document.getElementById('first' + authorn).value = match[1];
			document.getElementById('last' + authorn).value = match[2];
		}
		else {
			document.getElementById('last' + authorn).value = author;
		}
  	}
	document.getElementById('coauthors').value = bookdata.authors.splice(3).join(', ')
	setAccessDateToday()
	makeRefname()
}

function useDiberriData(bookdata) {
	document.getElementById('progress').style.visibility = "hidden";
	if (bookdata.title.length != 0) { document.getElementById('title').value = bookdata.title; }
	if (bookdata.isbn.length != 0) { document.getElementById('isbn').value = bookdata.isbn; }
	if (bookdata.publisher.length != 0) { document.getElementById('publisher').value = bookdata.publisher; }
	if (bookdata.location.length != 0) { document.getElementById('location').value = bookdata.location; }
	if (bookdata.year.length != 0) { document.getElementById('date').value = bookdata.year; }
	if (bookdata.authors.length != 0) {
		authors = bookdata.authors.split(';', 4);
		for (var i=0;i<authors.length && i<=2;i++) {
			authorn = i+1;
	  		nameparts = authors[i].split(',', 2);
			document.getElementById('last' + authorn).value = nameparts[0].trim();
			if (nameparts.length == 2) {
				document.getElementById('first' + authorn).value = nameparts[1].trim();
			}
		}
		if (authors[3]) { document.getElementById('coauthors').value = authors[3].trim(); }
	}
	makeRefname()	
}

function useDoiData(bookdata) {
	document.getElementById('progress').style.visibility = "hidden";
	if (bookdata.title) { document.getElementById('title').value = bookdata.title; }
	//if (bookdata.isbn.length != 0) { document.getElementById('isbn').value = bookdata.isbn; }
	//if (bookdata.publisher.length != 0) { document.getElementById('publisher').value = bookdata.publisher; }
	//if (bookdata.location.length != 0) { document.getElementById('location').value = bookdata.location; }
	if (bookdata.year) { document.getElementById('date').value = bookdata.year; }
	if (bookdata.issn) { document.getElementById('issn').value = bookdata.issn; }
	if (bookdata.journal) { document.getElementById('journal').value = bookdata.journal; }
	if (bookdata.volume) { document.getElementById('volume').value = bookdata.volume; }
	if (bookdata.issue) { document.getElementById('issue').value = bookdata.issue; }
	if (bookdata.pages) { document.getElementById('pages').value = bookdata.pages; }

	if (bookdata.authors) {
		var coauthors = [];
		for (var i=0;i<bookdata.authors.length;i++) {
			var authorn = i+1;
			var author = bookdata.authors[i];
			if (authorn == 1) {
				if (author.last) { document.getElementById('last').value = author.last.trim(); }
				if (author.first) { document.getElementById('first').value = author.first.trim(); }
			}
			else {
				var authorparts = [];
				if (author.first) { authorparts.push( author.first.trim() ); }
				if (author.last) { authorparts.push( author.last.trim() ); }
				coauthors.push(authorparts.join(' '));
			}
		}
		if (coauthors[0]) { document.getElementById('coauthors').value = coauthors.join(', '); }
	}
	makeRefname();
}

function useUrlData(data) {
	document.getElementById('progress').style.visibility = "hidden";
	if (data.title) { document.getElementById('title').value = data.title; }
	if (data.work) { document.getElementById('work').value = data.work; }
	if (data.page) { document.getElementById('pages').value = data.page; }
	if (data.date) {
		document.getElementById('date').value = formatDate(data.date, getDateFormat());
	}
	/*if (data.author) {
		var authors = data.author.replace(/ [Aa]nd /, ', ');
		var match = /(.+),\s*(.+)/.exec(authors);
		var firstauthor = '';
		if (match) {
			firstauthor = match[1];
			var coauthors = match[2];
			document.getElementById('coauthors').value = coauthors;
		}
		else {
			firstauthor = data.author;
		}
		var match = /(.+)\s+(.+)/.exec(firstauthor);
		if (match) {
			document.getElementById('first').value = match[1];
			document.getElementById('last').value = match[2];
		}
		else {
			document.getElementById('last').value = author;
		}
	}*/
	if (data.authors) {
		var coauthors = [];
		for (var i=0;i<data.authors.length;i++) {
			var authorn = i+1;
			var author = data.authors[i];
			if (authorn == 1) {
				var match = /(.+)\s+(.+)/.exec(author);
				if (match) {
					document.getElementById('first').value = match[1].trim();
					document.getElementById('last').value = match[2].trim();
				}
				else {
					document.getElementById('last').value = author.trim();
				}
			}
			else {
				coauthors.push(author);
			}
		}
		if (coauthors[0]) { document.getElementById('coauthors').value = coauthors.join(', '); }
	}
}

$( refbuttons );