$(document).ready(   
   function() {   
       NavigationHandler.loadLeftNavigation();       
   }
)

/*
 * @autor   hp
 * @summary NavigationHandler manage Left Navigation behaviour.
 * @equired jquery.core, jquery.cookie
 */
NavigationHandler = {	
	timer : false,	
	eventActivated : false,
	mouseCoordinate : { x: null, y: null },
	previewFileName : "vorschau.php",
	leftNaviPath : ( ( location.hostname.indexOf( "www" ) == 0 ) || ( location.hostname.indexOf( "test" ) == 0 ) ) ? config.navipath + "navi.html" : config.navipath + "/navi_staging.html",

    /* 
     * @summary Activate mouseover, mouseleave and click event for left navigation.
     */
    activate : function(){  
        $(document).mousemove(function(e){				
		    if(NavigationHandler.eventActivated == false) {
				var myX = e.pageX;
				var myY = e.pageY;				
				if(NavigationHandler.mouseCoordinate.x != null) {
					if(NavigationHandler.mouseCoordinate.x != myX || NavigationHandler.mouseCoordinate.y != myY) {						
						$('.left-nav-teaser ul li a').mouseover(function(){             				
							NavigationHandler.open($(this));
						});
						NavigationHandler.eventActivated = true;
					}
				} else {
					NavigationHandler.mouseCoordinate.x = e.pageX;
					NavigationHandler.mouseCoordinate.y = e.pageY;
				}
			}
	    });	
                
		$('.left-nav-teaser').mouseover(function(){		    
			window.clearTimeout(this.timer);			
        });		
        $('.left-nav-teaser').mouseleave(function(){			
			this.timer = window.setTimeout('NavigationHandler.close()', 3000);			
        });					
    },
	/*
     * summary	Load left navigation file and write it in to the page.
     */	
    loadLeftNavigation : function(){
		$.ajax({		    
			url: NavigationHandler.leftNaviPath,
			type: "POST",
			data: "path_self="+window.location.pathname,
			success: function(data) {			    
				$(".page .left-nav").html(data);
				NavigationHandler.activate();
				NavigationHandler.setBreadcrumb($('.left-nav-teaser ul:first'));		   
			},
			error: function(event){
			    //console.log("error");				
			}
		});
    },	
    /*
     * @param element LI Element
     * @return  UL Element or null
     * @summary Check UL Element for cssClass(=preview). If true (in this case there are no sub-navigation lists), return the UL Object, else null.
     */
    _getSubLevel : function(element){
        var el = (!$(element).children('ul').hasClass('preview')) ? $(element).children('ul') : null;
        return el;
    },
	/*
	 * @summary Returns url without domain and http.
	 */
    _getUrl : function(){
		var url = window.location.href.split("//")[1];		
		var url  = url.substring(url.indexOf("/"), url.lastIndexOf("/"))+"/";	
		
		return url;
	},	
	/*
	 * @summary Build visitedLevels string according to url. Return visited levels string, similiar to cookie visitedLevels value.
	 */
	_buildBreadcrumbFromUrl : function(){				
		var visitedLevelList = null;
		var el = null;	
		var url = this._getUrl();		
		if($(".sub-hover-teaser li a[href=" + url + "]").length > 0){
			el = $(".sub-hover-teaser li a[href=" + url + "]");
		}else if($(".sub-hover-teaser li a[href=" + url.substring(0, url.length-1) + "]").length > 0){
			el = $(".sub-hover-teaser li a[href=" + url.substring(0, url.length-1) + "]");	
		}else if($(".sub-hover-teaser li a[href=" + url + "index.php" + "]").length > 0){			
			el = $(".sub-hover-teaser li a[href=" + url + "index.php" + "]");
		}else if($(".sub-hover-teaser li a[href=" + window.location.protocol + "//" + window.location.host + url + "]").length > 0){			
			el = $(".sub-hover-teaser li a[href=" + window.location.protocol + "//" + window.location.host + url + "]");			
		}else{
			//console.log("link wurde nicht gefunden");			
		}	
		
		if(el != null && el.length > 0){
			el = $(el).parent("li");		
			visitedLevelList = this._getBreadcrumb($(el)).split("#");
		}
		
		return visitedLevelList;		
	},
    /*
     * @param element UL Element
     * @summary Open Sub UL Elements as breadcrumb width ancor highlighting.
     */
    setBreadcrumb : function(element){ 		
        var visitedLevelList = this._buildBreadcrumbFromUrl();		
        if(visitedLevelList != null){
            for(var i=0; i < visitedLevelList.length; i++){				
                var index = parseInt(visitedLevelList[i]);
                var visitedElement = element.children('li').get(index);
                this._deaktivateHover(visitedElement);				
                $(visitedElement).children('a').addClass('visited');				
                if(i == (visitedLevelList.length - 1) && $(visitedElement).children('ul.preview').size() == 1){                    
                    $(visitedElement).find('a.visited img').hide();
					$(visitedElement).find('a.visited').css("backgroundImage", "none");
                }
                if(i > 0){
                   $(visitedElement).css('padding-bottom', '0'); 
				   $(visitedElement).css('margin-top', '10px'); 
                }     			    
                element = this._getSubLevel(visitedElement);				
                if(element != null){
                    $(element).addClass('visited-teaser');
                    (this._handleNonSelectedElements(element, i, visitedLevelList)) ? $(element).hide() : $(element).show();                    
                }
            }			
        }
    },    	
     /*
     * @param element   LI Element
     * @param index     Index of LI Element
     * @return          Hash separated indexes of selected LI elements
     * @summary         Serach recursive for selected parent LI elements.
     */
    _getBreadcrumb : function(element, index){ 
        var parent = $(element).parents('ul');
        var _index = parent.children('li').index(element);
        if(_index > -1){
            _index = (index != undefined) ? String(index) + String(_index) + '#': String(_index) + '#';
            return this._getBreadcrumb($(parent).parents('li'), _index);
        }else{
            index = index.substring(0, index.lastIndexOf('#')).split('#').reverse().join('#');
            return index;
        }

    },
    /*
     * @param visitedElement   LI Element
     * @summary                Unbind mouseover event (Need for opened breadcrumb ancor element).
     */
    _deaktivateHover : function(visitedElement){
        if($(visitedElement).children('ul').hasClass('preview')){
            $(visitedElement).children('a').unbind('mouseover');
        }
    },
    /*
     * @param top   Top position
     * @param left  Left Position
     * @param height    Height
     * @param isPreview type Boolean, optional
     * @summary Create DIV Element and add the given parameters to Css attribute. Parameter "isPreview" distinguish among LI Pagelink and LI Preview Image.
     */
   _getLayer : function(top, left, height, isPreview){
        var layer = document.createElement('div');
        layer.className = (isPreview) ? 'sub-hover-layer  hover-preview' : 'sub-hover-layer';

		var headerHeight = $( '.navi-header' ).height();
		headerHeight = ( headerHeight > 16 ) ? ( headerHeight - 16 ) : 0;
		layer.style.height = ( 240 - headerHeight ) + 'px';
        layer.style.left = left + 'px';
        layer.style.top = '0px';
        layer.style.paddingTop = top + 'px';

        return layer;
    },
    /*
     * @param parent    UL Element
     * @return  Array with top and left position.
     */
    _getPosition : function(parent){
        var top = $('.left-nav-teaser .sub-hover-teaser').position().top;        
        var left = ($(parent).hasClass('visited-teaser') && !$(parent).hasClass('sub-hover-teaser')) ? $('.left-nav-teaser').width() : $(parent).width();
        return { top : top, left : left};
    },
    /*
     * @param element    UL Element
     * @return  Height, type number.
     */
    _getHeight : function(element){
        var top = $('.left-nav').position().top;
        var height = 0;
        if($('.left-nav-teaser').innerHeight() > element.innerHeight()){
            height = $('.left-nav-teaser').innerHeight() - top;
        }else{
            height = element.innerHeight() - top;
        }
        return height;
    },
	/*
	 * @param element	UL Element
	 * @url	  preview file
	 * @callback	callback 
	 */
	loadAjaxPreview : function(element, url, callback){	    
		var child = element.find('li');			        
		if($(child).children().size() == 0){			
			$.ajax({
				  url: url + NavigationHandler.previewFileName,
				  success: function(data) {	                    				 
					$(child).append(data);
					var image = $(child).find("img");
					if(image){
						image.load( function(){							
							if(typeof callback === "function"){
								callback();
							}
						});						
					}else{
						if(typeof callback === "function"){
							callback();
						}	
					}							
				  }
			});			
		}else{
			if(typeof callback === "function"){
				callback();
			}
		}		
	},	    
    /*
     * @param e    Ancor Element
     * @summary Show UL Child Element with DIV layer in the background.<br/>Position this to the right of Parent UL Element.
     */
    open : function(e){
        var parent = e.parent('li').parent('ul');
        var child = e.parent('li').children('ul:first');
        
        this.close(parent);
        e.addClass('active');
        if(child){            
            var height = this._getHeight(child);
            var position = this._getPosition(parent);
            var isPreview = false;
            if(child.hasClass('preview')){       				
                isPreview = true;                         
				child.css('padding-top', '26px').addClass('hover-preview');				
				child.css('height', '270px');				
				this.loadAjaxPreview(child, e.attr('href'), function(){	  				    
					NavigationHandler.close(parent);	
					e.addClass('active');
					child.before(NavigationHandler._getLayer(position.top, position.left, height, isPreview));			
					child.addClass('sub-hover-teaser').css('left', position.left + 'px').css('top', '0px').show();
					child.find('img').show(); /* IE Workaround */					
				});	 				
            }else{				
				child.css('padding-top', position.top + 'px');							
				child.css('height', height + 'px');
				child.before(this._getLayer(position.top, position.left, height, isPreview));			
				child.addClass('sub-hover-teaser').css('left', position.left + 'px').css('top', '0px').show();
				child.find('img').show(); /* IE Workaround */
			}			

		}
    },
    /*
     * @param parent    UL Element
     * @summary Close All opened UL Child Elements.
     * @deviation When "visited-teaser" element was selected, then close all childs of first level.
     */
    close : function(parent){		
        var e = (parent) ? parent : $('.sub-hover-teaser');		
        //@deviation
        if(e.hasClass("visited-teaser")){
           this._close(parent);           
        }        
        e.find('li a').removeClass('active');
        e.find('li ul.sub-hover-teaser img').hide(); /* IE Workaround */
        e.find('li ul.sub-hover-teaser').hide();
        e.find('li ul').removeClass('sub-hover-teaser');
        e.find('li div').remove();

    },
    /*
     * @param e UL Element
     * @summary Close all opened mouseover teaser in the visited breadcrumb.
     * This is because there are two list elements,
     * one of them is a clone of the UL element and is needed to show the mouseover teaser.
     * While the first UL element show the visited breadcrumb navigation-links.
     */
    _close : function(element){        
        $(element).addClass('justSelected');
        var e = $('.sub-hover-teaser:visible');
        $(e).each(function (i) {            
            if(i > 0 && !$(this).hasClass('justSelected')){                
                $(this).prev('div').remove();                
                $(this).hide();
            }
        });
        $(element).removeClass('justSelected');        
    },
    /*
     * @param element LI Element
     */
    _hideElements : function(element){
        if(element){            
            $(element).hide();            
        }
    },
    /*
     * @param element   UL
     * @param visitedLevelList Array, which contains visited LI indexes.
     * @param listIndex Current (array) index.
     * @return LI Elements, Handle LI Elements contained in UL "visited-teaser" Element, but not "visited".
     */
    _handleNonSelectedElements : function(element, listIndex, visitedLevelList){        
        var nextIndex = -1;
        if(visitedLevelList){
            nextIndex = ((listIndex + 1) < (visitedLevelList.length)) ? visitedLevelList[listIndex + 1] : -1;
        }else{
            nextIndex = listIndex;
        }        
        var elements = null;
        var hasChildElements = false;
        if(nextIndex > -1){
            elements = $(element).children('li:not(:eq(' + nextIndex + '))');            
            this._hideElements(elements);
            this._addClone(element, nextIndex);
        }else if(element.children('li').size() >= 1){            
            hasChildElements = true;            
        }
        
        return hasChildElements;
    },
    /*
     * @param element LI Elements
     * @param index Index of visited LI Element
     * @return UL Element
     * @summary Returns UL Element filled with LI Elements.
     *
     */
    _createClone : function(element, index){
        var list = $('<ul class="listClone" style="display:none"></ul>').append(element.clone(true));
        $(list).children('li:hidden').show();
        
        return list;
    },
    /*
     * @param element   UL Element
     * @param index Index of visited LI Element
     */
    _addClone : function(element, index){
        if(element){
            var clone = this._createClone($(element).children('li'), index);
            $(element).before(clone);
        }
    }
}
