மீடியாவிக்கி:Gadget-ProveItMain.js
/*
  * Imported from Mercurial commit c978344be3df as of 2013-06-30 from http://code.google.com/p/proveit-js/
  * Changes should be made through that Google Code project.
  */
 /*
  * ProveIt ([[User:ProveIt GT]]) is a powerful GUI tool for viewing, adding, editing, and inserting references on Wikipedia.
  *
  * Copyright 2008 - 2011
  *
  * Georgia Tech Research Corporation
  *
  * Atlanta, GA 30332-0415
  *
  * Copyright 2011 -
  *
  * Matthew Flaschen
  *
  * ALL RIGHTS RESERVED
  *
  * ProveIt is available under the GNU Free Documentation License (GFDL-1.3.txt), Creative Commons
  * Attribution/Share-Alike License 3.0 (http://creativecommons.org/licenses/by-sa/3.0/), and the GNU
  * General Public License 2 (GPL-2.txt)
  */
 
 /**
  * Electronic Learning Communities
  * @module elc
  */
 
 ( function ( mw, $ ) {
 
 /*
  Second parameter (pre-existing proveit object, if any) passed to extend overrides first.
  Gives users option to easily override initial constants, such as shouldAddSummary.
 
  If proveit is unintentionally imported more than once, the first import will take precedence.
 */
 /**
  * Main class and namespace for ProveIt software.  This is the only global variable.
  * @class proveit
  */
 var proveit = window.proveit = $.extend({
 	/**
 	 * Approximately half the height of the edit box.  Used in scrolling when highlighting text.
 	 * @type Number
 	 */
 	HALF_EDIT_BOX_HEIGHT: 200,
 
 	// This could be preference-controlled, instead of hard-coded.
 	/**
 	 * Language used for descriptions
 	 * @type String
 	 */
 	LANG: &quot;en&quot;,
 
 	/**
 	 * Text before param name (e.g. url, title, etc.) in creation box, to avoid collisions with unrelated ids.
 	 * @type String
 	 */
 	NEW_PARAM_PREFIX: &quot;newparam&quot;,
 
 	/**
 	 * Text before param name (e.g. url, title, etc.) in edit box, to avoid collisions with unrelated ids.
 	 * @type String
 	 */
 	EDIT_PARAM_PREFIX: &quot;editparam&quot;,
 
 	GUI_ID: &quot;proveit&quot;,
 
 	/**
 	 * Base URL used for static content
 	 *
 	 * This directory includes icons from the Silk set (http://www.famfamfam.com/lab/icons/silk/), by Mark James
 	 * @type String
 	 */
 	STATIC_BASE: &quot;//proveit-js.googlecode.com/hg/static/&quot;,
 
 	/* Used to map between keys, including citation parameter names, and human-readable text.  It can be
 	 * internationalized easily.  Add descriptions.xx , where xx is
 	 * the ISO 639-1 code for a language, then set proveit.LANG to &quot;xx&quot;
 	 * to use the new descriptions.
 	 */
 	descriptions :
 	{
 		en :
 		{
 			agency: &quot;Agency&quot;,
 			name: &quot;Name&quot;,
 			author: &quot;Author (L, F)&quot;,
 			author2: &quot;Author two (L, F)&quot;,
 			author3: &quot;Author three (L, F)&quot;,
 			author4: &quot;Author four (L, F)&quot;,
 			author5: &quot;Author five (L, F)&quot;,
 			author6: &quot;Author six (L, F)&quot;,
 			author7: &quot;Author seven (L, F)&quot;,
 			author8: &quot;Author eight (L, F)&quot;,
 			author9: &quot;Author nine (L, F)&quot;,
 			last: &quot;Last name&quot;,
 			last2: &quot;Last name (auth. two)&quot;,
 			last3: &quot;Last name (auth. three)&quot;,
 			last4: &quot;Last name (auth. four)&quot;,
 			last5: &quot;Last name (auth. five)&quot;,
 			last6: &quot;Last name (auth. six)&quot;,
 			last7: &quot;Last name (auth. seven)&quot;,
 			last8: &quot;Last name (auth. eight)&quot;,
 			last9: &quot;Last name (auth. nine)&quot;,
 			first: &quot;First name&quot;,
 			first2: &quot;First name (auth. two)&quot;,
 			first3: &quot;First name (auth. three)&quot;,
 			first4: &quot;First name (auth. four)&quot;,
 			first5: &quot;First name (auth. five)&quot;,
 			first6: &quot;First name (auth. six)&quot;,
 			first7: &quot;First name (auth. seven)&quot;,
 			first8: &quot;First name (auth. eight)&quot;,
 			first9: &quot;First name (auth. nine)&quot;,
 			authorlink: &quot;Author article name&quot;,
 			title: &quot;Title&quot;,
 			trans_title: &quot;Title in English&quot;,
 			publisher: &quot;Publisher&quot;,
 			year: &quot;Year&quot;,
 			location: &quot;Location&quot;,
 			place: &quot;Location of work&quot;,
 			isbn: &quot;ISBN&quot;,
 			id: &quot;ID&quot;,
 			doi: &quot;DOI&quot;,
 			page: &quot;Page&quot;,
 			pages: &quot;Pages&quot;,
 			quote: &quot;Quote&quot;,
 			month: &quot;Month&quot;,
 			journal: &quot;Journal&quot;,
 			edition: &quot;Edition&quot;,
 			volume: &quot;Volume&quot;,
 			issue: &quot;Issue&quot;,
 			url: &quot;URL&quot;,
 			date: &quot;Publication date&quot;,
 			accessdate: &quot;Access date&quot;,
 			coauthors: &quot;Co-authors&quot;,
 			booktitle: &quot;Title of Proceedings&quot;,
 			contribution: &quot;Contribution/Chapter&quot;,
 			encyclopedia: &quot;Encyclopedia&quot;,
 			newsgroup: &quot;Newsgroup&quot;,
 			version: &quot;Version&quot;,
 			site: &quot;Site&quot;,
 			newspaper: &quot;Newspaper&quot;,
 			&quot;publication-place&quot;: &quot;Publication location&quot;,
 			editor: &quot;Editor (L, F)&quot;,
 			article: &quot;Article&quot;,
 			pubplace: &quot;Publisher location&quot;,
 			pubyear: &quot;Publication year&quot;,
 			inventor: &quot;Inventor (L, F)&quot;,
 			&quot;issue-date&quot;: &quot;Issue date&quot;,
 			&quot;patent-number&quot;: &quot;Patent number&quot;,
 			&quot;country-code&quot;: &quot;Country code (XX)&quot;,
 			work: &quot;Work&quot;,
 			format: &quot;Format&quot;,
 			issn: &quot;ISSN&quot;,
 			pmid: &quot;PMID&quot;,
 			chapter: &quot;Chapter&quot;,
 			web: &quot;Web&quot;,
 			book: &quot;Book&quot;,
 			conference: &quot;Conference&quot;,
 			news: &quot;News&quot;,
 			paper: &quot;Paper&quot;,
 			&quot;press release&quot;: &quot;Press release&quot;,
 			interview: &quot;Interview&quot;,
 			&quot;AV media&quot;: &quot;Audiovisual work&quot;,
 			subject: &quot;Subject&quot;,
 			subjectlink: &quot;Subject article name&quot;,
 			subject2: &quot;Subject two&quot;,
 			subjectlink2: &quot;Subject two article name&quot;,
 			subject3: &quot;Subject three&quot;,
 			subjectlink3: &quot;Subject three article name&quot;,
 			subject4: &quot;Subject four&quot;,
 			interviewer: &quot;Interviewer&quot;,
 			cointerviewers: &quot;Co-interviewers&quot;,
 			type: &quot;Type&quot;,
 			program: &quot;Program&quot;,
 			callsign: &quot;Call sign&quot;,
 			city: &quot;City&quot;,
 			archiveurl: &quot;Archive URL&quot;,
 			archivedate: &quot;Date archived&quot;,
 			episode: &quot;Episode&quot;,
 			episodelink: &quot;Episode article name&quot;,
 			series: &quot;Series&quot;,
 			serieslink: &quot;Series article name&quot;,
 			credits: &quot;Credits&quot;,
 			network: &quot;Network&quot;,
 			station: &quot;Station&quot;,
 			airdate: &quot;Airdate&quot;,
 			began: &quot;Start date&quot;,
 			ended: &quot;End date&quot;,
 			season: &quot;Season number&quot;,
 			seriesno: &quot;Season number&quot;,
 			number: &quot;Number&quot;,
 			minutes: &quot;Minutes&quot;,
 			transcript: &quot;Transcript&quot;,
 			transcripturl: &quot;Transcript URL&quot;,
 			people: &quot;People&quot;,
 			medium: &quot;Production medium&quot;,
 			language: &quot;Language&quot;,
 			time: &quot;Time&quot;,
 			oclc: &quot;OCLC&quot;,
 			ref: &quot;Anchor ID&quot;,
 			deadurl: 'Dead URL?',
 			raw: 'Unknown format'
 		},
 		// Finnish translation by Olli (ollinpostit at gmail.com)
 		fi: {
                         agency: &quot;Edustaja&quot;,
                         name: &quot;Nimi&quot;,
                         author: &quot;Tekijä&quot;,
                         author2: &quot;Tekijä kaksi&quot;,
                         author3: &quot;Tekijä kolme&quot;,
                         author4: &quot;Tekijä neljä&quot;,
                         author5: &quot;Tekijä viisi&quot;,
                         author6: &quot;Tekijä kuusi&quot;,
                         author7: &quot;Tekijä seitsemän&quot;,
                         author8: &quot;Tekijä kahdeksan&quot;,
                         author9: &quot;Tekijä yhdeksän&quot;,
                         last: &quot;Sukunimi&quot;,
                         last2: &quot;Sukunimi (tekijä 2)&quot;,
                         last3: &quot;Sukunimi (tekijä 3)&quot;,
                         last4: &quot;Sukunimi (tekijä 4)&quot;,
                         last5: &quot;Sukunimi (tekijä 5)&quot;,
                         last6: &quot;Sukunimi (tekijä 6)&quot;,
                         last7: &quot;Sukunimi (tekijä 7)&quot;,
                         last8: &quot;Sukunimi (tekijä 8)&quot;,
                         last9: &quot;Sukunimi (tekijä 9)&quot;,
                         first: &quot;Etunimi&quot;,
                         first2: &quot;Etunimi (tekijä 2)&quot;,
                         first3: &quot;Etunimi (tekijä 3)&quot;,
                         first4: &quot;Etunimi (tekijä 4)&quot;,
                         first5: &quot;Etunimi (tekijä 5)&quot;,
                         first6: &quot;Etunimi (tekijä 6)&quot;,
                         first7: &quot;Etunimi (tekijä 7)&quot;,
                         first8: &quot;Etunimi (tekijä	8)&quot;,
                         first9: &quot;Etunimi (tekijä 9)&quot;,
                         authorlink: &quot;Tekijästä kertova sivu&quot;,
                         title: &quot;Otsikko&quot;,
                         publisher: &quot;Julkaisija&quot;,
                         year: &quot;Vuosi&quot;,
                         location: &quot;Paikka&quot;,
                         place: &quot;Työn paikka&quot;,
                         isbn: &quot;ISBN&quot;,
                         id: &quot;ID&quot;,
                         doi: &quot;DOI&quot;,
                         page: &quot;Sivu&quot;,
                         pages: &quot;Sivuja&quot;,
                         quote: &quot;Lainaus&quot;,
                         month: &quot;Kuukausi&quot;,
                         journal: &quot;Aikakauslehti&quot;,
                         edition: &quot;Painos&quot;,
                         volume: &quot;Vuosikerta&quot;,
                         issue: &quot;Numero&quot;,
                         url: &quot;Osoite&quot;,
                         date: &quot;Julkaisupäivä&quot;,
                         accessdate: &quot;Luettu&quot;,
                         coauthors: &quot;Muut tekijät&quot;,
                         booktitle: &quot;Jatko-osien otsikko&quot;,
                         contribution: &quot;Osallistuminen/yhteistyö&quot;,
                         encyclopedia: &quot;Tietosanakirja&quot;,
                         newsgroup: &quot;Uutisryhmä&quot;,
                         version: &quot;Versio&quot;,
                         site: &quot;Sivusto&quot;,
                         newspaper: &quot;Sanomalehti&quot;,
                         &quot;publication-place&quot;: &quot;Julkaisupaikka&quot;,
                         editor: &quot;Toimittaja&quot;,
                         article: &quot;Artikkeli&quot;,
                         pubplace: &quot;Julkaisijan paikka&quot;,
                         pubyear: &quot;Julkaisuvuosi&quot;,
                         inventor: &quot;Keksijä&quot;,
                         &quot;issue-date&quot;: &quot;Saatavilla päivänä&quot;,
                         &quot;patent-number&quot;: &quot;Patenttinumero&quot;,
                         &quot;country-code&quot;: &quot;Maakoodi (XX)&quot;,
                         work: &quot;Työ&quot;,
                         format: &quot;Muoto&quot;,
                         issn: &quot;ISSN&quot;,
                         pmid: &quot;PMID&quot;,
                         chapter: &quot;Luku&quot;,
                         web: &quot;Verkko&quot;,
                         book: &quot;Kirja&quot;,
                         conference: &quot;Kokous&quot;,
                         news: &quot;Uutiset&quot;,
                         paper: &quot;Lehti&quot;,
                         &quot;press release&quot;: &quot;Lehdistötiedote&quot;,
                         interview: &quot;Haastattelu&quot;,
                         subject: &quot;Otsikko&quot;,
                         subjectlink: &quot;Artikkelin otsikko&quot;,
                         subject2: &quot;Otsikko kaksi&quot;,
                         subjectlink2: &quot;Artikkelin kaksi otsikko&quot;,
                         subject3: &quot;Otsikko kolme&quot;,
                         subjectlink3: &quot;Artikkelin kolme otsikko&quot;,
                         subject4: &quot;Otsikko neljä&quot;,
                         interviewer: &quot;Haastattelija&quot;,
                         cointerviewers: &quot;Muut haastattelijat&quot;,
                         type: &quot;Tyyppi&quot;,
                         program: &quot;Ohjelma&quot;,
                         callsign: &quot;Call sign&quot;,
                         city: &quot;Kaupunki&quot;,
                         archiveurl: &quot;Arkiston osoite&quot;,
                         archivedate: &quot;Arkistointipäivämäärä&quot;,
                         episode: &quot;Jakso&quot;,
                         episodelink: &quot;Jakson sivun nimi&quot;,
                         series: &quot;Sarja&quot;,
                         serieslink: &quot;Sarjan sivun nimi&quot;,
                         credits: &quot;Tekijät&quot;,
                         network: &quot;Verkko&quot;,
                         station: &quot;Asema&quot;,
                         airdate: &quot;Lähetyspäivä&quot;,
                         began: &quot;Aloituspäivä&quot;,
                         ended: &quot;Lopetuspäivä&quot;,
                         season: &quot;Kauden numero&quot;,
                         seriesno: &quot;Kauden numero&quot;,
                         number: &quot;Numero&quot;,
                         minutes: &quot;Minuutit&quot;,
                         transcript: &quot;Puhtaaksi kirjoitettu teksti&quot;,
                         transcripturl: &quot;Puhtaaksikirjoitetun osoite&quot;,
                         video: &quot;Video&quot;,
                         people: &quot;Ihmiset&quot;,
                         medium: &quot;Tuotantomedia&quot;,
                         language: &quot;Kieli&quot;,
                         time: &quot;Aika&quot;,
                         oclc: &quot;OCLC&quot;,
                         ref: &quot;Ankkurin ID-tunnus&quot;
                 }
 	},
 
 	/**
 	 * Optional preference to specify default date format for new references.
 	 * If set, it overrides the general date preference from Special:Preferences.
 	 *
 	 * @type {String} supported date format string
 	 */
 	dateFormatString: null,
 
 	/**
 	 * Singleton used to format dates according to user preference
 	 *
 	 * @type DateFormatter
 	 */
 	dateFormatter: null,
 
 	/**
 	 * Gets the effective preference for date format.  If there is no ProveIt-specific
 	 * preference already at proveit.dateFormatString, it will determine the correct preference
 	 * from	MW user preferences.  Then, it will store that value to proveit.dateFormatString
 	 *
 	 * @return {String} format string to use for dates
 	 */
 	getDatePreference: function () {
 		if (this.dateFormatString === null) {
 			this.dateFormatString = mw.user.options.get('date');
 		}
 
 		return this.dateFormatString;
 	},
 
 	/**
 	 * Returns descriptions for the current language.
 	 * @return {Object} descriptions
 	 */
 	getDescriptions: function()
 	{
 		//this could be made Cite-specific if needed.
 		return this.descriptions[proveit.LANG];
 	},
 
 	/**
 	 * String added to logs for easy search
 	 * @type String
 	 */
 	LOG_MARKER: &quot;[ProveIt] &quot;,
 
 	/**
 	 * Convenience log function
 	 * @param {...Object} var_args objects (including strings) to log
 	 */
 	log: function()
 	{
 		var args = Array.prototype.slice.call(arguments);
 		args.unshift(this.LOG_MARKER);
 		mw.log.apply(mw, args);
 	},
 
 	/**
 	 * Log error object if possible, using error (preferable), or log, if available.
 	 * @param {Error} ex error object
 	 */
 	logException: function(ex)
 	{
 		var args = [ex, ex.stack];
 		if(typeof(console) === &quot;object&quot; &amp;&amp; $.isFunction(console.error))
 		{
 			args.unshift(this.LOG_MARKER);
 			console.error.apply(null, args);
 		}
 		else
 		{
 			this.log.apply(this, args);
 		}
 	},
 
 	/**
 	 * Returns true if the page has an edit box
 	 *
 	 * @return {Boolean} true if the page has an edit box, false otherwise
 	 */
 	isEditPage: function()
 	{
 		return mw.config.get('wgAction') == 'edit' || mw.config.get('wgAction') == 'submit';
 	},
 
 	/**
 	 * Returns true if the page is likely to contain references
 	 * @return {Boolean} true if page is supported, false otherwise
 	 */
 	isSupportedPage: function()
 	{
 	        // &quot;Regular&quot; article, userspace, or Wikipedia:Sandbox (exception for testing).
 	        return (mw.config.get('wgCanonicalNamespace') == '' || mw.config.get('wgCanonicalNamespace') == 'User' || mw.config.get('wgPageName') == 'Wikipedia:Sandbox');
 	},
 
 	/**
 	 * Convenience function.  Returns the refbox element.
 	 * @return {$Node} reference box
 	 */
 	getRefBox: function()
 	{
 		return $(&quot;#refs&quot;);
 	},
 
 	/**
 	 * Provides the x (left) and y (top) offsets to a given element. From QuirksMode (http://www.quirksmode.org/js/findpos.html), a freely available site by Peter-Paul Koch
 	 * @param {Node} node any HTML node
 	 * @return {Object} offsets to node, as object with left and top properties.
 	 */
 	getPosition: function(node)
 	{
 		var left = 0, top = 0;
 		do
 		{
 			left += node.offsetLeft;
 			top += node.offsetTop;
 		} while (node = node.offsetParent);
 		return {&quot;left&quot;: left, &quot;top&quot;: top};
 	},
 
 	/**
 	 * Highlights a given length of text, at a particular index.
 	 * @param {Number} startInd start index in Wikipedia edit box
 	 * @param {Number} length length of string to highlight
 	 * @return {Boolean} always true
 	*/
 	highlightLengthAtIndex: function(startInd, length)
 	{
 		if(startInd &lt; 0 || length &lt; 0)
 		{
 			this.log(&quot;highlightStringAtIndex: invalid negative arguments&quot;);
 		}
 		var box = this.getMWEditBox();
 		var origText = box.value;
 		var editTop = this.getPosition(box).top;
 		box.value = origText.substring(0, startInd);
 		box.focus();
 		box.scrollTop = 1000000; //Larger than any real textarea (hopefully)
 		var curScrollTop = box.scrollTop;
 		box.value += origText.substring(startInd);
 		if(curScrollTop &gt; 0)
 		{
 			box.scrollTop = curScrollTop + this.HALF_EDIT_BOX_HEIGHT;
 		}
 		$(box).focus().textSelection('setSelection',
 		{
 			start: startInd,
 			end: startInd + length
 		});
 		editTop = this.getPosition(box).top;
 		window.scroll(0, editTop);
 		return true;
 	},
 
 	/**
 	 * Highlights the first instance of a given string in the MediaWiki edit box.
 	 * @param {String} targetStr the string in the edit box to highlight
 	 * @return {Boolean} true if successful, false otherwise
 	*/
 	highlightTargetString: function(targetStr)
 	{
 		var origText = this.getMWEditValue();
 		var startInd = origText.indexOf(targetStr);
 		if(startInd == -1)
 		{
 			this.log(&quot;Target string \&quot;&quot; + targetStr + &quot;\&quot; not found.&quot;);
 			return false;
 		}
 		return this.highlightLengthAtIndex(startInd, targetStr.length);
 	},
 
 	/**
 	 * Convenience function. Returns the raw MediaWiki textarea element.
 	 * @return {Node} the edit box element
 	*/
 	getMWEditBox: function()
 	{
 		return $(&quot;#wpTextbox1&quot;)[0];
 	},
 
 	/**
 	 * Provides value of edit box with CR normalization
 	 *
 	 * @return {String} value of edit box with CRs stripped if document.selection exists
 	 */
 	getMWEditValue: function()
 	{
 		var box = this.getMWEditBox();
 		var value = box.value;
 		if(!box.selectionStart &amp;&amp; document.selection) // IE 8-like behavior
 		{
 			value = value.replace(/\r\n/g, &quot;\n&quot;);
 		}
 		return value;
 	},
 
 	/**
 	 * Returns raw edit form element, which contains MWEditBox, among other things.
 	 * @return {Node} the edit form element
 	*/
 	getMWEditForm: function()
 	{
 		return $(&quot;#editform&quot;)[0];
 	},
 
 	/**
 	 * Runs a given function on submission of edit form
 	 * @param {Function} subFunc function to run on submission
 	*/
 	addOnsubmit: function(subFunc)
 	{
 		var form = this.getMWEditForm();
 		if(!form)
 		{
 			throw new Error(&quot;No edit form, possibly due to protected page.&quot;);
 		}
 		form.addEventListener(&quot;submit&quot;, subFunc, false);
 	},
 
 	/**
 	 * Returns the raw MW edit summary element
 	 * @return {Node} the edit summary element
 	*/
 	getEditSummary: function()
 	{
 		return $(&quot;#wpSummary&quot;)[0];
 	},
 
 	/**
 	 * Keep track of whether we have already added an onsubmit function to include ProveIt in the summary.
 	 * This guarantees the function will not be run twice.
 	 * @type Boolean
 	 */
 	summaryFunctionAdded: false,
 
 	/**
 	 * Does the user want us to ever add &quot;Edited by ProveIt&quot; summary?
 	 * @type Boolean
 	*/
 	shouldAddSummary: true,
 
 	/**
 	 * ProveIt should be visible on load (rather than requiring toolbar button click) on supported edit pages
 	 * @type Boolean
 	 */
  	loadVisible: true,
 
 	/**
 	 * Maximize ProveIt when it first becomes visible.  If false, it will start minimized.  This has no effect on when it becomes visible.
 	 * @type Boolean
 	 */
 	loadMaximized: false,
 
 	/**
 	 * Specifies to include ProveIt edit summary on next save.
 	 * Can be disabled by modifying shouldAddSummary
 	 */
 	includeProveItEditSummary: function()
 	{
 		if(this.shouldAddSummary &amp;&amp; !this.summaryFunctionAdded)
 		{
 			try
 			{
 				var thisproveit = this;
 				this.addOnsubmit(function()
 				{
 					var summary = thisproveit.getEditSummary();
 
 					if(summary.value.indexOf(&quot;ProveIt&quot;) == -1)
 					{
 						summary.value += &quot; (edited with [[User:ProveIt_GT|ProveIt]])&quot;;
 					}
 				});
 				this.summaryFunctionAdded = true;
 			}
 			catch(e)
 			{
 				this.log(&quot;Failed to add onsubmit handler. e.message: &quot; + e.message);
 			}
 		}
 	},
 
 	/**
 	 * Setup button so users can load ProveIt on demand
 	 */
 	setupButton: function()
 	{
 		var $box = $(this.getMWEditBox());
 
 		// Ensures wikiEditor is loaded
 		$box.on('wikiEditor-toolbar-buildSection-main', function(event, section)
 		{
 			delete section.groups.insert.tools.reference;
 
 			section.groups.insert.tools.proveit = {
 				label: 'ProveIt',
 				type: 'button',
 				icon: '//upload.wikimedia.org/wikipedia/commons/thumb/1/19/ProveIt_logo_for_user_boxes.svg/22px-ProveIt_logo_for_user_boxes.svg.png',
 				action: {
 					type: 'callback',
 					execute: function()
 					{
 						proveit.toggleVisibility();
 					}
 				}
 			};
 		});
 	},
 
 	/**
 	 * Sets up ProveIt if we're on an edit page.  This includes setting up the toolbar button.  Depending on configuration and the current page, it may also call load to show ProveIt.
 	 */
 	setup: function()
 	{
 		if(this.isEditPage())
 		{
 			if(this.loadVisible &amp;&amp; this.isSupportedPage())
 			{
 				this.load();
 			}
 
 			this.setupButton();
 		}
 	},
 
 	/**
 	 * Loads dependencies and creates GUI
 	 */
 	load: function()
 	{
 		$(function()
 		{
 			var dependencies = ['jquery.ui', 'jquery.textSelection'];
 			var preference = proveit.getDatePreference();
 
 			proveit.dateFormatter = new proveit.DateFormatter(preference);
 
 			mw.loader.using(dependencies, function()
 			{
 				try
 				{
 					proveit.createGUI();
 					if(proveit.loadMaximized)
 					{
 						proveit.toggleViewAddVisibility();
 					}
 				}
 				catch(ex)
 				{
 					proveit.logException(ex);
 				}
 			}, function(ex, errorDependencies)
 			{
 				proveit.log('Failed to load one of: ', errorDependencies);
 			});
 		});
 	},
 
 	/**
 	 * Clears the refBox of refBoxRows, except for dummy rows.
 	 * @return {Boolean} false if refBox wasn't found
 	 */
 
 	clearRefBox: function()
 	{
 		var box = this.getRefBox();
 		if(box == null)
 		{
 			this.log(&quot;Ref box is not loaded yet.&quot;);
 			return false;
 		}
 		$(&quot;tr:not('tr#dummyRef')&quot;, box).remove();
 		return true;
 	},
 
 	/** Inserts ref text into MW edit box.
 	 * @param {String} ref Reference text to insert
 	 * @param {Boolean} full Insert the full reference text if true, citation otherwise.
 	 * @return {Boolean} false if errors
 	 */
 	insertRefIntoMWEditBox: function(ref, full)
 	{
 		var txtarea = this.getMWEditBox();
 		if(!txtarea)
 		{
 			this.log(&quot;insertRefIntoMWEditBox: txtarea is null&quot;);
 			return false;
 		}
 		txtarea = $(txtarea);
 		var insertionText = ref.getInsertionText(full);
 		 // Replace existing selection (if any), then scroll
 		txtarea.textSelection('encapsulateSelection',
 		{
 			peri: insertionText,
 			replace: true
 		});
 		var caretPos = txtarea.textSelection('getCaretPosition', {startAndEnd: true});
 
 		// This is slightly redundant.  It is called primarily for the scrollig workaround
 		this.highlightLengthAtIndex(caretPos[0], caretPos[1] - caretPos[0]);
 
 		this.includeProveItEditSummary();
 	},
 
 	/**
 	 * Modifies reference object from user-edited GUI. The reference object is mutated in place, so the return value is only for convenience.
 	 *
 	 * @param {Node} editPane the raw element of the editPane
 	 * @param {AbstractReference} ref the original citation object we're modifying
 	 *
 	 * @return {AbstractReference} same ref that was passed in
 	 */
 	changeRefFromEditPane: function(ref, editPane)
 	{
 		var paramBoxes = $(&quot;div.input-row&quot;, editPane);
 
 		var refName = $('#editrefname').val();
 		ref.name = refName != &quot;&quot; ? refName : null; // Save blank names as null
 
 		// Clear old params
 		ref.params = {};
 
 		var paramName, paramVal;
 		for (var i = 0; i &lt; paramBoxes.length; i++)
 		{
 			var paramRow = paramBoxes[i];
 			var valueTextbox = $(&quot;.paramvalue&quot;, paramRow)[0];
 			if($(paramRow).hasClass(&quot;addedrow&quot;)) // Added with &quot;Add another field&quot;
 			{
 				paramName = $.trim($(&quot;.paramdesc&quot;, paramRow)[0].value);
 			}
 			else
 			{
 				paramName = valueTextbox.id.substring(this.EDIT_PARAM_PREFIX.length);
 			}
 			this.log(&quot;paramName: &quot; + paramName);
 			paramVal = $.trim(valueTextbox.value);
 
 			this.log(&quot;paramVal: &quot; + paramVal);
 
 			if (paramName != &quot;&quot; &amp;&amp; paramVal != &quot;&quot;)
 			{
 				ref.params[paramName] = paramVal;
 			}
 		}
 		if (ref.toString() != ref.orig)
 		{
 			ref.save = false;
 		}
 		ref.update();
 		return ref;
 	},
 
 	/**
 	 * Creates refBoxRow, updates numbering for all refBoxRows, replaces old refBoxRow with new one, and updates ref text in MWEditBox.
 	 * @param {AbstractReference} ref the ref we want to save.
 	 */
 	saveRefFromEdit: function(ref)
 	{
 		if(!ref.save)
 		{
 		    var newRichItem = this.makeRefBoxRow(ref, true);
 			var oldRichItem = $('.selected', this.getRefBox()).get(0);
 			var oldNumber = $('td.number',oldRichItem).text();
 			$('td.number',newRichItem).text(oldNumber); // preserve old numbering
 			oldRichItem.parentNode.replaceChild(newRichItem, oldRichItem);
 			$(newRichItem).addClass('selected');
 
 			ref.updateInText();
 			this.includeProveItEditSummary();
 		}
 	},
 
 	/**
 	 * Updates the edit pane when you choose a reference to edit.
 	 * @param {AbstractReference} ref the ref that was chosen.
 	 */
 	updateEditPane: function(ref)
 	{
 		$('#editrefname').val(ref.name || &quot;&quot;);
 
 		// Don't contaminate actual object with junk params.
 		var tempParams = {};
 		for(var param in ref.params)
 		{
 			tempParams[param] = ref.params[param];
 		}
 
 		// Add default params with blank values.
 		var defaults = ref.getDefaultParams();
 		for(var i = 0; i &lt; defaults.length; i++)
 		{
 			if(!tempParams[defaults[i]])
 			{
 				tempParams[defaults[i]] = &quot;&quot;;
 			}
 		}
 
 		var required = ref.getRequiredParams();
 
 		var paramNames = new Array();
 
 		for(var item in tempParams)	//First run through just to get names.
 		{
 			paramNames.push(item);
 		}
 
 		var sorter = ref.getSorter();
 		if(sorter)
 		{
 			paramNames.sort(sorter);
 		}
 		else
 		{
 			paramNames.sort();
 		}
 		/* Sort them to provide consistent interface.  Uses custom sort order (which is easily tweaked)
 		   where possible.
 
 		   Javascript does destructive sorting, which in this case, is convenient...
 		*/
 
 		$('#edit-fields').children('.paramlist').children().remove('div:not(.hidden)'); // clear all fields in the edit box (except the hidden ones)
 
 		for(var j = 0; j &lt; paramNames.length; j++)
 		{
 			this.addPaneRow($(&quot;#edit-pane&quot;).get(), tempParams, this.getDescriptions(), paramNames[j], required[paramNames[j]], true);
 		}
 
 		var acceptButton = $('#edit-buttons .accept');
 		var acceptEdit = function()
 		{
 			proveit.changeRefFromEditPane(ref, $(&quot;#edit-pane&quot;).get());
 			proveit.saveRefFromEdit(ref);
 			$(&quot;#edit-pane&quot;).hide();
 			$(&quot;#view-pane&quot;).show();
 		};
 
 		// Without setTimeout, scoll reset doesn't work in Firefox.
 		setTimeout(function()
 		{
 		    // Reset scroll
 		    $('#edit-fields').scrollTop(0);
 		}, 0);
 
 		acceptButton.off('click.proveit').on('click.proveit', acceptEdit);
 	},
 
 	/**
 	 * Add a row to an editPane or addPane.
 	 * @param {Node} root root element for pane
 	 * @param {Object} params the param object from the reference, or null for added rows.
 	 * @param {Object} descs description object to use, or null for no description
 	 * @param {String} item the current param name
 	 * @param {Boolean} req true if current param name is required, otherwise not required.
 	 * @param {Boolean} fieldType true for label, false for textbox.
 	 */
 	addPaneRow: function(root, params, descs, item, req, fieldType)
 	{
 		var id = fieldType ? &quot;preloadedparamrow&quot; : &quot;addedparamrow&quot;;
 		var newline = $('#'+id).clone(); // clone the hidden row
 		$(newline).attr('id',''); // clear the ID (can't have two elements with same ID)
 		//this.activateRemoveField(newline);
 		var paramName = $('.paramdesc', newline).eq(0);
 		var paramValue = $('.paramvalue', newline).eq(0);
 
 
 		$('.paramlist', root).append(newline);
 
 		if(req) // if field is required...
 		{
 			$(paramName).addClass('required'); // visual indicator that label is required
 			$('.delete-field', newline).remove(); // don't let people remove required fields
 		}
 		else
 		{
 			this.activateRemoveField(newline);
 		}
 
 		if(fieldType) // the description/name is a label (not a textbox)
 		{
 			paramName.attr(&quot;for&quot;, this.EDIT_PARAM_PREFIX + item);
 			paramValue.attr('id',this.EDIT_PARAM_PREFIX + item);
 
 			var desc = descs[item];
 			if(!desc)
 			{
 				this.log(&quot;Undefined description for param: &quot; + item + &quot;.  Using directly as description.&quot;);
 				desc = item;
 			}
 			$(paramName).text(desc);
 			$(paramName).attr('title',item);
 			$(paramValue).val(params[item]);
 
 			$(newline).show();
 		}
 		else
 		{
 			// added a new row, so make it fancy
 			$(newline).show('highlight',{},'slow');
 			$('.inputs', root).scrollTop(100000);
 		}
 	},
 
 	/*
 	 * these are the current style and insert values to denote which one is
 	 * currently active
 	 */
 
 	/**
 	 * true signifies cite-style references, citation-style otherwise.  Used when creating a reference.
 	 * @type Boolean
 	 */
 	togglestyle: true,
 
 	// TODO: This should be eliminated if only name only inserts are allowed.
 	/** true signifies full references, name-only otherwise.  Used when inserting.
 	 * Note that new references are always inserted in full.
 	 *
 	 * @type Boolean
 	 */
 	toggleinsert: false,
 
 	/* Cross-Browser Split 1.0.1
 	 (c) Steven Levithan &lt;stevenlevithan.com&gt;; MIT License
 	 http://blog.stevenlevithan.com/archives/cross-browser-split
 	 An ECMA-compliant, uniform cross-browser split method
 	 */
 	/**
 	 * Cross-browser implementation of ECMAScript String.prototype.split function.
 	 *
 	 * @param {String} str input string to split
 	 * @param separator separator to split on, as RegExp or String
 	 * @param {Number} limit limit on number of splits.  If the parameter is absent, no limit is imposed.
 	 * @return {Array} array resulting from split
 	 */
 	split: function (str, separator, limit)
 	{
 		// if `separator` is not a regex, use the native `split`
 		if (Object.prototype.toString.call(separator) !== &quot;[object RegExp]&quot;) {
 			return proveit.split._nativeSplit.call(str, separator, limit);
 		}
 
 		var output = [],
 		lastLastIndex = 0,
 		flags = (separator.ignoreCase ? &quot;i&quot; : &quot;&quot;) +
 			(separator.multiline  ? &quot;m&quot; : &quot;&quot;) +
 			(separator.sticky     ? &quot;y&quot; : &quot;&quot;),
 			separator = RegExp(separator.source, flags + &quot;g&quot;), // make `global` and avoid `lastIndex` issues by working with a copy
 		separator2, match, lastIndex, lastLength;
 
 		str = str + &quot;&quot;; // type conversion
 		if (!proveit.split._compliantExecNpcg) {
 			separator2 = RegExp(&quot;^&quot; + separator.source + &quot;$(?!\\s)&quot;, flags); // doesn't need /g or /y, but they don't hurt
 		}
 
 		/* behavior for `limit`: if it's...
 		 - `undefined`: no limit.
 		 - `NaN` or zero: return an empty array.
 		 - a positive number: use `Math.floor(limit)`.
 		 - a negative number: no limit.
 		 - other: type-convert, then use the above rules. */
 		if (limit === undefined || +limit &lt; 0) {
 			limit = Infinity;
 		} else {
 			limit = Math.floor(+limit);
 			if (!limit) {
 				return [];
 			}
 		}
 
 		while (match = separator.exec(str)) {
 			lastIndex = match.index + match[0].length; // `separator.lastIndex` is not reliable cross-browser
 
 			if (lastIndex &gt; lastLastIndex) {
 				output.push(str.slice(lastLastIndex, match.index));
 
 				// fix browsers whose `exec` methods don't consistently return `undefined` for nonparticipating capturing groups
 				if (!proveit.split._compliantExecNpcg &amp;&amp; match.length &gt; 1) {
 					match[0].replace(separator2, function () {
 								 for (var i = 1; i &lt; arguments.length - 2; i++) {
 									 if (arguments[i] === undefined) {
 										 match[i] = undefined;
 									 }
 								 }
 							 });
 				}
 
 				if (match.length &gt; 1 &amp;&amp; match.index &lt; str.length) {
 					Array.prototype.push.apply(output, match.slice(1));
 				}
 
 				lastLength = match[0].length;
 				lastLastIndex = lastIndex;
 
 				if (output.length &gt;= limit) {
 					break;
 				}
 			}
 
 			if (separator.lastIndex === match.index) {
 				separator.lastIndex++; // avoid an infinite loop
 			}
 		}
 
 		if (lastLastIndex === str.length) {
 			if (lastLength || !separator.test(&quot;&quot;)) {
 				output.push(&quot;&quot;);
 			}
 		} else {
 			output.push(str.slice(lastLastIndex));
 		}
 
 		return output.length &gt; limit ? output.slice(0, limit) : output;
 	},
 
 	// TODO: Remove the split code, and just use a regular regex (with two main groups for name and val), iteratively. Regex.find?  Make name and val indices match, and rework calling code as needed.  Also, check how this was done in the original code.
 	/**
 	 * Overly clever regex to parse template string (e.g. |last=Smith|first=John|title=My Life Story) into name and value pairs.
 	 *
 	 * names is an array of all names, and values is an array of all values.  They have equal lengths.
 	 *
 	 * @param {String} workingString template string to parse.
 	 * @return {Object} object with two properties, names and values.
 	 */
 	splitNameVals: function (workingString)
 	{
 		var split = {};
 		// The first component is &quot;ordinary&quot; text (no pipes), while the second is a correctly balanced wikilink, with optional pipe.  Any combination of the two can appear.
 		split.names = proveit.split(workingString.substring(workingString.indexOf(&quot;|&quot;) + 1), /=(?:[^|]*?(?:\[\[[^|\]]*(?:\|(?:[^|\]]*))?\]\])?)+(?:\||\}\})/);
 		split.names.length--; // Remove single empty element at end
 
 		split.values = proveit.split(workingString.substring(workingString.indexOf(&quot;=&quot;) + 1, workingString.indexOf(&quot;}}&quot;)), /\|[^|=]*=/);
 		return split;
 	},
 
 	/**
 	 * Scan for references in the MWEditBox, and create a reference object and refBoxRow for each.
 	 */
 	scanForRefs: function()
 	{
 		// these are strings used to allow the correct parsing of the ref
 		var workingstring;
 		var cutupstring;
 
 		this.clearRefBox();
 
 		var textValue = this.getMWEditValue();
 		// since we should pick the name out before we get to the reference type, here's a variable to hold it
 		var name;
 
 		// key - name
 		// value -
 		//      object - key - &quot;reference&quot;, value - reference obj .  Avoids repeating same object in references array.
                 //               key - &quot;strings&quot;, value - array of orig strings
 		var citations = {};
 
 		// Array of reference objects.  At end of function, addNewElement called on each.
 		var references = [];
 		 // allRefs should count opening refs, but not ref citation (not &lt;ref name=&quot;...&quot;&quot; /&gt;)
 		var allRefs = textValue.match(/&lt;[\s]*ref[^\/&gt;]*&gt;/gi);
 		// currentScan holds the parsed (match objects) list of references.  Regex matches full or name-only reference.
 		var currentScan = textValue.match(/&lt;[\s]*ref[^&gt;]*&gt;(?:[^&lt;]*&lt;[\s]*\/[\s]*ref[\s]*&gt;)?/gi); // [^&lt;]* doesn't handle embedded HTML tags (or comments) correctly.
 		// if there are results,
 		if (currentScan)
 		{
 			for (var i = 0; i &lt; currentScan.length; i++)
 			{
 				var reference = this.makeRef(currentScan[i]);
 				if(reference) // Full reference object
 				{
 					name = reference.name;
 					if(!name) // with no name, no possibility of repeat name.
 					{
 						references.push(reference);
 					}
 				}
 				else // Not full reference.  Possibly citation.
 				{
 					var match = currentScan[i].match(this.REF_REGEX);
 					name = match &amp;&amp; (match[1] || match[2] || match[3]);
 				}
 
 				if(name)
 				{
 					if(!citations[name])
 					{
 						// Create array of original reference strings
 						citations[name] = {};
 						if(!citations[name].strings)
 						{
 							citations[name].strings = [];
 						}
 					}
 					if(reference &amp;&amp; !citations[name].reference) // reference, and not already one for this name
 					{
 						citations[name].reference = reference;
 						references.push(reference);
 					}
 
 					// Add to array
 					citations[name].strings.push(currentScan[i]);
 				}
 			}
 		}
 		for(var j = 0; j &lt; references.length; j++)
 		{
 			if(references[j].name)
 			{
 				var citation = citations[references[j].name];
 				references[j].setCitationStrings(citation.strings);
 			}
 			this.addNewElement(references[j]);
 		}
 	},
 
 	/**
 	 * Regex for parsing any reference text.
 	 * @type RegExp
 	*/
 	REF_REGEX: /&lt;[\s]*ref[\s]*name[\s]*=[\s]*(?:(?:\&quot;(.*?)\&quot;)|(?:\'(.*?)\')|(?:(.*?)))[\s]*\/?[\s]*&gt;/,
 
 	/**
 	 * Factory function for references.  Takes text of a reference, and returns instance of the appropriate class.
 	 * @param {String} refText reference string
 	 * @return {AbstractReference} null if refText isn't a ref, otherwise the reference object
 	 */
 	makeRef: function(refText)
 	{
 		var isReference = /&lt;[\s]*ref[^&gt;]*&gt;[^&lt;]*\S[^&lt;]*&lt;[\s]*\/[\s]*ref[\s]*&gt;/.test(refText); // Tests for reference (non-citation);
 		if(!isReference)
 		{
 			return null;
 		}
 		var citeFunction = refText.match(/{{[\s]*cite/i) ? this.CiteReference : refText.match(/{{[\s]*Citation/i) ? this.CitationReference : this.RawReference;
 
 		if(citeFunction != this.RawReference)
 		{
 			var workingstring = refText.match(/{{[\s]*(cite|Citation)[\s\S]*?}}/i)[0];
 			var match = refText.match(this.REF_REGEX);
 
 			if(match &amp;&amp; match != null)
 			{
 				var name = match[1] || match[2] || match[3]; // 3 possibilities, corresponding to above regex, are &lt;ref name=&quot;foo&quot;&gt;, &lt;ref name='bar'&gt;, and &lt;ref name=baz&gt;
 			}
 
 			var cutupstring = workingstring.split(/\|/g);
 
 			// This little hack relies on the fact that 'e' appears first as the last letter of 'cite', and the type is next.
 			if(citeFunction == this.CiteReference)
 			{
 				var beforeBar = cutupstring[0];
 				var typeStart = beforeBar.toLowerCase().indexOf('e');
 				// First end curly brace
 				var rightCurly = beforeBar.indexOf('}');
 				// Usually, rightCurly will be -1.  But this takes into account empty references like &lt;ref&gt;{{cite web}}&lt;/ref&gt;
 				var typeEnd = rightCurly != -1 ? rightCurly : beforeBar.length;
 				// grab the type, then trim it.
 				var type = $.trim(beforeBar.substring(typeStart + 1, typeEnd));
 			}
 		}
 		// type may be undefined, but that's okay.
 		var citation = new citeFunction({&quot;name&quot;: name, &quot;type&quot;: type, &quot;save&quot;: true, &quot;inMWEditBox&quot;: true, &quot;orig&quot;: refText});
 
 		if(citeFunction != this.RawReference)
 		{
 			var split = this.splitNameVals(workingstring);
 			var names = split.names;
 			var values = split.values;
 
 			for (var j = 0; j &lt; names.length; j++)
 			{
 				/* Drop blank space, and |'s without params, which are never correct for
 				 citation templates.*/
 				var paramName = $.trim(names[j]).replace(/(?:\s*\|)*(.*)/, &quot;$1&quot;);
 				var paramVal = $.trim(values[j]);
 						       // Should there be a setParam function?  It could handle empty values, and even drop (siliently or otherwise) invalid parameters.  Alternatively, should params be passed in the constructor?
 				if (paramVal != &quot;&quot;)
 				{
 					citation.params[paramName] = paramVal;
 				}
 			}
 		}
 		return citation;
 	},
 
 	// TODO: Use https://gerrit.wikimedia.org/r/#/c/67166/ when merged.
 	/**
 	 * Date-formatting class
 	 *
 	 * @param {String} format one of the format strings supported by MW core.
 	 *   Currently, the supported values are 'default', 'mdy', 'dmy', 'ymd', and 'ISO 8601'.
 	 *   If an unknown value is passed, it will use wgDefaultDateFormat.
 	 */
 	DateFormatter: function (format) {
 		// 1-indexed (due to filler item at 0), in page content language.
 		var monthNames = mw.config.get('wgMonthNames');
 
 		var supportedFormats = ['mdy', 'dmy', 'ymd', 'ISO 8601'];
 
 		if($.inArray(format, supportedFormats) === -1) {
 			format = mw.config.get('wgDefaultDateFormat');
 		}
 
 		function getMonthName(date) {
 			return monthNames[date.getMonth() + 1];;
 		}
 
 		this.formatAsMdy = function(date) {
 			return getMonthName(date) + ' ' + date.getDate() + ', ' + date.getFullYear();
 		};
 
 		this.formatAsDmy = function(date) {
 			return date.getDate() + ' ' + getMonthName(date) + ' ' + date.getFullYear();
 		};
 
 		this.formatAsYmd = function(date) {
 			return date.getFullYear() + ' ' + getMonthName(date) + ' ' + date.getDate();
 		};
 
 		this.formatAsISO8601 = function(date) {
 			return date.getFullYear() + '-' +
 				(date.getMonth() &lt; 9 ? '0' : '') + (date.getMonth() + 1) + '-' +
 				(date.getDate() &lt; 10 ? '0' : '') + date.getDate();
 		};
 
 		var formatters =
 		{
 			mdy: this.formatAsMdy,
 			dmy: this.formatAsDmy,
 			ymd: this.formatAsYmd,
 			'ISO 8601': this.formatAsISO8601
 		};
 
 		/**
 		 * Formats date according to stored preference
 		 *
 		 * @param {Date} date date to format
 		 *
 		 * @return {String} formatted date as String
 		 */
 		this.format = function(date)
 		{
 			return formatters[format](date);
 		};
 	},
 
 	/**
 	 * Root reference type. Parent of RawReference, CiteReference, and CitationReference.
 	 * @class AbstractReference
 	 * @for	proveit
 	 * @constructor
 	 * @param {Object} argObj argument object with keys for each option
 	*/
 	AbstractReference: function(argObj)
 	{
 		// CiteReference has a non-trivial override of this.  This is defined early (and conditionally) because it is used in the constructor.
 		if(!this.setType)
 		{
 			/**
 			 * @param {String} type type of reference
 			 */
 			this.setType = function(type)
 			{
 				this.type = type;
 			};
 		}
 
 		/**
 		 * Update citation strings after changing reference.  This runs after modifying a reference's fields (name, params), but before changing orig
 		 */
 		this.update = function()
 		{
 			var newCiteText = this.toString();
 			var strings = this.getCitationStrings();
 
 			/*
 			 * Update main citation in strings list.
 			 *
 			 * TODO:
 			 * Use strings array here to find and update citations that are not main references.  As is, they are orphaned.
 			 * Both array and textbox should be updated.
 			 * It may be enough to just set all non-main citations in text and array to this.getInsertionText(false).
 			 * However, if they remove the name entirely (not recommended), that would be a problem.
 			 */
 			if(strings.length &gt; 0) // This implies there was a name before
 			{
 				for(var i = 0; i &lt; strings.length; i++)
 				{
 					// If we find the full citation as a citation, update to the new text.
 					if(strings[i] == this.orig)
 					{
 						// this.orig itself is updated in updateInText
 						strings[i] = newCiteText;
 					}
 				}
 			}
 			else if(this.name != null) // They have added a name, so we should have a main citation.
 			{
 				// Now that it has a name, it is a citation to itself.
 				strings.push(newCiteText);
 			}
 		};
 		/**
 		 * &amp;lt;ref name /&amp;gt; for reference
 		 * @type String
 		 */
 		 this.name = argObj.name != &quot;&quot; ? argObj.name : null; // Save blank names as null
 
 		/*
 		  type of reference, e.g. cite web, cite news.  Also used (including for CitationReference objects) to determine default fields.
 		 */
 		this.setType(argObj.type);
 
  		 //TODO: Re-examine whether both (or indeed either) of save or inMWEditBox are really necessary.  Can it be determined from context?
 
  		/**
 		 * flag to determine whether citation must be saved.  false indicates &quot;dirty&quot; citation that has yet to be updated in text and metadata.
 		 * @type Boolean
 		*/
 		this.save = argObj.save;
 
 		/**
 		 * true if and only if the ref is in the MW edit box with the same value as this object's orig.
 		 * @type Boolean
  		 */
 		this.inMWEditBox = argObj.inMWEditBox;
 
 		/**
 		 * original wikitext for reference
 		 * @type String
 		 */
 		this.orig = argObj.orig;
 
 		/**
 		 * mapping of parameter names to values
 		 * @type Object
 		 */
 		this.params = {};
 
 		/**
 		 * Convenience method.  Returns sorter for parameters.
 		 * @return {Function} sorter for parameters
 		*/
 		this.getSorter = function()
 		{
 			var thisCite = this; // Make closure work as intended.
 			// Sorter uses paramSortKey first, then falls back on alphabetical order.
 			return function(paramA, paramB)
 			{
 				var aInd = thisCite.getSortIndex(paramA);
 				var bInd = thisCite.getSortIndex(paramB);
 				if(aInd != -1 &amp;&amp; bInd != -1)
 				{
 					return aInd - bInd;
 				}
 				else
 				{
 					proveit.log('Parameter missing from getSortIndex, which causes the sort to be invalid. paramA: ', paramA, ', aInd: ', aInd, ', paramB: ', paramB, ', bInd: ', bInd);
 					if(paramA &lt; paramB)
 					{
 						return -1;
 					}
 					else if(paramA == paramB)
 					{
 						return 0;
 					}
 					else
 					{
 						return 1;
 					}
 				}
 			};
 		};
 
 		/**
 		 * Returns true if this reference is valid, false otherwise.
 		 * Assume all AbstractReference objects are valid.  Can be overridden in subtypes.
 		 * @return {Boolean} AbstractReference.isValid always returns true
 		*/
 		this.isValid = function(){return true;};
 
 		/**
 		 * Generates label for reference using title, author, etc.
 		 * @return {String} the label that was generated
 		 */
 		this.getLabel = function()
 		{
 			var label = &quot;&quot;;
 
 			if (this.params.author)
 			{
 				label = this.params.author + &quot;; &quot;;
 			}
 			else if (this.params.last)
 			{
 				label = this.params.last;
 				if (this.params.first)
 				{
 					label += &quot;, &quot; + this.params.first;
 				}
 				label += &quot;; &quot;;
 			}
 
 			if (this.params.title)
 			{
 				label += this.params.title;
 			}
 
 			if(label == &quot;&quot;)
 			{
 				var value;
 				for (value in this.params)
 				{
 					break;
 				}
 				if(value) // There could be no parameters
 				{
 					label = value;
 				}
 			}
 			return label;
 		};
 
 
 		/**
 		 * Gets insertion text (for edit box).
 		 *
 		 * TODO: Generate a regex object instead (getInsertionRegExp), so highlighting would not fail due to trivial changes (e.g. spacing).
 		 * @param {Boolean} full If true, insert full text, otherwise ref name only
 		 * @return {String} insertion text
 		 */
 		this.getInsertionText = function(full)
 		{
 			if(full)
 			{
 				return this.toString();
 			}
 			else
 			{
 				if(this.name)
 				{
 					return &quot;&lt;ref name=\&quot;&quot;
 						+ this.name + &quot;\&quot; /&gt;&quot;;
 				}
 				else
 				{
 					throw new Error(&quot;getInsertionText: ref.name is null&quot;);
 				}
 			}
 		};
 
 		/**
 		 * Updates this reference in the edit box.
 		 */
 		this.updateInText = function()
 		{
 			var txtarea = proveit.getMWEditBox();
 
 			if (!txtarea || txtarea == null)
 				return;
 
 			txtarea.focus();
 			var text = proveit.getMWEditValue();
 
 			text = text.replace(this.orig, this.toString());
 
 			// Do replacement in textarea.
 			txtarea.value = text;
 
 			// Baseline for future modifications
 
 			this.orig = this.toString();
 			this.save = true;
 
 			proveit.highlightTargetString(this.toString());
 		};
 
 		/**
 		 * Internal helper method for toString.
 		 * @param {String} template template for ref (currently &quot;cite&quot; or &quot;Citation&quot;
 		 * @param {Boolean} includeType true to include this.type, false otherwise
 		 * @return {String} string for current reference
 		 */
 		this.toStringInternal = function(template, includeType)
 		{
 			if(this.name)
 			{
 				var returnstring = &quot;&lt;ref name=\&quot;&quot; + this.name + &quot;\&quot;&gt;&quot;;
 			}
 			else
 			{
 				var returnstring = &quot;&lt;ref&gt;&quot;;
 			}
 			returnstring += &quot;{{&quot; + template + (includeType ? &quot; &quot; + this.type : &quot;&quot;);
 			for (var name in this.params)
 			{
 				returnstring += &quot; | &quot; + name + &quot;=&quot; + this.params[name];
 			}
 			returnstring += &quot;}}&lt;/ref&gt;&quot;;
 			return returnstring;
 		};
 
 		/**
 		 * Array of citation strings for this reference.
 		 * @type Array
 		*/
 		this.citationStrings = [];
 
 		/**
 		 * Sets citationStrings to an array
 		 * @param {Array} strings array of citation strings, not null
 		 */
 		this.setCitationStrings = function(strings)
 		{
 			this.citationStrings = strings;
 		};
 
 		/**
 		 * Gets array of citationStrings.
 		 * @return {Array} (possibly empty) array of citation strings.  Will not return null.
 		 */
 		this.getCitationStrings = function()
 		{
 			return this.citationStrings;
 		};
 
 		/**
 		 * Get icon URL for reference
 		 * @return {String} icon URL
 		 */
 		this.getIcon = function()
 		{
 			return proveit.STATIC_BASE + &quot;page_white.png&quot;;
 		};
 	},
 
 	/**
 	 * Constructor for CiteReference type.
 	 * @class CiteReference
 	 * @for proveit
 	 * @constructor
 	 * @extends AbstractReference
 	 * @param {Object} argObj the argument object, with keys for each option
 	*/
 	CiteReference: function(argObj)
 	{
 		/* This is basically a fast representation of the template redirects, along with
 		 * self-mappings.
 		 */
 		var typeNameMappings =
 		{
 			web: &quot;web&quot;,
 			book: &quot;book&quot;,
 			journal: &quot;journal&quot;,
 			conference: &quot;conference&quot;,
 			encyclopedia: &quot;encyclopedia&quot;,
 			news: &quot;news&quot;,
 			newsgroup: &quot;newsgroup&quot;,
 			paper: &quot;journal&quot;,
 			&quot;press release&quot;: &quot;press release&quot;,
 		        &quot;pressrelease&quot;: &quot;press release&quot;,
 			interview: &quot;interview&quot;,
 		        episode: &quot;episode&quot;,
 			&quot;AV media&quot;: &quot;AV media&quot;,
 			DVD: &quot;AV media&quot;,
 			audio: &quot;AV media&quot;,
 			&quot;av media&quot;: &quot;AV media&quot;,
 			cd: &quot;AV media&quot;,
 			dvd: &quot;AV media&quot;,
 			media: &quot;AV media&quot;,
 			movie: &quot;AV media&quot;,
 			&quot;music video&quot;: &quot;AV media&quot;,
 			video: &quot;AV media&quot;,
 			visual: &quot;AV media&quot;
 		};
 
 		// Sets the type (e.g. web for cite web), applying the mappings.  This is up top because it is used in AbstractReference constructor.
 		this.setType = function(rawType)
 		{
 			var mappedType = typeNameMappings[rawType];
 			if(mappedType != null)
 				this.type = mappedType;
 			else
 				this.type = rawType; // Use naive type as fallback.
 		};
 
 		/**
 		 * Returns the type for display purposes, based on description messages.  For example, for &quot;AV media&quot; it currently returns &quot;Audiovisual work&quot;.
 		 *
 		 * @return {String} type for display
 		 */
 		this.getTypeForDisplay = function()
 		{
 			return proveit.getDescriptions()[this.type];
 		};
 
 		proveit.AbstractReference.call(this, argObj);
 
 		// TODO: Should CiteReference.getSortIndex and CitationReference.getSortIndex be merged into AbstractCitation?  Less fine-grained, but simpler to maintain.
 		/**
 		 * Returns the sort index for a given parameter
 		 * @param {String} param parameter name
 		 * @return {Number} sort index if found, otherwise -1
 		 */
 		this.getSortIndex = function(param)
 		{
 			// This is the order fields will be displayed or outputted.
 
 			return $.inArray(param, [
 				&quot;url&quot;,
 				&quot;title&quot;,
 				&quot;trans_title&quot;,
 				&quot;encyclopedia&quot;,
 				&quot;publisher&quot;,
 				&quot;work&quot;,
 				&quot;date&quot;,
 				&quot;agency&quot;,
 				&quot;accessdate&quot;,
 				&quot;author&quot;,
 				&quot;last&quot;,
 				&quot;first&quot;,
 				&quot;subject&quot;,
 				&quot;subjectlink&quot;,
 				&quot;inventor&quot;,
 				&quot;editor&quot;,
 				&quot;author2&quot;,
 				&quot;last2&quot;,
 				&quot;first2&quot;,
 				&quot;subject2&quot;,
 				&quot;subjectlink2&quot;,
 				&quot;author3&quot;,
 				&quot;last3&quot;,
 				&quot;first3&quot;,
 				&quot;subject3&quot;,
 				&quot;subjectlink3&quot;,
 				&quot;author4&quot;,
 				&quot;last4&quot;,
 				&quot;first4&quot;,
 				&quot;subject4&quot;,
 				&quot;author5&quot;,
 				&quot;last5&quot;,
 				&quot;first5&quot;,
 				&quot;author6&quot;,
 				&quot;last6&quot;,
 				&quot;first6&quot;,
 				&quot;author7&quot;,
 				&quot;last7&quot;,
 				&quot;first7&quot;,
 				&quot;author8&quot;,
 				&quot;last8&quot;,
 				&quot;first8&quot;,
 				&quot;author9&quot;,
 				&quot;last9&quot;,
 				&quot;first9&quot;,
 				&quot;authorlink&quot;,
 				&quot;coauthors&quot;,
 				&quot;interviewer&quot;,
 				&quot;cointerviewers&quot;,
 				&quot;type&quot;,
 				&quot;newsgroup&quot;,
 				&quot;journal&quot;,
 				&quot;booktitle&quot;,
 				&quot;program&quot;,
 				&quot;episodelink&quot;,
 				&quot;series&quot;,
 				&quot;serieslink&quot;,
 				&quot;credits&quot;,
 				&quot;network&quot;,
 				&quot;station&quot;,
 				&quot;callsign&quot;,
 				&quot;city&quot;,
 				&quot;airdate&quot;,
 				&quot;began&quot;,
 				&quot;ended&quot;,
 				&quot;season&quot;,
 				&quot;seriesno&quot;,
 				&quot;number&quot;,
 				&quot;minutes&quot;,
 				&quot;transcript&quot;,
 				&quot;transcripturl&quot;,
 				&quot;people&quot;,
 				&quot;year&quot;,
 				&quot;month&quot;,
 				&quot;article&quot;,
 				&quot;contribution&quot;,
 				&quot;format&quot;,
 				&quot;medium&quot;,
 				&quot;newspaper&quot;,
 				&quot;conference&quot;,
 				&quot;volume&quot;,
 				&quot;edition&quot;,
 				&quot;issue&quot;,
 				&quot;location&quot;,
 				&quot;pages&quot;,
 				&quot;page&quot;,
 				&quot;language&quot;,
 				&quot;isbn&quot;,
 				&quot;issn&quot;,
 				&quot;oclc&quot;,
 				&quot;doi&quot;,
 				&quot;pmid&quot;,
 				&quot;id&quot;,
 				&quot;archiveurl&quot;,
 				&quot;archivedate&quot;,
 				&quot;deadurl&quot;,
 				&quot;time&quot;,
 				&quot;quote&quot;,
 				&quot;ref&quot;
 			]);
 		};
 
 		/**
 		 * Returns this reference as a string.
 		 * @return {String} reference as string
 		 */
 		this.toString = function()
 		{
 			return this.toStringInternal(&quot;cite&quot;, true);
 		};
 
 		// References without these parameters will be flagged in red.
 		// True indicates required (null, or undefined, means not required)
 		var requiredParams =
 		{
 			web: { &quot;url&quot;: true, &quot;title&quot;: true},
 			book: { &quot;title&quot;: true },
 			journal: { &quot;title&quot;: true },
 			conference: { &quot;title&quot;: true },
 			encyclopedia: { &quot;title&quot;: true, &quot;encyclopedia&quot;: true },
 			news: { &quot;title&quot;: true, &quot;work&quot;: true, &quot;date&quot;: true },
 			newsgroup: { &quot;title&quot;: true },
 			&quot;press release&quot;	: { &quot;title&quot;: true },
 			interview: { &quot;last&quot;: true }, // TODO: Interview requires last *or* subject.  Currently, we can't represent that.
 			episode: { &quot;title&quot;: true },
 			&quot;AV media&quot;: { &quot;title&quot;: true }
 		};
 
 		/**
 		 * Return required parameters for this citation type.
 		 * @return {Object} object with required parameters as keys and true as value; empty object for unknown type
 		*/
 		this.getRequiredParams = function()
 		{
 			var curReq = requiredParams[this.type];
 			if(curReq)
 				return curReq;
 			else
 				return {}; // Return empty object rather than null to avoid dereferencing null.
 		};
 
 		// These paramaters will be auto-suggested when editing.
 		var defaultParams =
 		{
 		        web: [ &quot;url&quot;, &quot;title&quot;, &quot;author&quot;, &quot;accessdate&quot;, &quot;work&quot;, &quot;publisher&quot;, &quot;date&quot;, &quot;pages&quot;],
 		        book: [ &quot;title&quot;, &quot;author&quot;, &quot;authorlink&quot;, &quot;year&quot;, &quot;isbn&quot;, &quot;publisher&quot;, &quot;location&quot;, &quot;pages&quot;, &quot;url&quot; ],
 		        journal: [ &quot;title&quot;, &quot;author&quot;, &quot;journal&quot;, &quot;volume&quot;, &quot;issue&quot;, &quot;year&quot;, &quot;month&quot;, &quot;pages&quot;, &quot;url&quot;, &quot;doi&quot; ],
 		        conference: [ &quot;conference&quot;, &quot;title&quot;, &quot;booktitle&quot;, &quot;author&quot;, &quot;editor&quot;, &quot;year&quot;, &quot;month&quot;, &quot;url&quot;, &quot;id&quot;, &quot;accessdate&quot;, &quot;location&quot;, &quot;pages&quot;, &quot;publisher&quot; ],
 			encyclopedia: [ &quot;title&quot;, &quot;encyclopedia&quot;, &quot;author&quot;, &quot;editor&quot;, &quot;accessdate&quot;, &quot;edition&quot;, &quot;year&quot;,
 			&quot;publisher&quot;, &quot;volume&quot;, &quot;location&quot;, &quot;pages&quot; ],
 		        news: [ &quot;title&quot;, &quot;author&quot;, &quot;url&quot;, &quot;work&quot;, &quot;date&quot;, &quot;accessdate&quot;, &quot;pages&quot;, &quot;location&quot;, &quot;agency&quot; ],
 			newsgroup: [ &quot;title&quot;, &quot;author&quot;, &quot;date&quot;, &quot;newsgroup&quot;, &quot;id&quot;, &quot;url&quot;, &quot;accessdate&quot; ],
 		        &quot;press release&quot;	: [ &quot;title&quot;, &quot;url&quot;, &quot;publisher&quot;, &quot;date&quot;, &quot;accessdate&quot; ],
 			interview: [&quot;last&quot;, &quot;first&quot;, &quot;subjectlink&quot;, &quot;interviewer&quot;, &quot;title&quot;, &quot;callsign&quot;, &quot;city&quot;, &quot;date&quot;, &quot;program&quot;, &quot;accessdate&quot;],
 		        episode: [&quot;title&quot;, &quot;series&quot;, &quot;credits&quot;, &quot;airdate&quot;, &quot;city&quot;, &quot;network&quot;, &quot;season&quot;],
 			&quot;AV media&quot;: [&quot;people&quot;, &quot;date&quot;, &quot;url&quot;, &quot;title&quot;, &quot;medium&quot;, &quot;location&quot;, &quot;publisher&quot;]
 		};
 
 		/**
 		 * Returns default parameters (to be suggested when editing) for current reference
 		 * @return {Array} array of default parameter names; empty array if unknown
 		*/
 		this.getDefaultParams = function()
 		{
 			var curDefault = defaultParams[this.type];
 			if(curDefault)
 				return curDefault;
 			else
 				return []; // Return empty array rather than null to avoid dereferencing null.
 		};
 
 		this.isValid = function()
 		{
 		        if(this.type == '')
 			{
 			    return false;
 			}
 			var req = this.getRequiredParams();
 			var i = 0;
 			var allFound = true;
 			for(var reqParam in req)
 			{
 				/* Ignore parameters in req object that are null, undefined, or false.
 				   They are not required. */
 				if(!req[reqParam])
 					continue;
 				allFound &amp;= (reqParam in this.params);
 				if(!allFound)
 					break;
 			}
 			return allFound;
 		};
 
 		var iconMapping =
 		{
 			web: &quot;page_white_world.png&quot;,
 			book: &quot;book.png&quot;,
 			journal: &quot;page_white_text.png&quot;,
 			news: &quot;newspaper.png&quot;,
 			newsgroup: &quot;comments.png&quot;,
 			&quot;press release&quot;: &quot;transmit_blue.png&quot;,
 			interview: &quot;telephone.png&quot;,
 			episode: &quot;television.png&quot;,
 			&quot;AV media&quot;: &quot;film.png&quot;
 		};
 
 		var superGetIcon = this.getIcon;
 		this.getIcon = function()
 		{
 			var icon = iconMapping[this.type];
 			if(icon)
 			{
 				return proveit.STATIC_BASE + icon;
 			}
 			return superGetIcon.call(this);
 		};
 	},
 
 	/**
 	 * A function for citation style refs.
 	 * @class CitationReference
 	 * @for proveit
 	 * @constructor
 	 * @extends AbstractReference
 	 * @param {Object} argObj argument object with keys for each option
 	 */
 
 	CitationReference: function(argObj) {
 		proveit.AbstractReference.call(this, argObj);
 
 		// None currently required;
 		var requiredParams = {};
 
 		// These paramaters will be auto-suggested when editing.
 		var defaultParams =
 		{
 			web: [ &quot;url&quot;, &quot;author&quot;, &quot;title&quot;, &quot;date&quot;, &quot;accessdate&quot;],
 			news: [ &quot;author&quot;, &quot;title&quot;, &quot;newspaper&quot;, &quot;url&quot;, &quot;publication-place&quot;, &quot;volume&quot;, &quot;issue&quot;, &quot;date&quot;, &quot;pages&quot;],
 			encyclopedia: [&quot;author&quot;, &quot;editor&quot;, &quot;contribution&quot;, &quot;title&quot;, &quot;publisher&quot;, &quot;place&quot;, &quot;year&quot;, &quot;volume&quot;, &quot;pages&quot;],
 			book: [&quot;author&quot;, &quot;title&quot;, &quot;publisher&quot;, &quot;place&quot;, &quot;year&quot;],
 			journal: [&quot;author&quot;, &quot;title&quot;, &quot;journal&quot;, &quot;volume&quot;, &quot;issue&quot;, &quot;year&quot;, &quot;pages&quot;],
 			patent: [&quot;inventor&quot;, &quot;title&quot;, &quot;issue-date&quot;, &quot;patent-number&quot;, &quot;country-code&quot;]
 		};
 
 		/**
 		 * Returns the sort index for a given parameter
 		 * @param {String} param parameter name
 		 * @return {Number} sort index if found, otherwise -1
 		 */
 		this.getSortIndex = function(param)
 		{
 			// This is the order fields will be displayed or outputted.
 			return $.inArray(param, [
 				&quot;last&quot;,
 				&quot;first&quot;,
 				&quot;url&quot;,
 				&quot;author&quot;,
 				&quot;editor&quot;,
 				&quot;contribution&quot;,
 				&quot;author-link&quot;,
 				&quot;last2&quot;,
 				&quot;first2&quot;,
 				&quot;author2-link&quot;,
 				&quot;publication-date&quot;,
 				&quot;inventor&quot;,
 				&quot;title&quot;,
 				&quot;issue-date&quot;,
 				&quot;patent-number&quot;,
 				&quot;country-code&quot;,
 				&quot;journal&quot;,
 				&quot;volume&quot;,
 				&quot;newspaper&quot;,
 				&quot;issue&quot;,
 				&quot;date&quot;,
 				&quot;publisher&quot;,
 				&quot;place&quot;,
 				&quot;year&quot;,
 				&quot;edition&quot;,
 				&quot;publication-place&quot;,
 				&quot;series&quot;,
 				&quot;version&quot;,
 				&quot;pages&quot;,
 				&quot;page&quot;,
 				&quot;id&quot;,
 				&quot;isbn&quot;,
 				&quot;doi&quot;,
 				&quot;oclc&quot;,
 				&quot;accessdate&quot;
 			]);
 		};
 
 		/**
 		 * Returns this reference as a string.
 		 * @return {String} reference as string
 		 */
 		this.toString = function()
 		{
 			return this.toStringInternal(&quot;Citation&quot;, false);
 		};
 
 		/**
 		 * Return required parameters for this citation type.
 		 * @return {Object} object with required parameters as keys and true as value; empty object for unknown type
 		 */
 		this.getRequiredParams = function()
 		{
 			return requiredParams;
 		};
 
 		/**
 		 * Returns default parameters (to be suggested when editing) for current reference
 		 * @return {Array} array of default parameter names; empty array if unknown
 		 */
 		this.getDefaultParams = function()
 		{
 			if(this.type)
 			{
 				return defaultParams[this.type];
 			}
 			else
 			{
 				return [&quot;url&quot;, &quot;title&quot;, &quot;author&quot;, &quot;date&quot;, &quot;publisher&quot;]; // Can't determine more specific defaults when editing a pre-existing Citation.
 			}
 		};
 	},
 
 	/**
 	 * Constructor for RawReference type.
 	 * @class RawReference
 	 * @for proveit
 	 * @constructor
 	 * @extends AbstractReference
 	 * @param {Object} argObj the argument object, with keys for each option
 	 */
 	RawReference: function(argObj)
 	{
 		proveit.AbstractReference.call(this, argObj);
 		this.type = 'raw';
 
 		/**
 		 * Returns this reference as a string.
 		 * @return {String} reference as string
 		 */
 		this.toString = function()
 		{
 			return this.orig;
 		};
 		this.params['title'] = this.orig;
 
 		this.getIcon = function()
 		{
 			return proveit.STATIC_BASE + 'raw.png';
 		};
 
 		this.getTypeForDisplay = function()
 		{
 			return proveit.getDescriptions()['raw'];
 		};
 	},
 
 	// TODO: This should be unified with changeRefFromEditPane
 	/**
 	 * Convert the current contents of the add citation panel to a reference (i.e CiteReference(), CitationReference())
 	 * @for proveit
 	 * @param {Node} box typepane root of add GUI (pane for specific type, e.g. journal)
          * @return {AbstractReference} ref or null if no panel exists yet.
 	 */
 	getRefFromAddPane: function(box)
 	{
 		var $box = $(box);
 		var type = $box.data('proveitRefType');
 
 		// get &lt;ref&gt; name
 		var refName = $('#addrefname').val();
 
 		var citeFunc = this.togglestyle ? this.CiteReference : this.CitationReference;
 		var ref = new citeFunc({&quot;name&quot;: refName, &quot;type&quot;: type});
 
 		var paramName, paramVal;
 
 		var paramList = $(&quot;.paramlist&quot;, box)[0];
 		var paramRows = $('div', paramList);
 		for (var i = 0; i &lt; paramRows.length; i++)
 		{
 			var paramRow =  paramRows[i];
 			var valueTextbox = $(&quot;.paramvalue&quot;, paramRow)[0];
 
 			if($(paramRow).hasClass(&quot;addedrow&quot;)) // Added with &quot;Add another field&quot;
 			{
 				paramName = $.trim($(&quot;.paramdesc&quot;, paramRow)[0].value);
 			}
 			else
 			{
 				paramName = valueTextbox.id.substring(this.NEW_PARAM_PREFIX.length);
 			}
 
 			paramVal = $.trim(valueTextbox.value);
 			if(paramName != &quot;&quot; &amp;&amp; paramVal != &quot;&quot;)
 			{ // Non-blank
 				ref.params[paramName] = paramVal;
 			}
 		}
 		ref.update();
 		return ref;
 	},
 
 	/**
 	 * Called from the add citation panel, this is the function used to
 	 * add the actual citation.
 	 *
 	 * @param {AbstractReference} ref reference being added
 	 */
 	addReference: function(ref) {
 		// get this working, lots of typing here.
 
 		this.addNewElement(ref);
 
 		ref.orig = ref.toString();
 		/*
 		 * Cycle through the boxes and grab the id's versus the values, watch
 		 * for the final box and make sure to grab the type as well
 		 */
 
 		this.insertRefIntoMWEditBox(ref, true); // true means insert full text here, regardless of global toggle.
 		ref.save = true;
 		ref.inMWEditBox = true;
 	},
 
 	/**
 	 * Clear all rows of passed in add citation panes.
 	 * @param {Node} citePanes raw DOM element
 	 */
 	clearCitePanes: function(citePanes)
 	{
 		if(citePanes.hasChildNodes())
 		{
 			citePanes.removeChild(citePanes.firstChild);
 		}
 	},
 
 	/**
 	 * Add event handler to Delete Field button in Add/Edit Reference panes
 	 * @param {Node} fieldRow the fieldRow DOM element to remove
 	 */
 	activateRemoveField: function(fieldRow)
 	{
 		$('.delete-field', fieldRow).click(function()
 		{
 			$(fieldRow).hide(
 				'highlight',{},'slow',
 				function() {
 					$(fieldRow).remove();
 					}
 				);
 		});
 	},
 
 	/**
 	 * Changes the panel for the add reference panel to the correct type of entry
 	 * @param {Node} menu Raw HTML menu element
 	 */
 	changeAddPane: function(menu) {
 		// Reset scroll
 		$('#add-fields').scrollTop(0);
 		$(menu.parentNode).show(); // cite/citation vbox.
 
 		var citePanes = $(&quot;.addpanes&quot;, menu.parentNode.parentNode).get(0);
 		this.clearCitePanes(citePanes);
 		var newRefType = menu.value;
 
 		var genPane = document.getElementById(&quot;dummyCitePane&quot;).cloneNode(true);
 		var $genPane = $(genPane).attr('id', '');
 		$genPane.data('proveitRefType', newRefType);
 
 		// name the ref-name-row
 		$('.ref-name-row', $genPane).children('input').attr('id','addrefname');
 		$('.ref-name-row', $genPane).children('label').attr('for','addrefname');
 
 		// Somewhat hackish.  What's a better way?
 		var newRef;
 		if(menu.id == &quot;citemenu&quot;)
 		{
 			newRef = new this.CiteReference({});
 		}
 		else
 		{
 			newRef = new this.CitationReference({});
 		}
 		newRef.type = newRefType;
 		var descs = this.getDescriptions();
 		var defaultParams = newRef.getDefaultParams().slice(0); // copy
 		defaultParams.sort(newRef.getSorter());
 		//var required = newRef.getRequiredParams();
 
 		// Possibly, Cite objects should automatically include default parameters in their param maps.  That would seem to make this simpler.
 		for(var i = 0; i &lt; defaultParams.length; i++)
                 {
 			newRef.params[defaultParams[i]] = &quot;&quot;;
 		}
 
 		// Should there be a getParamKeys or similar function for this, or even getSortedParamKeys?
 		var newParams = [];
 		for(param in newRef.params)
 		{
 			newParams.push(param);
 		}
 		newParams.sort(newRef.getSorter());
 		var required = newRef.getRequiredParams();
 
 		var paramList = $(&quot;.paramlist&quot;, $genPane)[0];
 		for(var i = 0; i &lt; newParams.length; i++)
 		{
 			var param = newParams[i];
 			var paramBox;
 
 			if(descs[param])
 			{
 				paramBox = document.getElementById(&quot;preloadedparamrow&quot;).cloneNode(true);
 				var label = $('.paramdesc', paramBox);
 				if(required[param])
 				{
 					label.addClass(&quot;required&quot;);
 					$('.delete-field', paramBox).remove(); // don't let people remove required fields
 				}
 				else
 				{
 					this.activateRemoveField(paramBox);
 				}
 				label.text(descs[param]);
 				// Basically the same code as nameHbox above
 				label.attr(&quot;for&quot;, this.NEW_PARAM_PREFIX + param);
 				if(param == 'accessdate')
 					$('.paramvalue', paramBox).val(this.dateFormatter.format(new Date));
 			}
 			else
 			{
 				// Throwing an error here doesn't make sense if user-added fields can be copied over.
 				// throw new Error(&quot;Undefined description for param: &quot; + param);
 				paramBox = document.getElementById(&quot;addedparamrow&quot;).cloneNode(true);
 				var nameTextbox = $(&quot;.paramdesc&quot;, paramBox)[0];
 				nameTextbox.setAttribute(&quot;value&quot;, param);
 			}
 			paramBox.id = &quot;&quot;;
 			this.activateRemoveField(paramBox);
 
 			$(&quot;.paramvalue&quot;, paramBox)[0].id = this.NEW_PARAM_PREFIX + param;
 			//paramBox.childNodes[2].value = newRef.params[param]; // Causes parameters to disappear.  Why?
 			$(paramBox).show();
 			paramList.appendChild(paramBox);
 		}
 		$genPane.show();
 		$(citePanes).prepend($genPane);
 	},
 
 	/**
 	 * Create ProveIt HTML GUI
 	 */
 	createGUI: function()
 	{
 		if(this.getGUI().length &gt; 0)
 		{
 			// GUI already created
 			return false;
 		}
 
 		// more JqueryUI CSS: http://blog.jqueryui.com/2009/06/jquery-ui-172/
 		var gui = $('&lt;div/&gt;', {id: this.GUI_ID});
 		var tabs = $('&lt;div/&gt;', {id: 'tabs'});
 		var created = $('&lt;h1/&gt;');
 		var createdLink = $('&lt;a/&gt;', {title: 'Created by the ELC Lab at Georgia Tech',
 			                     href: 'http://proveit.cc.gatech.edu',
 					     target: '_blank'});
 		// Main logo in upper-right
 		var logo = $('&lt;img/&gt;', {src: this.STATIC_BASE + 'logo.png', alt: 'ProveIt', height: 30, width: 118 });
 		createdLink.append(logo);
 		created.append(createdLink);
 		// Minimize/maximize button
 		var showHideButton = $('&lt;button/&gt;', {text: 'show/hide'});
 		created.append(showHideButton);
 		tabs.append(created);
 		var header = $('&lt;ul/&gt;');
 		var view = $('&lt;li/&gt;');
 		// View tab link
 		var viewLink = $('&lt;a/&gt;', {id: 'view-link', &quot;class&quot;: 'tab-link', href: '#view-tab'});
 		viewLink.append('References (');
 		var numRefs = $('&lt;span/&gt;', {id: 'numRefs'}).
 			append('0');
 		viewLink.append(numRefs).
 			append(')');
 		view.append(viewLink);
 		header.append(view);
 		var add = $('&lt;li/&gt;');
 		// Add tab link
 		var addLink = $('&lt;a/&gt;', {id: 'add-link', &quot;class&quot;: 'tab-link', href: '#add-tab'}).
 			append('Add a Reference');
 		add.append(addLink);
 		header.append(add);
 		tabs.append(header);
 		// View tab
 		var viewTab = $('&lt;div/&gt;', {id: 'view-tab', css: {display: 'none'}});
 		// View pane used for displaying references; within view tab
 		var viewPane = $('&lt;div/&gt;', {id: 'view-pane'});
 		var viewScroll = $('&lt;div/&gt;', {&quot;class&quot;: 'scroll',
 					      style: 'height: 210px;'});
 		// Ref list root element
 		var refTable = $('&lt;table/&gt;', {id: 'refs'});
 		var dummyRef = $('&lt;tr/&gt;', {id: 'dummyRef',
 					   style: 'display: none;'});
 		dummyRef.append($('&lt;td/&gt;', {&quot;class&quot;: 'number'})).
 			append($('&lt;td/&gt;', {&quot;class&quot;: 'type'})).
 			append($('&lt;td/&gt;', {&quot;class&quot;: 'title'}));
 			//append($('&lt;td/&gt;', {&quot;class&quot;: 'details'}));
 		var editTd = $('&lt;td/&gt;', {&quot;class&quot;: 'edit'}).
 			append($('&lt;button/&gt;', {text: 'edit'}));
 		dummyRef.append(editTd);
 		refTable.append(dummyRef);
 		viewScroll.append(refTable);
 		viewPane.append(viewScroll);
 		viewTab.append(viewPane);
 		// div#edit-pane, within view tab
 		var editPane = $('&lt;div/&gt;', {id: 'edit-pane', style: 'display: none'});
 		// div#edit-fields
 		var editFields = $('&lt;div/&gt;', {id: 'edit-fields',
 					      &quot;class&quot;: 'inputs scroll',
 					      style: 'height: 170px',
 					      tabindex: -1});
 		// div.ref-name-row
 		var refNameRow = $('&lt;div/&gt;', {&quot;class&quot;: 'ref-name-row',
 					      tabindex: -1});
 		var refLabel = $('&lt;label/&gt;', {'for': 'editrefname',
 					      title: 'This is a unique identifier that can be used to refer to this reference elsewhere on the page.',
 					      &quot;class&quot;: 'paramdesc'}).
 			append('&amp;lt;ref&amp;gt; name');
 		refNameRow.append(refLabel);
 		refNameRow.append($('&lt;input/&gt;', {id: 'editrefname',
 						 &quot;class&quot;: 'paramvalue',
 						 tabindex: 0}));
 		// div.paramlist
 		var paramList = $('&lt;div/&gt;', {&quot;class&quot;: 'paramlist'});
 
 		editFields.append(refNameRow);
 		editFields.append(paramList);
 		editPane.append(editFields);
 
 		// div#edit-buttons, part of edit pane
 		var editButtons = $('&lt;div/&gt;', {id: 'edit-buttons'});
 		var addFieldButton = $('&lt;button/&gt;', {style: 'margin-right: 50px;'}).
 			append('add field');
 		editButtons.append(addFieldButton);
 		var reqSpan = $('&lt;span/&gt;', {&quot;class&quot;: 'required',
 					    text: 'bold'});
 		editButtons.append(reqSpan).
 			append(' = required field');
 		var saveButton = $('&lt;button/&gt;', {&quot;class&quot;: 'right-side accept',
 		                                 text: 'update edit form'});
 		editButtons.append(saveButton);
 		var cancelButton = $('&lt;button/&gt;', {&quot;class&quot;: 'right-side cancel',
 			                           text: 'cancel'});
 		editButtons.append(cancelButton);
 		editPane.append(editButtons);
 		viewTab.append(editPane);
 		tabs.append(viewTab);
 
 		// dumy cite pane
 		var dummyCite = $('&lt;div/&gt;', {id: 'dummyCitePane',
 					     &quot;class&quot;: 'typepane',
 					     style: 'display: none'});
 		var addRefNameRow = refNameRow.clone();
 		//$('input', addRefNameRow).attr('id', 'addrefname');
 		//$('label', addRefNameRow).attr('for', 'addrefname');
 		dummyCite.append(addRefNameRow);
 		dummyCite.append($('&lt;div/&gt;', {&quot;class&quot;: 'paramlist'}));
 		tabs.append(dummyCite);
 
 		var preloadedparam = $('&lt;div/&gt;', {id: 'preloadedparamrow',
 						  &quot;class&quot;: 'preloadedrow input-row',
 						  style: 'display: none'}).
 			append($('&lt;label/&gt;', {&quot;class&quot;: 'paramdesc'}));
 		var paramvalue = $('&lt;input/&gt;', {&quot;class&quot;: 'paramvalue',
 				                tabindex: 0});
 	        preloadedparam.append(paramvalue);
 		var deleteButton = $('&lt;button/&gt;', {&quot;class&quot;: 'delete-field',
 						   tabindex: -1}).
 			append('delete field');
 		preloadedparam.append(deleteButton);
 		tabs.append(preloadedparam);
 		var addedparam = $('&lt;div/&gt;', {id: 'addedparamrow',
 					      &quot;class&quot;: 'addedrow input-row',
  					      style: 'display: none'}).
 		        append($('&lt;input/&gt;', {&quot;class&quot;: 'paramdesc',
 					      tabindex: 0})).
 			append(paramvalue.clone()).
 			append(deleteButton.clone());
 		tabs.append(addedparam);
 		// Add tab
 		var addTab = $('&lt;div/&gt;', {id: 'add-tab', css: {display: 'none'}});
 		var addFields = $('&lt;div/&gt;', {id: 'add-fields',
 					     &quot;class&quot;: 'inputs scroll',
 					     style: 'height: 170px',
 					     tabindex: -1});
 		var cite = $('&lt;div/&gt;', {style: 'display: none',
 					id: 'cite',
 				        &quot;class&quot;: 'input-row'});
 		var refCiteTypeLabel = $('&lt;label/&gt;', {'for': 'citemenu',
 						  &quot;class&quot;: 'paramdesc required',
 						  text: 'Reference type'});
 		cite.append(refCiteTypeLabel);
 		var citemenu = $('&lt;select/&gt;', {id: 'citemenu',
 					       change: function()
 					       {
 						       proveit.changeAddPane(citemenu.get(0));
 					       }});
          	var citeTypes = this.CiteReference.getTypes();
 		var descs = this.getDescriptions();
 		for(var i = 0; i &lt; citeTypes.length; i++)
 		{
 			citemenu.append($('&lt;option/&gt;', {value: citeTypes[i],
 						        text: descs[citeTypes[i]]}));
 		}
 		cite.append(citemenu);
 		addFields.append(cite);
 		addFields.append($('&lt;div/&gt;', {&quot;class&quot;: 'addpanes',
 					      id: 'citepanes',
 					      tabindex: -1}));
 		var citation = $('&lt;div/&gt;', {style: 'display: none',
 					    id: 'citation',
 					    &quot;class&quot;: 'input-row'});
 		var refCitationTypeLabel = refCiteTypeLabel.clone().attr('for', 'citationmenu');
 		citation.append(refCitationTypeLabel);
 		var citationmenu = $('&lt;select/&gt;', {id: 'citemenu',
 		                                   change: function()
 						   {
 							   proveit.changeAddPane(citationmenu.get(0));
 						   }});
 		var citationTypes = ['web', 'book', 'journal', 'encyclopedia', 'news', 'patent'];
 		for(var j = 0; j &lt; citationTypes.length; j++)
 		{
 			citationmenu.append($('&lt;option/&gt;', {value: citationTypes[i],
 			                                    text: descs[citationTypes[i]]}));
 		}
 		citation.append(citationmenu);
 		addFields.append(citation).
 			append($('&lt;div/&gt;', {&quot;class&quot;: 'addpanes',
 					    id: 'citationpanes', style: 'display: none;'}));
 		addTab.append(addFields);
 		// Add buttons, part of add tab
 		var addButtons = $('&lt;div/&gt;', {id: 'add-buttons'});
 		addButtons.append($('&lt;button/&gt;', {style: 'margin-right: 50px;',
 						  text: 'add field'})).
 			append(reqSpan.clone()).
 			append(&quot; = required&quot;).
 			append(saveButton.clone().text('insert into edit form')).
 			append(cancelButton.clone());
 		addTab.append(addButtons);
 		tabs.append(addTab);
 		gui.append(tabs);
 		$(document.body).prepend(gui);
 
 		var cancelEdit = function() {
 				$(&quot;#edit-pane&quot;).hide();
 				$(&quot;#view-pane&quot;).show();
 		};
 
 		// set up tabs
 		$(&quot;#tabs&quot;).tabs({
 			selected: 0,
 				show: function(event,ui)
 				{
 					switch(ui.index)
 					{
 						case 0: // view
 						//$('tr.selected').focus();
 						break;
 
 						case 1: // add
 						    cancelEdit();
 						    proveit.changeAddPane(document.getElementById(proveit.togglestyle ? 'citemenu' : 'citationmenu'));
 						break;
 
 				      //	case 1: // edit
 						// proveit.updateEditPane();
 						//	$('tr.selected').dblclick();
 						//break;
 
 						default:
 						// nothing
 					}
 				}
 		});
 
 		// handle clicking on tabs
 		$(viewLink).click(function(){
 				if($(viewTab).is(&quot;:hidden&quot;))
 					proveit.toggleViewAddVisibility();
 				else
 					cancelEdit();	// Edit and view are the same tab, so we handle this specially.
 			});
 		$(addLink).click(function(){
 				if($(addTab).is(&quot;:hidden&quot;))
 					proveit.toggleViewAddVisibility();
 			});
 
 		// add panel buttons
 		$(&quot;#add-buttons button:first&quot;).button({
 			icons: {
 				primary: 'ui-icon-circle-plus'
 			}
 		}).click(function()
 			 {
 				 proveit.addPaneRow(document.getElementById(&quot;add-tab&quot;));
 			 })
 		.next().next().button({
 			icons: {
 				primary: 'ui-icon-circle-check',
 				secondary: 'ui-icon-circle-arrow-e'
 			}
 		}).click(function()
 			 {
 				 proveit.addReference(proveit.getRefFromAddPane($('#add-tab .typepane').get(0)));
 				 $(&quot;#tabs&quot;).tabs( { selected: '#view-tab' } );
 				 $(&quot;div.scroll, #view-pane&quot;).scrollTop(100000); // scroll to new ref
 			 }).next().
 		button({
 			icons: {
 				primary: 'ui-icon-circle-close'
 				}
 		}).click(function()
 			 {
 				 $(&quot;#tabs&quot;).tabs( { selected: '#view-tab' } );
 			 });
 
 		// cancel buttons
 		$(&quot;button.cancel&quot;).click(cancelEdit);
 
 		// edit panel buttons
 		$(&quot;#edit-buttons button:first&quot;).button({
 			icons: {
 				primary: 'ui-icon-circle-plus'
 			}
 		}).click(function()
 			 {
 				 proveit.addPaneRow($(&quot;#edit-pane&quot;));
 			 }).
 		next().next().
 		button({
 			icons: {
 				primary: 'ui-icon-circle-check'
 			}
 		}).next().button({
 			icons: {
 				primary: 'ui-icon-circle-close'
 			}
 		});
 
 		// delete field button
 		$(&quot;.delete-field&quot;).button({
 			icons: {
 				primary: 'ui-icon-close'
 			},
 			text: false
 		});
 
 		// create the minimize button
 		showHideButton.button({
 			icons: {
 				primary: 'ui-icon-triangle-1-n'
 			},
 			text: false
 		});
 
 		var viewAndAdd = $(&quot;#view-tab, #add-tab&quot;);
 		this.viewAndAddPanes = viewAndAdd;
 
 		function minimize()
 		{
 			viewAndAdd.hide();
 			showHideButton.button(&quot;option&quot;, &quot;icons&quot;, { primary: 'ui-icon-triangle-1-n' } );
 		}
 
 		function maximize()
 		{
 			viewAndAdd.show();
 			showHideButton.button(&quot;option&quot;, &quot;icons&quot;, { primary: 'ui-icon-triangle-1-s' } );
 		}
 
 		// set up the minimize button
 		showHideButton.toggle(
 			maximize,
 			minimize
 		);
 
 		this.toggleViewAddVisibility = function()
 		{
 			showHideButton.click();
 		};
 
 		this.scanForRefs();
 
 		$(&quot;#refs tr&quot;).eq(0).click().click(); // select first item in list.  TODO: Why two .click?
 
 		// alternate row colors
 		$(&quot;#refs tr:even&quot;).addClass('light');
 		$(&quot;#refs tr:odd&quot;).addClass('dark');
 	},
 
 	/**
 	 * A reference to the set containing two items, the view and add tabs.  Will be initialized by createGUI, so it is non-null if ProveIt is visible
 	 *
 	 * @type {$NodeSet}
 	 */
 	viewAndAddPanes: null,
 
 	/*
 	 * Gets jQuery set for ProveIt GUI, which will be empty if ProveIt has not initialized
 	 *
 	 * @return {$Node} root of ProveIt
 	 */
 	getGUI: function()
 	{
 		return $('#' + this.GUI_ID);
 	},
 
 	/**
 	 * Hides ProveIt completely
 	 */
 	hide: function()
 	{
 		this.getGUI().hide();
 	},
 
 	/**
 	 * Show ProveIt
 	 */
 	show: function()
 	{
 		this.createGUI();
 		this.getGUI().show();
 	},
 
 	/**
 	 * Toggle overall visiblility.  If currently hidden, go to minimized.  If minimized, maximize.  If maximize, hide
 	 */
 	toggleVisibility: function()
 	{
 		if(this.getGUI().is(':visible'))
 		{
 			if(this.viewAndAddPanes.is(':visible')) // maximized
 			{
 				this.hide();
 			}
 
 			/*
 			 * If previously maximized, we minimize after hiding, so when we show, it will already be minimized.
 			 * If minimized, we maximize
 			 */
 			this.toggleViewAddVisibility();
 		}
 		else
 		{
 			this.show();
 		}
 	},
 
 	/**
 	 * Toggle visibility of view and add panes.  Initialized by createGUI
 	 *
 	 * @method toggleViewAddVisibility
 	 */
          toggleViewAddVisibility: null,
 
 	/**
 	 * Generates refbox row and all children, to be used by addNewElement, and when updating
 	 *
 	 * @param {AbstractReference} ref reference to generate from
 	 * @param {Boolean} isReplacement if true, this replaces another refbox item, so no number will be assigned, and the count will not be updated.
 	 * @return {Node} new refbox row for refbox
 	 */
 	makeRefBoxRow: function(ref, isReplacement)
 	{
 		var refName = ref.name; //may be null or blank
 
 		//var refbox = this.getRefBox();
 
 		var newchild = $('&lt;tr&gt;&lt;td class=&quot;number&quot;&gt;&lt;/td&gt;&lt;td class=&quot;type&quot;&gt;&lt;/td&gt;&lt;td class=&quot;title&quot;&gt;&lt;/td&gt;&lt;td class=&quot;edit&quot;&gt;&lt;/td&gt;&lt;/tr&gt;').get(0);
 		// removed &lt;span class=&quot;pointers&quot;&gt;&lt;/span&gt;
 		// removed &lt;td class=&quot;details&quot;&gt;&lt;/td&gt;
 
 		if(!ref.isValid())
 		{
 			// Flag as invalid.
 			$(newchild).addClass('invalid');
 		}
 		// grab the nodes that need changed out of it
 		var neweditimage = $('.edit button', newchild).get(0);
 		var thisproveit = this;
 
 		var title = '';
 		var shortTitle = '';
 
 		if(ref.params['title'] != null)
 		{
 			title = ref.params['title'];
 			shortTitle = this.truncateTitle(title);
 		}
 
 		$('td.title', newchild).text(shortTitle);
 		$('td.title', newchild).attr('title', title);
 
 		// deal with variations of date info
 		var formattedYear = '';
 
 		if(ref.params['year'])
 			formattedYear = ref.params['year'];
 		else if (ref.params['date'])
 		{
 		        var yearMatch = ref.params['date'].match(/^([12]\d{3})/);
 			if(yearMatch)
 			{
 				formattedYear = yearMatch[1];
 			}
 		}
 
 		//$('td.year', newchild).text(formattedYear);
 
 		// deal with variations of author info
 		var formattedAuthor = '';
 
 		if(ref.params['author'])
 			formattedAuthor = ref.params['author'];
 		else if (ref.params['last'])
 		{
 			// if(ref.params['first'])
 				// formattedAuthor = ref.params['last'] + ', ' + ref.params['first'];
 			// else
 				formattedAuthor = ref.params['last'];
 		}
 
 		if(ref.params['coauthors'] || ref.params['last2'])
 			formattedAuthor += ' &lt;i&gt;et al.&lt;/i&gt;';
 
 		// build the &quot;details&quot; cell based on presence of author/year data
 		// var details = '';
 		// if (formattedYear != '' &amp;&amp; formattedAuthor != '')
 			// details = '(' + formattedAuthor + ', ' + formattedYear + ')';
 		// else if (formattedYear != '')
 			// details = '(' + formattedYear + ')';
 		// else if (formattedAuthor != '')
 			// details = '(' + formattedAuthor + ')';
 		// $('td.details', newchild).html(details);
 
 		// generate a URL based on ref type
 		var icon = ref.getIcon(), url = '', refType = ref.type;
 
 		switch(refType)
 		{
 			case 'web':
 				url = ref.params['url'];
 				break;
 			case 'book':
 				if(ref.params['isbn'] != null)
 					url = mw.config.get('wgServer') + '/w/index.php?title=Special%3ABookSources&amp;isbn=' + ref.params['isbn'];
 				break;
 			case 'journal':
 			case 'conference':
 				if(ref.params['doi'] != null)
 					url = 'http://dx.doi.org/' + ref.params['doi'];
 				break;
 			case 'news':
 				url = ref.params['url'];
 				break;
 			case 'episode':
 				url = 'http://www.imdb.com/find?s=ep&amp;q=' + escape(ref.params['title']);
 				break;
 		}
 		$('td.type', newchild).css('background-image','url('+icon+')');
 
 		var authorByline = '', yearByline = '', refTypeByline = '';
 		if(formattedAuthor != '')
 			authorByline = 'By: &lt;span class=&quot;author&quot;&gt;' + formattedAuthor + '&lt;/span&gt;';
 		if(formattedYear != '')
 			yearByline = 'Date: &lt;span class=&quot;date&quot;&gt;' + formattedYear + '&lt;/span&gt;';
 		if(refType != null)
 		{
 			var displayType = ref.getTypeForDisplay(), formattedRefType = displayType;
 			$('td.type', newchild).attr('title', displayType);
 
 			if(url != '')
 				formattedRefType = '&lt;a href=&quot;' + url + '&quot; target=&quot;_blank&quot;&gt;' + formattedRefType + '&lt;/a&gt;';
 			refTypeByline = 'Type: &lt;span class=&quot;type&quot;&gt;' + formattedRefType + '&lt;/span&gt;';
 		}
 
 		//alert(&quot;authorByline: &quot; + authorByline + &quot;\n yearByline: &quot; + yearByline + &quot;\n refTypeByline: &quot; + refTypeByline);
 		var byline = '', separator = ' | ';
 		if(refType == 'raw')
 		{
 			byline = refTypeByline + separator + mw.html.escape(ref.toString());
 		}
 		else if(authorByline != '') // a??
 		{
 			if(yearByline != '') // ad?
 			{
 				if(refTypeByline != '') // adt
 					byline = authorByline + separator + yearByline + separator + refTypeByline;
 				else // ad-
 					byline = authorByline + separator + yearByline;
 			}
 			else // a-?
 			{
 				if(refTypeByline != '') // a-t
 					byline = authorByline + separator + refTypeByline;
 				else // a--
 					byline = authorByline;
 			}
 		}
 		else // -??
 		{
 			if(yearByline != '') // -d?
 			{
 				if(refTypeByline != '') // -dt
 					byline = yearByline + separator + refTypeByline;
 				else // -d-
 					byline = yearByline;
 			}
 			else // --?
 			{
 				if(refTypeByline != '') // --t
 					byline = refTypeByline;
 				// no need for ---
 			}
 		}
 		byline = '&lt;p&gt;' + byline + '&lt;/p&gt;';
 		//alert(byline);
 
 
 		// create expanded &lt;div&gt;
 		var expanded = $('&lt;div /&gt;',{
 							&quot;class&quot;: 'expanded'
 						});
 
 		// append the infobar to the expanded info box
 		$(expanded).append(byline);
 
 		// append the expanded info box to the title &lt;td&gt;
 		$('td.title', newchild).append(expanded);
 
 		if(!isReplacement)
 		{
 		    // get ref number by counting number of refs (this includes dummy ref, but not the one we're creating)
 		    var numRefs = $('#refs tr').length;
 		    $('td.number', newchild).text(numRefs);
 		    $('#numRefs').text(numRefs); // update the number of refs in the view tab
 		}
 		// event handler for selecting a ref)
 		$(newchild).click(function() {
 				thisproveit.highlightTargetString(ref.orig);
 				//thisproveit.highlightTargetString(ref.orig);
 				$(&quot;#refs tr&quot;).removeClass('selected');
 				$(newchild).addClass('selected');
 			});
 
 
 
 		var doEdit = function() {
 			thisproveit.updateEditPane(ref);
 
 			$(&quot;#view-pane&quot;).hide();
 			$(&quot;#edit-pane&quot;).show();
 		};
 
 		var citationStrings = ref.getCitationStrings();
 
 		//var pointers = $('.pointers', newchild);
 
 		var allCitations = $('&lt;span class=&quot;all-citations&quot; /&gt;');
 
 		for(var i = 0; i &lt; citationStrings.length; i++)
 		{
 			var dividend = i + 1;
 			var colName = &quot;&quot;;
 
 			while(dividend &gt; 0)
 			{
 				var mod = --dividend % 26;
 				colName = String.fromCharCode(97 + mod) + colName;  // a = 97
 				dividend = Math.floor(dividend / 26);
 			}
 			var citationHolder = $('&lt;a href=&quot;#&quot;&gt;' + colName + '&lt;/a&gt;');
 			// Bind i
 			var clickFunc = (function(i)
 			{
 				return function()
 				{
 					var last = 0, j = 0;
 					var text = proveit.getMWEditValue();
 					for(j = 0; j &lt; i; j++)
 					{
 						last = text.indexOf(citationStrings[j], last);
 
 						// Shouldn't happen.  Indicates citation strings are out of date.
 						if(last == -1)
 						{
 							proveit.log(&quot;citationStrings[&quot; + j + &quot;]: &quot; + citationStrings[j] + &quot; not found.  Returning.&quot;);
 							return false;
 						}
 						last += citationStrings[j].length;
 					}
 					var startInd = text.indexOf(citationStrings[i], last);
 					if(startInd == -1)
 					{
 						proveit.log(&quot;citationStrings[&quot; + i + &quot;]: &quot; + citationStrings[i] + &quot; not found.&quot;);
 					}
 					else
 					{
 						proveit.highlightLengthAtIndex(startInd, citationStrings[i].length);
 					}
 					return false;
 				};
 			})(i);
 
 			citationHolder.click(clickFunc);
 			allCitations.append(citationHolder);
 		}
 
 
 		if(citationStrings.length &gt; 1)
 		{
 			var newP = $('&lt;p /&gt;');
 			newP.append('This reference is cited in the article &lt;span class=&quot;num-citations&quot;&gt;' + citationStrings.length + ' times&lt;/span&gt;: ').append(allCitations);
 			expanded.append(newP);
 		}
 
 		// edit buttons
 		if(ref.type != 'raw')
 		{
 		// SMALL EDIT BUTTON
 
 			// create button
 			var smallEditBtn = $('&lt;button /&gt;',{
 					text: 'edit'
 				});
 
 			// transform button
 			$(smallEditBtn).button({
 				icons: {
 					primary: 'ui-icon-pencil'
 				},
 				text: false
 			});
 
 			// button click event handler
 			smallEditBtn.click(doEdit);
 
 			// append button
 			$('.edit', newchild).append(smallEditBtn);
 
 		// LARGE EDIT BUTTON
 
 			// create button
 			var editBtn = $('&lt;button /&gt;',{
 					&quot;class&quot;: 'edit',
 					text: 'edit this reference'
 				});
 
 			// transform button
 			$(editBtn).button({
 				icons: {
 					primary: 'ui-icon-pencil'
 				},
 				text: true
 			});
 
 			// button click event handler
 			editBtn.click(doEdit);
 
 			// append button
 			expanded.append(editBtn);
 
 		// ROW EVENT HANDLER
 			$(newchild).dblclick(doEdit);
 		}
 		else
 		{
 			// needed to keep all rows the same height
 			$('.edit', newchild).append('&amp;nbsp;');
 		}
 
 		// ibid button
 		if(citationStrings.length &gt; 0)
 		{
 			// create button
 			var ibidBtn = $('&lt;button /&gt;',{
 					&quot;class&quot;: 'insert',
 					text: 'insert this reference at cursor'
 				});
 
 			// transform button
 			$(ibidBtn).button({
 				icons: {
 					primary: 'ui-icon-arrowthick-1-e'
 				},
 				text: true
 			});
 
 			// button click event handler
 			ibidBtn.click(function(){
 					thisproveit.insertRefIntoMWEditBox(ref, false);
 					return false;
 				});
 
 			// append button
 			expanded.append(ibidBtn);
 		}
 
 		return newchild;
 	},
 
 	/**
 	 * Truncates title to fit ProveIt refbox row.
 	 * @param {String} title title to truncate
 	 * @return {String} truncated title
 	*/
 	truncateTitle: function(title)
 	{
 		var MAX_LENGTH = 86;
 		var truncated = title;
 		if(title.length &gt; MAX_LENGTH)
 		{
 			truncated = truncated.substring(0, MAX_LENGTH);
 			var lastSpacePos = truncated.lastIndexOf(' ');
 			if(lastSpacePos != -1)
 			{
 				truncated = truncated.substr(0, lastSpacePos);
 				truncated += &quot; ...&quot;;
 			}
 		}
 		return truncated;
 	},
 
 	/**
 	 * Only to be used internally to add the citations to the list
 	 *
 	 * @param {AbstractReference} ref the reference to add
 	 */
 	addNewElement: function(ref)
 	{
 		var refbox = this.getRefBox();
 		$(refbox).append(this.makeRefBoxRow(ref, false));
 	}
 }, window.proveit);
 
 /**
  * Static method.  Returns valid Cite reference types
  * @for CiteReference
  * @static
  * @return {Array} array of cite method types
  */
 proveit.CiteReference.getTypes = function()
 {
 	return [&quot;web&quot;, &quot;book&quot;, &quot;journal&quot;, &quot;conference&quot;, &quot;encyclopedia&quot;, &quot;news&quot;, &quot;newsgroup&quot;, &quot;press release&quot;, &quot;interview&quot;, &quot;episode&quot;, &quot;AV media&quot;];
 };
 
 proveit.split._compliantExecNpcg = /()??/.exec(&quot;&quot;)[1] === undefined; // NPCG: nonparticipating capturing group
 proveit.split._nativeSplit = String.prototype.split;
 
 proveit.setup();
 
 }( mediaWiki, jQuery ) );
 
 // Local Variables:
 // js2-basic-offset: 8