/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

var $tendina;
var isOpen = false;
var timeoutClose;
var timeoutOpen;
var onFocus = false;
var hover = false;


$(document).ready( function() {
  $tendina = $('#tendina-login');
  $bottoneLogin = $('div.menu-principale ul#menu li.login a.bottone-login');

  $('input#signin_username, input#signin_password').keyup( function(key) {
    if (key.keyCode == 13) {
      //invio
      $('#form-tendina-login').submit();
    }
  })

  $('input#signin_username, input#signin_password').focus( function() {
    onFocus = true;
    triggerEvent();
  });
  $('input#signin_username, input#signin_password').blur( function() {
    onFocus = false;
    triggerEvent();
  });

  $bottoneLogin.hover(function() {
    hover = true;
    triggerEvent();
  }, function() {
    hover = false;
    triggerEvent();
  });

  $tendina.hover(function() {
    hover = true;
    triggerEvent();
  }, function() {
    hover = false;
    triggerEvent();
  });
  
});

function triggerEvent() {
  if (hover) {
    // evento di apertura
    isOpen = true;
    // apro
    $tendina.slideDown(400);
    $bottoneLogin.addClass('selected');
    if (timeoutClose) {
      clearTimeout(timeoutClose);
    }
  } else {
    // evento di chiusura
    // setto il timeout di chiusura
    timeoutClose = setTimeout(doClose, 500);
  }
}

function doClose() {
  if (onFocus) return;
  $tendina.slideUp(500, removeSelected);
}

// rimuove la classe selected dal bottone
function removeSelected() {
  $bottoneLogin.removeClass('selected');
}
