/**
 *
 * music player functionality
 *
 */
billboard.player = new (function($)
{
	var SONG_STUTTER = 5;

	var me = this;
	me.isOpen = false;
	me.isQueueOpen = false;
	me.queue = [];
	me.current = 0;
	me.widgetId = "lalaWidgetPlayer";
	me.isPlayerLoaded = false;
	me.autoPlay = false;
	me.stutter = 0;
	me.stutterPaused = false;
	me.callbackUrl = '';

	/**
	 * initialize the player, update the queue visually, 
	 * attach event handlers to the queue
	 */
	me.init = function()
	{	
		billboard.info("Player.init()");

		// subscribe to player events
        if ( window.lala ) {
			lala.Player.addEventListener( lala.Player.EVENT_PLAYER_LOADED, function(e){ me.onPlayerLoaded(e); });
			lala.Player.addEventListener( lala.Player.EVENT_PLAYER_STATUS_CHANGE, function(e){ me.onStateChange(e); });
			lala.Player.addEventListener( lala.Player.EVENT_PLAYBACK_COMPLETE, function(e){ me.onPlaybackComplete(e); });
			lala.Player.addEventListener( lala.Player.EVENT_PLAYBACK_FATAL_ERROR, function(e){ me.onPlaybackFatalError(e); });
			lala.Player.addEventListener( lala.Player.EVENT_PLAYBACK_ERROR, function(e){ me.onPlaybackError(e); });

			// Call initialization function
			lala.Player.init( me.widgetId, { width:220, height:66 }, { useSignupDialog: true, partnerId:"billboard", adDivId:"player-sponsor" } );
			
			// initialize the signup dialog object
			var host = document.location.host;
			me.callbackUrl = "http://" + host + "/html/lalaCallback.html";
			lala.SignupDialog.init( { partnerId:"billboard", callbackUrl:me.callbackUrl, adDivId:"player-sponsor" } );
		}

		// add rollover for the queue elements (if any);
		$("#player-queue ul li").removeClass("over");

		$("#player-ext .previous").css("opacity",".3");
		$("#player-ext .next").css("opacity",".3");
		
		// hide the queue mask layer, so it doesnt interfere with click throughs
		$("#player-queue-container").hide();		

		// if IE6 (since it doesnt support the position:fixed css), update 
		// everything, and start listening for scroll/resize to reposition player
		if ( $.browser.msie && parseInt($.browser.version) == 6 ) {
			billboard.info("IE6 - activating scroll/resize listeners to position player");
			var movePlayer = function() { 
				var pos = $(window).height() + $(window).scrollTop() - (288+72);
				$("#player-container").css({top:pos});
			}
			$("#player-container").css("position","absolute");
			$("#player-queue-container").css( { "position":"absolute","top":"-175px" });
			$(window).scroll( movePlayer );
			$(window).resize( movePlayer );
			//movePlayer();
			var pos = $(window).height() + $(window).scrollTop() - (288+72);
			$("#player-container").css({left:0,top:pos});
		}

		// open the player after a lil delay (sorta lets the page settle, so the opening is more noticeable)
		setTimeout( '$("#player-container").animate({"left":"0px"});', 1200);
	};

	/**
	 * 
	 */
	me.stop = function()
	{
		me.stutter = 0;
		lala.Player.stopPlayback();
	};

	/**
	 * this is triggered from the page, and should clear the queue and add
	 * this as the only item in the queue
	 *
	 * @param mixed - this can be one of 3 things:
	 *                  1) ID - string of numbers, where parseInt() will return !isNaN
	 *                  2) Object - containing two properties, id and title
	 *                  3) String - artist name
	 */
	me.play = function( mixed, title )
	{
		me.stutter = 0;
		if ( typeof ( parseInt(mixed) ) == "number" ) {
			me.setQueue( [{id:mixed,title:title}] );
		}
		else if ( typeof(mixed) == "object" ) {
			me.setQueue( [mixed] );
		}
		else {
			me.playArtist( mixed );
		}
	}

	me.resume = function()
	{
		me.stutter = 0;
		$(".queue-stutter-message").hide();
		$("#player-queue ul").show();
		me.next();
	};
	
	/**
	 * 
	 */
	me.playSongById = function( lalaId, noStutterReset )
	{
		billboard.log("Player.playSongById("+lalaId+")");

		if (noStutterReset!=false) me.stutter = 0;

		// find the item with this id, in the queue
		for ( var i=0;i<me.queue.length;i++ ) {
			if ( me.queue[i].id == lalaId ) {
				me.current = i;
			}
		}
		
		$("#player-queue ul li").removeClass("on");
		$("#player-queue ul li:eq("+me.current+")").addClass("on");

		billboard.log(" - LalaPlayer loaded: "+me.isPlayerLoaded);
		if ( me.isPlayerLoaded ) {
			billboard.log(" - LalaPlayer.playSongById("+lalaId+")");
			// send the id to the flash player
			lala.Player.playSongById( lalaId, true );
		}
		else {
			billboard.log(" - opening player");
			me.autoPlay = true;
			me.open();
		}
	};

	me.playArtist = function( artist )
	{		
	};

	me.playAlbum = function( artist )
	{		
	};

	me.next = function( noStutterReset )
	{
		billboard.log("Player.next()");
		if ( me.queue.length > 0 ) {
			if ( me.current < me.queue.length-1 ){
				me.current++;
			}
			else {
				me.current = 0;
			}
			me.playSongById( me.queue[me.current].id, noStutterReset );
		}		
	};

	me.previous = function()
	{
		billboard.log("Player.previous()");
		if ( me.queue.length > 0 ) {
			if ( me.current > 0 ) {
				me.current--;
			}
			else {
				me.current = me.queue.length - 1;
			}
			me.playSongById( me.queue[me.current].id );
		}
	};

	/**
	 *
	 */
	me.showStutterMessage = function() 
	{
		billboard.log("Player.stutter()");
		me.stutterPaused = true;
		me.open( true );
		me.openQueue();
		$(".queue-stutter-message").show();
		$("#player-queue ul").hide();
	};

	/**
	 * this will replace the current queue, with the passed in queue
	 * it is possible to send a single item array
	 */
	me.setQueue = function( tracks, title, resetCurrent )
	{
		billboard.log( "Player.setQueue("+((typeof tracks == "string")?(tracks):(tracks.length))+","+title+")");
		if ( typeof tracks == "array" ) { 
		    billboard.log( " first track: "+tracks[0].title +": "+ tracks[0].id );
		}
		
		resetCurrent = (resetCurrent==false)?(false):(true);
		if ( title && title.length>0 ) {
			$(".queue-title").text( title );
		}
		else {
			$(".queue-title").text( "" );
		}

		// set internal queue prop
		me.queue = tracks;

		// clear queue div list
		$("#player-queue ul").empty();

		// add an LI for each track
		var innerHtml;
		for ( var i=0;i<tracks.length;i++ ) {
			if ( tracks[i].id && tracks[i].title ) {
				innerHtml = 
					"<li><span class=\"queue_id\">"+tracks[i].id+"</span>"+
					"<a class=\"title\" href=\"javascript:billboard.player.playSongById('"+tracks[i].id+"');\">"+tracks[i].title+"</a>"+
					"<a class=\"remove\" href=\"javascript:billboard.player.remove('"+tracks[i].id+"');\">remove</a>"+
					"<a class=\"play\" href=\"javascript:billboard.player.playSongById('"+tracks[i].id+"');\">&gt;</a>"+
					"</li>";
				$("#player-queue ul").append( innerHtml );
			}
		}

		// attach rollover handlers to the queue item
		$("#player-queue ul li").hover( 
									   function(){ $(this).addClass("over"); },
									   function(){ $(this).removeClass("over"); } 
									   )

		// reset current to first item in the queue
		if ( resetCurrent ) {
			me.current = 0;
			me.stutter = 0;
		}

		// update the enabled-ness of the next/previous buttons (this is just a visual change)
		if ( me.queue.length > 1 ) {
			$("#player-ext .previous").css("opacity","1");
			$("#player-ext .next").css("opacity","1");
		}
		else {
			$("#player-ext .previous").css("opacity",".3");
			$("#player-ext .next").css("opacity",".3");
		}

		// show scroll bars
		$("#player-queue .scroll-track").remove();
		if ( me.queue.length > 4 ) { 
			var s = new Scroller($("#player-list-holder"),$("#player-list-holder ul"));
			s.makeDraggable($("#player-list-holder").find(".scroll-thumb"));
		}

		// start playing the first song, only if this is first time the queue is set (i.e. not from player.remove())
		if ( me.queue.length > 0 && resetCurrent ) {
			me.playSongById( me.queue[me.current].id );
		}

		// open queue
		if ( !me.isOpen ) { 
			me.open();
		}
	};

	/**
	 * locate and remove the playlist item from the queue and the UL based on ID
	 */
	me.remove = function( id )
	{
		me.stutter = 0;
		var newlist = [];
		var index = -1;
		for ( var i=0;i<me.queue.length;i++ ) {
			if ( me.queue[i].id == id ) {
				index = i;
			}
			else {
				newlist.push( me.queue[i] );
			}
		}

		// if we're removing the currently playing song, stop player
		if ( index == me.current ) {
			me.stop();
		}

		$("#player-queue ul li:eq("+index+")").remove();

		// store old current
		var oldCurrent = (index<me.current)?(me.current-1):(me.current);

		// update queue
		me.setQueue( newlist, false );

		// reset the current 
		me.current = (oldCurrent>me.queue.length-1)?(0):(oldCurrent);
		$("#player-queue ul li").removeClass("on");
		$("#player-queue ul li:eq("+me.current+")").addClass("on");
	};

	/**
	 * toggles open/close state
	 */
	me.toggle = function()
	{
		me.stutter = 0;
		if ( !me.isOpen ) me.open();
 		else me.close();
	};


	/**
	 * slide the player tray out to display full player view
	 */
	me.open = function( full )
	{
		billboard.info("Player.open()");
		me.stutter = 0;
		me.isOpen = true;
		$("#player-queue-container").css( "left", 0 );
		$("#player-queue").css("left", "0px");
	    $("#player-container").animate( {"left":"-329px"},300,"easeinout",function() {
			$("#player-closed").css("display","none");
			$("#player-container").css({"left":"-267px"});
			$("#player-open").css("display","block"); 
			$("#player-container").animate({"left":"0px"},750,"easeinout", function() {
				// show the ad portion of the player queue
				if ( !full ) { 
					$("#player-queue-container").show();
					$("#player-queue").animate( {"top":"124px"}, 100, "easeinout");
				}
				if ( me.autoPlay ) {
					billboard.info(" Player is now open");
					//me.playSongById( me.queue[me.current].id );
					//me.autoPlay = false;
				}
			});			
		});
	};

	/**
	 * close the player tray to show only the compact mode
	 */
	me.close = function()
	{
		billboard.log("Player.close()");
		me.stutter = 0;

		var leftPx = ($.browser.msie && parseInt($.browser.version) == 6) ? "-274px" : "-267px" ;

		// Q. why were the following 3 lines commented out?
		if ( me.isQueueOpen ) {
			me.closeQueue(true);
		}

		$("#player-queue").animate( {"top":"175px"}, 100, "easeinout");
	    $("#player-container").animate( {"left":leftPx},500,"easeinout",function() {
			$("#player-closed").css("display","block");
			$("#player-container").css({"left":"-329px"});
			$("#player-container").animate({"left":leftPx},300,"easeinout", function() { 
				$("#player-queue-container").css( "left", -500 );
			});
		});
		me.isOpen = false;
	};

	me.toggleQueue = function()
	{
		me.stutter = 0;
		billboard.log("Player.toggleQueue()");
		if ( me.isQueueOpen ) me.closeQueue();
		else me.openQueue();
	};

	me.openQueue = function()
	{
		me.stutter = 0;
		billboard.log("Player.openaQueue()");
		$("#player-queue-container").show();
		$("#player-queue").animate( {"top":"0px"}, 400, "easeinout" );
		me.isQueueOpen = true;
	};

	me.closeQueue = function(fast)
	{
		me.stutter = 0;
		billboard.log("Player.closeQueue()");
		duration = (fast)?100:400;
		$("#player-queue").animate( {"top":"124px"}, duration, "easeinout",function(){ 
			/* THIS BLOCKS SOME CONTENT ON LOWER RESOLUTIONS */
			/* $("#player-queue-container").hide(); */ 
		});
		me.isQueueOpen = false;
	};

	/**
	 * Player / Playback Events
	 */
	me.onPlayerLoaded = function(e) { 
		billboard.log("PLAYER EVENT: flash player Loaded");
		billboard.log("   autoplay: "+me.autoPlay);
		billboard.log("  cur queue: "+me.queue.length);
		me.isPlayerLoaded = true;
		if ( me.autoPlay ) {
			billboard.info( me.queue );
			billboard.info( me.current );
			billboard.info( me.queue[me.current] );
			me.playSongById( me.queue[me.current].id );
		}
	};

	me.onStateChange = function(e) {
		billboard.log("PLAYER EVENT: player state change ["+e+"]");
		if ( e == "playing" && me.stutterPaused ) {
			me.stutterPaused = false;
			me.resume();
		}
	};

	me.onPlaybackComplete = function(e) {
		billboard.log("PLAYER EVENT: playback complete");
		billboard.log( e );		
		if ( me.current < me.queue.length - 1 ) {
			me.stutter++;
			billboard.log ( "stutter now: "+me.stutter +" ?= " +(SONG_STUTTER) );
			if ( me.stutter >= SONG_STUTTER ) {
				me.stutter = 0;
				me.stop();
				me.showStutterMessage();
			}
			else {
				me.next(false);
			}
		}
	};

	me.onPlaybackError = function(e) {
		billboard.log("PLAYER EVENT: playback error");
		billboard.log( e );
	};

	me.onPlaybackFatalError = function(e) {
		billboard.log("PLAYER EVENT: playback fatal error");
	};

	me.onSignupComplete = function( canceled ) 
	{
		billboard.log("Player.onSignupComplete("+canceled+")");
		if ( !canceled ) {
			me.resume();
		}
	};

})(jQuery);
