function getBaseURL() {
	pathArray = window.location.href.split( '/' );
	return 'http://' + pathArray[2];
}

function bindVideoClick() {
	$('span.video-title a, a.video-thumbnail').unbind('click');
	$('span.video-title a, a.video-thumbnail').click(function(e) {
		e.preventDefault();
		$('html, body').animate({scrollTop:150}, 'slow'); 
		var clickedVideoLi = $(this).closest('li');
		$('#video-top-metadata span.video-title a').html(clickedVideoLi.find('span.video-title a').text());
		$('#video-top-metadata p.fb-like iframe').attr('src', 'http://www.facebook.com/plugins/like.php?href='+getBaseURL()+'/media/videos?v='+clickedVideoLi.find('span.video-url').text()+'&layout=button_count&show_faces=true&width=200&action=recommend&colorscheme=light');
		$('#video-top-metadata span.video-views span.value').html(clickedVideoLi.find('span.video-views span.value').text());
		$('#video-top-metadata span.video-comments span.value').html(clickedVideoLi.find('span.video-comments span.value').text());
		$('#video-top-metadata span.video-duration span.value').html(clickedVideoLi.find('span.video-duration span.value').text());
		$('#video-top-metadata span.video-post-date').html(clickedVideoLi.find('span.video-post-date').text());
		$('#video-top-metadata span.video-description').html(clickedVideoLi.find('span.video-description').text());
		var video_url = '/media/videos/embed.php?url='+(clickedVideoLi.find('span.video-url').text())+'&size=640&autoplay=true';
		$.ajax({
			url: video_url, 
			success: function(data) {
				if (typeof(console)!="undefined") {
					console.log(data);
				}
				$('#video-top-content').html(data.html);		  	
			},
			error: function(req, msg) {
				if (typeof(console)!="undefined") {
					console.log(msg);
				}				
			},
			dataType: 'json'
		});
	});	
}

$(document).ready(function() {
	bindVideoClick();

	$('#more-videos a').click(function(e) {
		e.preventDefault();
		var get_row_url = '/media/videos/getrow.php?start='+video_count;
		$(this).html("Retrieving more videos from CURE...");
		$.ajax({
			url: get_row_url,
			dataType: 'json',
			error: function(req, msg) {
				if (typeof(console)!="undefined") {
					console.log(msg);
				}				
				$('#more-videos a').html("Error retrieving videos. Click to retry");
			},
			success: function(data) {
				video_count += 4;
				if (video_count >= data.video_count) {
					$('#more-videos a').unbind('click');
					$('#more-videos a').html("More Videos at vimeo.com/cure<span class=\"arrow\">&nbsp;</span>");
				} else {
					$('#more-videos a').html("More Videos from CURE<span class=\"arrow\">&nbsp;</span>");
				}
				$('#video-gallery').append(data.html);
				bindVideoClick();
				$('li.added-videos').slideDown('slow');
			}
		});
	});
});

function playVideo(data) {
	if (typeof(console)!="undefined") {
		console.log(data);
	}
	$('#video-top-content').html(data.html);
}

var video_count = 0;
