/*
 ******************************************************************************************************************
 * LANDING
 ******************************************************************************************************************
 */

function showLandingHeader(location) {
	
	window.setTimeout("window.location.replace(\""+location+"?page=home\")", 4000);
}


/*
 ******************************************************************************************************************
 * HORIZONTAL NAVIGATION
 ******************************************************************************************************************
 */

function showHorizontalNavigation() {
	
	var $navHorizontal = $('#navigation ul li');
		if (isIPad) {
		} else {
			$navHorizontal.filter(':not(.current-cat)').children('ul').css("display","none");
		}
        $navHorizontal.hover(function(){ 
            $(this).addClass("hover");
        }, function() {
            $(this).children('ul').stop(true,true).css("display","none");
            $(this).removeClass("hover");
        });
        $navHorizontal.filter(':has(ul)').children(':first-child').click(function(){
			if (isIPad) {
			} else {
				$(this).parent().siblings().children('ul:visible').slideUp('fast');
				$(this).next().slideToggle('fast');
				return false;
			}
        });
}


/*
 ******************************************************************************************************************
 * HOME
 ******************************************************************************************************************
 */
 
function showHome() {

	handleHomeResize();
	showContent();
	
	var timeout = false;
	$(window).bind('resize', function () {
		if(timeout !== false) {
			clearTimeout(timeout);
		}
		timeout = setTimeout(handleHomeResize, 100);
		return false;
	});
	
	function handleHomeResize() {
		$('#navigation').resizeNavigation();
		$('#viewHomeDetail img').first().resizeImage();
	}
	
	function showContent() {
		$.ajax({
			type: "GET",
			url: "xml/settings/_settings.xml",
			dataType: "xml",
			success: function(xml) {
				$(xml).find('setting[id="home_image_path"] image_path').first().each(function(){
					calcImageHeight($(this).attr('width') / $(this).attr('height'));
					$('#viewHomeDetail').hide();
					$('#viewHomeDetail').fadeIn('slow');
					$('#viewHomeDetail').html('<img src="' + $(this).text() + '" height="' + mImageHeight + '" />');
				});
			}
		});
	}
}


/*
 ******************************************************************************************************************
 * PORTFOLIOS
 ******************************************************************************************************************
 */
 
function showPortfolios() {

	handlePortfolioResize();
        
	var $navVertical = $('#scrollContent');
	if(!isIPad) {
		$navVertical.jScrollPane({wheelSpeed: 30, dragMaxHeight:30, scrollbarWidth: 17, animateTo:true, animateInterval:50, animateStep:5});
	} else {
		$navVertical.jScrollPane({wheelSpeed: 30, dragMaxHeight:40, scrollbarWidth: 28, animateTo:true, animateInterval:50, animateStep:5, isIPad:true});
	}
	
	var $navThumbs = $('#scrollContent div.imageThumbnail');
	$navThumbs.click(function(){
		$(this).siblings().removeClass('active');
		$(this).addClass('active');
		var image = $(this).children('a').attr("rel");
		imageUrl = image.substr(0, image.lastIndexOf("/"));
		imageSize = image.substr(image.lastIndexOf("/")+1, image.length).split("_");
		calcImageHeight(imageSize[0] / imageSize[1]);
		$('#viewPortfolioDetail').hide();
		$('#viewPortfolioDetail').fadeIn('slow');
		$('#viewPortfolioDetail').html('<a href=\'#\'><img src="' + imageUrl + '" height="' + mImageHeight +'" /><div class="contentNavigation"></div></a>');
		return false;
	});
	
	var $content = $('#viewPortfolioDetail');
	$content.click(function(e){
		var currentImage = $('#viewPortfolioDetail a img').attr('src');
		/* use only filename as ie returns absolute path to image (other browsers return relative path) */
		currentImage = currentImage.substr(currentImage.lastIndexOf("/")+1,currentImage.length);
		var currentImageOffset = $('#viewPortfolioDetail').offset();
		var currentImageMouseX = e.pageX - currentImageOffset.left;
		if( currentImageMouseX < $('#viewPortfolioDetail a img').width() / 2 ) {
			var $nextThumb = $('#scrollContent div.imageThumbnail a[rel*=\''+currentImage+'\']').parent().prev();
			if ($nextThumb.length == 0) 
				$nextThumb = $('#scrollContent div.imageThumbnail a[rel*=\''+currentImage+'\']').parent().siblings().last();
		} else {
			var $nextThumb = $('#scrollContent div.imageThumbnail a[rel*=\''+currentImage+'\']').parent().next();
			if ($nextThumb.length == 0) 
				$nextThumb = $('#scrollContent div.imageThumbnail a[rel*=\''+currentImage+'\']').parent().siblings().first();
		}
		
		if ($nextThumb.length > 0) {
			$nextThumb.trigger('click');
			$navVertical[0].scrollTo('a[rel='+$nextThumb.find('a').attr('rel')+']');
		}
		return false;
	});
	
	if(!isIPad) {
		$content.mousemove(function(e){
			handlePortfolioContentNav(e);
			return false;
		});
		
		$content.hover(function(e){
			handlePortfolioContentNav(e);
			return false;
		}, function(e){
			handlePortfolioContentNavFadeOut(e);
			return false;
		});
	}
	
	/* select first image on startup of page "portfolio" */
	if( $navThumbs.length > 0 ) {
		$navThumbs.first().trigger('click');
	}
	
	var timeout = false;
	$(window).bind('resize', function () {
		if(timeout !== false) {
			clearTimeout(timeout);
		}
		timeout = setTimeout(handlePortfolioResize, 100);
		return false;
	});
	
}

function handlePortfolioResize() {
	$('#navigation').resizeNavigation();
	$('#viewPortfolioDetail a img').first().resizeImage();
	$('#navPortfolio').resizeNavigationHeight();
}

function handlePortfolioContentNav(e) {
	var currentImage = $('#viewPortfolioDetail a img').attr('src');
	/* use only filename as ie returns absolute path to image (other browsers return relative path) */
	currentImage = currentImage.substr(currentImage.lastIndexOf("/")+1,currentImage.length);
	var currentImageOffset = $('#viewPortfolioDetail').offset();
	var currentImageMouseX = e.pageX - currentImageOffset.left;
	var navigationLayer = $('div.contentNavigation');
	if( currentImageMouseX < $('#viewPortfolioDetail a img').width() / 2 ) {
		if($('div.contentNavigation:contains("PREV")').length == 0) {
			navigationLayer.hide();
			navigationLayer.fadeIn(300);
			navigationLayer.css({textAlign: 'left'});
			navigationLayer.html('PREV');
		}
	} else {
		if($('div.contentNavigation:contains("NEXT")').length == 0) {
			navigationLayer.hide();
			navigationLayer.fadeIn(300);
			navigationLayer.css({textAlign: 'right'});
			navigationLayer.html('NEXT');
		}
	}
}

function handlePortfolioContentNavFadeOut(e) {
	var navigationLayer = $('div.contentNavigation');
	navigationLayer.hide();
	navigationLayer.html('');
}


/*
 ******************************************************************************************************************
 * CLIENTS
 ******************************************************************************************************************
 */

var CLIENT_CATEGORY_ADVERTISING = '1';
var CLIENT_CATEGORY_EDITORIAL = '2';

function showClients(category) {
	
	handleClientsResize();
        
	var $navVertical = $('#scrollContent');
	if(!isIPad) {
		$navVertical.jScrollPane({wheelSpeed: 30, dragMaxHeight:30, scrollbarWidth: 17, animateTo:true, animateInterval:50, animateStep:5});
	} else {
		$navVertical.jScrollPane({wheelSpeed: 30, dragMaxHeight:40, scrollbarWidth: 28, animateTo:true, animateInterval:50, animateStep:5, isIPad:true});
	}
	
	var $clients = new Array();
	
	var $contentClient = $('#viewClientDetail');
	$contentClient.click(function(e){
		var currentImage = $('#viewClientDetail a img').attr('src');
		/* use only filename as ie returns absolute path to image (relative path in other browsers) */
		currentImage = currentImage.substr(currentImage.lastIndexOf("/")+1,currentImage.length);
		var currentImageOffset = $('#viewClientDetail').offset();
		var currentImageMouseX = e.pageX - currentImageOffset.left;
		for(var i=0; i< $clients.length; i++) {
			var image = $clients[i].text();
			image = image.substr(image.lastIndexOf("/")+1,image.length);
			if( currentImage == image) break;
		}
		
		if( currentImageMouseX < $('#viewClientDetail a img').width() / 2 ) {
			$nextImageId = i > 0 ? i-1 : $clients.length-1;
			$nextImage = $clients[$nextImageId];
		} else {
			$nextImageId = i < $clients.length-1 ? i+1 : 0;
			$nextImage = $clients[$nextImageId];
		}
		
		if( $nextImage.text() != '' ) {
			calcImageHeight($nextImage.attr('width') / $nextImage.attr('height'));
			$('#viewClientDetail').hide();
			$('#viewClientDetail').fadeIn('slow');
			$('#viewClientDetail').html('<a href=\'#\'><img src="' + $nextImage.text() + '" height="' + mImageHeight + '" /><div class="contentNavigation"></div></a>');
		}
		return false;
	});
	
	if(!isIPad) {
		$contentClient.mousemove(function(e){
			handleClientContentNav(e, $clients);
		});
		
		$contentClient.hover(function(e){
			handleClientContentNav(e, $clients);
		}, function(e){
			handleClientContentNavFadeOut(e);
		});
	}
	
	var $navClients = $('#scrollContent ul.clients a');
	$navClients.click(function() {
		$(this).closest('li.clientEntry').siblings().removeClass('active');
		$(this).closest('li.clientEntry').addClass('active');
		var clientId = $(this).attr('rel');
		var url = category == CLIENT_CATEGORY_ADVERTISING ? 
					"xml/advertisings/advertising_"+clientId+".xml" : 
					"xml/editorials/editorial_"+clientId+".xml";
		$.ajax({
			type: "GET",
			url: url,
			dataType: "xml",
			success: function(xml) {
				while( $clients.length > 0 ) $clients.pop();
				$(xml).find('detail_path').each(function(){
					$clients.push( $(this) );
					if( $clients.length > 0 ) {
						calcImageHeight($(this).attr('width') / $(this).attr('height'));
						$('#viewClientDetail').hide();
						$('#viewClientDetail').fadeIn('slow');
						$('#viewClientDetail').html('<a href=\'#\'><img src="' + $clients[0].text() + '" height="' + mImageHeight + '" /><div class="contentNavigation"></div></a>');
					}
				});
			}
		});
	});
	
	/* read in xml on startup of page "clientlist" */
	if( $navClients.length > 0 ) {
		$navClients.first().trigger('click');
	}
	
	var timeout = false;
	$(window).bind('resize', function () {
		if(timeout !== false) {
			clearTimeout(timeout);
		}
		timeout = setTimeout(handleClientsResize, 100);
		return false;
	});
        	
}

function handleClientsResize() {
	$('#navigation').resizeNavigation();
	$('#viewClientDetail a img').first().resizeImage();
	$('#navClient').resizeNavigationHeight();
}

function handleClientContentNav(e, $clients) {
	var currentImage = $('#viewClientDetail a img').attr('src');
	/* use only filename as ie returns absolute path to image (relative path in other browsers) */
	currentImage = currentImage.substr(currentImage.lastIndexOf("/")+1,currentImage.length);
	var currentImageOffset = $('#viewClientDetail').offset();
	var currentImageMouseX = e.pageX - currentImageOffset.left;
	
	for(var i=0; i< $clients.length; i++) {
		var image = $clients[i].text();
		image = image.substr(image.lastIndexOf("/")+1,image.length);
		if( currentImage == image) break;
	}
	
	var navigationLayer = $('div.contentNavigation');
	if( currentImageMouseX < $('#viewClientDetail a img').width() / 2 ) {
		if($('div.contentNavigation:contains("PREV")').length == 0) {
			navigationLayer.hide();
			navigationLayer.fadeIn(300);
			navigationLayer.css({textAlign: 'left'});
			navigationLayer.html('PREV');
		}
	} else {
		if($('div.contentNavigation:contains("NEXT")').length == 0) {
			navigationLayer.hide();
			navigationLayer.fadeIn(300);
			navigationLayer.css({textAlign: 'right'});
			navigationLayer.html('NEXT');
		}
	}
}

function handleClientContentNavFadeOut(e) {
	var navigationLayer = $('div.contentNavigation');
	navigationLayer.hide();
	navigationLayer.html('');
}


/*
 ******************************************************************************************************************
 * BLOG
 ******************************************************************************************************************
 */
 
function showBlog() {

	handleBlogResize();
        
	if(!isIPad) {
		$('#viewBlogDetail').jScrollPane({wheelSpeed: 30, dragMaxHeight:30, scrollbarWidth: 17, animateTo:true, animateInterval:50, animateStep:5, reinitialiseOnImageLoad:true });
	} else {
		$('#viewBlogDetail').jScrollPane({wheelSpeed: 30, dragMaxHeight:40, scrollbarWidth: 45, animateTo:true, animateInterval:50, animateStep:5, reinitialiseOnImageLoad:true, isIPad:true});
	}
	
	var timeout = false;
	$(window).bind('resize', function () {
		if(timeout !== false) {
			clearTimeout(timeout);
		}
		timeout = setTimeout(handleBlogResize, 100);
		return false;
	});
	
}

function handleBlogResize() {
	$('#navigation').resizeNavigation();
	$('#content').resizeContentHeight();
}


/*
 ******************************************************************************************************************
 * MOTION GRAPHICS
 ******************************************************************************************************************
 */
 
function showMotions() {

	handleMotionResize();

	var $navVertical = $('#scrollContent');
	if(!isIPad) {
		$navVertical.jScrollPane({wheelSpeed: 30, dragMaxHeight:30, scrollbarWidth: 17, animateTo:true, animateInterval:50, animateStep:5});
	} else {
		$navVertical.jScrollPane({wheelSpeed: 30, dragMaxHeight:40, scrollbarWidth: 28, animateTo:true, animateInterval:50, animateStep:5, isIPad:true});
	}
	
	var $navThumbs = $('#scrollContent div.imageThumbnail');
	$navThumbs.click(function(){
		$(this).siblings().removeClass('active');
		$(this).addClass('active');
		var motion = $(this).children('a').attr("rel");
		$('#viewMotionDetail').hide();
		$('#viewMotionDetail').fadeIn('slow' );
		/* check for video support of the browser*/
		if($.flash.available && $.flash.hasVersion('9.0.28')) {
			/* flash support */
			$('#viewMotionDetail').html('<div id="flash"></div>');
			$('#viewMotionDetail #flash').flash({
				swf: 'shockwave/player.swf',
				height: '100%',
				width: '100%',
				bgcolor: '#FFFFFF',
				allowfullscreen: 'true',
				flashvars: {
					site: '.',
					videoPath: '../'+ motion
				}
			});
		} else if(!!document.createElement('video').canPlayType) {
			/* HTML5 video tag support */
			/* iPad: support for H.264 video up to 720p, 640 by 480 pixels (http://www.apple.com/ipad/specs/) */
			$('#viewMotionDetail').html('<video src="'+ motion + '" width="640" height="360" preload="none" controls="controls"></video>');
		} else {
			/* no video support */
			$('#viewMotionDetail').html('<div id="flash">'+
										'<span>Please <a href="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" target="_blank">'+
										'upgrade your Flash Player</a> or use a browser with HTML5-video support</span></div>');
		}
		
		return false;
	});
	
	/* select first image on startup of page "motion" */
	if( $navThumbs.length > 0 ) {
		$navThumbs.first().trigger('click');
	}
	
	var timeout = false;
	$(window).bind('resize', function () {
		if(timeout !== false) {
			clearTimeout(timeout);
		}
		timeout = setTimeout(handleMotionResize, 100);
		return false;
	});
	
}

function handleMotionResize() {
	$('#navigation').resizeNavigation();
	$('#navMotion').resizeNavigationHeight();
}


/*
 ******************************************************************************************************************
 * CONTACT
 ******************************************************************************************************************
 */
 
function showContact() {
	
	handleContactResize();
        
	if(!isIPad) {
		$('#viewContactDetail').jScrollPane({wheelSpeed: 30, dragMaxHeight:30, scrollbarWidth: 17, animateTo:true, animateInterval:50, animateStep:5, reinitialiseOnImageLoad:true });
	} else {
		$('#viewContactDetail').jScrollPane({wheelSpeed: 30, dragMaxHeight:40, scrollbarWidth: 45, animateTo:true, animateInterval:50, animateStep:5, reinitialiseOnImageLoad:true, isIPad:true});
	}
	
	var timeout = false;
	$(window).bind('resize', function () {
		if(timeout !== false) {
			clearTimeout(timeout);
		}
		timeout = setTimeout(handleContactResize, 100);
		return false;
	});

	}

function handleContactResize() {
	$('#navigation').resizeNavigation();
	$('#content').resizeContentHeight();
}


/*
 ******************************************************************************************************************
 * HELPERS
 ******************************************************************************************************************
 */

$.fn.resizeImage = function() {
	calcImageHeight(mScale);
	$(this).attr({
		height: mImageHeight
	})
}
    
$.fn.resizeNavigation = function() {
	if($(window).width() <= 1130) {
		$(this).find('>ul >li').each(function(){
			$(this).find('a:first').css({
				paddingLeft : '1em',
				paddingRight : '1em'
			});
			$(this).find('ul:first').css({
				/* no reset of padding heights -> no jump-problem with jQuery.slideToggle */
				paddingLeft : '1.2em',
				paddingRight : '1.2em'
			});
		});
	} else {
		$(this).find('>ul >li').each(function(){
			$(this).find('a:first').css({
				paddingLeft : '1.8em',
				paddingRight : '1.8em'
			});
			$(this).find('ul:first').css({
				/* no reset of padding heights -> no jump-problem with jQuery.slideToggle */
				paddingLeft : '2.2em',
				paddingRight : '2.2em'
			});
		});
	}
}


$.fn.resizeNavigationHeight = function() {
	var navVerticalMarginTop = $(this).offset().top;
	$(this).css({
		height: calcNavigationVerticalHeight(navVerticalMarginTop)
	});
	
	$('#scrollContent div.imageThumbnail a img').each(function(){
		$(this).attr({
			height: 130
		});
	});
	
	if(!isIPad) {
		$('#scrollContent').jScrollPaneRemove();
		$('#scrollContent').jScrollPane({wheelSpeed: 30, dragMaxHeight:30, scrollbarWidth: 17, animateTo:true, animateInterval:50, animateStep:5});
	} else {
		$('#scrollContent').jScrollPaneRemove();
		$('#scrollContent').jScrollPane({wheelSpeed: 30, dragMaxHeight:40, scrollbarWidth: 28, animateTo:true, animateInterval:50, animateStep:5, isIPad:true});
	}
}

$.fn.resizeContentHeight = function() {
	var contentMarginTop = $(this).offset().top;
	var contentMarginLeft = $(this).offset().left;

	$(this).css({
		height: calcContentHeight(contentMarginTop),
		width: calcContentWidth(contentMarginLeft, minContentWidth, maxContentWidth)
	});
	
	var tableWidth = !isIPad ? $(this).width() - 45 : $(this).width() - 45;
	$(this).find('TABLE').first().css({
		width: tableWidth
	});
	
	$(this).find('TABLE IMG').each(function(){
		var originalsize = $(this).attr('name').substring($(this).attr('name').indexOf('_')+1, $(this).attr('name').length).split('x');
		if (originalsize[0] > tableWidth) {
			$(this).attr({width: tableWidth});
		} else if (originalsize[0] < tableWidth) {
			$(this).attr({width: originalsize[0]});
		}
	});
	
	if(!isIPad) {
		$(this).find('div.scrollPane:first').jScrollPaneRemove();
		$(this).find('div.scrollPane:first').jScrollPane({wheelSpeed: 30, dragMaxHeight:30, scrollbarWidth: 17, animateTo:true, animateInterval:50, animateStep:5});
	} else {
		$(this).find('div.scrollPane:first').jScrollPaneRemove();
		$(this).find('div.scrollPane:first').jScrollPane({wheelSpeed: 30, dragMaxHeight:40, scrollbarWidth: 45, animateTo:true, animateInterval:50, animateStep:5, isIPad:true});
	}
}

function calcImageHeight(scale) {
	mScale = scale;
	
	var minWidth = minImageHeight * scale;
	var maxWidth = $(window).width() - 270;
	var imageWidth = maxWidth;
	var imageHeight = $(window).height() - 196;
	
	if( imageHeight < minImageHeight || imageWidth < minWidth ) {
		// image must not be smaller than minImageHeight
		imageHeight = minImageHeight;
	} else {
		// image must fit into browser window
		if( imageHeight > maxImageHeight ) {
			imageHeight = maxImageHeight;
		}
		imageWidth = scale * imageHeight;
		if( imageWidth > maxWidth ) {
			imageHeight = Math.floor(maxWidth / scale);
		}
	}
	
	mImageHeight = imageHeight;
	
}

function calcNavigationVerticalHeight(marginTop) {
	var navVerticalHeight = Math.round($(window).height() - marginTop - 10);
	return navVerticalHeight;
}

function calcContentHeight(marginTop) {
	var contentHeight = Math.round($(window).height() - marginTop - 10);
	return contentHeight;
}

function calcContentWidth(marginLeft, minWidth, maxWidth) {
	var contentWidth = Math.round($(window).width() - marginLeft - 10);
	if (contentWidth < minWidth) {
		contentWidth = minWidth;
	} else if(contentWidth > maxWidth) {
		contentWidth = maxWidth;
	}
	return contentWidth;
}
