// Loaded
function loaded(el) {
	$(el).attr('data-loaded', 1);
}

// Define Window Dimensions
var winHeight = 0;
var winWidth = 0;

// Resize Elements
function resizeElements(pageResized) {
	// Resize content Area
	$('.content-area').css('margin-top', headerHeight+17+'px');

	// Specifiy Window Dimensions
	winHeight = $(window).height();
	winWidth = $(window).width();
	
	// Fix Window to cope when it is too small.
	if (winWidth < 800) {
		winWidth = 800;
		winWidthLessPadding = winWidth - 120;
		$('header').width(800);
		$('.text-wrapper, .content-area').width(winWidthLessPadding);
	} else {
		$('header').css({width:'100%'});
		winWidthLessPadding = winWidth - 120;
		$('.text-wrapper, .content-area').width(winWidthLessPadding);
	}

	// Update Text Wrapper
	var textWrapper = $('.text-wrapper');
	if ($(textWrapper).length) {
		/**
		 * There is a science to defining the correct text wrapper height
		 */
		var maxImageWidth = $('.text-photos').width()+6;
		
		// Work out max height of image.
		var textWrapperHeight = maxImageWidth * 0.625;
		
		$(textWrapper).height(textWrapperHeight);
		
		// Update Text Page Images
		var textPhotos = $('.text-photos');
		var textPhotosWidth = $(textPhotos).width();
		var textPhotosHeight = textWrapperHeight;
		$(textWrapper).find('img').each(function() {
			var imgWidth = $(this).data('width');
			var imgHeight = $(this).data('height');
			if (imgWidth > textPhotosWidth) {
				var ratio = textPhotosWidth / imgWidth;
				imgHeight = ratio * imgHeight;
				imgWidth = textPhotosWidth;
			}
			
			if (imgHeight > textPhotosHeight) {
				var ratio = textPhotosHeight / imgHeight;
				imgWidth = ratio * imgWidth;
				imgHeight = textPhotosHeight;
			}
			
			var left = (textPhotosWidth - imgWidth) / 2;
			var top = (imgHeight > textPhotosHeight) ? 0 : ((textPhotosHeight - imgHeight) / 2);
			$(this).css({'width':imgWidth+'px', 'height':imgHeight+'px', 'left':left+'px', 'top':top+'px'});
		});
				
		// Update Height for Padding
		var innerTextBlockHeight = textWrapperHeight - 20;
		var innerTextBlockWidth = $(textWrapper).width() - maxImageWidth - 20;
		
		// Ammend TextBlock width if there are no images.
		if ( ! $(textWrapper).find('img').length) {
			$(textWrapper).width(((800 < $(window).width()) ? $(window).width() - 120 : winWidthLessPadding));
			innerTextBlockWidth = $(textWrapper).width() - 25;
			$('.text-block').css({'margin-right':'5px'});
		}
		$('.text-block').css({'width':innerTextBlockWidth+'px' , 'height':innerTextBlockHeight+'px'});

	}
	
	var homeWrapper = $('.home-wrapper');
	if ($(homeWrapper).length) {
		$('.content-area').height(winHeight - siteYpadding);
		var contentAreaWidth = $('.content-area').width() - (borderWidth * 2);
		var contentAreaHeight = winHeight - siteYpadding - (borderWidth * 2);
		$(homeWrapper).find('img').each(function() {
			var imgWidth = $(this).data('width');
			var imgHeight = $(this).data('height');
			if (imgWidth > contentAreaWidth) {
				var ratio = contentAreaWidth / imgWidth;
				imgHeight = ratio * imgHeight;
				imgWidth = contentAreaWidth;
			}
			
			if (imgHeight > contentAreaHeight) {
				var ratio = contentAreaHeight / imgHeight;
				imgWidth = ratio * imgWidth;
				imgHeight = contentAreaHeight;
			}
			
			var left = (contentAreaWidth - imgWidth) / 2;
			var top = (imgHeight > contentAreaHeight) ? 0 : ((contentAreaHeight - imgHeight) / 2);
			
			if ($('.home-page').length) {
				$(this).data('left', left+'px');
				left = '-2000';
			};

			$(this).css({'width':imgWidth+'px', 'height':imgHeight+'px', 'left':left+'px', 'top':top+'px'});
		});
	}
	
	// IE7 needs a poke and a kick to get it to vertically center.
	if ($.browser.msie && $.browser.version.substr(0,1) == 7) {
		var header = $('header').height();
		var siteContainer = $('.site-container').height();
		var contentContainer = $('.content-area').height();
		var diff = parseInt((siteContainer - contentContainer) / 2);
		
		if (header > diff) {
			diff = header;
		}
		$('.content-area').css({'top' : diff+'px', 'margin-top' : 0});
	}
}

/**
 * Home page Slideshow
 * slideImgs: object containing the images
 * end: Should the slideshow play after this iteration: true / false
 * previousCurrent: Manually specify the previous image
 */
function slideshow(slideImgs, end, previousCurrent) {

	end = (end) ? true : false;
	
	// Check image is loaded before progressing
	if ( ! $(slideImgs[current]).attr('data-loaded')) {
		clearTimeout(timeoutID);
		timeoutID = setTimeout(function() { slideshow(slideImgs, end) }, 200);
		return;
	} else {
		clearTimeout(timeoutID);
	}

	// Remove the caption if it exists
	if ($('.caption').length) {
		$('.caption').fadeOut(300, function() {
			$('.caption').remove();
		});
	}

	var slideOut = ((previousCurrent || end) ? previousCurrent : current);

	/**
	 * Switch Image
	 * If previous image is specified remove that instead of the current image
	 */
	$(slideImgs[slideOut]).fadeOut(500, function() {
		
		// If the previous image has been specified the current contains the new image and we don't want to change anything.
		if ( ! previousCurrent && ! end) {
			if (current == (slideImgs.length - 1)) {
				current = 0;
			} else {
				current++;
			}
		}
		
		$(slideImgs[current]).fadeIn(500, function() {
			// Look for a caption.
			var caption = $(slideImgs[current]).attr('alt');
			if (caption) {
				var left = parseInt($(slideImgs[current]).css('left')) + 15;
				var top = parseInt($(slideImgs[current]).css('top')) + 15;
				$('.home-wrapper').append('<p class="caption" style="top:'+top+'px;left:'+left+'px">'+caption+'</p>');
			}
			
			// Update the thumbs if they exist.
			var thumbs = $('.thumbs');
			if (thumbs.length) {
				var identifier = $(slideImgs[current]).attr('id');
				$(thumbs).find('img').removeClass('selected');
				$(thumbs).find('.'+identifier+' img').addClass('selected');
			}
		
			clearTimeout(timeoutID);
			
			if ( ! end) {
				timeoutID = setTimeout(function() { slideshow(slideImgs) }, slideshowTimer);
			} else {
				$('.slideshow-status').html('Start Slideshow').data('status', 'on');
			}
		});
	});
}

function slideshowDisplayImage(slideImgs) {
	if ( ! $(slideImgs[current]).attr('data-loaded')) {
		clearTimeout(timeoutID);
		timeoutID = setTimeout(function() { slideshowDisplayImage(slideImgs) }, 200);
		return;
	} else {
		clearTimeout(timeoutID);
	}
	
	$(slideImgs[current]).fadeIn(500, function() {
		var caption = $(slideImgs[current]).attr('alt');
		if (caption) {
			var left = parseInt($(slideImgs[current]).css('left')) + 10;
			var top = parseInt($(slideImgs[current]).css('top')) + 10;
			$('.home-wrapper').append('<p class="caption" style="top:'+top+'px;left:'+left+'px">'+caption+'</p>');
		}
			
		if (slideImgs.length > 1) {
			if ( $('.thumbs').length && ! slideshowStart ) {
				$('.slideshow-status').html('Start Slideshow').data('status', 'on');
			} else {
				timeoutID = setTimeout(function() { slideshow(slideImgs) }, slideshowTimer);
			}
		}
	});
}

/** Video Support Functions **/
function videoVerticalAlignImages() {
	videoHeight = 150;
	
	$('.video img').each(function() {
		var imgHeight = $(this).height();
		var marginTop = (videoHeight - imgHeight) / 2;
		$(this).css('margin-top', marginTop);
	})
}

// Function to move thumbs left / right
function moveThumbsRight(e) {
	e.preventDefault();
	
	// If the control is disabled - quit
	if ($(this).hasClass('control-off')) {
		return;
	}
	
	// Left will be 0 or a negative number
	var left = $('.thumbs-inner').css('margin-left');
	var goLeft = 0;
	var turnControlOff = false;
	
	// Stop if the thumbs cannot move any more left.
	if (actualThumbContainerWidth + left < origThumbContainerWidth) {
		return;
	}
	
	// Determine how far left we want to go.
	if (actualThumbContainerWidth + left - 100 > origThumbContainerWidth) {
		goLeft = left - 100
	} else {
		goLeft = left - (actualThumbContainerWidth - origThumbContainerWidth)
	}
	
	$('.thumbs-inner').css('margin-left', goLeft+'px');
}

$(document).ready(function() {
	headerHeight = $('header').height();
	siteYpadding = headerHeight + 60;
	siteXpadding = 120;

	resizeElements(true);

	$('.overlay').fadeOut();
	
	$(window).resize(function() {
		resizeElements(true);
	});
	
	// Slideshows
	var slideImgs = $('.slide img');
	if ($(slideImgs).length) {
		current = 0;
		timeoutID = 0;
		slideshowDisplayImage(slideImgs);
	}
	
	// Thumbnail Code!
	var thumbs = $('.thumbs');
	if (thumbs.length) {
		var thumbCount = $(thumbs).find('a').length;
		
		// Hide Link
		if (thumbCount == 1) {
			$(thumbs).find('a').css({'cursor':'default'});
		}
		
		// Show image if a thumbnail is clicked.
		$('.thumbs a').click(function(e) {
			e.preventDefault();
			if (thumbCount > 1) {
				clearTimeout(timeoutID);
				previousCurrent = current;
				current = $(this).attr('class').substring(5) - 1;
				slideshow($('.slide img'), true, previousCurrent);
			}
		});
	
		// Calculate actual thumb width and activate controls if width > 100%
		var origThumbContainerWidth = $('.thumbs-container').width();
		var actualThumbContainerWidth = 3;
		
		$('.thumbs-inner img').each(function() {
			actualThumbContainerWidth += $(this).width() + 3;
		});
		
		// If someone resizes the window we need to reset the width attributes
		$(window).resize(function() {
			$('#thumbsLeft').addClass('control-off')
			$('.thumbs-inner').css({'margin-left': 0});
		
			origThumbContainerWidth = $('.thumbs-container').width();
			actualThumbContainerWidth = 3;
			
			$('.thumbs-inner img').each(function() {
				actualThumbContainerWidth += $(this).width() + 3;
			});
			
			// Set new Width
			if ( actualThumbContainerWidth > origThumbContainerWidth) {
				$('.thumbs-inner').width(actualThumbContainerWidth);
				
				// Activate Right Arrow
				$('#thumbsRight').removeClass('control-off');
			} else {
				$('#thumbsRight').addClass('control-off');
			}
		});
		
		// Set new Width
		if ( actualThumbContainerWidth > origThumbContainerWidth) {
			$('.thumbs-inner').width(actualThumbContainerWidth);
			
			// Activate Right Arrow
			$('#thumbsRight').removeClass('control-off');
		}
			
		// If Right arrow is clicked process the request.
		$('#thumbsRight').live('click', function (e) {
			e.preventDefault();
			
			// If the control is disabled - quit
			if ($(this).hasClass('control-off')) {
				return;
			}
			
			// Left will be 0 or a negative number
			var left = parseInt($('.thumbs-inner').css('margin-left'));
			var goLeft = 0;

			if (isNaN(left)) {
				left = 0;
			}
			
			// Stop if the thumbs cannot move any more left.
			if (actualThumbContainerWidth + left <= origThumbContainerWidth) {
				return;
			}
			
			// Determine how far left we want to go.
			if (actualThumbContainerWidth + left - 300 > origThumbContainerWidth) {
				goLeft = left - 300
			} else {
				goLeft = left - ((left + actualThumbContainerWidth) - origThumbContainerWidth);
				$(this).addClass('control-off');
			}

			$('#thumbsLeft').removeClass('control-off');
			$('.thumbs-inner').animate({'margin-left': goLeft+'px'}, 300);
		});
		
		// If Left arrow is clicked. Do shizzle
		$('#thumbsLeft').live('click', function (e) {
			e.preventDefault();
			
			// If the control is disabled - quit
			if ($(this).hasClass('control-off')) {
				return;
			}
			
			// Left will be 0 or a negative number
			var left = parseInt($('.thumbs-inner').css('margin-left'));
			var goLeft = 0;
			
			// Stop if the thumbs cannot move any more left.
			if (left == 0) {
				return;
			}
			
			// Determine how far left we want to go.
			if (left + 300 < 0) {
				goLeft = left + 300
			} else {
				goLeft = 0;
				$(this).addClass('control-off');
			}
			
			$('#thumbsRight').removeClass('control-off');
			$('.thumbs-inner').animate({'margin-left': goLeft+'px'}, 300);
		});
		
		
	}
	
	// Start / Stop Slideshow
	if ($('.slideshow-status').length) {
		if (thumbCount == 1) {
			$('.slideshow-status').html('Start Slideshow').css({'cursor':'default'});
			$('.slideshow-status').click(function(e) {
				e.preventDefault();
			});
		} else {
			$('.slideshow-status').click(function(e) {
				e.preventDefault();
				if ($(this).data('status') == 'off') {
					clearTimeout(timeoutID);
					$(this).html('Start Slideshow').data('status', 'on');
				} else {
					$(this).html('Stop Slideshow').data('status', 'off');
					slideshow($('.slide img'));
				}
				
			});
		}
	}
	
	// Password Page JS
	$('#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) {
					$('#password').addClass('error');
					if ( ! $('#passwordForm label.error').length) {
						$('#password').after('<label for="password" generated="true" class="error" style="display: block; ">This Password is incorrect.</label>');
					}
				} else {
					window.location.replace('proofing/login.php?gallery'+msg);
				}
			}
		});
		return false;
	});

	$('#password').change(function() {
		$('#password').removeClass('error');
		$('label.error').remove();
	});

	/**
     * Contact Page
	 */
	$('#contactForm').submit(function(evt) {
		$('.error').removeClass('error');

		if ($('#contactForm .required').length) {
			$('.required').each(function() {
				if ($(this).val() == '') {
					$(this).parent().addClass('error');
				}
			});

			if ($('.error').length) {
				evt.preventDefault();
			}
		}
	});

	$('#contactForm .required').change(function() {
		if ($(this).val() == '') {
			$(this).parent().addClass('error');
		} else {
			$(this).parent().removeClass('error');
		}
	});
	/*
     * End
	 **/
	 
	/**
     * Video Page
	 */
	if ($('#videos').length) {
		// Correct Video Width
		var videoCount = $('#videos .video').length;
		var center = $('#videos .center');

		if (videoCount == 1) {
			$(center).css('width', '170px');
		} else if(videoCount == 2) {
			$(center).css('width', '340px');
		}
		
		if ( $.browser.msie && $.browser.version == 7.0 ) {
			videoVerticalAlignImages();
		}

		if ($(window).height() < 520) {
			$('#videos .clear').remove();
			if ($('#videos').width() < 340) {
				videoNavigation(2);
			} else {
				videoNavigation(3);
				var count = 1;
				$('#videos .video').each(function() {
					if(count % 3 == 0) {
						$(this).after('<div class="clear"></div>');
					}
					count++;
				});
			}
		} else {
			$('#videos .clear').remove();
			videoNavigation(6);
			var count = 1;
			$('#videos .video').each(function() {
				if(count % 3 == 0) {
					$(this).after('<div class="clear"></div>');
				}
				count++;
			});
		}

		$(window).resize(function() {
			if ($(window).height() < 520) {
				$('#videos .clear').remove();
				if ($('#videos').width() < 340) {
					videoNavigation(2);
				} else {
					videoNavigation(3);
					$('#videos .video').each(function() {
						if(($(this).index() + 1) % 3 == 0) {
							$(this).after('<div class="clear"></div>');
						}
					});
				}
			} else {
				$('#videos .clear').remove();
				videoNavigation(6);
				$('#videos .video').each(function() {
					if(($(this).index() + 1 - $('#videos .clear').length) % 3 == 0) {
						$(this).after('<div class="clear"></div>');
					}
				});
			}

			$('#videos').css('height', $('#rightBlock').height());
			videoVerticalCenter()
		});
	
		function videoVerticalCenter() {
			// IE 7 needs a little extra wuv
			if ($.browser.msie && $.browser.version.substr(0,1) == 7) {
				var centerHeight = ($('.center').height()) ? $('.center').height() : 170;
				var top = (($('.site-container').height() - centerHeight) / 2) - 80;
				top = (top > 0) ? top : 0;
				$('.center').css('top', top +'px');
			}
		}
		videoVerticalCenter();
	}

	function videoNavigation(inc) {
		$('.video').hide();
		$('#video-controls').remove();

		var i = 0;
		var currInc = 1;
		$('.video').each(function() {
			$(this).attr('class', 'video');

			if (i == (inc * currInc)) {
				currInc++;
			}

			$(this).addClass('group'+currInc);
			i++;
		});

		if (currInc > 1) {
			var videoControls = '<div id="video-controls">';
			for(e=1; e <= currInc; e++) {
				videoControls += '<a href="#" class="group'+e+'">'+e+'</a>';
			}
			videoControls += '</div>';
			$('#videos .center').append(videoControls);

			$('#video-controls a').click(function(){
				$('#video-controls a').attr('id', '');
				$(this).attr('id', 'controlOn');
				$('.video').hide();
				$('.'+$(this).attr('class')).css('display', 'inline-block');
				return false;
			});

			$('#video-controls a:first-child').attr('id', 'controlOn');
		}

		$('.group1').css('display', 'inline-block');
	}

	$("#videos a").click(function() {
		if ($(this).hasClass('youtube')) {
			$.fancybox({
				'padding'		: 0,
				'autoScale'		: false,
				'transitionIn'	: 'none',
				'transitionOut'	: 'none',
				'title'			: this.title,
				'width'			: $(this).attr('data-width'),
				'height'		: $(this).attr('data-height'),
				'href'			: this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
				'type'			: 'swf',
				'swf'			: {
					'wmode'		: 'transparent',
					'allowfullscreen'	: 'true'
				}
			});

			return false;
		}

		if ($(this).hasClass('vimeo')) {
			$.fancybox({
				'width' : parseInt($(this).attr('data-width')),
				'height' : parseInt($(this).attr('data-height')),
				'href' : 'http://player.vimeo.com/video/' + $(this).attr('data-video'),
				'autoScale' : true,
				'title'	: this.title,
				'transitionIn' : 'none',
				'transitionOut' : 'none',
				'type' : 'iframe',
				'padding' : 0
			});

			return false;
		}

		return false;
	});
	/*
     * End
	 **/
	 
	/**
	 * Start Menus
	 */
	$('.selected').css('color', $('.selected').data('rollover'));
	
	// Duplicate Top Level Menus
	$('nav a:not(nav ul ul a)').each(function() {
		if ( ! $(this).hasClass('selected')) {
			var span = $(this).find('span').clone();
			$(span).addClass('dupe').css('color', $(this).data('rollover'));
			$(this).prepend(span);
		}
	}).hover(function() {
		if ( ! $(this).hasClass('selected')) {
			$(this).find('span:not(span.dupe)').animate({'margin-top': '15px'}, 200);
			$(this).find('span.dupe').animate({'margin-top': '0'}, 200);
		}
	}, function() {
		if ( ! $(this).hasClass('selected')) {
			if ( $(this).parent().find('ul').css('display') != 'block') {
				$(this).find('span.dupe').animate({'margin-top': '-16px'}, 200);
				$(this).find('span:not(span.dupe)').animate({'margin-top': '1px'}, 200);
			}
		}
	});
	
	// Do the dropdown.
	$('nav').removeClass('default');
	$('nav li:has(ul) a:not(ul ul a)').click(function(e) {
		e.preventDefault();
		//$('nav ul ul').slideUp();

		var ul = $(this).parent().find('ul');
		
		if ( $(ul).css('display') == 'block') {
			$(this).find('.dupe').animate({'margin-top': '-15px'}, 200);
			$(this).find('span:not(span.dupe)').animate({'margin-top': '1px'}, 200);
		}
		
		$(ul).slideToggle();
	});
	
	// Pad Nav elements correctly
	if ($('h1').length) {
		var imgHeight = $('h1').height();
		
		if ( imgHeight > 19) {
			// Work out the padding required to center
			//var padding = (imgHeight / 2) - 18;
			var padding = imgHeight - 18;
			$('nav, section.icons').css('padding-top', padding);
		}
	}
	
	windowHeight = $(window).height();
	$('.thumbs').css('opacity', 0);
	$('html').mousemove(function(event) {
		var diff = windowHeight - 160;
	  	if (event.pageY > diff) {
			$('.thumbs').css('opacity', 1);
	  	} else {
	  		$('.thumbs').css('opacity', 0);
	  	}
	});
	
})
