/*
 * Caption! 0.2g
 * Created by Charles Phillips
 * Caption! is made for the jQuery library.
 * http://www.doublerebel.com/captions
 * Depends on jQuery Dimensions Plugin or now jQuery 1.2.1
 * Features Caption caching for quicker cappin, Captain
 */

/* 
 * @name caption
 * @version 0.2g
 * @type jQuery
 * @param N/A options N/A
 * @option Object {
 * 			speedIn: Int fadeIn speed | default: 250,
 * 			speedOut: Int fadeOut speed | default: 200,
 * 			bottom: Bool Place caption at bottom of captionee | default: false,
 * 			top: Int distance from top of captionee | default: 0,
 * 			left: Int distance from left of captionee | default: 0,
 * 			borderStart: Border color of captionee on start,
 * 			borderEnd: Border color of captionee on end,
 * 			style: DOM Style Object
 * 		 }
 * 			
 */

(function ($) {
	$.fn.extend({
		caption: function(o) {
			o = $.extend(true,{
				appendTo: 'body',
				speedIn: 250,
				speedOut: 200,
				bottom: false,
				top: 0,
				left: -5,
				borderStart: 'lightgreen',
				borderEnd: '#444',
				style: {
					zIndex: 40,
					backgroundColor: '#404040',
					color: 'white',
					fontSize: '10px',
					fontFamily: 'Arial,Helvetica,sans',
					padding: '3px'
					}
				}, o);
			if ($.Counter === undefined) $.Counter = 0;	
			this.each( function(i) {
				var capn = o.capn || this.alt || this.title || 'Captain!';
				$.data(this,'capkey',$.Counter);
				$.Counter++;
				$(this).hover( function() {
					this.style.borderColor = o.borderEnd; //todo: borderfade fx
					var c = 'caption' + $.data(this,'capkey'); 
					if (!document.getElementById(c)) {
						var offset = $(this).offset();
						o.top = (o.bottom) ? $(this).height() : 0;
						$appendTo = $(o.appendTo);
						$appendTo.append(
							"<div id='" + c +
							"' style='display: none; margin: 0px; position: absolute; " +
							"top: " + (offset.top + o.top + parseInt($appendTo[0].scrollTop)) + "px; " +
							"left: " + (offset.left + o.left + parseInt($appendTo[0].scrollLeft)) + "px;'></div>"
						);
						var el = document.getElementById(c);
						for (attr in o.style) { $.attr(el.style, attr, o.style[attr]); }
						if (capn.nodeType === 1 || capn.jQuery) { el.appendChild(capn);
						} else { el.innerHTML = capn; }
					}
					$('#' + c).fadeIn(o.speedIn); //todo: fade speed settings
				  }, function() {
					this.style.borderColor = o.borderStart;
					$('#caption' + $.data(this,'capkey')).fadeOut(o.speedOut);
				});
			});
			var self = this, resizeTimer = null;
			$(window).resize( function() {
				if (resizeTimer) clearTimeout(resizeTimer);
				resizeTimer = setTimeout(function() { resizeFix(self, o) }, 100);
			});	
			return this;
		}
	});
	var resizeFix = function(els, options) { //todo: abstract into repositioning function written OO style
		for (var i=0; i < $.Counter; i++) $('#caption' + i).remove();
		$(els).caption(options);
	};
})(jQuery);

