// contextual help
// written by brandon burkett for elementblend
// may 1, 2006

//globals
var CURRENT_ELEM;
var STANDARD_WIDTH = 160;


// create object
var contextualHelp = 
{
	position: function (elem)
	{
		if (elem.offsetParent)
		{
			for (var posX = 0, posY = 0; elem.offsetParent; elem = elem.offsetParent)
			{
				posX += elem.offsetLeft;
				posY += elem.offsetTop;
			}
			return [posX, posY];
		}
		else
		{
			return [elem.x, elem.y];
		}
	},	

	show: function(elem)
	{
		if (CURRENT_ELEM) contextualHelp.hide(CURRENT_ELEM);
    	if (!document.getElementsByTagName) return;

		// check class names		
		var contextual_help = $(elem).attr('contextualhelp');    
	    var newDiv = document.createElement('div');
		newDiv.className = 'contextualHelp';		

	    innerText = "<div>"+contextual_help.replace(/\r\r|\n\n|\r\n\r\n/g, "</div><div>")+"</div>";
		newDiv.innerHTML = innerText;

		var w = STANDARD_WIDTH;
		        
	    newDiv.style.width = w + 'px';    

	    mpos = contextualHelp.position($(elem).get(0));
	    mx = mpos[0];
	    my = mpos[1];

	    newDiv.style.left = (mx+15) + 'px';
	    newDiv.style.top = (my+35) + 'px';
		
	    if (window.innerWidth && ((mx+w) > (window.innerWidth-30)))
		{
	       newDiv.style.left = (window.innerWidth - w - 45) + 'px';
		}
	    if (document.body.scrollWidth && ((mx+w) > (document.body.scrollWidth-30)))
		{
	        newDiv.style.left = (document.body.scrollWidth - w - 45) + 'px';
		}

		newDiv.style.display = 'none';    
		document.getElementsByTagName('body')[0].appendChild(newDiv);			
	    $(newDiv).show();

	    CURRENT_ELEM = newDiv;			
				
	},

	hide: function (elem)
	{
		if(CURRENT_ELEM)
		{
			$(CURRENT_ELEM).hide();
			CURRENT_ELEM = null;
		}
	},

	// initalizer function
	init: function()
	{
		// change these to whatever entity you wish (div, span, img, etc)
		var entity = new Array();
		entity.push('img');

		for(i=0; i<entity.length; i++)
		{
			$(entity[i]).each( function()
			{
				if($(this).attr('class') == 'swatch' || $(this).attr('class') == 'activeSwatch' || $(this).attr('class') == 'pickerButton')
				{
					var thisTitle = $(this).attr('alt');					

					// remove title and add new attribute
					$(this).attr('contextualhelp', thisTitle);
					$(this).attr('alt','');						

					// add events for item
					$(this).bind('mouseover',function() { contextualHelp.show($(this)); });
					$(this).bind('mouseout', function() { contextualHelp.hide($(this)); });
				}
			});
		}		
	}
}

// add to document after dom is loaded
$(document).ready(function() { contextualHelp.init(); });
