if(!jsFrontend) { var jsFrontend = new Object(); }

jsFrontend = {
	// datamembers
	debug: false,
	// init, something like a constructor
	init: function() {
		jsFrontend.layout.init();
		jsFrontend.player.init();
		jsFrontend.artist.init();
		jsFrontend.modal.init();
		jsFrontend.search.init();
	},
	// end
	eof: true
}

/**
 * All code related to artists
 */
jsFrontend.artist = {
	// init, something like a constructor
	init: function() {
		// bind
		$('#artistName, #artistInfo, #artistNameButton').click(function(evt) { evt.preventDefault(); jsFrontend.artist.showInfo() });
	},
	// toggle the artist info 
	showInfo: function() {
		// if visible we should hide it
		if($('#artistInfoTooltip').is(':visible')) $('#artistInfoTooltip').fadeOut(500);
		// show the info
		else $('#artistInfoTooltip').css('top', '-' + parseInt($('#artistInfoTooltip').height() - 35) +'px')
									.css('z-index', 500)
									.fadeIn(500);
	},
	// end
	eof: true
}

/**
 * Some general methods
 */
jsFrontend.general = {
	formatTime: function(seconds) {
		// init vars
		var minutes = parseInt(seconds/60);
		var realSeconds = seconds - (minutes * 60);
		// less then 10 seconds
		if(realSeconds < 10) return minutes.toString() + ':0' + realSeconds.toString();
		// fallback
		return minutes.toString() + ':' + realSeconds.toString();
	},
	// end
	eof: true
}

/**
 * All code related to Last.fm
 */
jsFrontend.lastfm = {
	// import data from Last.fm
	load: function(username) {
		$.ajax({ type: 'POST', 'cache': false, dataType: 'json', url: '/ajax.php?module=lastfm&action=load',
			data: 'username=' + username,
			success: function (data, textStatus) {
				// redirect to the users playlist
				if(data.code == 200) document.location = '/playlists/lastfm/'+ username;
				else alert('Foutje');
			}
		});
	},
	// end
	eof: true
}

/**
 * All code related to the layout
 */
jsFrontend.layout = {
	// init, something like a constructor
	init: function() {
		// set width
		$('#leftColumn').width(parseInt($(window).width()) - parseInt($('#rightColumn').width()) - 100);
		
		if($('#songList').length > 0) {
			$('#songList').height(parseInt($(window).height() * 0.45));
		}
		
		
		// hook resize-event
		$(window).resize(jsFrontend.layout.init);

		// hovers
		$('li.clip').hover(function() { $('#'+ $(this).attr('id').replace('movie', 'tooltip')).show(); }, function() { $('#'+ $(this).attr('id').replace('movie', 'tooltip')).hide(); });
		$('#channels li').hover(function() { $(this).addClass('hover'); }, function() { $(this).removeClass('hover'); });
	},
	// end
	eof: true
}

/**
 * All code related to the modal-player
 */
jsFrontend.modal = {
	// init, something like a constructor
	init: function() {
		// bind
		jsFrontend.modal.bind();
	},
	// bind the links
	bind: function() {
		$(window).resize(jsFrontend.modal.reposition);
		
		// bind clips
		$('#playlist li a').bind('click', function(evt) {
			// prevent defaults
			evt.preventDefault();
			// show the player
			jsFrontend.modal.toggle($(this));
		});
		// bind clips
		$('#playlist li .tooltip').bind('click', function(evt) {
			// prevent defaults
			evt.preventDefault();
			// show the player
			jsFrontend.modal.toggle($($(this).parent()[0]).find('a'));
		});
		
		// bind click on overlay
		$('#overlay').live('click', function() { jsFrontend.modal.toggle(); });
	},
	// position the player
	reposition: function() {
		// get data
		var viewportHeight = $(window).height();
		var viewportWidth = $(window).width();
		// calculate the height
		var height = parseInt(viewportHeight - 110); 
		var width = parseInt(height * (16/9));
		// fit in window?
		if(width > viewportWidth) {
			// recalculate
			width = parseInt(viewportWidth - 50);
			height = parseInt(width * (9/16));
		}
		// calculate offset
		var offsetTop = 20;
		var offsetLeft = parseInt((viewportWidth - width) / 2)
		// position
		$('#playerModal').css('width', width)
						 .css('height', height)
						 .css('top', offsetTop)
						 .css('left', offsetLeft);
		$('#player').css('width', width)
					.css('height', height);
	},
	// show or hide the player
	toggle: function(el) {
		// if the player is visible we should hide it
		if($('#playerModal').is(':visible')) {
			// remove overlay
			$('#overlay').remove();
			// set new state for player
			jsFrontend.player.unload();
			// remove player modal
			$('#playerModal').fadeOut(500);
		}
		
		// show the player
		else {
			jsFrontend.modal.reposition();
			// add overlay
			$('body').prepend('<div id="overlay">&nbsp;</div>');
			// load video
			var id = $(el).attr('href').replace('#','');
			jsFrontend.player.playVideo(id);
			// show player modal
			$('#playerModal').fadeIn(500);
			// go to player
			$.scrollTo($('playerModal'));
		}
	},
	// end
	eof: true	
}

/**
 * All code related to the player
 */
jsFrontend.player = {
	// datamembers
	current: null,
	currentState: -1,
	isReady: false,
	instance: null,
	interval: null,
	itemQueued: null,
	playlist: new Array(),
	// init, something like a constructor
	init: function() {
		// load the player
		jsFrontend.player.load();
		// bind
		jsFrontend.player.bind();
	},
	// bind events
	bind: function() {
		// bind buttons
		$('#togglePlay').bind('click', jsFrontend.player.togglePlayPause);
		$('#nextSong').bind('click', jsFrontend.player.playNext);
		// bind sliders
		$('#volumeSlider').slider({ min: 0, max: 100, stop: function(event, ui) { jsFrontend.player.setVolume(parseInt(ui.value)); } });
		$('#timeSlider').slider({ min: 0, start: function(event, ui) { clearInterval(jsFrontend.player.interval); }, stop: function(event, ui) { jsFrontend.player.seekTo(parseInt(ui.value)); } });
		// bind links
		$('#wrongClip').bind('click', jsFrontend.player.wrongMovie);
		// init dialogs
		$('#wrongClipConfirm').dialog({ autoOpen: false, resizable: false, modal: true, draggable: false, zIndex: 3000,
										open: function() {
											$('#myytplayer').height('1%')
															.width('1%');
										},
										close: function() {
											$('#myytplayer').height('100%')
															.width('100%');
										},
										buttons: {	'OK': function() {
														var modal = $(this);
														$.ajax({ type: 'POST', 'cache': false, dataType: 'json', url: '/ajax.php?module=playlists&action=wrong_clip',
															data: 'id=' + modal.attr('rel'),
															error: function (XMLHttpRequest, textStatus, errorThrown) {
																modal.dialog('close');
															},
															success: function (data, textStatus) {
																$('#movie-'+ modal.attr('rel')).remove();
																modal.dialog('close');
																jsFrontend.player.playNext();
															}
														});														
													},
													'Cancel': function() { $(this).dialog('close'); }
												 }
									  });
		
		$('#share').bind('click', function(evt) {
			// prevent default
			evt.preventDefault();
			// if visible we should hide it
			if($('#tooltipShare').is(':visible')) $('#tooltipShare').fadeOut(500);
			// show the info
			else $('#tooltipShare').css('top', '-20px')
								   .css('left', '-210px')
								   .css('z-index', 500)
								   .css('position', 'absolute')
								   .width(200)
								   .fadeIn(500);
		});
	},
	// load the player
	load: function() {
		// embed the flash
		swfobject.embedSWF('http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=ytplayer', 'player', '100%', '100%', '8', null, null, 
							{ allowScriptAccess: 'always', allowFullScreen: 'true', bgcolor: '#000000' }, 
							{ id: 'myytplayer' }
						);
		// populate playlist
		$('#playlist li.clip a').each(function() { jsFrontend.player.playlist.push($(this).attr('href').replace('#', '')); });
	},
	// unload the player
	unload: function() {
		// clear the interval
		clearInterval(jsFrontend.player.interval);

		// reset members
		jsFrontend.player.current = null;
		jsFrontend.player.currentState = -1;
		jsFrontend.player.isReady = false;
		jsFrontend.player.instance = null;
		jsFrontend.player.interval = null;
		jsFrontend.player.itemQueued = null;
		jsFrontend.player.playlist = new Array();
	},
	// play a video
	playVideo: function(id) {
		if(jsFrontend.player.playlist) {
			// populate playlist
			$('#playlist li.clip a').each(function() { jsFrontend.player.playlist.push($(this).attr('href').replace('#', '')); });
		}
		
		if(!jsFrontend.player.isReady) {
			jsFrontend.player.itemQueued = id;
		}
		else {
			// clear queue
			jsFrontend.player.itemQueued = null;

			if(id == null) {
				alert('No ID specified');
				window.location.reload();
			}
			else
			{
				// get info
				$.ajax({ type: 'POST', 'cache': false, dataType: 'json', url: '/ajax.php?module=playlists&action=get_info',
					data: 'id=' + id,
					error: function (XMLHttpRequest, textStatus, errorThrown) {
						alert('could not retrieve artist info');
						window.loaction.reload();
					},
					success: function (data, textStatus) {
						// ok?
						if(data.code == 200) {
							// build html
							var html = '';
							// add image if it is present
							if(data.data.image != '' && data.data.image != undefined) html += '<img src="/cache/images/artists/80x60/'+ data.data.artistImage +'" width="80" height="60" alt="'+ data.data.name +'" />';
							// add summary
							html += data.data.artistSummary;
							// set stuff
							$('#iTunesLink').attr('href', data.data.iTunesLink);
							$('#wrongClip').attr('href', '#'+ id);
							$('#artistInfo').html(html);
							$('#songTitle').html(data.data.title);
							$('#artistName').html(data.data.artistName);
							$('title').html(data.data.title +' by '+ data.data.artistName + ' - Listenr.TV');
							if($('#videoTitle').length > 0) $('#videoTitle').html(data.data.videoTitle);
							$('#playerShareTwitter').attr('href', data.data.shareTwitterLink);
							$('#playerShareFacebook').attr('href', data.data.shareFacebookLink);
						}
						else
						{
							alert('could not retrieve artist info');
							window.location.reload();
						}
					}
				});
				
				// init var
				var width = $('#myytplayer').width();
				var height = $('#myytplayer').height();
				var quality = 'default';
				// calculate quality
				if(width >= 640 && height >= 360) quality = 'medium';
				if(width >= 854 && height >= 480) quality = 'large';
				if(width >= 1280 && height >= 720) quality = 'hd720';
				// load the video
				jsFrontend.player.instance.loadVideoById(id, 0, quality);
				// start interval
				jsFrontend.player.interval = setInterval('jsFrontend.player.update()', 1000);
				// set current
				jsFrontend.player.current = id;
				// set class
				$('#togglePlay').removeClass('pause')
								.addClass('play');
			}
		}
	},
	// player state is changed
	onStateChange: function(newState) {
		// possible states: -1: unstarted, 0: ended, 1: playing, 2: paused, 3: buffering, 5: video cued
		jsFrontend.player.currentState = newState;
		// movie has ended?
		if(jsFrontend.player.currentState == 0) {
			// get next video in line
			var nextID = jsFrontend.player.getNextID();
			// validate video and play if ok 
			if(nextID != false) jsFrontend.player.playVideo(nextID);
			// no video
			else jsFrontend.modal.toggle();
		} 
	},
	// an error occured
	onError: function(errorCode) {
		// possible errors: 100: video not found, 101: not embeddable, 150: same as 101
		$.ajax({ type: 'POST', 'cache': false, dataType: 'json', url: '/ajax.php?module=playlists&action=wrong_clip',
			data: 'id=' + jsFrontend.player.current,
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				jsFrontend.player.playNext();
			},
			success: function (data, textStatus) {
				$('#movie-'+ jsFrontend.player.current).remove();
				jsFrontend.player.playNext();
			}
		});														
	},
	// seek
	seekTo: function(seconds) {
		// seek to
		jsFrontend.player.instance.seekTo(parseInt(seconds), true);
		
		// restart the interval
		jsFrontend.player.interval = setInterval('jsFrontend.player.update()', 1000);
	},
	// set volume
	setVolume: function(newVolume) {
		jsFrontend.player.instance.setVolume(newVolume);
	},
	// toggle play/pause
	togglePlayPause: function(evt) {
		// prevent default
		evt.preventDefault();
		// paused?
		if(jsFrontend.player.currentState == 2) {
			// play video
			jsFrontend.player.instance.playVideo();
			// set classes
			$(this).removeClass('pause')
				   .addClass('play');
		}
		else {
			// pause video
			jsFrontend.player.instance.pauseVideo();
			
			// set classes
			$(this).removeClass('play')
				   .addClass('pause');
		}
	},
	// play next song
	playNext: function(evt) {
		// prevent default
		if(evt != undefined) evt.preventDefault();
		// get next video in line
		var nextID = jsFrontend.player.getNextID();
		// validate video and play if ok 
		if(nextID != false) jsFrontend.player.playVideo(nextID);
		// no video
		else jsFrontend.modal.toggle();
	},
	// update player info
	update: function() {
		try {
			// get and calculate vars
			var totalTime = parseInt(jsFrontend.player.instance.getDuration());
			var currentTime = parseInt(jsFrontend.player.instance.getCurrentTime());
			var volume = parseInt(jsFrontend.player.instance.getVolume());
			// parse into the DOM
			$('#totalTime').html(jsFrontend.general.formatTime(totalTime));
			$('#currentTime').html(jsFrontend.general.formatTime(currentTime));
			$('#volumeSlider').slider('value', volume);
			$('#timeSlider').slider('option', 'max', totalTime);
			$('#timeSlider').slider('value', currentTime);
		} catch(err) {
			jsFrontend.player.unload();
		}
	},
	// get next id in line
	getNextID: function() {
		// loop playlist
		for(var i in jsFrontend.player.playlist) {
			// is this the current item?
			if(jsFrontend.player.playlist[i] == jsFrontend.player.current) {
				// calculate new index
				var newIndex = parseInt(i) + 1;
				// is the new index available 
				if(jsFrontend.player.playlist[newIndex] != undefined) return jsFrontend.player.playlist[newIndex];
				// no song next
				else return false;
			}
		}
		// fallback
		return false;
	},
	wrongMovie: function() {
		$('#wrongClipConfirm').attr('rel', $(this).attr('href').replace('#', ''));
		$('#wrongClipConfirm').dialog('open');
	},
	// end
	eof: true
}

/**
 * This method will be called when the player is ready
 */
function onYouTubePlayerReady(playerId) {
	// get player
	jsFrontend.player.instance = document.getElementById('myytplayer');
	jsFrontend.player.isReady = true;

	// should we play an item?
	if(jsFrontend.player.itemQueued != null) {
		jsFrontend.player.playVideo(jsFrontend.player.itemQueued);
	}
	else {
		window.location.reload();
	}
	
	// bind events
	jsFrontend.player.instance.addEventListener('onStateChange', 'jsFrontend.player.onStateChange');
	jsFrontend.player.instance.addEventListener('onError', 'jsFrontend.player.onError');
}

/**
 * Search
 */
jsFrontend.search = {
	// init, something like a constructor
	init: function() {
		if($('#search').length > 0) {
			$('#search').autocomplete({ ajax_get: jsFrontend.search.get, noresults: 'no results', cache: false, callback: jsFrontend.search.goTo });
			$('#search').focus(function() { $(this).select() });
		}
	},
	// get
	get: function(input, cont) {
		$('#search').addClass('loading');
		$.ajax({ type: 'POST', 'cache': false, dataType: 'json', url: '/ajax.php?module=playlists&action=search',
			data: 'q=' + input,
			success: function (data, textStatus) {
				if(data.code == 200) {
					var results = [];
					for(var i in data.data) results.push({ id: data.data[i].url, value: data.data[i].name });
				}
				// build suggestion list
				cont(results);
			}
		});
		$('#search').removeClass('loading');
	},
	goTo: function(selected) { window.location = selected.id; },
	// end
	eof: true
}

/**
 * Initialize
 */
$(document).ready(function() { jsFrontend.init(); });