/*global $, alert, cmsLoad, document, jQuery, unescape, urldecode, SITE_ROOT, stopEvent */
var cmsFiles = ['cms/tooltip/module.css'];
if(typeof(cmsLoad) === 'function'){
    cmsLoad(cmsFiles);
}

/**
 * CMS Tooltip Module
 * A jQuery module which makes it easy to add tooltips to any page.
 * For any html element all you need is to add a data-tooltip="Test" attribute.
 *
 * @version 1.0
 * @requires
 * @author Ed Rodriguez Ed.Rodriguez@watermatters.org
 */
$(function(){
	$.cms.tooltip.init();
});
(function($){
	$.cms.tooltip = {
		mode: 'loading',
		
		setup: function(){
			if($.cms.tooltip.mode === 'loaded'){
				$('[data-tooltip]').unbind('mouseover mouseout mousemove');
				$('[data-tooltip]').each(function(){
					var tooltip = $(this).attr('data-tooltip');
					if(typeof(tooltip) === 'string' && tooltip !== '' && $('.cms-tooltip').is(':hidden')){
						$(this).bind('mouseover',{},function(event){
							if(typeof($('#'+tooltip)) === 'object'){
								if($('#'+tooltip).html() !== null){
									var html = $('#'+tooltip).clone();
									html.removeAttr('id');
									html.removeClass('hidden');
									$('.cms-tooltip .pane').html('');
									$('.cms-tooltip .pane').append(html);
									$('.cms-tooltip').fadeIn();
								}
							}else{
								$('.cms-tooltip .pane').html(tooltip);
								$('.cms-tooltip').fadeIn();
							}
						}).bind('mouseout',{},function(event){
						   $('.cms-tooltip').hide();
						}).bind('mousemove',{},function(event){
						   $('.cms-tooltip').css({left: event.pageX+15, top: event.pageY+15});
						   stopEvent(event);
						});
					}
				});
			}
		},
		
		init: function(options){
			if(typeof(options) === 'undefined'){
				options = {};
			}
			
			// DEFAULTS
			$.cms.tooltip = $.extend(true, $.cms.tooltip, $.cms.tooltip.defaults, options);
            
            if(typeof(SITE_ROOT) === 'undefined'){
                SITE_ROOT = '/';            
            }
            
            $.ajax({
                url: SITE_ROOT+'snippet/cms/ui/tooltip.snip',
				type: 'POST',
				data: {
					whitespace: 0
				},
                success: function(response){
					$.cms.tooltip.mode = 'loaded';
					$('body').append(response);
					$('.cms-tooltip').hide();
					$.cms.tooltip.setup();
					$(document).bind('mousemove',{},function(event){
						$('.cms-tooltip').hide();
					});
                }
            });
        }
	};
	$.cms.tooltip.defaults = {
	};
}(jQuery));
