jQuery(document).ready(function($) {	
	
	// Flickr API lookup, trigger on home.
	if ($(document.body).hasClass('home')) {
//		function mysqlDateTimeToDate(datetime) {
//			//function parses mysql datetime string and returns javascript Date object
//			//input has to be in this format: 2007-06-05 15:26:02
//			var regex = /^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
//			var parts = datetime.replace(regex,"$1 $2 $3 $4 $5 $6").split(' ');
//			return new Date(parts[0], parts[1]-1, parts[2], parts[3], parts[4], parts[5]);
//		}
//		
//		function dateToTimestamp(date) {
//			return Math.round(date.getTime()/1000.0);
//		}
		
		// Loading notificaton
		$('#flickrLoader').show();
		$('#articles').attr('class', 'grid_9 pull_3');
		
		var maxPhotosPerArticle = 8;
		$.getJSON(Flickr.API.getPublicPhotosUrl(),
			function(data) {
				$('#flickrLoader').hide();
				$('#articles').attr('class', 'grid_9');
				var photos = data.photos.photo;
//				// Attach Date object to each photo.
//				for (var key in photos) {
//					var date = mysqlDateTimeToDate(photos[key].datetaken);
//					photos[key].date = date
//					//photos[key].timestamptaken = dateToTimestamp(date);
//				}
				
				// Group photos by date diff.
				var tmp;
				var pool = [];
				var prevTimestamp = 0;
				for (var key in photos) {
					if (prevTimestamp === 0 || (parseInt(prevTimestamp) - parseInt(photos[key].dateupload)) > 3600*8) {
						tmp = {
							timestamp: photos[key].dateupload,
							photos: []
						};
						pool.push(tmp);
					}
					tmp.photos.push(photos[key]);
					prevTimestamp = photos[key].dateupload;
				}
				
				// Iterate of each group of photos in the pool and inject where appropriate.
				var articles = $('#articles > div');
				for (var key in pool) {
					articles.each(function() {
						var art = $(this);
						// Check if div is a post and that the timestamp
						if (art.attr('id').replace(/\-\d+/, '') === 'post' && (parseInt(art.attr('timestamp')) - parseInt(pool[key].timestamp)) < 0) {
							var photosCount = pool[key].photos.length;
							var uniqueId = pool[key].timestamp;
							var localDateTime = uniqueId *1000;
							var content = '<div class="post flickr" style="display: none;" id="'+ uniqueId +'">';
								content += '<div class="flickr"></div>';
								content += '<div class="meta"><small>'+ prettyDate(localDateTime) +' Nicklas uploaded</small></div>';
								content += '<h2 class="title"><a href="'+ Flickr.photostreamUrl +'">'+ photosCount +' photos to flickr</a></h2>';
								content += '<div class="content">';
									// For each photo get the correct src and href.
									for (var i = 0; i < photosCount && i < maxPhotosPerArticle; i++) {
										var photo = pool[key].photos[i];
										var href = Flickr.getImgHref(photo.owner, photo.id);
										var src = Flickr.getImgSrc(photo.farm, photo.server, photo.id, photo.secret, 't');
										content += '<div class="item">';
											content += '<a href="'+ href +'"><img src="'+ src +'" /></a>';
										content += '</div>';
									}
									
									if (photosCount > maxPhotosPerArticle) {
										var diff = photosCount-maxPhotosPerArticle;
										content += '<div class="right clearFloats"><a href="'+ Flickr.photostreamUrl +'">'+ diff +' photos more</a></div>';
									}
									content += '<div style="clear:both;"></div>';
								content += '</div>';
							content += '</div>';
							
							
							var flickrArticle = $(content);
							// If first article, change classification...
							if (/first/.test(art.attr('class'))) {
								flickrArticle.attr('class', flickrArticle.attr('class') +' first');
								art.attr('class', art.attr('class').replace(/first/, ''));
							}
							art.before(flickrArticle);
							flickrArticle.slideDown('slow');
							
							// For each photo in new article attach event handlers.
							$('#'+uniqueId).find('img').each(function() {
								$(this).mouseover(function() {
									ImageOverlay.render(Flickr.getBigSrc(this.src));
								}).mouseout(function() {
									ImageOverlay.reset();
								});
							});
							
							// Return false means we stop iterating following articles, to go next item in pool.
							return false;
						}
					});
				}
		});
	}
	
	
	
	

	// RSS link
	$('.rss').hover(function(){
		$(this).parent().css({ color: '#555' });
	});
	
	// Make comments popup links to display comments instead of link
	$('.commentsPopup').bind('click', function() {
		$(this).hide().next().slideDown(500, 'easeOutCirc');
		return false;
	});
	
	
	// Attach AJAX requests to comments
	$('.commentform').submit(function() {
		var self = $(this);
		$("#cwait-"+ self.attr('id').replace(/[^\d]/g, '')).show();
		$.post('/wp-admin/admin-ajax.php', $(this).serialize()+'&action=new_comment', function(obj, textStatus, xmlHttpRequest) {
			if (typeof obj === 'string') {
				ojb = {
					status: 'fail',
					data: obj,
					error_fields: []
				};
			}
			var status = obj.status;
			var data = obj.data;
			var postId = self.attr('id').replace(/[^\d]+/, '');
			$("#cwait-"+ postId).hide();
			if (status === 'success') {
				$("#respond-"+ postId).slideUp(250);
				$("#respond-thanks-"+ postId).delay(500).slideDown(250);
				$("#commentlist-"+ postId).append(data).find('li:last').slideDown(250);
			} else if (status === 'fail') {
				var errors;
				if (typeof data === 'object') {
					errors = data.join('<br \\>');
				} else {
					errors = data;
				}
				var fields = obj.error_fields;
				if ($("#errors-"+ postId).text() === '') {
					$("#errors-"+ postId).css({display:'none'}).html(errors).slideDown(250);
				} else { 
					$("#errors-"+ postId).fadeOut(200, function() { 
						$(this).html(errors).fadeIn(200);
					});
				}
				
				// Remove error class
				$("#commentform-"+ postId +" :input").each(function(){
					$(this).removeClass('error');
				});
				
				// Add error class
				for (var i = 0; i < fields.length; i++) {
					$("#"+ fields[i] +"-"+ postId).addClass('error');
				}
			}
		}, 'json');
		return false;
	});
	
	
	// Make all textareas elastic
	$('textarea').elastic();
	
	
	// Update gravatar when writing a comment
	var update_avatar = function(self) {
		var new_src;
		if (/.+@.+/.test(self.value)) {
			new_src = 'http://www.gravatar.com/avatar/'+ $.md5(self.value) +'?s=96&d=identicon';
		} else {
			new_src = 'http://www.gravatar.com/avatar/ad516503a11cd5ca435acc9bb6523536?s=96&d=identicon&r=X';
		}
		var postId = self.id.replace(/[^\d]+/, '');
		$('#avatar-'+ postId +' img').attr('src', new_src);
	};
	var timeout_update_avatar;
	var update_avatar_with_timeout = function() {
		$(this).doTimeout('timeout_update_avatar', 500, update_avatar, this);
	};
	$('input[name=email]').keyup(update_avatar_with_timeout).change(update_avatar_with_timeout).each(function(){ update_avatar(this); });
	

});