$(document).ready(function() {
	// This is our colors classes in our stylesheet
	var colors = ['color-1', 'color-2', 'color-3', 'color-4', 'color-5', 'color-6'];
	// We need to count
	var i = 0;
	
	// Foreach block date
	$('input.info-date').each(function() {
		// First we add the color class
		$(this).next().addClass(colors[i]);
		// Next we iterate throught all post with the same post date and we add the same class
		$('input[class!="info-date"][value="' + $(this).attr('value') + '"]').each(function() {
			$(this).next().children('.block-icon').addClass(colors[i]);
		});
		// We need to increment now!
		i = (i > 5) ? i = 0 : i = i + 1;
	});
	
	// And now, we want an image for our video post
	$('div[class*=thumb]').each(function() {
		// We want our post id
		var idPost = $(this).attr('class').substring($(this).attr('class').indexOf('thumb_') + 6);
		var videoURL = "";
		var currentEle = this;

		// We load the object into a hidden div and then we try to make a thumbmail
		$(this).append('<div id="info-video-' + idPost + '" style="display:none;"></div>');
		$('#info-video-' + idPost + '').load('/post/' + idPost + ' #content', function() {
			$('#info-video-' + idPost + ' object').children('param').each(function() {
				if($(this).attr('name') == "movie") {
					videoURL = $(this).attr('value');
				}
			});
			
			if(videoURL.indexOf("youtube.com") >=0 || $('iframe[src*=http://www.youtube]').length) {
				var youtubeId;
				
				if(videoURL != "")
				{
					//youtubeId = videoURL.substring(videoURL.indexOf("/v/")+3, videoURL.indexOf("&"));
					youtubeId = videoURL.substring(videoURL.lastIndexOf("/")+1);
					if(youtubeId.indexOf('&') >= 0)
						youtubeId = youtubeId.substring(0, youtubeId.indexOf('&'));
				}
				else
				{
					videoURL = $("iframe").attr("src");
					youtubeId = videoURL.substring(videoURL.lastIndexOf("/")+1);
				}
				
				var thumbURL = "http://i.ytimg.com/vi/"+youtubeId+"/0.jpg";
				$(this).parent().attr('style', 'background: url(' + thumbURL + ') no-repeat center center;');
				$('#info-video-' + idPost).remove();
			}
			else if($('iframe[src*=http://player.vimeo.com]').length) {
				videoURL = $("iframe").attr("src");
				var vimeoId = videoURL.substring(videoURL.lastIndexOf("/")+1);

				$.ajax({
				  url: "http://vimeo.com/api/oembed.json?url=http%3A//vimeo.com/"+vimeoId+"&maxwidth=320&callback=?",
				  dataType: 'jsonp',
				  crossDomain: true,
				  context: document.body,
				  success: function(data, s, a){
					var thumbURL = data.thumbnail_url;
					$('#info-video-' + idPost).parent().attr('style', 'background: url(' + thumbURL + ') no-repeat center center;');
					$('#info-video-' + idPost).remove();
				  }
				});
			}
		});
		
		//$(this).attr('style', 'background: url(' + this.thumbURL + ') no-repeat center center;');
		//$('#info-video-' + idPost + '').remove();
	});
});
