$(document).ready(function(){
						   
/* AJAX Libary 
 * 
 * Typo3 Inhalte Ã¼ber Ajax Request 
 * auslesen und animieren
 ************************************/
 
// ScrollPane Init + Instanz für ReInit
// (Muss hier rein, um Instanz für ReInit zu haben)
//var pane = $('.scrollable')
//    pane.jScrollPane({showArrows: true});
//var paneApi = pane.data('jsp');

// Globale Variablen / Konstanten
var stored         = false; // aktive Navis speichern um nach dem ajaxRequest zu stylen
var storedInside   = false; // aktive Navis speichern um nach dem ajaxRequest zu stylen
var lastCalledLink = false;
var lastCalledSect = false;
var contentOpen    = true;
var contentElement = '#contentWrap';
var imageElement   = '#background';
var altImgElement  = '#toiSlider';
var oldImage       = '#oldBG'; 
var loaderElement  = '#ajaxLoader';
var sliderElement  = '#toiSlider';
var sliderNavi     = '#slideNavi';
var baseUrl        = 'http://georgiew.rpdweb.de/';
var galeryCatClick = false;
var activeRequest  = false;
var trackAnalytics = false;

init();
 
 
 
function init() {
	//$('.galCat:first a').addClass('act');
	$('#footWrap').append('<div id="slideNaviWrap"><div id="slideNavi"></div></div>');
		
	$('#toiSlider').toiSlider('init');
	
	if((checkSpecialLink(location.href, 'photography') || checkSpecialLink(location.href, 'fotographie')) || location.href == baseUrl) {
		$('#slideNavi').show();
		$('#footNews').hide();
	}
	
	$('#toiSlider').find('.mainImage:first').addClass('act');
	
	initializeEvents();
}


function initializeEvents() {
	
	 // Haupt- und Metanavi Click Event
	/*
$('#mainNavi, #metaNavi').find('a').unbind('click').click(function() {
		url     = $(this).attr("href");
		section = contentElement;
		
		animateOut('Kleinen Moment bitte...', 'Seite wird geladen', url, section);	
		
		stored = $(this).attr('id');
		switchNavis(stored);
		$('#'+stored).parent().addClass('active');
		
		return false;
	});
*/
	
	 // Kontakt Links
	$('#kontakte .form, #extraButton').unbind('click').find('a').click(function() {
		url     = $(this).attr("href");
		section = '#content';
		
		animateOut('Kleinen Moment bitte...', 'Seite wird geladen', url, section);
		
		$('html').animate({scrollTop: 0}, 600);
		$('#content').animate({'height': '500px'}, 600);
		$('#topAlign').animate({'height': '727px'}, 600);
		
		return false;
	});
	
	// Link auf dem Logo (Startseite)
	$('#logoLink').unbind('click').click(function() {
		url     = $(this).attr("href");
		section = '#content';
		
		animateOut('Kleinen Moment bitte...', 'Seite wird geladen', url, section);
		
		$('#content').animate({'height': '371px'}, 600);
		$('#topAlign').animate({'height': '600px'}, 600);
		
		return false;
	});
	
	// Links innerhalb des ajaxContent
	$('#contentMain').find('a').unbind('click').click(function() {
		url     = $(this).attr("href");
		section = contentElement;

		animateOut('Kleinen Moment bitte...', 'Seite wird geladen', url, section);
		
		return false;
	});
	
	// Links innerhalb des ajaxContent
	/*
$('#galCats').find('a').unbind('click').click(function() {
		url     = $(this).attr("href");
		section = contentElement;
		
		galeryCatClick = true;
		resetGaleryCategories($(this));		
		
		$(this).addClass('act');

		animateOut('Kleinen Moment bitte...', 'Seite wird geladen', url, section);
		
		return false;
	});
*/
}


/* Navigation Styles etc. */  	
  	function switchNavis(id) {
  		$('#mainNavi li').each(function() {
  			$(this).removeClass('active');
  		});
		
		if(id == 'fn6') $('#mn6').parent().addClass('active');
  	}


/* Ajax Content einlesen und verarbeiten */  	
  	function getContent(url, section) {	
		
		$(sliderElement).toiSlider('kill');
		
  		rand = Math.random() * 1000;
		$(loaderElement).show();
		
		if(!activeRequest) {
			activeRequest = true;
			
			$.ajax({
				//erweitere aufzurufenden Link
				url: checkInnerLink(url) + '&r='+rand,
				//wenn es geklappt hat
				success: function(html) {
					//Inhalt reinschreiben und anzeigen
					$(section).html(html);
					$(section).animate({opacity: 1}, 200, function() {
						
						//$('.scrollable').jScrollPane({showArrows: true});
						if($.browser.msie) this.style.removeAttribute('filter');
						
						if(trackAnalytics) {
							if (typeof _gaq !== "undefined" && _gaq !== null) {
								_gaq.push(['_trackPageview', url]);
							}
						}
						
						reInitBackground(url);
						//reInitNavi(url);
						reInitMailform();
						reFormatContent(url);
						//resizeBackground();
						resetFooter(url);
						animateIn(url);
						
						activeRequest  = false;
					});
					
					//if($.browser.msie) crapBrowserFixes();
					
					if(storedInside && storedInside != '') $('#'+storedInside).parent().addClass('active');
					lastCalledLink = url;
					lastCalledSect = section;
				},
				error: function(request, error) {
					alert('Beim laden der Seite ist ein Fehler aufgetreten: ' + error);
				}
			});
		}
	}
	
	
	/* * *
	* Anpassung des Footers nach erfolgreichem ajaxRequest
	*
	* @url -> Link, der über ajax geladen wurde
	*/
	function resetFooter(url) {
		if(checkSpecialLink(url, 'photography') || checkSpecialLink(url, 'fotographie')) {
			$('#footNews').animate({opacity: 0}, 600, function() {
				$(this).hide();
				
				if(!galeryCatClick) {
					resetGaleryCategories($('.galCat a:first'));
					
					$('#galCats').css({
						opacity: '0',
						display: 'block'
					}).animate({opacity: 1}, 800);
				}
				
				galeryCatClick = false;
			});
		} else if(checkSpecialLink(url, 'aktuelles')) {
			$('#slideNavi').animate({opacity: 0}, 600);
			$('#galCats').animate({opacity: 0}, 600, function() {
				$(this).hide();
			});
			$('#footNews').animate({opacity: 0}, 600);
		} else {
			$('#slideNavi').animate({opacity: 0}, 600, function() {
				$(this).hide();
				$('#footNews').css({
					opacity: '0',
					display: 'block'
				}).animate({opacity: 1}, 800);
			});
			$('#galCats').animate({opacity: 0}, 600, function() {
				$(this).hide();
			});
		}
	}
	
	
	/* * *
	* Hintergrund an Fenstergröße anpassen
	*/
	function resizeBackground() {		
		var fix = $('#fixedBG').find('img');
	  
		var sW;
		var sH;
		var iW = fix.width();
		var iH = fix.height();	  

		sW = $(window).width();
		sH = $(window).height();
		if(iW != sW) {
		    fix.removeAttr('height');
		    fix.attr('width', sW);
		    iW = fix.width();
		    iH = fix.height();
		    
		    /*
if(iH > sH) {
		  	  nH = iH - sH;
		  	  fix.css({
		  		'position': 'absolute',
		  		'top'     : '-'+nH+'px'
		  	  });
		    }
*/			  
		}
		
		iW = fix.width();
		//iH = fix.height();
		
		/*
if(iH < sH) {
		    fix.removeAttr('width'); 
		    
		    fix.attr('height', sH); 
		    fix.css({
		  	'position': 'absolute',
		  	'top'     : '0'
		    });
		}
*/
	}
	
	
	/* * *
	* Neu geladenen Content anzeigen
	*
	* @url -> über ajax geladener Link
	*/
  	function animateIn(url) {
  		imgElementForAnim = ($(imageElement).length > 0) ? imageElement : altImgElement;
		
		$('#fixedBG').animate({'opacity': '1'}, 1500);
  		$(loaderElement).hide();
  		
		$(imgElementForAnim).animate({opacity: 1}, 1000, function() {
			reInitEvents();
			reInitContent();
		});
		
		$('#mainOverlay').animate({'opacity': '0'}, 500, function() {
			$(this).css({'opacity': '0', 'display': 'block'}).hide();
			$(contentElement).css('left', '-1300px').animate({left: 350}, 600, function() {
				
			});
		});
	}
	
	
	/* * *
	* Content raus animieren, anschließend @url über ajax laden
	*
	* @egonHeader -> deprecated.
	* @egonMsg -> deprecated.
	* @url -> Link der über ajax geladen werden soll
	* @section -> Container-Element, wo der neue Content nach
	*             erfolgreichem ajaxRequest integriert werden soll
	*/
  	function animateOut(egonHeader, egonMsg, url, section) {
  	
  		if($('#fixedBG').html() != '') {
  			$(oldImage).html($('#fixedBG img').clone());
  		} else {
  			$('#toiSlider').find('.mainImage').each(function() {
  				if($(this).hasClass('act')) {
  					oldSlide = $(this).find('img');
  				} else {
  					oldSlide = $(this).find('img:first');
  				}
  			});
  			$(oldImage).html(oldSlide.clone());
  		}
  		
  		$('#fixedBG').css('opacity', 0);
  		
  		imgElementForAnim = ($(imageElement).length > 0) ? imageElement : sliderElement;
  		
  		contentCount = 1;
  		$(contentElement).each(function() {
  			contentCount++;
  		});
  		
  		if(sliderNavi) {
  			$(sliderNavi).parent().animate({bottom: '-200px'}, 600);
  		}
  		
  		if($.browser.msie) $(imageElement).hide();
  		if($(contentElement).length > 0) {
  			$(imgElementForAnim).css({opacity: 1}).stop().animate({opacity: 0}, 500);
  			$('#mainOverlay').css({'opacity': '0', 'display': 'block'}).animate({'opacity': '0.7'}, 600, function() {
  				//$(sliderElement).toiSlider('kill');
				$(contentElement).animate({left: 2200}, 700, function() {
					getContent(url, section);
				});
			});
		} else {
			$(imgElementForAnim).css({opacity: '1'}).stop().animate({opacity: 0}, 700, function() {
				getContent(url, section); 
			});
		}
	}
	
	
	/* * *
	* Navigation je nach Link anpassen
	*
	* @url -> Link der aktiven Seite
	*/
	function reInitNavi(url) {
		$('#toiSlider h2').css('top', 465);
		
		if(checkSpecialLink(url, 'home')) {
			resetNavi();
			$('#mn2').parent().addClass('active');
			$('#toiSlider h2').css('top', 335);
		} else if(checkSpecialLink(url, 'ueber')) {
			resetNavi();
			$('#mn17').parent().addClass('active');
		} else if(checkSpecialLink(url, 'philosophie')) {
			resetNavi();
			$('#mn21').parent().addClass('active');
		} else if(checkSpecialLink(url, 'leistung')) {
			resetNavi();
			$('#mn22').parent().addClass('active');
		} else if(checkSpecialLink(url, 'hersteller')) {
			resetNavi();
			$('#mn23').parent().addClass('active');
		} else if(checkSpecialLink(url, 'kontakt')) {
			resetNavi();
			$('#mn6').parent().addClass('active');
		}
	}
	
	
	/* * *
	* User-Events für ajax-Content neu initialisieren
	* (Klick Events etc.)
	*/
	function reInitEvents() {
		initializeEvents();
		
		$('.fancybox').fancybox({
			'overlayOpacity' : 0.8,
			'overlayColor'   : '#000000'
		});
		
		$('.newsContent').find('a').unbind().die('click');
//		$('.newsContent').find('a').click(function() {
//			alert('externer link');
//			window.location = $(this).attr('href');
			
//			return false;
//		});
		
		$('#nextPart').click(function() {
			$('.formPart1').animate({opacity: 0}, 300, function() {
				$(this).hide();
				$('.formPart2').show().css('opacity', 0).animate({opacity: 1}, 800, function() {
					checkScrollableContent($('#contentWrap'));
				});
			});
		});
		
		$('#footNews').find('a').click(function() {
			url     = $(this).attr("href");
			section = contentElement;
		
			animateOut('Kleinen Moment bitte...', 'Seite wird geladen', url, section);
			
			return false;
		});
	}
	
	
	/* * *
	* Hintergrund der Seite anpassen (Slider oder statisch)
	*
	* @url -> Link der aktiven Seite
	*/
	function reInitBackground(url) {			
		if(checkSpecialLink(url, 'photography') || checkSpecialLink(url, 'fotographie')) {
			reInitSlider();
			$('#imgOverlay').show();
			$('#fixedBG').empty().hide();
		} else {
			$('#imgOverlay').hide();
			$('#fixedBG').html($('#background').html()).show();
		}
		
		tmpSrc = $('#fixedBG').find('img').attr('src');
		if(tmpSrc != null) {		
  			tmpSrc = tmpSrc.replace("/aktuelles", "");
  			tmpSrc = tmpSrc.replace("/film", "");
  			tmpSrc = tmpSrc.replace("/kontakt", "");
  		
  			$('#fixedBG').find('img').attr('src', tmpSrc);
  		}
	}
	
	
	/* * *
	* Slider neu initialisieren
	*/
	function reInitSlider() {
		console.log('reInit slider..');
		$('#slideNaviInner').remove();
		
		sliderOrig = $('#toiSlider');
		$('body').append(sliderOrig.clone());
		$('#contentWrap').find('#toiSlider').remove();
		
		$('#toiSlider').find('.mainImage').css('opacity', 0);
		$('#toiSlider').toiSlider('init');
		
		if(sliderNavi) {
			$(sliderNavi).css({opacity: 1, display: 'block'});
  			$(sliderNavi).parent().animate({bottom: '0'}, 600);
  		}
	}
	

	/* * *
	* Events für das Kontaktformular neu initialisieren
	*/
	function reInitMailform() {		
		$('#mailForm .submitButton').click(function() {
			$(loaderElement).show();
					
			if($.browser.msie) $(imageElement).hide();
		  		if($(contentElement).length > 0) {
		  			$(imageElement).css({opacity: 1}).stop().animate({opacity: 0}, 500);
					$(contentElement).animate({left: '-1000px'}, 700, function() {
						mailFormRequest();												   
					});
				} else {
					$(imageElement).css({opacity: '1'}).stop().animate({opacity: 0}, 700, function() {
						mailFormRequest();		
					});
				}
			
			
			return false;
		});
		
		$('#mailForm').find('input, textarea, select').focus(function() {
			$(this).attr('style', '');
		});
	}
	
	
	/* * *
	* Kontaktformular Absenden und confirmation über einen
	* seperaten ajaxRequest
	*/
	function mailFormRequest() {
		var rand = Math.random() * 1000;
			
		$.ajax({
			type: 'POST',
			url:  checkInnerLink('/kontakt/formular/') + '&r='+rand,
			data: $('#mailForm').serialize(),
			success: function(html) {
				$('#content').html(html).animate({opacity: 1}, 800, function() {
					if($.browser.msie) $(this).removeAttr('filter');
					
					captchaRand = parseInt(Math.random() * 1000);
					captchaLink = $('#mailForm').find('.captchaImg img').attr('src');
					$('#mailForm').find('.captchaImg img').attr('src', '/' + captchaLink + '?r=' + captchaRand);
				});
				$('#slogan, #claim').remove();
				
				reInitMailform();
				reInitInnerLinks('/kontakt/formular/');
				animateIn('/kontakt/formular/');
			}
		});
	}
	
	
	/* * *
	* einzelne Content-Elemente nach ajaxRequest initialisieren
	* (hier vorallem die Videoboxen für die Film-Seite
	*/
	function reInitContent(url) {
		isLoggedIn = true;
		vidCount = 0;
		$('.csc-downloadBox').each(function() {
			
			flowplayer("vidItem"+vidCount, "pub/js/flowplayer-3.2.7.swf", {
			    clip:  {
        	    	autoPlay: false,
        	    	autoBuffering: true
    		    },
    		    
    		    plugins: {
   					controls: {
   						all: false,
   						play: true,
   						fullscreen: true,
   						stop: true,
   						scrubber: true,
   						mute: isLoggedIn,
   						
   						progressColor: '#d9ca54',
   					}
				}
			});
			
			$(this).find('.vidOverlay').click(function() {
				$(this).hide();
				$f($(this).parent().data('num')).play();				
			});
			
			$(this).find('a').unbind('click').die('click');
			
			vidCount = vidCount + 1;
		});
		
		checkScrollableContent($('#contentWrap'));
	}
	
	
	/* * *
	* #contentWrap Höhe gegen Fensterhöhe prüfen
	* -> bei Bedarf scrollbar machen
	*
	* @obj -> Object, welches mit Fensterhöhe verglichen werden soll
	*/
	function checkScrollableContent(obj) {
		if(($(window).height() - 300) < obj.height()) {
			obj.css({
				'overflow': 'auto',
				'height'  : $(window).height() - 300
			});
		}
	}
	
	
	/* * *
	* einzelne Content-Elemente nach ajaxRequest formatieren
	* (hier vorallem die Videoboxen für die Film-Seite
	*/
	function reFormatContent(url) {
		vidCount = 0;
		$('.csc-downloadBox').each(function() {
			$(this).data('num', vidCount);
			$(this).find('a').unbind('click').die('click');
			//$(this).find('a').unwrap();
			$(this).find('.fileDesc:not(:first)').remove();
			
			imgFile = $(this).find('a:first').attr('href');
			vidFile = $(this).find('a:not(:first)').attr('href');
			
			$(this).find('a:first').remove();
			$(this).find('br').remove();
			$(this).prepend('<div class="vidOverlay"><img src="'+imgFile+'" /></div>');
			$(this).find('a').empty().attr('id', 'vidItem'+vidCount).attr('href', baseUrl + vidFile).attr('class', 'vidBox');
			$(this).find('.fileDesc').remove();
			
			$(this).append('<div id="vidControl'+vidCount+'"></div>');
			
			vidCount = vidCount + 1;
		});
	}
	
	
	function resetNavi() {
		$('#mainNavi li').each(function () {
			$(this).removeClass('active');
		});
	}
	
	
	function resetGaleryCategories(obj) {
		$('#galCats').find('a').each(function() {
			$(this).removeClass('act');
		});
			
		obj.addClass('act');
	}
	
	
	/* * *
	* Prüfen, ob ein Querystring an der URL hängt
	* getVar @type entsprechend anhängen
	*
	* @currentLink -> Link der von ajax geladen werden soll
	*/
	function checkInnerLink(currentLink) {
		splits  = currentLink.split('?');
		if(splits.length > 1) {
		    return currentLink+'&type=55';
		} else {
		    return currentLink+'?type=55';
		}
	}
	
	
	/* * *
	* Link auf bestimmten String prüfen
	* 
	* @currentLink -> zu prüfender Link
	* @part -> String
	*
	* Ist @part in @currentLink enthalten -> return true
	*/
	function checkSpecialLink(currentLink, part) {
		splits = currentLink.split(part);
		if(splits.length > 1) {
		    return true;
		} else {
		    return false;
		}
	}
	
	

	
});
