/*
*	Navigation
*	Generates Flickr-style dropdown navigation
*	
*	Requires Trapeze jQuery distribution
*	
*	Taylan Pince (tpince at trapeze dot com) - February 23, 2009
*/

$.namespace("trapeze.Navigation");

trapeze.Navigation = $.Class.extend({
    
    selector : "",
    active_dropdown : null,
    wrapper_template : '<div class="dropdown-button"></div>',
	arrow_template : '<a href="javascript:void(0);" class="arrow"><img src="%(media_path)images/btn-nav-arrow.png" alt="" /></a>',
	subnav_arrow_template : '<a href="javascript:void(0);" class="arrow"><img src="%(media_path)images/btn-subnav-arrow.png" alt="" /></a>',
    
    build_dropdown : function(index, obj) {
	
        if ($(obj).find("div.dropdown").size() > 0) {

			if ($(obj).parent().attr("id") == "SubNavigation") {
	            $(obj).children("a").after(trapeze.render_template(this.subnav_arrow_template, {
	                "media_path" : trapeze.media_path
	            }));
			} else {
				$(obj).children("a").after(trapeze.render_template(this.arrow_template, {
	                "media_path" : trapeze.media_path
	            }));
			}
			
            
            $(obj).children("a.arrow").click(
                this.open_dropdown.bind(this)
            ).hover(
                this.over_dropdown.bind(this),
                this.out_dropdown.bind(this)
            );
            
            $(obj).children().wrapAll(this.wrapper_template);
        }
    },
    
    over_dropdown : function(evt) {
        $(evt.currentTarget).parent().addClass("dropdown-hover");
    },
    
    out_dropdown : function(evt) {
        $(evt.currentTarget).parent().removeClass("dropdown-hover");
    },
    
    open_dropdown : function(evt) {
        var obj = $(evt.currentTarget).parent().find("div.dropdown").get(0);
        
        if (this.active_dropdown && this.active_dropdown != obj) {
            $(this.active_dropdown).slideUp("fast");
        }
        
        if (this.active_dropdown == obj) {
            $(obj).slideUp("fast");
            
            this.active_dropdown = null;
        } else {
            $(obj).slideDown();
            
            this.active_dropdown = obj;
        }
    },
    
    close_active_dropdown : function(evt) {
        if (this.active_dropdown && $(evt.target).parents(this.selector).size() == 0) {
            $(this.active_dropdown).slideUp("fast");
            
            this.active_dropdown = null;
        }
    },
    
    init : function(selector) {
        this.selector = selector;
        
        $(this.selector).children("li").each(this.build_dropdown.bind(this));
        $("html").click(this.close_active_dropdown.bind(this));
    }
    
});
