$(document).ready(function() {	


// NAVIGATION
	/* Show the donate button when hovered */
	$('div#support').mouseenter(function(){
		$(this).children('a.more').css('width','520px');
		$(this).children('div.donate_now').show();
	});
	
	$('div#support').mouseleave(function(){
		$(this).children('a.more').css('width','405px');
		$(this).children('div.donate_now').hide();
	});
	
	
	
// STORIES & COMMENTS	
	/* Toggle the 'Comments' link if necessary */
	$('ol.commentlist').children('li').each(function() {
			if ( $(this).find('ul.children').size() > 0 ) {
				$(this).find('ul.actions li.show').show();

				var numComments = $(this).find('ul.children').find('li.depth-2').size();
				$(this).find('ul.actions li.show a').text('Comments ('+numComments+')');				
			} else {
				$(this).find('ul.actions li.show').hide();
			}
	});

	/* Toggle comments when 'Comments' link is clicked */
	$('ul.actions li.show a').click(function() {		
		if ( $(this).parents('li').children('ul.children').size() > 0  ) {	
			$(this).parents('li').children('ul').toggle();			
		}
		return false;
	});


	
// PHOTO GALLERY
	$('#flickr a.popup').live('click', function() {
		var getUrl = $(this).attr('rel');
		
		/* Get 20 most recent Flickr photos */
		$('<div id="gallery_popup"></div>').appendTo('#wrapper');
		$('#gallery_popup').hide().fadeIn('normal', getFlickr);
		
		function getFlickr() {
			$.getJSON('http://api.flickr.com/services/feeds/photos_public.gne?id=48850449@N06&lang=en-us&format=json&jsoncallback=?', displayImages);
			
			function displayImages(data) {
				var htmlString = "";
				
				$.each(data.items, function(i,item){
					var sourceSquare = (item.media.m).replace("_m.jpg", "_s.jpg");
					
					htmlString += '<li><a href="#" rel="' + item.media.m + '">';
					htmlString += '<img title="' + item.title + '" src="' + sourceSquare;
					htmlString += '" alt="'; htmlString += item.title + '" />';
					htmlString += '</a></li>';
				});
				
				$('#gallery_popup').append('<h2>Photo Gallery</h2><div id="ajax_content"><div id="full_img"><img id="full" /></div><ul id="thumbnails"></ul></div>');
				$('ul#thumbnails').append(htmlString);
				completeFlickr();
			}
		}
		
		function completeFlickr() {
			$('<a class="close" href="#">Close</a>').appendTo('#gallery_popup');
			$('#gallery_popup').fadeIn(350);
		}
	});
	
	/* Show medium size image (500px) when thumbnail is clicked */ 
	$('ul#thumbnails li a').live('click', function() {
		var photoId = $(this).attr('rel').replace("_m.jpg", ".jpg");
		$('img#full').attr('src',''+photoId+'');		
	});


	/* Close the popup photo gallery, remove from DOM */
	$('#gallery_popup a.close').live('click', function() {
		$('#gallery_popup, #overlay').fadeOut('normal', function() {
			$('#gallery_popup, #overlay').remove(); 
		});
	});
	

});
