/*
 * Migliorie di usabilita' al dropdown
 * 
 * Author: Andrea Zilio, http://andrea.zilio.name
 */

$(function() {

  var dropDownDelay = 100;
  var hoverClass = 'dropdownContainerOnHover';

  // Set the document as JS enabled (this disables css-only dropdown menu)
  $(document.body).removeClass('noJS');
  
  // close button for dropdowns
  var $closeButton = $('<a href="#closeSubMenu">Chiudi</a>').addClass('closeButton');
  $closeButton.attr('title','Chiudi questo menu');

  // Add the close button to all dropdowns
  $('.dropdownContainer .dropdown').append($closeButton);
  $('.dropdownContainer .dropdown .closeButton').click(function(e) {
    var $ancestor = $(this).parents('.dropdownContainer').eq(0);
    window.clearInterval($ancestor.get(0).hoverTimer);
    $ancestor.removeClass(hoverClass);
    $(this).blur();
    e.preventDefault();
  });

  // Add hover handlers
  $('.dropdownContainer').hover(function () {
    var $this = $(this);
    if(!$this.hasClass(hoverClass)) {
      // mouseHover & dropdown closed
      var timeoutID = window.setTimeout(function() {
        if($.browser.msie && $.browser.version == '6.0') {
          // Aggiusta l'altezza in IE 6
          if($this.find('.blank').size() > 0)
          	$this.find('.blank').height($this.innerHeight());
        }
        $this.addClass(hoverClass);
        if (typeof ClickTaleExec == "function") {
          ClickTaleExec("$('#" + $this.find('.dropdown').attr('id') + "').parent().addClass('" + hoverClass + "')");
        }
      },dropDownDelay);
      $this.get(0).hoverTimer = timeoutID;
    } else {
      // mouseHover & dropdown opened
      window.clearInterval($this.get(0).hoverTimer);
    }
  }, function () {
    var $this = $(this);
    if($this.hasClass(hoverClass)) {
      // mouseOut & dropdown opened
      var timeoutID = window.setTimeout(function() {
        $this.removeClass(hoverClass);
        if (typeof ClickTaleExec == "function") {
          ClickTaleExec("$('#" + $this.find('.dropdown').attr('id') + "').parent().removeClass('" + hoverClass + "')");
        }
      },dropDownDelay);
      $this.get(0).hoverTimer = timeoutID;
    } else {
      // mouseOut & dropdown closed
      window.clearInterval($this.get(0).hoverTimer);
    }
  });
});