jQuery(document).ready(function(){
	var videos;
	var played;
	var active = -1;
	var counter = 0;
	var playlistLoaded = 0;
	
	loadAllVideos();
	setupFlowPlayer();
	
	function createPlaylist() {
		playlistLoaded++;
		shuffle = function(o){ 
			for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
			return o;
		};
		
		var pole = shuffle(videos);
		var out = [];
		
		for( var i = 0; i < pole.length; i++ ) {
			var filename = "/video/" + pole[i].id;
			filename += pole[i].ext;
			
			out.push(filename);
		}
		$f().setPlaylist(out).play();
	}
	
	function videoStart(url) {
		var name = getFileName(url);
		for( var v = 0; v < videos.length; v++ ) {
			if(videos[v].id == name) {
				$('.desc').html(
					"<strong>" + videos[v].title + "</strong>" + "<br />" +
					videos[v].description
				);
				$('#video_logo').html('<img src="/video/logo/'+ videos[v].id + videos[v].logo +'" />');
				break;
			}
		}
		saveStatistic();
	}
	
	//load all videos on startup
	function loadAllVideos() {
		$.get("videoHandler.php",{action: "getAll"},function( data ){ 
			data = eval(data);
			videos = data; 
			if( playlistLoaded > 0 ) {
				createPlaylist();
			}
		});
	}
	
	function saveStatistic() {
		var file = $f().getClip().completeUrl;
		var id = getFileName(file);
		$.get('videoHandler.php',{action:"stat", id: id});
	}
	
	//seting up flowplayer and playing first video
	function setupFlowPlayer() {

		$f("player", "flowplayer-3.2.5.swf", {
			clip: {
				onStart: function(clip) {
						videoStart(clip.completeUrl);
					}
			},
			onFinish: function() {
				counter++;
				if( counter >= videos.length ) {
					counter = 0;
					if( playlistLoaded < 2 ) {
						loadAllVideos();
					} else { //when played for second time, playlist have to have all videos, do not have to load it again
						createPlaylist();
					}
				}
			},
			onLoad: function() {
				createPlaylist();
			},
			onPlaylistReplace: function() {
			},
			plugins: {
				controls: {
					playlist: true
				}
			}
		});
	}
	
	function getFileName(file) {
		file = file.match(/.*\/(.+)\..+/);
		return file[1];
	}
});
