
var mapX;
var mapY;
var bubble;

$(window).load(function() {
	mapX = $('#grImg').offset().left;
	mapY = $('#grImg').offset().top;
});

$(document).ready(function() {	
	offclick.init();
	
	// bind onclick handler to all <area> elements
	$('area').click(function() {
		var name = $(this).attr('class');
		var type = $(this).attr('rel');
		var coords = $(this).attr('coords');
		var coords = coords.split(',');
		var x = ((mapX + parseInt(coords[0])) > mapX + 496) ? mapX + 496 : mapX + parseInt(coords[0]);
		//var y = mapY + parseInt(coords[1]);
		bubble = $('.' + type);
		bubble.css('left', x);
		$('.top', bubble).html($('#' + name).html());
		bubble.show();
		var height = bubble.height();
		var y = (mapY + parseInt(coords[1])) - height - 5;
		bubble.css('top', y);
		
		// dynamically bind the view full link handler each time
		$('.viewFull', bubble).click(function() {
			var full = $('#' + name + '_Full');
			$('.top', bubble).html(full.html());
			var fullHt = bubble.height();
			var maxY = mapY + 566;
			var yBot = y + fullHt;
			if(yBot > maxY)
				bubble.css('top', y - (yBot - maxY));

			return false;
		});
		
		return false;
	});
});

// offclick function
var offclick = {
	list: [],
	
	// prepare the list of target objects to receive offclick behavior
	init: function() {
		offclick.list = [
			{
				root			: '.bubble',
				callback	: function() {
					$('.bubble').hide();
				}
			}
		];
		
		offclick.attach();
	},
	
	// have the onmousedown event bind to the body,
	// which will attempt to close all the targets
	// unless a user clicks on a target itself
	attach: function() {
		var list = offclick.list;
		
		$('html').mousedown(function(evt) {
			for(x in list) {
				if($(evt.target).parents().filter(list[x].root).length == 0)
					list[x].callback();
			}
		});
	}
};