// JavaScript Document

// referencia: http://www.learningjquery.com/2007/10/a-plugin-development-pattern

(function($) {
//	var $warehouseTips = {};
	$.fn.Rnd_Tooltip = function(customOptions) {
		var options = {
						 'EL_pos_y': 			0							// posição do elemento em eixo y (pixels)
						,'EL_pos_x':			0							// posição do elemento em eixo x (pixels)
						,'EL_with':				0							// largura do elemento (pixels)
						,'EL_height':			0							// altura do elemento (pixels)
						,'html_content':		''							// conteudo html para ser inserido no tooltip
						,'html_content_element':''							// Objeto para retirar conteudo html para ser inserido no tooltip
						,'template_class':		'rnd_tooltip_default'		// classe padrão do template do tooltip
						,'style_css':			{}							// classe padrão do template do tooltip
						,'type':				'message'					// tipo do tooltip (message, alert, errror, confirm)
						,'on_out_destroy':		false						// destroi o elemento ao esconder
						,'reuse_tip':			false						// reutiliza bloco de toltip caso ele exista
						,'use_debug':			false						// exibe debug enquanto executa o script
						,'hide_other_tips':		true						// esconde qualquer tooltip que estava sendo visualizado quando for exebir o atual
						,'effect_show':			'smooth_slide_bt'			//	tipo de efeito a aplicar ao mostrar o elemento
						,'effect_hide':			'smooth_slide_bt'			//	tipo de efeito a aplicar ao ocultar o elemento
						,'event_show':			'mouseover'					// evento que dispara a visualização do tooltip
						,'event_hide':			'mouseleave'					// evento que dispara ocultação do tooltip
						,'tooltip_view_x':		'center'							// posição para o bloco do tooltip em eixo x
						,'tooltip_view_y':		'bottom'							// posição para o bloco do tooltip em eixo y
						,'tooltip_x':			0							// posição em pixels  de x
						,'tooltip_y':			0							// posição em pixels  de y
						,'corner':				'10px'							// utilização de corners no elemento
						
						
					}
		$.extend(options, customOptions); 
		
		
		
		return this.each(function(index) {
			var $element = $(this);
			var $ControlEvent = {
								'showing_tip':false
								,'hiding_tip':false
								,'mouseover_tip':false
								,'mouseover_element':true
								,'tip_visible':false
								};
			var $container = '';
			
			
			
			/*
			*	função de inicialização
			*/
			function init() {
				
				update_pos_element();
				if(create_tip()){
					if(tooltip_to_html()){
						corner_tooltip();
						mouseover_tooltip();
						mouseleave_tooltip();
					}
				}
				set_event_show();
				set_event_hide();
			}
			/************************************************************************************************/
			/*										CRIAÇÃO DO ELEMENTO TOOLTIP
			/************************************************************************************************/
			/*
			*	seta posicionamento e tamanho do elemento
			*/
			function update_pos_element(){
				set_config_item('EL_pos_y', $element.offset().top);
				set_config_item('EL_pos_x',  $element.offset().left);
				set_config_item('EL_height',  $element.height());
				set_config_item('EL_with',  $element.width());
				return true;
			}
			
			/*
			*	cria tooltip
			*/
			function create_tip(){
				log('function start: create_tip()');
				$container = $("<div></div>")
					.addClass('rnd_tooltip') 
					.addClass(options.template_class)
					.css({
						 'width':'300px'
						 ,'height':'auto'
						 ,'padding':'10px'						 
						 ,'background-color':'#3C3C3C'
						 ,'color':'#FFFFFF'
						 ,'font-size':'12px'
						 ,'font-family':'Tahoma, Geneva, sans-serif'
						 ,'display':'none'
						 ,'position':'absolute'
						 ,'border':'2px'
						 ,'border-color':'#FFFFFF'
						 ,'border-style':'solid'
						 ,'line-height':'13px'
						,'z-index':'99999'
						});
				$container.css(options.style_css);
				/*
				var $Style = {};
				if(typeof(options.style_css) == 'object'){
					jQuery.each(options.style_css, function(key, value) {
						//console.log("key", key, "value", value);
						$Style[''+key+''] = value;
					});
				}
				*/
				 /*jQuery.each(options.style_css, function(key, value) {
				   console.log("key", key, "value", value);
				 });
				 */


					if(options.html_content_element != ''){
						$container.html($("#"+options.html_content_element).html()); 
					}else if(options.html_content != ''){
						$container.html(options.html_content); 
					}
					
					
				/*	
					var $arrow = $('<div></div>').css({
											   'position':'relative'
											  ,'left':'0px'
											  ,'width':'300px'
											  ,'height':'500px'
											  ,'color':'#333'
											  ,'background-color':'#000'
											  ,'text-align':'center'
											  ,'font-size':'30px'
											  ,'border':'1px solid #333'
											  	});

	
	
					$container.canvas();
					var info = [];		// will get populated with info
					$container.canvasinfo( info);   // info[ 0].width  point to the width
					$container
					.style({ 
						'fillStyle'					: 'rgba( 79, 120, 204, 0.4)',
						'strokeStyle'			: 'rgba( 79, 120, 204, 0.8)',
						'lineWidth'					: 5
					})
					.beginPath()
					.moveTo( [-10, 10])
					.lineTo( [ -10 , 20])
					.lineTo( [ -10, 30])
					.closePath()
					.stroke()
					.fill();
					*/
					//$container.html($arrow);
				
				
				log('criado elemento tooltip');
				return true;
			}
			/*
			*	adiciona o bloco de tooltip no html
			*/
			function tooltip_to_html(){
				log('function start: tooltip_to_html()');
				$('body').append($container);
				log('conteudo adicionado ao documento');
				return true;
			}
			
			function corner_tooltip(){
				if(options.corner != '' && options.corner != 'none'){
					$container.corner(''+options.corner+'');
				}
			}
			
			/*
			*	cópia da função do jquery.qtip para criação do ponteiro do tooltip
			*
			*	@param 	string 		tipo do canto
			*	@param 	int 		largura do elemento tooltip
			*	@param	int			altura do elemento tooltip
			*/
		
		/*  
		*
		*	 SER IMPLANTADO FUTURAMENTE
		*
			// Tip coordinates calculator
		   function calculateTip(corner, width, height)
		   {
			  // Define tip coordinates in terms of height and width values
			  var tips = {
				 bottomRight:   [[0,0],              [width,height],      [width,0]],
				 bottomLeft:    [[0,0],              [width,0],           [0,height]],
				 topRight:      [[0,height],         [width,0],           [width,height]],
				 topLeft:       [[0,0],              [0,height],          [width,height]],
				 topMiddle:     [[0,height],         [width / 2,0],       [width,height]],
				 bottomMiddle:  [[0,0],              [width,0],           [width / 2,height]],
				 rightMiddle:   [[0,0],              [width,height / 2],  [0,height]],
				 leftMiddle:    [[width,0],          [width,height],      [0,height / 2]]
			  };
			  return tips[corner];
		   };
		   function drawTip(canvas, coordinates, color)
		   {
			  // Setup properties
			  var context = canvas.get(0).getContext('2d');
			  context.fillStyle = color;
		
			  // Create tip
			  context.beginPath();
			  context.moveTo(coordinates[0][0], coordinates[0][1]);
			  context.lineTo(coordinates[1][0], coordinates[1][1]);
			  context.lineTo(coordinates[2][0], coordinates[2][1]);
			  context.fill();
		   };
		  
		  */
			/************************************************************************************************/
			
			
			/************************************************************************************************/
			/*										SETA AÇÕES PARA O OBJETO 
			/************************************************************************************************/
			
			/*
			*	seta evento de aparecimento do tooltip
			*/
			function set_event_show(){
				log('function start: set_event_show()');
				if(options.event_show != 'mouseover'){
					log('invalido options.event_show:'.options.event_show);
					return false
				}
				$element.bind(options.event_show, function(){
					log('element MOUSE HOVER --- showing_tip: '+$ControlEvent['showing_tip']+'  --- hiding_tip: '+$ControlEvent['hiding_tip']);	
					$ControlEvent['mouseover_element'] = true;
					if($ControlEvent['showing_tip'] === false){
						/*
						if($ControlEvent['hiding_tip'] === true){
							// se estava escondendo o tooltip, para 
							$element.stop();
							$ControlEvent['hiding_tip'] = false;
							//e mostra (opacidade 100%) ele na posição onde ele está
							$container.css({opacity: 1, 'display':'inline'});
						}else{
							if($ControlEvent['tip_visible'] === false){
								update_pos_element();
								set_tipPosition();
								show_tooltip();
							}
						}*/
						$container.stop();
						$ControlEvent['hiding_tip'] = false;
						update_pos_element();
						set_tipPosition();
						show_tooltip();
					}
				});
				return true;
			}
			
			/*
			*	seta evento de ocultar o tooltip
			*/
			function set_event_hide(){
				log('function start: set_event_hide()');
				if(options.event_hide != 'mouseleave'){
					log('invalido options.event_hide:'.options.event_hide);
					return false
				}
				$element.bind(options.event_hide, function(){
						log('element MOUSE OUT --- showing_tip: '+$ControlEvent['showing_tip']+'  --- hiding_tip: '+$ControlEvent['hiding_tip']);													
						$ControlEvent['mouseover_element'] = false;
						$container.animate({opacity: 1}, 1000, function(){
							if(($ControlEvent['showing_tip'] === false || $ControlEvent['hiding_tip'] === false) && $ControlEvent['mouseover_tip'] === false && $ControlEvent['tip_visible'] === true){
								hide_tooltip();
							}
						});
							
						
				});
				return true;
			}
			/************************************************************************************************/
			
			
			/************************************************************************************************/
			/*										SETA AÇÕES PARA O TOOLTIP
			/************************************************************************************************/
			
			
			/*
			*	seta efeito ao ficar com o mouse sobre o tooltip
			*/
			function mouseover_tooltip(){
				log('function start: mouseover_tooltip()');
				$container.bind('mouseenter mouseover', function(){
														  $ControlEvent['hiding_tip'] = false;
														  $ControlEvent['mouseover_tip'] = true;
														  log('mouseover_tip === '+$ControlEvent['mouseover_tip']);
														});
			}
			
			
			/*
			* seta efeito ao tirar o mouse de sobre o tooltip
			*/
			function mouseleave_tooltip(){
				log('function start: mouseleave_tooltip()');
				$container.bind('mouseleave', function(){
				   	$ControlEvent['mouseover_tip'] = false;
				   	$container.animate({opacity: 1}, 1000, function(){
						if(($ControlEvent['showing_tip'] === false || $ControlEvent['hiding_tip'] === false) && ($ControlEvent['mouseover_element'] === false) && ($ControlEvent['mouseover_tip'] === false) ){
							hide_tooltip();
						}
					});

				});
			}
			
			/************************************************************************************************/
			
			/************************************************************************************************/
			/*										SETA CONFIGS 
			/************************************************************************************************/
			
			
			/*
			*	seta valor na variável de configuração
			*/
			function set_config_item(key, value){
				try {
					options[key] = value;
				}
				catch(exception) {
					log(exception);
				}
				return true;
			}
			
			
			/*
			*	retorna o posicionamento que deve ser feito no tooltip
			*/
			function set_tipPosition(){
				log('function start: return_tipPosition()');
					if(isNaN(options.tooltip_view_y)){
						if(options.tooltip_view_y == 'bottom'){
							options.tooltip_y = options.EL_pos_y + options.EL_height;
						}else 
						if(options.tooltip_view_y == 'middle'){
							options.tooltip_y = options.EL_pos_y + (options.EL_height / 2) - ($container.height()/2);
						}else
						if(options.tooltip_view_y == 'top'){
							options.tooltip_y = options.EL_pos_y - $container.height() - options.EL_height;
						}else{
							log('options.y não é um valor válido esperado');
							return false;
						}
					}else if(!isNaN(options.tooltip_view_y)){

					}
					//  -----------------
					if(isNaN(options.tooltip_view_x)){
						var a = 0;
						if(options.tooltip_view_x == 'left'){
							options.tooltip_x = options.EL_pos_x - $container.width();
						}else 
						if(options.tooltip_view_x == 'center'){
							options.tooltip_x = options.EL_pos_x + (options.EL_with / 2 ) - ($container.width() / 2);
						}else
						if(options.tooltip_view_x == 'right'){
							options.tooltip_x = options.EL_pos_x + options.EL_with;
						}else{
							log('options.y não é um valor válido esperado');
							return false;
						}
					}else if(!isNaN(options.tooltip_view_x)){

					}					
				return true;
			}
			/************************************************************************************************/
			
			/************************************************************************************************/
			/*										SETA EFEITOS
			/************************************************************************************************/
			
			/*
			*	adiciona o efeito de ocultar o tooltip
			*/
			function hide_tooltip(){
				log('function start: hide_tooltip()');
				if($ControlEvent['hiding_tip'] === true){
					log('function hiding_tip === true, return false');
					return false;
				}
				$ControlEvent['hiding_tip'] = true;
				if(options.effect_hide == 'smooth_slide_bt'){
					//	$container.stop();
						$container.animate({
											 'top':(options.tooltip_y - 10 )+'px', 
											 opacity: 0
											 }, 300, function(){
												 $container.css({'display':'none'}, function(){
																								$ControlEvent['hiding_tip'] = false;
																								 $ControlEvent['tip_visible'] = false;
																							 });
												 
												 });
				}
				return true;
			}
			
			/*
			*	adiciona o efeito de exibição do tooltip
			*/
			function show_tooltip(){
				log('function start: show_tooltip()');
					$ControlEvent['showing_tip'] = true;
					if(options.hide_other_tips){
						$('.rnd_tooltip').css({'display':'none'});
					}
					if(options.effect_show == 'smooth_slide_bt'){
							//$container.stop();
							$container.css({
											'display':'inline'
											,'top': (options.tooltip_y + 10)+'px'
											,'left': (options.tooltip_x) +'px'
											})
										.animate({
												 'top':(options.tooltip_y )+'px', 
												 opacity: 1
												 }, 200, function(){
															$ControlEvent['showing_tip'] = false;
															$ControlEvent['tip_visible'] = true;
													 });
						
					}
				return true;
			}
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
				
			
			/************************************************************************************************/
			
			
			
			/*
			* debug
			*/			
			function log(message) {
				if(options.use_debug === true){
					message = 'Log: '  + message;
					if(window.console) {
						console.debug(message);
					} else {
						alert(message);
					}
				}
				return true;
			};

			init();
		});
	}
})(jQuery);


// $('#seta_teste').Rnd_Tooltip({'html_content':'<h3>teste</h3>'})
