$(document).ready(function(){	
	
	/* Manually apply classes to rows in 'tworows' and 'threerows' table elements */
	
	$('.tworows tbody tr:odd').addClass('tr-odd');
	$('.threerows tbody tr:odd').addClass('tr-odd');
	
	// make sure to display the small under menu borders if no submenu is visible
	if ($('ul.subNav').length > 0) {}
	else {$('#subNavBackground').addClass('empty');}
	
	/* Generate a decent pagebrowser for the Abenteuer des Alltags */
	
	$('.tx-ttnews-browsebox .bottom_page_navigation td:first').width(100);	
	var check1 = $('.tx-ttnews-browsebox .bottom_page_navigation td:last').text();	
	if (check1 != 'weiter') {
		$('.tx-ttnews-browsebox .bottom_page_navigation td:last').after('<td>weiter</td>')	
	}
	
	
	$('.tx-ttnews-browsebox .bottom_page_navigation td:not(:first):not(:last)').wrapAll("<td align='center' style='text-align: center'><table class='pageNavTable' cellpadding='0' cellspacing='0' align='center'><tr></tr></table></td>");
	$('.tx-ttnews-browsebox .bottom_page_navigation .pageNavTable td:not(:last)').addClass("pagenav_td").css("border-right","1px solid #c6dcf9");
	$('.tx-ttnews-browsebox .bottom_page_navigation .pageNavTable td:last').addClass("pagenav_td_last");
	$('.tx-ttnews-browsebox .bottom_page_navigation td:last').width(100).css("text-align","right");
	
	var check2 = $('.tx-ttnews-browsebox .bottom_page_navigation td:last').text();	
	if (check2 > 0) {
		//$('.tx-ttnews-browsebox #bottom_page_navigation td:last').text('weiter');
	}
	
	/* Generate a decent pagebrowser for the Calendar Events */
	
	$('.calListNext').each(function (i) {
	
		var content = $(this).html();				
		if (content.length == 11) {
			$(this).html("<span>weiter</span>");
		}
	});
	
	$('.calListPrev').each(function (i) {
	
		var content = $(this).html();				
		if (content.length == 11) {
			$(this).html("<span>zurück</span>");
		}
	});	
	
	
	/*
	
	$('.tx-ttnews-browsebox #bottom_page_navigation').each(function() {
	
		var tt_news_offset2 = 330;
	
		var tt_news_offset = tt_news_offset2-($('.tx-ttnews-browsebox #bottom_page_navigation .bottom_page_item:last').offset().left);	
		$('.tx-ttnews-browsebox #bottom_page_navigation .bottom_page_item_last:first').css("margin-left",tt_news_offset).css("margin-right",0).css("padding-right",0).css("padding-left",0).css("text-align","right").width(100);	
	
	});
	
	*/

});

Rvlt = (typeof(Rvlt)=="undefined"?{}:Rvlt); //Namespace Revelate

/**
 * To attach to window.onload
 */
Rvlt.init = function () {
	Rvlt.BuildMenu('serviceNav', 'serviceNavLayerSrc');
	
	if( $('#caSubNav').length ) {
		Rvlt.BuildMenu('caSubNav', 'subNavLayerSrc');
	}
}

/**
 * @param   MainNavID      	id of the Div which contains the top nav
 * @param   NavLayerSrcID   id of the Div which contains the list of drop downs
 * @param   IsImageNav [optional Bool]  Is the top level image based
 */
Rvlt.BuildMenu = function (MainNavID, NavLayerSrcID, IsImageNav) {
	//Get the top nav objects
	var MenuObj = document.getElementById(MainNavID);
	var TopList = MenuObj.getElementsByTagName('li');
	var SrcListItem = document.getElementById(NavLayerSrcID).getElementsByTagName('li')[0];
	var i = 0;	
	
	//Build the popup layers
	for (var i=0;i<TopList.length;i++){
		TopList[i].ParentItem = MenuObj;
		if (SrcListItem != null) {			
			if (SrcListItem.getElementsByTagName("ul").length > 0) {
				TopList[i].SubNav = BuildLayer(SrcListItem, TopList[i], "horizontal", 1); 
			}
			SrcListItem = Rvlt.Utils.FindNextSiblingByTagName(SrcListItem, 'li');
		} 
	}
	
	//Now everything is in place, Activate the top nav
	MenuObj.onmouseover = MouseOverListener;
	MenuObj.onmouseout = MouseOutListener;
	
	function BuildLayer (ParentListItem, AttachTo, Tile, Level) { //horizontal tile --> will display under the listitem. Otherwise next to it.
		Tile = Tile || "vertical";
		AttachTo = AttachTo || ParentListItem;
		var theDiv = document.createElement('div');
		var theListItem = ParentListItem.getElementsByTagName('li')[0];

		while (theListItem != null) {
			if (theListItem.getElementsByTagName("ul").length > 0) { //Has sub nav
				theListItem.SubNav = BuildLayer (theListItem, null, null, Level + 1); 	
				theListItem.className = "WithSubNav";
			}
			theListItem.ParentItem = theDiv;
			theListItem = Rvlt.Utils.FindNextSiblingByTagName(theListItem, 'li');
		}

		theDiv.appendChild(ParentListItem.getElementsByTagName('ul')[0]); //Move the list into a seperate div
		theDiv.className = "NavLayer VerticalNav Level" + Level;
		theDiv.ParentItem = AttachTo;
		theDiv.onmouseover = MouseOverListener;
		theDiv.onmouseout = MouseOutListener;
		theDiv.Tile = Tile;
		document.body.appendChild(theDiv);
		
		return theDiv;
	}
	
	function toggleActive (ListItem, direction) { 
		var theImg = null;
		if (IsImageNav) {
			theImg = Rvlt.Utils.FindElementByTagName(ListItem, 'img', 'children'); 
		}
		if (direction == 'on') {
			if (theImg != null && theImg.IsActive != true) {
				theImg.Inactive = theImg.src;
				theImg.IsActive = true;
				theImg.src = window[theImg.name + "_h"].src;
			}
			Rvlt.Utils.AddCssClass(ListItem, 'over');
		}
		else {
			if (theImg != null) {
				theImg.IsActive  = false;
				theImg.src = theImg.Inactive;
			}
			Rvlt.Utils.RemoveCssClass(ListItem, 'over');
		}
	}
	
	function MouseOverListener(e) {
		var el = Rvlt.Utils.FindElementByTagName(Rvlt.Utils.GetEventTarget(e), 'li', 'parent');
		if (el != null) { 					//target contained in a list item
			Rollover(el);
		} 
		else if (this.ParentItem != null) { //'this.' refers to the owner of the event handler, i.e. the div layer
			Rollover (this.ParentItem); 	//keep the parent list item selected
		} 
	}
	
	function MouseOutListener (e){
		var el = Rvlt.Utils.FindElementByTagName(Rvlt.Utils.GetEventTarget(e), 'li', 'parent') || this.ParentItem; //'this.' = the div layer
		while (el != null) { 					
			el.RollOutTimer = window.setTimeout(Rollout(el), 200); 
			el = el.ParentItem;		//Also rollout the parents. If they are subsequently rolled over, they will be kept alive.
		}  
	}
	
	function Rollover (el) { //We only really need to rollover the li's, but we also do the div's to follow the lineage (li's are children of divs who are children of li's)
		var LeftPos = AbsoluteOffset(el, "Left");
		var TopPos =  AbsoluteOffset(el, "Top");		
		
		// 	var winWidth = window.innerWidth || document.documentElement.clientWidth - 15; //the -15 is to account for scrollbars
				
		// 	width of window set to fixed value due to display problems		
		var winWidth = 800;
		
		var winHeight = window.innerHeight || document.documentElement.clientHeight;
		if (el.ParentItem != null && el.ParentItem.CurrentActive != null && el.ParentItem.CurrentActive != el) {
			Rollout(el.ParentItem.CurrentActive)(); 					//Hide the currently visible menu immediately
		}
		ClearTimer (el); 
		if (el.tagName.toLowerCase() == 'li') toggleActive(el, 'on'); 	//show active state
		if (el.SubNav != null) { 										//show child
			/*
				POSITIONING: 
				Some effort is made so that menu items do not end up off the screens, but
				some edge cases are not covered. For example a hypothetical third level would not know
				that it's parent is to the left of it's parent, so it would go right and cover it's grandad.
				A way to work around this would be to add a DisplayedRight property to the parent.
			*/			
				
			
			if (el.SubNav.Tile == 'horizontal') { 									//'Horizontal' --> displays under the item				

				if (LeftPos + el.SubNav.offsetWidth > winWidth) {					//Falls out of window
					LeftPos = LeftPos - el.SubNav.offsetWidth + el.offsetWidth; 	// --> Align with right edge of item							
				}
				el.SubNav.style.top = TopPos + el.offsetHeight + 1 + "px";
				el.SubNav.style.left = LeftPos + "px";		
				
				
			}
			else {																	//'Vertical' --> displays next to the item
				LeftPos = LeftPos + el.offsetWidth + 1;				
				if (LeftPos + el.SubNav.offsetWidth > winWidth) { 					//Falls out of window
					LeftPos = LeftPos - el.offsetWidth - el.SubNav.offsetWidth - 2; //-- > display to the left of the item
				} 
				if (TopPos + el.SubNav.offsetHeight > winHeight){
					TopPos = winHeight - el.SubNav.offsetHeight;
				}
				el.SubNav.style.top = TopPos + "px";
				el.SubNav.style.left = LeftPos + "px";
			}
			el.SubNav.style.display = 'block';
		}
		if (el.ParentItem != null) {
			el.ParentItem.CurrentActive = el;
			Rollover (el.ParentItem); //Keep parents active
		}
	}
	
	function Rollout (el){
		return function () { //we return a function so it can be used on SetTimeout. To execute direct, call with (), so Rollout(el)();
			ClearTimer (el);
			if (el.tagName.toLowerCase() == 'li') toggleActive(el, 'off');
			if (el.CurrentActive != null) {
				Rollout(el.CurrentActive)();
			}
			if (el.SubNav != null) {
				el.SubNav.style.display = 'none';
			}
			if (el.ParentItem != null && el.ParentItem.CurrentActive == el) {
				el.ParentItem.CurrentActive = null;
			}
		}
	}
	
	function ClearTimer (el) {
		if (el.RollOutTimer != null) {
			window.clearTimeout(el.RollOutTimer);
			el.RollOutTimer = null;
		}
	}
	
	function AbsoluteOffset (el, which) { // Returns position from edge of screen. @param 'which' accepts 'Top' or 'Left' (case sensitive)		
		return el.offsetParent ? el['offset' + which] + AbsoluteOffset(el.offsetParent, which) : el['offset' + which];
	}
}

Rvlt.Utils = {}

/**
 * Returns a single node, or the node itself if it has the tag name. 
 * If more than one child with that name is present, returns null.
 * Useful for: Event delegation
 * @param   el      		DOM object to to start with
 * @param   tagName         Name of tag to search for. Lowercase.
 * @param   searchFor       Accepts "parent" or "child"
 */
Rvlt.Utils.FindElementByTagName = function (el, tagName, searchFor) { //
	var ChildElements;
	if (el.tagName.toLowerCase() == tagName) {
		return el;
	}
	if (searchFor == "parent") {
		while (el != null && el.tagName.toLowerCase() != tagName) {
			el = el.parentNode.tagName != null ? el.parentNode : null;
		}
		return el;
	}
	else {
		ChildElements = el.getElementsByTagName(tagName);
		return ChildElements.length == 1 ? ChildElements[0] : null;
	}
}

/**
 * Finds next sibling of a particular tag
 * @param   el      		DOM object to to start with
 * @param   tagName         Name of tag to search for. Lowercase.
 */
Rvlt.Utils.FindNextSiblingByTagName = function (el, tagName) { //
	while (el.nextSibling != null) {
		if (el.nextSibling.tagName !=null && el.nextSibling.tagName.toLowerCase() == tagName) {
			return el.nextSibling;
		}
		else {
			el = el.nextSibling;
		}
	}
	return null;
}

/**
 * @param   e      			DOM Event
 */
Rvlt.Utils.GetEventTarget = function (e) { //Cross browser malarkey
	e = e || window.event;
	return e.target || e.srcElement;
}

/**
 * The "raison d'etre" of these functions is that an object can have
 * several classes seperated by a space in the className 
 * @param   el      		DOM element to add class to
 * @param   theClass        Class to be added (string)
 */
Rvlt.Utils.AddCssClass = function (el, theClass){
	el.className = el.className.indexOf(theClass) > -1 ? el.className : (el.className ? el.className + ' ' : '') + theClass;
}

/**
 * @param   el      		DOM element to add class to
 * @param   theClass        Class to be removed (string)
 */
Rvlt.Utils.RemoveCssClass = function (el, theClass){
	var classArray = el.className.split(' ');
	var classString = "";
	for (var i=0;i<classArray.length-1;i++) {
		if (classArray[i] != theClass) classString += classArray[i] + ' ';
	}
	el.className  = classString.substr(0, classString.length -1);
}





