// This script requires 'prototype.js' (Prototype) and 'effects.js' (Scriptaculous) to be
// loaded.


/*
Highlight the <map><area> tag with the given HMDB ID as the id attribute.  Adds a div 
with a border to the image, and pulsates the border using prototype.
*/
function highlight(hmdb_id) {
	border_width = 5; // Width the of border which will surround the metabolite area

	var pathway_image = $('pathway');
	var map = $('map');

	/* Grab the image offsets for the pathway image (the coordinates are zeroed at the
		top left corner of the image) */

	$$('.' + hmdb_id).each(function(metabolite) {
		var offset_x = pathway_image.cumulativeOffset().left;
		var offset_y = pathway_image.cumulativeOffset().top;

		var highlighter = new Element('a', { 'class': 'highlight', 'style': 'position: absolute; padding: 0em; margin: 0em' });
		
		// Grab the coordinates of the area we want to highlight
		var map_coords = metabolite.coords.split(",");
		var area_left = new Number(map_coords[0]);
		var area_top = new Number(map_coords[1]);
		var area_right = new Number(map_coords[2]);
		var area_bottom = new Number(map_coords[3]);

		// Update the div to display a border around our object of interest
		highlighter.style.border = border_width + 'px solid red';
		highlighter.style.top = offset_y + area_top + 'px';
		highlighter.style.left = offset_x + area_left + 'px';
		highlighter.style.width = area_right - area_left - (2*border_width) + 'px';
		highlighter.style.height = area_bottom - area_top - (2*border_width) + 'px';

		// Need to set the href for the div because it essentially covers the original area
		highlighter.href = metabolite.href;
		highlighter.target = metabolite.target;
		
		map.insert(highlighter); // Add the link to the document

		highlighter.scrollTo();
		highlighter.pulsate({ pulses: 3, duration: 3 });
		return false;
	} );

	// Change the zoom buttons to add the HMDB ID param
	$$('.zoom_in', '.zoom_out').each( function(tag) { tag.href = tag.href + '?hmdb_id=' + hmdb_id; } );
}

/*
Grab a URL parameter and return it to you. For example if the current 
URL is "...?opendocument&id=testid" then calling getURLParam("id") will return "testid".
*/
function getURLParam(strParamName) {
	var strReturn = "";
	var strHref = window.location.href;
	if ( strHref.indexOf("?") > -1 ) {
		var strQueryString = strHref.substr(strHref.indexOf("?"));
		var aQueryString = strQueryString.split("&");
		for ( var iParam = 0; iParam < aQueryString.length; iParam++ ) {
			if ( aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 ) {
				var aParam = aQueryString[iParam].split("=");
				strReturn = aParam[1];
				break;
			}
		}
	}
	return unescape(strReturn);
}