//CK: this here to avoid JS errors for undefined console when user does not have firebug installed (console is defined by firebug)
if (!console) { var console={log:function(){}}; }
var PLAYER;
(function($) {
	PLAYER = {
		onYouTubePlayerReady:function (playerId) {
			PLAYER.swf = document.getElementById("myytplayer");
			PLAYER.swf.addEventListener("onStateChange", 'onStateChange');
			META.setup.onFbLogin();
		},
		setup:function() {
			PLAYER.size.setup();
			if(PLAYER.pastTinyVideo == 'tiny') {
			  PLAYER.tinyVideo();
			} else if (PLAYER.pastClosedOpen == 'closed') {
				PLAYER.close(document.getElementById("close"));			
			};
			$('#player').addClass('hover introHover').hover(
					function(){
						$(this).addClass('hover').removeClass('introHover');
						$('#query input').focus().select();
						clearTimeout(PLAYER.hideGracefullyTimeout);
					},
					function(){
						var here = $(this);
						PLAYER.hideGracefullyTimeout = setTimeout( function() {here.removeClass('hover')}, 750)
					}).
				find('a').click(function() {this.blur(); $('#query input').focus().select()});
			$('#stage').hover( function(){ $(this).addClass('hover'); }, function(){ $(this).removeClass('hover'); });
			$('#currentTitle').click(PLAYER.seekTo);

			LIST.setup();
		},
		onStateChange:function(newState) {
			if(newState == 1) {
				setTimeout(function() {$('#player').hasClass('introHover') && $('#player').removeClass('hover')}, 3000);
				setInterval(PLAYER.progressBar, 1000);
			} else if(newState == 0) {
				LIST.next();
			};
		},
		laterLoad:function() {
			PLAYER.swf.loadVideoById(PLAYER.laterLoad.id, 0)
			PLAYER.onVideoLoad = setInterval(function() {
				if(PLAYER.swf.getVideoBytesLoaded() > 0) {
					PLAYER.play();
					clearTimeout(PLAYER.onVideoLoad);
				};
			}, 10);
			$('#progressBar').css('width', 0);
			$('#youtube').attr('href', 'http://www.youtube.com/watch?v='+LIST.now.id);
			PLAYER.nextPrev();
			$('#playPauseTiny, #tinyVideo').unbind('click', PLAYER.laterLoad);
		},
		loadNewVideo:function(id) {
			clearTimeout(PLAYER.onPlayerLoad);
			clearTimeout(PLAYER.onVideoLoad);
			if(PLAYER.swf) { 
				PLAYER.laterLoad.id = id;
				if(PLAYER.pastPlayPause == 'pause') {
					$('#playPauseTiny img').src('play').removeClass('loading').css('margin','0');
					$('#playPauseTiny, #tinyVideo').bind('click', PLAYER.laterLoad);
				} else {
					PLAYER.laterLoad();
				};
			} else {
				PLAYER.onPlayerLoad = setTimeout(function() {PLAYER.loadNewVideo(id)}, 300);
			};
		},
		play:function() {
			if(PLAYER.swf) { 
				$('#playPause img').src('pause-big');
				$('#playPauseTiny img').src('pause').removeClass('loading').css('margin','0');
				document.title = LIST.now.bestTitle + ' / '+'Friend Radio';
				PLAYER.swf.playVideo();
			}
		},
		pause:function() {
			if(PLAYER.swf) { 
				$('#playPause img').src('play-big');
				$('#playPauseTiny img').src('play');
				PLAYER.swf.pauseVideo();
			}
		},
		playPause:function() {
			PLAYER.swf.getPlayerState() == 1 ? PLAYER.pause() : PLAYER.play();
			window.STREAM && window.STREAM.playPause(false, 'fromPlayer');
		},
		stop:function() { PLAYER.swf && PLAYER.swf.stopVideo(); },
		close:function(o) {
			if(PLAYER.inExtension) {
				PLAYER.pause(); 
				var player = $('#player'), tinyVideo = $('#tinyVideo');
				swapTitleSrc(tinyVideo, 'Play music with friendradio!', 'play');
				player.addClass('closed').data('videoWidth', player.css('width')).css('width', 40).
				data('videoTop', player.css('top')).css('top', player.data('originalTop'));
				PLAYER.popup.close();
			} else { 
				window.location = 'http://www.facebook.com/';
			};
		},
		clickedClose:function(o) {
      $.post('/metrics/log/player_clicked_close/');
      PLAYER.close(o);
		},
		size:{
			auto:function() {
				PLAYER.size.autoWidth = 160 + Math.max(PLAYER.size.ww-1024,0)/2.0;
				PLAYER.size.change(PLAYER.size.autoWidth);
				$('#player').removeClass('big');
			},
			bigSmall:function(manual) {
				var bigSmall = $('#bigSmall'), player = $('#player'), width;
				if(player.hasClass('big') && !manual ) {
					swapTitle(bigSmall);
					player.removeClass('big');
					width = PLAYER.size.autoWidth;
				} else {
					swapTitle(bigSmall, 'Click to restore to SMALL size. Drag to RESIZE!');
					player.addClass('big');
					width = Math.max(manual || PLAYER.size.ww, 160);
				};
				PLAYER.size.change(width);
			},
			change:function(width) {
				if(PLAYER.size.wh-(.72*width)-150 < 0) width = Math.floor((PLAYER.size.wh - 150)/.72);
				var height = .72*width;
				var top = PLAYER.size.wh-height-150;

				$('iframe').css('height', PLAYER.size.wh);
				$('#player').css({width:width, top:top}).data('originalTop', $('#player').data('originalTop')||top);
					$('#myytplayer').attr('height',height).attr('width',width-10);
					$('#currentTitle').css('width',width-10);
					$('#youtube').css({left:width-70-6, top:height-35+5});
					$('#next').css('left', width-35-5).add('#prev').css('top', (height/2.0)-17.5+8);
					$('#query').css('top', height-20).find('input').css('width', width-40);
					$('#playPause img').css('margin-top', (height/2.0)-25+8);
					$('#buy').css('top', height-30+5);

					$('.popup').css({top:top+55});
			},
			setup:function() {
				(window.onresize = function() {
					PLAYER.size.wh = parseFloat($(window).height());
					PLAYER.size.ww = parseFloat($(window).width());
					PLAYER.size.auto();
				})();
				$('#bigSmall').mousedown(function() {
					$('#veil').show();
					$('body').addClass('dragging').mousemove( function(e) {
						$('#player').addClass('hover');
						PLAYER.size.bigSmall(e.pageX);
					});
					return false;
				});
				$('body').mouseup(function() {
					$('body').removeClass('dragging').unbind('mousemove');
					$('#veil').hide();
				})
			}
		},
		nextPrev:function() {
			if(LIST.now) $('#currentTitle').attr('title', LIST.getQuery(LIST.now)).find('span').text(LIST.getQuery(LIST.now));
			if(LIST.now) {
				$('#buy').attr('href','http://click.linksynergy.com/fs-bin/stat?id=JeW5DXRXL0g&offerid=146261&type=3&subid=0&tmpid=1826&RD_PARM1=itms%3A%2F%2Fphobos.apple.com%2FWebObjects%2FMZSearch.woa%2Fwa%2FadvancedSearchResults%3FsongTerm%3D'+encodeURI(LIST.now.title)+'%2526artistTerm%3D'+encodeURI(LIST.now.artist));
			}
			LIST.batch.length > 1 ? $('#next').show().attr('title', LIST.getQuery(LIST.next)) : $('#next').hide();
			LIST.now.index > 0 ? $('#prev').show().attr('title', LIST.getQuery(LIST.prev)) : $('#prev').hide();
		},
		fave:function(index) { index = index||LIST.now.index;
			var fave = $('#fave, #faveTiny');
			$.post('/metrics/log/player_fave/');	
			if( (LIST.now.index==index) && (!fave.hasClass('faved')) && (!fave.hasClass('faving')) ) {
				fave.addClass('faving');
				window.STREAM && window.STREAM.fave(index);
				OUTSIDE.fave(index);
			};
		},
		progressBar:function() {
			if(PLAYER.swf) { 
				var current = Math.ceil(PLAYER.swf.getCurrentTime()), duration = Math.ceil(PLAYER.swf.getDuration());
				$('#progressBar').css('width', Math.max(Math.ceil(current/duration*$('#currentTitle').innerWidth())-10, 0));
				$('#currentTitle').attr('title', LIST.now.bestTitle + ' ('+pretty(current)+' of '+pretty(duration)+')');
			};
		},
		seekTo:function(e) {
			if(PLAYER.swf) {
				PLAYER.swf.seekTo(Math.ceil(e.pageX/$('#currentTitle').innerWidth()*PLAYER.swf.getDuration()), true);
			}
		},
		buy:function(result) {
			$.post('/metrics/log/buy_player/');	
		},
		allow:function(result) {
			if(result) {
				$.post('/metrics/log/player_allow/');	
				$('iframe[name=facebook]').attr('src', 'http://apps.facebook.com/friendradio/friends/');
				$('#introduction').css('display','none');
				
			} else {
				$.post('/metrics/log/player_skip/');	
				$('#introduction').css('display','none');
			}
			
		},
		tinyVideo: function() { var player = $('#player'), tinyVideo = $('#tinyVideo');
		  // tiny -> video
			if(player.hasClass('tiny')) {
				swapTitleSrc(tinyVideo, false, 'tiny');
				player.removeClass('tiny').css({width:player.data('videoWidth'), top:player.data('videoTop')});
				$('.popup').css({top:player.data('videoTop')+35});
		  // closed -> big
			} else if (player.hasClass('closed')) {
				swapTitleSrc(tinyVideo, false, 'tiny');
				player.removeClass('closed').css({width:player.data('videoWidth'), top:player.data('videoTop')});
				PLAYER.popup.closed ? PLAYER.play() : $('#popup .play').click();
			  $('.popup').css({top:player.data('videoTop')+35});	
		  // video -> tiny
			} else {
				swapTitleSrc(tinyVideo, 'Expand player to show VIDEO', 'video');
				player.addClass('tiny').data('videoWidth', player.css('width')).css('width', 40).
					data('videoTop', player.css('top')).css('top', player.data('originalTop'));
				$('.popup').css({top:player.data('originalTop')+55});
			}
		},
		find: {
			hint: 'Type a band or song you like',
			send:function() { var query = $('#query input').val();
				if(query != PLAYER.find.hint) {
					$('#query').addClass('finding').find('div').html('<img src="/static/img/loading-84CF33.gif" style="vertical-align:middle"/> Finding...');
					LIST.lucky(query.replace('+', ''), false, false, PLAYER.find.receive);
				} else {
					$('#query input').focus().select();
				};
			},
			receive:function(lucky) { var query = $('#query input').val();
				if((lucky===null) || (lucky.length == 0)) {
					$('#query').addClass('error').find('div').html('<div style="width:50%; overflow:hidden; float:left">'+query+'</div> <b>NOT</b> found');
				} else {
					LIST.update([$.extend(lucky, {'query':query})], (query.indexOf('+')!=-1 ? 1 : undefined));
					$('#query div').html('<b>'+(query.indexOf('+')!=-1 ? 'QUEUED' : 'FOUND')+'</b> '+lucky.bestTitle)
				};
				setTimeout(function() {
					$('#query').removeClass('error finding').find('input').attr('value', PLAYER.find.hint).removeClass('changed').focus().select();
				}, 2000);
			}
	    },
		embed: function() {
			window.google.load("swfobject", "2.1");
			$(function() {
				swfobject.embedSWF("http://www.youtube.com/apiplayer?enablejsapi=1&yt:crop=16:9&playerapiid=ytplayer", "ytapiplayer",
					'10', '10', '8', null, null, { allowScriptAccess: "always", bgcolor: "#ccc", wmode: 'transparent' }, { id: "myytplayer" });
			});
	    },
		popup:{
			closed:true,
			open:function(id, type) {
				console.log('cu'+PLAYER.popup.current);
				console.log('cl'+PLAYER.popup.closed);
				console.log('id'+id);
				if(id != PLAYER.popup.current) {
          //show loading image because data call is slow
				  $('#playPauseTiny').html('<img class="loading" src="/static/img/loading-047ca3.gif" /><img class="loading-84CF33" src="/static/img/loading-84CF33.gif" />');
				  console.log("new popup id, testing weird line");
					(!PLAYER.popup.current) && (PLAYER.popup.current = id);
					console.log("done setting popup current id, going to friend or page");
					type == 'friend' ? PLAYER.popup.isFriend(id) : PLAYER.popup.isPage(id);
				};
			},
			isFriend:function(uid) {
			  console.log('friend!');
        $.post('/metrics/log/popup_on_friend_page/');	
				OUTSIDE.getUser(uid, function(user) {
					$.getJSON("/fbapp/data/feed/"+(user.uid)+"/", function(songs) { 
						PLAYER.popup.make(user.first_name, songs.feed, 'Music');
					});
				});
			},
			isPage:function(id) {
			   console.log('page!');
			   OUTSIDE.login(function() {
				   FB.Facebook.apiClient.fql_query('SELECT name, type FROM page WHERE page_id='+id, function(page) { page = page[0];
					   console.log(page);
					   if(page.type == 'MUSICIANS') PLAYER.popup.isBand(page.name)
				   });
			   });
			},
			isBand:function(name) {
			   console.log('band!');
        $.post('/metrics/log/popup_on_band_page/');	 
				$.getJSON("/fbapp/data/lastfm/"+name+"/", function(songs) { 
					PLAYER.popup.make(name, songs.feed, 'Top Songs');
				});
			},
			make:function(name, songs, type) {
				console.log('making');
				//restore play button after data call is done
        $('#playPauseTiny img').removeClass('loading').src('play').css('margin','0');
				if (!(songs.length > 0)) console.log("making 0 songs :(");
				if(songs.length > 0) {
				  console.log("making from " + songs.length + " songs"); 
					PLAYER.popup.songs = songs.slice(0,5);
//CK: fixing the popup offset too far to right
//http://www.screencast.com/users/DropPlay/folders/Jing/media/370cf6fe-a605-4106-8011-56890f2b5881
//					$('#popup').show().animate({left:parseFloat($('#player').css('width'))+($('#player').hasClass('tiny') ? (-10) : 0) }, 2000).
					var player = $('#player');
//					var futureLeft = parseFloat(player.css('width')); // left for default big player
//					if (player.hasClass('tiny')) { futureLeft = 30; } // left for tiny
//					else if (player.hasClass('closed')) { futureLeft = 0; } // left for closed
var futureLeft = 0;
//CK: setting the popup left of where it's animating to, since sometimes the popup left gets set to video width even when closed
				  (type == 'Music') ? $.post('/metrics/log/popup_open_friend/') :  $.post('/metrics/log/popup_open_band/');		
					$('#popup').css({left:(futureLeft - 275)}).show().animate({left:futureLeft}, 1000).find('.name').text(name).end();
					$('#popup .play').unbind('click').bind('click', function() {
							if(!PLAYER.popup.closed) {
				        (type == 'Music') ? $.post('/metrics/log/popup_playing_friend/') :  $.post('/metrics/log/popup_playing_band/');		
				        LIST.update(PLAYER.popup.songs);
					      PLAYER.popup.close('mm');
                if (player.hasClass('closed')) { var tinyVideo = $('#tinyVideo');
				          swapTitleSrc(tinyVideo, false, 'tiny');
				          player.removeClass('closed').css({width:player.data('videoWidth'), top:player.data('videoTop')});
					      };
					      var bubble = $('#bubble');
					      bubble.show('slow');//.bind('click', function(){bubble.hide('normal');});
					      setTimeout(function(){bubble.hide('slow');}, (1000*4));
			        };
			      });
						//find('type').text(' '+(type == 'friend' ? 'Music' : 'Top Songs')).end();
					$('#popup .tracks').html('');
					$.each(PLAYER.popup.songs, function() {
					  var title = this.title, artist = this.artist;
					  if ((title.length + artist.length) > 30) { 
  					  title = (title.length > 10) ? (title.substring(0,10)) : title;
					    if ((title.length + artist.length) > 30) artist = (artist.length > 15) ? (artist.substring(0,10) + "...") : artist;
						};
						$('#popup .tracks').append('<div class="artist"><b>'+title+ '</b> by '+artist+'</div>');
						$('#popup .artist').stripe();
					});
          PLAYER.popup.closed = false;
				};
			},
			close:function(tracker){
			  console.log('tr'+tracker);
				if($('#popup').css('display') != 'none') {
					console.log('clooose');
					PLAYER.popup.closed = true, PLAYER.popup.current = false;
//CK: setting closed to false in popup.open so that we can use it for toggling popup playlist vs. regular playlist
//					setTimeout(function() {PLAYER.popup.closed = false},2000);
					$('#popup').animate({left:'-275px'}, 1000, function(){ $('#popup').hide(); });
				};
			},
			clickedClose:function(){
        $.post('/metrics/log/popup_clicked_close/');	
			  PLAYER.popup.close();
			}
		}
	};

	//private helpers
	function pretty(seconds) {
		var rest = seconds%60;
		return Math.floor(seconds/60)+':'+(rest > 10 ? rest : '0'+rest)
	}
	jQuery.fn.src = function(fname) {
		return this.attr('src', '/static/img/player/'+fname+'.png');
	}
	function swapTitleSrc(obj, title, fname) {
		swapTitle(obj, title);
		obj.attr('title', title||obj.data('title')).find('img').src(fname+'');
	}
	function swapTitle(obj, title) {
		if(!obj.data('title')) obj.data('title', obj.attr('title'));
	}
})(jQuery);

//Google's code needs these hooks
var onYouTubePlayerReady = PLAYER.onYouTubePlayerReady;
var onStateChange = PLAYER.onStateChange;
