var menuActive = false;
var	menuTimer;
var	reanimate = true;
var	moodCount = 0;
var referrerMood;
var mood;
var title;
var	fgRequest = $.manageAjax({manageType: 'queue', maxReq: 1, blockSameRequest: true});
var fadingDiv = $('<div class="fadecurtain"/>');

$(document).ready(function() {
	$.historyInit(loadPage);
	$(document).pngFix();
	$('div.content').css('zIndex',5);
	fadingDiv.css({'opacity':1,'zIndex':10});
	$('div.content').after(fadingDiv);
	$('div.main').css('visibility','visible');
	extend($('body'));
	fadeInFrom();
});

(function($) {
	
	$.fn.replaceLinks = function() {		
		return this.each(function() {
			$(this).find('a').each(function() {
				var a = $(this);
				var url = a.attr('href').substring(0,a.attr('href').indexOf('.shtml'));
				if (a.parent('li')[0] == a.parent('ul#navigation > li')[0] 
					&&
					url.indexOf('/') != url.lastIndexOf('/')) {
						url = url.substring(0,url.lastIndexOf('/'));
				}
				a.url = '/_binary/menu' + url + '.gif';
				a.hurl = '/_binary/menu_over' + url + '.gif';
				a.img = $('<img src='+a.url+' alt="'+ a.text() +'">');
				a.text('').append(a.img);
				a.mouseover(function() {
						a.img.attr('src',a.hurl);
					}).mouseout(function() {
						if (a.parent('li.selected').length == 0) a.img.attr('src',a.url);
					});
				if (a.parent('li.selected').length != 0) {
					a.img.attr('src',a.hurl);
				}
			});
		});
	};
	
	$.fn.makeExternal = function() {
		return this.each(function() {
			$(this).attr('target','_blank');
		});
	};
	
	$.fn.customFadeIn = function(speed, callback) {
		$(this).fadeIn(speed, function() {
			if(jQuery.browser.msie)
				$(this).get(0).style.removeAttribute('filter');
			if(callback != undefined)
				callback();
		});
	};
	$.fn.customFadeOut = function(speed, callback) {
		$(this).fadeOut(speed, function() {
			if(jQuery.browser.msie)
				$(this).get(0).style.removeAttribute('filter');
			if(callback != undefined)
				callback();
		});
	};
	
	
    $.escape = function(myid) {
        return myid.replace(/:/g,"\\:").replace(/\./g,"\\.");
    };

})(jQuery);

function loadPage(url) {
    if (url && url.indexOf('/')==0) {
		var options = {
	        url: url,
	        type: 'GET',
	        dataType: 'text',
	        success: function(html) {
				fadingDiv.css('zIndex','10').animate({opacity:1},500,function() {
					swapContent(html,url);
				});
		        if (pageTracker) pageTracker._trackPageview(url);
	        },
	        beforeSend: function() {
				moodCount = 0;
			}
	    };
		fgRequest.add(options);
	}
}

function swapContent(html,url) {
	title = wrapContentOfTagInString('title',html);
	if(jQuery.browser.msie) {
		setTimeout(function() {
			document.title = $(title).text();
		},100);
	} else {
	    document.title = $(title).text();
	}
	var content = $('div.content',html);
	$('div.content').replaceWith(content);
	content.css('zIndex',5);
	extend(content);
	fadeInFrom();
}

function wrapContentOfTagInString(tag,string) {
    var p = string.indexOf('<'+tag);
    string = '<div' + string.substring(p + tag.length + 1);
    p = string.lastIndexOf('</'+tag+'');
    return string.substring(0, p) + '</div>';
}

function extend(that) {
	$('div.main',that).css('visibility','visible');
	$('div.smalldevice',that).css('opacity',0);
	$('ol.panelLinks',that).each(function() {
		// this plugin is mainly based on a plugin from Remy Sharp -> http://jqueryfordesigners.com/ thanks a bunch!
		var $links = $(this).find('a'),
			panelIds = $links.map(function() { return this.hash; }).get().join(","),
			$panels = $(panelIds).hide(),
			$panelwrapper = $panels.filter(':first').parent(),
			delay = 500,
			heightOffset = 60;
			
		$links.addClass('panel').click(function () {
			var link = this, 
			$link = $(this);

			if ($link.is('.selected')) {
				return false;
			}

			$links.removeClass('selected');
			$link.addClass('selected');

			$panelwrapper.stop().animate({
				height: 0
			}, delay, function () {
				var height = $panels.hide()
				.filter(link.hash)
				.show()
				.height() + heightOffset;

				$panelwrapper.animate({
					height: height
					}, delay);
			});
			return false;
		});
		$links.filter(':first').click();
	});
	$('#buero').slimbox();
	$('div.gallery a',that).slimbox();
	$('div.gallery',that).append('<small>Zum Vergrößern auf das Bild klicken</small>');
	$('ul#navigation > li.selected ul',that).show();
	$('ul#navigation > li a',that).mouseover(function() {
			var a = $(this);
			a.parent('li').addClass('mouseover');
			a.parents('ul:first').find('li:not(.mouseover,.selected) ul').stop(true,true).slideUp(300);
			a.next().slideDown(300).parent('li').removeClass('mouseover');
	});
	$( 'ul#navigation > li:not(.selected), ul#navigation li:not(.selected) li',that).mouseover(function() {
		clearTimeout(menuTimer);
		menuActive = true;
	}).mouseout(function() {
		menuActive = false;
		clearTimeout(menuTimer);
		menuTimer = setTimeout(function() {
			if (!menuActive) $('ul#navigation > li:not(.selected) ul').slideUp(300);
		},100);
	});
	$('a[rel^="modal"]',that).addClass('modal').nyroModal({autoSizable: false,minHeight:400,minWidth:700});
	$('a.form.modal',that).addClass('modal').nyroModal({autoSizable: false,minHeight:300,minWidth:500,type:"form"});
	$('a[href^="http://"]:not([href^="' + document.location.protocol + '//' + document.location.host + '"]),a[href$=".pdf"]').addClass('external').makeExternal();
	$('a:not(.external,.modal,.panel,[href^="mailto"])',that).click(function() {
		if ($(this).attr('href')=='#' || 
			$(this).attr('href')== document.location.protocol + '//' + document.location.host + '/#') return;
		if ($(this).parents('.gallery').length == 0) {
			if ($(this).parents('ul#navigation').lenght!=0) {
				$(this).parents('li').addClass('selected');
				$('ul#navigation > li:not(.selected) ul').slideUp(300);
			}
			var href = $(this).attr('href');
			if (href.indexOf(document.location.host)!=-1) {
				href = href.substring(href.indexOf(document.location.host) + document.location.host.length);
			}
			fadeOutTo(href);
		}
		return false;
	});
	$('div.main form',that).submit(function() {
		return ajaxForm(this);
	});
	$('div.main form select',that).change(function() {
		$('td.contact input').hide()
		$('td.contact input#'+$(this).val()).show();
	});
	$('div#moodflash').each(function() {
		mood = $(this).attr('title');
		var flashvars = {};
		flashvars.image_path = "/_binary/mood/" + mood + ".png";

		var params = {};
		params.allowScriptAccess = "true";
		params.wMode = "transparent";

		var attributes = {};
		attributes.id = "moodflash";
		attributes.name = "moodflash";

		swfobject.embedSWF("/_binary/mood/motiv.swf", "moodflash", "168", "190", "9.0.0","/_binary/expressInstall.swf", flashvars, params, attributes);
	});
	$('div.print',that).append('<a href="javascript:print();">Seite Drucken</a>');
}

function fadeInFrom() {
	reanimate = true;
	if (referrerMood && mood == referrerMood) reanimate = false;
	$('ul#navigation').find('li').removeClass('selected');
	$('a[href='+document.location.hash.substring(1)+']').parents('li').addClass('selected');
	$('a[href='+document.location.hash.substring(1)+']').parents('ul').slideDown(300);
	$('ul#navigation > li:not(.selected) ul').slideUp(300);
	setTimeout(function() {
		fadingDiv.animate({opacity:0},500, function(){
			if (reanimate) moodFlashReady();
			fadingDiv.css('zIndex','1')
		});
		if (!reanimate) moodFlashReady();
	},100);
	if(jQuery.browser.msie) {
		$('div#main').get(0).scrollTop = 100;
		setTimeout(function() {
			$('div#main').get(0).scrollTop = 0;
		},90);
	}
}

function fadeOutTo(location) {
	referrerMood = mood;
	$.historyLoad(location);
}

function thisMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName];
    } else {
        return document[movieName];
    }
}
function sendToFlash(value) {
	try {
		thisMovie("moodflash").sendToFlash(value);
	} catch(e) {}
}

function moodFlashReady() {
	moodCount++;
	if (moodCount==2) {
		sendToFlash(reanimate);
	}
}


function ajaxForm(myForm) {
	if (validateForm(myForm)) {
		var form = $(myForm);
		var url = form.attr('action');
		var data = form.serialize();
		$.ajax({ 
		   	type: "GET", 
		   	url: url, 
		   	data: data,
			dataType: 'html',
		   	success: function(html){
				$('.reload:first').replaceWith($('.reload:last',html));
		   	} 
		 });		
		return false;
	} else return false;
}


function closeModal() {
	$('.modalwrapper').fadeOut();
}

function validateForm(form) {
	var myForm = $(form);
	var result = true;
	var fs = myForm.find('td:last');
	myForm.find('p.error').remove();
	myForm.find('.mandatory').each(function() {
		var lab = $(this);
		var id = lab.attr('for');
		var val = $('#' + id).val();
		if (lab.hasClass('select')) {
			id = val;
			val = $('#' + val).val();
		}
		if (!val) {
			result = false;
			lab.addClass('error');
			fs.append('<p class="error">Bitte ausfüllen: "' + lab.text() + '"</p>');
		} else {
			if ((lab.hasClass('email') || id == 'email') && !validEmail(val)) {
				result = false;
				lab.addClass('error');
				fs.append('<p class="error">"' + val + '" ist keine gültige Email-Adresse.</p>');
			} else {
				lab.removeClass('error');
			}
		}
	});
	return result;
}

function validEmail(email) {
	// contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
	return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/.test(email);
}

