// Plugin created by Brock Nusser - http://mlamenu.blogspot.com/

$.noConflict();
jQuery(document).ready(function($) {
 
	initSideMenu($);
	
	if($.browser.msie && $.browser.version < 7) {
		$('#nav > li').mouseenter(function() {
			$(this).addClass('iefix');
		}).mouseleave(function() {
			$(this).removeClass('iefix');
		});
	} else {
		/* shadow overlay */
		$('.page .header').append('<div id="shadow-hack"></div>')
		$( '#nav' ).dynamicMenu({
			columnWidth : 210,
			offsetLeft: 120
		});		
	} 	
	
});






(function($){
	//globals
	var helper = {},
		current = {};  
		
	
	$.dynamicMenu = {
			defaults: {
				offsetLeft: 124,
				columnHeight: 120,
				id: 'dynamicMenuBox',
				columnWidth: 200,
				heightInterval: 20,
				maxColumns: 4,
				containerWidth: 840
			}
		};
	
    $.fn.extend({
        dynamicMenu: function(settings) {
             
            var settings = $.extend({}, $.dynamicMenu.defaults, settings);
            helper.settings = settings;

            return this.each(function() {      
                  var items = $(" > li", this);
              	  //den alten subnavis eine breite geben, damit wir die dimensions der li elemente holen können   
                  $(" ul", this).css('width', settings.columnWidth);                  
                 
                  //die neue subnavi im li erstellen
                  $.each(items, function(index, element) {
                	  
                      //das aktuelle element muss zwingend gegeben sein..
                	  current = element;
                	  if($('li', current).length > 0) {
                		  //box innerhalb des eigenen li erstellen
                          init();  
                          //init display mode
                          if($.browser.msie && $.browser.version < 8) {
                        	  $(helper.parent).addClass('no-slide');
                        	  $('.dynamicMenuBoxContainer').hide();
                    	  } else {
                    		  $(current).find('.'+helper.settings.id + ' .dynamicMenuBoxContainer').animate({'height': 0, paddingBottom: 0}, 1);                    		  
                    	  }
                          
                          
                          $(element).mouseenter(function() {
                	  		  if($.browser.msie && $.browser.version < 8) {
                	  			$(this).find('.'+helper.settings.id).show().find('.dynamicMenuBoxContainer').show();
                        	  } else {
                        		  $(this).find('.'+helper.settings.id).show().find('.dynamicMenuBoxContainer')
                            	  .stop().animate({'height': $(this).data('boxHeight'), paddingBottom: 36}, 500);  
                        	  }
                        	   
                          })                  
                          .mouseleave(function() {
                        	  if($.browser.msie && $.browser.version < 8) {
                        		  $(this).find('.'+helper.settings.id).show().find('.dynamicMenuBoxContainer').hide();  
                        	  } else {
                        		  $(this).find('.'+helper.settings.id + ' .dynamicMenuBoxContainer').stop().animate({'height': 0, paddingBottom: 0}, 500);  
                        	  }
                        	  
                          });
                          
                	  }
                	  
                  });     
                          
                  
                  
            });
        }
    });
    
    function init() {
    	helper.columns = [];   
    	//minimal menuheight is 0
    	helper.menuHeight = 0;    	
    	helper.parent = $('<span class="'+helper.settings.id+'"></span>')
    	.appendTo(current)
    	.append('<span class="right-bg"><span class="inner dynamicMenuBoxContainer"></span></span>');
    	helper.inner = $(current).find('.dynamicMenuBoxContainer');
    	
    	//gather the data
    	//prepare columns
    	//move left
    	var offset = $(current).position();
    	//abstand vom linken rand (abzüglich dem statischen offset am anfang (zb. margin))
    	helper.settings.offsetLeft = offset.left - $.dynamicMenu.defaults.offsetLeft;
    	moveBox(0);    	
    	var columnHeight = helper.settings.columnHeight;
    	var response = createColumns( current, columnHeight ); 
    	var numAdditionalRows = 0;
    	while(response > 0) {
    		numAdditionalRows += 1;
    		reset();
    		columnHeight += helper.settings.heightInterval;
    		response = createColumns( current, columnHeight );
    	}
    	
    	drawColumns(current, numAdditionalRows);
    	
    }
    
    
    
    
    
    function createColumns(containerelement, height) {
    	var maxColumnHeight = height;
    	
    	var columnIndex = 0;
    	var hTotal = 0;
    	var maxHeight = 0;
    	var i = 0;
    	
    	var eOverflow = 0;
    	
    	//loop and create matrix
    	$("li", containerelement).each( function(index, element) {
    		if( i == 0 ) {
    			addColumn();
    		}
    		
    		var heightNew = $(element).height(); 

    		//add a column, because max height is reached
    		if(  (heightNew + hTotal) > maxColumnHeight ) {    			
    			//move left if necessary
    			//console.log($(helper.parent).width()  +'-'+ (columnIndex+2)  +'-'+ helper.settings.columnWidth  +'-'+ getBoxOffset()  +'-'+ helper.settings.offsetLeft +'-'+ helper.settings.containerWidth );
    			if( ( $(helper.parent).width() + ((columnIndex+2) * helper.settings.columnWidth) + getBoxOffset()  ) > helper.settings.containerWidth) {
    				
    				if( getBoxOffset() > 0 ) {
    					//console.log(getBoxOffset() +'-' + $(helper.parent).position().left + '-'+helper.settings.offsetLeft);
	    				//move left a columnWidth but not over the starting point
	    				moveBox( Math.max(getBoxOffset() - helper.settings.offsetLeft - helper.settings.columnWidth, -helper.settings.offsetLeft)) ;	    				
    				}
    			}	
    			addColumn();
    			hTotal = 0;
    			columnIndex += 1;
    		}
    		
    		//die anzahl elemente die zuviel sind erhöhen
    		if(columnIndex >= helper.settings.maxColumns) {
    			eOverflow += 1;
    		}
    		
    		//der spalte ein element anfügen
    		helper.columns[columnIndex].push($(element).addClass('c'+helper.settings.offsetLeft));
    		hTotal += heightNew;
    		helper.menuHeight = Math.max(helper.menuHeight, hTotal);
    		i += 1;    		
    	});
    	
    	return eOverflow;
    }
    
    
    function drawColumns(element, additionalLines) {
    	if(!helper.columns) {
    		return false;
    	}
    	
    	var maxHeight = 0;
    	var maxWidth = 0;
    	
    	$.each(helper.columns, function(index, value) {
        	helper.inner.append( $('<ul></ul>', {
    			css: {'width': helper.settings.columnWidth }
    		}));        	
    		$.each(value, function(i_index, i_value) {
    			//console.log('new link ' + i_index);
    			$(i_value).clone().appendTo( $(' ul:last', helper.inner) ).fadeIn();
    		});    		
    		//maxHeight = Math.max(maxHeight, $('ul:last', helper.inner).height(), helper.settings.columnHeight );
    	});
    	maxWidth = Math.max(maxWidth, ($('ul', helper.inner).length * helper.settings.columnWidth) );
    	//changeHeight(helper.settings.columnHeight + (additionalLines * helper.settings.heightInterval) );
    	changeHeight( helper.menuHeight );
    	changeWidth(maxWidth);
    }
    
    function moveBox(left) {
    	helper.parent.css({'left': left});
    }
    
    function changeHeight(height) {
    	helper.inner.css('height',height);
    	$(current).data('boxHeight', height);
    }
    
    function changeWidth(width) {
    	helper.inner.animate({'width':width}, 100);
    }
    
    function getBoxOffset() {
    	//offset is relative to the starting point
    	var offset = $(helper.parent).position();
    	return (offset.left + helper.settings.offsetLeft);
    }    
    
    function addColumn() {
    	if(!helper.inner) {
    		return false;
    	}
    	helper.columns.push(
    		[]
		);    	
    }
    
    
    function reset() {
    	if(!helper.parent) {
    		return false;
    	}
    	helper.columns = [];
    	$('ul', helper.parent ).remove();
    }
    
})(jQuery);











function initSideMenu($) {

	
    //setup - all values in pixels
    var navWidth = 180;
    var ulIndent = 15;
    //end setup

    var pathname = window.location.pathname;

   /* $('#nav-sidebox-new').css('width', navWidth + 'px');
    $('#nav-sidebox-new ul').css('width', navWidth + 'px');
    $('#nav-sidebox-new ul').css('margin-left', ulIndent + 'px'); 

    $('#nav-sidebox-new a').each(function() {
        var level = $(this).parents('ul').length;
        var liWidth = navWidth - (ulIndent * level) + 30;
        $(this).parent('li').css('width', liWidth + 'px');
    }); */
	
	
	var NavImgOffClosed = "http://www.boatdriver.ch/skin/frontend/default/f003/mlamenu/images/NavImgOffClosed.png";
    var NavImgOnClosed  = "http://www.boatdriver.ch/skin/frontend/default/f003/mlamenu/images/NavImgOnClosed.png";
    var NavImgOnOpen    = "http://www.boatdriver.ch/skin/frontend/default/f003/mlamenu/images/NavImgOnOpen.png";
	

    //prepend expand/collapse icons
    $('#nav-sidebox-new li.level0 ul li').each(function() {
        if($(this).children('ul').length > 0) {
			if ($(this).children('ul').is(":visible")) {
                $(this).prepend('<img src="'+NavImgOnOpen+'" />');
            } else {
                $(this).prepend('<img src="'+NavImgOffClosed+'" />'); //  NavImgOnClosed
            }
        }
    });

    //Required Section
    var slideSpeed = 'slow'; // 'slow', 'normal', 'fast', or miliseconds 
    $('#nav-sidebox-new a').each(function() {
        var thisHref = $(this).attr('href')
        if ((window.location.pathname.indexOf(thisHref) == 0) || (window.location.pathname.indexOf('/' + thisHref) == 0)) {
            $(this).addClass('Current');
        }
    });
    
    $('.Current').parent('li').children('ul').show();
    $('.Current').parents('ul').show();

    //prepend expand/collapse icons
    $('#nav-sidebox-new li.level0 ul li').each(function() {
        if ($(this).children('ul').length > 0) {
            if ($(this).children('ul').is(":visible")) {
                $(this).children('img').attr('src', NavImgOnOpen);
            }
			// unter-unter navigatino hat ein anderes bild
			else if($(this).hasClass('level1') == false  && $(this).children('ul').html() != null) {
				$(this).children('img').attr('src', NavImgOnClosed);
			}
        }
    });
    
    $('#nav-sidebox-new img').click(function() {
    
        if ($(this).parent('li').children('ul').html() != null) {
			//console.log('click');
            $(this).parent('li').parent('ul').children('li').children('ul').hide(slideSpeed);
			// alle auf onClosed setzen
           //$(this).parent('li').parent('ul').children('li').children('img').attr('src', NavImgOnClosed);
            //console.log($(this).parent('li').parent('ul').children('li').children('img'));
			// die obersten auf offClosed setzen //narf
			$('#nav-sidebox-new').children('li').children('ul').children('li').children('img').attr('src', NavImgOffClosed); // , NavImgOnClosed
			// das oberste angewÃ¤hlte auf onOpen setzen
			if($(this).parent('li').parent('ul').parent('li').hasClass('level1')) {
				$(this).parent('li').parent('ul').parent('li').children('img').attr('src', NavImgOnOpen);
			} else if($(this).parent('li').parent('ul').parent('li').parent('ul').parent('li').hasClass('level1')) {
				$(this).parent('li').parent('ul').parent('li').parent('ul').parent('li').children('img').attr('src', NavImgOnOpen);
			}
		
            $(this).delay(100).is(':hidden');
            
          //  console.log($(this).parent('li').children('ul').css('display'));
            if ($(this).parent('li').children('ul').css('display') == "block") {
                $(this).parent('li').children('ul').hide(slideSpeed);
                if($(this).parent('li').children('ul').html() != null) {
					$(this).attr('src', NavImgOnClosed);
				} 
				if($(this).parent('li').hasClass('level1')) {
					$(this).attr('src', NavImgOffClosed); // NavImgOffClosed, NavImgOnClosed
				}
				$(this).siblings('a').removeClass('active');
								
				//console.log($(this));
            } else {
            
				//alert($(this).parent().siblings().find('a.active').siblings('ul').css('display'));
				//console.log($(this).parent().find('a.active'));
				if ($(this).parent().siblings().find('a.active').siblings('ul').css('display')=='block') {
					$(this).parent().siblings().find('a.active').siblings('ul').hide(slideSpeed);   
					
					if($(this).parent().siblings().find('a.active').siblings('ul').html() != null) {
						$(this).parent().siblings('.level1').children('a.active').siblings('img').attr('src', NavImgOffClosed);
						$(this).parent('li').parent('ul').children('li').children('a.active').siblings('img').attr('src', NavImgOnClosed);
						$(this).parent('li').parent('ul').parent('li').parent('ul').children('li').children('ul').children('li').children('a.active').siblings('img').attr('src', NavImgOnClosed);
					}                   
				}
				   
               
               $(this).parent().siblings().find('a.active').removeClass('active');
               
               $(this).parent('li').children('ul').show(slideSpeed);
               $(this).attr('src', NavImgOnOpen);
               
				$(this).siblings('a').addClass('active');
				//console.log('addClass');
            }
            return false;
        }

    });

    $('#nav-sidebox-new li').click(function() {
		if ($(this).children('a').length == 0) {
            if ($(this).children('ul').html() != null) {
                $(this).parent('ul').children('li').children('ul').hide(slideSpeed);
                if ($(this).children('ul').css('display') == "block") {
                    $(this).children('ul').hide(slideSpeed);
                } else {
                    $(this).children('ul').show(slideSpeed);
                }
            }
        }
    });
    //End Required Section
    
    //Optional Section - Show Carrots
    var imgOffClosed = "url(images/NavImgOffClosed.png) no-repeat 5px ";
    var imgOnClosed = "url(images/NavImgOnClosed.png) no-repeat 5px ";
    var imgOnOpen = "url(images/NavImgOnOpen.png) no-repeat 5px ";
    var charBeforeLB = 23; //characters before line break - you must calculate this - based on font-size and LI width;
    var paddingBig = 12; //push carrot arrow down (in pixels) when no there is a line break in the LI
    var paddingSmall = 8;  //push carrot arrow down (in pixels) when no there is no line break in the LI
    var maxLIHeight = 50; // max height of LI when list is closed

    $('#nav-sidebox-new > li').each(function() {
		
        var childText = $(this).children('a').text();
        var topPadding = paddingBig;
        if (childText.length < charBeforeLB) { topPadding = paddingSmall; }
        if ($(this).height() < maxLIHeight) { //list is closed
            if ($(this).children('a').attr('class') == "Current") {
                $(this).parent('li').children('img').attr('src', NavImgOnOpen);
            } else {
                $(this).parent('li').children('img').attr('src', NavImgOffClosed); // , NavImgOnClosed
            }
        }
        
        else {// list is open
            $(this).children('img').attr('src', NavImgOnOpen);
            //$(this)
        }
    });
    
    //Initiate active Items
    
      //console.log($('#nav-sidebox-new a.active'));
    
      $('#nav-sidebox-new a.active').each(function(){
         $(this).siblings('ul').css('display','block');
         $(this).siblings('img').attr('src', NavImgOnOpen);         
      });
	  
	  
	  // hover-state
      $('#nav-sidebox-new a').hover(
		function(){ 
			if(!($(this).hasClass('active')) && $(this).parent('li').hasClass('level1')) {
				$(this).parent('li').children('img').attr('src', NavImgOnClosed);
			}
		},
		function() {
			if(!($(this).hasClass('active')) && $(this).parent('li').hasClass('level1')) {
	  			$(this).parent('li').children('img').attr('src', NavImgOffClosed);
			}
	  });
    
    
    //End Optional Section
}
