/*
	A library to convert the oldest Jmol pages that used the <applet> syntax into modern (2022) JSmol syntax.
	Author: Angel Herráez, https://wiki.jmol.org/index.php/User:AngelHerraez
	2022-08-14
	Use is explained at 
	https://wiki.jmol.org/index.php/Jmol_JavaScript_Object/Legacy#Converting_the_oldest_Jmol_pages_that_used_the_.3Capplet.3E_syntax
	Licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) 
*/

$(document).ready(function() {
	let appTags = document.querySelectorAll('applet');
	let i = appTags.length;  
	//alert(i + ' applet tags found')
	while(i--) {
		let p; let n; let a; let s='';
		let c = appTags[i].getAttribute('code');
		switch(c) {
		case 'JmolApplet':
			n = appTags[i].getAttribute('name').replace(/\-/g, '_'); //hyphen is problematic for IDs
			p = readParams(appTags[i]);
			JmolInfo.color = p.boxbgcolor;
			if (p.load) { s = 'load "' + p.load + '";' }
			if (p.script) { s += p.script + ';' }
			JmolInfo.script = s;			
			a = document.createElement('div');
			a.style.width = appTags[i].getAttribute('width') + 'px';
			a.style.height = appTags[i].getAttribute('height') + 'px';
			a.id = 'JSmolDiv_' + n;
			appTags[i].replaceWith(a);
			$(a).html( Jmol.getAppletHtml(n, JmolInfo) );
			break;
		case 'JmolAppletControl':
			p = readParams(appTags[i]);
			p.target = p.target.replace(/\-/g, '_');
			switch(p.type) {
			case 'button':
				if (p.load) { s = 'load "' + p.load + '";' }
				if (p.script) { s += p.script + ';' }
				a = document.createElement('button');
				a.innerHTML = p.label;
				a.onclick = function() { Jmol.script(window[p.target], s); }
				appTags[i].replaceWith(a);
				break;
			case 'chimeToggle':
				a = document.createElement('input');
				a.type = 'checkbox';
				a.onclick = function() {
					s = (this.checked ? p.script : p.altscript);
					Jmol.script(window[p.target], s);
				}
				appTags[i].replaceWith(a);			
				break;
			default:
				// we only convert buttons and checkboxes for now; maybe there is not anything else
			}
			break;
		default:
			alert('could not process applet tag nr. ' + (i+1));
		} // end of switch c
	}
 
});

var JmolInfo = {
	width:'100%',
	height:'100%',
	color:'#333',
	j2sPath:'j2s',
	serverURL:'php/jsmol.php',
	use:'html5'
}

function readParams(appletNode) {
	let ob = {};
	let p = appletNode.querySelectorAll('param');
	for (let i=0;i<p.length;i++) {
		ob[p[i].getAttribute('name')] = p[i].value;
	}	
	return ob;
}

