// -------------------------------------------------------------------
// CONSTANTS 
// -------------------------------------------------------------------

var PLAYER;
var PERCENT_LOADED = 0;
var TIME_ELAPSED = 0;
var TIME_TOTAL = null;
var CURRENT_STATE = 0;
var PREVIOUS_STATE = CURRENT_STATE;
var KILL_SONG = false;
var PLAYING_NEXT = false;
var STAT_PLAY = false;
var STAT_COMP = false;
var CURRENT_VOLUME;

var CURRENT_SONG = "";

// -------------------------------------------------------------------
// Player Commands
// -------------------------------------------------------------------

function playSong( target ) {
	$("#query").blur();
	songID = youtubeId( target );
	CURRENT_SONG = songID;
	if(CURRENT_STATE > 0) {
		stopSong();
	}
	showPlayer();
  	setSound( songID );
  	setPlayMarker(target);
}

function rewindSong() {
	curSong = CURRENT_SONG;
	stopSong();
	setSound( curSong );
  	setPlayMarker(CURRENT_SONG);	
	transparentMessage( "The song is reloading." )
}

function pauseSong() {
	if( CURRENT_STATE == 0 ) {
		transparentMessage( "The song is still paused." )
	} else {
		updatePlayButton("pause");
		notifyPlayer('playpause');
		updatePlayerStatus('Paused');
		transparentMessage( "Paused" );
	}
}

function resumeSong() {
	if( CURRENT_STATE == 0 ) {
		updatePlayButton("play");
    notifyPlayer('playpause');
    updatePlayerStatus('Now Playing');
    transparentMessage( "Playing" );
	} else {
    transparentMessage( "The song is already playing." )
  }
}

function stopSong() {
  // Notify the player that it should stop the current song
  notifyPlayer('stop');

  // Update the player display to reflect no song playing
  updatePlayButton("pause");
  updatePlayerIndicator('');
  hidePlayerIndicatorLoading();
  updateProgressLoaded(0);
  updateProgressPlayed(0);
  updatePlayerStatus('Last Played');
}

function scrubSong( event ) {
	// Only perform this action if TIME_TOTAL is set
	if( TIME_TOTAL > 0 ) {
		
		// Setup the variables
		click_location = event.pageX - event.target.offsetLeft;
		progress_width = $(event.target).width();
		parent_width = $(event.target).parent().width();
	
		// Determine the number of seconds where the user wants to scrub to
		scrub_to = Math.floor( TIME_TOTAL * ( click_location / parent_width ) );
		// Scrub
		notifyPlayer( 'scrub', scrub_to );
	}
}

function setVolume( event ) {
	// See if the user clicked the volume box or a bar itself
	if( $(event.target).is(".vol-bar") ) {
		// Get the bar number to figure out volume percentage
		bar_num = $(event.target).attr("id").substring(3, 4);
	} else {
		// Setup the variables
		click_location = event.pageX - event.target.offsetLeft;
		vol_width = $(event.target).width();
		bar_num = Math.round( (click_location / vol_width) * 5 );
		
		// Don't let the volume go to zero
		if( bar_num == 0 ) bar_num = 1;
	}
	
	// Set the display to match current volume
	updateVolume( bar_num );
	
	// Notify the player of the new volume
	CURRENT_VOLUME = ( bar_num / 5 ) * 100;
	notifyPlayer( 'volume', CURRENT_VOLUME );
	
	// Set the cookie value
	$.cookie( "volume", CURRENT_VOLUME, {expires:365} );
}

// -------------------------------------------------------------------
// Display Functions 
// -------------------------------------------------------------------

function updatePlayerIndicator(message) {
	$("#ctl-indicator").text(message);
}

function showPlayerIndicatorLoading() {
	if( $("#ctl-loading").is(':hidden') )
		$("#ctl-loading").fadeIn("fast");
}

function hidePlayerIndicatorLoading() {
	$("#ctl-loading").hide();
}

function resetPlayerVars() {	
	PERCENT_LOADED = 0;
	TIME_ELAPSED = 0;
	TIME_TOTAL = null;
	CURRENT_STATE = 0;
	PREVIOUS_STATE = CURRENT_STATE;
	PLAYING_NEXT = false;
	STAT_PLAY = false;
	STAT_COMP = false;
}

function updateProgressLoaded(percent) {
	$('#ctl-progress-loaded').css('width', percent + '%');
}

function updateProgressPlayed(percent) {
	// Send stat information here
	if( percent > 0 && !STAT_PLAY ) {
		STAT_PLAY = true;
		updateStats( songID, 'play' );
	}
	if( percent > 70 && !STAT_COMP ) {
		STAT_COMP = true;
		updateStats( CURRENT_SONG, 'complete' );
	}
	
	progress_bar = $('#ctl-progress-played');
	
	if( percent == 0 ) progress_bar.css('visibility', 'hidden');
	else progress_bar.css('visibility', 'visible');
	progress_bar.css('width', percent + '%');
}

function updateSongName(name) {
	$('#froogel-name').html(name);
}

function updatePlayerStatus(message) {
	$('#froogel-status').text(message + ':');
	
	// There's a second argument to this function which will specify whether or not this is an error message
	if(arguments[1])
		$('#froogel-status').addClass('failed');
	else
	$('#froogel-status').removeClass('failed');
}

function updatePlayButton(state) {
	if(state == "pause") {
		$('#pause').addClass('ctl-button-active');
		$('#play').removeClass('ctl-button-active');
	} else {
		$('#play').addClass('ctl-button-active');
		$('#pause').removeClass('ctl-button-active');
	}
}

function transparentMessage( message ) {
	humanMsg.displayMsg( message );
}

function showCurrentlyPlaying( songID, title ) {
	var link = document.createElement("a");
	var div = document.createElement("div");
	link.value = songID;
  	$(link).addClass( "song" );
	$(div).html( title );
	$(link).prepend( div );
  	$(link).flower({ click: flowerInfo.searchResultHandler,
                          indicate: flowerInfo.shelves,
                          image: "/images/flower_main.png",
                          leave: flowerInfo.leave     });
 
	if( $('#right-col').is(':hidden') ) {
		$('#left-col').prepend( $('#currently-playing') );
		if( $('#left-col').is(':hidden') )
			$('#left-col').fadeIn();
	} else
		$('#right-col').prepend( $('#currently-playing') );
	
	$("#currently-playing .box").empty().append( link );

  $("#currently-playing #discography").html( "Discography" )
    .attr( "href", "http://www.google.com/musicsearch?q=" + title )
    .attr( "target", "_new" )

  $("#currently-playing #buy").html( "Buy" )
    .attr( "href", "http://www.google.com/products?q=" + title )
    .attr( "target", "_new" )

  $("#currently-playing #watch").html( "Watch Video" )
    .attr( "href", "http://youtube.com/watch?v=" + songID )
    .attr( "target", "_new" )

	if( $("#currently-playing").is(':hidden') )
		$("#currently-playing").fadeIn("normal")
}

function showRightCol() {
	// Show the playlist and adjust the search box
	if( $('#right-col').is(':hidden') && !$('#content').is(':hidden') ) {
		// If there's a currently playing song, shift it to the right column
		if( CURRENT_SONG != "" && ( $("#search-results").is(':visible') || $("#tips").is(':visible') ) ) {
			$("#currently-playing").fadeOut("normal", function() {
				$("#right-col").prepend( $("#currently-playing") );
			});
			$("#currently-playing").show("fast", function() {		
				$('#left-col').animate({ marginLeft: '0'}, "normal", "easeout", function() {
					$('#right-col').fadeIn("normal");
				});
			});
		} else {
			$('#left-col').animate({ marginLeft: '0'}, "normal", "easeout", function() {
				$('#right-col').fadeIn("normal");
			});
		}
	}
}

function hideRightCol() {
	// IE 6 is touchy about it's left-margin value
	if( isIE6() )
		marginValue = "87px";
	else
		marginValue = "175px";
	
	$('#right-col').fadeOut("normal", function() {	
		$('#left-col').animate({ marginLeft: marginValue}, "normal", "easein", function() {
			// If we've got a currently playing song, we need to put the div in the left-col first
			if( CURRENT_SONG != "" ) {
				$("#currently-playing").fadeOut("normal", function() {
					$("#left-col").prepend( $("#currently-playing") );
					$("#currently-playing").fadeIn();
				});
			}
		});
	});
}

function updateVolume( bar_num ) {
	for( i=1; i<=5; i++ ) {
		// Change the opacity of the unused volume bars
		if( i <= bar_num )
			$("#vol" + i).removeClass("vol-fade");
		else {
			$("#vol" + i).addClass("vol-fade");
		}
	
	}
}

// -------------------------------------------------------------------
// Init Functions
// -------------------------------------------------------------------

function initPage(){
  setupForm();
  setupCtls();
  loadVolume();
  loadPlaylist();
  setupSortables();
  loadPassedQuery();
  preloadImages();
  initContent();
  setupGlobalKeyhooks();
}

function setupGlobalKeyhooks(){
   $(document).keydown( function(event){
     if( $(event.target).is("input") ){ return true; }

     // !isPlaying != isPaused because no song could be playing.
     // Thus, we have to have both of these variables.
     var isPlaying = $('#play').is('.ctl-button-active');
     var isPaused  = $('#pause').is('.ctl-button-active');

     switch( event.keyCode ){
	 	case 90: // Z (For Undo/Redo)
		  if( event.ctrlKey )
			undo();
			break;
        case 32: // Space
          if( isPlaying ){
            transparentMessage( "Paused" )			
			pauseSong();
		  }
		  else if( isPaused ){
            transparentMessage( "Playing" )
            resumeSong();
          }
          return false;
        case 39: // Right arrow
          if(playNext(true)){ transparentMessage( "Loading next song..." ) }
          return false;
        case 37: // Left arrow
          if(playPrev()){ transparentMessage( "Loading previous song..." ) }
          return false;
        case 38: // Left arrow
          if(rewindSong()){ transparentMessage( "Reloading song..." ) }
          return false;		  
     }
     return true;
   })
}

function setupSortables(){
 $('#playlist').Sortable(
    {
	  accept : 'song',
 	  helperclass : 'sorthelper',
      handle: "img.grip",
      opacity: 	0.5,
      axis: 'vertically',
	  fit :	false,
	  onChange: savePlaylist	
	  }
  )
}

function loadPassedQuery(){
  qs = location.search.substring(1);

  if( qs && qs.length > 0 ) {
  	param = qs.split("=")[0];
	  paramValue = qs.split("=")[1]
  
	  switch( param ) {
		case 'z':
			songID = paramValue;
			if ( songID != undefined ){
				  showPlayer();
			      setSound( songID );
			}
			break;
		case 'q':
			searchTerm = unescape(paramValue.replace("+", " "));
			$("input#query").val( searchTerm );
			doSearch();
			break;
	  }
	}
  
}

function loadVolume() {
	vol = $.cookie( "volume" );
	if( vol && vol.length > 0 ) {
		CURRENT_VOLUME = vol;
	} else {
		CURRENT_VOLUME = 80;
	}
	
	updateVolume( (CURRENT_VOLUME / 100) * 5 );
}


// -------------------------------------------------------------------
// Interface Functions
// -------------------------------------------------------------------

function addPieMenus(){
  $("#results a div").flower({ click: flowerInfo.searchResultHandler,
                           indicate: flowerInfo.shelves,
                           image: "/images/flower_main.png",
                           leave: flowerInfo.leave,
    					   clickstyle: "song-click"
						});

  $("#playlist .song div").flower({ click: flowerInfo.playlistHandler,
                                indicate: flowerInfo.shelves,
                                image: "/images/flower_alt.gif",
                                leave: flowerInfo.leave,
								clickstyle: "song-click"
						});

}

function setupCtls() {
	$('#play a').click( resumeSong );
	$('#rewind a').click( rewindSong );
	$('#pause a').bind( 'click', function() { pauseSong(); } );
	$('#ctl-progress-loaded').bind( 'click', function(event) { scrubSong(event) } );
	$('#ctl-volume').bind( 'click', function(event) { setVolume(event) } );
}

function rateSong( target, rating, showMessage ){
	songID = youtubeId(target);
	
	$.post('/rate', {sid: songID, r: rating}, function() {
		// If the song is bad, fade it out of the search results
		//alert(rating);// 1 = good ; 0 = bad
		if( !rating ){
	      msg = "The song has been marked as a <b>bad</b> recording.<br/>";
	      msg += "<span style='font-size:85%;'>It'll appear <b>lower</b> in searches.</span>";
	
	      removeSongOption( target, false );
	
		  // If this is the current song, stop playing
		  if( CURRENT_SONG == songID ) stopSong();
		
        }
		// If it's good, turn it slightly green to show that it's 
		else{
	      msg = "The song has been marked as a <b>good</b> recording.<br/>";
	      msg += "<span style='font-size:85%;'>It'll appear <b>higher</b> in searches!</span>";			
        //$(target).addClass('good-song');
	  	  }
	
	 if( showMessage )
     	transparentMessage( msg );
	});
  return true;
}

function linkToSong( songID ){
  $("#player").css("visibility", "hidden");
  tb_show( "Here's the link for this song:",
           "link?sid=" + songID + "&"
           + "keepThis=true&TB_iframe=true&height=50&width=550")
}

function addToPlaylistOption( target ){
  songID = youtubeId( target );
  addSongToPlaylist( songID, $(target).text() );
  rateSong( target, 1, false );
  savePlaylist();
}

function removeSongOption( target, undo ){
   // Hide the newly deleted to-do item.
   $(target).slideUp("normal", function() {
		// Setup undoable item
		if( undo )
			recordUndoable( target );
   });

   // If this is the last option, hide the playlist and move the search box
   hash = $.cookie( "playlist");
   if( !hash || hash.length == 0 ) {
	 hideRightCol();
   }
}

function sendToFriend( target ){
  $("#player").css("visibility", "hidden");
  tb_show( "Send this song to a friend!",
           "/friend?"
		   + "title="+ escape($(target).text()) + "&"
		   + "url=" + "http://www.froogel.info/listen?sid=" + youtubeId(target) + "&"
           + "keepThis=true&TB_iframe=true&height=345&width=420")

}

function sentEmail( result ) {
	tb_remove();
	if( result )
		transparentMessage('Thanks, the song has been sent to your friend.');
	else
		transparentMessage('Sorry, there was a problem sending this song to your friend.');
}

function embedSong( target ){
  $("#player").css("visibility", "hidden");
  tb_show( "Add Froogel to your website!",
           "/embed" + "?"
		   + "title="+ escape($(target).text()) + "&"
		   + "id=" + youtubeId(target) + "&"
           + "keepThis=true&TB_iframe=true&height=395&width=420")

}
function myspaceProfile( target ){
  $("#player").css("visibility", "hidden");
  tb_show( "Add Froogel to your MySpace Profile!",
           "/myspace" + "?"
		   + "title="+ escape($(target).text()) + "&"
		   + "id=" + youtubeId(target) + "&"
           + "keepThis=true&TB_iframe=true&height=395&width=420")

}
function watchVideo( songID ) {
	pauseSong();
	window.open("http://www.youtube.com?v=" + songID );
}


function addSongToPlaylist( songId, songTitle ){
  // Add the playlist item
  addPlaylistItem( songId, songTitle );

  // Show the right-col if necessary
  showRightCol();

  // If this song is the currently playing song, reset the play marker
  if( songId == CURRENT_SONG )
	setPlayMarker( $('#playlist #' + songId ) );
	
}

function addPlaylistItem( songId, songTitle ) {
	// Does this already exist in the playlist?
	if( $('#playlist li#' + songId).is("li") ) {
		li = $('#playlist li#' + songId);
	} else {
		li = document.createElement("li");
		li.id = songId;
		li.className = "song";
		$(li).hover( function(){$(this).addClass("hover");}, function(){$(this).removeClass("hover"); });
		div = document.createElement("div");
		div.className = "song-title";
		$(div).html( songTitle );
		$(li).prepend( "<img src='/images/grip.gif' class='grip'/>" );
		$(li).prepend( div );
		try{$('#playlist').SortableAddItem(li);} catch(err){}
	}


	// Try to insert after the currently playing item, if applicable
	currently_playing = $('#playlist div#play-marker');
	if( currently_playing.is(':visible') ) {
		currently_playing.parent().after(li);
	} else {
		$('#playlist').append(li);
	}

	addPieMenus();
}


// -------------------------------------------------------------------
// Search Functions
// -------------------------------------------------------------------

function getMovies( query ){
	
  rubric = function(obj){
    if(obj['url'] != "") {
		return true;
	}
  }

  populate = function( soundLinks ){
    hideLoading();
    for( var i=0; i<soundLinks.length; i++ ){
      a = document.createElement("a");
	  div = document.createElement("div");
      a.value = soundLinks[i]['id'];
      $(a).addClass( "song" );
	  $(div).html( soundLinks[i]['title'] );
	  $(div).addClass( "song-title" );
	  $(a).prepend( div );
      $("div#results").append(a);
    }

    if(soundLinks.length == 0){
      div = document.createElement("div");
      div.id = "no-results";
      $(div).html( "no songs found" );
      $("div#results").append(div);
      $("#instructions").hide();
    }else{
      $("#instructions").fadeTo("slow", 1.0);
    }
	
    addPieMenus();
  }

  $("div#results")[0].innerHTML = "";
  useFoundLinks( '/find.php', query, rubric, populate );
}

// -------------------------------------------------------------------
// Form Functions 
// -------------------------------------------------------------------

//var DEFAULT = "band/song name";
var DEFAULT = "";

function showLoading(){
  $("div#results").hide()
  $("#loading-results").fadeIn("1500");
}

function hideLoading(){
  $("#loading-results").fadeOut( "normal",
  function(){$("div#results").fadeIn("fast");}  );
}

function doKey( event ){
  if( event.keyCode == 13 ) doSearch();
}

function doSearch(){
  var search = $("input#query")[0].value;

  if( trim(search) != "") {
	
	  // Show search results if necessary
	  if( $('#search-results').is(':hidden') ) {
		$('#search-results').fadeIn(500);
	  }
	
	  showLoading(); 
	  getMovies(search);

	  // Update search header
	  $("#search-title").text("search results:");
	  
	  
  }
}

function setupForm(){
  $("input#submit").click(doSearch);
  $("input#query").keydown(doKey);
}

function initContent() {
	// First off, do we have a playlist?
	hash = $.cookie( "playlist");
	if( hash != undefined && hash.length > 0 ) {
		// Change position of search box
		$('#left-col').css('margin-left', '0');
		
		// Show did-you-know
		$('#tips #know-box').show();
		
		// Show the playlist
		$('#right-col').show();	
	
		// Unhide content
		if( $('#content').is(':hidden') ) {
			$('#content').fadeIn(500);
		}
	}
	
	// Show the top played list
	loadMostPlayed();
	
	// Show the tips box
	$('#tips').show();
	
	// Attach undo command to the undo link
	$("#undo").click(undo);

  $("#about").click(showAboutPage);
}

// -------------------------------------------------------------------
// Stats Functions 
// -------------------------------------------------------------------

function updateStats( songID, type ){
  $.post( '/a/stats', {z:songID, t:type} );
}

function loadMostPlayed(){
  // Fix for IE caching problem
  var date = new Date();
  var timestamp = date.getTime();
  $.getJSON('/json_return.php', {time: timestamp}, function(json) {
	// Create the top songs links
	songs = json['songs'];

	for(i=0; i<songs.length; i++) {
		if( songs[i] != null ) {
			id = songs[i]['id'];
			title = songs[i]['title'];
			li = document.createElement("li");
			div = document.createElement("div");
		    $(li).attr("id", id).addClass( "song" );
		    $(div).html( title );
		 	$(div).addClass( "song-title" );
		    $(li).prepend( div );
	        $(div).flower({ click: flowerInfo.searchResultHandler,
		                          indicate: flowerInfo.shelves,
		                          image: "/images/flower_main.png",
		                          leave: flowerInfo.leave,
								  clickstyle: "song-click"
		     				});
		    $("#top-results").append(li);
		}
	}
	
	// Update the total number of songs played
	$("#num_played").text( addCommas( json['total'] ) ); 
  });
}

// -------------------------------------------------------------------
// Player Functions 
// -------------------------------------------------------------------

// Used to capture space bar event, to control player
/*if( document.captureEvents && Event.KEYUP ) {
  document.captureEvents( Event.KEYUP );
}
document.onkeyup = playerListener;*/

function loadPlayer(fil,id,str,stt) {
	
	var so = new SWFObject('mediaplayer.swf','mediaplayer','722','20','7');
	so.addParam("allowfullscreen","false");
	so.addVariable("file",fil);
	so.addVariable("start",stt);
	so.addVariable("autostart","true");
	so.addVariable("usefullscreen","false");
	so.addVariable("displayheight","0");	
	so.addVariable("lightcolor", "0xCC0000");
	so.addVariable("enablejs", "true");
	so.addVariable("showfsbutton", "false");
	so.addVariable("javascriptid", "mediaplayer");
	so.addVariable("volume", CURRENT_VOLUME);
	
	if(id != '') { 
		so.addVariable("id",id); 
	} else {
		so.addVariable("type","flv");
	}
	if(str != '') { 
		so.addVariable("streamscript",str); 
	}
	so.write('player');
};

// Move to the next playlist song when current song finishes playing
function getUpdate(type, pr1, pr2) {
  if( type == "load" ) {
	PERCENT_LOADED = pr1;
	updateProgressLoaded( PERCENT_LOADED );
  }
  if( type == "time" ) {
	TIME_ELAPSED = pr1;
		
	// Some time totals do not appear. If we have a total, let's show it. If not, don't.
	if(TIME_TOTAL == null && pr2 != "" && pr2 != "0" ) {
		TIME_TOTAL = pr2;
		hidePlayerIndicatorLoading();
		updatePlayerIndicator('N/A');
	}
	
	// If we dont' have a time total, just display the time elapsed
	if(TIME_TOTAL == null) {
		updateProgessPlayed( (TIME_ELAPSED / 100) * 100 );
		updatePlayerIndicator(strToTime(TIME_ELAPSED));
	} else {
		updateProgressPlayed( (TIME_ELAPSED / TIME_TOTAL) * 100 );
		updatePlayerIndicator(strToTime(TIME_ELAPSED) + " / " + strToTime(TIME_TOTAL));
	}
	
  }	
  if( type == "state" ){
    CURRENT_STATE = pr1;

	if(CURRENT_STATE == "1") {
		// Update the indicator
		if( PREVIOUS_STATE != "2") {
			showPlayerIndicatorLoading();
		}
		
	}
	if(CURRENT_STATE == "2") {
		KILL_SONG = false;
		if(PREVIOUS_STATE == "1") {
			updatePlayerStatus('Now Playing');
		}
	}
	if(CURRENT_STATE == "3" && PREVIOUS_STATE != "2") KILL_SONG = true;
	
    if( CURRENT_STATE == "0" && TIME_ELAPSED == "0" && PERCENT_LOADED == "100" ){
	  stopSong();
      playNext();
    }

	// Set the previous state
	PREVIOUS_STATE = CURRENT_STATE;
	
  }
};

function notifyPlayer(cmd, param1) {
  mediaPlayer = thisMovie('mediaplayer');
  if( mediaPlayer != undefined ) mediaPlayer.sendEvent(cmd, param1);
}

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

function setPlayMarker(el){
  id = "play-marker";
  html =  '<div style="position:absolute;" id="%s">'.replace( "%s", id );
  html += '<img src="/images/play.gif"/ style="position:relative;left:-5x;">';
  html += '</div>';
  
  $("#"+id).remove()
  $(el).prepend( html );
  return true;

}

function _playItem( nextItem, message ){
  if( nextItem.length ){
	id = youtubeId( nextItem );//nextItem.attr("id");
	// IDs only seem to be present in the playlist
	// If it's not a playlist song, let's just stop and let the user decide what to do
	if(id && id.length) {
	    setSound( id )
	    setPlayMarker( $(nextItem) );
	    return true;
	}
  }	
  return false;
}

function playNext(override){
  // Only continuously play songs from the playlist and top played list
  if( !PLAYING_NEXT && ( $("#play-marker").parent().is("li") || override ) ) {
	PLAYING_NEXT = true;
	
	// Only play the next visible item
	nextItem = $("#play-marker").parent().next();
	while( nextItem && nextItem.length > 0 ) {
		if( $(nextItem).is(':visible') )
			return _playItem( nextItem );
		else {
			nextItem = $(nextItem).next();
		}
	} 
	
  } else {
	// Indicate that the last song was finished playing
	updatePlayerStatus('Last Played');
	return false;
  }
}

function playPrev(){
	// Only play the previous item if it's visible
	prevItem = $("#play-marker").parent().prev();
	while( prevItem && prevItem.length > 0 ) {
		if( $(prevItem).is(':visible') )
			return _playItem( prevItem );
		else {
			prevItem = $(prevItem).prev();
		}
	}
}


function killSong() {
  if(KILL_SONG) {
	  stopSong();
	  showDeadSong();
	  updateStats( CURRENT_SONG, 'fail' );
	  playNext();
  }
}

function showDeadSong() {
	updatePlayerStatus('Failed To Load', true);
	//$('#song-name').parent().css('background', 'transparent url(/images/sad_face.png) center center no-repeat');
}

function loadSong(url, title, songID) {
  // Show the currently playing song
  showCurrentlyPlaying( songID, title );	

  // Reset the player variables
  resetPlayerVars();

  // Set the KILL_SONG switch
  KILL_SONG = true;

  // If the song is not stopped, stop it first
  loadPlayer(url, '', '', 0);

  // Update Song Name
  updateSongName(title);
  updatePlayerStatus('Loading');

  // Update play button
  updatePlayButton('play');

  // Show the player controls
  $("#player-ctls").css('visibility', 'visible');

}

function setSound( songID ){
  $.get('/getpath.php', {v: songID}, function(data) {
	var JSONFile = "songDetails = " + data;  // example of what is received from the server.
	eval(JSONFile); // Execute the javascript code contained in JSONFile.
	
	title = songDetails.title;
	VideoURL =  songDetails.VideoURL;
	code =  songDetails.t;
	flv = "http://youtube.com/get_video?video_id=" + songID + "%26t=" + code;

    loadSong(flv, title, songID);
  });
}

function showPlayer() {
	if( $('#player-wrap').is(':hidden') ){
		$('#footer').css('paddingBottom', '50px');
		$('#player-wrap').slideDown("slow");
  }
}

function playerListener(e) {
  if( !e ) {
    //if the browser did not pass the event information to the
    //function, we will have to obtain it from the event register
    if( window.event ) {
      //Internet Explorer
      e = window.event;
    } else {
      //total failure, we have no way of referencing the event
      return;
    }
  }
  if( typeof( e.keyCode ) == 'number'  ) {
    //DOM
    e = e.keyCode;
  } else if( typeof( e.which ) == 'number' ) {
    //NS 4 compatible
    e = e.which;
  } else if( typeof( e.charCode ) == 'number'  ) {
    //also NS 6+, Mozilla 0.9+
    e = e.charCode;
  } else {
    //total failure, we have no way of obtaining the key code
    return;
  }

  // Toggle the song if it's the space bar
  if( e == 32 ) {}
	//alert(window.focus());

}

// -------------------------------------------------------------------
// Playlist saving
// -------------------------------------------------------------------

var DELIMITER = "<||>";

function savePlaylist(){
  songs = $("#playlist li");
  hash = "";
  for( var i=0; i<songs.length; i++ ){
	song = songs[i];
	songID = song.id;
	title = $(song).text();
	
	// Only save visible songs (used for hidden Undo items)
	if( $(song).is(":visible") ) {
    	hash += songID + DELIMITER;
    	hash += title + DELIMITER;
	}
  }
  
  $.cookie( "playlist", hash, {expires:365} );
}

function loadPlaylist(){
  hash = $.cookie( "playlist");
  if( !hash || hash.length == 0 ) return;

  tokens = hash.split( DELIMITER );
  for( var i=0; i<tokens.length-1; i+=2 ){
    songId = tokens[i];
    songTitle = tokens[i+1];
    addPlaylistItem( songId, songTitle );
  }
}

// -------------------------------------------------------------------
// Undo/Redo
// -------------------------------------------------------------------

var EVENT_QUEUE = [];
var UNDO_DISPLAY_WAIT = 300;

function undo() {
	// Get the last to-do item added to the event queue and un-hide it.
	$( "#playlist #" + EVENT_QUEUE.pop() ).slideDown();
	updateUndoLink();
	savePlaylist();
}

function recordUndoable( target ) {	
	// Add the to-do item to the event queue.
	EVENT_QUEUE.push( $(target).attr("id") );
	updateUndoLink();
	savePlaylist();
}

function updateUndoLink() {
	// If there are no items that are undoable, hide the undo link.
    if( EVENT_QUEUE.length == 0 ){
      setTimeout( '$("#undo").fadeOut();', UNDO_DISPLAY_WAIT )
    }
    // If there are any items that are undoable, show the undo link.
    else if( EVENT_QUEUE.length == 1 ){
      $("#levels").text( "" );

      // Only do the fade in if the undo link is currently hidden.
      if( $("#undo").css("display") == "none" ){
        setTimeout( '$("#undo").fadeIn()', UNDO_DISPLAY_WAIT );
      }
    }
    // If there is more than one thing that can be undone, then let the user
    // know how many levels of undo there are.
    else if( EVENT_QUEUE.length > 1 ){
      $("#levels").text( "("+EVENT_QUEUE.length+")" );
    }
}

// -------------------------------------------------------------------
// Utilities
// -------------------------------------------------------------------

function useFoundLinks( url, query, func, callback ){
   $.getJSON(url, {q: query}, function(json) {
	pageLinks = [];
		for(i=0;i<json.length;i++){
			if ( func(json[i]) ){
            	pageLinks.push( json[i] );
          	}
        }
        callback( pageLinks );
	});
}

function strToTime(total_secs) {
	sec = Math.round(total_secs % 60);
	if(sec < 10) sec = "0" + sec;
	min = Math.floor(total_secs / 60);
	
	return min + ":" + sec;
}

function youtubeId( target ){
  if ( $(target).attr("id") == undefined ) return $(target).attr("value");
  return $(target).attr("id");
}

function trim( string ) {
	return string.replace(/^\s+|\s+$/g,"");
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function preloadImages() {
	if (document.images) {
		url_prefix = "http://" + location.hostname + "/images/";
		
		image1 = new Image();
		image1.src = url_prefix + "flower_main.png";
		image2 = new Image();
		image2.src = url_prefix + "flower_alt.gif";
		image3 = new Image();
		image3.src = url_prefix + "yes.png";
		image4 = new Image();
		image4.src = url_prefix + "no.png";
		image5 = new Image();
		image5.src = url_prefix + "bg_ctls.png";
		image6 = new Image();
		image6.src = url_prefix + "button_play.png";
		image7 = new Image();
		image7.src = url_prefix + "button_pause.png";
		image8 = new Image();
		image8.src = url_prefix + "play.gif";
		image9 = new Image();
		image9.src = url_prefix + "trans.gif";
		image10 = new Image();
		image10.src = url_prefix + "grip.gif";
	}
}

function showAboutPage(){
  if( CURRENT_STATE > 0 ){
    $(this).attr( "target", "_new" ).attr( "href", "about#playing" );
  } else {
    $(this).attr( "target", "" ).attr( "href", "about" );
  }
}

function isIE6() {
	if( $.browser.msie && $.browser.version == "6.0" )
		return true;
	else
		return false;
}