
/* Script to enhance the interactivity of the periodic table */

function add_interaction(){
    var elements = $("div.element");
    elements.each(function(i, elt){
	elt = $(elt);
	elt.css("cursor", "help");
	var symbol = elt.find(".symbol").text();
	var Z = elt.find(".Z").text();
	var mass = elt.find(".mass").text();
	var struct = elt.find(".struct").html();
	elt.click(
	    function make_callback(o){
		return function (evt){
		    var x = elt.css("top"), y = elt.css("top");
		    o.html(""); /* erase all previous contents */
		    var p;
		    p = $("<p>").text("Element: " + symbol);
		    o.append(p);
		    p = $("<p>").text("Atomic number: " + Z);
		    o.append(p);
		    p = $("<p>").text("Molar mass: " + mass);
		    o.append(p);
		    p = $("<p>").html("Electronic structure: " + struct);
		    o.append(p);
		    o.dialog();
		    var top = parseInt(elt.css("top"));
		    if (top > 250){
			/* the element is low enough, let us animate above */
			top -= 250;
		    } else {
			top += 60;
		    }
		    var left = parseInt(elt.css("left"));
		    if (left > 320){
			/* the element is right enough, let us go to the left */
			left -= 320;
		    } else{
			left +=50;
		    }	       
		    o.parents(".ui-dialog").animate(
			{top: top+"px", left: left+"px"});
		}
	    }($("#one_element")));
    });
    $("#wait").fadeOut();
}

/**
 * imports jQuery (JS), jQuery-UI (JS and CSS)
 * parametes url1 .. url3 are for jquery.js, jquery-ui.js, jquery-ui.css 
 **/
function importScript(url1, url2, url3){
    var script1, script2, link;
    script1 = document.createElement('script');
    script1.src = url1;
    document.head.appendChild(script1);
    script2 = document.createElement('script');
    script2.src = url2;
    document.head.appendChild(script2);
    link = document.createElement('link');
    link.rel = "stylesheet";
    link.type = "text/css";
    link.href = url3;
    document.head.appendChild(link);
}

function jQueryIsHere(){
    result = true;
    try {
	if (! jQuery) result = false;
    }
    catch(e) {
	if(e.name == "ReferenceError") {
	    result = false;
	}
    }
    return result
}

function tryLocal(){
    importScript(
	"http://localhost/javascript/jquery/jquery.js",
	"http://localhost/javascript/jquery-ui/jquery-ui.js",
	"http://localhost/javascript/jquery-ui/css/smoothness/jquery-ui.css"
    );
}

function tryRemote(){
    importScript(
	"https://code.jquery.com/jquery-1.11.3.js",
	"https://code.jquery.com/ui/1.13.2/jquery-ui.js",
	"https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css"
    );
    
}

window.onload = function(){
    setTimeout(function(){
	if (!jQueryIsHere()) tryLocal();
    }, 1000);
    setTimeout(function(){
	if (!jQueryIsHere()) tryRemote();
    }, 3000);
    setTimeout(function(){
	add_interaction();
    }, 5000);
};
