﻿/// <reference path="jquery-1.7.1.min.js" />
/// <reference path="utils.js" />

//=========== Всплывающие подсказки (jQuery plugin) ==========
(function( $) {
  var $callout = null;
  $(document).ready( function() {
    if( $callout === null) {     // Создаем всплывающее окно
      $callout = $(
      '<table cellpadding="0" cellspacing="0" id="dTooltip">' +
        '<tr><td class="tdTipFirst">&nbsp;</td></tr>' +
        '<tr><td class="tdTipSec"><img src="img/tooltip-img.png" alt="" width="14" height="7" /></td></tr>' +
      '</table>'
      );
      $callout.appendTo( $(document.body));
      $callout.hide();
    }
    $(document).bind( 'mousemove', function( event) { mouseX = event.pageX; });
  });

  var defaults = {
    func     : null,
    text     : null,
    topBase  : null,
    topOffset: 0
  };
  var currentlyHovered = null; // tracks the node which is being hovered over
  var mouseX;

  $.hideTooltip = function() {
    //Debug.writeln('hiding tooltip ' + new Date());
    if( $callout != null) {
      $callout.hide().css({ left: '0px', top: '0px' });
    }
  };

  function showTooltip( target, options) {
    // Compose options
    options = $.extend( { func: null, text: null, topBase: null, topOffset: 0}, options);
    if( options.func) {
      var result = options.func.call( target, options);
      if( $.isPlainObject( result))
        $.extend( options, result);
      else if( result)
        options.text = result;
    }

    if( options.text) {
      //Debug.writeln('showing tooltip ' + options.text + ' ' + new Date());
      var $title = $callout.find('td:first');

      // Если вертикальная "база" не задана, подсказка будет показана над this
      var $thisBase = $(options.topBase === null ? target : options.topBase);

      $title.text( options.text);
      $callout.show();

      var baseTop = $thisBase.offset().top;
      var top = baseTop - $title.innerHeight() + options.topOffset;
              
      // Ограничим подсказку по "клиентской" части страницы
      var width = $callout.width();
      var left  = Math.floor( mouseX - width/2);
      var right = left + width;

      var $page = $('.dPage');
      var pageLeft  = $page.offset().left + parseFloat( $page.css('padding-left'));
      var pageRight = $page.offset().left + $page.innerWidth() - parseFloat( $page.css('padding-right'));
      var dx = 0;
      if( left < pageLeft)
        dx = pageLeft - left;
      else if( right > pageRight)
        dx = pageRight - right;
      left += dx;

      $callout.css({ left: left, top: top });
              
      // Выставим клюв по мыши
      var $beakTD     = $callout.find('.tdTipSec')
      var beakWidth   = $('img', $beakTD).outerWidth( false);
      var paddingLeft = mouseX - left - Math.floor( beakWidth/2);
      paddingLeft = Math.max( paddingLeft, 14);
      paddingLeft = Math.min( paddingLeft, width - beakWidth - 14);
      $beakTD.css( 'padding-left', paddingLeft);
    }
  };

  function parseArguments( tooltipArguments) {
    var arg0 = tooltipArguments[0], text, func, explicitOptions;
    if( $.isFunction( arg0))
      func = arg0;
    else if( $.isPlainObject( arg0))
      explicitOptions = arg0;
    else
      text = arg0;
    if( tooltipArguments.length > 1)
      explicitOptions = tooltipArguments[1];
    var inputOptions = $.extend( {}, defaults, explicitOptions);
    if( text)
      inputOptions.text = text;
    if( func)
      inputOptions.func = func;
    return inputOptions;
  }

  // Устанавливает текст всплывающей подсказки
  $.fn.tooltip = function( /*textOrFunc, explicitOptions*/) {
    this.unbind('.tooltip');
    if( arguments.length && arguments[0]) {
      var tooltipArguments = arguments;
      this.bind( 'mouseenter.tooltip',
        function( event) {
          mouseX = event.pageX;
          // Update currentlyHovered and save its value for later use
          var saveHovered = currentlyHovered = this;
        
          window.setTimeout(
            function() {
              if( currentlyHovered === saveHovered) // still hovering over the same node?
                showTooltip( currentlyHovered, parseArguments( tooltipArguments));
            }, 500);
        }
      )
      .bind( 'mouseleave.tooltip',
        function( event) {
          currentlyHovered = null;
          $callout.filter(':visible')
            .hide()
            .css({ left: '0px', top: '0px' });
        }
      )
    }
    return this;
  };

  // Устанавливает текст всплывающей подсказки
  $.startTooltip = function( target, event, options) {
    mouseX = event.pageX;
    // Update currentlyHovered and save its value for later use
    var saveHovered = currentlyHovered = target;
        
    window.setTimeout(
      function() {
        if( currentlyHovered === saveHovered) // still hovering over the same node?
          showTooltip( currentlyHovered, options);
      }, 500);
  };
  $.stopTooltip = function() {
    currentlyHovered = null;
    if( $callout) {
      $callout.filter(':visible')
        .hide()
        .css({ left: '0px', top: '0px' });
    }
  };
})( jQuery);

