Add
 
No edit summary
Line 1: Line 1:
/**
/**
  * Citoid for Bharatpedia (BharatpediaNeo)
  * Citoid for Bharatpedia / BharatpediaNeo
  * Generates a CS1 <ref>{{cite …}}</ref> from a URL via Wikimedia Citoid.
  * Safe on wikitext-model .js pages (no HTML tag literals).
*
* Adapted from User:Salix alba/Citoid.js (enwiki)
* and User:Mvolz/veCiteFromURL.js
*
* Install in User:WikiDwarf/common.js:
*  mw.loader.load('/w/index.php?title=User:WikiDwarf/Citoid.js&action=raw&ctype=text/javascript');
*
* @version 1.1-bpneo
  */
  */
( function ( $, mw ) {
( function ( $, mw ) {
Line 15: Line 7:


var CITOID_ENDPOINT = 'https://en.wikipedia.org/api/rest_v1/data/citation/mediawiki/';
var CITOID_ENDPOINT = 'https://en.wikipedia.org/api/rest_v1/data/citation/mediawiki/';
var lang = mw.config.get( 'wgUserLanguage' ) || 'en';
var msg = {
'toolbox-label': 'Citoid',
'toolbox-tooltip': 'Generate a Bharatpedia reference from a URL',
title: 'Citoid – Bharatpedia',
close: 'Close',
generate: 'Generate citation',
urlLabel: 'URL',
dateLabel: 'Date format',
codeLabel: 'Template code',
rawLabel: 'Raw Citoid data',
monthnames: [
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
]
};
var lastUrl = '';


var messages = {
function el( tag, attrs, text ) {
en: {
var node = document.createElement( tag );
'toolbox-label': 'Citoid',
var k;
'toolbox-tooltip': 'Generate a Bharatpedia reference from a URL',
attrs = attrs || {};
title: 'Citoid – Bharatpedia',
for ( k in attrs ) {
close: 'Close',
if ( Object.prototype.hasOwnProperty.call( attrs, k ) ) {
generate: 'Generate citation',
node.setAttribute( k, attrs[ k ] );
urlLabel: 'URL',
}
dateLabel: 'Date format',
codeLabel: 'Template code',
rawLabel: 'Raw Citoid data',
monthnames: [
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
]
}
}
};
if ( text ) {
if ( !messages[ lang ] ) {
node.textContent = text;
lang = 'en';
}
return node;
}
}
var msg = messages[ lang ];
var lastUrl = '';


function escapePipes( val ) {
function escapePipes( val ) {
Line 51: Line 50:
return '';
return '';
}
}
var style = $( 'input:radio[name=citoid-datestyle]:checked' ).val() || 'DMY';
var style = $( 'input[name=citoid-datestyle]:checked' ).val() || 'DMY';
var day = '', month = 0, year = '', daynum = '', monthnum = '';
var raw = String( isodate );
var raw = String( isodate );
var test1 = raw.match( /(\d{4})-(\d{2})-(\d{2})/ );
var test1 = raw.match( /(\d{4})-(\d{2})-(\d{2})/ );
var test2 = raw.match( /([A-Z][a-z]+) (\d+), (\d{4})/ );
var test2 = raw.match( /([A-Z][a-z]+) (\d+), (\d{4})/ );
var test3 = raw.match( /(\d{4})-(\d{2})(?:$|[^\d])/ );
var test3 = raw.match( /(\d{4})-(\d{2})(?:$|[^\d])/ );
var day, month, year, daynum, monthnum, index;


if ( test1 ) {
if ( test1 ) {
Line 69: Line 67:
day = parseInt( test2[ 2 ], 10 );
day = parseInt( test2[ 2 ], 10 );
daynum = day < 10 ? '0' + day : String( day );
daynum = day < 10 ? '0' + day : String( day );
var index = messages.en.monthnames.indexOf( test2[ 1 ] ) + 1;
index = msg.monthnames.indexOf( test2[ 1 ] ) + 1;
if ( index < 1 ) {
if ( index < 1 ) {
return raw;
return raw;
Line 100: Line 98:


var templateTypeMap = {
var templateTypeMap = {
book: 'Cite book',
book: 'Cite book', bookSection: 'Cite book',
bookSection: 'Cite book',
journalArticle: 'Cite journal', magazineArticle: 'Cite news',
journalArticle: 'Cite journal',
newspaperArticle: 'Cite news', thesis: 'Cite journal',
magazineArticle: 'Cite news',
webpage: 'Cite web', blogPost: 'Cite web', forumPost: 'Cite web',
newspaperArticle: 'Cite news',
email: 'Cite web', report: 'Cite journal',
thesis: 'Cite journal',
conferencePaper: 'Cite journal', encyclopediaArticle: 'Cite journal',
letter: 'Citation',
dictionaryEntry: 'Cite journal', presentation: 'Cite journal'
manuscript: 'Cite book',
interview: 'Citation',
film: 'Citation',
artwork: 'Citation',
webpage: 'Cite web',
report: 'Cite journal',
bill: 'Citation',
hearing: 'Citation',
patent: 'Citation',
statute: 'Citation',
email: 'Cite web',
map: 'Citation',
blogPost: 'Cite web',
instantMessage: 'Citation',
forumPost: 'Cite web',
audioRecording: 'Citation',
presentation: 'Cite journal',
videoRecording: 'Citation',
tvBroadcast: 'Citation',
radioBroadcast: 'Citation',
podcast: 'Citation',
computerProgram: 'Citation',
conferencePaper: 'Cite journal',
document: 'Citation',
encyclopediaArticle: 'Cite journal',
dictionaryEntry: 'Cite journal'
};
 
var citationParams = {
first1: 'author1-first', last1: 'author1-last',
first2: 'author2-first', last2: 'author2-last',
first3: 'author3-first', last3: 'author3-last',
first4: 'author4-first', last4: 'author4-last',
title: 'title', url: 'url', publisher: 'publisher',
journal: 'publicationTitle', date: 'date', location: 'place',
issn: 'ISSN', isbn: 'ISBN', pages: 'pages', volume: 'volume',
series: 'series', issue: 'issue', via: 'libraryCatalog',
pmid: 'PMID', pmc: 'PMCID', doi: 'DOI'
};
};


Line 152: Line 112:
first3: 'author3-first', last3: 'author3-last',
first3: 'author3-first', last3: 'author3-last',
first4: 'author4-first', last4: 'author4-last',
first4: 'author4-first', last4: 'author4-last',
'access-date': 'accessDate',
'access-date': 'accessDate', title: 'title', url: 'url',
title: 'title', url: 'url', date: 'date',
date: 'date', publisher: 'publisher', via: 'libraryCatalog',
publisher: 'publisher', via: 'libraryCatalog',
website: 'publicationTitle'
website: 'publicationTitle'
};
};
Line 163: Line 122:
first3: 'author3-first', last3: 'author3-last',
first3: 'author3-first', last3: 'author3-last',
first4: 'author4-first', last4: 'author4-last',
first4: 'author4-first', last4: 'author4-last',
'access-date': 'accessDate',
'access-date': 'accessDate', title: 'title', url: 'url',
title: 'title', url: 'url', publisher: 'publisher',
publisher: 'publisher', newspaper: 'publicationTitle', date: 'date',
newspaper: 'publicationTitle', date: 'date', location: 'place',
location: 'place', issn: 'ISSN', pages: 'pages', volume: 'volume',
issn: 'ISSN', isbn: 'ISBN', pages: 'pages', volume: 'volume',
issue: 'issue', via: 'libraryCatalog', doi: 'DOI'
series: 'series', issue: 'issue', via: 'libraryCatalog', doi: 'DOI'
};
};


var bookParams = {
var journalParams = {
first1: 'author1-first', last1: 'author1-last',
first1: 'author1-first', last1: 'author1-last',
first2: 'author2-first', last2: 'author2-last',
first2: 'author2-first', last2: 'author2-last',
Line 178: Line 136:
journal: 'publicationTitle', date: 'date', location: 'place',
journal: 'publicationTitle', date: 'date', location: 'place',
issn: 'ISSN', isbn: 'ISBN', pages: 'pages', volume: 'volume',
issn: 'ISSN', isbn: 'ISBN', pages: 'pages', volume: 'volume',
series: 'series', issue: 'issue', via: 'libraryCatalog', doi: 'DOI'
issue: 'issue', pmid: 'PMID', pmc: 'PMCID', doi: 'DOI'
};
};


var journalParams = {
var bookParams = {
first1: 'author1-first', last1: 'author1-last',
first1: 'author1-first', last1: 'author1-last',
first2: 'author2-first', last2: 'author2-last',
first2: 'author2-first', last2: 'author2-last',
Line 189: Line 147:
journal: 'publicationTitle', date: 'date', location: 'place',
journal: 'publicationTitle', date: 'date', location: 'place',
issn: 'ISSN', isbn: 'ISBN', pages: 'pages', volume: 'volume',
issn: 'ISSN', isbn: 'ISBN', pages: 'pages', volume: 'volume',
series: 'series', issue: 'issue',
series: 'series', via: 'libraryCatalog', doi: 'DOI'
pmid: 'PMID', pmc: 'PMCID', doi: 'DOI'
};
};


var templateParamMap = {
var templateParamMap = {
Citation: citationParams,
'Cite web': webParams,
'Cite web': webParams,
'Cite news': newsParams,
'Cite news': newsParams,
'Cite journal': journalParams,
'Cite journal': journalParams,
'Cite book': bookParams
'Cite book': bookParams,
Citation: journalParams
};
};


Line 206: Line 163:
var paramMap = templateParamMap[ templateName ] || webParams;
var paramMap = templateParamMap[ templateName ] || webParams;
var paramObj = {};
var paramObj = {};
var authors, i, n, pair;


if ( !citation.url ) {
if ( !citation.url ) {
Line 221: Line 179:
} );
} );


var authors = citation.author;
authors = citation.author;
if ( $.isArray( authors ) ) {
if ( $.isArray( authors ) ) {
for ( var i = 0; i < authors.length; i++ ) {
for ( i = 0; i < authors.length; i++ ) {
var n = i + 1;
n = i + 1;
var pair = authors[ i ] || [];
pair = authors[ i ] || [];
paramObj[ 'first' + n ] = { wt: escapePipes( pair[ 0 ] ) };
paramObj[ 'first' + n ] = { wt: escapePipes( pair[ 0 ] ) };
paramObj[ 'last' + n ] = { wt: escapePipes( pair[ 1 ] ) };
paramObj[ 'last' + n ] = { wt: escapePipes( pair[ 1 ] ) };
Line 238: Line 196:
}
}


return {
return { templateName: templateName.toLowerCase(), params: paramObj };
templateName: templateName.toLowerCase(),
href: 'Template:' + templateName,
params: paramObj
};
}
}


Line 248: Line 202:
var res = '<ref>{{' + obj.templateName;
var res = '<ref>{{' + obj.templateName;
$.each( obj.params, function ( key, value ) {
$.each( obj.params, function ( key, value ) {
var wt = value && value.wt;
if ( value && value.wt ) {
if ( wt ) {
res += '|' + key + '=' + value.wt;
res += '|' + key + '=' + wt;
}
}
} );
} );
Line 264: Line 217:
}
}
lastUrl = url;
lastUrl = url;
$( '#citoid-code' ).val( 'Loading…' );
$( '#citoid-code' ).val( 'Loading...' );
$( '#citoid-full' ).val( '' );
$( '#citoid-full' ).val( '' );


Line 272: Line 225:
dataType: 'json',
dataType: 'json',
success: function ( result ) {
success: function ( result ) {
var plain = getPlainObject( lastUrl, result );
$( '#citoid-code' ).val( buildTemplateCode( getPlainObject( lastUrl, result ) ) );
$( '#citoid-code' ).val( buildTemplateCode( plain ) );
$( '#citoid-full' ).val( JSON.stringify( result, null, 2 ) );
$( '#citoid-full' ).val( JSON.stringify( result, null, 2 ) );
},
},
Line 288: Line 240:
$( '#citoid-cont' ).fadeIn( 'fast' );
$( '#citoid-cont' ).fadeIn( 'fast' );
$( '#citoid-url' ).trigger( 'focus' );
$( '#citoid-url' ).trigger( 'focus' );
}
function closeDialog() {
$( '#citoid-cont' ).fadeOut( 'fast' );
}
}


function injectCSS() {
function injectCSS() {
mw.util.addCSS(
mw.util.addCSS(
'#citoid-cont{position:fixed;z-index:2000;inset:8% 10%;' +
'#citoid-cont{position:fixed;z-index:2000;inset:8% 10%;background:#fff;color:#202122;border:1px solid #a2a9b1;box-shadow:0 2px 16px rgba(0,0,0,.25);padding:12px 16px;overflow:auto;}' +
'background:var(--color-surface-1,#fff);color:var(--color-base,#202122);' +
'border:1px solid var(--border-color-base,#a2a9b1);' +
'box-shadow:0 2px 16px rgba(0,0,0,.25);padding:12px 16px;overflow:auto;}' +
'#citoid-dialog h2{margin:0 32px 8px 0;font-size:1.25em;}' +
'#citoid-dialog h2{margin:0 32px 8px 0;font-size:1.25em;}' +
'#citoid-close{position:absolute;top:10px;right:12px;font-size:22px;line-height:1;text-decoration:none;}' +
'#citoid-close{position:absolute;top:10px;right:12px;font-size:22px;text-decoration:none;}' +
'#citoid-url{width:98%;max-width:100%;}' +
'#citoid-url,#citoid-code,#citoid-full{width:98%;}' +
'#citoid-code,#citoid-full{width:98%;min-height:8em;font-family:monospace;font-size:12px;}' +
'#citoid-code,#citoid-full{min-height:8em;font-family:monospace;font-size:12px;}' +
'#citoid-button{margin:8px 0;}' +
'#citoid-button{margin:8px 0;}' +
'#citoid-floating{position:fixed;right:16px;bottom:16px;z-index:2001;}'
'#citoid-floating{position:fixed;right:16px;bottom:16px;z-index:2001;}'
);
);
}
function radio( value, label, checked ) {
var wrap = el( 'label' );
var input = el( 'input', { type: 'radio', name: 'citoid-datestyle', value: value } );
if ( checked ) {
input.checked = true;
}
wrap.appendChild( input );
wrap.appendChild( document.createTextNode( ' ' + label ) );
return wrap;
}
}


function buildHTML() {
function buildHTML() {
var $button = $( '<button>' )
var cont = el( 'div', { id: 'citoid-cont' } );
.attr( { id: 'citoid-button', type: 'button' } )
var dialog = el( 'div', { id: 'citoid-dialog' } );
.text( msg.generate )
var close = el( 'a', { id: 'citoid-close', href: '#' }, '×' );
.on( 'click', callCitoid );
var body = el( 'div', { id: 'citoid-body' } );
var urlP = el( 'p' );
var dateP = el( 'p' );
var gen = el( 'button', { id: 'citoid-button', type: 'button' }, msg.generate );
var code = el( 'textarea', { id: 'citoid-code' } );
var full = el( 'textarea', { id: 'citoid-full' } );
 
cont.style.display = 'none';
close.onclick = function ( e ) {
e.preventDefault();
$( cont ).fadeOut( 'fast' );
};
gen.onclick = callCitoid;


var $body = $( '<div>' ).attr( 'id', 'citoid-body' )
urlP.appendChild( document.createTextNode( msg.urlLabel + ': ' ) );
.append( $( '<p>' ).append(
urlP.appendChild( el( 'input', { type: 'text', id: 'citoid-url', size: '80' } ) );
document.createTextNode( msg.urlLabel + ': ' ),
$( '<input>' ).attr( { type: 'text', id: 'citoid-url', size: 80 } )
) )
.append( $( '<p>' ).append(
document.createTextNode( msg.dateLabel + ': ' ),
$( '<label>' ).append(
$( '<input>' ).attr( { type: 'radio', name: 'citoid-datestyle', value: 'DMY', checked: true } ),
' 1 September 2014'
),
'  ',
$( '<label>' ).append(
$( '<input>' ).attr( { type: 'radio', name: 'citoid-datestyle', value: 'MDY' } ),
' September 1, 2014'
),
'  ',
$( '<label>' ).append(
$( '<input>' ).attr( { type: 'radio', name: 'citoid-datestyle', value: 'YMD' } ),
' 2014-09-01'
)
) )
.append( $button )
.append( $( '<p>' ).text( msg.codeLabel ) )
.append( $( '<textarea>' ).attr( { id: 'citoid-code' } ) )
.append( $( '<p>' ).text( msg.rawLabel ) )
.append( $( '<textarea>' ).attr( { id: 'citoid-full' } ) );


var $cont = $( '<div>' )
dateP.appendChild( document.createTextNode( msg.dateLabel + ': ' ) );
.attr( 'id', 'citoid-cont' )
dateP.appendChild( radio( 'DMY', '1 September 2014', true ) );
.append(
dateP.appendChild( document.createTextNode( ' ' ) );
$( '<div>' ).attr( 'id', 'citoid-dialog' ).append(
dateP.appendChild( radio( 'MDY', 'September 1, 2014', false ) );
$( '<h2>' ).text( msg.title ),
dateP.appendChild( document.createTextNode( ' ' ) );
$( '<a>' ).attr( {
dateP.appendChild( radio( 'YMD', '2014-09-01', false ) );
id: 'citoid-close',
href: '#',
title: msg.close
} ).on( 'click', function ( e ) {
e.preventDefault();
closeDialog();
} ).text( '×' ),
$body
)
)
.hide();


$( document.body ).append( $cont );
dialog.appendChild( el( 'h2', {}, msg.title ) );
dialog.appendChild( close );
body.appendChild( urlP );
body.appendChild( dateP );
body.appendChild( gen );
body.appendChild( el( 'p', {}, msg.codeLabel ) );
body.appendChild( code );
body.appendChild( el( 'p', {}, msg.rawLabel ) );
body.appendChild( full );
dialog.appendChild( body );
cont.appendChild( dialog );
document.body.appendChild( cont );
}
}


Line 375: Line 318:


function addEntryPoint() {
function addEntryPoint() {
var $slot = $( '#antivandal-slot' );
var node, i, portlets, btn;
if ( $slot.length && !$( '#t-citoid' ).length ) {
portlets = [ 'p-cactions', 'p-views', 'p-tb' ];
var $slotBtn = $( '<button>' )
 
.attr( { type: 'button', id: 't-citoid', title: msg[ 'toolbox-tooltip' ] } )
btn = el( 'button', {
.text( msg[ 'toolbox-label' ] );
type: 'button',
$slot.append( $slotBtn );
id: 't-citoid',
bindOpener( $slotBtn.get( 0 ) );
title: msg[ 'toolbox-tooltip' ]
}, msg[ 'toolbox-label' ] );
 
if ( document.getElementById( 'antivandal-slot' ) && !document.getElementById( 't-citoid' ) ) {
document.getElementById( 'antivandal-slot' ).appendChild( btn );
bindOpener( btn );
return;
return;
}
}


var portlets = [ 'p-cactions', 'p-views', 'p-tb' ];
node = null;
var node = null;
var i;
for ( i = 0; i < portlets.length; i++ ) {
for ( i = 0; i < portlets.length; i++ ) {
node = mw.util.addPortletLink(
node = mw.util.addPortletLink(
portlets[ i ],
portlets[ i ], '#', msg[ 'toolbox-label' ], 't-citoid', msg[ 'toolbox-tooltip' ]
'#',
msg[ 'toolbox-label' ],
't-citoid',
msg[ 'toolbox-tooltip' ]
);
);
if ( node ) {
if ( node ) {
Line 402: Line 344:


if ( !node ) {
if ( !node ) {
node = $( '<button>' )
btn.id = 'citoid-floating';
.attr( { type: 'button', id: 'citoid-floating', title: msg[ 'toolbox-tooltip' ] } )
document.body.appendChild( btn );
.text( msg[ 'toolbox-label' ] )
node = btn;
.appendTo( document.body )
.get( 0 );
}
}
bindOpener( node );
bindOpener( node );
}
}

Revision as of 18:08, 24 September 2026

/**
 * Citoid for Bharatpedia / BharatpediaNeo
 * Safe on wikitext-model .js pages (no HTML tag literals).
 */
( function ( $, mw ) {
	'use strict';

	var CITOID_ENDPOINT = 'https://en.wikipedia.org/api/rest_v1/data/citation/mediawiki/';
	var msg = {
		'toolbox-label': 'Citoid',
		'toolbox-tooltip': 'Generate a Bharatpedia reference from a URL',
		title: 'Citoid – Bharatpedia',
		close: 'Close',
		generate: 'Generate citation',
		urlLabel: 'URL',
		dateLabel: 'Date format',
		codeLabel: 'Template code',
		rawLabel: 'Raw Citoid data',
		monthnames: [
			'January', 'February', 'March', 'April', 'May', 'June',
			'July', 'August', 'September', 'October', 'November', 'December'
		]
	};
	var lastUrl = '';

	function el( tag, attrs, text ) {
		var node = document.createElement( tag );
		var k;
		attrs = attrs || {};
		for ( k in attrs ) {
			if ( Object.prototype.hasOwnProperty.call( attrs, k ) ) {
				node.setAttribute( k, attrs[ k ] );
			}
		}
		if ( text ) {
			node.textContent = text;
		}
		return node;
	}

	function escapePipes( val ) {
		if ( val === undefined || val === null ) {
			return '';
		}
		return String( val ).replace( /\|/g, '-' );
	}

	function formatCS1Date( isodate ) {
		if ( !isodate ) {
			return '';
		}
		var style = $( 'input[name=citoid-datestyle]:checked' ).val() || 'DMY';
		var raw = String( isodate );
		var test1 = raw.match( /(\d{4})-(\d{2})-(\d{2})/ );
		var test2 = raw.match( /([A-Z][a-z]+) (\d+), (\d{4})/ );
		var test3 = raw.match( /(\d{4})-(\d{2})(?:$|[^\d])/ );
		var day, month, year, daynum, monthnum, index;

		if ( test1 ) {
			year = test1[ 1 ];
			monthnum = test1[ 2 ];
			daynum = test1[ 3 ];
			day = parseInt( daynum, 10 );
			month = parseInt( monthnum, 10 ) - 1;
		} else if ( test2 ) {
			year = test2[ 3 ];
			day = parseInt( test2[ 2 ], 10 );
			daynum = day < 10 ? '0' + day : String( day );
			index = msg.monthnames.indexOf( test2[ 1 ] ) + 1;
			if ( index < 1 ) {
				return raw;
			}
			monthnum = index < 10 ? '0' + index : String( index );
			month = index - 1;
		} else if ( test3 ) {
			year = test3[ 1 ];
			monthnum = test3[ 2 ];
			month = parseInt( monthnum, 10 ) - 1;
			if ( style === 'MDY' ) {
				return msg.monthnames[ month ] + ', ' + year;
			}
			if ( style === 'YMD' ) {
				return year + '-' + monthnum;
			}
			return msg.monthnames[ month ] + ' ' + year;
		} else {
			return raw;
		}

		if ( style === 'MDY' ) {
			return msg.monthnames[ month ] + ' ' + day + ', ' + year;
		}
		if ( style === 'YMD' ) {
			return year + '-' + monthnum + '-' + daynum;
		}
		return day + ' ' + msg.monthnames[ month ] + ' ' + year;
	}

	var templateTypeMap = {
		book: 'Cite book', bookSection: 'Cite book',
		journalArticle: 'Cite journal', magazineArticle: 'Cite news',
		newspaperArticle: 'Cite news', thesis: 'Cite journal',
		webpage: 'Cite web', blogPost: 'Cite web', forumPost: 'Cite web',
		email: 'Cite web', report: 'Cite journal',
		conferencePaper: 'Cite journal', encyclopediaArticle: 'Cite journal',
		dictionaryEntry: 'Cite journal', presentation: 'Cite journal'
	};

	var webParams = {
		first1: 'author1-first', last1: 'author1-last',
		first2: 'author2-first', last2: 'author2-last',
		first3: 'author3-first', last3: 'author3-last',
		first4: 'author4-first', last4: 'author4-last',
		'access-date': 'accessDate', title: 'title', url: 'url',
		date: 'date', publisher: 'publisher', via: 'libraryCatalog',
		website: 'publicationTitle'
	};

	var newsParams = {
		first1: 'author1-first', last1: 'author1-last',
		first2: 'author2-first', last2: 'author2-last',
		first3: 'author3-first', last3: 'author3-last',
		first4: 'author4-first', last4: 'author4-last',
		'access-date': 'accessDate', title: 'title', url: 'url',
		publisher: 'publisher', newspaper: 'publicationTitle', date: 'date',
		location: 'place', issn: 'ISSN', pages: 'pages', volume: 'volume',
		issue: 'issue', via: 'libraryCatalog', doi: 'DOI'
	};

	var journalParams = {
		first1: 'author1-first', last1: 'author1-last',
		first2: 'author2-first', last2: 'author2-last',
		first3: 'author3-first', last3: 'author3-last',
		first4: 'author4-first', last4: 'author4-last',
		title: 'title', url: 'url', publisher: 'publisher',
		journal: 'publicationTitle', date: 'date', location: 'place',
		issn: 'ISSN', isbn: 'ISBN', pages: 'pages', volume: 'volume',
		issue: 'issue', pmid: 'PMID', pmc: 'PMCID', doi: 'DOI'
	};

	var bookParams = {
		first1: 'author1-first', last1: 'author1-last',
		first2: 'author2-first', last2: 'author2-last',
		first3: 'author3-first', last3: 'author3-last',
		first4: 'author4-first', last4: 'author4-last',
		title: 'title', url: 'url', publisher: 'publisher',
		journal: 'publicationTitle', date: 'date', location: 'place',
		issn: 'ISSN', isbn: 'ISBN', pages: 'pages', volume: 'volume',
		series: 'series', via: 'libraryCatalog', doi: 'DOI'
	};

	var templateParamMap = {
		'Cite web': webParams,
		'Cite news': newsParams,
		'Cite journal': journalParams,
		'Cite book': bookParams,
		Citation: journalParams
	};

	function getPlainObject( url, searchResults ) {
		var citation = ( searchResults && searchResults[ 0 ] ) ? searchResults[ 0 ] : {};
		var templateName = templateTypeMap[ citation.itemType ] || 'Cite web';
		var paramMap = templateParamMap[ templateName ] || webParams;
		var paramObj = {};
		var authors, i, n, pair;

		if ( !citation.url ) {
			citation.url = url;
		}
		if ( citation.PMCID ) {
			citation.url = null;
		}
		if ( citation.websiteTitle ) {
			citation.publicationTitle = citation.websiteTitle;
		}

		$.each( paramMap, function ( key, value ) {
			paramObj[ key ] = { wt: escapePipes( citation[ value ] ) };
		} );

		authors = citation.author;
		if ( $.isArray( authors ) ) {
			for ( i = 0; i < authors.length; i++ ) {
				n = i + 1;
				pair = authors[ i ] || [];
				paramObj[ 'first' + n ] = { wt: escapePipes( pair[ 0 ] ) };
				paramObj[ 'last' + n ] = { wt: escapePipes( pair[ 1 ] ) };
			}
		}

		if ( paramObj.date && paramObj.date.wt ) {
			paramObj.date.wt = formatCS1Date( paramObj.date.wt );
		}
		if ( paramObj[ 'access-date' ] && paramObj[ 'access-date' ].wt ) {
			paramObj[ 'access-date' ].wt = formatCS1Date( paramObj[ 'access-date' ].wt );
		}

		return { templateName: templateName.toLowerCase(), params: paramObj };
	}

	function buildTemplateCode( obj ) {
		var res = '<ref>{{' + obj.templateName;
		$.each( obj.params, function ( key, value ) {
			if ( value && value.wt ) {
				res += '|' + key + '=' + value.wt;
			}
		} );
		res += '}}</ref>';
		return res;
	}

	function callCitoid() {
		var url = $.trim( $( '#citoid-url' ).val() );
		if ( !url ) {
			mw.notify( 'Enter a URL first.' );
			return;
		}
		lastUrl = url;
		$( '#citoid-code' ).val( 'Loading...' );
		$( '#citoid-full' ).val( '' );

		$.ajax( {
			url: CITOID_ENDPOINT + encodeURIComponent( url ),
			type: 'GET',
			dataType: 'json',
			success: function ( result ) {
				$( '#citoid-code' ).val( buildTemplateCode( getPlainObject( lastUrl, result ) ) );
				$( '#citoid-full' ).val( JSON.stringify( result, null, 2 ) );
			},
			error: function ( xhr, textStatus, errorThrown ) {
				var detail = textStatus + ( errorThrown ? ': ' + errorThrown : '' );
				mw.notify( 'Citoid failed — ' + detail );
				$( '#citoid-code' ).val( '' );
				$( '#citoid-full' ).val( detail );
			}
		} );
	}

	function openDialog() {
		$( '#citoid-cont' ).fadeIn( 'fast' );
		$( '#citoid-url' ).trigger( 'focus' );
	}

	function injectCSS() {
		mw.util.addCSS(
			'#citoid-cont{position:fixed;z-index:2000;inset:8% 10%;background:#fff;color:#202122;border:1px solid #a2a9b1;box-shadow:0 2px 16px rgba(0,0,0,.25);padding:12px 16px;overflow:auto;}' +
			'#citoid-dialog h2{margin:0 32px 8px 0;font-size:1.25em;}' +
			'#citoid-close{position:absolute;top:10px;right:12px;font-size:22px;text-decoration:none;}' +
			'#citoid-url,#citoid-code,#citoid-full{width:98%;}' +
			'#citoid-code,#citoid-full{min-height:8em;font-family:monospace;font-size:12px;}' +
			'#citoid-button{margin:8px 0;}' +
			'#citoid-floating{position:fixed;right:16px;bottom:16px;z-index:2001;}'
		);
	}

	function radio( value, label, checked ) {
		var wrap = el( 'label' );
		var input = el( 'input', { type: 'radio', name: 'citoid-datestyle', value: value } );
		if ( checked ) {
			input.checked = true;
		}
		wrap.appendChild( input );
		wrap.appendChild( document.createTextNode( ' ' + label ) );
		return wrap;
	}

	function buildHTML() {
		var cont = el( 'div', { id: 'citoid-cont' } );
		var dialog = el( 'div', { id: 'citoid-dialog' } );
		var close = el( 'a', { id: 'citoid-close', href: '#' }, '×' );
		var body = el( 'div', { id: 'citoid-body' } );
		var urlP = el( 'p' );
		var dateP = el( 'p' );
		var gen = el( 'button', { id: 'citoid-button', type: 'button' }, msg.generate );
		var code = el( 'textarea', { id: 'citoid-code' } );
		var full = el( 'textarea', { id: 'citoid-full' } );

		cont.style.display = 'none';
		close.onclick = function ( e ) {
			e.preventDefault();
			$( cont ).fadeOut( 'fast' );
		};
		gen.onclick = callCitoid;

		urlP.appendChild( document.createTextNode( msg.urlLabel + ': ' ) );
		urlP.appendChild( el( 'input', { type: 'text', id: 'citoid-url', size: '80' } ) );

		dateP.appendChild( document.createTextNode( msg.dateLabel + ': ' ) );
		dateP.appendChild( radio( 'DMY', '1 September 2014', true ) );
		dateP.appendChild( document.createTextNode( '  ' ) );
		dateP.appendChild( radio( 'MDY', 'September 1, 2014', false ) );
		dateP.appendChild( document.createTextNode( '  ' ) );
		dateP.appendChild( radio( 'YMD', '2014-09-01', false ) );

		dialog.appendChild( el( 'h2', {}, msg.title ) );
		dialog.appendChild( close );
		body.appendChild( urlP );
		body.appendChild( dateP );
		body.appendChild( gen );
		body.appendChild( el( 'p', {}, msg.codeLabel ) );
		body.appendChild( code );
		body.appendChild( el( 'p', {}, msg.rawLabel ) );
		body.appendChild( full );
		dialog.appendChild( body );
		cont.appendChild( dialog );
		document.body.appendChild( cont );
	}

	function bindOpener( node ) {
		if ( !node ) {
			return;
		}
		$( node ).on( 'click', function ( e ) {
			e.preventDefault();
			openDialog();
		} );
	}

	function addEntryPoint() {
		var node, i, portlets, btn;
		portlets = [ 'p-cactions', 'p-views', 'p-tb' ];

		btn = el( 'button', {
			type: 'button',
			id: 't-citoid',
			title: msg[ 'toolbox-tooltip' ]
		}, msg[ 'toolbox-label' ] );

		if ( document.getElementById( 'antivandal-slot' ) && !document.getElementById( 't-citoid' ) ) {
			document.getElementById( 'antivandal-slot' ).appendChild( btn );
			bindOpener( btn );
			return;
		}

		node = null;
		for ( i = 0; i < portlets.length; i++ ) {
			node = mw.util.addPortletLink(
				portlets[ i ], '#', msg[ 'toolbox-label' ], 't-citoid', msg[ 'toolbox-tooltip' ]
			);
			if ( node ) {
				break;
			}
		}

		if ( !node ) {
			btn.id = 'citoid-floating';
			document.body.appendChild( btn );
			node = btn;
		}
		bindOpener( node );
	}

	mw.loader.using( 'mediawiki.util' ).then( function () {
		$( function () {
			injectCSS();
			buildHTML();
			addEntryPoint();
		} );
	} );

}( jQuery, mediaWiki ) );