/**
 * @author balazs.suhajda
 */

var pd = pd || {};

pd.tooltip = (function() {
    var ttSelector = '.tooltip-trigger',
		zindex = 0; //	initial z-index for tooltip. each gets z-index + 1
    
    var ttTemplate = '<div class="tooltip"><div class="tooltip-wrapper"><div class="tooltip-content"><p/></div></div><div class="tooltip-arrow"></div></div>';
    var init = function() {
        $(ttSelector)
		.live('mouseover', function() {
		    clearTimeout(this.t);
		    if (!this.tooltip) {
		        if (!this.title && !this.alt) return;
				
				/*	grab title or alt attribute and empty both to avoid stardard tooltip behaviour	*/
		        var tooltipTxt = $(this).attr('title') && $(this).attr('title') != '' ? $(this).attr('title') : $(this).attr('alt');
		        $(this).attr('title', '').attr('alt', '');
		        var tooltip = $(ttTemplate)
					.find('.tooltip-content p')
						.html(tooltipTxt)
					.end()
					.appendTo('body');

                /*  have to make tooltip visible for size calculations   */
		        tooltip.show();
		        var content = tooltip.find('p');
				
		        /*  apply additional classnames for single/multi line tooltips  */
		        var classname = (Math.floor(content.height() / parseInt(content.css('line-height'))) > 1)
		            ? 'tooltip-multiline'
		            : 'tooltip-singleline';
		        tooltip.addClass(classname);
		        this.tooltip = tooltip;
		    }
		    zindex++;

		    this.tooltip
		        .show()
				.css({
				    top: $(this).offset().top - this.tooltip.height() - 10,
				    left: $(this).offset().left - (this.tooltip.width() - $(this).width()) / 2,
				    zIndex: zindex
				})
				.animate({
				    top: $(this).offset().top - this.tooltip.height() - 5
				}, 300);
		}).live('mouseout', function() {
		    var el = this;
		    this.t = setTimeout(function() {
		        el.tooltip && el.tooltip.hide();
		    }, 250);
		});
    }


    return {
        init: init
    }
})();

/*	Can wait to init tooltip after page is rendered,
 * 	since noone can hover it before it's icon is loaded & displayed ;)
 */
$(window).load(pd.tooltip.init);
