(function( $ ){

	var settings = {
		target: null
		,delay: 500
	};

	var methods = {

		init : function( options ) {

			if ( options ) $.extend( settings, options );

			settings.doShow = false;
			settings.doHide = false;
			settings.current = null;
			settings.nav = this;

			settings.target
			.hover(
				function(){
					settings.doHide = false;
					settings.current = $(this).data("id");
				}
				,function(){
					settings.doHide = true;
					$.fn.WomanspaceTopNav("scheduleHide");
				}
			);

			return this.each(function() {
				$(this)
				.children("li")
				.hover(
					function(){ $(this).WomanspaceTopNav("scheduleShow"); }
					,function(){ $.fn.WomanspaceTopNav("scheduleHide"); }
				);
			});
		},

		scheduleShow : function(){
			settings.doShow = true;
			settings.doHide = false;
			settings.current = this;
			setTimeout(function(){
				$.fn.WomanspaceTopNav("doShow");
			},settings.delay);

		},

		scheduleHide : function(){
			settings.doHide = true;
			setTimeout(function(){
				$.fn.WomanspaceTopNav("doHide");
			},settings.delay);
		},

		doShow : function(){

			if( !settings.doShow ) return;
			if( settings.doHide ) return;

			settings.target
			.hide()
			.html("")
			;

			$(settings.target.data("id"))
			.removeClass("hovered")
			;

			settings.target
			.data("id",settings.current)
			;

			var contents =
			$("<div/>")
			.appendTo(settings.target)
			;

			settings.current
			.addClass("hovered")
			.children(".children")
			.clone()
			.appendTo(contents)
			;

			settings.target
			.show()
			;

		},

		doHide : function(){

			if( !settings.doHide ) return;

			settings.current
			.removeClass("hovered")
			;

			settings.target
			.hide()
			.html("")
			;
		}

	};

	$.fn.WomanspaceTopNav = function( method ) {
		// Method calling logic
		if ( methods[method] ) {
			return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} else if ( typeof method === 'object' || ! method ) {
			return methods.init.apply( this, arguments );
		}
	};

})( jQuery );

$(document).ready(function(){
	$("ul.topnav")
	.WomanspaceTopNav("init",{ target: $("#topnav_subnav") });
});

