(function($) {

	var dbug = function( msg ){
		try {
			if(window.console){
				console.debug(msg);
			}
		} catch(e) { /* ignore silently */ }
	};



	$.fn.bmbNavigation = function(opts){

		// set default options and extend them with user-options
		var options = $.extend({
			"activeElement": null,
			"duration": 200
		}, opts);

		return this.each(function(){

			var $navListItems = $("#menu-hauptmenu > li", this);
			var $navBars = $("#menu-hauptmenu .nav_bar", this);

			// nav_bar clicks
			$navBars.click(function(){
				// index of the clicked element
				var idx = $navBars.index(this);

				// iterate over all elements
				$navBars.each(function(index, elem){
					var $elem = $(elem);
					var $navListItem = $navListItems.eq(index);

					// finish all prior animations before doing anything
					$navListItem.stop(true, true);

					// check if element is left or right of clicked element or the clicked element
					if( index <= idx ){
						// element is left

						// if element is not on the left/active animate!
						if( !$navListItem.hasClass("nav_active") ){

							$navListItem
								.animate({
									"left": "-=600"
								},
								options.duration,
								function(){
									$navListItem.addClass("nav_active");
								});
						}
					}
					else {
						// element is right

						// if element is not on the right/inactive animate!
						if( $navListItem.hasClass("nav_active") ){

							$navListItem
								.animate({
									"left": "+=600"
								},
								options.duration,
								function(){
									$navListItem.removeClass("nav_active");
								});
						}
					}
				});

				return false;
			});

			if(options.activeElement !== null){
				// index of the clicked element
				var idx = options.activeElement;

				// iterate over all elements
				$navBars.each(function(index, elem){

					var $elem = $(elem);
					var $navListItem = $navListItems.eq(index);

					// check if element is left or right of active element
					if( index <= idx ){
						// element is left
						$navListItem
							.css({ "left": index*($navBars.eq(0).width()) })
							.addClass("nav_active");
					}
					else {
						// element is right
						$navListItem.removeClass("nav_active");
					}
				});
			}

		});
	};

})(jQuery);

