// Fixes bugs and non-existance of push and pop in browsers
Array.prototype.push = function() {
    var n = this.length >>> 0;
    for (var i = 0; i < arguments.length; i++) {
	this[n] = arguments[i];
	n = n + 1 >>> 0;
    }
    this.length = n;
    return n;
};

Array.prototype.pop = function() {
    var n = this.length >>> 0, value;
    if (n) {
	value = this[--n];
	delete this[n];
    }
    this.length = n;
    return value;
};

var current_dropdown = '';
$(document).ready(function(){  
    
    
    $("ul.subnav").parent().append("<span></span>"); //Only shows drop down trigger when js is enabled (Adds empty span tag after ul.subnav*)  
    
    $("ul.topnav li span, .topnav > li > a").mouseover(function() { //When trigger is clicked...  
        
        // Dont fade in a menu if already live
        id = $(this).parent().attr("id");
        if( id == current_dropdown)
          return false;
        current_dropdown = id;

        $(".selected").removeClass("selected")        
        $(this).parent().addClass("selected")
        
        //Following events are applied to the subnav itself (moving subnav up and down)  
        // Take subnav and populate the links into container
        
        contents = $(this).parent().find("ul.subnav").clone(); //Drop down the subnav on click  
        $("#subnav_container").html( contents).show(); 
        
        
        
        $(this).parent().hover(function() {  
        }, function(){  
            //$(this).parent().find("ul.subnav").fadeOut('fast'); //When the mouse hovers out of the subnav, move it back up  
        });  
  
        //Following events are applied to the trigger (Hover events for the trigger)  
        }).hover(function() {  
            $(this).addClass("subhover"); //On hover over, add class "subhover"  
        }, function(){  //On Hover Out  
            $(this).removeClass("subhover"); //On hover out, remove class "subhover"  
    });  
  
    // Select dropdown of page if currently loaded
    page_list = window.location.href.split("/");
    page_name = 'none';
    if(typeof(page_list) == "object"){      
      page_name = page_list.pop();
      page_name = page_name.split("#")[0];
    }
    
    li_box = $("li ul li [href="+page_name+"]").parent().parent().parent();
    
    if(li_box){
      li_box.addClass("selected");
      id = li_box.attr("id");
      current_dropdown = id;
      
      contents = li_box.find("ul.subnav").clone(); //Drop down the subnav on click  
      $("#subnav_container").fadeOut( function(){
        $("#subnav_container").html(contents).show();       
      });
      
    }
  
  
});
