//
// RailEasy Blog Theme
// Author: Christophe Bouthier - Binary Gastronome
//
// javascript menus, display categories and sub-categories as drop-down menus
//

var current_cat = null;               // category of the page
var current_sub_cat = null;           // sub-category of the page
var shown_sub_cat = null;             // sub-categories shown
var category_is_current = false;      // is the page a category page ?
var sub_category_is_current = false;  // is the page a sub-category page ?
var selected_category = null;         // category that is selected (hovered)

// register hovering functions
$(function() {
  hideAllSubCat();
  setCurrentSubCat();
  showCurrentSubCat();

  $(".categories > ul > li").hover(
    function() {  // hover in
      $(".categories").stopTime();
    
      hideShownSubCat();
      showSubCat($(this));
      selectCategory($(this));
    },
    function() {  // hover out, letting time for the user to hover back in or on sub-category
      $(".categories").oneTime(300, function() {
        hideShownSubCat();
        showCurrentSubCat();
        deselectAllCategory();
      });
    }
  );
});


function hideAllSubCat() {
  $(".categories ul ul").hide();
}

function hideShownSubCat() {
  if (shown_sub_cat) {
    shown_sub_cat.hide();
  }
  shown_sub_cat = null;
}

function showSubCat(category) {
  if (category.is(":has('ul')")) {
    shown_sub_cat = $(" ul", category);
    shown_sub_cat.show();
  }
}

function setCurrentSubCat() {
  var current_categories = $(".categories > ul > li.category-current");
  var current_sub_categories = $(".categories > ul > li > ul > li.category-current");
  
  if (current_categories.length != 0) {
    category_is_current = true;
    current_cat = current_categories;
  }
  
  if (current_sub_categories.length != 0) {
    sub_category_is_current = true;
    current_sub_cat = current_sub_categories; 
    current_cat = current_sub_cat.parent().parent();
    current_cat.addClass("subcategory-current");
  }
}

function showCurrentSubCat() {
  if (category_is_current) {
    shown_sub_cat = $(" ul", current_cat);
  } else if (sub_category_is_current) {
    shown_sub_cat = current_sub_cat.parent();
  }
  
  if (shown_sub_cat) {
    shown_sub_cat.show();
  }
}

function selectCategory(category) {
  deselectAllCategory();
  selected_category = category;
  
  if ((current_cat) && (category[0] == current_cat[0])) {
    selected_category.addClass("current-selected");
  } else {
    selected_category.addClass("selected");
  }
}

function deselectAllCategory() {
  if (selected_category) {
    selected_category.removeClass("selected");
    selected_category.removeClass("current-selected");
  }
}
