$(document).ready(function() {

	$('#signup #em').focus(function(){
		if(this.value=='Email Address')
			this.value='';
	});
	$('#signup #em').blur(function(){
		if(this.value=='')
			this.value='Email Address';
	});

	// Searchbox show/hide
	$('#search').click(function() { $('#search-box').hide();$(this).next().show();return false; });

	$('#search, #search-hide').toggle(
		function () {
			$('#search-box').show();
		},
		function () {
			$('#search-box').hide();
		}
	);

	// Match column heights
	$("#show-info .meta, #show-info .info").equalHeight();

	// Image Hovers
	$("#right-nav li a, #movie-archive a, .sresult a").hover(
		function(){ // in
			$(this).find('img').stop().animate({ opacity: 1.0 }, 0);
		},
		function(){ // out
			$(this).find('img').stop().animate({ opacity: 0.5 }, 0);
	});

	// Ajax Sidebar Nav
	$('#archive-nav a').click(function(){
		// Disable the link if it has unavailable class
		if($(this).hasClass('unavail')) return false;
		
		// Increment by one each time.
		var increment = 4;
		
		// Get offset - we get #next, but #prev is the same.
		var offset = $("#archive-nav #next").attr("href").match(/offset=([0-9]+)/)[1];
		offset = parseInt(offset);

		// Get maximum number of results.
		var max = $('#ajax-max').attr('href').match(/max=([0-9]+)/)[1];
		max = parseInt(max);
		//alert('max is ' +max);
		
		// Update offset
		if($(this).attr("id") == 'next') {
			offset = offset + increment;
		} else { //prev
			offset = offset - increment;
		}
		
		// If offset is <= 0, make previous unavail and set offset = 0
		if( offset <= 0) { 
			$('#archive-nav #prev').addClass('unavail');
			offset = 0;
			// Should we remove link entirely?
		} else {
			$('#archive-nav #prev').removeClass('unavail');
		}

		// Check if we've exceed the max # of entries 
		if( (offset + increment) >= max ) {
			$('#archive-nav #next').addClass('unavail');
		} else {
			$('#archive-nav #next').removeClass('unavail');
		}

		// Update all offsets
		$('#archive-nav a').attr('href','#offset=' + offset);

		// Actually load content
		$('ul#right-nav, #archive-nav').fadeOut(100,function() {
			$('ul#right-nav').load('/ajax-sidebar/?offset='+offset, function() {
				$('ul#right-nav, #archive-nav').fadeIn(100);
				// Duplicate code from above.
				$("#right-nav li a, #movie-archive a, .sresult a").hover(
					function(){ // in
						$(this).find('img').stop().animate({ opacity: 1.0 }, 0);
					},
					function(){ // out
						$(this).find('img').stop().animate({ opacity: 0.5 }, 0);
				});
			});
		});
		return false;
	});
});

// Equal Heights - adapted from: http://www.cssnewbie.com/equalheights-jquery-plugin/
$.fn.equalHeight = function() {
   tallest = 0;
   this.each(function() {
      thisHeight = $(this).height();
      if(thisHeight > tallest) {
         tallest = thisHeight;
      }
   });
   this.height(tallest);
};


