/**
 * jQuery helpPopup function.
 * June 23, 2009
 * Kevin Kucera
 * 
 * This function prepends a help icon, to the front of the targeted element
 * and provides a informational popup if the icon is rolled over.  
 * 
 * To use this function attach it to any jQuery selector result.  Each item that 
 * you wish to have help displayed for will need to have a "help" attribute containing
 * the text you wish to display in the help box.
 * 
 * Usage example:
 * $(document).ready(function(){
 *    $(".helpPopup").helpPop({image: '/images/help.png'});
 * });
 * 
 * <label class="helpPopup" help="This is the text that will appear when someone hovers over the help icon" />My Label</label>
 * 
 * You must also set the popup formating using css.  The default class name is "helpPopupDiv" but you can 
 * change that by including a class name in the function call options.  Ex:
 * $(".helpPopup").helpPop({image: '/images/help.png', className:'myNewClassName'});
 * 
 * The default css is included in a file called helpPopup.css.
 * 
 */
(function($){
       
	$.fn.helpPop = function(newOptions){

		var defaults = {image:'',className:'helpPopupDiv'};
		var options = $.extend({},defaults,options,newOptions);
		
		// append a hidden div to the body that will contain the popup
		$('<div/>').appendTo('body').each(function(){
			this.style.visibility = 'hidden';
			this.style.position = 'absolute';
			this.style.zIndex = 101;
			this.className = options.className;	
		});	
		
		return this.each(function(){
			var target = this;
			var helpTxt = $(this).attr('help');
			var link = (options.image=='' ? '(?) ' : '<img src="'+options.image+'"> ');
			
			$('<div/>').insertBefore(target).css('display','inline').attr('helpTitle',$(this).text()).html(link).hover(
					function(){ 
							var pos = $(this).offset();
							var width = $(this).width();
							var height = $(this).height();
							var x = pos.left + (width/2);
							var y = pos.top + height;
							var title = $(this).attr('helpTitle');
							$(".helpPopupDiv").each(function(){
								var titleDiv = '<div class="helptitle">' + title + '</div>';
								var bodyDiv = '<div class="helpcontent">' + helpTxt + '</div>';
								this.innerHTML = titleDiv + ' ' + bodyDiv;
								this.style.left = x;
								this.style.top = y;
								this.style.visibility = 'visible';
							});
					}, 
					function(){ 
						$(".helpPopupDiv").each(function(){
							this.innerHTML = helpTxt;
							this.style.visibility = 'hidden';
						});
					});
			});
		
    }
	
})(jQuery);