// tipsy, facebook style tooltips for jquery
// version 1.0.0a
// (c) 2008-2010 jason frame [jason@onehackoranother.com]
// released under the MIT license

(function($) {
    
    function maybeCall(thing, ctx) {
        return (typeof thing == 'function') ? (thing.call(ctx)) : thing;
    };
    
    function Tipsy(element, options) {
        this.$element = $(element);
        this.options = options;
        this.enabled = true;
        this.fixTitle();
    };
    
    Tipsy.prototype = {
        show: function() {
            var title = this.getTitle();
            if (title && this.enabled) {
                var $tip = this.tip();
                
                $tip.find('.tipsy-inner')[this.options.html ? 'html' : 'text'](title);
                $tip[0].className = 'tipsy'; // reset classname in case of dynamic gravity
                $tip.remove().css({top: 0, left: 0, visibility: 'hidden', display: 'block'}).prependTo(document.body);
                
                var pos = $.extend({}, this.$element.offset(), {
                    width: this.$element[0].offsetWidth,
                    height: this.$element[0].offsetHeight
                });
                
                var actualWidth = $tip[0].offsetWidth,
                    actualHeight = $tip[0].offsetHeight,
                    gravity = maybeCall(this.options.gravity, this.$element[0]);
                
                var tp;
                switch (gravity.charAt(0)) {
                    case 'n':
                        tp = {top: pos.top + pos.height + this.options.offset, left: pos.left + pos.width / 2 - actualWidth / 2};
                        break;
                    case 's':
                        tp = {top: pos.top - actualHeight - this.options.offset, left: pos.left + pos.width / 2 - actualWidth / 2};
                        break;
                    case 'e':
                        tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth - this.options.offset};
                        break;
                    case 'w':
                        tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width + this.options.offset};
                        break;
                }
                
                if (gravity.length == 2) {
                    if (gravity.charAt(1) == 'w') {
                        tp.left = pos.left + pos.width / 2 - 15;
                    } else {
                        tp.left = pos.left + pos.width / 2 - actualWidth + 15;
                    }
                }
                
                $tip.css(tp).addClass('tipsy-' + gravity);
                $tip.find('.tipsy-arrow')[0].className = 'tipsy-arrow tipsy-arrow-' + gravity.charAt(0);
                if (this.options.className) {
                    $tip.addClass(maybeCall(this.options.className, this.$element[0]));
                }
                
                if (this.options.fade) {
                    $tip.stop().css({opacity: 0, display: 'block', visibility: 'visible'}).animate({opacity: this.options.opacity});
                } else {
                    $tip.css({visibility: 'visible', opacity: this.options.opacity});
                }
            }
        },
        
        hide: function() {
            if (this.options.fade) {
                this.tip().stop().fadeOut(function() { $(this).remove(); });
            } else {
                this.tip().remove();
            }
        },
        
        fixTitle: function() {
            var $e = this.$element;
            if ($e.attr('title') || typeof($e.attr('original-title')) != 'string') {
                $e.attr('original-title', $e.attr('title') || '').removeAttr('title');
            }
        },
        
        getTitle: function() {
            var title, $e = this.$element, o = this.options;
            this.fixTitle();
            var title, o = this.options;
            if (typeof o.title == 'string') {
                title = $e.attr(o.title == 'title' ? 'original-title' : o.title);
            } else if (typeof o.title == 'function') {
                title = o.title.call($e[0]);
            }
            title = ('' + title).replace(/(^\s*|\s*$)/, "");
            return title || o.fallback;
        },
        
        tip: function() {
            if (!this.$tip) {
                this.$tip = $('<div class="tipsy"></div>').html('<div class="tipsy-arrow"></div><div class="tipsy-inner"></div>');
            }
            return this.$tip;
        },
        
        validate: function() {
            if (!this.$element[0].parentNode) {
                this.hide();
                this.$element = null;
                this.options = null;
            }
        },
        
        enable: function() { this.enabled = true; },
        disable: function() { this.enabled = false; },
        toggleEnabled: function() { this.enabled = !this.enabled; }
    };
    
    $.fn.tipsy = function(options) {
        
        if (options === true) {
            return this.data('tipsy');
        } else if (typeof options == 'string') {
            var tipsy = this.data('tipsy');
            if (tipsy) tipsy[options]();
            return this;
        }
        
        options = $.extend({}, $.fn.tipsy.defaults, options);
        
        function get(ele) {
            var tipsy = $.data(ele, 'tipsy');
            if (!tipsy) {
                tipsy = new Tipsy(ele, $.fn.tipsy.elementOptions(ele, options));
                $.data(ele, 'tipsy', tipsy);
            }
            return tipsy;
        }
        
        function enter() {
            var tipsy = get(this);
            tipsy.hoverState = 'in';
            if (options.delayIn == 0) {
                tipsy.show();
            } else {
                tipsy.fixTitle();
                setTimeout(function() { if (tipsy.hoverState == 'in') tipsy.show(); }, options.delayIn);
            }
        };
        
        function leave() {
            var tipsy = get(this);
            tipsy.hoverState = 'out';
            if (options.delayOut == 0) {
                tipsy.hide();
            } else {
                setTimeout(function() { if (tipsy.hoverState == 'out') tipsy.hide(); }, options.delayOut);
            }
        };
        
        if (!options.live) this.each(function() { get(this); });
        
        if (options.trigger != 'manual') {
            var binder   = options.live ? 'live' : 'bind',
                eventIn  = options.trigger == 'hover' ? 'mouseenter' : 'focus',
                eventOut = options.trigger == 'hover' ? 'mouseleave' : 'blur';
            this[binder](eventIn, enter)[binder](eventOut, leave);
        }
        
        return this;
        
    };
    
    $.fn.tipsy.defaults = {
        className: null,
        delayIn: 0,
        delayOut: 0,
        fade: false,
        fallback: '',
        gravity: 'n',
        html: false,
        live: false,
        offset: 0,
        opacity: 0.8,
        title: 'title',
        trigger: 'hover'
    };
    
    // Overwrite this method to provide options on a per-element basis.
    // For example, you could store the gravity in a 'tipsy-gravity' attribute:
    // return $.extend({}, options, {gravity: $(ele).attr('tipsy-gravity') || 'n' });
    // (remember - do not modify 'options' in place!)
    $.fn.tipsy.elementOptions = function(ele, options) {
        return $.metadata ? $.extend({}, options, $(ele).metadata()) : options;
    };
    
    $.fn.tipsy.autoNS = function() {
        return $(this).offset().top > ($(document).scrollTop() + $(window).height() / 2) ? 's' : 'n';
    };
    
    $.fn.tipsy.autoWE = function() {
        return $(this).offset().left > ($(document).scrollLeft() + $(window).width() / 2) ? 'e' : 'w';
    };
    
    /**
     * yields a closure of the supplied parameters, producing a function that takes
     * no arguments and is suitable for use as an autogravity function like so:
     *
     * @param margin (int) - distance from the viewable region edge that an
     *        element should be before setting its tooltip's gravity to be away
     *        from that edge.
     * @param prefer (string, e.g. 'n', 'sw', 'w') - the direction to prefer
     *        if there are no viewable region edges effecting the tooltip's
     *        gravity. It will try to vary from this minimally, for example,
     *        if 'sw' is preferred and an element is near the right viewable 
     *        region edge, but not the top edge, it will set the gravity for
     *        that element's tooltip to be 'se', preserving the southern
     *        component.
     */
     $.fn.tipsy.autoBounds = function(margin, prefer) {
		return function() {
			var dir = {ns: prefer[0], ew: (prefer.length > 1 ? prefer[1] : false)},
			    boundTop = $(document).scrollTop() + margin,
			    boundLeft = $(document).scrollLeft() + margin,
			    $this = $(this);

			if ($this.offset().top < boundTop) dir.ns = 'n';
			if ($this.offset().left < boundLeft) dir.ew = 'w';
			if ($(window).width() + $(document).scrollLeft() - $this.offset().left < margin) dir.ew = 'e';
			if ($(window).height() + $(document).scrollTop() - $this.offset().top < margin) dir.ns = 's';

			return dir.ns + (dir.ew ? dir.ew : '');
		}
	};
    
})(jQuery);

/**
 * Hover balloon on elements without css and images.
 *
 * Copyright (c) 2011 Hayato Takenaka
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * @author: Hayato Takenaka (http://urin.take-uma.net)
 * @version: 0.0.1
**/
;(function($){var Meta={};Meta.pos=$.extend(["top","bottom","left","right"],{camel:["Top","Bottom","Left","Right"]});Meta.size=$.extend(["height","width"],{camel:["Height","Width"]});Meta.getRelativeNames=function(position){var idx={pos:{o:position,f:(position%2==0)?position+1:position-1,p1:(position%2==0)?position:position-1,p2:(position%2==0)?position+1:position,c1:(position<2)?2:0,c2:(position<2)?3:1},size:{p:(position<2)?0:1,c:(position<2)?1:0}};var names={};for(var m1 in idx){if(!names[m1])names[m1]={};for(var m2 in idx[m1]){names[m1][m2]=Meta[m1][idx[m1][m2]];if(!names.camel)names.camel={};if(!names.camel[m1])names.camel[m1]={};names.camel[m1][m2]=Meta[m1].camel[idx[m1][m2]]}}names.isTopLeft=(names.pos.o==names.pos.p1);return names};function NumericalBoxElement(){this.initialize.apply(this,arguments)}(function(){var Methods={setBorder:function(pos,isVertical){return function(value){this.$.css("border-"+pos.toLowerCase()+"-width",value+"px");this["border"+pos]=value;return(this.isActive)?digitalize(this,isVertical):this}},setPosition:function(pos,isVertical){return function(value){this.$.css(pos.toLowerCase(),value+"px");this[pos.toLowerCase()]=value;return(this.isActive)?digitalize(this,isVertical):this}}};NumericalBoxElement.prototype={initialize:function($element){this.$=$element;$.extend(true,this,this.$.offset(),{center:{},inner:{center:{}}});for(var i=0;i<Meta.pos.length;i++){this["border"+Meta.pos.camel[i]]=parseInt(this.$.css("border-"+Meta.pos[i]+"-width"))||0}this.active()},active:function(){this.isActive=true;digitalize(this);return this},inactive:function(){this.isActive=false;return this}};for(var i=0;i<Meta.pos.length;i++){NumericalBoxElement.prototype["setBorder"+Meta.pos.camel[i]]=Methods.setBorder(Meta.pos.camel[i],(i<2));if(i%2==0)NumericalBoxElement.prototype["set"+Meta.pos.camel[i]]=Methods.setPosition(Meta.pos.camel[i],(i<2))}function digitalize(box,isVertical){if(isVertical==undefined){digitalize(box,true);return digitalize(box,false)}var m=Meta.getRelativeNames((isVertical)?0:2);box[m.size.p]=box.$["outer"+m.camel.size.p]();box[m.pos.f]=box[m.pos.o]+box[m.size.p];box.center[m.pos.o]=box[m.pos.o]+box[m.size.p]/2;box.inner[m.pos.o]=box[m.pos.o]+box["border"+m.camel.pos.o];box.inner[m.size.p]=box.$["inner"+m.camel.size.p]();box.inner[m.pos.f]=box.inner[m.pos.o]+box.inner[m.size.p];box.inner.center[m.pos.o]=box.inner[m.pos.f]+box.inner[m.size.p]/2;return box}})();function adjustBalloon($target,$balloon,options){var outerTip,innerTip,initTipStyle={position:"absolute",height:"0",width:"0",border:"solid 0 transparent"},target=new NumericalBoxElement($target),balloon=new NumericalBoxElement($balloon);balloon.setTop(-options.offsetY+((options.position&&options.position.indexOf("top")>=0)?target.top-balloon.height:((options.position&&options.position.indexOf("bottom")>=0)?target.bottom:target.center.top-balloon.height/2)));balloon.setLeft(options.offsetX+((options.position&&options.position.indexOf("left")>=0)?target.left-balloon.width:((options.position&&options.position.indexOf("right")>=0)?target.right:target.center.left-balloon.width/2)));if(options.tipSize>0){if($balloon.data("outerTip")){$balloon.data("outerTip").remove();$balloon.removeData("outerTip")}if($balloon.data("innerTip")){$balloon.data("innerTip").remove();$balloon.removeData("innerTip")}outerTip=new NumericalBoxElement($("<div>").css(initTipStyle).appendTo($balloon));innerTip=new NumericalBoxElement($("<div>").css(initTipStyle).appendTo($balloon));var m;for(var i=0;i<Meta.pos.length;i++){m=Meta.getRelativeNames(i);if(balloon.center[m.pos.c1]>=target[m.pos.c1]&&balloon.center[m.pos.c1]<=target[m.pos.c2]){if(i%2==0){if(balloon[m.pos.o]>=target[m.pos.o]&&balloon[m.pos.f]>=target[m.pos.f])break}else{if(balloon[m.pos.o]<=target[m.pos.o]&&balloon[m.pos.f]<=target[m.pos.f])break}}m=null}if(m){balloon["set"+m.camel.pos.p1](balloon[m.pos.p1]+((m.isTopLeft)?1:-1)*(options.tipSize-balloon["border"+m.camel.pos.o]));makeTip(balloon,outerTip,m,options.tipSize,$balloon.css("border-"+m.pos.o+"-color"));makeTip(balloon,innerTip,m,options.tipSize-2*balloon["border"+m.camel.pos.o],$balloon.css("background-color"));$balloon.data("outerTip",outerTip.$).data("innerTip",innerTip.$)}else{$.each([outerTip.$,innerTip.$],function(){this.remove()})}}function makeTip(balloon,tip,m,tipSize,color){var len=Math.round(tipSize/1.7320508);tip.inactive()["setBorder"+m.camel.pos.f](tipSize)["setBorder"+m.camel.pos.c1](len)["setBorder"+m.camel.pos.c2](len)["set"+m.camel.pos.p1]((m.isTopLeft)?-tipSize:balloon.inner[m.size.p])["set"+m.camel.pos.c1](balloon.inner[m.size.c]/2-len).active().$.css("border-"+m.pos.f+"-color",color)}}$.fn.balloon=function(options){options=$.extend(true,{},$.balloon.defaults,options);return this.one("mouseenter",function(e){var $target=$(this),t=this;$target.showBalloon(options).mouseenter(function(e){var b=$target.data("balloon").get(0);if(b&&(b==e.relatedTarget||$.contains(b,e.relatedTarget)))return;$target.showBalloon()}).data("balloon").mouseleave(function(e){if(t==e.relatedTarget||$.contains(t,e.relatedTarget))return;$target.hideBalloon()}).mouseenter(function(e){$target.showBalloon()})}).mouseleave(function(e){var $target=$(this);var b=$target.data("balloon").get(0);if(b==e.relatedTarget||$.contains(b,e.relatedTarget))return;$target.hideBalloon()})};$.fn.showBalloon=function(options){var $target,$balloon;if(!$.balloon.defaults.css)$.balloon.defaults.css={};if(!this.data("options"))this.data("options",$.extend(true,{},$.balloon.defaults,options));options=this.data("options");return this.each(function(){$target=$(this);if($target.data("offTimer"))clearTimeout($target.data("offTimer"));if($target.data("balloon")){$balloon=$target.data("balloon")}else{$balloon=(options.contents)?$("<div>").append(options.contents):$("<div>",{html:$target.attr("title")||$target.attr("alt")});if(!options.url&&(!$balloon||$balloon.html()==""))return;if(!options.contents)$target.removeAttr("title");if(options.url)$balloon.load(options.url,function(res,sts,xhr){if(options.ajaxComplete)options.ajaxComplete(res,sts,xhr);adjustBalloon($target,$balloon,options)});$balloon.addClass(options.classname).css(options.css).css({visibility:"hidden",position:"absolute"}).appendTo("body");$target.data("balloon",$balloon);adjustBalloon($target,$balloon,options);$balloon.hide().css("visibility","visible")}if(options.onAnimation){options.onAnimation.apply($balloon.stop(true,true),[options.onDuration])}else{$balloon.show(options.onDuration,function(){if(this.style.removeAttribute){this.style.removeAttribute("filter")}})}$.balloon.instances.push($target)})};$.fn.hideBalloon=function(options){options=(this.data("options"))?this.data("options"):$.extend(true,{},$.balloon.defaults,options);return this.each(function(){var $target=$(this);var offTimer=$target.data("offTimer");if(offTimer)clearTimeout(offTimer);$target.data("offTimer",setTimeout(function(){if(options.offAnimation){options.offAnimation.apply($target.data("balloon").stop(true,true),[options.offDuration])}else{$target.removeData("offTimer").data("balloon").stop(true,true).hide(options.offDuration)}},options.keep))})};$(window).resize(function(){$.each($.balloon.instances,function(){adjustBalloon(this,this.data("balloon"),this.data("options"))})});$.balloon={defaults:{contents:null,url:null,ajaxComplete:null,classname:null,position:"top",offsetX:0,offsetY:0,tipSize:12,keep:300,onDuration:100,onAnimation:null,offDuration:80,offAnimation:function(d){this.fadeOut(d)},css:{maxWidth:"150px",minWidth:"20px",padding:"5px",'z-index': 90,borderRadius:"6px",border:"solid 1px #0272b4",boxShadow:"4px 4px 4px #555",color:"#0272b4",backgroundColor:"#fff",opacity:($.support.opacity)?"1":null,textAlign:"left"}},instances:[]}})(jQuery);


