var timeout_flag    = null;
var shown_id        = null;
var shown_img       = null;
var hide_interval   = 1000;

function hideSubNav(){
    if (shown_id){
        $('#' + shown_id).hide();
        if (!$(shown_img).attr('data-selected')){
            shown_img.src = shown_img._img.src;
        }
    }
}

function showSubNav(sub_nav, img_obj){

    shown_id = sub_nav;
    shown_img = img_obj;
    if (!$(shown_img).attr('data-selected')){
        shown_img.src = shown_img._over.src;
    }
    if (sub_nav){
        $('#' + shown_id).show();
    }
}

$(document).ready(function(){
    var img_over_sufix  = '-over';
    
    $("img.hover").each(function() {
        // preload images
        this.src.match(/^(.*)\.(\w+)$/);
        var over_src = RegExp.$1 + img_over_sufix + "." + RegExp.$2;
        
        this._over     = new Image();
        this._over.src  = over_src;

        this._img      = new Image();
        this._img.src  = this.src;

        if (this.src.indexOf(img_over_sufix) != -1){
            $(this).attr('data-selected', true);
        }

        $(this).mouseover(function(){
            clearTimeout(timeout_flag);
            hideSubNav();
            showSubNav($(this).attr('subid'), this);
        });

        $(this).mouseout(function(){
            if ($(this).attr('no_sub_nav')){
                hideSubNav();
            } else {
                timeout_flag = setTimeout(hideSubNav,hide_interval);
            }
            
        });
    });

    $("div.sub_navigation").each(function() {

        $(this).mouseover(function(){
            clearTimeout(timeout_flag);
        });

        $(this).mouseout(function(){
            timeout_flag = setTimeout(hideSubNav,hide_interval);
        });

    });

    $("div.sub_navigation > div.item").each(function() {
        $(this).click(function(){
            var link_obj = $(this).children('a:first').get(0);
            document.location = $(link_obj).attr('href');
        });

        $(this).mouseover(function(){
            $(this).addClass("item_hover");
            $(this).children('a:first').css('color', '#3d64a0');
        });

        $(this).mouseout(function(){
            $(this).removeClass("item_hover");
            $(this).children('a:first').css('color', '#ffffff');
        });

    });

})
