var LIST;
(function($) {
	LIST = {
		flush:true, intervalCount:0, cookieName:'', firstUpdate:true,
		setup:function() {
			if( (window.location.href.indexOf('?share=') == -1) &&
					(window.location.hash == '' || window.location.hash == '#/home/' || window.location.hash == '#/playlists/')) {
				LIST.flush = false;
				LIST.update(SETTINGS.query||( ((typeof(LIST.past)=='string') && (LIST.past != 'false')) ? eval(LIST.past) : false)||'');

				LIST.cookieInterval = setInterval(function() {
					if (LIST.intervalCount++ < 120) { //if it hasn't loaded in 30 seconds, then give up
						if(LIST.cookieName != '') {
							if (LIST.cookieName != encodeURI($.cookie(SETTINGS.api_key+'_session_key'))) {
								//cookie changed
								LIST.update(SETTINGS.query);
								LIST.cookieName = encodeURI($.cookie(SETTINGS.api_key+'_session_key'));
								clearInterval(LIST.cookieInterval);
							}
						} else {
							LIST.cookieName = encodeURI($.cookie(SETTINGS.api_key+'_session_key'));
						} 
					} else {
						clearInterval(LIST.cookieInterval);
					}
				}, 250);
			};
		},
		lucky:function(query, artist, title, fun) {
			$.getJSON("/data/lucky/"+encodeURI(query)+'/?artist='+encodeURI(artist||'')+'&title='+encodeURI(title||''), fun);
		},
		play:function(index) { 
			var song = LIST.batch[index];
			LIST.now = song;

			if(song.id) {
				PLAYER.loadNewVideo(song.id);
				LIST.autoMore();
				LIST.nextPrev();
			} else {
				LIST.lucky(LIST.getQuery(song), song.artist, song.title, function(lucky) {
					if((lucky==null) || (lucky.length == 0)) {
						LIST.autoMore(LIST.batch.length - 1);
						LIST.remove(index);
					} else {
						song = LIST.batch[index] = LIST.now = $.extend(song, lucky);
						PLAYER.loadNewVideo(lucky.id);
						data = {"artist" : encodeURI(song.artist), "title" : encodeURI(song.title)}
						$.post("/metrics/log/play/", data);
						LIST.autoMore();
					};
					LIST.nextPrev();
				});
			}
			window.STREAM && window.STREAM.refresh();
			$('#fave').removeClass('faved');
		},
		getQuery:function(song) {
			return song.bestTitel||song.query||(song.artist+' - '+song.title)
		},
		remove:function(index) {
			var playNext = LIST.now.index == index;
			LIST.batch = LIST.reindex( LIST.batch.slice(0, index).concat(LIST.batch.slice(index+1)) );
			playNext && LIST.play(index >= LIST.batch.length ? LIST.batch.length-1 : index);
	    },
		nextPrev:function() {
			$.extend($.extend(LIST.next, {query:false, bestTitle:false}), LIST.batch[LIST.now.index+1]); //this is cool!
			(LIST.now.index != 0) && ($.extend($.extend(LIST.prev, {query:false, bestTitle:false}), LIST.batch[LIST.now.index-1]));
			PLAYER.nextPrev();
		},
		next:function() {
			return LIST.play(LIST.now.index+1);
		},
		prev:function() {
			return (LIST.now.index != 0) && LIST.play(LIST.now.index-1);
		},
		reindex:function(batch) {
			return $.map(batch, function(s, i) {s.index = i; return s});
		},
		fromTo:function(from, to) {
			var first = LIST.batch.slice(0,from), second = LIST.batch.slice(from+1), moved = [LIST.batch[from]];

			if(to <= from) {
			  first = first.slice(0,to).concat(moved.concat(first.slice(to)));
			} else {
			  second = second.slice(0,to-from).concat(moved.concat(second.slice(to-from)));
			};

			LIST.batch = LIST.reindex( first.concat(second) );
			LIST.nextPrev();
			LIST.autoMore();
		},
		more:function(fun) {
			// Append a random number to the JSON call to circumvent browser caching
			META.onReady('stream', function() { window.STREAM.more('loading') });

			OUTSIDE.login(function() {
				$.getJSON("/data/feed/?"+encodeURI($.cookie(SETTINGS.api_key+'_session_key'))+"&ajax_id="+Math.floor(Math.random()*1000000000), function(data) {
					LIST.update(data.feed, -1);
					fun && fun();
				});
			});		
			

		},
		autoMore:function(l) {
			if((l||LIST.batch.length) - LIST.now.index <= 2 ) {
				LIST.flush = false;
				LIST.more();
			}
		},
	   //SONGS can be a comma-separated string or an array
	   //QUEUE can be empty to start playing SONGS;
	   //0,1,2... to queue them next, after-next, after-after-next...;
	   //or -1,-2,-3, to append them at the end, before-end, before-before-end.
		update:function(songs, queue) { 
			META.onReady('stream', function() { window.STREAM.more('loading') });
			LIST.batch = LIST.batch||[];
			var index = (LIST.now ? LIST.now.index : 0) + (queue===undefined ? (LIST.now ? 1 : 0) : (queue < 0 ? LIST.batch.length+queue+1 : queue));
			var fun = function(batch) { var l = batch.list.length;
				if(l==0) return;

				(LIST.flush && LIST.now) && (LIST.batch = [LIST.now]);
				LIST.flush = true;

				LIST.batch = LIST.reindex( LIST.batch.slice(0, index).concat(batch.list).concat(LIST.batch.slice(index)) );
				if(queue===undefined) {
								console.log("playing index:" + index + "/batch: " + LIST.batch);
					LIST.play(index); 
				} else {
					(LIST.batch.length == batch.list.length) && LIST.play(0);
					LIST.nextPrev();
					
				};
				META.onReady('stream', function() {
					window.STREAM.more('done');
					META.cache.add((META.hash.current||'').replace(/\#|\//g,'').replace(/^$/,'home'));
				});
			};
			if((typeof(songs)=='string') && (songs != '')) {
				fun({list:$.map(songs.match(/[^,]+/g), function(q) {return {query:q}})});
			} else if(songs.constructor.toString().indexOf('Array') != -1) {
				fun({list:songs});
			} else {
				LIST.more();
			};
	   	}
	};
})(jQuery);
