var _player;
var _playlist0; // playlist array for search results
var _videodata0; // videodata array for search results
var _currentPlaylist;
var _playlistSize = 3;
var _stopped = false;
var soundEmbed = null;

$(function() {
	init();	
});

function init() {
	$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8" });
	setScrollableElements("div.playlist");
	refreshScrollableControls();

	$('#search_list').hide();
	$('#clip_base').hide();
	
	if (typeof(_first_video) !== 'undefined')
		play(_first_playlist, _first_video);
	else if (typeof(_first_playlist) !== 'undefined')
		play(_first_playlist, 0);
	else
		play(1, 0);

	// setup sound for all buttons
	/*$("div.clip, div.channels_list_row_icon, #player_btn_left, #player_btn_right, #channels_search_btn, div.channels_list_row_btn_left, div.channels_list_row_btn_right").live("mousedown", function () {
		playSound();
	});*/
	
	/*$("div.channels_list_row_btn_left, div.channels_list_row_btn_right").live("click", function () {
		playSound();
	});*/
	
	// setup delegates for click events from clips 
	$("div.clip").live("click", function () {
		var a = $(this).attr("id").split("_");
		var playlist_id = a[1];
		var clip_id = a[2];
		//if (playlist_id != _currentPlaylist) {
			play(playlist_id, parseInt(clip_id));
		//}
		//_player.play(parseInt(clip_id));
		$('html, body').animate({scrollTop:0}, 'fast');
		playSound();
		return false;
	});
	
	// setup delegate for click events from channel icons 
	$("div.channels_list_row_icon").delegate("", "click", function () {
		var a = $(this).attr("id").split("_");
		var playlist_id = a[1];
		//if (playlist_id != _currentPlaylist)
			play(playlist_id, 0);
		//_player.play(0);
		playSound();
		return false;
	});
	
	$("#player_btn_left").click(function (e) {
		e.preventDefault();
		var clipIndex = $f().getClip().index;
		if (clipIndex > 0) {
			--clipIndex;
			$f().play(clipIndex);
			/*if (clipIndex == 0)
				$(this).css("visibility", "hidden");*/
		}
		playSound();
	});

	$("#player_btn_right").click(function (e) {
		e.preventDefault();
		var clipIndex = $f().getClip().index; 
		++clipIndex; 
		$f().play(clipIndex);
		playSound();
	});

	$("#channels_search_btn").click(function (e) {
		e.preventDefault();
		doSearch();
		playSound();
	});
	
	$('#search_input').keypress(function(event) {
		if (event.keyCode == 13) {
			doSearch();
			playSound();
		}
	});
}

function setScrollableElements(selector) {
	$(selector).scrollable({
		circular: false,
		items:'div.clips',
		prev:'div.channels_list_row_btn_left',
		next:'div.channels_list_row_btn_right',
		onBeforeSeek: function(event, newIndex) {
			if (newIndex + _playlistSize - 1 == this.getSize()) 
				event.preventDefault();
		},
		onSeek: function(event, newIndex) {
			refreshScrollableControls();
		}
	});
}

function refreshScrollableControls() {
	$('div.playlist').each(function () {
		var scrollable = $(this).data("scrollable");
		if (scrollable.getIndex() > 0)
			scrollable.getRoot().parent().find('.channels_list_row_btn_left').css("visibility", "visible");
		else
			scrollable.getRoot().parent().find('.channels_list_row_btn_left').css("visibility", "hidden");
		if (scrollable.getSize() <= _playlistSize || scrollable.getIndex() + _playlistSize == scrollable.getSize())
				scrollable.getRoot().parent().find('.channels_list_row_btn_right').css("visibility", "hidden");
			else
				scrollable.getRoot().parent().find('.channels_list_row_btn_right').css("visibility", "visible")
	});
}

function play(playlist_index, clip_index) {
	//alert(playlist_index+", "+clip_index+", _currentPlaylist: "+_currentPlaylist);
	_stopped = false;
	_currentPlaylist = playlist_index;
	_player = $f("player", "flowplayer/flowplayer.commercial-3.2.5.swf", {
		key: '#$f7da1bc2e4dda1813e6',
		logo: {
			url: '',
			fullscreenOnly: false,
			displayTime: 2000
		},
		canvas:  {
			background: '#000000',
			backgroundGradient: 'none',
			border:'none'
		},
		screen: {
				height: 484,
				top: 0
		},
		clip: { 
				timeColor: '#000000',
				sliderColor: '#ff6b00',
				scaling: 'fit',
				accelerated: true,
				autoPlay: true,
				autoBuffering: true,
				fadeInSpeed: 3000,
				fadeOutSpeed: 3000,
				bufferLength: 2,
				onBegin: function() {
					refreshDetails();

					// this is only executed once, when the instream 'preroll' is playing
					if ($f().getClip().isInStream)
						checkQueue();
    		},
				onStart: function () {
					var clip = $f().getClip();
					if (!clip.isInStream)
						logEvent('Play');
				},
				onPause: function () {
					var clip = $f().getClip();
					if (!clip.isInStream)
						logEvent('Pause');
				},
				onStop: function () {
					var clip = $f().getClip();
					if (!clip.isInStream)
						logEvent('Stop');
				},
				onFinish: function () {
					var clip = $f().getClip();
					if (!clip.isInStream)
						logEvent('Finish');
				},
				coverImage: { url: 'http://www.radiovalo.fi/images/audioonly.jpg', scaling: 'orig' }
			},
			plugins: {
				controls: {	
								height: 40,
								backgroundGradient: [0.1, 0.1, 0.1],
								autoHide: 'never',
								time: false,
								scrubberHeightRatio: 0.7,
								scrubberBarHeightRatio: 0.1,
								volumeBarHeightRatio: 0.1,
								volumeSliderHeightRatio: 0.7	},
				audio: {
					url: 'flowplayer/flowplayer.audio-3.2.2.swf'
				}
			},
		play: { opacity: 100 },
		autoPlay: true,
		autoBuffering: true,
		bufferLength: 2,
		playlist: eval("_playlist"+playlist_index),
		onError: function (error, message) {
				if (error == 200 || error == 201) {
					var clipIndex = $f().getClip().index; 
					++clipIndex; 
					play(_currentPlaylist, clipIndex);
				}
			}
	}).ipad();
	//}).ipad().playlist("#clips"+i, {loop: true});
	refreshScrollableControls();
	_player.play(clip_index);
	refreshDetails();
}

function refreshDetails() {
	if (!$f())
		return;
	if (!$f().getClip())
		return;
	var index = $f().getClip().index;
	var page = Math.floor(index/_playlistSize) * _playlistSize;
	var scrollable = $("#playlist"+_currentPlaylist).data("scrollable");
	scrollable.seekTo(page);

	$("div.clip_active").removeClass("clip_active").addClass("clip");
	$("#clip_"+_currentPlaylist+"_"+index).removeClass("clip").addClass("clip_active");

	var vda = eval("_videodata"+_currentPlaylist)[index];
	$("#videotitle").text(vda.title);
	$("#videodescription").text(vda.description);
	$("#link").text("http://www.radiovalo.fi/"+vda.id);
	if (vda.download) {
		$("#download").attr("href", vda.download);
		$("#download").css("visibility", "visible");
	} else 
		$("#download").css("visibility", "hidden");
	
	/* skip this when using iPad or iPhone (causes problems with UI) */
	if (navigator.userAgent.match(/iPad/i) == null && navigator.userAgent.match(/iPhone/i) == null) {
		if (vda.showcontrols == '1')
			$f().getPlugin("controls").show();
		else
			$f().getPlugin("controls").hide();
	}
	
	if (index == 0)
		$("#player_btn_left").css("visibility", "hidden");
	else
		$("#player_btn_left").css("visibility", "visible");
	if (index == scrollable.getSize()-1)
		$("#player_btn_right").css("visibility", "hidden");
	else
		$("#player_btn_right").css("visibility", "visible");
}

function checkQueue() {
	var index = $f().getClip().index;
	var vda = eval("_videodata"+_currentPlaylist)[index];
	$.ajax({
		type: "POST",
		url: "services/getcount.php",
		dataType: "text",
		contentType: "application/x-www-form-urlencoded;charset=UTF-8",
		data: "video="+vda.id,
		success: function(result){
			//$("#output").text('result: '+result+', '+(result == 0));
			if (result == 0) {
				$("#player_maxuserslimit").css("visibility", "visible");
				$f().stop();
				_stopped = true;
				// start automatic queue timer
				setTimeout('checkQueue()', 4000);
			} else {
				if (_stopped) {
					_stopped = false;
					$("#player_maxuserslimit").css("visibility", "hidden");
					$f().play();
				}
				logEvent('begin');
				//_tracker._trackEvent("Videos", "Play", clip.url);
			}
		}
	});
}

function logEvent(type) {
	var videodata = eval("_videodata"+_currentPlaylist)[$f().getClip().index];
	$.ajax({
		type: "POST",
		url: "services/videoevent.php",
		dataType: "xml",
		contentType: "application/x-www-form-urlencoded;charset=UTF-8",
		data: "video="+videodata.id+"&type="+type,
		success: function() {}
	});
	_tracker._trackEvent("Videos", type, $f().getClip().url);
}

function doSearch() {
	$('#clips0').empty();
	var keyword = $("#search_input").val();
	if (keyword == null || keyword == "") {
		$('#search_list').slideUp();
		return;
	}
	$('#search_list').slideDown();
	$.ajax({
		type: "POST",
		url: "services/search.php",
		dataType: "xml",
		contentType: "application/x-www-form-urlencoded;charset=UTF-8",
		data: "keywords="+keyword,
		success: function(xml) {
			_playlist0 = [];
			_videodata0 = [];
			var cnt = 0;
			$(xml).find("video").each(function () {
				var hashkey = $(this).find("hashkey").text();
				var url = $(this).find("url").text();
				var title = $(this).find("title").text();
				var description = $(this).find("description").text();
				var download = $(this).find("download").text();
				var thumbnail = $(this).find("thumbnail_url").text();
				var clip_id = 'clip_0_'+cnt;
				$('#clip_base').clone().show().appendTo('#clips0').find('.clip').attr('id', clip_id);
				$('#'+clip_id).find('#thumbnail').attr('src', thumbnail);
				$('#'+clip_id).find('#title').text(title);
				_playlist0.push({url: url});
				_videodata0.push({id: hashkey, title: title, description: description, url: url, download: download});
				++cnt;
			});
			refreshScrollableControls();
		}
	});
}

function playSound() {
	var url = 'sounds/buttonsound.wav';
	if (!soundEmbed) {
	  soundEmbed = document.createElement("embed");
	  soundEmbed.setAttribute("src", url);
	  soundEmbed.setAttribute("hidden", true);
	  soundEmbed.setAttribute("autostart", true);
	} else {
	  document.body.removeChild(soundEmbed);
	  soundEmbed.removed = true;
	  soundEmbed = null;
	  soundEmbed = document.createElement("embed");
	  soundEmbed.setAttribute("src", url);
	  soundEmbed.setAttribute("hidden", true);
	  soundEmbed.setAttribute("autostart", true);
	}
	soundEmbed.removed = false;
	document.body.appendChild(soundEmbed);
}

