/*
 * Hover Boxen v0.2
 * Alex Panayotopoulos, Copyright (C) 2009 VisitScotland.com
 *
 * A HoverBox is a collection of trigger and target elements. When the user hovers over a trigger element,
 * the corresponding target element is displayed (and the previous target element is hidden).
 *
 * Sample code:
 *   var myHoverBox = new HoverBox();
 *   myHoverBox.setTriggerActiveClass('myActiveElement');
 *   myHoverBox.add('foo', 'fooBox');
 *   myHoverBox.add('bar', 'barBox');
 *   myHoverBox.add('baz', 'bazBox');
 *
 * All mouseover code will be automatically handled by this script. The initially visible target should be
 * automatically detected, however any additional targets should be made visible via 'style="display: none;"'
 */

function HoverBox() {
	this.mapping = [];		// Mapping from trigger IDs to target elements
	this.current = null;	// Currenly active trigger element
	this.triggerActiveClass = 'hoverBoxActive';		// CSS class to apply to active trigger
	
	/*
	 * Add a new trigger/target pair
	 * 
	 * trigger:	CSS id for a trigger element (what you hover over)
	 * target:	CSS id for the corresponding target element (what shows after you hover)
	 */
	this.add = function(trigger, target) {
		var triggerElem = $(trigger);
		var targetElem = $(target);
		
		if (!triggerElem) {
			alert('HoverBox.add: No such element "#' + trigger + '"');
			return;
		}
		
		if (!targetElem) {
			alert('HoverBox.add: No such element "#' + target + '"');
			return;
		}
		
		this.mapping[trigger] = targetElem;
		
		if (!this.current && targetElem.visible()) {
			this.current = triggerElem;
			triggerElem.addClassName(this.triggerActiveClass);
		}
		
		triggerElem.hoverBoxHandler = this;
		triggerElem.onmouseover = function() {
			this.hoverBoxHandler.trigger(this);
		}
	}
	
	/*
	 * Set the CSS class name to be applied to active triggers.
	 * This should be called *before* any of the 'add' method calls.
	 */
	this.setTriggerActiveClass = function(className) {
		this.triggerActiveClass = className;
	}
	
	/* Fires when the user hovers over a trigger */
	this.trigger = function(triggerElem) {
		this.current.removeClassName(this.triggerActiveClass);
		this.mapping[this.current.id].hide();

		this.current = triggerElem;
		
		triggerElem.addClassName(this.triggerActiveClass);
		this.mapping[triggerElem.id].show();
	}
}