jQuery(document).ready(function($){
	
	jQTubeUtil.init({
		key: 'AI39si73J88KqOpnS0qufASk1veyM38Bx1c2n4FNr--LoSh3hQrNI6BT9PsWblRvP_gbX2sQ651gR0ThY1lCABwSL5aFedgPqQ',
		orderby: 'relevance', // optional, available values: relevance, published, viewCount, rating
		time: 'all_time',  // optional,  available values: today, this_week, this_month, all_time
		maxResults: 12
	});
	
	$('.search').keyup(function(){
		var val = $(this).val(); // get '.search' value when the user releases a key on the keyboard
		jQTubeUtil.suggest(val, function(response){
			var html = '';
			for(s in response.suggestions){
				var sug = response.suggestions[s];
				html += '<li><a href="#">'+sug+'</a></li>';
			}
			if (response.suggestions.length)
				$('.autocomplete').html(html).fadeIn(500); // show suggestions if exists
			else 
				$('.autocomplete').fadeOut(500); // hide '.autocomplete' element
		});
	});
	
	
	$('.btn').click(function(){
		show_videos();
		$('.autocomplete').fadeOut(500);
		return false;
	});
	
	$('.autocomplete').find('a').live('click', function(){
		// .live() method is able to affect elements that have not yet been added to the DOM 
		var text = $(this).text();
		$('.blocks').find('.search').val(text);
		$('.autocomplete').fadeOut(500);
		show_videos();
		return false;
	});
	
	function show_videos(){
		var val = $('.blocks').find('.search').val(); // get value from '.search' element
		$('.videos').addClass('preloader').html(''); // add preloader class and clear HTML in '.videos' element
		jQTubeUtil.search(val, function(response){ // init search method
			var html = '';
			for (v in response.videos) {
				var	video = response.videos[v], // YouTube video object
					minutes = parseInt(video.duration / 60),
					seconds = video.duration % 60;
				html += '<li>';
				html += '<p class="image"><a href="http://www.youtube.com/watch?v='+video.videoId+'">';
				html += '<img src="' + video.thumbs[1].url + '" alt="' + video.title + '" title="' + video.title + '" />';
				html += '</a></p>'
				html += '<p class="entry"><a href="http://www.youtube.com/watch?v='+video.videoId+'">' + video.title + '</a>';
				html += '<small>' + minutes + ':' + (seconds < 10 ? '0'+seconds : seconds) + '</small>';
				html += '</p>';
				html += '</li>';
			}
			$('.videos').removeClass('preloader').html(html); // remove preloder class and show videos
		});
	};
		
});
