﻿
var hoverFlag	= false;	

function FuncSetAsHomepage(link, ref){
			// extra function was neccessary for Gewinnspiel Links in Articles added by the editor
				var element = link
				var ff = /Firefox/;
				var op = /Opera/;
				var ns = /Netscape/;
		
				if ( !(ff.exec(navigator.userAgent)) && !(op.exec(navigator.userAgent)) && !(ns.exec(navigator.userAgent)) ) 
				{
					element.style.behavior='url(#default#Homepage)';
					element.setHomepage('http://www.' + MainNavigationCommon.strPortalDomain );
					element.href=ref ;
				}
			}

function PortalUser(strUserName, strPasswordHash, strFullName) {
	//properties
	this.strUserName 		= null;
	this.strPasswordHash 	= null;
	this.strFullName 		= null;
		
	//set given values
	if (strUserName 	&& strUserName != "") 		this.strUserName 		= strUserName;
	if (strPasswordHash && strPasswordHash != "") 	this.strPasswordHash 	= strPasswordHash;
	if (strFullName 	&& strFullName != "")		this.strFullName 		= strFullName;
	
}

function MainNavigationBar () {
	//properties
	this.ULNavigation 				= null;
	this.strActiveNodeID1			= null;
	this.strActiveNodeID2			= null;
	
	this.User						= null;
		
	this.strRegisterUrl				= MainNavigationCommon.strRegisterUrl;
	this.strLoginUrl				= MainNavigationCommon.strLoginUrl;
	this.strLogoutUrl				= null;
	this.strOverrideLoginUrl		= null; //this is an extra property so we can see if there is an override
		
	this.strFormAction				= null;
	this.strUNameFieldName			= MainNavigationCommon.strUNameFieldName;
	this.strPWFieldName				= MainNavigationCommon.strPWFieldName;
	this.strProfileUrl				= MainNavigationCommon.strProfileUrl;
	this.boolShowLogin = true; //sets wether the login-stuff is visible or not
	//try to fetch user info
	this.User =  this._ReadUserCookie();
}

	//"Private" methods
	
	//internal method for reading cookie 
	MainNavigationBar.prototype._GetCookie = function (name){
		 var i=0;  //Suchposition im Cookie
		 var suche = name+"=";
		 var cook = null;
		 while (i<document.cookie.length){
				if (document.cookie.substring(i, i+suche.length)==suche){
					 var ende = document.cookie.indexOf(";", i+suche.length);
					 ende = (ende>-1) ? ende : document.cookie.length;
					 cook = unescape(document.cookie.substring(i+suche.length, ende));
				}
				i++;
		 }
		
		return cook;
	};
	
	//opens the login form overlay
	MainNavigationBar.prototype._OpenLoginForm = function () {
		//clean up a bit...
		var nodeSSOMessages 	=	document.getElementById("SSOMessages");
		while (nodeSSOMessages.firstChild)
			nodeSSOMessages.removeChild(nodeSSOMessages.firstChild);	
		var formLogin		= document.getElementById("SSOLoginForm");
		var inputUserName	= formLogin["SSOUser"];
		var inputPassword	= formLogin["SSOPassword"];
		//inputUserName.value = MainNavigationCommon.strUNameValue;	
		//inputPassword.value = MainNavigationCommon.strPWValue;	
			
		//slide login form down and up	
		var nodeLoginForm = document.getElementById("SSOLogin");
			if (nodeLoginForm.style.display == "block" ) {
				$("div#SSOLogin").slideUp('slow', function() {
					$("div#SSOLogin").removeClass("CloseLogin");
				});
			} else {
				$("div#SSOLogin").slideDown('slow', function() { 
					$("div#SSOLogin").addClass("CloseLogin");
				}); 
			}
	};
	
	//closes the login form overlay
	MainNavigationBar.prototype._CloseLoginForm = function () {
		var nodeLoginForm = document.getElementById("SSOLogin");
		nodeLoginForm.style.visibility = "hidden";
	};
	
	//reads user info from cookie and returns a PortalUser object
	MainNavigationBar.prototype._ReadUserCookie = function () {
		var NavBar = this;
		var strUserName;
		var strPasswordHash;
		var strFullName;
		var strActive;
		var User = null;
		var SSOCookie = null;
		
		//get the cookie
		try 
		{
				SSOCookie = NavBar._GetCookie("SsoSessionCookie");
				
		}
		catch(e) {
				alert (e.description);
		}
		//if (!SSOCookie) alert("No Cookie...");
		
		if (SSOCookie == null) return null;		
				
		var CookieVals = SSOCookie.split(/\&/);		
				
		for (var i = 0; i < CookieVals.length; i++) {
			var Val = CookieVals[i].split(/\=/);
			//alert("cookie: " + CookieVals[i]);
			
			if (Val[0] == 'username') 			strUserName 	= (""+Val[1]).replace(/ /, "\\20");
			if (strUserName != "guest") {
				if (Val[0] == 'passwordhash') 	strPasswordHash = (""+Val[1]) + "==";
				if (Val[0] == 'active') 		strActive 		= ""+Val[1];
				if (Val[0] == 'fullname')		strFullName		= decodeURI(""+Val[1]).replace(/\+/g,' ');
			}
		}
				
		//alert("Active: " + strActive);
		if (strActive == "True") {
			User = new PortalUser(strUserName, strPasswordHash, strFullName);
		}
		return User;
	}
	
		
	//"Public" methods
	
	//method for setting the active navigation node(s)
	MainNavigationBar.prototype.SetActiveNodes = function(strActiveNodeID1, strActiveNodeID2) {
			this.strActiveNodeID1 = strActiveNodeID1;
			this.strActiveNodeID2 = strActiveNodeID2;
	};
	
	
	//method to authenticate user
	MainNavigationBar.prototype.SSOAuthenticateUser = function(strUserName, strPassword, boolKeepLoggedIn, errorMessageContainer, boolReloadPage, funcSuccessCallback) {
	    var NavBar = this;

	    if (typeof errorMessageContainer != "undefined") {
	        MainNavigationCommon.strErrorMsgContainer = errorMessageContainer;
	    }
	    else {
	        MainNavigationCommon.strErrorMsgContainer = "SSOMessages";
	    }

	    if (typeof boolReloadPage != "undefined") {
	        MainNavigationCommon.boolReloadPage = boolReloadPage;
	    }
	    else {
	        MainNavigationCommon.boolReloadPage = true;
	    }

	    if (typeof funcSuccessCallback != "undefined") {
	        MainNavigationCommon.funcSuccessCallback = funcSuccessCallback;
	    }
	    else {
	        MainNavigationCommon.funcSuccessCallback = function() { };
	    }

	    try {
	        $.get(MainNavigationCommon.strSNPEServicePath + MainNavigationCommon.strSSOWebServiceAuthMethod, { user: strUserName, pass: strPassword, bKeepLoggedIn: boolKeepLoggedIn }, NavBar._SSOAuthenticateUserCallback, "xml");
	    }
	    catch (e) {
	        //alert("Login ist fehlgeschlagen.");  	
	    }

	}
	
	//callback method for authentication webservice (called when the service gave a response)
	MainNavigationBar.prototype._SSOAuthenticateUserCallback = function(xml) {
	    var nodeSSOMessages = document.getElementById(MainNavigationCommon.strErrorMsgContainer);

	    while (nodeSSOMessages.firstChild)
	        nodeSSOMessages.removeChild(nodeSSOMessages.firstChild);

	    if (xml.getElementsByTagName("user")[0]) {
	        //login successfull
	        //alert (xml.getElementsByTagName("user-name")[0].firstChild.data);
	        //refresh the page
	        $("div#SSOLogin").slideUp('slow')

	        if (MainNavigationCommon.boolReloadPage) {
	            location.reload();
	        }

	        MainNavigationCommon.funcSuccessCallback();
	    }
	    else {
	        //login failed

	        nodeSSOMessages.className = "error";
	        nodeSSOMessages.appendChild(document.createTextNode(MainNavigationCommon.strSSOErrorMessage));
	        nodeSSOMessages.style.display = "block";
	    }
	}
	
	MainNavigationBar.prototype.SSOLogoutUser = function() {
		var NavBar = this;
		try {
			$.get(MainNavigationCommon.strSNPEServicePath + MainNavigationCommon.strSSOWebServiceLogoutMethod,{}, NavBar._SSOLogoutUserCallback, "xml");
		} catch(e) {
			alert ("Logout ist fehlgeschlagen.");
		}
	}
	
	MainNavigationBar.prototype._SSOLogoutUserCallback = function (xml) {
			
		if (xml.getElementsByTagName("*")[0].tagName.toLowerCase() == "snpewebservicemessage") {
			//logout successfull
			//refresh the page			
			window.location.href = window.location.href + " ";
			location.reload();
		}
		
		else {
			//logout failed (and now??? )
		}
	}
	
	
	//method to set the SSO state display (user logged-in or not etc..)
	MainNavigationBar.prototype.SetSSOFragment = function () {
		var NavBar				= this;

		//do only if login-stuff should be visible
		if (this.boolShowLogin) {
							
				//check if user is logged in...
				if (this.User) {
					
					$('#SSOLoggedOutFragment').hide();
					$('#SSOLoggedInFragment').show();
					
					// modify the UserIconProfile stuff
						$('#UserIconProfileImage').attr("src", MainNavigationCommon.strAvatarUrl.replace(/###username###/, encodeURI(this.User.strUserName)));
						$('#UserIconProfileLink').attr("href", this.strProfileUrl.replace(/###username###/, encodeURI(this.User.strUserName)));
					
					// modify the UserProfileData stuff
						$('#UserProfileDataName').html((this.User.strFullName != null && this.User.strFullName != '') ? this.User.strFullName : this.User.strUserName);
						$('#UserProfileLink').attr("href", this.strProfileUrl.replace(/###username###/, encodeURI(this.User.strUserName)));

					// set the logout action
						if (this.strLogoutUrl) {
							$('#SSOLogoutLink').attr("href", this.strLogoutUrl);
						} else {
							$('#SSOLogoutLink').click(function() {
									NavBar.SSOLogoutUser(); return false;
								});
						}
						
				} else {
				
					$('#SSOLoggedOutFragment').show();
					$('#SSOLoggedInFragment').hide();


					ssoLoginLink = $("a.SSOLoginLink");
					
					if (this.strOverrideLoginUrl == null) {
						ssoLoginLink.click(function() { NavBar._OpenLoginForm(); return false; });
						ssoLoginLink.attr("href", this.strLoginUrl);
					} else {
						ssoLoginLink.unbind("click");
						ssoLoginLink.attr("href", this.strOverrideLoginUrl);
					}
					
					//only use the formaction if there is one defined via the override method
					// - otherwise we use a onclickevent which tries to login the user via a call
					//	 to the SNPEWebservice.
						var formLogin = document.getElementById("SSOLoginForm");
					
						if (this.strFormAction) {
							formLogin.action = this.strFormAction; 
							formLogin.onsubmit = function () {};
						} else {
							formLogin.onsubmit = function () { NavBar.SSOAuthenticateUser(document.getElementById("SSOUser").value, document.getElementById("SSOPassword").value, document.getElementById("SSOKeepLoggedIn").checked); return false; }; 
						}
					
				}
		}
		//do only if login-stuff should not be visible
		else {
			$('#SSOLoggedOutFragment').hide();
			$('#SSOLoggedInFragment').hide();
				
		}
	};
			
			
	//method: override settings of the navigation bar
	MainNavigationBar.prototype.OverrideSettings = function(strLoginUrl, strLogoutUrl, strRegisterUrl, strFormAction, strUNameFieldName, strPWFieldName, strProfileUrl, boolShowLogin) {
		if (strLoginUrl) 		    this.strOverrideLoginUrl 		= strLoginUrl;
		if (strLogoutUrl) 		    this.strLogoutUrl 				= strLogoutUrl;
		if (strRegisterUrl) 	    this.strRegisterUrl 			= strRegisterUrl;
		if (strFormAction) 		    this.strFormAction				= strFormAction;
		if (strUNameFieldName) 	    this.strUNameFieldName			= strUNameFieldName;
		if (strPWFieldName) 	    this.strPWFieldName				= strPWFieldName;
		if (strProfileUrl) 		    this.strProfileUrl				= strProfileUrl;
		if (boolShowLogin != null)  this.boolShowLogin				= boolShowLogin;
	}
	
	//method: override the user data
	MainNavigationBar.prototype.OverrideUser = function(strUsername, strPasswordHash) {
		if (strUsername) this.User = new PortalUser (strUsername, strPasswordHash);
		else this.User = null;
	}
			
			
	//initialize the navigation
	MainNavigationBar.prototype.Init = function() {

		if (document.domain.indexOf(MainNavigationCommon.strPortalDomain) > 0) document.domain = MainNavigationCommon.strPortalDomain;
		
		this.ULNavigation = $("ul[id='MainNavigationBar']");
		
		var thisNavigationBar = this;
		
		//set active Nodes
		var element = this.ULNavigation.find("li[id =" + this.strActiveNodeID1 + "]")
		var subelement = this.ULNavigation.find("li[id =" + this.strActiveNodeID1 + "]").find("li[id =" + this.strActiveNodeID2 + "]")
		if (element && this.strActiveNodeID1) {
			var ActiveNode1 = element;
		} else {
			var ActiveNode1 = this.ULNavigation.find("li[id = MNB1Home]");
		}
		if (subelement && this.strActiveNodeID2) {
			var ActiveNode2 = subelement;
		} else {
			var ActiveNode2 = this.ULNavigation.find("li[id = '']");
		}	
		
		ActiveNode1.addClass("Selected Active");
		ActiveNode2.addClass("Selected2 Active");
		
		this.SetSSOFragment();
	}
	
	function fallto(id) {
		if (hoverFlag == false || $(".Hovered").attr("id")!= id ) return;
		$("ul[id='MainNavigationBar']").find("li.Selected").toggleClass("Selected");
					$(".Hovered").toggleClass("Selected");
					$("ul[id='MainNavigationBar']").find("li.VertAndSel").toggleClass("VertAndSel");
					if ($(".Hovered").is(".Vertical"))
					{
						$(".Hovered").toggleClass("VertAndSel");
					};
	}
	
	// to let navigation switch back to active node
	function fallback(){
		if (hoverFlag) return;
		var activeNodes = $("ul[id='MainNavigationBar']").find("li.Active");
		
		if ($("ul[id='MainNavigationBar']").find("li.Selected").is(".VertAndSel")) 
		{
			$("ul[id='MainNavigationBar']").find("li.Selected").toggleClass("VertAndSel");
		}

		if ($("ul[id='MainNavigationBar']").find("li.Selected2").not(".Active")) 
		{
			$("ul[id='MainNavigationBar']").find("li.Selected2").toggleClass("Selected2");
			$(activeNodes[1]).toggleClass("Selected2");
		}
		
		$("ul[id='MainNavigationBar']").find("li.Selected").toggleClass("Selected");
		
		$(activeNodes[0]).toggleClass("Selected");
		$(".Hovered").toggleClass("Hovered");
		
	}
	


	$(document).ready(function(){
	var stimeout = null;
	var stimein = null;

			$("ul[id='MainNavigationBar']")
			.hover(
				function(){},
				function(){
					stimeout = setTimeout("fallback()" ,2500);
				}
			)

			$("ul[id='MainNavigationBar']").find("li")
			.hover(
				function () {
					//clearTimeout(stimeout);
					hoverFlag=true;
					$(this).addClass("Hovered");
					if ($(this).is(".Vertical")){$(this).addClass("VerticalHovered");}
				}, 
				function () {
				  hoverFlag=false;
				  $(this).removeClass("Hovered");
				  $(this).removeClass("VerticalHovered");
				         
      })
      .mouseover(function(){
					//$("ul[id='MainNavigationBar']").find("li.Hovered").removeClass("Hovered");
					//$(this).toggleClass("Hovered");
					//jump to tab after a delay
					stimein = setTimeout("fallto('"+ $(this).attr("id") +"')", 500);
				})
				.find("li").mouseover(function(){
					$("ul[id='MainNavigationBar']").find("li").find("li.Selected2").toggleClass("Selected2");
					$(this).toggleClass("Selected2")					
				})
				/*.click(function(){
					$("li.Selected").toggleClass("Selected");
					$(this).toggleClass("Selected");
				});
				
			$("ul[id='MainNavigationBar']").find("li").find("li")
				.click(function(){
					$("ul[id='MainNavigationBar']").find("li.Active").toggleClass("Active");
					$(this).toggleClass("Active");
				});*/
			
	});
		$(function () {
			$("#SSOLogin").outerClick( function (event) {
					if($(this).is(".CloseLogin")){
						$(this).removeClass("CloseLogin");
						$(this).slideUp('slow');}
			});
			
			$("li.ui-state-default a").click(function() {
				if($("#SSOLogin").is(".CloseLogin")){
						$("#SSOLogin").removeClass("CloseLogin");
						$("#SSOLogin").slideUp('slow');}
				});
				
			$("li.ui-state-active a").click(function() {
				if($("#SSOLogin").is(".CloseLogin")){
						$("#SSOLogin").removeClass("CloseLogin");
						$("#SSOLogin").slideUp('slow');}
				});
			
			//in internet explorer should open a popup without forwarding to setasHomepage page
			$("#asHomepage").click(function() {
				FuncSetAsHomepage(this,'#');
			});
			
			
			});

