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

// Resize Elements
function resizeElements() {
	var imgs = $('.slide img');

	ratio = 1.6;
	width = $(window).height() * ratio;

	var bodyWidth = $(window).width();

	if (width > bodyWidth) {
		width = bodyWidth;
	}

	if (width > 1920) {
		width = 1920;
	}
	
	$('.site-container').width(width);	

	var windowWidth = $('.site-container').width();
	var windowHeight = $('.site-container').height();
	
	if (imgs.length) {
		$(imgs).each(function() {
			var imgWidth = $(this).attr('width');
			var imgHeight = $(this).attr('height');

			var windowRatioW = windowWidth / windowHeight;
			var imgRatioW = imgWidth / imgHeight;

			// If is letterbox and screen isn't.
			if (imgRatioW > windowRatioW) {
				
			} else {
				// Resize to Width
				if (imgWidth > windowWidth) {
					var ratio = windowWidth / imgWidth;
					imgHeight = ratio * imgHeight;
					imgWidth = windowWidth;
				}
			}

			// Resize To Height
			if (imgHeight > windowHeight) {
				var ratio = windowHeight / imgHeight;
				imgWidth = ratio * imgWidth;
				imgHeight = windowHeight;
			}
			
			var left = (windowWidth - imgWidth) / 2;
			var top = (imgHeight > windowHeight) ? 0 : ((windowHeight - imgHeight) / 2);

			$(this).css({'width':imgWidth+'px', 'height':imgHeight+'px', 'margin-left':left+'px', 'margin-top':top+'px'});

		});
	}

	var txtWrap = $('.text-wrapper');
	if (txtWrap.length) {
		var space = windowHeight - 170 - 70; // 50 Footer + 60 + 60 Margins + 70 padding
		$(txtWrap).height(space);
	}

}

/**
 * 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() {

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

	// Remove the caption if it exists
	if ($('.caption').length) {
		$('.caption').animate({'opacity':0}, 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++;
			}
		}

		var background = $(slideImgs[current]).attr('data-background');
		if ($(slideImgs[current]).attr('data-background')) {
			$('body').animate({'background-color':'#'+background}, 400);
		}

		$(slideImgs[current]).fadeIn(500, function() {
			// Look for a caption.
			var caption = $(slideImgs[current]).attr('alt');
			if (caption) {
				$('.home-wrapper').append('<p class="caption" style="color:'+$('.selected').attr('data-rollover')+'">'+caption+'</p>');
			}

			// Update the thumbs if they exist.
			var thumbs = $('.thumbs');
			if (thumbs.length) {
				var identifier = $(slideImgs[current]).attr('id');
				$(thumbs).find('img.selected').removeClass('selected');
				$(thumbs).find('.'+identifier+' img').addClass('selected');
			}
		
			clearTimeout(timeoutID);
			
			if (previousCurrent) {
				previousCurrent = false;
			}

			if ( ! end) {
				timeoutID = setTimeout("slideshow()", slideshowTimer);
			} else {
				end = false;
				$('.slideshow-control').attr('id', 'slideshowOff');
			}
		});
	});
}

function slideshowDisplayImage() {
	if ( ! $(slideImgs[current]).attr('data-loaded')) {
		clearTimeout(timeoutID);
		timeoutID = setTimeout("slideshowDisplayImage()", 200);
		return;
	} else {
		clearTimeout(timeoutID);
	}
			
	var background = $(slideImgs[current]).attr('data-background');
	if (background.length) {
		$('body').animate({'background-color':'#'+background}, 400);
	}
	
	$(slideImgs[current]).fadeIn(500, function() {
		var caption = $(slideImgs[current]).attr('alt');
		if (caption) {
			$('.home-wrapper').append('<p class="caption" style="color:'+$('.selected').attr('data-rollover')+'">'+caption+'</p>');
		} 
			
		if (slideImgs.length > 1) {
			if ( $('.thumbs').length && ! slideshowStart ) {
				$('.slideshow-status').data('status', 'on');
			} else {
				timeoutID = setTimeout("slideshow()", slideshowTimer);
			}
		}
	});
}

function prepThumbs(thumbs) {
	$('.thumbs-inner').css('margin-left', 0);
	$('.left').css('opacity', 0.6).data('clickable', false);

	// Count Images, set inner thumbs width
	var ti = $('.thumbs-inner');
	var totalThumbs = $('.thumbs-inner img').length;
	var innerThumbWidth = totalThumbs * 51;
	$('.thumbs-inner').width(innerThumbWidth);


	// Determine Thumbs Width
	var windowWidth = $('footer').width();
	var navWidth = $('footer nav').width();
	var h1Width = $('h1').width();
	var thumbsWidth = windowWidth - navWidth - h1Width - 60 - 1; // 20px = 10 + 10 for nav + h1 padding. 40px = thumb margins

	$(thumbs).width(thumbsWidth); 

	if (thumbsWidth < 60) {
		$(thumbs).hide();
	} else {
		$(thumbs).show();
	}

	// Define thumbs container width.
	var thumbContainerWidth = thumbsWidth - 60
	$('.thumbs-container').width(thumbContainerWidth); // 60 accounts for thumb controls + play button

	// Decide if we need the left / right arrows
	if ( innerThumbWidth > thumbContainerWidth) {
		$('.left, .right').show();
		$('.right').css('opacity', 1);

		// Define how far thumbs should slide.
		var slideDistance = thumbContainerWidth;

		$('.right:not(.right[data-clickable="false"])').unbind();
		$('.left:not(.left[data-clickable="false"])').unbind();

		// Right Arrow
		$('.right:not(.right[data-clickable="false"])').click(function() {
			var ti = $('.thumbs-inner');
			var thumbsPos = parseInt($(ti).css('margin-left'));

			// Is there room to slide?
			if (innerThumbWidth - thumbContainerWidth + thumbsPos) {
				// Determine move distance. Mutiply by -1 to force a positive number
				var move = (thumbsPos - slideDistance) * -1;

				if (innerThumbWidth > move + thumbContainerWidth) { // Loads of space!
					$(ti).animate({'margin-left':'-'+move+'px'}, 300);
				} else { // We have reached the end
					$(ti).animate({'margin-left':'-'+(innerThumbWidth - thumbContainerWidth)+'px'}, 300);
					$(this).css('opacity', 0.6).data('clickable', false);
				}

				$('.left').css('opacity', 1).removeData('clickable');
			}
		});

		// Left Arrow
		$('.left:not(.left[data-clickable="false"])').click(function() {
			var ti = $('.thumbs-inner');
			var thumbsPos = parseInt($(ti).css('margin-left')) * -1;

			// Is there room to slide?
			if (thumbsPos != 0) {
				
				// Determine move distance.
				var move = (thumbsPos - slideDistance);

				if (move > 0) { // Loads of space!
					$(ti).animate({'margin-left':'-'+move+'px'}, 300);
				} else { // We have reached the end
					$(ti).animate({'margin-left':0}, 300);
					$(this).css('opacity', 0.6).data('clickable', false);
				}
				
				$('.right').css('opacity', 1).removeData('clickable');
			}
		});
	} else { // If thumbs are less than container width
		$('.left, .right').hide();
	}

	$('.slideshow-control').unbind();
	$('.thumbs-inner a').unbind();
	
	// Start / Stop Slideshow
	$('.slideshow-control').click(function() {
		if ($(this).attr('id') == 'slideshowOn') {
			clearTimeout(timeoutID);
			$(this).attr('id', 'slideshowOff');
		} else {
			$(this).attr('id', 'slideshowOn');
			slideshow();
		}
	});

	// Click on a Thumbnail.
	$('.thumbs-inner a').click(function(e) {
		e.preventDefault();

		clearTimeout(timeoutID);
		end = true
		previousCurrent = current;
		current = $(this).attr('class').substring(5) - 1;
		slideshow();
	});
}

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


$(document).ready(function() {

	resizeElements();

	$(window).resize(function() {
		resizeElements();
	});

	/**
	 * Vertically Center h1
	 */
	$('h1').css('margin-top', ((50 - $('h1 a').height()) / 2)+'px');
	
	// Slideshows
	slideImgs = $('.slide img');
	if ($(slideImgs).length) {
		current = 0;
		end = false;
		previousCurrent = false
		timeoutID = 0;
		slideshowDisplayImage();



		if (! slideshowStart) {
			$('.slideshow-control').attr('id', 'slideshowOff');
		} else {
			$('.slideshow-control').attr('id', 'slideshowOn');
		}
	}

	/**
	 * Gallery Thumbs + Slideshow Controls
	 */
	var thumbs = $('#thumbs');
	if (thumbs.length) {

		// Temporary hack
		setTimeout(function() { prepThumbs(thumbs); }, 700);

		$(window).resize(function() {
			prepThumbs($('#thumbs'));
		});
	}
	
	/**
	 * Password Page Validation
	 */
	var pwdForm = $('#passwordForm');
	if (pwdForm.length) {
		$('#passwordForm').submit(function(e) {
			var password = $('#password').val();
			e.preventDefault();
			$.ajax({
				type: "POST",
				url: $(this).attr('data-cms') + "/sproof_dbaccess.php",
				data: "password="+password,
				success: function(msg){
					if (msg.length == 0) {
						$('#password').parent().addClass('error');
						if ( ! $('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').parent().removeClass('error');
			$('label.error').remove();
		});
	}
	/*
	 * End
	 **/

	/**
	 * Contact Page Validation
	 */
	var conForm = $('#contactForm');
	if (conForm.length) {
		$(conForm).submit(function(evt) {
			$('.error').removeClass('error');

			if ($('.required').length) {
				$('.required').each(function() {
					if ($(this).val() == '' || $(this).val() == $(this).data('label')) {
						$(this).parent().addClass('error');
					}
				});

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

		$('#clear').click(function(e) {
			e.preventDefault();
			if (confirm('Are you use you would like to clear this form?')) {
				$('input[type="text"], textarea').each(function() {
					$(this).val($(this).data('label'));
				});
				$('.error').removeClass('error');
			}
		});

		$('.required').change(function() {
			if ($(this).val() == '') {
				$(this).parent().addClass('error');
			} else {
				$(this).parent().removeClass('error');
			}
		});
	}

	$('input, textarea').focusin(function() {
		if ($(this).val() == $(this).data('label')) {
			$(this).val('');
		}
	});
	$('input, textarea').focusout(function() {
		if ($(this).val() == '') {
			$(this).val($(this).data('label'));
		}
	})
	/*
	 * End
	 **/
	
	 
	/**
	 * Website Navigation
	 */
	// Set Hover State
	$('nav li').hover(function() {
		//$(this).find('a:not(ul ul a)').css('background', 'black');
	}, function() {
		//$(this).find('a:not(ul ul a)').css('background', 'transparent');
	});

	if ($('nav ul ul a.selected').length) {
		$('.selected').parent().parent().parent().find('a:first').addClass('selected');
	}

	$('.selected').css('color', $('.selected').data('rollover'));

	$('nav ul ul a').hover(function() {
		$(this).css('color', $(this).data('rollover'));
	}, function() {
		if ( ! $(this).hasClass('selected')) {
			$(this).css('color', $(this).data('color'));
		}
	})
	
	// 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);
		}
	})

	$('nav a:not(nav ul li ul li a)').hover(function() {
		if ( ! $(this).hasClass('selected')) {
			$(this).find('span:not(span.dupe)').animate({'margin-top': '24px'}, 200);
			$(this).find('span.dupe').animate({'margin-top': '1px'}, 200);
		}
	}, function() {
		if ( ! $(this).hasClass('selected')) {
			if ( $(this).parent().find('ul').css('display') != 'block') {
				$(this).find('span.dupe').animate({'margin-top': '-44px'}, 200);
				$(this).find('span:not(span.dupe)').animate({'margin-top': '28px'}, 200);
			}
		}
	});

	$('nav li:not(nav ul ul li)').hover(function() {}, function() {
		if ($(this).find('ul').length && ! $(this).find('a:first-child').hasClass('selected')) { 
			var parent = $(this).find('a:not(li li a)');

			// Put parent back to normal
			//var parent = $(this).parents('ul').siblings('a');
			$(parent).find('span.dupe').animate({'margin-top': '-44px'}, 200);
			$(parent).find('span:not(span.dupe)').animate({'margin-top': '28px'}, 200);
		}
	});
	
	/*
	 * End
	 **/

	 /**
     * Video Page
	 */
	if ($('#videos').length) {
		var windowHeight = $(window).height();

		// 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 (windowHeight < 520) {
			$('#videos .clear').remove();
			if ($('#videos').width() < 340) {
				videoNavigation(2);
			} else {
				videoNavigation(3);
				var count = 1;
				var videoCount = $('#videos .video').length;
				$('#videos .video').each(function() {
					if(count % 3 == 0 || count == videoCount) {
						$(this).after('<div class="clear"></div>');
					}
					count++;
				});
			}
		} else {
			$('#videos .clear').remove();
			videoNavigation(6);
			var count = 1;
			var videoCount = $('#videos .video').length;
			$('#videos .video').each(function() {
				if(count % 3 == 0 || count == videoCount) {
					$(this).after('<div class="clear"></div>');
				}
				count++;
			});
		}

		function videoVerticalCenter() {
			var centerHeight = ($('.center').height()) ? $('.center').height() : 170;
			var top = (($('.site-container').height() - centerHeight - 50) / 2);
			top = (top > 0) ? top : 0;
			$('.center').css('top', top +'px');
		}
		videoVerticalCenter();

		$(window).resize(function() {
			var windowHeight = $(window).height();

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

			$('#videos').css('height', $('#rightBlock').height());
			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
	 **/
	
})
