/*
 *		Copyright (c) 2010 ffc architekten gmbh. Alle Rechte Vorbehalten.
 *		Erstellt von Bernd Lutz, http://berndlutz.com
 */


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


/*
 *		convert to integer, e.g. 10px -> 10
 */


function int(v)
{
	return Math.round(Number(String(v).replace(/[^0-9\.\-]+/, '')));
}


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


/*
 *		navigation and horizontal scrolling
 */


var Navigation = {
	
	mouseMove: false,
	mouseMoveInterval: false,
	mouseMoveSpeed: 0,
	anchorCheck: true,
	loadProjectAfterScrollTo: false,
	
	init: function()
	{
		// navigation click events
		$('#nav a, .subnav a').click(function()
		{
			if ( $('#project').length )
			{
				Project.close();
				return false;
			}
			
			Navigation.scrollTo('#' + Navigation.getFirstSectionIdByType($(this).attr('id').substr(5)));
			
			return false;
		});
		
		// set total width
		var total_width = 0;
		$('#content > div').each(function()
		{
			total_width += $(this).outerWidth() + 355;
		});
		
		total_width -= (355 - 150) * ($('.section-projekte').length - 1); // width correction because project sections have a 150px margin
		
		Navigation.scrollInWidth = 200;
		Navigation.offset = Math.round(($(window).width() - 750) * 0.5) + Navigation.scrollInWidth;
		
		$('#content').css(
		{
			width: total_width + 'px',
			padding: '0 ' + Navigation.offset + 'px 0 ' + Navigation.offset + 'px'
		});
		
		// initialise position and open home or content by anchor
		var initialSection = 'section-home';
		
		if ( window.location.hash.match(/^#(home|aktuelles|buero|projekte|kontakt)/) )
		{
			var target = this.getFirstSectionIdByType(window.location.hash.substr(1));
			
			var m = target.match(/[0-9]+\-([0-9]+)$/);
			if ( m )
			{
				target = target.replace(/\-[0-9]+$/, '');
				Project.id = m[1];
				
				window.setTimeout('Project.load(Project.id)', 1100);
			}

			if ( document.getElementById(target) && target != 'section-home' )
				initialSection = target;
		}
		
		this.scrollTo('#' + initialSection);
		window.setInterval('Navigation.scrollByAnchor()', 750);
		
		// scrolling by mouse position (after 1s to prevent flickering initial scroll)
		$('#content').append('<span class="move-left">&laquo;</span><span class="move-right">&raquo;</span>');
		window.setTimeout('Navigation.initMouseMoveByPosition()', 1000);
	},
	
	
	getFirstSectionIdByType: function(type)
	{
		if ( type == 'projekte' || type == 'buero' )
			return 'section-' + $('.section-' + type).attr('id').substr(8);
		
		return 'section-' + type;
	},
	
	
	/*
	 *		scrolling
	 */
	
	
	scrollTo: function(s)
	{
		if ( $(s).length == 0 )
			return false;
	
		var left = this.getScrollPosition(s);
		this.anchorCheck = false;
		
		// is there a project to be loaded directly after scrolling
		this.setProjectToBeLoadedAfterScrollTo();
		
		// scroll
		$('#content').animate(
			{
				left: left + 'px'
			},
			1000,
			'swing',
			function()
			{
				Navigation.setActiveItem();
				Navigation.anchorCheck = true;
				
				// load project
				if (Navigation.loadProjectAfterScrollTo)
				{
					Project.load(Navigation.loadProjectAfterScrollTo);
					Navigation.loadProjectAfterScrollTo = false;
				}
			}
		);
	},
	
	
	getScrollPosition: function(s)
	{
		var pos = $(s).position().left;
		pos = Math.round(($(window).width()-750)/2) - pos;
		
		return pos;
	},
	
	
	scrollByAnchor: function()
	{
		if ( !this.anchorCheck )
			return false;

		var hash = window.location.hash ? window.location.hash.substr(1).replace(/([0-9]+)\-[0-9]+$/, '$1') : 'home';

		if ( this.activeItem.join('-') != 'section-' + hash )
			this.scrollTo('#' + this.getFirstSectionIdByType(hash));
	},
	
	
	setProjectToBeLoadedAfterScrollTo: function()
	{
		var m = window.location.hash.match(/[0-9]+\-([0-9]+)$/);
		this.loadProjectAfterScrollTo = m ? m[1] : false;
	},
	
	
	initMouseMoveByPosition: function()
	{
		Navigation.mouseMove = true;
		
		$('#content').mouseenter(function()
		{
			Navigation.mouseMoveInterval = window.setInterval('Navigation.moveByMousePosition();', 25);
		});
		
		$('#content').mousemove(function(e)
		{
			if ( !document.getElementById('project') && !Navigation.mouseMoveInterval )
				Navigation.mouseMoveInterval = window.setInterval('Navigation.moveByMousePosition();', 25);

			Navigation.setMouseMoveSpeed(e.pageX);
		});
		
		$('#content').mouseleave(function()
		{
			window.clearInterval(Navigation.mouseMoveInterval);
		});
	},
	
	
	moveByMousePosition: function()
	{
		if ( Navigation.mouseMove == false )
		{
			window.clearInterval(Navigation.mouseMoveInterval);
			return false;
		}

		var pos = int($('#content').css('left'));
		var moveBy = Navigation.mouseMoveSpeed;
		
		if ( moveBy !== 0 )
		{
			pos = pos + moveBy;
			var offset = Math.round($(window).width() + ($(window).width() - 750) * 0.5);
		
			if ( pos > -Navigation.scrollInWidth )
			{
				pos = -Navigation.scrollInWidth;
			}
	
			if ( pos < -$('#content').outerWidth() + Navigation.scrollInWidth + $(window).width() + 355 )
			{
				pos = -$('#content').outerWidth() + Navigation.scrollInWidth + $(window).width() + 355;
			}
			
			$('#content').css(
			{
				left: pos + 'px'
			});
			
			Navigation.setActiveItem();
		}
	},
	
	
	setMouseMoveSpeed: function(s)
	{
		var scrollArea = Math.round(($(window).width() - 750) / 2);
		if ( scrollArea < 30 )
			scrollArea = 30;
		
		if ( s < scrollArea )
			this.mouseMoveSpeed = Math.round(15 * (1 - s/scrollArea));
		else if ( s > $(window).width() - scrollArea )
			this.mouseMoveSpeed = - Math.round(15 * (s - $(window).width() + scrollArea)/scrollArea);
		else
			this.mouseMoveSpeed = 0;
	},
	
	
	/*
	 *		setting the active navigation item depending on the current position
	 */
	
	
	activeItem: false,
	
	
	initActiveItemStorage: function()
	{
		this.storage = [];
		
		$('#content > div').each(function()
		{
			Navigation.storage.push([
				$(this).attr('id').split('-'),
				Navigation.getScrollPosition($(this))
			]);
		});
	},
	
	
	setActiveItem: function()
	{
		var x0 = int($('#content').css('left'));
		
		for ( var i = 0; i < this.storage.length; i++ )
		{
			if ( this.storage[i][1]  >= x0 - 200 && this.storage[i][1] < x0 + 355 )
			{
				if ( this.storage[i][0] == Navigation.activeItem )
					break;
			
				var id = this.storage[i][0];
			
				$('#nav a, .subnav a').removeClass('active');
				$('#item-' + id[1]).addClass('active');
				
				if ( Navigation.activeItem[1] != id[1] )
					$('.subnav').hide();
				
				if ( id[2] )
				{
					$('#item-' + id[1] + '-' + id[2]).addClass('active');

					if ( Navigation.activeItem[1] != id[1] )
						$('#subnav-' + id[1]).fadeIn(750);
				}
				
				Navigation.activeItem = id;
				
				if ( (!window.location.hash && id[1] != 'home') || window.location.hash )
					window.location.hash = id[1] + (id[2] ? '-' + id[2] : '');
				
				// update section print view
				$('#content > div').removeClass('current-section');
				$('#' + id.join('-')).addClass('current-section');
			
				break;
			}
		}
	}
};


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


/*
 *		project view in ajax loaded dialog
 */


var Project = {

	zIndex: 10,
	image: 0,
	images: [],
	interval: false,
	fadeTime: 1500,
	holdingTime: 2000,
	
	load: function(id)
	{
		Navigation.mouseMove = false;
		Project.id = id;
		
		$.ajax(
		{
			url: '/ajax/projekt/' + Project.id,
			data: {
				id: Project.id
			},
			success: Project.build
		});
		
		return false;
	},
	
	
	build: function(data)
	{
		Project.image = 0;
		Project.images = [];
		Project.files = [];
		
		$('#content').after('<div id="project"><div class="info"><h1>' + data.title + '</h1>' + data.text + '</div><a href="#" class="close">schließen</a></div>');
		$('#project').hide();
		
		if ( $.trim(data.subtitle) != '' )
			$('#project h1').after('<h2>' + data.subtitle.replace(/\n/, '<br>') + '</h2>');
		
		if ( data.table.length )
		{
			$('#project .info').append('<table></table>');
			
			for ( var i = 0; i < data.table.length; i++ )
				$('#project table').append('<tr><td>' + data.table[i][0] + '</td><td>' + data.table[i][1] + '</td></tr>');
			
			if ( data.fontSize == 'small' )
				$('#project table').css({fontSize: '86%'});
		}
		
		if ( data.images.length || data.files.length )
		{
			$('#project .info').after('<div id="project-thumbnails"><a href="#" class="toggle-play">abspielen</a></div>');
			
			for ( var i = 0; i < data.images.length; i++ )
				$('#project-thumbnails').append('<a href="#" class="thumbnail"><img src="' + data.images[i][0] + '/thumbnails/' + data.images[i][1] + '" alt="' + data.images[i][2] + '"></a>');
			
			$('.thumbnail').click(function()
			{
				Project.closeDownloads();
				
				var img = $(this).children('img');
				Project.stopSlideshow();
				Project.setImage($(img).attr('src').replace(/\/thumbnails\//, '/'), $(img).attr('alt'));
				Project.image = $(this).prevAll().length - 1;
				
				return false;
			});
			
			if ( data.images.length > 1 )
			{
				$('.toggle-play').click(Project.toggleImageSlideshow);

				Project.images = $('#project-thumbnails img').get();
				Project.image = 0;
				
				// start slideshow a little bit later to trick the fade+holding time to an experienced holding time.
				Project.slideshowStartTimeout = window.setTimeout('Project.setNextImage(); Project.startSlideshow();', Project.holdingTime);
				$('.toggle-play').removeClass('paused');
			}
			else
			{
				$('.toggle-play').remove();
			}
		}
		
		if ( data.images.length )
		{
			$('#project-thumbnails').after('<img src="' + data.images[0][0] + '/' + data.images[0][1] + '" alt="' + data.images[0][2] + '" class="large">');
		}
		
		if ( data.images.length <= 1 && !data.files.length )
		{
			$('#project-thumbnails').remove();
		}
		
		$('#project .close').click(function()
		{
			Project.close();
			return false;
		});
		
		$(document).bind('click.close', function(e)
		{
			if ( (!$(e.target).is('#project') && !$(e.target).parents('#project').length) )
				Project.close();
		});
		
		$('#project').fadeIn(1000);
		
		$('.current-section').removeClass('current-section');
		
		if ( data.files.length )
		{
			$('#project-thumbnails').append('<a href="#" class="open-downloads">&darr;</a>');
			
			Project.files = data.files;
			$('.open-downloads').click(Project.openDownloads);
		}
		
		// extend anchor by project id
		window.location.hash = window.location.hash + '-' + data.id;
	},
	
	
	close: function()
	{
		Project.stopSlideshow();
		Navigation.mouseMove = true;
		$(document).unbind('click.close');
		
		$('#project').fadeOut(1000, function(){
			$('#project').remove();
		});
		
		Navigation.setActiveItem();
		
		// remove project id from anchor
		window.location.hash = window.location.hash.replace(/\-[0-9]+$/, '');
	},
	
	
	setImage: function(file, title)
	{
		Project.zIndex++;

		$('#project-thumbnails').after('<img src="' + file + '" alt="' + title + '" class="large">');
		$('.large:first')
			.hide()
			.load(function()
			{
				var padding = $(this).width() < 600 ? 600 - $(this).width() : 0;
				
				$(this)
					.css({zIndex: Project.zIndex, paddingRight: padding + 'px'})
					.fadeIn(Project.fadeTime, function(){$(this).next('img').remove();});
				
			});
	},
	
	
	toggleImageSlideshow: function()
	{
		if ( $(this).hasClass('paused') )
		{
			Project.setNextImage();
			Project.startSlideshow();
		}
		else
		{
			Project.stopSlideshow();
		}
		
		return false;
	},
	
	
	startSlideshow: function()
	{
		Project.closeDownloads();
		Project.interval = window.setInterval("Project.setNextImage();", Project.holdingTime + Project.fadeTime);
		$('.toggle-play').removeClass('paused');
	},
	
	
	stopSlideshow: function()
	{
		window.clearInterval(Project.interval);
		window.clearTimeout(Project.slideshowStartTimeout);
		Project.interval = false;
		$('.toggle-play').addClass('paused');
	},
	
	
	setNextImage: function()
	{
		Project.image++;
		
		if ( Project.image == Project.images.length )
			Project.image = 0;
		
		Project.setImage($(Project.images[Project.image]).attr('src').replace(/\/thumbnails\//, '/'), $(Project.images[Project.image]).attr('alt'));
	},
	
	
	/*
	 *		downloads
	 */
	
	
	openDownloads: function()
	{
		Project.stopSlideshow();
		Project.closeDownloads();
		
		$('#project').append('<div id="downloads"><h3>Downloads</h3><p>Die folgenden Dateien zu diesem Projekt können Sie herunterladen:</p><table></table></div>');
		
		for ( var i = 0; i < Project.files.length; i++ )
		{
			$('#downloads table').append('<tr><td><a href="' + Project.files[i][0] + '">' + Project.files[i][1] + '</a></td><td>' + String(Project.files[i][2] ? Project.files[i][2] : 0.1).replace(/\./, ',') + ' MB</td></tr>');
		}
		
		return false;
	},
	
	
	closeDownloads: function()
	{
		$('#downloads').remove();
	}
};


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


/*
 *		projects view mosaic
 */


var ProjectsView = {
	
	init: function()
	{
		$('.section-projekte a, #section-aktuelles a').click(function(e)
		{
			Project.load(Number($(this).attr('rel')));
			return false;
		});
	},
	
	arrangeImages: function()
	{
		$('.section-projekte, #section-aktuelles').each(function()
		{
			// set max with
			var max = 0;
			$(this).find('img').each(function()
			{
				var pos = $(this).attr('src').match(/([0-9]+)_([0-9]+)_[\w]+\.(jpg|gif|png)$/);
				
				if ( pos )
				{
					if ( pos[1] > max )
						max = Number(pos[1]);
					
					$(this).css(
					{
						right: pos[1] + 'px',
						top: pos[2] + 'px'
					});
				}
			});
		
			// arrange images inverted (0/0 = upper right corner)
		
			$(this).css({width: (max + 120) + 'px'});
		});
	
		$('#section-aktuelles, .section-projekte:last').css({marginRight: '355px'});
	}
};


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


/*
 *		sending contact messages via ajax
 */


var Kontakt = {
	
	init: function()
	{
		$('#section-kontakt form').submit(Kontakt.submit);
	},
	
	
	submit: function(e)
	{
		var data = Kontakt.formData();

		if ( data )
		{
			$.ajax(
			{
				url: '/ajax/kontakt',
				data: data,
				success: function(data)
				{
					if ( data.status == 'ok' )
					{
						$('#section-kontakt .content')
						.empty()
						.html('<p>Vielen Dank für Ihr Interesse. Wir werden Ihre Anfrage so schnell wie möglich bearbeiten.</p>');
					}
					else if ( data.status == 'error' )
					{
						$('#section-kontakt form').prepend('<p class="error">Tut uns leid, aufgrund eines Fehlers konnte Ihre Anfrage nicht verschickt werden.</p>');
					}
					else
					{
						$('#section-kontakt form').prepend('<p class="error">Der Spamschutz wurde aktiviert und hat das Senden verhindert.');
					}
				}
			});
		}
		
		return false;
	},
	
	
	formData: function()
	{
		var data = {
			name: $('#name').val(),
			kemail: $('#kemail').val(),
			text: $('#text').val(),
			dummy: $('#dummy').val()
		};

		if ( !this.empty(data.name) && !this.empty(data.kemail) && !this.empty(data.text) )
			return data;
		
		return false;
	},
	
	
	empty: function(v)
	{
		return $.trim(v) == '' ? true : false;
	}
};


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


/*
 *		iPhone / iPad content arragement
 */


function arrangePage()
{
	var height = $(window).height();
	height = height > 700 ? height : 700;
		
	$('#wrapper').css(
	{
		height: height + 'px'
	});
		
	var top = Math.round((height * 0.5 - 200) * 0.5 - 65);
	top = top > 5 ? top : 0;
		
	$('#header').css(
	{
		top: top + 'px'
	});
}


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


/*
 *		putting all together
 */


$(document).ready(function()
{
	arrangePage();
	
	// main page
	if ( $('#home').length )
	{
		// default ajax settings
		$.ajaxSetup(
		{
			type: 'POST',
			cache: false,
			dataType: 'json',
			dataFilter: function(data, type)
			{
				if ( type == 'json' && (data.match(/^\{\"error\":\".*\"\}$/) || $.parseJSON(data).error) )
				{
					return response.error;
				}
				
				return data;
			}
		});
		
		// initialise projects, navigation, forms etc.
		ProjectsView.init();
		ProjectsView.arrangeImages();
		Navigation.init();
		Kontakt.init();
		
		// vertical centering
		window.onresize = arrangePage;
		
		Navigation.initActiveItemStorage();
		
		// afterwards applied special distance between paragraphs
		if ( $('.section-home p').length == 3 )
		{
			$('.section-home p:eq(0)').css({marginTop: '2.5em'});
			$('.section-home p:eq(1)').css({marginTop: '1em'});
			$('.section-home p:eq(2)').css({marginTop: '5.5em'});
		}
	}
	
	// iPhone/iPad compatibility
	if ( navigator.userAgent.match(/webkit/i) && navigator.userAgent.match(/mobile\//i) )
	{
		$('.move-left, .move-right').hide();
		window.onorientationchange = arrangePage;
	}
});
