function thumbLoader() {
  //fade in images after they're loaded
  var imgs = $('ul.grid li a img');

  $(imgs).one('load', function() {
    $(this).fadeIn().parent().addClass('loaded');
  })
  .each(function() {
    if (this.complete || (jQuery.browser.msie && parseInt(jQuery.browser.version) == 6)) {
      $(this).trigger('load');
    } 
  });
}

function scrollAnimation() {
  //Animates scrolling to anchor links. Thanks Karl Swedberg. http://www.learningjquery.com/2007/10/improved-animated-scrolling-script-for-same-page-links
	$('a[href*=#]').click(function() {
	 if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
	 && location.hostname == this.hostname) {
	   var $target = $(this.hash);
	   $target = $target.length && $target
	   || $('[name=' + this.hash.slice(1) +']');
	   if ($target.length) {
	  var targetOffset = $target.offset().top;
	  $('html,body')
	  .animate({scrollTop: targetOffset}, 900);
	    return false;
	   }
	  }
	}); 
}

function catDisplayer() {
	//javascript dropdown category selector
	var cat_list = $('.categories');
	cat_list.hide();

	$('h3.categorizer').click(function() {
		
		$(this).next(cat_list).slideDown('fast');

		$('.category-selector').hover(
			function() {}, 
			function() {
				cat_list.slideUp('fast');
			});
	});
}

function shimBuilder() {
	// Puts an empty <li> shim between grid rows if the grid spans more than 1 row
	// Allows us to use equal columns trick with fake "margins" between rows
	if ($('.grid.blog-posts li').length >= 5) {
		$('.grid.blog-posts li:nth-child(4n)').each(function() {
			$(this).after('<li class="shim"></li>');
		});
	
	} else {
		return false;
	}
}

function hoverOpacity() {
	//animate opacity on hover
	var opacity = 1, toOpacity = 0.7, duration = 200;
	//set opacity ASAP and events
	$('ul.grid li img').css('opacity',opacity).hover(function() {
			$(this).fadeTo(duration,toOpacity);
		}, function() {
			$(this).fadeTo(duration,opacity);
		}
	);
}

function labelHider() {
	// put label inside the form fields but hide them when they're in the way
	$('form .slider label').each(function() {
		//Style the label with JS for progressive enhancement
		$(this).css({
			'position': 'absolute',
			'display': 'inline',
			'top': '6px',
			'left': '5px'
		});

		// grab the input value
		var inputval = $(this).next('input').val();
		var textareaval = $(this).next('textarea').val();
		
		//onload, check if a field is filled out, if so, hide the label TODO: make this work
		if(inputval !== '') {
			$(this).prev('label').hide();
		}		

		// if the input is empty on focus, hide its label
		// if it's empty on blur, show the label
		
		var form_inputs = $('input, textarea');
		
		if (form_inputs.val() !== '') {

			$(this).prev('label').hide();

		}
		
		$(form_inputs).focus(function() {

			$(this).prev('label').hide();	

			}).blur(function() {

				var value = $(this).val();

				if (value === '') {			
					$(this).prev('label').show();
				}		

			});
	});
}

(function($) {
	//jquery plugin to make textarea autogrow
	$.fn.autogrow = function(options) {
    
		this.filter('textarea').each(function() {
    
	    var $this       = $(this),
	        minHeight   = $this.height(),
	        lineHeight  = $this.css('lineHeight');
  
	    var shadow = $('<div></div>').css({
	        position:   'absolute',
	        top:        -10000,
	        left:       -10000,
	        width:      $(this).width(),
	        fontSize:   $this.css('fontSize'),
	        fontFamily: $this.css('fontFamily'),
	        lineHeight: $this.css('lineHeight'),
	        resize:     'none'
	    }).appendTo(document.body);
  
	    var update = function() {
      
	      var val = this.value.replace(/</g, '&lt;')
	                          .replace(/>/g, '&gt;')
	                          .replace(/&/g, '&amp;')
	                          .replace(/\n/g, '<br/>');
   
	      shadow.html(val);
	      $(this).css('height', Math.max(shadow.height() + 20, minHeight));
	    }
  
	    $(this).change(update).keyup(update).keydown(update);
  
	    update.apply(this);
    
		});

		return this;
	}
    
})(jQuery);

function clickFader() {
	//makes body fade out on link click
	$('a').not('a[href*=#]').click(function() {
		$('body').fadeOut();	
	});
}

function contactSubmit() {
  //Enhancements to contactForm in Footer. TODO: fix this
  $('form#contactForm').submit(function() {
		$('form#contactForm .error').remove();
		var hasError = false;
		$('.requiredField').each(function() {
			if(jQuery.trim($(this).val()) == '') {
				var labelText = $(this).prev('label').text();
				$(this).parent().append('<span class="error">You forgot to enter your '+labelText+'.</span>');
				hasError = true;
			} else if($(this).hasClass('email')) {
				var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
				if(!emailReg.test(jQuery.trim($(this).val()))) {
					var labelText = $(this).prev('label').text();
					$(this).parent().append('<span class="error">You entered an invalid '+labelText+'.</span>');
					hasError = true;
				}
			}
		});
		
		if(!hasError) {
      $('form#contactForm li.buttons button').fadeOut('normal', function() {
        $(this).parent().append('');
      });
      var formInput = $(this).serialize();
      $.post($(this).attr('action'), formInput, function(data){
      $("form#contactForm").before('<p class="thanks"><strong>Thanks!</strong> Your message was successfully sent.</p>');
      });
      $("form#contactForm").slideUp("fast",function() {});
    }

		return false;

	});


}

$(function() {  
	
	//stuff to call on document.ready
	//$('textarea').autogrow();
	//shimBuilder();
	//labelHider();
	scrollAnimation();
	catDisplayer();
	hoverOpacity();
  thumbLoader();
	
  //jQuery backed CSS3 support for IE
  $('input[type=hidden]').hide(); 
 
});

