/* Author: Kilian Schefer */

var ui = {
	viewportWidth:0,
	viewportHeight:0,
	mainNavigationHeight:0,
	crossfadeFolder:'1680x1050',
	crossfadeImages:["01.jpg","02.jpg","03.jpg","04.jpg","05.jpg","06.jpg","07.jpg","08.jpg","09.jpg","10.jpg","11.jpg","12.jpg"],
	stadelmaierCrossfadeImages:["01.jpg","02.jpg","03.jpg","04.jpg","05.jpg","06.jpg","07.jpg","08.jpg"],
	crossfadeCurrentImage:0,
	crossfadeTimer:'',
	siteTitle:'',
	contentWasDisplayed:false,
	startPath:'',
	mobile:0,
	mobile_lastnav:'',
	branch_id:0,
	lang:'de',
		
	init: function(start_path,branch_id,mobile,lang) {
		if(start_path !== undefined && start_path != '' && location.hash == '' && !mobile) {
			location.href = '#!/'+start_path;
		}
		
		$.address.change(function(event) {
			ui.getContent(event.value);
		});

		
		if(mobile !== undefined) ui.mobile = mobile;
		if(lang !== undefined) ui.lang = lang;
		if(ui.mobile == 0) {
			ui.getViewportSize();
			ui.resizeCrossfade();
			ui.startCrossfade();
			ui.resizeNavigation();
		}
		ui.siteTitle = document.title;
		ui.branch_id = branch_id;
	},
	getViewportSize: function() {
		ui.viewportWidth = $(window).width();	
		ui.viewportHeight = $(window).height();
		
		if(ui.branch_id > 1) ui.mainNavigationHeight = $('.main-navigation-wrapper').outerHeight()+390;
		else ui.mainNavigationHeight = $('.main-navigation-wrapper').outerHeight()+480;
		
		if(ui.viewportHeight < ui.mainNavigationHeight) ui.viewportHeight = ui.mainNavigationHeight;
	},
	/* Crossfade BG */
	startCrossfade: function() {
		
		$('.crossfade').height(ui.viewportHeight);
		ui.crossfadeFolder = ui.getCrossfadeFolder();
		$('.crossfade-visible,.crossfade-static').css('zIndex',1).fadeIn(0);
		if($('#crossfade1').length == 0 && $('#crossfade2').length == 0) return;
		ui.crossfadeTimer = setInterval(function() {
			$('.crossfade-hidden').css('zIndex',2).fadeIn(2000,function() {
				ui.crossfadeCurrentImage += 1;
				$('.crossfade-visible').addClass('crossfade-hidden').removeClass('crossfade-visible').hide();
				$(this).addClass('crossfade-visible').removeClass('crossfade-hidden').css('zIndex',1);
				if(ui.branch_id == 24) $('.crossfade-hidden').css('backgroundImage','url(/images/stadelmaier-akustik/'+ui.crossfadeFolder+'/'+ui.stadelmaierCrossfadeImages[(ui.crossfadeCurrentImage+1)%ui.stadelmaierCrossfadeImages.length]+')');
				else $('.crossfade-hidden').css('backgroundImage','url(/images/'+ui.crossfadeFolder+'/'+ui.crossfadeImages[(ui.crossfadeCurrentImage+1)%ui.crossfadeImages.length]+')');
			});
		},10000);		
	},
	resizeCrossfade: function() {
		var visibleImage = $('#crossfade1').css('backgroundImage');
		var hiddenImage = $('#crossfade2').css('backgroundImage');
		
		var oldCrossfadeFolder = ui.crossfadeFolder;
		ui.getViewportSize();
		ui.crossfadeFolder = ui.getCrossfadeFolder();
		$('.crossfade').height(ui.viewportHeight);
		if(oldCrossfadeFolder != ui.crossfadeFolder) {
			if($('#crossfade1').length > 0) $('#crossfade1').css('backgroundImage',visibleImage.replace(oldCrossfadeFolder,ui.crossfadeFolder));
			if($('#crossfade2').length > 0) $('#crossfade2').css('backgroundImage',hiddenImage.replace(oldCrossfadeFolder,ui.crossfadeFolder));	
		}
	},
	getCrossfadeFolder: function() { 
		var crossfadeFolder = 0;
		if(ui.viewportWidth > 1680) crossfadeFolder = '1920x1080';
		else if(ui.viewportWidth > 1280) crossfadeFolder = '1680x1050';
		else if(ui.viewportWidth <= 1280 && ui.viewportHeight > 800) crossfadeFolder = '1280x1024';
		else crossfadeFolder = '1280x800';	
		return crossfadeFolder;	
	},
	/* Navigation */
	resizeNavigation: function() {
		$('.scroll-rail-visible').height($(window).height());
		$('.navigation-wrapper').height(ui.viewportHeight+10);
		$('.navigation-inner-wrapper').height(ui.viewportHeight);
		$('.content-wrapper').css('minHeight',ui.viewportHeight-20);
	},
	/* Content */
	getContent: function(path) {		
		if(path != '/' && path != ui.mobile_lastnav) {
			var arrPath = path.split("/");
			var level = (arrPath.length-3);
			if(ui.mobile && $('a[href$="'+ui.getPartialPath(arrPath,1)+'"]').length == 1 && level == 0 && $('a[href$="'+ui.getPartialPath(arrPath,1)+'"]').parent('li').find('div').length > 0) {
				ui.markActiveNavigation(path);
				ui.mobile_lastnav = path;
				return false;
			}
			$.ajax({
				url: "?path="+path,
				context: document.body,
				dataType:'jsonp',
				success: function(data){
					if(data.content !== undefined && data.content != '') {
						if(ui.mobile) {
							$('.mobile-slide').animate({left:'-524px'},500);
							$('.content-wrapper').html(data.content).css('display','block');
							if(ui.lang == 'fr') {
								$('.content-wrapper').prepend('<a href="/fr/#!'+ui.mobile_lastnav+'" class="navigation-control">retour</a>');								
							} else {
								$('.content-wrapper').prepend('<a href="/de/#!'+ui.mobile_lastnav+'" class="navigation-control">zur&uuml;ck</a>');
							}
							$('#main').height($('.content-wrapper').outerHeight());
						} else {
							$('.content-wrapper').html(data.content).stop(true,true).fadeIn();	
						}
						document.title=data.title+' - '+ui.siteTitle;
						
						ui.initGallery();
						ui.initLightbox();
						ui.initFormHandler();
						ui.markActiveNavigation(path);
					} else {
						$('.content-wrapper').html('<div class="text text-first"><h1>Sorry</h1><p class="lead">No content was found.</p></div>\r').fadeIn();	
					}
				},
				beforeSend:function(){
					$('.content-wrapper').html('<div class="loader-wrapper"><img src="/images/load.gif" border="0" class="load"></div>').fadeIn();
        		},
				error:function(){
					document.title='Kein Inhalt - '+ui.siteTitle;
					/*$('.content-wrapper').html('<div class="text text-first"><h1>Gummibärchen</h1>\r<p class="lead">Freilebende Gummibärchen gibt es nicht. Man kauft sie in Packungen an der Kinokasse. Dieser Kauf ist der Beginn einer fast erotischen und sehr ambivalenten Beziehung Gummibärchen-Mensch. Zuerst genießt man. Dieser Genuß umfaßt alle Sinne. Man wühlt in den Gummibärchen, man fühlt sie. Gummibärchen haben eine Konsistenz wie weichgekochter Radiergummi. Die Tastempfindung geht auch ins Sexuelle. Das bedeutet nicht unbedingt, daß das Verhältnis zum Gummibärchen ein geschlechtliches wäre, denn prinzipiell sind diese geschlechtsneutral. Nun sind Gummibärchen weder wabbelig noch zäh; sie stehen genau an der Grenze. Auch das macht sie spannend. Gummibärchen sind auf eine aufreizende Art weich. Und da sie weich sind, kann man sie auch ziehen.</p></div>\r').fadeIn();*/
					$('.content-wrapper').html('<div class="text text-first"><h1>Kein Inhalt</h1>\r<p class="lead">Bitte fügen Sie dieser Seite einen Inhalt hinzu.</p></div>\r').fadeIn();
					ui.markActiveNavigation(path);
				}

			});	
		} else {
			if(ui.mobile) {
				$('.mobile-slide').animate({left:'0'},500);
				$('.content-wrapper').empty();
				$('#main').height($('.navigation-wrapper').outerHeight());
			} else {
				$('.content-wrapper').stop(true,true).fadeOut();
			}
			ui.markActiveNavigation(path);
		}
	},
	initFormHandler: function() {
		$('#contact-form input[type="submit"]').click(function() {
			var error = [];
			
			var $email = $('#contact-form input[name="email"]');
			var $name = $('#contact-form input[name="name"]');
			var $firstname = $('#contact-form input[name="firstname"]');
			var $zipcity = $('#contact-form input[name="zipcity"]');
			
			if($email.val().indexOf('@') == -1 || labels['email'] == undefined || labels['email'] == $email.val()) error.push('email');
			if($name.val() == '' || labels['name'] == undefined || labels['name'] == $name.val()) error.push('name');
			if($firstname.val() == '' || labels['firstname'] == undefined || labels['firstname'] == $firstname.val()) error.push('firstname');
			if($zipcity.val() == '' || labels['zipcity'] == undefined || labels['zipcity'] == $zipcity.val()) error.push('zipcity');
			
			if(error.length == 0) {
				$('#contact-form').ajaxSubmit(function(data) { 
					if(data != '') {
						alert(data);
						$('#contact-form').resetForm();
						$('#contact-form input[type="text"]').css('backgroundColor','#fff');
					} else {
						alert('Error!');	
					}
				});
				return false; 
			} else {
				$('#contact-form input[type="text"]').css('backgroundColor','#fff');
				$.each(error,function(i,val) {
					$('#contact-form input[name="'+val+'"]').css('backgroundColor','#ffcccc');
				});
				return false;
			}
		});
	},
	initLightbox: function() {
		$(".lightbox a").fancybox({
			'transitionIn'	: 'elastic',
			'transitionOut'	: 'elastic',
			'easingIn'      : 'easeOutBack',
			'easingOut'     : 'easeInBack',
			'titlePosition'  : 'over',
			'overlayColor'	: '#000'
		});
		$(".gallery_lightbox a").fancybox({
			'transitionIn'	: 'elastic',
			'transitionOut'	: 'elastic',
			'easingIn'      : 'easeOutBack',
			'easingOut'     : 'easeInBack',
			'titlePosition'  : 'over',
			'overlayColor'	: '#000'
		});
	},
	markActiveNavigation: function(path) {		
		var arrPath = path.split("/");
		var level = (arrPath.length-3);
		
		// reset all active nav points	
		$('.main-navigation-wrapper li a,.bottom-navigation-wrapper li a,.level3-toc li a').removeClass('active'); 
		
		// no highlighting on empty path
		if(path != '/') {
			var $active1 = $('a[href$="'+ui.getPartialPath(arrPath,1)+'"]').addClass('active');
			if(ui.mobile) var $active2 = $('a[href$="'+ui.getPartialPath(arrPath,2)+'"]');
			else var $active2 = $('a[href$="'+ui.getPartialPath(arrPath,2)+'"]').addClass('active');
			var $active3 = $('a[href$="'+ui.getPartialPath(arrPath,3)+'"]').addClass('active');
		}
		
		// don't close subnavigation if we are using 3rd level navigation
		if(level < 2) {
			var openNav = $('.main-navigation-wrapper li div');
			$.each(openNav,function(i,elem) {
				if($(elem).css('display') == 'block' && $(elem).find('a.active').length == 0  && $(elem).parent().find('a.active').length == 0) $(elem).stop(true,true).hide("blind",500)
			});	
		}
		
		// open subnavigation if not already open and is child of currently active main navigation	
		if($active1 != undefined) {
			if($active1.length == 0 && $active2.length == 2) {
				$.each($active2,function(i,elem) {
					if($(elem).parent().parent().hasClass('main-navigation-wrapper')) $active1 = $(elem);
				});
			} else {
				$active1 = $active2.parents('ul.main-navigation-wrapper li').find('>a');
				$active1.addClass('active');
			}
			if($active1.parent().find('div').length > 0 && $active1.parent().find('div').css('display') != 'block') $active1.parent().find('div').stop(true,true).show("blind",500,function() {
				ui.getViewportSize();
				ui.resizeCrossfade();
				ui.resizeNavigation();					
			});
		}
		
		/*if(level < 2) $('.main-navigation-wrapper li a,.bottom-navigation-wrapper li a').removeClass('active'); // reset all active nav points
		else $('.level3-toc li a').removeClass('active');
		
		if(path != '/') {	
			$active = $('a[href$="'+path+'"]');
			$active.addClass('active');
			$active.parents('li').find('>a').addClass('active');
		}
		if(level < 2) {
			var openNav = $('.main-navigation-wrapper li div');
			$.each(openNav,function(i,elem) {
				if($(elem).css('display') == 'block' && $(elem).find('a.active').length == 0  && $(elem).parent().find('a.active').length == 0) $(elem).stop(true,true).hide("blind",500)
			});	
			if($('.active').parent().find('div').length > 0 && $('.active').parent().find('div').css('display') != 'block') $('.active').parent().find('div').stop(true,true).show("blind",500);			
		}*/		
	},
	getPartialPath: function(arrPath,level) {
		var output = [];
		$.each(arrPath,function(i,value) {
			if(value == '') return true;
			if(i <= level && value != '') output[(i-1)] = value;
		});
		return "/"+output.join("/")+"/";		
	},
	/* Gallery Module */
	initGallery: function() {
		$.each($('.gallery'),function(i,g) {
			var slidesCount = $(g).find('.gallery-slide img').length;
			var currentSlide = 1;
			
			/* Slideshow Mode */
			if($(g).find('.gallery-caption .caption').length == 0 || slidesCount == 1) {
				$('.gallery-slide',g).addClass('gallery-slideshow');
				$('.gallery-control,.gallery-caption',g).css('display','none');
				$('.gallery-slideshow').cycle({
					fx:'fade',
					speed:1500, 
					timeout:2750
				});
				return;
			}
			
			/* Slidepage Mode */
			ui.showGalleryImageXFromY(g,currentSlide,slidesCount);
			ui.showGalleryImageCaption(g,currentSlide);
			$('.btn-arrow-left',g).click(function() {
				if(currentSlide > 1) {
					currentSlide--;
					ui.showGalleryImageXFromY(g,currentSlide,slidesCount);
					ui.showGalleryImageCaption(g,currentSlide);
					ui.slideGallery(g,-1);
				}
			});
			
			$('.btn-arrow-right',g).click(function() {
				if(currentSlide < slidesCount) {
					currentSlide++;
					ui.showGalleryImageXFromY(g,currentSlide,slidesCount);
					ui.showGalleryImageCaption(g,currentSlide);
					ui.slideGallery(g,1);
				}
			});
		});
	},
	slideGallery: function(g,diff) {
		if(diff == 1) $('.gallery-slide',g).stop(true,true).animate({left:'-=417px'},750);
		else $('.gallery-slide',g).stop(true,true).animate({left:'+=417px'},750);
	},
	showGalleryImageCaption: function(g,curr) {
		$('.caption',g).css('display','none');
		$('.caption:nth-child('+curr+')',g).css('display','block');
	},
	showGalleryImageXFromY: function(g,curr,total) {						
		if(curr == 1 && total > 1) {
			$(g).find('.btn-arrow-left').removeClass('btn-enabled');
			$(g).find('.btn-arrow-right').addClass('btn-enabled');
		} else if(curr == total && total > 1) {
			$(g).find('.btn-arrow-right').removeClass('btn-enabled');
			$(g).find('.btn-arrow-left').addClass('btn-enabled');			
		} else if(total > 1) {
			$(g).find('.btn-arrow-right').addClass('btn-enabled');
			$(g).find('.btn-arrow-left').addClass('btn-enabled');
		}
		$('.gallery-control span',g).html(curr+' / '+total);
	}
}
