﻿function loadDropDowns() {
    var SubCats = $("#prim-nav .sub-nav");
    for (var idx = 0, len = SubCats.length; idx < len; idx++) {
        //get the id
        var topCatId = $(SubCats[idx]).attr("id").replace(/sub-nav-/ig, "");
        //create the container
        var dropDown = document.createElement("div");
        $("#prim-nav").append(dropDown);
        $(dropDown).attr("id", "menu-drop-down-" + topCatId);
        $(dropDown).attr("class", "menu-drop-down");
        //create the top bit
        var topBit = document.createElement("div");
        $(dropDown).append(topBit);
        $(topBit).attr("class", "top");
        //create the middle bit
        var middleBit = document.createElement("div");
        $(dropDown).append(middleBit);
        $(middleBit).attr("class", "middle");
        //move the list over
        var ul = document.createElement("ul");
        $(ul).html($(SubCats[idx]).html());
        $(middleBit).append(ul);
        //create the bottom bit
        var bottomBit = document.createElement("div");
        $(dropDown).append(bottomBit);
        $(bottomBit).attr("class", "bottom");
        //position the drop down
        var primNavEle = $("#top-menu-" + topCatId).parent();
        var left = $(primNavEle).position().left;
        $(dropDown).css("left", left);
        var top = $(primNavEle).position().top + $(primNavEle).height();
        $(dropDown).css("top", top);
    }
}

var dropDownTimeout = null;    
$(document).ready(function(){
    //load up the drop downs...
    loadDropDowns();
    
    //Event handle when user move the mouse over the top category
    $("#page-header-v2 #prim-nav ul li").hover(function() {
        //find the id for this ele from the a inside it...
        var topCatId = $(this).children("a").attr("id").replace(/top-menu-/ig, "");
        //show the appropriate dropdown
        $("#menu-drop-down-" + topCatId).show();
    }, function() {
        var topCatId = $(this).children("a").attr("id").replace(/top-menu-/ig, "");
        //set a timeout to hide the drop down
        dropDownTimeout = setTimeout(function() {
            $("#menu-drop-down-" + topCatId).hide();
        }, 10);
    });
    //event for when user clicks the li 
    $("#page-header-v2 #prim-nav ul li").click(function() {
        //get the a inside it and click it!
        var link = $(this).children("a").attr("href");
        window.location = link;
    });
    //event handler for when user mouses over the drop downs
    $("#page-header-v2 .menu-drop-down").hover(function() {
        //clear the 'hide' timeout so the drop down doesn't disappear
        if (dropDownTimeout != null) {
            clearTimeout(dropDownTimeout);
        }
    }, function() {
        $(this).hide();
    });
});