jQuery.fn.fadeIn = function(speed, callback) { 
    return this.animate({opacity: 'show'}, speed, function() { 
        if (jQuery.browser.msie)  
            this.style.removeAttribute('filter');  
        if (jQuery.isFunction(callback)) 
            callback();  
    }); 
}; 
 
jQuery.fn.fadeOut = function(speed, callback) { 
    return this.animate({opacity: 'hide'}, speed, function() { 
        if (jQuery.browser.msie)  
            this.style.removeAttribute('filter');  
        if (jQuery.isFunction(callback)) 
            callback();  
    }); 
}; 
 
jQuery.fn.fadeTo = function(speed,to,callback) { 
    return this.animate({opacity: to}, speed, function() { 
        if (to == 1 && jQuery.browser.msie)  
            this.style.removeAttribute('filter');  
        if (jQuery.isFunction(callback)) 
            callback();  
    }); 
}; 
    
$(document).ready(function(){

		/* variables */	  
		var navigation = new Array();
		
		navigation[0] = new Array();
		navigation[0]["title"] = "Aktuelles";
		navigation[0]["filename"] = "aktuelles";
		navigation[0]["subnavigation_title"] = new Array();
		navigation[0]["subnavigation_filename"] = new Array();
		
		navigation[1] = new Array();
		navigation[1]["title"] = "Medien";
		navigation[1]["filename"] = "medien";
		navigation[1]["subnavigation_title"] = new Array("Bücher", "Artikel", "Fernsehen", "Hörfunk");
		navigation[1]["subnavigation_filename"] = new Array("buecher", "artikel", "fernsehen", "hoerfunk");
		
		navigation[2] = new Array();
		navigation[2]["title"] = "Therapie";
		navigation[2]["filename"] = "therapie";
		navigation[2]["subnavigation_title"] = new Array("Familien-Mobile", "Therapie-Manual", "Fragebogen", "Burnout-Test");
		navigation[2]["subnavigation_filename"] = new Array("familien-mobile", "therapie-manual", "fragebogen", "burnout-test");
		
		navigation[3] = new Array();
		navigation[3]["title"] = "Praxis";
		navigation[3]["filename"] = "praxis";
		navigation[3]["subnavigation_title"] = new Array("Bilder", "Mitarbeiter");
		navigation[3]["subnavigation_filename"] = new Array("bilder", "mitarbeiter");
		
		navigation[4] = new Array();
		navigation[4]["title"] = "Seminare";
		navigation[4]["filename"] = "seminare";
		navigation[4]["subnavigation_title"] = new Array("Anti-Burnout", "Sucht in der Arbeit");
		navigation[4]["subnavigation_filename"] = new Array("anti-burnout", "sucht-in-der-arbeit");
		
		navigation[5] = new Array();
		navigation[5]["title"] = "Vita";
		navigation[5]["filename"] = "vita";
		navigation[5]["subnavigation_title"] = new Array();
		navigation[5]["subnavigation_filename"] = new Array();
		
		navigation[6] = new Array();
		navigation[6]["title"] = "Kontakt";
		navigation[6]["filename"] = "kontakt";
		navigation[6]["subnavigation_title"] = new Array();
		navigation[6]["subnavigation_filename"] = new Array();
		
		navigation[7] = new Array();
		navigation[7]["title"] = "Impressum";
		navigation[7]["filename"] = "impressum";
		navigation[7]["subnavigation_title"] = new Array();
		navigation[7]["subnavigation_filename"] = new Array();
		
		var start_item = 0;
		var selected_item = start_item;
		var selected_subnavigation_item = "";
		var subnavigationTop = $("#subnavigation").css("top");
		var subnavigationTopDown = parseInt(subnavigationTop.slice(0, subnavigationTop.length-2))+60;
		var initialized = false;
		var navigationLock = false;
		var subnavigationLock = false;
		var pwd = "";
		
		/* main function calls */
		initalizeNavigation();
		checkForHeaderClick();
		checkForMouseOverOnNavigationItems();
		checkForMouseOutOnNavigationItems();
		checkForMouseClickOnNavigationItems();
		
		/* insert navigation items */
		function initalizeNavigation() {
			
			/* set up background image */
			var newDiv = document.createElement("div");
				newDiv.setAttribute("class", "header_image");
				newDiv.setAttribute("id", "header_image_"+selected_item);
				newDiv.style.left = "0px";
				newDiv.style.top = "0px";
				newDiv.style.position = "relative";

				
			var image = new Image();
			image.onload = function() {
							
				$("#header_image_"+selected_item).append(image);
						
			};
			image.src = navigation[selected_item]["filename"]+"/images/header.jpg";
			image.alt = navigation[selected_item]["title"];
				
			document.getElementById("header_image_container").appendChild(newDiv);
			
			for (var navigation_item in navigation) {
				$(document.createElement("div"))
						.addClass("navigation_item")
						.attr({id:"navigation_item_"+navigation_item})
						.appendTo("#navigation_items")
						.text(navigation[navigation_item]["title"]);
			}	
			
			/* position the selector without animation */
			var item_center = $("#navigation_item_"+selected_item).position().left+$("#navigation_item_"+selected_item).width()/2;
			var selector_x = item_center-$("#navigation_selector").width()/2;
			$("#navigation_selector").css({left:selector_x+"px"});
			
			/* load start page content*/
			loadHTML(navigation[selected_item]["filename"]+"/index.html");
		}
		
		/* positions the selector */
		function positionSelector(left, width, duration) {
			if(!navigationLock) {
				var item_center = left+width/2;
				var selector_x = item_center-$("#navigation_selector").width()/2;
				$("#navigation_selector").animate({left:selector_x+"px"}, {duration:duration, easing:"easeOutCirc"});
			}
		}

		function checkForHeaderClick() {
			$("#header").click(function() {
				if(!navigationLock) {
					$("#navigation_item_"+start_item).trigger("click");
				}
				positionSelector($("#navigation_item_"+start_item).position().left, $("#navigation_item_"+start_item).width(), 500);
			});
		}
		
		/* checks for mouseover events and positions the selector accordingly */
		function checkForMouseOverOnNavigationItems() {
				$(".navigation_item").mouseover( function() {
					$("#navigation_selector").stop();
					positionSelector($(this).position().left, $(this).width(), 300);
				});
		}
		
		/* checks for mouseover events and positions the selector accordingly */
		function checkForMouseOutOnNavigationItems() {
				$(".navigation_item").mouseout( function() {
					$("#navigation_selector").stop();
					positionSelector($("#navigation_item_"+selected_item).position().left, $("#navigation_item_"+selected_item).width(), 800);
				});
		}
		
		function checkForMouseClickOnNavigationItems() {
			$(".navigation_item").click(function() {			
						
				if(!navigationLock) {
					
						positionSelector($(this).position().left, $(this).width(), 300);
						
						if(pwd != "") {
							logout();	
						}
		
						// get id
						var id = $(this).attr("id");
						id = id.substring(16);
						
						
						// get direction and animate
						var direction = "none";
						var direction_neg = "none";
						if(selected_item != id) {
							direction = (selected_item < id) ? "-" : "+";
							direction_neg = (direction == "-") ? "+" : "-";
						}
						
						// animate
						if(direction != "none") {
							
							navigationLock = true;	
							
							var newDiv = document.createElement("div");
							newDiv.setAttribute("class", "header_image");
							newDiv.setAttribute("id", "header_image_"+id);
							newDiv.style.left = direction_neg+"774px";
							newDiv.style.top =  "-249px";
							newDiv.style.position = "relative";
							
							document.getElementById("header_image_container").appendChild(newDiv);						
					
							var image = new Image();
							image.onload = function() {
								
								$("#header_image_"+id).append(image);						
								$("#header_image_"+selected_item).animate({left:direction+"774px"},{duration:400, easing:"easeOutCirc"});																
								$("#header_image_"+id).animate({left:"0px"},{duration:400, easing:"easeOutCirc", complete:function() {
										
										selected_subnavigation_item = "";
										checkForSubnavigation(id);
										
										$("#content").stop();
										$('#content_load_screen').stop();
										
										loadHTML(navigation[id]["filename"]+"/index.html");
										selected_item = id;	
										deleteOtherFrames();
								}});
								
							};
							image.src = navigation[id]["filename"]+"/images/header.jpg";
							image.alt = navigation[id]["title"];
						}	
					}
			});
		}
		
		function checkForSubnavigation(id) {
			var subnavigation = false;
			if(navigation[id]["subnavigation_title"].length > 0) {
				subnavigation = true;
			}			
			
			if(subnavigation) {
				// move subnavigation out
				var duration = 0;
				if($("#subnavigation").css("top") == subnavigationTopDown+"px") {
					duration = 300;
				}
				
				$("#subnavigation").stop()
								   .animate({top:subnavigationTop},{duration:duration, easing:"easeInCirc", complete: function() {																	   
					$("#subnavigation").empty();
					
					var subnavigation_items = navigation[id]["subnavigation_title"];
				
					for (var subnavigation_item in subnavigation_items) {
						$(document.createElement("div"))
								.addClass("subnavigation_item")
								.attr({id:"subnavigation_item_"+subnavigation_item})
								.appendTo("#subnavigation")
								.text(subnavigation_items[subnavigation_item]);
					}
					
					// position subnavigation under navigation item
					var nav_center = $("#navigation_item_"+id).position().left + $("#navigation_item_"+id).width()/2;
					var subnav_center = nav_center-$("#subnavigation").width()/2;
					
					if(subnav_center < 20) {
						subnav_center = 20;	
					}
					else if($("#subnavigation").position().left+$("#subnavigation").width() > 600) {
						subnav_center = 777-$("#subnavigation").width()-20;	
					}
					
					$("#subnavigation").css({"left":subnav_center+"px"});
					
					checkForMouseOverSubnavigationItems();
					checkForMouseOutSubnavigationItems();
					checkForMouseClickOnSubnavigationItems();
					
					// move subnaivgation in
					$("#subnavigation").animate({top:subnavigationTopDown+"px"},{duration:300, easing:"easeOutCirc"});
				
				}});	
				
			}
			else if(!subnavigation && $("#subnavigation").css("top") == subnavigationTopDown+"px") {
				$("#subnavigation").stop()
								   .animate({top:subnavigationTop},{duration:300, easing:"easeInCirc"});
			}
			
		}
		
		function checkForMouseOverSubnavigationItems() {
			$(".subnavigation_item").mouseover(function() {									
				if(!subnavigationLock && $(this).css("font-weight") != "bold" && $(this).attr("id") != selected_subnavigation_item) {
					var text = $(this).text();
					$(this).empty()
						   .css({"font-weight":"bold"})
						   .text(text);
				}
			});
		}
		
		function checkForMouseOutSubnavigationItems() {
			$(".subnavigation_item").mouseout(function() {											   
				if(!subnavigationLock && $(this).css("font-weight") != "normal" && $(this).attr("id") != selected_subnavigation_item) {
					var text = $(this).text();
					$(this).empty()
						   .css({"font-weight":"normal"})
						   .text(text);
				}
			});
		}
		
		function checkForMouseClickOnSubnavigationItems() {
			$(".subnavigation_item").click(function() {
				if(!subnavigationLock) {
					var id = $(this).attr("id");
					
					if(selected_subnavigation_item != id || selected_subnavigation_item == "") {
						
						// set all font-weights to normal
						$(".subnavigation_item").each(function() {
							var text = $(this).text();
							
							if($(this).attr("id") == id){
								$(this).empty()
								   .css({"font-weight":"bold"})
								   .text(text);	
							}
							else {
								$(this).empty()
								   .css({"font-weight":"normal"})
								   .text(text);	
							}
		
						})
						
						selected_subnavigation_item = id;
						id = id.substr(19);
						loadHTML(navigation[selected_item]["filename"]+"/"+navigation[selected_item]["subnavigation_filename"][id]+".html");
					}
				}
			})
		}
		
		function deleteOtherFrames() {
			var container = document.getElementById("header_image_container");
													
			for(var i=0; i<container.childNodes.length; i++) {
				
				if(container.childNodes[i].id != "header_image_"+selected_item) {
					container.removeChild(container.childNodes[i]);	
				}	
			}
			
			$("#header_image_"+selected_item).css({"top":"0px"});
		}
		
		function loadHTML(filename) {
			subnavigationLock = true;
			$("#content").fadeOut(500, function(){
				$('#content_load_screen').fadeIn(200);
				$.post("php/loadHTML.php", {filename: filename}, function(content){
																
					$("#content").empty().html(content);
					
					checkForMouseClickOnEditNewsButton();
					if($('#termine').length > 0){
						receive_news_list();
					}
					if(document.getElementById("kontakt_input_submit") != null) {
						checkForContactForm();
					}
					//betrifft die artikel seite
					if(document.getElementById("artikel_Page") != null){
					    $('a[rel="artikel_newWin"]').click( function() {
						window.open( $(this).attr('href'), $(this).text() );
						return false;
					    });
					}
					//END artikel seite
					$('#content_load_screen').fadeOut(200, function(){
						$('#content').fadeIn(500);
						navigationLock = false;
						subnavigationLock = false;
					});
				});	
			});			
		}
		
		function checkForMouseClickOnEditNewsButton() {
			$("#edit_news")
			.click(function() {
				$("#admin_bg").css({"opacity":"0.8"});
				
				if($("#admin").position().left == 0) {
					$("#admin").animate({left:"490px"},{queue:false, duration:300, easing: "easeOutCirc"});
					initialized = false;
				}
				else {
					$("#admin").animate({left:"0px"},{duration:300, easing: "easeOutCirc"});
					initialized = true;
				}
				
			})
			.mousedown(function() {
				$("#edit_news").css({top:"1px", left:"1px"});
			})
			.mouseup(function() {
				$("#edit_news").css({top:"0px", left:"0px"});
			})
			.mouseout(function() {
				$("#edit_news").css({top:"0px", left:"0px"});
			});
			
			checkForLogin();
		}
		
		function checkForLogin() {
			if(document.getElementById("login_form") != null) {
				
				disableEditForm(true);
				
				var form = document.getElementById("login_form");
				form.onsubmit = function() { return false };
				
				var field = document.getElementById("password");
				field.onblur = function() {if(this.value==""){ this.value="password";}};
				field.onfocus = function() {if(this.value=="password"){ this.value="";}};
				
				$("#edit")
				.live("click", function() {
					$("#edit").css({top:"1px", left:"1px"});
					show_news_formular($(this).closest('li').attr('id'));
				});
				
				$("#remove")
				.live("click", function() {
					remove_news($(this).closest('li').attr('id'));
				});
			}
		}
		
		function checkForContactForm(){

			var submitForm = function() {
				$("#kontakt_input_error").text("");
				text = $('#kontakt_input_text').val()
				mail = $('#kontakt_input_email').val()
				phone = $('#kontakt_input_telefon').val()
				person = $('#kontakt_input_name').val()
				
				if(text == '' || person == '' || (mail == '' && phone == '')){
					msg = 'Das Formular wurde unvollständig ausgefüllt.';
					if(person == ''){
						msg += ' Bitte geben Sie Ihren Namen an.';
					}else if(mail == '' && phone == ''){
						msg += ' Bitte geben Sie eine gültige eMail-Adresse oder Telefonnummer ein, damit Herr Dr. Kolitzus Sie kontaktieren kann.';
					}else if(text == ''){
						msg += ' Bitte geben Sie eine Nachricht ein.';
					}
					$("#kontakt_input_error").text(msg);
				}else{
					//$("#kontakt_input_submit").live('click', function(){});
					$("#kontakt_input_submit").attr('disabled',true);
					$('#content_load_screen').fadeIn(200);
					$("#kontakt_formular").css({'opacity':'0.4'});
					$.post("php/send_mail.php", {email: mail, from: person, text:text, phone:phone}, function(result){
						if(result.indexOf('success') != -1){
							$("#kontakt_formular").fadeOut(500, function(){
								$("#kontakt_erfolgt").fadeIn(500);
							});
						}else{
							$("#kontakt_input_error").text("Es ist ein Fehler aufgetreten. Bitte versuchen Sie es später nochmal.");
						}
						$('#content_load_screen').fadeOut(200);
						//$("#kontakt_input_submit").live('click', submitForm);
						$("#kontakt_formular").removeAttr('disabled');
					});
				}
			};

			$("#kontakt_erfolgt").css({display:'none'});
			$("#kontakt_input_submit").live('click', submitForm);
		}

		function disableLoginForm(value) {
			document.login_form.password.disabled = value;	
		}
		
		function disableEditForm(value) {
			document.edit_form.text.disabled = value;
			document.edit_form.date.disabled = value;
			document.edit_form.location.disabled = value;
			document.edit_form.cancel.disabled = value;
			document.edit_form.save.disabled = value;	
		}
		
		$(document).keyup(function(event){
			switch (event.keyCode) {			
			
			 // enter
			case 13 : if(initialized && pwd == "") {
						login(); 
					  }
					  break;
		  }						   
		});
		
		function login() {
			
			checkForLogout();
			
			var ok = false;
			var password = trim(document.forms.login_form.password.value);
			
			var servertime;
			$.post("php/login.php", {request:"servertime"}, function(answer) {
				servertime = answer;
				
				if(password != "" && password != "password"){
				password = MD5(password);
				var pass = MD5(password+servertime);
				
				$.post("php/login.php", {passphrase:pass, request:"authentication"}, function(answer) {
					ok = (answer == "true") ? true : false;
					
					if(ok) {
						
						$("#login").fadeOut(200);
						$("#admin_bg").fadeOut(200, function() {
							$("#admin_tools").animate({top:"0px"},{queue:false, duration: 200, easing: "easeOutCirc"});	
							$(".admin_news_tools").animate({left:"0px"},{queue:false, duration:200, easing:"easeOutCirc"});
							
							disableEditForm(false);						  
						});
						pwd = password;
						
						$("#edit_news").css({"opacity":"0.3", "cursor":"default"})
					}
					else {
						$("#login").effect("shake", { times:3 }, 70);
						document.forms.login_form.password.value = "";	
					}
				});
			}
			});
		}
	

	function show_news_formular(id){
		$('#cancel').click(function(){
			$("#edit_news_area").animate({left:"490px"},{queue:false, duration:300, easing: "easeOutCirc"});
			//$("#edit_bg").animate({left:"490px"},{queue:false, duration:300, easing: "easeOutCirc"});
			//$("#edit_bg").css({"opacity":"1"});
			//$("#edit_news_area").css({left:"0px"});
		});
	
		//$("#edit_news_area").css({left:"490px"});
		//$("#edit_news_form").fadeIn(0);
		//$("#edit_bg").fadeIn(0);
		
		var form = document.getElementById("edit_form");
		
		$("#edit_bg").css({"opacity":"0.8"});
		$("#edit_news_area").animate({left:"0px"},{duration:300, easing: "easeOutCirc"});
		if($("#"+id).length > 0){
			$("#text").attr('value', $('#'+id+' .news_entry .termine_headline').text());
			$("#date").attr('value', $('#'+id+' .news_entry .termine_datum').text());
			$("#location").attr('value',  $('#'+id+' .news_entry .termine_text').text());
			
			
			form.onsubmit = function() {
				edit_news_save_changes(id,$("#location").attr('value'),$("#text").attr('value'),$("#date").attr('value'));
				reset_news_form();
				return false;
			};
		}else{
			$("#text").click(function(){
				if($(this).attr('value') == "Titel der Veranstaltung"){
					$(this).attr('value', "");
				}
			});
			$("#date").click(function(){
				if($(this).attr('value') == "Datum"){
					$(this).attr('value', "");
				}
			});
			$("#location").click(function(){
				if($(this).attr('value') == "Ort"){
					$(this).attr('value', "");
				}
			});
			
			form.onsubmit = function() {
				insert_news($("#location").attr('value'),$("#text").attr('value'),$("#date").attr('value'));
				reset_news_form();
				return false;
			};
		}
	}
	
	function reset_news_form(){
		$("#location").attr('value', "Ort");
		$("#text").attr('value', "Titel der Veranstaltung");
		$("#date").attr('value', "Datum");
		//$("#edit_news_form").fadeOut(200);
		//$("#edit_bg").fadeOut(200);
		//$("#edit_bg").css({"opacity":"1"});
		//$("#edit_news_area").css({left:"0px"});
		$("#edit_news_area").animate({left:"490px"},{queue:false, duration:300, easing: "easeOutCirc"});
	}
	
	function insert_news(loc,text,date) {
		var servertime;
		$.post("php/login.php", {request:"servertime"}, function(answer) {
			servertime = answer;
			
			if(pwd != "" && pwd != "password"){
			var pass = MD5(pwd+servertime);
			$.post("php/news.php", {request:"insert_news", date:date, location:loc, title:text, passphrase:pass}, function(answer) {
				if(answer.slice(0,4) != "err:"){
					receive_news_list();
				}
			});
			}
		});
	}
	
	function edit_news_save_changes(id,loc,text,date) {
		var servertime;
		$.post("php/login.php", {request:"servertime"}, function(answer) {
			servertime = answer;
			
			if(pwd != "" && pwd != "password"){
			var pass = MD5(pwd+servertime);
			
			$.post("php/news.php", {request:"edit_news", id:id, date:date, location:loc, title:text, passphrase:pass}, function(answer) {
				if(answer.slice(0,4) != "err:"){
					receive_news_list();
				}
			});
			}
		});
	}
	
	function remove_news(id) {
		var servertime;
		$.post("php/login.php", {request:"servertime"}, function(answer) {
			servertime = answer;
			
			if(pwd != "" && pwd != "password"){
			var pass = MD5(pwd+servertime);
			
			$.post("php/news.php", {request:"remove_news", id:id, passphrase:pass}, function(answer) {
				if(answer.slice(0,4) != "err:"){
					receive_news_list();
				}
			});
			}
		});
	}
	
	
	function receive_news_list(){
		if($('#termine').length > 0){
			$.post("php/news.php", {request:"recieve_news"}, function(answer) {
				if(answer.slice(0,4) != "err:"){
					$("#termine").fadeOut(500, function(){
						$("#termine").html("");
						var items = answer.split(">>>");
						for(var i=0;i<items.length;i++){
							var entry = items[i].split("|||");
							addNewsToList(entry[0],entry[1],entry[3],entry[2]);
						}
						$("#termine").fadeIn(500);
						if(pwd != ""){
							$(".admin_news_tools").css({left:"0px"});
						}
					});
				}
			});
		}
	}
	
	function addNewsToList(id,date,location,headline){
		$("#termine").append("<li id=\""+id+"\"><div id=\"admin_news_tools_container\"><div class=\"admin_news_tools\"><div class=\"admin_news_tool\" id=\"edit\"><img src=\"aktuelles/images/edit_text.png\" width=\"13\" height=\"13\" alt=\"Nachricht bearbeiten\" /></div><div class=\"admin_news_tool\" id=\"remove\"><img src=\"aktuelles/images/delete_news.png\" width=\"15\" height=\"15\" alt=\"Nachricht l&ouml;schen\" /></div></div></div><div class=\"news_entry\"><span class=\"termine_headline\">"+headline+"</span><div><span class=\"termine_datum\">"+date+"</span></div><div><span class=\"termine_text\">"+location+"</span></div></div></li>");
	}
	
	function checkForLogout() {
		$("#logout")
		.mousedown(function() {
			$("#logout").css({top:"1px", left:"1px"});								
		})
		.mouseup(function() {
			$("#logout").css({top:"0px", left:"0px"});
			$(".admin_news_tools").animate({left:"-15px"},{queue:false, duration:200, easing: "easeInCirc"});
			$("#admin_tools").animate({top:"-40px"},{queue:false, duration: 200, easing: "easeInCirc", complete:function() {
				logout();																										 
			}})
		})
		.mouseout(function() {
			$("#logout").css({top:"0px", left:"0px"});								
		});
		
		$("#add_news")
		.mousedown(function() {
			$("#add_news").css({top:"1px", left:"1px"});								
		})
		.mouseup(function() {
			$("#add_news").css({top:"0px", left:"0px"});
			show_news_formular();
		})
		.mouseout(function() {
			$("#add_news").css({top:"0px", left:"0px"});
		});
	}
		
	
	function logout() {
		pwd = "";
		initalized = false;
		
		disableEditForm(true);
		
		$("#admin").css({left:"490px"});
		$("#login").fadeIn(0);
		$("#admin_bg").fadeIn(0);
		$(".admin_tool").fadeIn(0);
		$("#edit_news_area").css({left:"490px"});
		$("#edit_news_form").fadeIn(0);
		$("#edit_bg").fadeIn(0);
		$("#edit_news").css({"opacity":"1.0", "cursor":"pointer"})
		
	}
		
	/* trim Strings */
	function trim (st) {
	   return st.replace (/^\s+/, '').replace (/\s+$/, '');
	}
});

