(function( $ ){
	
	var settings = {
		//
    };
	
	var methods = {
		init : function (options) {
			if ( options ) { 
				$.extend( settings, options );
			}
			
			return this.each(function(i, el){
		    	var _this = this;
		    	var $this = $(this);
		    	var selected = null;
		    	var elements = [];
		    	var lastElWithSubNavId = null;
		    	
		    	$('body').click(function(evt) {
		    		setSelection(null);
				});
		    	
		    	function setSelection (el) {
		    		if (selected) {
		    			$(selected).removeClass('active');
		    			var secNav = $('> ul.primarySubNavigation', $this.parent());
		    			secNav.appendTo(selected);
		    			secNav.hide();
		    		}
		    		if (selected != el) {
		    			selected = el;
		    			if (!selected) return;
			    		$(selected).addClass('active');
			    		secNav = $('ul.primarySubNavigation', el);
			    		secNav.appendTo($this.parent());
			    		secNav.show();
			    		var l = Math.round($('> a', selected).offset().left);
//			    		if (el == elements[lastElWithSubNavId].el) l = Math.round($('> a', elements[lastElWithSubNavId-1].el).offset().left);
		    			secNav.offset({left: l});
		    		}
		    	}
		    	
		    	$('> li > a', _this).each(function(i, el){
		    		var liEl = $(this).parent().get()[0];
		    		var hasSecNav = $('ul.primarySubNavigation', liEl).length;
		    		if (hasSecNav) lastElWithSubNavId = elements.length;
		    		elements.push({el: liEl, hasNav: hasSecNav});
		    	}).click(function(evt){
		    		var el = $(this).parent().get()[0];		    		
		    		var hasSecNav = $('ul.primarySubNavigation', el).length;
	    			if (hasSecNav) {
	    				setSelection(el);
	    				return false;
	    			}
		    	}).mouseover(function(evt){
		    		if (selected) {
		    			var el = $(this).parent().get()[0];
			    		var hasSecNav = $('ul.primarySubNavigation', el).length;
		    			if (hasSecNav) {
		    				setSelection(el);
		    				return false;
		    			}
		    		}
		    	});
		    });
		}
	}
	
	$.fn.primaryNavigation = function( method ) {
	    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 );
	    } else {
	        $.error( 'Method ' +  method + ' does not exist on jQuery.primaryNavigation' );
	    }
	}	
})( jQuery );
