/* Minification failed. Returning unminified contents.
(20,41-42): run-time error JS1195: Expected expression: .
(20,63-64): run-time error JS1195: Expected expression: .
(24,2-3): run-time error JS1002: Syntax error: }
(25,59-60): run-time error JS1004: Expected ';': {
(26,40-41): run-time error JS1195: Expected expression: .
(37,9-10): run-time error JS1014: Invalid character: `
(37,15-16): run-time error JS1193: Expected ',' or ')': :
(38,20-21): run-time error JS1195: Expected expression: >
(38,37-38): run-time error JS1004: Expected ';': )
(39,25-26): run-time error JS1004: Expected ';': {
(40,28-29): run-time error JS1195: Expected expression: .
(42,20-21): run-time error JS1195: Expected expression: .
(42,80-81): run-time error JS1197: Too many errors. The file might not be a JavaScript file: )
 */
(function(window, undefined) {
	//  Only perform check from authorized domains
	//  and for clients that support fetch()
	if(!window.fetch || (window.location.hostname.indexOf('trb.org') === -1))
		return;

	//  Determine if there are any sciencedirect.com record URIs for this record
	var sdUri = document.querySelector('.record-info > li > ul > a[href*="sciencedirect.com/"]');

	if(!sdUri) //no sciencedirect uris found
		return;

	//  Find an identifier accepted by the Eslevier Entitlement API to pass
	var apiArgs = { idType: '', id: '' };

	//  Try DOI first
	var doiUri = document.querySelector('.record-info > li > ul > a[href*="dx.doi.org/"]');

	if(doiUri) {
		var doi = doiUri.getAttribute('href')?.split('dx.doi.org/')?.[1];

		apiArgs.idType = 'doi';
		apiArgs.id = doi;
	}
	else if(sdUri.getAttribute('href').indexOf('/pii/') > 0) { //try Publication Item Identifier (pii)
		var pii = sdUri.getAttribute('href')?.split('/pii/')?.[1];

		apiArgs.idType = 'pii';
		apiArgs.id = pii;
	}

	//  Call Elsevier Entitlement api to determine access
	//  No error handler here; we want this to fail silently as it's
	//  not important for the display of the record or the running
	//  of the application
	if(apiArgs.id)
		fetch(`https://api.elsevier.com/content/article/entitlement/${apiArgs.idType}/${apiArgs.id}?APIKey=0a041792960d258f6d9ef95e7fef3ccf`, { mode: 'cors' })
			.then(response => response.json())
			.then(function(data) {
				var entitlement = data?.['entitlement-response']?.['document-entitlement'];

				if(entitlement?.entitled && entitlement?.link && entitlement?.link['@href']) {
					console.log('Received response from api.elsevier.com.');

					var uri = entitlement?.link['@href'];
					var flagsContainer = document.querySelector('#publication-flags-container');
					var getContainer = flagsContainer? false : true;
					var mediaInfoContainer = document.querySelector('#media-info-container');
					var titleContainer = document.querySelector('#record-title');

					//  Get markup to insert into record view
					fetch('/Record/ScienceDirectPublicationFlag?uri=&showContainer=false')
						.then(response => response.text())
						.then(text => {
							var s = document.createElement('span');
							s.innerHTML = text;
							titleContainer.prepend(s);
						})
						.catch((ex) => console.log(`Could not retrieve /Record/ScienceDirectPublicationFlag: ${ex}`));

					fetch(`/Record/ScienceDirectPublicationFlag?uri=${encodeURIComponent(uri)}&showContainer=${getContainer}`)
						.then(response => response.text())
						.then(text => {
							var li = document.createElement('li');
							li.innerHTML = text;

							if(getContainer)
								mediaInfoContainer?.append(li);
							else
								flagsContainer?.append(li);
						})
						.catch((ex) => console.log(`Could not retrieve /Record/ScienceDirectPublicationFlag: ${ex}`));
				}
			})
			.catch((ex) => console.log('Error from api.elsevier.com: ' + ex?.message));
})(window);;
