// JavaScript Document

$(document).ready(function(){
	$("#go").click(doSearch);
	$("#search").keyup(listenToKeys);
	$("#search").keydown(listenToKeysDown);
	$('#giveFeedback').click(feedback);
	$('#search').blur(hideHint);
	$(window).scroll(repos);
	$(window).resize(repos);
	loadPlaylist();
});


function hideHint(){
	setTimeout(function(){
	$('#hint').empty();
	}, 200);
}

function getSearches(){
	if($('#search').val())
		$.get('getsearches.php?term='+$('#search').val(), getSearchesCallback);
	else hideHint();
}

function getSearchesCallback(res){
	var res = res.split('\n');
	$('#hint').empty();
	for(var key in res){
		if(res[key]!='')
			$('<div>').attr('class', 'hintRow').html(res[key]).appendTo('#hint');
	}
	$('#hint').show();
	$('.hintRow').mouseover(hintRowOver);
	$('.hintRow').mousedown(hintRowClick);
}

function listenToKeys(event){
	switch(event.keyCode){
		case 13:
		case 40:
		case 38:
		case 27:
		
		break;
		default:
			getSearches();
		break;
	}
}

function listenToKeysDown(event){
	switch(event.keyCode){
		case 13:
			doSearch();
		break;
		case 40:
			if($('#hint').html()=='') getSearches()
			else if(!$('#selectedHintRow').length) $('#hint').children('div:eq(0)').attr('id', 'selectedHintRow');	
			else{
				var cur = $('#selectedHintRow').removeAttr('id');
				
				if(cur.next().length)
					cur.next().attr('id', 'selectedHintRow');
				else
					$('#hint').children('div:eq(0)').attr('id', 'selectedHintRow');
			}
			event.preventDefault();
		break;
		case 38:
			if($('#hint').html()=='') getSearches()
			else if(!$('#selectedHintRow').length) $('#hint').children('div:last-child').attr('id', 'selectedHintRow');
			else{
				var cur = $('#selectedHintRow').removeAttr('id');
				
				if(cur.prev().length)
					cur.prev().attr('id', 'selectedHintRow');
				else
					$('#hint').children('div:last-child').attr('id', 'selectedHintRow');
			}
			event.preventDefault();
		break;
		case 27:
			hideHint();
		break;
	}
}

function hintRowOver(){
	$('#selectedHintRow').removeAttr('id');
	$(this).attr('id', 'selectedHintRow');
}

function hintRowClick(){
	$('#selectedHintRow').removeAttr('id');
	$(this).attr('id', 'selectedHintRow');
	doSearch();
}

function doSearch(){
	autoplay = false;
	if($('#selectedHintRow').length){
		var res = $('#selectedHintRow').html();
		res = res.replace(/^(.*)\<(b|B)\>(.*)\<\/(b|B)\>(.*)$/, '$1$3$5');
		$('#search').val(res);
	}
	hideHint();
	var srch = $('#search').val();
	if(srch=='') return false;
	$('#res').html('<div class="row">loading...</div>');
	pageTracker._trackPageview('/search:'+srch);
	$.getJSON('/API/Search/', {term:srch}, searchCallBack);
}

var srchO;
function searchCallBack(obj)
{
	srchO = obj;
	var o = obj.items;
	$('#res').empty();
	for(var key in o){
		var holder = $('<div>').attr('id', key).click(resClick).attr('class', 'row');
		if(o[key].thumb) $('<img/>').attr('src', o[key].thumb).appendTo(holder);
		holder.append('<h2>'+o[key].title+' ('+o[key].year+')</h2>');
		
		var hrs = 0;
		var mns = 0;
		var sec = o[key].media.duration;
		for(sec; sec>3600; sec-=3600)
			hrs++;
		for(sec; sec>60; sec-=60)
			mns++;
		
		
		holder.append('<b>Length:</b> '+hrs+':'+(mns<10?'0':'')+mns+':'+(sec<10?'0':'')+sec+'<br/>');
		holder.append('<b>Score:</b> '+(o[key].score==null?0:o[key].score));
		
		var playImg = $('<img />').attr('src', '/images/playlist.png');
		var playL = $('<a>').html('Add to playlist').attr('class', 'addToPlaylist').append(playImg).click(addToPlaylist).prependTo(holder)
		
		$('#res').append(holder).css('visibility', 'visible');
	}
	$('<div>').attr('class', 'clear').appendTo('#res');
	$('.row').mouseover(rowOver).mouseout(rowOut);
	play = null;
	
	if(o.length==0) $('#res').html('<div class="row">No results</div>');
	
	if(autoplay){
		playRow($('#res').children('.row:eq(0)'));
	}
	$('.footer').css('display', 'block');
}

var play;

autoplay = false;
function resClick()
{
	playRow(this);
}

function playRow(row){
	if(play==$(row).attr('id')) return false;
	
	if($('#player').length){
		$('#'+play).css('cursor', 'pointer');
		$('#'+play).children('.title').children('b').remove();
		$('#player').remove();
		$('#'+play).css('background-color', 'transparent');
		$('#'+play).children('.vote').remove();
	}
	
	var o = srchO.items[$(row).attr('id')];
	play = $(row).attr('id');
	
	var vars = new Object();
	var url;
	switch(o.media.mediatype){
		case 1:
			url = 'http://d.yimg.com/cosmos.bcst.yahoo.com/up/fop/embedflv/swf/fop.swf';
			vars.eID = '1301797';
			vars.ympsc = '559940629';
			vars.autoStart = '1';
			vars.eh = 'flashCallBacks';
			vars.bw = '10000';
			vars.id = o.media.id;
			vars.enableFullScreen = 1;
		break;
		case 2:
			url = 'http://www.youtube.com/v/'+o.media.id;
			vars.autoplay = 1;
			vars.enablejsapi = 1;
			vars.fs = 1;
			checkAvailable(o.media.id);
		break;
	}
	
	pageTracker._trackPageview('/view:'+o.media.id);
	
	
	
	var vote = $('<div>').attr('class', 'vote');
	//(o.score==null?0:o.score)+
	vote.html('Rate this video: ');
	$('<img />').attr('id', 'voteDown').attr('src', 'images/vote_down.png').click(doVote).appendTo(vote);
	$('<img />').attr('id', 'voteUp').attr('src', 'images/vote_up.png').click(doVote).appendTo(vote);
	$(row).append(vote);
	
	$(row).css('cursor', 'default');
	
	var params = new Object();
	params.allowScriptAccess = 'always';
	params.allowFullScreen = true;
	params.wmode = 'transparent';
	
	$('<div>').attr('id', 'player').appendTo($(row));
	
	swfobject.embedSWF(url, 'player', 920, 517, '9.0.0', '', vars, params);
	
	document.location = '#'+play;
	repos();
	$('#'+play).css('background-color', 'black');
	$(row).children('.title').prepend('<b>Playing now: </b> ');
	//o.media.id
	return true;
}

function flashCallBacks(pType, pItem){
	switch(pType){
		case 'init':
			playerReady();
		break;
		case 'itemEnd':
			videoStopped();
		break;
	}
}

function videoStopped(){
	if(autoplay){
		var nxt = $('#'+play).next()
		if(nxt.length) playRow(nxt);
	}
}

function onYouTubePlayerReady(playerId){
	setTimeout(function(){
						//alert(document.getElementById('player').getPlayerState());
						}, 2000);
	playerReady();
	$('#player')[0].addEventListener("onStateChange", "onytplayerStateChange")
}

function onytplayerStateChange(newState)
{
	if(newState=='0')
		videoStopped();
}


function playerReady(){
	document.location = '#'+play;	
	repos();
}

function rowOver()
{
	$(this).children('.addToPlaylist').css('visibility', 'visible');
}

function rowOut()
{
	//var id = parseInt($(this).attr('id'));
	
	//if(id!=play)
	//	$(this).css('background-color', Math.round(id/2)==id/2?'transparent':'#404040');
	$(this).children('.addToPlaylist').css('visibility', 'hidden');
}

function feedback(){
	var form = $('<div>').attr('class', 'form');
	form.html("Email:");
	$('<input type="text" name="email"/>').appendTo(form);
	form.append("Your valued feedback:");
	$('<textarea name="message"/>').appendTo(form);
	$('<button>').attr('class', 'feedbackButton').html('Send').appendTo(form).click(sendFeedback);
	$('#res').html(form);
}

function sendFeedback(){
	$(this).attr('disabled', 'disabled');
	$.post('feedback.php', {email:$('input[name=email]').val(), message:$('textarea[name="message"]').val()}, function(res){
		switch(parseInt(res)){
			case 5:
			case 3:
				alert('please complete both fields');
			break;
			case 2:
				alert('invallid emailadres');
			break;
			case 1:
				$('.form').html('Your feedback has been send.<br/>Thank you very much!');
			break;
		}
		$('.feedbackButton').removeAttr('disabled');
	});	
}

function doVote(){
	var direct = $(this).attr('id')=='voteUp'?'up':'down';
	$.get('thumb.php', {dir:direct, id:srchO.items[play].media.id});
	srchO.items[play].score = parseInt(srchO.items[play].score)+(direct=='up'?+1:-1);
	$(this).parent().children('span').html(srchO.items[play].score);
	$('#'+(direct=='up'?'voteDown':'voteUp')).css('visibility', 'hidden');
	
	$('#voteUp').unbind('click');
	$('#voteDown').unbind('click');
}

function checkAvailable(id){
	$.getScript('http://gdata.youtube.com/feeds/api/videos/'+id+'?alt=json-in-script&callback=infoCallback');
}

function infoCallback(obj){
	if(obj.entry.yt$noembed){
		if(confirm("media is not embeddable\nGo to original page?")){
			window.open("http://www.youtube.com/watch?v="+srchO.items[play].media.id);
		}
	}
}

function loadPlaylist()
{
	$.getJSON('playlist.php', playlistLoaded);
}

var tmp;
function playlistLoaded(o){
	tmp = o;
	if(o.length&&!$('#playlist').length){
		$('<div>').attr('id', 'playlist').appendTo('body').html('<h1>Playlist</h1> <a id="hide">Hide</a><img src="img/play.png"/>');
		$('#hide').click(toggleHide);
	}else if(!o.length)
		$('#playlist').remove();
	
	$('#playlist').children('div').remove();
	$('img[src="img/play.png"]').click(playPlaylist);
	//alert($('#playlist').scrollTop());
	
	for(var key in o) $('<div>').html(o[key].title).appendTo('#playlist').attr('id', key);
	$('<img />').attr('src', 'img/cross.png').click(deletePlaylistItem).load(repos).appendTo($('#playlist').children('div'));
	
	repos();
}

var hidden = false;
function repos(){
	$('#playlist').css('top', $(window).scrollTop()+$(window).height()-$('#playlist').height()-40);
}

function toggleHide(){
	hidden = hidden?false:true;
	$('#playlist').css('height', hidden?'25px':'auto').children('a').html(hidden?'Show':'Hide');
	repos();
}


function deletePlaylistItem(){
	$.getJSON('playlist.php?delete='+$(this).parent().attr('id'), playlistLoaded);
}

function addToPlaylist(event)
{event.stopImmediatePropagation()
	var o = srchO.items[$(this).parent().attr('id')];
	$.getJSON('playlist.php?add='+o.media.id+'&title='+o.title, playlistLoaded);
}

function playPlaylist(){
	autoplay = true;
	$.getJSON('search.php?playlist=true', searchCallBack);	
}
