/**
 * tooltip - simple tooltip for anchors; works with either tip content in a hidden element, or from an ajax request.
 *   http://actingthemaggot.com/projects/jquery/tooltip
 *
 * Copyright (c) 2008 Michael Manning (http://actingthemaggot.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 */
(function($){
	$.fn.extend({
		tooltip: function(options) {
			var defaults = { 
	      'name':'rbTT',
				'width' : 400,
				'offset_x':25,
				'offset_y':25,
				'relative_to_mouse':false,
				'appendElement':'body',
				'text':undefined,
				'html': '<div id="{name}" style="width:{width}px"><div id="{name}_arrow" class="{ttclass}"></div><div id="{name}_close_left">{title}</div><div id="{name}_copy" style="z-index:999999;"><div class="{name}_loader"></div></div></div>'
			};
			var settings = $.extend({}, defaults, options);
			return this.each(function() {
				var t = this.tagName.toLowerCase();
				$(this).hover(function(e) {
					showTT(this,e);
				}, function(){t==='a'?$(this).attr('title',settings.title):'';$('#'+settings.name).remove();})
				.click(function(){return false});
			});
			function showTT(a,e) {
				// If we haven't hidden the last tt element yet, do so now
				if($('#'+ settings.name).get(0)) {
				  $('#'+ settings.name).remove();
				}
				
				var t = a.tagName.toLowerCase();
				if(a.href || t ==='img'){
					var p = {};
					var startPos = (settings.relative_to_mouse ? [e.pageX, e.pageY] : getCumulativeOffsetPos(a));
					p['name'] = settings.name;
					var d = document.documentElement;
					var w = self.innerWidth || (d && d.clientWidth) || document.body.clientWidth;
					var loc = w - (settings.appendElement=='body'?startPos[0]+10:getPosition(a).x);
					var clickY = settings.appendElement=='body'?startPos[1]:getPosition(a).y - 3; //set y position
					p['title'] = settings.title = (t==='img')?a.alt:a.title;

					if(t!=='img'){$(a).attr('title','');} //now that we have it clear the title so id doesn't display as well
					var params = (t==='img')?{}:parseQuery( a.href.replace(/^[^\?]+\??/,'') );
					p['title'] = (params['title'] || p['title']).replace(/_/g," ");
					p['width'] = +(params['width']) || settings.width;
					if(params['link'] !== undefined){
						$(a).css('cursor','pointer').bind('click',function(){window.location = params['link']});
					}
					//set x position
					var clickX = (loc > (p['width']+settings.offset_x)) ? (settings.appendElement=='body'?startPos[0]:getPosition(a).x) + (a.offsetWidth + 11) : (settings.appendElement=='body'?startPos[0]:getPosition(a).x) - (p['width'] + 15);
					p['ttclass'] = (loc > (p['width']+settings.offset_x)) ? p['name']+"_left" : p['name']+"_right";
					$(settings.appendElement).append( supplant(settings.html,p) );
					$('#'+p['name']).css({left: clickX+"px", top: clickY+"px"});
					$('#'+p['name']).show();
					
					if(t!=='img'){
						if(a.href.endsWith('#')||a.href.indexOf('#?')!=-1){
							$('#'+p['name']+'_copy').html($('#'+a.id+'_tt').html());
						}else{
							$('#'+p['name']+'_copy').load(a.href);
						}
					} else {
						$('#'+p['name']+'_copy').html(a.alt);
					}
				} 
			};
			function supplant(o,p) { /* via Douglas Crockford, remedial but useful */
				return o.replace(/{([^{}]*)}/g,
					function (a, b) {
						var r = p[b];
						return typeof r === 'string' || typeof r === 'number' ? r : a;
					}
				);
			};
			function getPosition(o) {	
			  oPos = getCumulativeOffsetPos(o,$j(settings.appendElement).get(0));				
				return {'x':oPos[0],'y':oPos[1]};
			};
			function parseQuery ( query ) {
			   var Params = {};
			   if ( ! query ){ return Params;} // return empty object
			   var Pairs = query.split(/[;&]/);
			   for ( var i = 0; i < Pairs.length; i++ ) {
				  var KeyVal = Pairs[i].split('=');
				  if ( ! KeyVal || KeyVal.length != 2 ){ continue; }
				  var key = unescape( KeyVal[0] );
				  var val = unescape( KeyVal[1] );
				  val = val.replace(/\+/g, ' ');
				  Params[key] = val;
			   }
			   return Params;
			};
		}
		
	});

	if(typeof String.prototype.endsWith != "function"){ //see if somebody else fixed this already
		String.prototype.endsWith = function(s) { //why is there a startswith and not an endswith?
			if ('string' != typeof s) {
				throw('IllegalArgumentException: Must pass a string to String.prototype.endsWith()');
			}
			var d = this.length - s.length;
			return d >= 0 && this.lastIndexOf(s) === d;
		};
	}	
	
})(jQuery);

