User:Bargioni/CC Lit Box.js

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
/* -----------------------------------------------------------------------------
   ____ ____   _     _ _     ____               _     
  / ___/ ___| | |   (_) |_  | __ )  _____  __  (_)___ 
 | |  | |     | |   | | __| |  _ \ / _ \ \/ /  | / __|
 | |__| |___  | |___| | |_  | |_) | (_) >  < _ | \__ \
  \____\____| |_____|_|\__| |____/ \___/_/\_(_)/ |___/
                                             |__/     
                                             
 Helps to build a Colon Classification (P8248) value
 for authors, works, manifestations
 A gadget by User:Carlobia and User:Bargioni - 2021-04-02
 This is version 2, and a fork of gadget CC literature Box

 ASCII art: 
 https://patorjk.com/software/taag/#p=display&f=Standard&t=CC%20Lit%20Box.js	
----------------------------------------------------------------------------- */

mw.loader.using([ 'jquery.ui' ]).then(function () {

$( function($) { // our workspace

	const VERSION = '2.0';
	const VERSION_DATE = '2021-04-24';
	
	function makeSPARQLQuery( endpointUrl, sparqlQuery, doneCallback ) {
		var settings = {
			headers: { Accept: 'application/sparql-results+json' },
			data: { query: sparqlQuery }
		};
		return $.ajax( endpointUrl, settings ).then( doneCallback );
	}

	function I18n(label) {
		var user_langs = wb.getUserLanguages();
		var user_lang = user_langs[0];
		if(typeof CCLitBox_conf === 'undefined') {
			mw.log.error('CCLitBox_conf dependency not available');
			return;
		}
		if (!CCLitBox_conf[user_lang]) user_lang = 'en';
		return CCLitBox_conf[user_lang][label] || '?'+user_lang+'_'+label+'?';
	}
	
	function check_if_exists_property(P) {
		$('#colon_messages').html('');
		if ($('#'+P).length) {
			$('#colon_messages').html(I18n('warn_exists_P') +' '+P);
			// adapt drop-down values to current P
			var existing_P = get_property_value(P);
			var parts = existing_P.split(/,/);
			var cpl = parts[0].substr(1);
			var cpo = parts[1].substr(0,1);
			var ciy = parts[1].substr(1);
			$('#cc_popup_languages').val(cpl);
			$('#cc_popup_occupations').val(cpo);
			$('#cc_year').val(ciy);
			$('#CC').val(existing_P);
	check_if_new_value_is_used_in_other_item();
			return true;
		}
		return false;
	}

	function cb_check_if_new_value_is_used_in_other_item(R) {
		$('#colon_messages').html('');
		var results = R.results.bindings;
		if (results.length > 0) {
			var H = [];
			H.push(I18n('yet_in_use')+'<br>');
			for (var i in results) {
				var result = results[i];
				H.push(result.CC.value + ' ');
				H.push('<a target="_blank" href="'+result.author.value+'">' + result.authorLabel.value + '</a><br>');
			}
			if (results.length == 1 && results[0].author.value.endsWith(mw.CC.Q)) {
				$('#colon_messages').html( I18n('warn_exists_P') + ' P8248' );
			}
			// if (results.length > 1) {
			if (results.length > 1 || (results.length == 1 && !results[0].author.value.endsWith(mw.CC.Q))) {
				$('#colon_messages').html(H.join(''));
				$('#CC').css('border','2px solid red');
			}
		}
		else {
			$('#colon_messages').html('');
			$('#CC').css('border','');
		}
	}
	
	function check_if_new_value_is_used_in_other_item() {
		// warning: only works for P8248, for now TODO
		if ($('#CC').val().indexOf('?')>-1) return;
		var CC = $('#CC').val().trim();
		if (!CC) return;
		var sparqlQuery = `SELECT ?author ?authorLabel ?CC {
  ?author wdt:P31 wd:Q5 .
  ?author wdt:P8248 ?CC .
  # MINUS { wd:${mw.CC.Q} wdt:P8248 ?CC . }
  FILTER(STRSTARTS(?CC, "${CC}")).
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
ORDER BY ASC(?CC)`;
	$('#colon_messages').html(I18n('check_not_in_use'));
	makeSPARQLQuery( 'https://query.wikidata.org/sparql', sparqlQuery, cb_check_if_new_value_is_used_in_other_item );
	}
	
	function compute_CC() {
		$('#CC').val(
			'O' + 
			($('#cc_popup_languages').val() || '???') + ',' +
			($('#cc_popup_occupations').val() || '???') +
			($('#cc_year').val() || '???')
		);
		check_if_new_value_is_used_in_other_item();
	}

	function style_the_box() {
		// style some components of the CCLitBox
		$('#CCLitBox_close').css({'float':'right', 'font-size':'12pt', 'position':'relative', 'left':'-10px', 'top':'6px'});
		$('#CCLitBox_name').css({'font-size':'11.2pt'});
		$('#CCLitBox_close').css({'color':'rgb(39, 121, 170)'});
		$('#CCLitBox_tabs').css({'font-size':'1em', 'margin-top':'5px', 'margin-bottom':'5px'});
		$('#CCLitBox_table').css('padding','4px');
		$('#CCLitBox_table td').css({'border':'1px solid lightgray'});
		$('#colon_value').css({'border':'1px solid lightgray', 'padding':'6px', 'text-align':'center'});
		// $('#colon_buttons').css({'border':'1px solid lightgray', 'padding':'6px'});
		$('#colon_messages').css({'border':'1px solid lightgray', 'padding':'6px'});
	}

	function get_property(P) {
		var item = mw.CC.item.entities[qid];
		var claims = item.claims[P] ? item.claims[P] : [];
		// filter out deprecated claims
		claims = claims.filter(function(claim){
			if (claim.rank != 'deprecated') return true; 
			else return false;
		});
		return claims;
	}

	function get_property_value(P) {
		// return the value of the first claim
		var v = get_property(P).length ? get_property(P)[0].mainsnak.datavalue : null;
		if (v) {
			if (v.type == 'time') { return v.value.time }
			if (v.type == 'wikibase-entityid') { return v.datavalue ? v.datavalue.value.id : v.value.id }
			if (v.type == 'string') { return v.datavalue ? v.datavalue.value : v.value }
			alert('CCLitBox: unknown type '+v.type);
			console.error('CCLitBox: unknown type '+v.type);
		}
	}

	function CC_year(yob) {
		var cc_year;
		if (yob < 0) {
			// result must be C(999-yob)
			cc_year = 'C'+('000'+(999-Math.abs(yob))).substr(-3);
		}
		else {
			if (yob < 1000) {
				// result must be D0yob
				cc_year = 'D' + ('000' + yob).substr(-3);
			} 
			else {
				var century = Math.floor(yob / 100) * 100;
				var mod = yob % 100;
				if (mod < 10) mod = '0'+mod;
				cc_year = CCLitBox_conf.date[century].CCnotation + mod;
			}
		}
		mw.CC.cc_year = cc_year;
		return cc_year;
	}

	function check_valid_occup(occup) {
		var Q = occup.mainsnak.datavalue.value.id;
		return CCLitBox_conf.occupation[Q] ? true : false;
	}
	
	function get_valid_occups() {
		var occups = get_property('P106');
		occups = occups.filter(function(occup){
				return check_valid_occup(occup);
		});
		return occups;
	}
	
	function get_Qs(claims){
		var Qs = claims.map(function(claim){
			return claim.mainsnak.datavalue.value.id;
		});
		return Qs;
	}
	
	function get_labels(claims) {
		// get labels in the user language from the html page, using the claim id
		var labels = claims.map(function(claim){
			var claim_id = claim.id;
			claim_id = claim_id.replace(/\$/,'\\$');
			var div_class = 'wikibase-statement-' + claim_id;
			var a = $('div.'+div_class).find('.wikibase-snakview-value-container').find('a')[0];
			return $(a).text();
		});
		return labels;
	}
	
	function set_cc_year() {
		$('#cc_year').val('???');
		var dob = get_property_value('P569');
		if (dob) {
			// e.g.: -0065-10-08, 1921, ...
			var yob = dob;
			var date_before_Christ = false;
			if (yob.indexOf('-') == 0) {
				date_before_Christ = true;
				yob = yob.substr(1);
			}
			yob = yob.split(/-/)[0];
			if (date_before_Christ) yob = -yob;
			$('#cc_year').val(CC_year(yob));
		}
		return dob; // for testing
	}
	
	function drop_down_edition() {
		var editions = Object.keys(CCLitBox_conf.edition);
		var drop_down = [];
		drop_down.push('<select id="CC_edition">');
		for (var ed of editions) {
			var sel = ''; 
			if (CCLitBox_conf.edition[ed].default) {
				sel = 'selected="selected"';
				if (!mw.cookie.get('cc_edition')) mw.cookie.set('cc_edition',ed);
			}
			var val = 'value="'+CCLitBox_conf.edition[ed].property+'"';
			drop_down.push('<option ' + val + ' ' + sel+'>' + ed);
		}
		drop_down.push('</select>');
		return drop_down.join('');
	}

	function drop_down_occups() {
		var occups = get_valid_occups(); // array of claims
		var Qs     = get_Qs(occups);
		var labels = get_labels(occups);
		if (Qs.length != labels.length) console.error('CCLitBox: error populating occupations');
		// manage no occups TODO
		var options = [];
		var CCnotations = [];
		for (var i = 0; i < labels.length; i++) {
			// var label = labels[i]; 
			var Q = Qs[i];
			CCnotations.push(CCLitBox_conf.occupation[Q] ? CCLitBox_conf.occupation[Q].CCnotation : '');
		}
		for (var j = 0; j < labels.length; j++) {
			// only add occupations listed in our config
			if (CCnotations[j]) options.push('<option value="'+CCnotations[j]+'">'+labels[j]+' ('+Qs[j]+')</option>');
		}
		$('#cc_popup_occupations option').remove(); // unused
		$('#cc_popup_occupations').append(options.join(''));
	}
	
	function include_lang(langs,lang) {
		var Q = lang.mainsnak.datavalue.value.id;
		for (var j= 0; j< langs.length; j++) {
			if (langs[j].mainsnak.datavalue.value.id == Q) return true;
		}
		return false;
	}
	
	function dedup_langs(langs) {
		if (langs.length == 0) return langs;
		var dedup_langs = [langs[0]];
		for (var i = 1; i < langs.length; i++) {
			if (!include_lang(dedup_langs,langs[i])) dedup_langs.push(langs[i]);
		}
		return dedup_langs;
	}
	
	function get_languages() {
		var langs = [];
		langs = langs.concat(get_property('P103'));
		langs = langs.concat(get_property('P1412'));
		langs = langs.concat(get_property('P6886'));
		langs = dedup_langs(langs);
		return langs;
	}
	
	function drop_down_languages() {
		var langs = get_languages(); // array of claims
		var Qs = get_Qs(langs);
		var labels = get_labels(langs);
		// popolare la tendina
		if (Qs.length != labels.length) console.error('CCLitBox: error populating languages');
		var CCnotations = [];
		mw.CC.edition_code = $('#CC_edition option:selected').text();
		if (mw.CC.edition_code == 'CC6') {
			// CC6: codes of languages are defined by CC6, and depend on CCLitBox_conf
			for (var i = 0; i < labels.length; i++) {
				var label = labels[i]; 
				var Q = Qs[i];
				CCnotations.push(CCLitBox_conf.language[Q] ? CCLitBox_conf.language[Q].CCnotation : ' unknown language '+Q);
			}
			add_languages_options(CCnotations, Qs, labels);
		}
		if (mw.CC.edition_code == 'WC4Lit') {
			// WC4Lit: codes of languages are iso6392 bib compliant
			var Qs1 = Qs.map(function(e){return 'wd:'+e}).join(' ');
			var Qs2 = Qs.map(function(e,i){return '(wd:'+e+' '+i+')'} ).join(' ');
			var sparqlQuery = `SELECT ?q ?qLabel ?iso6392 { 
			?q p:P219 [ ps:P219 ?iso6392 ; pq:P518 wd:Q1631107 ] .
			VALUES ?q { ` + Qs1 + ` } 
			VALUES (?q ?i) {
			` + Qs2 + `
			}
			SERVICE wikibase:label { bd:serviceParam wikibase:language "'+user_lang+',en". } }
			ORDER BY ?i`;
			var context = {'Qs':Qs, 'labels':labels};
			makeSPARQLQuery( 'https://query.wikidata.org/sparql', sparqlQuery, cbWC4lit.bind(context) );
		}
	}
	
	function cbWC4lit(R) {
		var CCnotations = R.results ? R.results.bindings.map(function(e){return e.iso6392.value}) : [];
		add_languages_options(CCnotations, this.Qs, this.labels);
	}
	
	function add_languages_options(CCnotations, Qs, labels) {
		var options = [];
		for (var j = 0; j < Qs.length; j++) {
			options.push('<option value="'+CCnotations[j]+'">'+labels[j]+' ('+Qs[j]+')</option>');
		}
 		$('#cc_popup_languages option').remove();
		$('#cc_popup_languages').append(options.join(''));
		compute_CC();
	}
	
	/*
	function get_CC_in_works() {
		var sparq_query = `select ?q ?cc {
			?q wdt:P8248 ?cc .
			values ?q { $(Q_list) 
		}`;
	}
	*/
	
	function CCLitBox_addclaim(claim, succtext) {
	    var api = new mw.Api();
	    var token = mw.user.tokens.values.csrfToken;
	    api.post({ 
			action: 'wbsetclaim',
			summary: "Added with [[User:Bargioni/CC_literature_box|CC_Lit_Box]]",
			claim: JSON.stringify(claim),
			token: token
		}).then(
			function(aw){
				var I18n = mw.CC.I18n;
				if (aw.success == 1) {
					$('#colon_messages').html( succtext );
					// console.log('CC ok',aw); // test
					mw.notify(I18n("success"), {title: 'CCLitBox', type: 'info'});
				}
				else { // never used?
					$('#colon_messages').html( '<div style="color:darkred; font-weight:bold">'+I18n("error_saving")+'</div>' );
					console.log('CC ko1',aw);
					mw.notify(I18n("error_saving"), {title: 'CCLitBox', type: 'error'});
				}
				$('#colon_gear').html('');
			})
		.catch(function(aw) {
			var I18n = mw.CC.I18n;
			console.log('CC ko',aw);
			$('#colon_messages').html( '<div style="color:darkred; font-weight:bold">'+I18n("error_saving")+'</div>' );
			mw.notify(I18n("error_saving"), {title: 'CCLitBox', type: 'error'});
		});
	}
	
	function CCLitBox_addqualifier (claim, cc_edition) {
		var qualifiers = {
			"P747": [
				{
					"snaktype": "value",
					"property": "P747", // edition
					"datavalue" : {
						"type" : "wikibase-entityid",
						"value" : {
							"id" : cc_edition
						},
					}
				}
			]
		};
		claim.qualifiers = qualifiers;
		return claim;	
	}
	
	function CCLitBox_addstringstatement(qid, pid, msg, cc_str, cc_edition) {
	    var claim = {
			"id": (new wb.utilities.ClaimGuidGenerator("q" + qid)).newGuid(),
			"type": "statement",
			"mainsnak": {
				"snaktype": "value",
				"property": pid, // P8248 oppure nnn per la CB
				// "datatype": "string-id", // "external-id",
				"datavalue": {
					"value": cc_str,
					"type": "string"
				}
			},
			"rank" : "normal",
			"qualifiers-order" : [
				"P747"
			]
		};
		claim = CCLitBox_addqualifier(claim, cc_edition);
		// console.log( claim ); // test
		CCLitBox_addclaim(claim,  "<div style=\"color:darkgreen; font-weight:bold\">"+msg+"</div>");
	}

	function CC_save() {
		var cc_str = $('#CC').val().trim();
		if (cc_str == '' || cc_str.indexOf('?') >= 0) {
			$('#colon_messages').html( '<div style="color:orange; font-weight:bold">'+I18n("invalid_value")+'</div>' );
			$('#CC').focus();
			setTimeout(function(){
				$('#colon_messages').html('');
			}, 3000);
			return;
		}
		var qid = mw.CC.Q; 
		qid = qid.substr(1);
		var pid = $('#CC_edition').val();
		var msg = I18n("success");
		var cc_label = $('#CC_edition option:selected').text();
		var cc_edition = CCLitBox_conf.edition[cc_label].Q;
		mw.CC.I18n = I18n;
		$('#colon_gear').html('<img width="32" src="https://upload.wikimedia.org/wikipedia/commons/d/de/Ajax-loader.gif">');
		CCLitBox_addstringstatement(qid, pid, msg, cc_str, cc_edition);
	}
	
	function CC_reset() {
		if (confirm('Reload this page?')) document.location.reload();
	}

	/*	function check_if_exists_property(P) {
		$('#colon_messages').html('');
		if ($('#'+P).length) {
			$('#colon_messages').html(I18n('warn_exists_P') +' '+P);
		}
	} */

	function work_link(uri) {
		var Q = uri.replace(/.+\//,'');
		var link = `<a target="_blank" href="https://www.wikidata.org/wiki/${Q}">${Q}</a>`;
		return link;
	}
	
	function work_button(W) {
		var CC = W.CC ? W.CC.value : '';
		var wcc; 
		if (!CC) {
			wcc = compute_CC_work(W, false);
			if (wcc.lastIndexOf(',') == wcc.length-1) return ''; // CC lacks data
			if (wcc.indexOf('?') > -1 ) return ''; // CC lacks data
			var Q = W.opera.value; Q = Q.replace(/.+\//,'');
			return `<button type="button" class="button_save_CC" data-Q="${Q}">${I18n("create_CC_for_work")}</button>`;
		}
		return '';
	}
	
	function compute_CC_works() {
		// replace the first char after the ',' with the current occupation
		var occup = $('#cc_popup_occupations').val();
		var cc_works = $('td.work_CC>input');
		for (var i in cc_works) {
			var cc_work = cc_works[i];
			var cc_str = $(cc_work).val();
			cc_str = cc_str.replace(/,./,','+occup);
			$(cc_work).val(cc_str);
		}
	}
	
	function currens() {
		// integer from 1, skipping used
		var n = ++mw.CC.currens;
		while (mw.CC.previous.includes(n+'')) n++;
		mw.CC.currens = n;
		return n;
	}
	
	function compute_CC_work(W,incr) {
		var P1='???', P2='???', P3='???', P4;
		var obj = CCLitBox_conf.language;
		var Q;
		if (W.iso6392) {
			Q = Object.keys(obj).find(key => obj[key].iso6392 === W.iso6392.value);
		}
		if (Q) P1 = obj[Q].CCnotation;
		// P2
		P2 = $('#cc_popup_occupations').val() || '???';
		P3 = $('#cc_year').val().trim() || '???';
		if (W.date.value == 9999) {
			P4 = '';
		}
		else {
			if (incr) P4 = currens();
			else P4 = mw.CC.currens;
		}
		return `O${P1},${P2}${P3},${P4}`;
	}
	
	function work_CC(W) {
		var CC = W.CC ? W.CC.value : '';
		var readonly = 'readonly';
		if (!CC) {
			CC = compute_CC_work(W, true);
			readonly = '';
		}
		else {
			mw.CC.previous.push(CC.split(/,/)[2]);
		}
		let classes = set_classes(CC,readonly);
		return `<input type="text" class="${classes}" size="16" value="${CC}" ${readonly}>`;
	}
	
	function set_currens(results) {
		mw.CC.currens = 0;
		for (var i = 0; i < results.length; i++) {
			let r = results[i];
			let CC = r.CC ? r.CC.value : '';
			if (CC) {
				let n = CC.split(/,/)[2]; // e.g. O111,3N61,3 ---> n=3
				n = n/1;
				if (n > mw.CC.currens) mw.CC.currens = n;
			}
		}
		return mw.CC.currens;
	}
	
	function set_classes (text_value, readonly_flag) {
		let classes = [];
		if (text_value.match(/\?/) || text_value.split(/,/).filter(item => item).length != 3) classes.push('incomplete');
		if (readonly_flag) classes.push('readonly');
		return classes.join(' ');
	}
	
	function save_CC_work(b) {
		var Q = $(b).attr('data-q'); 
		var qid = Q.substr(1);
		var pid = $('#CC_edition').val();
		var cc_label = $('#CC_edition option:selected').text();
		var cc_edition = CCLitBox_conf.edition[cc_label].Q;
		mw.CC.I18n = I18n;
		var cc_str = $(b).parentsUntil('tbody').find('.work_CC input').val().trim();
		var msg = I18n("success_work") + ' ' + `${Q}, ${pid}, ${cc_str}`;
		// $('#colon_gear').html('<img width="32" src="https://upload.wikimedia.org/wikipedia/commons/d/de/Ajax-loader.gif">');
		CCLitBox_addstringstatement(qid, pid, msg, cc_str, cc_edition);
		$(b).prop('disabled', true); // disable button
	}
	
	function show_P571(W) {
		var v = W.date.value;
		if ( v < 0) {
			v = -v + ' ' + I18n('before_Christ');
		}
		else {
			v = v == 9999 ? '&nbsp;'.repeat(4) : v;
		}
		return v;
	}
	
	function cb_CC_works_builder(R) {
		if (R.results.bindings.length == 0) {
			$('#CC_works').html(I18n("no_works")).css('display','block');
			return;
		}
		mw.CC.currens = set_currens(R.results.bindings);
		var H = [];
		H.push(`<div id="CC_works_div"><span>${I18n("works")}</span><table id="CC_works_table">`);
		let Qs = [];
		for (var k=0; k<R.results.bindings.length; k++) {
			var W = R.results.bindings[k];
			var Q = W.opera.value; Q = Q.replace(/.+\//,'');
			// --- do not include the same work more than once - 2022-02-08
			if (Qs.includes(Q)) continue; // sparql query returned the same work more than once (double year of pub, double title...)
			Qs.push(Q);
			// ---
			H.push(`<tr class="" data-uri="${Q}">`);
			H.push('<td>' + work_link(W.opera.value));
			H.push('<td>' + W.operaLabel.value);
			H.push('<td title="P407 (iso6392)">' + (W.iso6392 ? W.iso6392.value : ''));
			// H.push('<td title="P571">' + (W.date.value == 9999 ? '&nbsp;'.repeat(4) : W.date.value));
			H.push('<td title="P571">' + show_P571(W));
			H.push('<td class="work_CC">' + work_CC(W));
			H.push('<td>' + work_button(W)); // button appears only if ...
		}
		H.push('</table></div>');
		$('#CC_works').html(H.join(''));
		$('#CC_works_div>span').css('font-weight','bold');
		$('#CC_works').css({'display':'block','border':'1px solid lightgray'});
		$('#CC_works td').css({'border':'1px solid lightgray'});
		$('.incomplete').css('color','red');
		$('.readonly').css('color','green');
		$('.button_save_CC').click(function(){ save_CC_work(this) });
	}
	
	function CC_works_builder() {
		var sparqlQuery = `select distinct ?opera ?operaLabel ?titolo ?lingua_dell_opera ?iso6392 ?CC ?date {
			?opera wdt:P50 wd:${mw.CC.Q} ;
				wdt:P31 ?lwww .
			values ?lwww { wd:Q7725634 wd:Q47461344 } # literary work wd:Q7725634, written work  wd:Q47461344
			optional { ?opera wdt:P1476 ?titolo .}
			optional { ?opera wdt:P407 ?lingua_dell_opera .
			?lingua_dell_opera p:P219 [ ps:P219 ?iso6392 ; pq:P518 wd:Q1631107 ] }
			optional { ?opera wdt:P8248 ?CC . }
			optional { ?opera wdt:P571 ?creation_date1 . }
			optional { ?opera wdt:P577 ?creation_date2 . }
			BIND( COALESCE( year(?creation_date1), year (?creation_date2), 9999 ) AS ?date ) .
			minus { ?opera wdt:P361 ?o . }
			service wikibase:label { bd:serviceParam wikibase:language "${mw.user.options.values.language},en". }
		}
		order by asc(?date) asc(?operaLabel)`;
		makeSPARQLQuery( 'https://query.wikidata.org/sparql', sparqlQuery, cb_CC_works_builder );
	}
	
	function CCLitBox_builder() {
		// append the CCLitBox
		$('.wikibase-entitytermsview-entitytermsforlanguagelistview').append(html);
		// use values from cookie
		var ed = mw.cookie.get('cc_edition');
		$('#CC_edition').find('option:contains("'+ed+'")').prop("selected",true);

		// activate the CCLitBox
		$('#CCLitBox_tabs').tabs();
		style_the_box();
		
		check_if_exists_property($('#CC_edition').val());
		$('#CC_edition').change(function(){
			check_if_exists_property($(this).val());
			mw.CC.edition_code = $('#CC_edition option:selected').text();
			mw.cookie.set('cc_edition', mw.CC.edition_code);
			// setup dropdown menus
			drop_down_languages();
			drop_down_occups();
			// set CC year
			set_cc_year();
			compute_CC();
		});
		$('#cc_popup_languages').change(function(){ 
			compute_CC();
		});
		$('#cc_popup_occupations').change(function(){ 
			compute_CC();
			compute_CC_works();
		});
		$('#CC').change(function(){
			check_if_new_value_is_used_in_other_item();
		});
		$('#CC_save').click(function(){ CC_save() });
		$('#CC_reset').click(function(){ CC_reset() });
		// setup dropdown menus
		drop_down_languages();
		drop_down_occups();
		// set CC year
		set_cc_year();
		// do not show the Box when missing data
		if ($('#cc_popup_occupations option').length == 0 || 
		$('#cc_popup_languages option').length == 0 || 
		$('#cc_year') == '') {
			// mw.notify ?
			$('#CCLitBox_tabs').remove();
			return;
		}
		compute_CC();
		// use stored CC, if any
		check_if_exists_property( $('#CC_edition').val() );
		CC_works_builder();
	}
	
	function CCLitBox_waitForConfig(func) {
		mw.CC.wait_for_config_retries++;
		if (mw.CC.wait_for_config_retries == 100) {
			console.error('CCLitBox: unable to load config');
			return false;
		}
	    if (typeof CCLitBox_conf !== "undefined"){
			func();
	    }
	    else{
			setTimeout(CCLitBox_waitForConfig, 100, func);
	    }
	}

	function get_item( qid ) {
		var url = 'https://www.wikidata.org/wiki/Special:EntityData/'+qid+'.json';
		$.getJSON(url, function(R){
			mw.CC.item = R;
			// check if the item is an author or a literary work
			var instance = get_property_value('P31');
			if (instance != 'Q5') { // && instance != 'Q7725634'
				console.log('CC_Lit_Box: exit');
				return;
			}
			CCLitBox_builder();
		});
	}
	
	// --------------- main
	
	// check if we're viewing an item
	var qid = mw.config.get( 'wbEntityId' );
	if ( !qid ) return;
	
	// define a global object
	mw.CC = {};

	mw.CC.wait_for_config_retries = 0;
	mw.CC.currens = 0;
	mw.CC.previous = [];
    CCLitBox_waitForConfig(function() {
		// config loaded
		mw.CC.Q = qid;
		get_item( qid );
    });
	
	// html code of the box
	var html = `
<div id="CCLitBox_tabs">
	<div id="CCLitBox_close">
		<span id="CCLitBox_name">CCLitBox</span> <a href="#" title="Close the CCLitBox box" onclick="$(&quot;#CCLitBox_tabs&quot;).remove();return false">×</a>
	</div>
	<ul>
		<li><a href="#CCLitBox_editor"><span>CC editor</span></a></li>
		<li><a href="#CCLitBox_info"><span>&#9432;</span></a></li>
	</ul>
	
	<table id="CCLitBox_editor">
		<tr><td>
			<table id="CCLitBox_table">
				<tr class="CC_component" id="edition"><td>${I18n("edition")}</td><td>${drop_down_edition()}</td></tr>
				<tr class="CC_component" id="letterO"><td>${I18n("class")}</td><td>O</td></tr>
				<tr class="CC_component" id="language"><td>${I18n("language")}</td><td>
				<select id="cc_popup_languages" class="cc_popup_menu"></select>
				</td></tr>
				<tr class="CC_component" id="occupation"><td>${I18n("occupation")}</td><td>
				<select id="cc_popup_occupations" class="cc_popup_menu"></select>
				</td></tr>
				<tr class="CC_component" id="birth"><td>${I18n("yob")}</td><td>
					<input type="text" id="cc_year" value="" readonly/>
				</td></tr>
			</table>
		</td><td id="colon_value"><input type="text" id="CC">
		<br/><span id="colon_buttons">
		<button id="CC_save" title="${I18n("button_save_tooltip")}" class="cc_button">${I18n("button_save")}</button>
		<button id="CC_reset" title="${I18n("button_reset_tooltip")}" class="cc_button">${I18n("button_reset")}</button>
		</span></td>
		<td id="colon_gear"></td>
		<td id="colon_messages"></td>
		</tr>
		<tr><td colspan="9">
			<div id="CC_works" style="display:none">
				<!-- list of literary works -->
			</div>
		</td></tr>
	</table>
	
	
	<div id="CCLitBox_info">
		<img src="https://upload.wikimedia.org/wikipedia/commons/9/96/Idea.svg" width="24px"/>
		${I18n("info")}
		<br/>Version ${VERSION} - ${VERSION_DATE}
	</div>
</div>
	`;
});

});