var current = '';
var current_playlist = 'new';
var playing_playlist = '';
var playing = false;
var shuffle = false;
var repeat = false;
var nw_playlist = true;

var yt_start = 1;
var yt_number = 5;
var from_search_results = '';
var from_related_results = '';

var playlist = new Array();

var search;
var show_hide_results;
var warning;
var related;
var playlists;

var scroll;

var pl_start = 0;
var pl_number = 5;

function sendEvent(swf,typ,prm) { 
	thisMovie(swf).sendEvent(typ,prm); 
};

function getUpdate(typ,pr1,pr2,swf) {
	var button_play = $('button_play');
	if(typ == 'state') {
		if(pr1 == 0) {
			playing = false;
			button_play.src = base_url+'graphics/play.gif';
   		button_play.addEvent('mouseover', function() {button_play.src = base_url+'graphics/play_over.gif';});
   		button_play.addEvent('mouseout', function() {button_play.src = base_url+'graphics/play.gif';});
   		button_play.addEvent('click', function() {button_play.src = base_url+'graphics/pause.gif';});			
		}
		if(pr1 == 1) {
			playing = true;
			button_play.src = base_url+'graphics/pause.gif';
   		button_play.addEvent('mouseover', function() {button_play.src = base_url+'graphics/pause_over.gif';});
   		button_play.addEvent('mouseout', function() {button_play.src = base_url+'graphics/pause.gif';});
   		button_play.addEvent('click', function() {button_play.src = base_url+'graphics/play.gif';});		
		}
		if(pr1 == 2) {
			if(!playing) {
				playing = true;
				button_play.src = base_url+'graphics/pause.gif';
   			button_play.addEvent('mouseover', function() {button_play.src = base_url+'graphics/pause_over.gif';});
   			button_play.addEvent('mouseout', function() {button_play.src = base_url+'graphics/pause.gif';});
   			button_play.addEvent('click', function() {button_play.src = base_url+'graphics/play.gif';});
   		}		
		}		
		if(pr1 == 3) {
			if(repeat) 	do_play();
			else do_next();
		}            
	}	 
}


function do_next() {
	if(!shuffle) {
		var curEl = $(current);
		if(curEl && playing_playlist == current_playlist) {			
			if(curEl.getParent().id == 'playlist') {
				var next = curEl.getNext();
			}
		}
		if(next) {
			current = next; 
		}
		else {			
			playing_playlist = current_playlist;
			var songs = $('playlist').getChildren();				
			current = songs[0];
		}
	}
	else {
		var songs = $('playlist').getChildren();				
		current = songs[$random(0, songs.length - 1)];		
	}
	if(current.id != 'empty') do_play();
}

function do_prev() {
	var curEl = $(current);
	if(curEl && playing_playlist == current_playlist) {
		if(curEl.getParent().id == 'playlist') {
			var prev = curEl.getPrevious();
		}
		if(prev) {
			current = prev; 
		}
	}
	else {
		playing_playlist = current_playlist;				
		var songs = $('playlist').getChildren();				
		current = songs[songs.length - 1];
	}
	do_play();
}

function do_play(song) {
	if(nw_playlist) {
		nw_playlist = false;
		var jsonRequest = new Request.JSON({url: site_url+'?c=player&m=playlist_view'}).post({'playlist_id':current_playlist});
	}
	if(song) current = song;
	if(current) {

		
		window.setTimeout("start_play(current.id)", 500);

		$('playing_now_title').set('text', current.retrieve('song'));
		
		scroll.toElement(current.id);	

		$('playlist').getChildren().each(function(child) {
			child.set('class', '');
		});
		$(current).set('class', 'now_playing');
		
		window.setTimeout("show_related(current.id)", 5000);		 		
	}
}

function start_play(id) {
	var load = 'http://www.youtube.com/watch?v='+id;
	loadFile('mediaplayer', {file:load})
}


function show_related(video_id) {
	$('related').set('html', '<img src="'+base_url+'graphics/loading.gif" style="margin: 40px 0px 0px 140px;" />');
	var jsonRequest = new Request.JSON({url: site_url+'?c=player&m=related', onComplete: function(feed){

		$('related').set('text', '');
		var li = video_list(feed, 'related');
		$('related').set('text', '');
		var ul = new Element('ul', {
			'id': 'related_results'
		}).inject('related').adopt(li);
		
		make_sortable();
		related.slideIn();		
	}}).post({'video_id':video_id});
}

function toggle_shuffle() {
	if(shuffle) {
		shuffle = false;
		$('shuff').set('text', 'Shuffle off');
	}
	else {
		shuffle = true;
		$('shuff').set('text', 'Shuffle on');		
	}
}

function toggle_repeat() {
	if(repeat) {
		repeat = false;
		$('repeat').set('text', 'Repeat off');
	}
	else {
		repeat = true;
		$('repeat').set('text', 'Repeat on');		
	}
}

function loadFile(swf,obj) {
	thisMovie(swf).loadFile(obj); 
};
function thisMovie(movieName) {
	if(navigator.appName.indexOf("Microsoft") != -1) {
		return window[movieName];
	} else {
		return document[movieName];
	}
};

function play_pause(swf) {
	if(!current.id) do_next();
	else thisMovie(swf).sendEvent('playpause');
} 
  
function yt_search(new_search) {
	if(new_search) {
		yt_start = 1; 
		yt_number = 5; 
	}
	$('search_result').set('html', '<img src="'+base_url+'graphics/loading.gif" style="margin: 40px 0px 0px 140px;" />');
	var jsonRequest = new Request.JSON({url: site_url+'?c=player&m=search', onComplete: function(feed){

		$('search_result').set('text', '');
				
		show_hide_results.slideIn();
		if(feed.videos) {
			$('show_hide_results').setStyle('display', 'block');
			yt_start = feed.part;
			var li = video_list(feed, 'search');
			var ul = new Element('ul', {
				'id': 'search_results'
			}).inject('search_result').adopt(li);

			tmp_start = yt_start;

			var next_results = new Element('span', {
				text: 'Next results',
				id: 'next_results'
			});
			
			next_results.addEvent('click', function() {yt_number = 5; yt_start = parseFloat(yt_start) + 5; yt_search();});

			var prev_results = new Element('span', {
				text: 'Previous results',
				id: 'prev_results'
			});
			
			prev_results.addEvent('click', function() {yt_number = 5; yt_start = parseFloat(yt_start) - 5; yt_search();});
			
			var div = new Element('div', {id: 'more_results'});
			if(tmp_start > 1) div.adopt(prev_results);
			if(feed.videos.length > 4) div.adopt(next_results);
			$('search_result').adopt(div);		
			
			make_sortable();
		}
		else {
			var p = new Element('p', {
				'text': 'Sorry .. no results', 'id': 'no_results'
			}).inject('search_result');						
		}	
	
		search.slideIn();
		 
	}}).post({'q': $('query').value, 'start': yt_start, 'number':yt_number});

}

function load_playlists() {

	$('playlists_container').set('html', '<img src="'+base_url+'graphics/loading.gif" style="margin: 40px 0px 0px 140px;" />');
	var jsonRequest = new Request.JSON({url: site_url+'?c=player&m=load_playlists', onComplete: function(feed){
		if(feed.playlists) {	
			var li = [];

			var title = new Element('span', {'text': 'Create a new playlist!', 'class': 'new_playlist'});		
			var item = new Element('li', {'id': 'new'}).adopt(title);

		
			item.addEvent('click', function(e){														
				new_playlist();
			});
			item.addEvent('selectstart', function(e){
				return false;
			});
			item.unselectable = "on";
			item.style.MozUserSelect = "none";

			li.push(item);
			
			feed.playlists.each(function(playlist){
				var remove_item;
				if(playlist.owner) {
					var remove_item = new Element('span', {'text': 'x', 'class': 'remove_item'});
		
					remove_item.addEvent('click', function(e) {
						e.stop();
						if(confirm('Do you want to delete this playlist?')){
							item.dispose();
							var jsonRequest = new Request.JSON({url: site_url+'?c=player&m=delete_playlist', onComplete: function (reply) {
								load_playlists();
								if(playlist.id == current_playlist) new_playlist();
							}}).post({'playlist_id': playlist.id});
							if($('playlist').getChildren().length == 0) $('playlist').adopt(empty); 
						}
					});
				}
				var title = new Element('span', {'text': playlist.title, 'class': 'playlist_title'});		
				var by = new Element('span', {'text': '(by: '+playlist.by+', '+playlist.views+' views)', 'class': ''});
				var item = new Element('li', {'id': playlist.id}).adopt(remove_item, title, by);
		
				item.addEvent('click', function(e){														
					load_playlist(playlist.id);
					$('playlist_title').set('text', playlist.title);
					warning.slideOut();
				});
				item.addEvent('selectstart', function(e){
					return false;
				});
				item.unselectable = "on";
 				item.style.MozUserSelect = "none";

				li.push(item);
			});
			$('playlists_container').set('text', '');
			var ul = new Element('ul', {
				'id': 'playlists'
			}).inject('playlists_container').adopt(li);
		
			var next_results = new Element('span', {
				text: 'Next playlists',
				id: 'next_playlists'
			});
			
			next_results.addEvent('click', function() {
				pl_number = 10; 
				pl_start = parseFloat(pl_start) + 10; 
				load_playlists();
			});

			var prev_results = new Element('span', {
				text: 'Previous playlists',
				id: 'prev_playlists'
			});
			
			prev_results.addEvent('click', function() {
				pl_start = parseFloat(pl_start) - 10; 
				load_playlists();
			});
			
			var div = new Element('div', {id: 'more_results'});
			if(pl_start > 0) div.adopt(prev_results);
			if(feed.playlists.length > 9) div.adopt(next_results);
			$('playlists_container').adopt(div);
			playlists.slideIn();
		}
	}}).post({'q': $('query').value, 'start': pl_start, 'number':pl_number});	

}

function new_playlist() {
	warning.slideOut();
	var li = new Element('li', {'id': 'empty', 'html': '<b>Empty playlist ..</b><br />Search your favorite videos and drag them into your playlist'});
	
	$('playlist_container').set('text', '');	
	var ul = new Element('ul', {
		'id': 'playlist'
	}).inject('playlist_container').adopt(li);
	$('playlist_title').set('text', 'Empty playlist ..');
	make_sortable();
	current_playlist = 'new';
	playlists.slideOut();
}

function load_playlist(playlist_id) {
	$('playlist_container').set('html', '<img src="'+base_url+'graphics/loading.gif" style="margin: 40px 0px 0px 140px;" />'); 	
	var jsonRequest = new Request.JSON({url: site_url+'?c=player&m=playlist', onComplete: function(feed){
		
		if(feed.videos.length) {
			var li = video_list(feed);
		}
		else {
			var li = new Element('li', {'id': 'empty', 'html': '<b>Empty playlist ..</b><br />Search your favorite videos and drag them into your playlist'});
		}
		$('playlist_container').set('text', '');	
		var ul = new Element('ul', {
			'id': 'playlist'
		}).inject('playlist_container').adopt(li);

		make_sortable();
		playlists.slideOut();
		current_playlist = playlist_id;
		nw_playlist = true;
		if(!current) do_next();		
	}}).post({'playlist_id': playlist_id});
}


function video_list(feed, type) {
	var li = [];
	feed.videos.each(function(video){
		var img = new Element('img', {src: video.img});		 	
		var title = new Element('span', {'text': video.title, 'class': 'video_title'});
		
		var seconds = (video.seconds / 60).round() +':'+ (video.seconds % 60).round(2);
		if(seconds.length < 4) seconds = seconds+'0';
		
		var time = new Element('span', {'text': 'Duration: '+seconds+' mins', 'class': 'video_time'});
		var rating = '';//new Element('span', {'text': 'Rating: '+video.rating, 'class': 'video_rating'});
		var views = '';//new Element('span', {'text': 'Views: '+video.views, 'class': 'video_views'});
		if(type == 'search' || type == 'related') {
			var item = new Element('li', {'id': video.id, 'title':'Drag to your playlist or Double-click to play right away'}).adopt(img, title, time, rating, views);
		}
		else {

			var remove_item = new Element('span', {'text': 'x', 'class': 'remove_item'});
	
			remove_item.addEvent('click', function() {
				if(confirm('Remove this video from your playlist?')){ 
					item.dispose();
					var jsonRequest = new Request.JSON({url: site_url+'?c=player&m=save_playlist', onComplete: function (reply) {
						if(reply.msg == 'max5') $('warning').set('text','Warning! You \'ve reached your maximum of 5 playlists. Your changes are only saved for your current session.');
						if(reply.msg == 'not_owner') $('warning').set('text', 'Warning! You are editing another users\' playlist. Your changes are only saved for your current session.');
						if(reply.msg == 'not_logged') $('warning').set('text','Warning! You are not logged in. Your changes are only saved for your current session.');
						if(reply.msg == 'new') {
							current_playlist = reply.playlist_id;
							$('playlist_title').set('text', reply.title);
							$('warning').set('text','Your new playlist has been saved! How about changing that borring title? Click the title to edit the name of your playlist.');
							//load_playlists(false);
						}
						if(reply.msg == 'success') $('warning').set('text','');
						warning.slideIn();
					}}).post({'playlist_id': current_playlist, 'playlist': sortables.serialize(0).join(',')});
					if($('playlist').getChildren().length == 0) $('playlist').adopt(empty); 
				}
			});
		
			var item = new Element('li', {'id': video.id, 'title':'Double-click to play'}).adopt(remove_item, img, title, time, rating, views);
		} 
		item.store('song', video.title);		
		item.addEvent('dblclick', function(e){												
			do_play($(video.id));
			if(type != 'search' || type != 'related') playing_playlist = feed.playlist_id;
		});
		item.addEvent('selectstart', function(e){
			return false;
		});
		item.unselectable = "on";
 		item.style.MozUserSelect = "none";

		li.push(item);
	});
	return li;
}


var sortables;

function make_sortable() {

	sortables = new Sortables('#playlist, #search_results, #related_results', {handle: 'img', revert: true, clone: true, 
		onStart: function(e) {
			if(e.getParent().id == 'search_results') {				
				from_search_results = e.id;
			}	
			if(e.getParent().id == 'related_results') {				
				from_related_results = e.id;
			}			
		},
		onComplete: function(e){										
			var empty = new Element('li', {'id': 'empty', 'html': '<b>Empty playlist ..</b><br />Search your favorite videos and drag them into your playlist'});
			if(!$('playlist').getChildren().length) {					
				$('playlist').adopt(empty);				
			}
			if(e.getParent().id == 'playlist') {
				e.setProperty('title', 'Double-click to play');
				if(e.id == from_search_results || e.id == from_related_results) {

					var remove_item = new Element('span', {
						'text': 'x',
						'class': 'remove_item'
					});
	
					remove_item.addEvent('click', function() {
						if(confirm('Remove this video from your playlist?')){ 
							e.dispose();
							var jsonRequest = new Request.JSON({url: site_url+'?c=player&m=save_playlist', onComplete: function () {
								if(reply.msg == 'max5') $('warning').set('text','Warning! You \'ve reached your maximum of 5 playlists. Your changes are only saved for your current session.');
								if(reply.msg == 'not_owner') $('warning').set('text', 'Warning! You are editing another users\' playlist. Your changes are only saved for your current session.');
								if(reply.msg == 'not_logged') $('warning').set('text','Warning! You are not logged in. Your changes are only saved for your current session.');
								if(reply.msg == 'new') {
									current_playlist = reply.playlist_id;
									$('playlist_title').set('text', reply.title);
									$('warning').set('text','Your new playlist has been saved! How about changing that borring title? Click the title to edit the name of your playlist.');
									//load_playlists();
								}
								if(reply.msg == 'success') $('warning').set('text','');					
								warning.slideIn();
							}}).post({'playlist_id': current_playlist, 'playlist': sortables.serialize(0).join(',')});
							if($('playlist').getChildren().length == 0) $('playlist').adopt(empty); 
						}
					});
									
					remove_item.inject(e, 'top');
					if($('empty')) $('empty').dispose();

					var anchor = new Element('a', {'name': e.id });
					e.adopt(anchor);						  
				}
				var jsonRequest = new Request.JSON({url: base_url+'?c=player&m=save_playlist', onComplete: function(reply) {
					if(reply.msg == 'max5') $('warning').set('text','Warning! You \'ve reached your maximum of 5 playlists. Your changes are only saved for your current session.');				
					if(reply.msg == 'not_owner') $('warning').set('text', 'Warning! You are editing another users\' playlist. Your changes are only saved for your current session.');
					if(reply.msg == 'not_logged') $('warning').set('text','Warning! You are not logged in. Your changes are only saved for your current session.');
						if(reply.msg == 'new') {
							current_playlist = reply.playlist_id;
							$('playlist_title').set('text', reply.title);
							$('warning').set('text','Your new playlist has been saved! How about changing that borring title? Click the title to edit the name of your playlist.');
							//load_playlists();
						}
					if(reply.msg == 'success') $('warning').set('text','');					
					warning.slideIn();
				}}).post({'playlist_id': current_playlist, 'playlist': sortables.serialize(0).join(',')});
			}				
			else {
				//alert(from_search_results);
				//if(e.id != from_search_results) e.dispose();
				//load_playlist(1);
			}
			if(e.id == from_search_results) {
				from_search_results = '';
				search.slideIn();
			}
			if(e.id == from_related_results) from_related_results = ''; 
		}
	});
	sortables.removeItems($('empty'));

}

window.addEvent('domready', function() { 

	//load_playlists();

	show_hide_results = new Fx.Slide('show_hide_results',{duration: 1000});
	show_hide_results.hide();
	
   search = new Fx.Slide('search_result',{'duration': '1000'});	
	search.hide();
	
	warning = new Fx.Slide('warning',{'duration': '1000'});	
	warning.hide();	

	related = new Fx.Slide('related',{'duration': '1000'});	
	related.hide();
	
	playlists = new Fx.Slide('playlists_container',{'duration': '1000'});	
	playlists.hide();	

   $('playlist_container').makeResizable({handle: $('playlist_handle'),modifiers: {x: false, y: 'height'},limit: {y: [150, 800]}});

	$('search_form').addEvent('submit', function(e) {e.stop(); yt_search(1);});
	
	$('choose_playlist').addEvent('click', function() {if(!playlists.open) load_playlists(); else playlists.slideOut();});
	
	$('show_hide_related').addEvent('click', function() {related.toggle()});
	$('show_hide_results').addEvent('click', function() {search.toggle()});


	$('edit_title').addEvent('blur', function() {
		var jsonRequest = new Request.JSON({url: base_url+'?c=player&m=save_title', onComplete: function(reply) {
			if(reply.msg = 'success') {
				$('playlist_title').set('text', reply.title);
			}
			$('edit_title').setStyle('display', 'none');	 
			$('playlist_title').setStyle('display', 'block');
		}}).post({'playlist_id': current_playlist, 'title': this.value});		
	});
	 //
	$('playlist_title').addEvent('click', function() {
		var jsonRequest = new Request.JSON({url: base_url+'?c=player&m=is_logged_in', onComplete: function(reply) {
			if(reply.logged_in && reply.owner) {
				$('edit_title').value = $('playlist_title').getProperty('text');
				$('edit_title').setStyle('display', 'block').focus(); 
				$('playlist_title').setStyle('display', 'none');
			}		
		}}).post({'playlist_id': current_playlist});	 
	});		

	// previous button
   var button_prev = $('button_prev');   
   button_prev.addEvent('click', function() {do_prev();});
   button_prev.addEvent('mouseover', function() {button_prev.src = base_url+'graphics/prev_over.gif';});
   button_prev.addEvent('mouseout', function() {button_prev.src = base_url+'graphics/prev.gif';});
   
	// next button
   var button_next = $('button_next');   
   button_next.addEvent('click', function() {do_next();});
   button_next.addEvent('mouseover', function() {button_next.src = base_url+'graphics/next_over.gif';});
   button_next.addEvent('mouseout', function() {button_next.src = base_url+'graphics/next.gif';});   

	// play button   
	var button_play = $('button_play');   
	button_play.addEvent('click', function() {
		play_pause('mediaplayer'); 
		/*if(playing) {
			playing = false;
   		button_play.addEvent('mouseover', function() {button_play.src = base_url+'graphics/play_over.gif';});
   		button_play.addEvent('mouseout', function() {button_play.src = base_url+'graphics/play.gif';});
   		button_play.addEvent('click', function() {button_play.src = base_url+'graphics/pause.gif';});			
		}
		else {
			playing = true;
   		button_play.addEvent('mouseover', function() {button_play.src = base_url+'graphics/pause_over.gif';});
   		button_play.addEvent('mouseout', function() {button_play.src = base_url+'graphics/pause.gif';});
   		button_play.addEvent('click', function() {button_play.src = base_url+'graphics/play.gif';});
		}	*/
	});
   button_play.addEvent('mouseover', function() {button_play.src = base_url+'graphics/play_over.gif';});
   button_play.addEvent('mouseout', function() {button_play.src = base_url+'graphics/play.gif';});	
   
	// shuffle button   
	var shuffle_button = $('button_shuffle');   
	shuffle_button.addEvent('click', function() { 
		if(shuffle) {
			shuffle = false;
			shuffle_button.src = base_url+'graphics/shuffle.gif';
   		shuffle_button.addEvent('mouseover', function() {shuffle_button.src = base_url+'graphics/shuffle_over.gif';});
   		shuffle_button.addEvent('mouseout', function() {shuffle_button.src = base_url+'graphics/shuffle.gif';});			
		}
		else {
			shuffle = true;
			shuffle_button.src = base_url+'graphics/shuffle_over.gif';
   		shuffle_button.addEvent('mouseover', function() {shuffle_button.src = base_url+'graphics/shuffle_over.gif';});
   		shuffle_button.addEvent('mouseout', function() {shuffle_button.src = base_url+'graphics/shuffle_over.gif';});
		}
	});
   shuffle_button.addEvent('mouseover', function() {shuffle_button.src = base_url+'graphics/shuffle_over.gif';});
	shuffle_button.addEvent('mouseout', function() {shuffle_button.src = base_url+'graphics/shuffle.gif';});

	// repeat button   
	var repeat_button = $('button_repeat');   
	repeat_button.addEvent('click', function() { 
		if(repeat) {
			repeat = false;
			repeat_button.src = base_url+'graphics/repeat.gif';
   		repeat_button.addEvent('mouseover', function() {repeat_button.src = base_url+'graphics/repeat_over.gif';});
   		repeat_button.addEvent('mouseout', function() {repeat_button.src = base_url+'graphics/repeat.gif';});
   		//button_play.addEvent('click', function() {button_play.src = base_url+'graphics/pause.gif';});			
		}
		else {
			repeat = true;
			repeat_button.src = base_url+'graphics/repeat_over.gif';
   		repeat_button.addEvent('mouseover', function() {repeat_button.src = base_url+'graphics/repeat_over.gif';});
   		repeat_button.addEvent('mouseout', function() {repeat_button.src = base_url+'graphics/repeat_over.gif';});
   		//button_play.addEvent('click', function() {button_play.src = base_url+'graphics/play.gif';});
		}
	});
   repeat_button.addEvent('mouseover', function() {repeat_button.src = base_url+'graphics/repeat_over.gif';});
	repeat_button.addEvent('mouseout', function() {repeat_button.src = base_url+'graphics/repeat.gif';});


	scroll = new Fx.Scroll('playlist_container', {
		wait: false,
		duration: 2500,
		offset: {'x': 0, 'y': -80},
		transition: Fx.Transitions.Quad.easeInOut
	});   
	//new SmoothScroll({ duration: 1800 }, $('playlist')); 
});