var backhand_bubble = (function($) {
	$.fn.attachBubble = function(content, options) {
		
		/*
		 * TODO: Other content options like fetch from Ajax
		 */
		
		// Bubble element id
		var bubbleElementId = $(this).attr('id') + '-bubble';
		
		// Set cursor to pointer on element
		$(this).css('cursor','pointer');
		
		// Add bubble element to DOM
		$('body').append('<div id="'+bubbleElementId+'"class="backhand-speech-bubble"><div>'+content+'</div></div>');
		
		// Store reference to container
		var bubbleContainer = $('#'+bubbleElementId);
		
		// Get window dimensions
		var windowWidth = $(window).width();
		var windowHeight = $(window).height();
		
		$(this).hover(
				function(e) {
					
					// Get offset of hover element
					var offset = $(this).offset();
					
					// Get current scroll height
					var viewPortOffset = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
					
					// Position bubble such that if element is currently in the lower half of 
					// the screen, the bubble is placed above the element otherwise below
					if(offset.top > (viewPortOffset + (windowHeight/2)) ) {
						if(bubbleContainer.hasClass('backhand-speech-bubble-below'))
							bubbleContainer.removeClass('backhand-speech-bubble-below');
						if(!bubbleContainer.hasClass('backhand-speech-bubble-above'))
							bubbleContainer.addClass('backhand-speech-bubble-above');
						
						bubbleContainer.css('top',  (offset.top  - bubbleContainer.height()) + 'px');
						bubbleContainer.css('left', (offset.left - 20 + $(this).width()/3) + 'px');
					} else {
						if(bubbleContainer.hasClass('backhand-speech-bubble-above'))
							bubbleContainer.removeClass('backhand-speech-bubble-above');
						if(!bubbleContainer.hasClass('backhand-speech-bubble-below'))
							bubbleContainer.addClass('backhand-speech-bubble-below');
						bubbleContainer.css('top',  (offset.top  + $(this).height()) + 'px');
						bubbleContainer.css('left', (offset.left - 20 + $(this).width()/3) + 'px');
					}
					
					// Fade in container
					bubbleContainer.stop(true,true).fadeIn(250);
				},
				function(e) {
					bubbleContainer.stop(true,true).fadeOut(250, function() {
						
					});
				}
			);
	};
})(jQuery);
