// Copyright 2007 David Johansson, Redpill AB

/*
 * jQuery plugin for special tooltips
 *
 * usage: $('#myid').tooltip('#idofcontent',options);
 */

(function($){

var tp_html = '<div id="tp-box">'+
                '<div id="tp-tip">'+
                    '<div class="tp-header"></div>'+
                    '<div id="tp-content" class="tp-body"></div>'+
                    '<div class="tp-foot"></div>'+
                '</div>'+
              '</div>';

jQuery.fn.tooltip = function (content_id,settings) {
    settings = jQuery.extend({}, settings);
     
     //is it up? outside of link? outside of box?
     var tooltip = {visible:false,link:false,box: false,off:null};
     
     //hide tooltip content
     $(content_id).hide();
     
     
     $(this).hover(function(){
       
        //build and show tooltip
        tooltip.link = true;
        if (!tooltip.visible) {//check if it's already up
            
            //create tooltip
            $("body").prepend(tp_html);

            //move it
            var off = $(this).offset({scroll: false});            
            var h = $(this).height();
            var w = $(this).width();
            $('#tp-box').css('top',(off.top+h-0)+'px');
            $('#tp-box').css('left',(Math.max(off.left-305+(w/2),0)+'px'));
            
            //fetch content
            $('#tp-content').append($(content_id).html());
            
            //setup hover
            $('#tp-box').hover(function(){ tooltip.box = true; },function(){
                tooltip.box = false;
                if (tooltip.visible && !tooltip.link) {
                    tooltip.visible = false;
                    //remove the tooltip
                    $('#tp-box').fadeOut("fast",callback=function(){
                        $(this).remove();
                    });    
                }
            });
            
            //show it
            tooltip.visible = true;
            $('#tp-box').fadeIn("fast");
        }
     }, function(e){
            tooltip.link = false;
            if (tooltip.visible && !tooltip.box) {
                //check to see if this is just the event before we get mouse over on the tooltip
                //ie are we inside the box but with tooltip.box == false?
                var off = $('#tp-box').offset({scroll:false});
                var h = $('#tp-box').height();
                var w = $('#tp-box').width();
                
                if (e.pageY < off.top-1 || e.pageY > off.top+h+1 ||
                    e.pageX < off.left-1 || e.pageX > off.left+w+1) {
                    tooltip.visible = false;
                    //remove the tooltip
                    $('#tp-box').fadeOut("fast",callback=function(){
                        $(this).remove();
                    });    
                }
            }
     
     
     });     
};



})(jq)

