/**
 * Tooltip plugin
 * Somewhat based on http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/
 * 
 * @author  michael.paige@ogilvy.com
 * @memberOf $.fn
 * @name tooltip
 * @function
 * @requires jQuery
 * @example: $(object).tooltip();
 * @example: $(object).tooltip({ additionalClass: 'foo', closeButton: true, events: 'click' });
 * @cat plugin
 * @type jQuery 
 * @version $Rev$
 */
(function ($) {
    var current;

    $.fn.tooltip = function (options) {
        // build main options before element iteration
        var opts = $.extend({}, $.fn.tooltip.defaults, options);

        createTooltipHTML(opts);

        return this.each(function () {
            $.data(this, 'tooltip', opts);
            this.tOpacity = $('#tooltip').css('opacity');
            // copy tooltip into its own data attr and remove the title
            $.data(this, 'title', this.title);
            $(this).removeAttr('title');
            // also remove alt attribute to prevent default tooltip in IE
            this.alt = '';
        })
		.bind(opts.events, eventHandler)
		.bind('click', function (e) { e.preventDefault(); });
    };

    /*
    * plugin defaults 
    */
    $.fn.tooltip.defaults = {
        contentSrc: 'title', 			// title, href
        speed: 'fast', 					// slow, normal, fast
        closeButton: false, 			// boolean
        events: 'mouseover mouseout',  	// click, mouseover, mouseout (default - mouseover mouseout should be passed together)
        additionalClass: ''				// additional class - used for creating different tooltip styles
        //width: 460					// (optional)
    };

    function eventHandler(e) {
        e.preventDefault();

        var eventType = e.type;

        switch (eventType) {
            case 'mouseover':
            case 'click':
                showTip(this);
                break;
            case 'mouseout':
                hideTip(this);
                break;
        }
    }

    function createTooltipHTML(settings) {
        // use only one tooltip
        if ($('#tooltip').length > 0) { return; }

        // create the HTML
        var html = $('<div id="tooltip" class="modalDiv">'
						+ '<a href="#" class="closeModalDiv">close</a>'
						+ '<div class="modalDivArrow"></div>'
						+ '<div class="modalDivContent"></div>'
					+ '</div>')
        // add to document
		.appendTo(document.body)
        // hide initially
		.hide();

        var tooltip = $('#tooltip');
        tooltip.find('.closeModalDiv').bind('click', function (e) {
            e.preventDefault();

            //tooltip.fadeOut('fast');
            hideTip(current);
        });
    }

    function getSettings(obj) {
        return $.data(obj, 'tooltip');
    }

    function positionTip(obj, callback) {
        var target = $(obj),
			targetWidth = target.width(),
			pos = target.offset(),
			settings = getSettings(obj),
			tooltip = $('#tooltip'),

			wrapper = $('.contentWrapper'),
			wrapperWidth = wrapper.width(),
			wrapperPos = wrapper.position(),
			leftBoundary = wrapperPos.left,
			rightBoundary = leftBoundary + wrapperWidth,

			centered = ((pos.left + (targetWidth / 2)) - (tooltip.width() / 2)),
			moveLeft = ((pos.left + (targetWidth / 2)) - (tooltip.width() - 100)),
			moveRight = ((pos.left + (targetWidth / 2)) - 92),
			leftPos = centered,

			topPos = (pos.top - (tooltip.height() + 14));

        /* Check to see if the position of the tooltip would extend beyond the 
        * website boundary. If it does, move it.
        */
        if (centered < leftBoundary) {
            leftPos = moveRight;
            tooltip.addClass('leftArrow');
        }

        if ((centered + tooltip.width()) > rightBoundary) {
            leftPos = moveLeft;
            tooltip.addClass('rightArrow');
        }

        if (topPos < 0) {
            topPos = 5;
            leftPos = moveRight;
            tooltip.addClass('leftArrow');
        }
        //alert(topPos);
        //alert(tooltip.height());
        tooltip.css({ top: topPos, left: leftPos });
        callback();
    }

    function showTip(obj) {
        if (obj === current) { return; }

        var _this = obj,
			settings = getSettings(_this),
			contentSrc = ($.data(_this, 'title') !== '') ? $.data(_this, 'title') : $('<img src="' + _this.href + '" />'),
			tooltip = $('#tooltip'),
			closeButton = tooltip.find('.closeModalDiv'),
			content = tooltip.find('.modalDivContent');

        tooltip.attr('className', 'modalDiv').attr('style', '');

        current = obj;

        if (settings.closeButton) {
            closeButton.show();
        } else {
            closeButton.hide();
        }

        // set width if specified
        if (settings.width !== undefined) {
            tooltip.css({ width: settings.width });
        }

        // add any additional class for this tip
        tooltip.addClass(settings.additionalClass);

        content.html(contentSrc);

        function showIt() {
            if (tooltip.is(':animated')) {
                tooltip.stop().show().fadeTo(settings.speed, _this.tOpacity);
            } else {
                tooltip.is(':visible') ? tooltip.fadeTo(settings.speed, _this.tOpacity) : tooltip.fadeIn(settings.speed);
            }
        }

        if (typeof contentSrc === 'string') {
            positionTip(_this, function () {
                if ($.support.leadingWhitespace) { //is not IE
                    showIt();
                } else {
                    tooltip.show();
                }
            });
        } else { //assume content is image
            contentSrc.load(function () {
                positionTip(_this, function () {
                    if ($.support.leadingWhitespace) { //is not IE
                        showIt();
                    } else {
                        tooltip.show();
                    }
                });
            });
        }
    }

    function hideTip(obj) {
        var settings = getSettings(obj),
			tooltip = $('#tooltip'),
			closeButton = tooltip.find('.closeModalDiv'),
			content = tooltip.find('.modalDivContent');

        current = null;

        // reset the tooltip
        function complete() {
            tooltip.attr('class', 'modalDiv').hide().css({ opacity: '' });
            //.removeAttr('style');
        }

        if ($.support.leadingWhitespace) { //is not IE
            if (tooltip.is(':animated')) {
                tooltip.stop().fadeTo(settings.speed, 0, complete);
            } else {
                tooltip.fadeOut(settings.speed, complete);
            }
        } else {
            complete();
        }
    }
})(jQuery);

