/**
 * JavaScript which runs the page.
 */
$(document).ready(function() {

	// Prepare Page
	preparePage();
	setHeader();

	// Take some measurements.
	socialBarHeight = $('.has-social-bar').length ? 30 : 0;

	// Set up navigation colors.
	nav.prepare();

	// Specify the homepage for when the hash isn't specified.
	$('body').data('home', $('.page-container').data('home-id'));

	// Listen for navigation changes.
	initialise.run();

	// Start Music
	if (navigator.userAgent.match(/iPad/i) != null) {
		musicStart = false;
	}

	// Init Music
    if ($('body').data('music') && ajax.hasHistoryAPI)
    {
        music = new com.cmd.model.MusicPlayer();
        music.init($('#musicIcon'),$('#musicPlayer'),track,templatePath,musicStart);
        $('body').addClass('music-supported');
    }

	$('#ajax').fadeIn(500, function() {
		// Resize Large Thumbs
		if ($('.pages').length && videoSettings.videoThumbnailSize == 1) {
			$(window).resize();
	 	}
	});
	initialise.load($('.page-container').data('type'));

	if (videoSettings.videoThumbnailSize == 1) {
		var resizeLargeThumbs;
	}

	// Caption Controls
	$('body').delegate("#caption", "mouseenter", function() {
		if ($('.caption-text').html().length) {
			$('.caption-text').show();
		}
	})
	$('body').delegate("#caption", "mouseout", function() {
		$('.caption-text').hide();
	})

	// On Resize
	$(window).resize(function() {
		preparePage();
		setHeader();

		positionImages();
		resizeText();
		if ($('.pages').length) {
			pages.windowWidth = $('#ajax').width();
			pages.windowHeight = $('#ajax').height();
			pages.updateThumbnailsLayout();

			if (videoSettings.videoThumbnailSize == 1) {
				$('.large-thumbs').height($('#ajax').height());
				pages.windowHeight = $('#ajax').height();
		        pages.windowWidth = $('#ajax').width();

				clearTimeout(resizeLargeThumbs);
    			resizeLargeThumbs = setTimeout(pages.largeThumbsSizeToggle, 500);
			}
		}
		if ($('#photoSlider').length) {
			getSliderWidth();
		}
	});
});

/**
 * CMD Ajax
 */
var ajax = {

	// Specify the nav and submenu thumbnail links.
	target : '',

	// Specify the page change callback function
	callback : '',

	// Stores whether the browser supports this feature.
	hasHistoryAPI : false,

	// First Load
	firstLoad : true,

	init : function(target, callback) {
		this.target = target;
		this.callback = callback;
		this.hasHistoryAPI = (typeof history.pushState !== 'undefined');

		// Redirect old urls
		var urlSegments = window.location.href.split('/#!/');
		if (urlSegments.length > 1) {
			window.location.href = rootPath + urlSegments[1];
			return;
		}

		if (this.hasHistoryAPI) {
			$('body').delegate(this.target, 'click', this.callback);

			window.addEventListener('popstate', function(event) {
				if ($.browser.webkit && ajax.firstLoad) {
					ajax.firstLoad = false;
					return;
				}
				initialise.changePage(window.location.href.substring(rootPath.length, window.location.href.length));
			});
		}
	}
}

/**
 * Menu Scripting
 */
var nav = {
	// Set up menu colors and transitions.
	prepare : function () {
		$('#nav a').each(function() {
			$(this).attr('data-color', $(this).css('color'));
		})

		$('#nav a:not(#nav a.selected)').hover(function() {
			$(this).css({'color':$(this).attr('data-rollover')});
		},function() {
			if ( ! $(this).hasClass('selected')) {
				$(this).css({'color':$(this).attr('data-color')});
			}
		});

		$('#nav a.selected').css('color', $('#nav a.selected').attr('data-rollover'));
		// End menu styles

		// Show Submenus on click.
		$('#nav a[href="#"]').click(function(e) {
			e.preventDefault();
			if ( $.browser.msie && $.browser.version < 8) {
				$(this).next().toggle();
			} else {
				if (isiPad()) {
					$(this).next().fadeToggle();
				}
			}
		});
	},

	change : function(hash) {
		var el = $('#nav [data-slug="'+hash+'"]');
		var selected = $('.selected');

		if ($(el)[0] == $(selected)[0]) {
			return false;
		}

		$(selected).removeClass('selected').css({'color':$(selected).attr('data-color')});
		$(el).addClass('selected').css({'color':$(el).attr('data-rollover')});
	}
}

/**
 * Initialise Page
 */
var initialise = {
    // Form object
    _form:null,

	run : function() {
		ajax.init('#nav a, .submenu-thumbnails a', initialise.linkClick);
	},

	// Listen for clicks on the menu, trigger the unload / load functions.
	linkClick : function(e) {

		// Determine if link is going to a cmd page
		if ( ! $(this).data('type')) {
			return;
		}

		e.preventDefault();

		// Update state
		var title = $(this).html();
		var href = $(this).attr('href');
        history.pushState({}, title,href === '' ? '.' : href);

		// Change Page
		initialise.changePage($(this).data('slug'));
	},

	changePage : function(urlSegment) {
		// Ajaxify
		$.ajax({
			url : 'index.php?s='+urlSegment+'&ajax=true',
			type : 'POST',
			success : function(data) {
				initialise.unload();

				nav.change(urlSegment);

				// Load New Page
				$('#ajax').fadeOut('slow', function() {
					$(this).find('.page-container:first-child').remove();

					$(this).append(data);
					initialise.load($('.page-container').data('type'));
					$(this).fadeIn(function() {
						registerPageView(urlSegment);
					});

					// Resize Large Thumbs
					if ($('.pages').length && videoSettings.videoThumbnailSize == 1) {
						$(window).resize();
					}
				});
			}
		});
	},

	// Switches page type to load correct page.
	load : function(type) {

		// Resize Images + Text Box.
		positionImages();
		resizeText();

		// Set page title
		document.title = $('.page-container').data('title');

        if ($('body').data('music') && ajax.hasHistoryAPI)
        {
            music.checkPageMusic($('.page-container').data('music'));

            // Check auto stop to/from video-page
            var Context = com.cmd.enm.Context;

            if (type == "videos")
            {
                if (music.isPlaying()) music.togglePlayPause(Context.APPLICATION);
            }
            else
            {
                if (!music.isPlaying() && music.getChangeAgent() == Context.APPLICATION) music.togglePlayPause();
            }
        }

		// Change Body Background.
		var background = $('.page-container').data('background');
		initialise.changeBodyBackground(background);

		$('body').removeClass('page-404');

		switch(type) {
			case 'home':
				initialise.loadHome();
			break;
			case 'text':
				initialise.loadText();
			break;
			case 'password':
				initialise.loadPassword();
			break;
			case 'password_prompt':
				initialise.loadPasswordPrompt();
			break;
			case 'contact':
				initialise.loadContact();
			break;
			case 'photo':
			case 'photos':
				initialise.loadPhoto();
			break;
			case 'photos2':
			case 'photos3':
			case 'photos4':
				initialise.loadPhoto2();
			break;
			case 'videos':
				initialise.loadVideos();
			break;
			case 'submenu_thumbs':
				initialise.loadSubmenu();
			break;
			case 'page_not_found':
				$('body').addClass('page-404');
			break;
		}

		if ($('#textBlock,.large-thumbs, #photoSlider2, #photoSlider3').length) {
			$("#textBlock,.large-thumbs, #photoSlider2, #photoSlider3").mCustomScrollbar({
				scrollInertia : 0
			});
			$(window).resize();
		}

	},

	// Stops slideshow, removes events, fades page out.
	unload : function() {
		$('#nav li').css('opacity', 1);

		// Kill slideshow
		if ($('#fotoblock').length) {
			$('#fotoblock').cycle('destroy');
		}

		// Remove Password events
		if ($('#passwordForm').length) {
			$('#password, #passwordForm').unbind();
		}

		// Remove Contact Events
		/*if ($('#contactForm').length) {
			$('#contactForm, #contactForm .required, #contactForm .text, #contactForm textarea').unbind();
		}*/
        if (this._form)
        {
            this._form.destroy();
            this._form = null;
        }

		// Remove Photo Events
		if ($('.sliderIn').length) {
			$('.sliderIn img, #right, #left, #slide, .prev_image, .next_image, #photoSlider').unbind();
		}

		$('body').removeClass('image-not-loaded');

		$('#nav li').unbind('hover');

		// Remove Caption
		$('#caption').fadeOut('fast', function() {
			$(this).remove();
		});
	},


	// Loads Home Page
	loadHome : function() {
		positionImages();
		resizeText();

		$('.page-container').css('background',$('.page-container').data('sub_background'));

		if ($('#fotoblock img').length) {

			// Caption
			var caption = $('#fotoblock img').first().data("caption");
			if (caption) {
				$('.caption-text').html(caption);
			} else {
				$('#caption').css('opacity', 0);
			}
		}

		var images = $('#fotoblock img');
		if ($(images).length > 1)	{
			var slideshowSpeed = slideshow_type == 'fade' ? 800 : 300;
			$('#fotoblock').cycle({
				slideResize: 0,
				fx: slideshow_type,
				speed: slideshowSpeed,
				timeout : slideshowTimer,
				before : function(currSlideElement, nextSlideElement) {
					if ( ! $(nextSlideElement).data('loaded')) {
						$('#fotoblock').cycle('pause');
						$('body').addClass('image-not-loaded');
						return;
					}

					// Show / Hide Caption
					var caption = $(nextSlideElement).data('caption');

					if (caption.length) {
						$('#caption').css('opacity', '1');
						$('.caption-text').html(caption);
					} else {
						$('.caption-text').html('');
						$('#caption').css('opacity', '0');
					}

					// Body background colors.
//					var newBg = $(nextSlideElement).data('background').toString();
//					if (newBg == '#') {
//						newBg = '#'+$('.page-container').data('background');
//					}
//					initialise.changeBodyBackground(newBg);
				}
			});
		} else {
			$(images).fadeIn();
		}
	},

	// Loads Text Page
	loadText : function() {
		positionImages();
		resizeText();

		var images = $('#fotoblock img');
		if ($(images).length > 1)	{
			$('#fotoblock').cycle({
				slideResize: 0,
				slideExpr : 'img:not(.img-overlay img)',
				timeout : slideshowTimer,
				before : function(currSlideElement, nextSlideElement) {
					if ( ! $(nextSlideElement).data('loaded')) {
						$('#fotoblock').cycle('pause');
						$('body').addClass('image-not-loaded');
						return;
					}
				}
			});
		} else {
			$(images).fadeIn();
		}

	},


	// Loads Password Page
	loadPassword : function() {
		positionImages();
		resizeText();

		// Set up slideshow
		var images = $('#fotoblock img');
		if ($(images).length > 1)	{
			$('#fotoblock').cycle({
				slideResize: 0,
				slideExpr : 'img:not(.img-overlay img)',
				timeout : slideshowTimer,
				before : function(currSlideElement, nextSlideElement) {
					if ( ! $(nextSlideElement).data('loaded')) {
						$('#fotoblock').cycle('pause');
						$('body').addClass('image-not-loaded');
						return;
					}
				}
			});
		} else {
			$(images).fadeIn();
		}

		// Set up form validation.
		$('#passwordForm').submit(function() {
			var password = $('input[name="password"]').val();
			$.ajax({
				type: "POST",
				url: $(this).attr('data-cms') + "/sproof_dbaccess.php",
				data: "password="+password,
				success: function(msg){
					if (msg.length == 0) {
						$('#passwordForm .buttons').append('<div class="success">Incorrect Password. Please Retry.</div>');

						setTimeout(function() {
							$('.success').fadeOut('fast', function() {
								$(this).remove();
							})
						}, 3000);
					} else {
						window.location.replace(rootPath+'proofing/login.php?gallery'+msg);
					}
				}
			});
			return false;
		});

		$('#password').change(function() {
			$('#password').removeClass('error');
			$('label.error').remove();
		});
	},

	loadPasswordPrompt : function() {
		$('.password-box').css('margin-top', ($('#ajax').height() - 180) / 2);

		var password = $('input[type="password"]');

		$('.password-box form').submit(function(e) {
			e.preventDefault();

			var location = window.location.href;
			if (track) {
				location = window.location.href.split('#!/')[0]+'?s='+window.location.href.split('#!/')[1]
			}

			$.ajax({
				url : window.location.href,
				type : 'POST',
				data : 'password='+password.val(),
				success : function(data) {
					if (data == 'success') {
						initialise.changePage($('.page-container').data('passwordslug'));
					} else {
						password.css('border-color', 'red');
					}
				}
			});
		});

		$(window).resize(function() {
			$('.password-box').css('margin-top', ($('#ajax').height() - 180) / 2);
		});

		password.change(function() {
			$(this).css('border-color', '#aaa');
		});
	},

	// Loads Contact Page
	loadContact : function() {
		positionImages();
		resizeText();

		// Set up slideshow
		var images = $('#fotoblock img');
		if ($(images).length > 1)	{
			$('#fotoblock').cycle({
				slideResize: 0,
				slideExpr : 'img:not(.img-overlay img)',
				timeout : slideshowTimer,
				before : function(currSlideElement, nextSlideElement) {
					if ( ! $(nextSlideElement).data('loaded')) {
						$('#fotoblock').cycle('pause');
						$('body').addClass('image-not-loaded');
						return;
					}
				}
			});
		} else {
			$(images).fadeIn();
		}

        if (!this._form)
        {
            this._form = new com.cmd.view.Form($('#contactForm'));
            this._form.registerEventListeners();
        }
	},

	// Photo page logic
	loadPhoto : function() {
		$('#fotoblock').height($('#ajax').height() - 20 - 43);
		getSliderWidth();

		$('.page-container').css('background',$('.page-container').data('sub_background'));

		if ($('#fotoblock img').length) {
			// Caption
			var caption = $('#fotoblock img').first().data('caption');
			if (caption) {
				$('.caption-text').html(caption);
			} else {
				$('#caption').css('opacity', 0);
			}
		}

		// Thumb Action
		$('.sliderIn a').first().addClass('current');

		$("#right:not(.off)").click(function(e) {

			var slideTo = $(slider).width() - 160;
			var position = parseInt($('.sliderIn').css('margin-left'));
			var maxPosition = (sliderInner - sliderWidth + 160) * -1;

			// Protect against rapid clicking
			if ($(this).attr('class') == 'off') {
				return false;
			}
			$(this).attr('class', 'off');

			e.preventDefault();
			if (position > maxPosition) {
				if (position - slideTo > maxPosition) {
					$(".sliderIn").animate({"margin-left": '-='+slideTo}, 300, function() {
						$('#right').attr('class', '');
					});
				} else {
					slideTo = maxPosition - position > 0 ? maxPosition - position : (maxPosition - position) * -1;
					$(".sliderIn").animate({"margin-left": "-="+slideTo+"px"});
				}
			}

			$("#left").removeClass("off");
		});


		$("#left").click(function(e){
			var slideTo = $(slider).width() - 160;
			var position = parseInt($('.sliderIn').css('margin-left'));
			var maxPosition = (sliderInner - sliderWidth + 160) * -1;

			// Protect against rapid clicking
			if ($(this).attr('class') == 'off') {
				return false;
			}
			$(this).attr('class', 'off');

			e.preventDefault();

			if (position < 0) {
				if (position + slideTo < 0) {
					$(".sliderIn").animate({"margin-left": '+='+slideTo}, function() {
						$('#left').attr('class', '');
					});
				} else {
					slideTo = position > 0 ? position : position * -1;
					$(".sliderIn").animate({"margin-left": "+="+slideTo+"px"});
				}
			}

			$("#right").removeClass("off");
		});

		$('.sliderIn a').click(function(e) {
			e.preventDefault();

			$('#fotoblock').cycle($(this).index()).show();
			$('#fotoblock').cycle('pause');
			$('.start,.stop').attr('class', 'stop');
		});

		$('.sliderIn a').hover(function() {
			if ( ! $(this).find('img').hasClass('visible')) {
				$(this).find('img').addClass('temp-select').fadeIn(200);
			}
		}, function() {
			if ( ! $(this).find('img').hasClass('visible')) {
				$(this).find('img').fadeOut(200, function() {
					$(this).removeClass('temp-select');
				});
			}
		})

		$('#thumbs').click(function(evt) {
			evt.preventDefault();

			if($('.sliderIn .visible').length) {
				$('.sliderIn img').removeClass('visible').fadeOut();
			} else {
				$('.sliderIn img').addClass('visible').fadeIn();
			}
		});

		// Set up slideshow
		var images = $('#fotoblock img');
		if ($(images).length > 1) {
			var slideshowSpeed = slideshow_type == 'fade' ? 800 : 300;
			$('#fotoblock').cycle({
				slideResize: 0,
				fx: slideshow_type,
				speed: slideshowSpeed,
				timeout : slideshowTimer,
				before : function(currSlideElement, nextSlideElement) {
					if ( ! $(nextSlideElement).data('loaded')) {
						$('#fotoblock').cycle('pause');
						$('body').addClass('image-not-loaded');
						return;
					}

					// Apply Thumb Styles
					$('.sliderIn a').removeClass('current');
					var id = $(nextSlideElement).attr('id');
					$('a[rel="'+id+'"]').addClass('current');

					// Show / Hide Caption
					var caption = $(nextSlideElement).data('caption');

					if (caption.length) {
						$('#caption').css('opacity', '1');
						$('.caption-text').html(caption);
					} else {
						$('.caption-text').html('');
						$('#caption').css('opacity', '0');
					}

				}
			})

			if ( ! slideshowStart) {
				$('#fotoblock').cycle('pause');
				$('#fotoblock').addClass('paused');
				$('#slide').addClass('slideOff');
				$('#startStop').attr('class', 'stop');
			} else {
				$('.slideshow_label').html('Stop Slideshow');
				$('#caption,.mouse-left, .mouse-right, .mouse-close').show();
				$('#startStop').attr('class', 'start');
			}
		} else {
			$(images).fadeIn();
			$('#startStop,#thumbs,#slider,.prev-image,.next-image').css('display', 'none');
		}

		// Start / Stop slideshow
		$('.stop').live('click', function(e) {
			e.preventDefault();
			$('#fotoblock').cycle('resume');
			$(this).attr('class', 'start');
		});
		$('.start').live('click', function(e) {
			e.preventDefault();
			$('#fotoblock').cycle('pause');
			$(this).attr('class', 'stop');
		});

		// Next / Previous Image
		$('.prev-image').click(function(e) {
			e.preventDefault();
			$('#fotoblock').cycle('prev');
			$('#fotoblock').cycle('pause');
			$('#startStop').attr('class', 'stop');
		});

		$('.next-image').click(function(e) {
			e.preventDefault();
			$('#fotoblock').cycle('next');
			$('#fotoblock').cycle('pause');
			$('#startStop').attr('class', 'stop');
		});


	},
	loadPhoto2 : function() {


		$('#photoSlider2, #photoSlider3').zoomit("update");
		$('#photoSlider2, #photoSlider3').mCustomScrollbar("update");
	},

	loadVideos : function() {

		// Update colors to reflect navigation
		var color = $('a.selected').css('color');
		var background = $('a.selected').css('background-color');
		$('.page label').css({
			'color' : color,
			'background' : background
		});

		if (videoSettings.videoThumbnailSize == 1) {
			pages.setThumbnailsCSS();
			pages.centerThumbnailsY($('.six section a'));
		} else {
			pages.run({width:$('#ajax').width(),height:$('#ajax').height()});
	        pages.updateThumbnailsLayout();
        	pages.setThumbnailsCSS();
	    }
		pages.videoEvents();

        if ($('body').data('music'))
        {
            if (music && music.isPlaying()) music.togglePlayPause();
        }
	},
	loadSubmenu : function() {
		if ($('body').data('music')) {
			$('#ajax a[data-ajax-url]').each(function() {
				//$(this).attr('href', url+'#!/'+$(this).data('slug'));
				//$(this).attr('href', '?p#'+$(this).data('slug'));
			});
		}

		// Load Background
		if ($('#fotoblock img').length) {
			var background = '#'+$('#fotoblock img').first().data('background');
			initialise.changeBodyBackground(background);
		}

		// Load Slideshow
		var images = $('#fotoblock img');
		if ($(images).length > 1) {
			var slideshowSpeed = slideshow_type == 'fade' ? 800 : 300;
			$('#fotoblock').cycle({
				slideResize: 0,
				fx: slideshow_type,
				speed: slideshowSpeed,
				timeout : slideshowTimer,
				before : function(currSlideElement, nextSlideElement) {
					if ( ! $(nextSlideElement).data('loaded')) {
						$('#fotoblock').cycle('pause');
						$('body').addClass('image-not-loaded');
						return;
					}

					// Body background colors.
					var newBg = $(nextSlideElement).first().data('background').toString();
					if (newBg == '#') {
						newBg = '#'+$('.page-container').data('background');
					}
					initialise.changeBodyBackground(newBg);
				}
			});
		} else {
			$(images).fadeIn();
		}

		// Update colors to reflect navigation
		var color = $('a.selected').css('color');
		var background = $('a.selected').css('background-color');
		$('.page label').css({
			'color' : color,
			'background' : background
		});

		if (videoSettings.videoThumbnailSize == 1) {
			pages.setThumbnailsCSS();
			pages.centerThumbnailsY($('.six section a'));
		} else {
			pages.run({width:$('#ajax').width(),height:$('#ajax').height()});
        	pages.setThumbnailsCSS();
	        pages.updateThumbnailsLayout();
	    }
	},

	// Change Body background
	changeBodyBackground : function(background) {
		if (background != '#0' && background != '#' && background != '##') {
			changeBodyBackground(background,'body');
		}
	}

}

/**
 * Resize and Position Images / Text Boxes
 */
function positionImages() {
	var imgWidth, imgHeight;

	var theBorderSize = borderWidth;

	// If text page use photo box dimensions
	if ($('.slide-text').length) {
		var docWidth = $('#fotoblock').width();
		var docHeight = $('#ajax').height();
		theBorderSize = 0;
	// If gallery page
	} else if ($('.slide-gallery').length) {
		var docWidth = $('#ajax').width();
		var docHeight = $('#ajax').height() - 60;
	} else {
		var docWidth = $('#ajax').width();
		var docHeight = $('#ajax').height();
	}

	$('#fotoblock, .prev-image, .next-image').height(docHeight);

	// Loop through images - resize down if required - center using margins.
	if ($('#fotoblock img').length) {
		$('#fotoblock img').each(function() {
			resizeDefault(this, docWidth, docHeight, theBorderSize);
		});
	}
}

function resizeDefault(img, width, height, theBorderSize) {
	imgWidth = $(img).attr('width');
	imgHeight = $(img).attr('height');

	// Correct for magic 3px height of thumbs
	if ($('#photoSlider').length) {
		height -= 3;
	}

	if (imgWidth > width) {
		var ratio = imgHeight / imgWidth;
		imgWidth = width;
		imgHeight = imgWidth * ratio;
	}

	if (imgHeight > height) {
		var ratio = imgWidth / imgHeight;
		imgHeight = height;
		imgWidth = imgHeight * ratio;
	}

	var marginLeft = (width - imgWidth) / 2;
	var marginTop = (height - imgHeight) / 2;

	// Fix issue on text pages where resizing is a % of a pixel out leaving a 1px border.
	if (theBorderSize == 0) {
		if (marginTop <= 1) {
			marginTop = 0;
			imgHeight += 1;
		}
		if (marginLeft <= 1) {
			marginLeft = 0;
			imgWidth += 1;
		}
	}

	$(img).css({'width':imgWidth-(theBorderSize*2), 'height':imgHeight-(theBorderSize*2), 'margin-left':marginLeft, 'margin-top':marginTop});
}

function resizeText() {
	if ($('#textBlock').length) {
	//	$('#textBlock').css('height', ($(window).height()-socialBarHeight-20)+'px');
	}
}

// Detect isiPad
function isiPad(){
    return navigator.userAgent.match(/iPad/i) != null;
}

// Loaded
function loaded(el) {
	$(el).attr('data-loaded', 1);
	if ($('body').hasClass('image-not-loaded')) {
		if ( ! $('#fotoblock').hasClass('paused')) {
			$('#fotoblock').cycle('resume');
			$('body').removeClass('image-not-loaded');
		}
	}
}

function getSliderWidth() {

	var thumbWidth = 63;
	var thumbs = $('.sliderIn a').length;

	// Determine slider and inner widths
	sliderWidth = $('#ajax').width();
	sliderInner = (thumbs * thumbWidth);

	// Set inner width
	$('.sliderIn').css({
		'width' : sliderInner+'px'
	});

	// If inner width > outer width. Show right / left nav. Apply relevant margin.

	if (sliderInner+160 > sliderWidth) {
		$('#move').show();
	} else {
		// The left side is 100px, right is 60px. There is chance of getting a negative margin as the page width is lessened.
		// We need to set marginLeft to 0 if below 0;
		var marginLeft = ((sliderWidth - sliderInner) / 2) - 100;
		if (marginLeft < 0) {
			marginLeft = 0;
		}

		// Center + Add left margin.
		$('.sliderIn').css({
			'margin-left' : marginLeft,
			'width' : sliderInner
		});


		$('#move').hide();
	}
}

function preparePage() {
	var imageRatio = 1.6;
	var reverseImageRatio = 1 / 1.6;
	var headerHeight = $('#header').height()+30;
	var windowWidth = $(window).width();
	var socialBar = $('.has-social-bar').length ? 30 : 0;
	var windowHeight = $(window).height() - socialBar;
	var templateHeight;
	var contentWidth = 800;
	var contentHeight = 600;
	var textBoxRatio = 0.72;
	var windowMinHeight = 540 + headerHeight + 20;

	windowWidth = ((windowWidth < 800) ? 800 : windowWidth) - 60;
	windowHeight = ((windowHeight < windowMinHeight) ? windowMinHeight : windowHeight) - 20;

	// Work out the maximum size of the website.
	contentHeight = windowHeight - headerHeight;

	if (windowWidth > contentHeight * imageRatio) {
		contentWidth = contentHeight * imageRatio;
		templateHeight = windowHeight;
	} else {
		contentWidth = windowWidth;
		templateHeight = contentWidth * reverseImageRatio + headerHeight;
	}

	templateHeight = parseInt(templateHeight);

	// Set the dimensions of the template.
	$('.template').css({'width':contentWidth+'px', 'height':templateHeight+'px'});


	// If there is no logo image we may need to tweak the navigation.
	if ( ! $('#header h1 img').length) {
		var navLength = 0;

		// We clone h1 because if we remove the float it will display as 100% width.
		// This gives us the accurate width.
		if ( ! $('h1.clone').length) {
			var clone = $('#header h1').clone().css({
				'display' : 'inline-block',
				'opacity' : 0
			}).addClass('clone');
			$('body').append(clone);
		}

		// 20 = Margin; 81 = social icon width
		var logoWidth = $('h1.clone').width() + 20 + 81;
		$('#nav li:not(ul ul li)').each(function() {
			navLength += $(this).width();
		});

		if (contentWidth < logoWidth + navLength) {
			$('#header').addClass('nav-below-logo');
		} else {
			$('#header').removeClass('nav-below-logo');
		}

		// Correct headerHeight
		var headerHeight = $('#header').height()+30;
	}

	contentWidth = parseInt(contentWidth);
	contentHeight = templateHeight - headerHeight;


	$('#ajax').css({'margin-top':headerHeight, 'width':contentWidth+'px', 'height':(contentHeight)+'px'});

	// Set Gallery Size
	$('#fotoblock, #fotoblockIn').height(contentHeight - 62);

	// Set the Text Page Sizes
	var textPhotoWidth = Math.ceil(contentHeight * textBoxRatio);
	if ($('.text-wrapper-full').length) {
		var textBoxWidth = contentWidth - 10;
	} else {
		var textBoxWidth = contentWidth - textPhotoWidth - 10;
	}

	$('.slide-text').width(textPhotoWidth);
	$('.text-video').width(textPhotoWidth);
	$('#textBlock').width(textBoxWidth).height(contentHeight - 10);

	var templateMargin = (($(window).height() - templateHeight) / 2) - 20;
	$('.template').css('padding-top', ((templateMargin > 0) ? templateMargin : 0) + 'px');
}

function setHeader() {
	if ($('h1 img').length) {
		var logoWidth = $('h1 img').attr('width');
		var logoHeight = $('h1 img').attr('height');
		var actualWidth = $('h1 img').width();
		var origLogoHeight = $('h1 img').height();
		var socialWidth = $('.social-icons').width();
		var navWidth = $('#nav').width()
		var setMargins = false;

		var maxLogoWidth = $('#header').width() - navWidth - socialWidth - 30;

		if (maxLogoWidth < actualWidth)
		{
			// Get logo height
			var ratio = logoHeight / logoWidth;
			logoWidth = logoWidth * 0.5;
			logoHeight = logoWidth * ratio;

			// Apply new styles
			$('h1').css({'width':logoWidth, 'margin-right':0, 'position' : 'absolute', 'left' : 0, 'top' : 0});
			$('h1 img').width(logoWidth).height(logoHeight);
			$('.social-icons').css({'position' : 'absolute', 'right' : 0, 'top' : 0, 'margin' : 0});
			$('#nav li:not(#nav ul ul li)').css({'margin-top':(logoHeight + 5)+'px', 'margin-left':0});
			$('#nav li:first-child a:not(#nav ul ul li:first-child a)').css({'padding-left' : 0});
		}
		else if (maxLogoWidth > logoWidth)
		{
			$('h1 img').css({'width':'auto', 'height':'auto'});
			$('h1').css({'width':logoWidth, 'margin-right':'20px', 'position' : 'static'});
			$('.social-icons').css({'position':'static'});
			setMargins = true;
		}

		if (logoHeight > origLogoHeight) {
			logoHeight = origLogoHeight;
		}

		var headerHeight = logoHeight > $('#header').height() ? logoHeight : logoHeight;
	} else {
		var headerHeight = $('#header h1 a').css('font-size');
	}

	if ( setMargins)
	{
		var navHeight = parseInt($('#nav a').first().css('font-size')) + 6;
		var navMargin = (headerHeight - navHeight) / 2;
		var socialHeight = 23;
		var socialMargin = (headerHeight - socialHeight) / 2;
		$('#nav li:not(#nav ul ul li)').css('margin-top', navMargin);
		$('.social-icons').css('margin-top', socialMargin);
	}
}

function strpad(val) {

	if (val === '') {
		return val;
	}

	var str = '';

	if (val.length < 6) {
		for (i=0; i < 6-val.length; i++) {
			str += '0';
		}
	}

	str += val;

	return str;
}

// Help stat trackers log page views
function registerPageView(slug) {
	// Variants of GA
	if (typeof ga != 'undefined') {
		ga('send', 'pageview');
	}

	if (typeof _gaq != 'undefined') {
		_gaq.push(['_trackPageview', slug]);
	}

	if (typeof pageTracker != 'undefined') {
		pageTracker._trackPageview('/some-page');
	}
}