$(document).ready( function() {

	// Add a 'js' class to the body
	$('body').addClass('js');
	
	// Set up FancyBox
	$('a[href$="png"], a[href$="jpg"]').fancybox({
		'titleShow': false
	});

	/**********
	Image overlay (on mouseover fade to another image)
	**********/
	$('.imgtoggle').each(function() {
		var one = $(this).find('img:first').addClass('one');
		var two = $(this).find('img:last').addClass('two');
		var oneHeight = $(one).height();
		var twoHeight = $(two).height();
		var height;
		
		if (oneHeight != twoHeight) {
			alert('WARNING! Heights do not match');
			height = (oneHeight + twoHeight) / 2;
		}
		else {
			height = oneHeight;
		}
		
		//$(two).css('top', (-1 * height));
		
		$(this).bind({
  			mouseenter: function() {
    				$(two).stop(true, true).fadeOut('fast');
  			},
 			mouseleave: function() {
   				 $(two).stop(true, true).fadeIn('fast');
  			}
		});

	});
	
	
	/**********
	Box Links
	**********/
	
	var originalColor = $('a.box').css('background-color');
	
	$('a.box').bind('focusin mouseover', function() {
		
		$(this).stop().animate({
			backgroundColor: '#ff7b04'
		}, 350);
		
	}).bind('focusout mouseout', function() {
		
		$(this).stop().animate({
			backgroundColor: originalColor
		}, 350);
		
	});
	
	/**********
	Resume
	**********/
	
	$('#resume .image').mouseenter(function() {
		
		var overlay = $(this).find('.overlay');
		
		// IE can not fade in transparent PNGs :( 
		if ($.support.opacity) {
			$(overlay).stop(true, true).fadeIn('fast');
		}
		else {$(overlay).show();}
	}).mouseleave(function() {
	
		var overlay = $(this).find('.overlay');
		
		// ... or fade out transparent PNGs
		if ($.support.opacity) {
			$(overlay).stop(true, true).fadeOut('fast');
		}
		else {$(overlay).hide();}
	});
	
	/**********
	Portfolio Images
	**********/
	
	$('.item .image').each(function() {
		
		// Lets set some variables
		var images = $(this).children('ul');
		var next = $(this).find('a.next');
		var prev = $(this).find('a.prev');
		
		// jQuery data is FUN!
		$.data(images, 'data', {
			imageCount: $(images).children('li').size(),
			imageWidth: 538,
			currentImage: 0
		});
		
		// If there is more than one image
		if ($.data(images, 'data').imageCount > 1) {$(next).show();}
		
		// When the user wants to advance the slideshow
		$(next).click(function() {
		
			var currentImage = $.data(images, 'data').currentImage;
			var nextImage = currentImage + 1;
			var nextMargin = nextImage * $.data(images, 'data').imageWidth;

			// Animate it!
			$(images).animate({
				marginLeft: nextMargin * -1
			}, 350, function() {
				$.data(images, 'data').currentImage = nextImage;
			});
			
			// If we are at the end of the slideshow, hide the 'next' button
			if ($.data(images, 'data').currentImage == $.data(images, 'data').imageCount - 2) {$(this).hide('fast');}
			// Show the 'previous' button
			$(prev).show('fast');
		});
		
		// When the user wants to view the previous slide
		$(prev).click(function() {
		
			var currentImage = $.data(images, 'data').currentImage;
			var nextImage = currentImage - 1;
			var nextMargin = nextImage * $.data(images, 'data').imageWidth;
			
			// Animate it!
			$(images).animate({
				marginLeft: nextMargin * -1
			}, 350, function() {
				$.data(images, 'data').currentImage = nextImage;
			});
			
			// If we are at the beginning of the slideshow, hide the 'previous' button
			if ($.data(images, 'data').currentImage == 1) {$(this).hide('fast');}
			// Show the 'next' button
			$(next).show('fast');
		});

	});
	
	/**********
	Replace form labels and backgrounds
	**********/
	
	// Replace the ugly submit button!
	$('#submit').each(function() {
		var text = $(this).val();
		$(this).replaceWith('<a href="javascript:void(0);" id="submit" class="small">' + text + '</a>');
	});
	
	// Label those text boxes!
	$('input[type="text"], textarea').each(function() {
		
		// Get the URL for the background image
		var imageURL = $(this).css('background-image');
		
		// If there is text already in the input
		if ($(this).val() != '') {
			$(this).css('background-image', 'none');
		}
		
		// Bind some events
		$(this).bind({
			focusin: function() {
				// Get rid of the background image
				$(this).css('background-image', 'none');
			},
			focusout: function() {
				// If there is no text in the input, put the background image back
				if ($(this).val() == '') {
					$(this).css('background-image', imageURL);
				}
			}
		});
	});
	
	/**********
	Comment form
	**********/
	
	// When the comment form is submitted
	$('#comment_form #submit').click(function() {
		var commentForm = $('#comment_form');
		var action = $(this).closest('form').attr('action');
			
		// Hidden inputs
		var ACT = $(commentForm).find('input[name="ACT"]').val();
		var RET = $(commentForm).find('input[name="RET"]').val();
		var URI = $(commentForm).find('input[name="URI"]').val();
		var PRV = $(commentForm).find('input[name="PRV"]').val();
		var XID = $(commentForm).find('input[name="XID"]').val();
		var entry_id = $(commentForm).find('input[name="entry_id"]').val();
		var site_id = $(commentForm).find('input[name="site_id"]').val();
		
		// Other inputs
		var name = $(commentForm).find('input[name="name"]').val();
		var email = $(commentForm).find('input[name="email"]').val();
		var url = $(commentForm).find('input[name="url"]').val();
		var comment = $(commentForm).find('textarea[name="comment"]').val();
		
		// Validate form
		var errors = $('<ul />');
		
		// Validate name
		if (name == '') {
			$(errors).append('<li><span>No name provided</span></li>'); 
		}
		else if (name.length == 1) {
			$(errors).append('<li><span>Name must be more than one character</span></li>'); 
		}
		
		// Validate email
		var emailReg = /^(?=.{5,254})(?:(?:\"[^\"]{1,62}\")|(?:(?!\.)(?!.*\.[.@])[a-z0-9!#$%&'*+\/=?^_`{|}~^.-]{1,64}))@(?:(?:\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\])|(?:(?!-)(?!.*-\$)(?!.*-\.)(?!.*\.-)(?!.*[^n]--)(?!.*[^x]n--)(?!n--)(?!.*[^.]xn--)(?:[a-z0-9-]{1,63}\.){1,127}(?:[a-z0-9-]{1,63})))$/i;
		if (email == '') {
			$(errors).append('<li><span>No email provided</span></li>'); 
		}			
		else if(!emailReg.test(email)) {
			$(errors).append('<li><span>Invalid email provided</span></li>'); 
		}
		
		// Validate url (only if a value is entered)
		if (!(url == '' || url == 'http://')) {
			var urlReg = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
			if(!urlReg.test(url)) {
				$(errors).append('<li><span>Invalid url provided</span></li>'); 
			}
		}
		
		// Validate comment
		if (comment == '') {
			$(errors).append('<li><span>No comment provided</span></li>'); 
		}
		else if (comment.length < 5) {
			$(errors).append('<li><span>Comment must be more than four characters</span></li>'); 
		}
		
		// If we encountered no errors
		if ($(errors).children('li').size() == 0) {
			
			// Post it!
			$.post(action, {
					submit: 'submit',
					ACT: ACT,
					RET: RET,
					URI: URI,
					PRV: PRV,
					XID: XID,
					entry_id: entry_id,
					site_id: site_id,
					name: name,
					email: email,
					url: url,
					comment: comment
				}, function(data){
					if (data == '') {
						// Add new comments...
						$(commentForm).slideUp('slow', function() {
							$('#comments').load(action + ' #comments');
						});
					}
					else {
						// JavaScript validation passed, however ExpressionEngine validation did not
						alert('Error: ' + data);
					}
				});
		}
		// If we encountered errors
		else {$('#errors').html(errors);}

		return false;
	});
	
	/**********
	Contact form
	**********/
		
	$('#contact_form #submit').click(function() {
		var contact_form = $('#contact_form');
		
		$.post($(contact_form).attr('action'),
			$(contact_form).serialize(),
			function(data) {
			
				// Remove "error" class from all inputs
				$(contact_form).find('input, textarea').removeClass('error');
				
				// Success or failure?
				var status = data.status;
				
				// If there were no errors
				if (status == 'success') {
					var name = data.name;
					var from = data.from;
					
					$(contact_form).slideUp('slow', function() {
						$('#success').html('Thank you ' + name + ', your message has been sent').hide().fadeIn('slow');
					});
				}
				
				// If there were errors
				else if (status == 'failure') {
					// The errors shall go here
					var errors = $('<ul />');
					
					for (i in data.errors) {
					
						var name = data.errors[i].name;
						var error = data.errors[i].error;
						var type = data.errors[i].type;
						
						$(errors).append('<li><span>' + error + '</span></li>');
						$('#' + name).addClass('error');
					}
					
					$('#errors').html(errors);
				}
				
				// If something crazy happened
				else {
					var errors = $('<ul />');
					$(errors).append('<li><span>There was an error sending this email, please try again later</span></li>');
					$('#errors').html(errors);
				}
				
			}, 'json');
		
	});

});
