
(function($){
	$(document).bind('ready', function(){
		if (location.hash== '') {
			window.location.href='#home';
		}
		/*
		$("a[rel^='prettyPhoto']").prettyPhoto({
			deeplinking: false, 
			social_tools:false
				
		});
		*/
		
		$('#movieplayer').hide();	
		$('#home').bind('showPage hidePage', function (e, attr){
			//console.log(e.type, attr);
			switch(e.type){
				case 'showPage': $('#movieplayer').slideDown(); break;
				case 'hidePage': $('#movieplayer').slideUp(); break;	
			}
		})
		
		
		$('section[role=page]').pageSlider();
		$('.fader').ivsFader();
		$('.slider .pageWrap').ivsSlider();
		
		
		// buttons
		$('a.toggleFeedback').click(function(){
			$('#feedback .form').trigger('toogle');
			return false;
		});
		$('#feedback .form').bind('show hide toogle', function(e){
			switch(e.type){
				case 'hide':	
					$(this).slideUp('fast', function(){			
						$('#main').css('opacity', 1);	
						$('a.toggleFeedback').text('Feedback');	
					});
				break;
				case 'show':	
					$(this).slideDown('fast', function(){
						$('#main').css('opacity', 0.3);
						$('a.toggleFeedback').text('close');	
					});
				break;
				case 'toogle':			
					if ($(this).css('display') == 'none')	$(this).trigger('show');
					else 									$(this).trigger('hide');
				break;
			}			
		});
		$('.popup').ivsPopup();
		
		$('a.switcher').click(function(){
			//$(this.hash+'_hash').trigger('show');
		})
		$("#feedbackForm").validationEngine('attach', {
                    isOverflown: true,
                    overflownDIV: "#feedback"
                    
        });
		$("#feedbackForm")
			.bind("jqv.form.result", function(event , errorFound){
				if(errorFound) {
					//$("#hookError").append("There is some problems with your form");
					return false;		
				}
				$(this).trigger('send');
				return false;
			})
			.submit(function(){	
				return false;	
			})
			.bind('send', function(){
				var $this = $(this);
				var url = $(this).attr('action');
				var _data = $(this).serializeArray();
				$.post(url, _data, function(dataX){		
				  	if (dataX.hasError == null)
				  	{
				  		$('feedbackReturn').text('');
						$('#feedback .form').trigger('hide');
					  	$this.children('input').attr('value', '');
					  	$this.children('textarea').val('');
					  	alert('E-Mail verschickt');
					} else {
				  		$('feedbackReturn').text('Bitte Eingabe überprüfen!');
						//$.each(dataX.errorMsg, function(){}	
					}
				} , "json");
				//$(this).stop();
				//return false;
			})
		
		
		// videoplayer
		jwplayer('playerWrapper').setup({
				'flashplayer': 'js/libs/player.swf',
				'id': 'player',
				'width': '940',
				'height': '400', 
				'backcolor': '000000',
			    'frontcolor': '666666',
			    'lightcolor': '333333',
			    'screencolor': '000000',
			    'controlbar': 'over',
			    'image': 'data/video/IMAGINE_Showreel_2011.jpg',
			    'file': 'data/video/IMAGINE_Showreel_2011.mp4'
				//'file': '/data/GFK_short.flv'
		});
		/*
		$('dl.hoverable').bind('mouseover mouseout', function(e){
			var bgImg = $(this).find('img.hoverImg').first();
			if (bgImg.length == 0)
			{
				$(this).unbind(e.type);	
				return false;		
			}
			switch (e.type) {
				case 'mouseover':
					bgImg.attr('src', bgImg.attr('hover'));
				break;
				case 'mouseout':
					bgImg.attr('src', bgImg.attr('out'));
				break;
			}	
		})
		*/
		$(window).bind( "hashchange", function(e) {
			$(location.hash+'_hash').trigger('showPage', '167');
		});
		$(window).trigger('hashchange');
	})		
}(jQuery));



(function($){
	var curSection = $('section[role=page]').first()[0];
	var curPos = 0;
	var curHeight =0;
	function moveToEl(el, info){
		//console.log('movetoEl',el, info);
		if (el == null) return false;
		if (el.position() == null) return false;
		var moveToPos = -(el.position().top);
		var newSliderHeight = el.outerHeight();
		
		if (newSliderHeight != curHeight){
			// passt groesse an
			curHeight = newSliderHeight;
			$('#main').stop().animate({"height": newSliderHeight}, "fast" );
		}
		if (moveToPos != curPos){
			// bewegt slider auf aktuelles element
			curPos = moveToPos;  		
	    	$('#main .main').stop().animate({"top": moveToPos}, "slow");
	    }
	}
	$.fn.pageSlider = function(){	
		curSection = $('section[role=page]').first()[0];	
		$('#main').css('overflow','hidden'); 
		$('#main').css('position','relative');
		$('#main .main').css('position','relative'); 
		$('#main .main').bind('heightChange', function(e){			
			moveToEl($(location.hash+'_hash'), {'line':170});
	    });
		return this.each(function(){
			if (location.hash ==  '#'+$(this).attr('id')) curSection = $(this);
			$(this).data('origHash', $(this).attr('id'));
			$(this).attr('id', $(this).attr('id')+'_hash');
			$(this).bind('showPage', function(e, attr){
				$(this).children().trigger('showFromPage');
				$(this).addClass('active');
				if (location.hash != '#'+$(this).data('origHash')) {
					window.location.href = '#'+$(this).data('origHash');
					return false;	
				}
				if (curSection != this && curSection[0] != this) {$(curSection).trigger('hidePage', {'line':178, 'curSection': curSection, 'this': this});	}	
				curSection = this;		
				$this = $(this);			
				moveToEl($this, {'line':186});
				/*
				var moveToPos = -($this.position().top);				
	            $('#main').stop().animate({"height": $this.outerHeight()}, "fast" )  
	            $('#main .main').stop().animate({"top": moveToPos}, "slow");	            
				*/
				$('#mainNav nav').find('a.switcher').each(function(){
					if (location.hash == '#home')	{						
						 $(this).slideUp();
					} else if (this.hash == location.hash) 	{
						 $(this).slideUp().addClass('active');
					} else 	{
						if($(this).css('display') == 'none'){
							$(this).slideDown().removeClass('active');							
						}
					}	
				})
			});
				
			$(this).bind('hidePage', function(){
				$(this).removeClass('active');
				$(this).children().trigger('hideFromPage');
				$(document).find('video').each(function(){
					this.pause();
				});
			});
			
			//if ($(this).hash != location.hash) $(this).trigger('hide');			
		})
		$(curSection).trigger('showPage', '201');
	}
	
}(jQuery));



(function($){
	var that;
	var html5Content
	var baseOptions = {
		modal: false,
		target: null,
		src:null,
		width: 940,
		height: 396
	};
	function useJwplayer(options){		
		jwplayer(options.target).setup({
				'flashplayer': 'js/libs/player.swf',
				'id': options.target+'_player',
				'width': options.width,
				'height': options.height, 
				'backcolor': '000000',
			    'frontcolor': '666666',
			    'lightcolor': '333333',
			    'screencolor': '000000',
			    'controlbar': 'over',
				'file': options.src,
				'autostart': true
		});
	}
	function useJwplayerHtml5(options){
		html5Content = '';
		html5Content = that.find('video').clone();
		var id = html5Content.attr('id') || options.target+'_html5'+'_'+Math.random();
			id+='_html5';
		html5Content.attr('id', id);		
		$('#'+options.target).append(html5Content);
		
		jwplayer(id).setup({
	    	'id': id+'_player',
			'width': options.width,
			'height': options.height, 
			'backcolor': '000000',
			'frontcolor': '666666',
			'lightcolor': '333333',
			'screencolor': '000000',
			'controlbar': 'over',
			'file': options.src,
			'autostart': true,
	    	modes: [
	        	{ type: 'html5' },
	        	{ type: 'flash', src: '/js/libs/player.swf' }
	    	]
  		});
  		
	}
	$.showVideo = function(options)
	{
		that = options.opener;
		options = $.extend({},baseOptions, options);
		if (options.modal)
		{
			$modalContent = $('<div id="'+options.target+'" style="width:'+options.width+'px; height:'+options.height+'px;" /><a class="closeButton simplemodal-close">x</a>');	
			$.modal($modalContent, {
					opacity: 100,
					overlayClose: true
			});
		}
		//useJwplayer(options);
		useJwplayerHtml5(options);
		/*
		jwplayer(options.target).setup({
				'flashplayer': 'js/libs/player.swf',
				'id': options.target+'_player',
				'width': options.width,
				'height': options.height, 
				'backcolor': '000000',
			    'frontcolor': '666666',
			    'lightcolor': '333333',
			    'screencolor': '000000',
			    'controlbar': 'over',
				'file': options.src,
				'autostart': true
		});
		*/
	}
}(jQuery));

(function($){
	var baseOptions = {
		modal: true,
		target: null
	};
	var curEl, curId, curCenteredPic,  options, content, elements, counter;
	
	function wrapper(){
		content = $('<div id="'+options.target+'"  class="galleryPopup" />');			
		content.bigPicture = $('<div class="inner" style="overflow:hidden;"></div>').appendTo($('<div id="'+options.target+'_big" class="bigPicture modalCloseImg""></div>').appendTo(content));
		content.overview = $('<div class="scroller" style="position:relative" />').appendTo($('<div id="'+options.target+'_overview" class="overview"></div>').appendTo(content));
		//content.close = $('<a class="closeButton simplemodal-close">x</a>').appendTo(content);
		
		$('<div class="picNavi"><span class="button prev">&lt;</span><span class="button next">&gt;</span><a class="closeButton simplemodal-close">x</a></div>').appendTo(content.bigPicture);
		$('<div class="picNavi"><span class="buttonWrap prev">&lt;</span><span class="buttonWrap next">&gt;</span></div>').insertBefore(content.overview);
		
		content.bigPicture.find('.button').hide();		
		content.bigPicture.delegate('span.prev', 'click', function(){
			toPrev();	
		})
		content.bigPicture.delegate('span.next', 'click', function(){
			toNext();	
		})
		content.overview.parent().find('.buttonWrap').wrapInner('<div class="button" />');	
		content.overview.parent().find('.button').hide();		
		content.overview.parent().delegate('span.prev .button', 'click', function(){
			moveToPrev();	
		})
		content.overview.parent().delegate('span.next .button', 'click', function(){
			moveToNext();	
		})
		return content;
		
	}	
	
	function checkButtons(){
		content.bigPicture.find('.button').css('height', content.bigPicture.height());
		if (curId >= elements.length -1)	{content.bigPicture.find('span.next').fadeOut();}
		else 							{content.bigPicture.find('span.next').fadeIn();}
		if (curId <= 0)					{content.bigPicture.find('span.prev').fadeOut();}
		else 							{content.bigPicture.find('span.prev').fadeIn();}	
	}
	function toPrev(){		
		showPic(Number(curId)-1);
	}
	function toNext(){			
		showPic(Number(curId)+1);
	}
	function moveToNext(){
		centerOverviewPic(curCenteredPic.next(), 'fast');
	}
	function moveToPrev(){
		centerOverviewPic(curCenteredPic.prev(), 'fast');
	}
	function centerOverviewPic(pic, speed){
		curCenteredPic = pic;
		if (pic.hasClass('first'))	{content.overview.parent().find('.prev .button').fadeOut()}
		else 						{content.overview.parent().find('.prev .button').fadeIn();}
		if (pic.hasClass('last'))	{content.overview.parent().find('.next .button').fadeOut()}
		else 						{content.overview.parent().find('.next .button').fadeIn();}
		newPos = (	(content.overview.parent().width()- pic.width()) /2);
		newPos = (newPos - pic.position().left);
		moveScroller(newPos, speed);
	}
	function moveScroller(pos, speed){
		if (speed == null) speed = 'slow';
		content.overview.animate({'left': pos}, speed);	
	}
	function getWidth(){
		
	}
	function showPic(id){
		//if (id == curId) return false;
		$element = elements[id];
		//console.log(id);
		curEl = content.bigPicture.find('img.big');
		newEl = $('<img class="big" src="'+$element.big+'" height="500"  />').hide();
		if (curEl.length >0)
		{
			oldPos = curEl.position();
			curEl.fadeOut('slow', function(){$(this).remove();});
			newEl.appendTo(content.bigPicture);
		}
		else {
			content.bigPicture.append(newEl);
		}
		
		newEl.bind('load', function(e){
			newEl.fadeIn('fast', function(){
				newWidth = $(this).width()+80;
				content.bigPicture.animate({'width':newWidth}, 'fast');
			});
		});
		content.trigger('showPic', id);
		curId =id;
		checkButtons();
	}
	function addElement(el){
		el.id = counter;
		miniPic = $('<img class="miniPic" src="'+el.small+'" height="100" index="'+counter+'" style="float:left;" />').hide();
		miniPic.click(function(){
			showPic($(this).attr('index'));	
		});
		counter++;
		elements.push(el);
		content.overview.append(miniPic);
		miniPic.bind('load', function(e){
			$(this).fadeIn('fast', function(){
				content.overview.width((content.overview.width() + $(this).width()));
			});
		});
	}
	function setElements(el){
		elements = [];
		$(el).children('dd').each(function(){
			$element = {
				'title': $(this).attr('title') || 'kein Titel',
				'small': $(this).children('span').first().attr('src'),
				'big': $(this).attr('src')				
			}	
			addElement($element);
		});
		content.overview.children('.miniPic').first().addClass('first');
		content.overview.children('.miniPic').last().addClass('last');
		return elements;
	}
	function init(el){
		counter = 0;
		content = wrapper();
		elements = setElements(el);
		
		content.bind('showPic', function(e, picId){
			curOverviewPic = content.overview.children('[index="'+picId+'"]');
			content.overview.children('.active').removeClass('active');
			curOverviewPic.addClass('active');
			centerOverviewPic(curOverviewPic);
		})
		
		content.bind('click', function(e){
			if (e.target == content || e.target == content.bigPicture.parent()[0]){
				$.modal.close(); 
			}
		})
		
		$.modal(content, {opacity:100, overlayClose:true});		
		showPic(0);	
	}
	$.showGallery = function (el, _options)
	{
		options = $.extend({},baseOptions, _options);
		return init(el);
		content = $('<div id="'+options.target+'" class="galleryPopup" />');	
		content.bigPicture = $('<div id="'+options.target+'_big" class="bigPicture"></div>').appendTo(content);
		content.overview = $('<div id="'+options.target+'_overview" class="overview"></div>').appendTo(content);
		content.close = $('<a class="closeButton simplemodal-close">x</a>').appendTo(content);
		var childEls =  $(el).children('dd');
			childEls.first().addClass('first');
			childEls.last().addClass('last');
		content.bigPicture.html('<img src="'+childEls.first().attr('src')+'" height="400" />');
			childEls.each(function(){
				var $childEl = $(this);
				$miniPic = $($childEl.html());
				content.overview.append($miniPic);
				$miniPic.click(function(){
					content.bigPicture.html('<img src="'+$childEl.attr('src')+'" height="400"  />');
				});	
			})
		$.modal(content, {opacity:100, overlayClose:true});
		
	}
}(jQuery));



(function($){
	$.fn.ivsPopup = function (){
		return this.each(function(){
			$(this).bind('click', function(){
				$popupcontent  = $(this).children().first();
				if ($popupcontent.attr('type') == 'video')
				{
					$.showVideo({'opener': $popupcontent, 'modal': true, 'target':'popup', 'src': $popupcontent.attr('src'), 'width': '854', 'height': '480'});	
				}
				else {
					$.showGallery($popupcontent, {
						modal:true,
						target:'popup'	
					})
				}
				return false;
			})	
		});
	}
	
}(jQuery));



(function($){
	var timer = 2500;
	var faderHeight = 0;
	function initFader(el) {
		$faderWrapper = $('<div class="faderWrapper" style="position:relative; overflow:hidden;" />');
		$(el).wrapInner($faderWrapper);
		var childEls = $(el).children('.faderWrapper').children('dl');		
		$(el).data('childEls', childEls);
		var buttonBar = $('<div class="buttonBar" />');
		$(el).children('.faderWrapper').append(buttonBar);			
		$(el).data('buttonBar', buttonBar);
		
		childEls.each(function(index){
			$curEl  = $(this);
			var buttonTitle = $(this).attr('title');		
			$button = $('<span />')
				.text(buttonTitle)
				.appendTo(buttonBar)
				.data('dest', $curEl)
				.addClass('button')
				.attr('index', index)
				.click( function(){	
					fadeTo($(el), index);
				})
			
		});
		$firstEl 	= childEls.first();
		$lastEl 	= childEls.last();
		$(el).data('firstEl',	$firstEl);
		$(el).data('lastEl', 	$lastEl);
		//$(el).data('currentEl', $firstEl);
		$(el).bind('show hide', function(e){
			switch (e.type){
				case 'hide': stopFader(this); break;
				case 'show': startFader(this);	break;
			}
		})
		//$(el).css('position', 'relative');
		childEls.hide().css('position', 'absolute');
		fadeTo($(el), 0);
	}
	function fadeTo(fadeGroup, index){		
		$hideEl 	= $(fadeGroup).data('currentEl') || null;
		$showEl 	= $($(fadeGroup).data('childEls')[index]);	
		$buttons 	= $(fadeGroup).data('buttonBar');	
		if ($showEl.length == 0) $showEl = $(fadeGroup).data('firstEl');
		if ($hideEl && $showEl[0] == $hideEl[0]) return false;
		if ($hideEl) $hideEl.fadeOut(500);
		$showEl.fadeIn('fast', function(){
			$(fadeGroup).children('.faderWrapper').height($(this).height())	;
			$(fadeGroup).trigger('heightChange');	
		});
		
		$buttons.children('.active').removeClass('active');
		$buttons.children('[index='+index+']').addClass('active');
		
		$(fadeGroup).data('currentEl', $showEl);
		
	}
	function fade(el){
		var hideEl = $(el).data('currentEl');
		fadeTo($(hideEl).next());
		var showEl = $(hideEl).next();
	}
	function loop(el){
		var step = $(el).data('step') || 1;
		if (el.loop == 1)
		{
			
			if (step == 4)
			{
				step = 0;
				fade(el);
			}
			step++;
			$(el).data('step', step);
			setTimeout(loop, timer, el);
		}	
	}
	function startFader(el){
		el.loop = 1;
		//loop(el);     
	}
	function stopFader(el){	
		el.loop = 0;
	}
	$.fn.ivsFader = function(){
		this.each(function(){
			initFader(this);
		});				
	}
	
}(jQuery));


(function($){
		
	function toPrev(wrapper){
		moveWrapper(wrapper, wrapper.data('currentEl').prev('li').first());
	}
	function toNext(wrapper){		
		moveWrapper(wrapper, wrapper.data('currentEl').next('li').first());
	}
	function toIndex(wrapper, index){
		$el = wrapper.children('li')[index];
		moveWrapper(wrapper, $($el));
	}
	function jumpToIndex(wrapper, index){
		$el = wrapper.children('li')[index];
		jumpTo(wrapper, $($el));
	}
	function jumpTo(wrapper, el){
		if ($(el).position() == null) return false;
		var curEl =  wrapper.data('currentEl');
		$(curEl).trigger('hide');
		$(el).trigger('show');
		$(curEl).removeClass('active');
		$(el).addClass('active');
		wrapper.data('currentEl', el);
				
		var newPos = - el.position().left;
		$(wrapper).stop().css('left', newPos);
		update(wrapper, el);
	}
	function moveWrapper(wrapper, el){		
		if ($(el).position() == null) return false;
		var curEl =  wrapper.data('currentEl');
		$(curEl).trigger('hide');
		$(el).trigger('show');
		$(curEl).removeClass('active');
		$(el).addClass('active');
		wrapper.data('currentEl', el);
		
		var newPos = - el.position().left;
		$(wrapper).stop().animate({'left':newPos}, 'slow');		
		
		update(wrapper, el);
	}
	function update(wrapper, el){
		
		var infotextBox = wrapper.parent().data('infotextBox');
		infotextBox.html($(el).data('infotext'));

		var newHeight = $(el).height();
		$(wrapper).parent().parent().find('.sliderPagination .button').removeClass('active');
		$(wrapper).parent().parent().find('.sliderPagination .button[index="'+$(el).attr('index')+'"]').addClass('active');
		$(wrapper).parent().animate({'height': newHeight}, 'fast', function(){
			$(wrapper).trigger('heightChange');	
			setButtonPos(this);
		});
	}
	function setButtonPos(wrapper){
		var newHeight = $(wrapper).height();
		var slider = $(wrapper).data('slider');
		var curEl = slider.data('currentEl');
		if ($(curEl).hasClass('first')){
			$(wrapper).parent().find('.sliderControl .prev').hide();
		}else {
			$(wrapper).parent().find('.sliderControl .prev').show();			
		}
		if ($(curEl).hasClass('last')){
			$(wrapper).parent().find('.sliderControl .next').hide();			
		}else {
			$(wrapper).parent().find('.sliderControl .next').show();			
		}
		//console.log(newHeight-(100)/2, wrapper);
		$(wrapper).parent().find('.sliderControl .button').height(100);
		$(wrapper).parent().find('.sliderControl .button').animate({'top':(newHeight/2 - 50)}, 'fast');
		//$(wrapper).parent().find('.sliderControl .button').css('top', (newHeight-(100)/2));
		//$(wrapper).parent().find('.sliderControl .button').animate({'height':newHeight}, 'fast');
	}
	$.fn.ivsSlider = function(){
		this.each(function(){			
			$this  = $(this);
			$(this).parent().bind('showFromPage', function(e){
				var tempWrapper = $(this).find('.slidingWrapper');
				jumpToIndex(tempWrapper, 0)	
			})
			// add an infotext block after the slideable Content
			$(this).data('infotextBox', $('<div class="pageWrap infotextWrapper">InfotextWrapper</div>').insertAfter($(this)));
			
			var elWidth = $(this).width();
			$(this).css('overflow', 'hidden').css('position', 'relative');
			var wrapper = $(this).children('ul');
			$(wrapper).delegate('li.active', 'heightChange', function(e){
				update(wrapper, e.target);
			});			
					
			
			$(this).data('slider', wrapper);
			var wChildren = wrapper.children('li');
				wChildren.each(function(index){
					$(this).attr('index', index);
					$(this).data('infotext', $(this).children('.infotext').html());
					$(this).children('.infotext').remove();
				})
			wrapper.data('curId', 0);
			wrapper.data('firstEl', wChildren.first().addClass('first active'));
			wrapper.data('lastEl', wChildren.last().addClass('last'));
			
			var sliderControl = $('<div class="sliderControl pageWrap" />')		
				.append($('<span class="button prev" title="zurück"></span>'))
				//.append($('<span class="pagination"></span>'))
				.append($('<span class="button next" title="vor"></span>'))
			/*
			var pagination =$('<div class="sliderPagination pageWrap" />')
			wChildren.each(function(index){
				pagination.append($('<span class="button" index="'+index+'">'+(index+1)+'</span>'));
			});
			*/
			$(this).parent()
				.prepend(sliderControl)
				//.append(pagination)
				.delegate('.prev','click', function(){toPrev(wrapper)})
				.delegate('.next','click', function(){toNext(wrapper)})
				//.delegate('.sliderPagination .button','click', function(){toIndex(wrapper, $(this).attr('index'))})
			;
			$(this).parent().css('position', 'relative');
			
			wrapper.data('currentEl', wChildren.first());
			wrapper.addClass('slidingWrapper');
			wrapper.children('li').width(elWidth);
			wrapper.width((wrapper.children('li').length * elWidth));	
			setButtonPos(this);
		})	
	}
}(jQuery));
