var curPl = false;
var curPlayListTitle = false;
var curSort = false;
var curEditPrefix = false;
var curEditID = false;
var curEditString = false;
var ignoreLoadSongs = false;
var cancellingEdit = false;

function loadSongs(playlistID,scrollFlag){

    scrollFlag = typeof(scrollFlag) != 'undefined' ? scrollFlag : true;

//	alert(scrollFlag);

    if(ignoreLoadSongs == true){
        return false;
        //alert('test');
    }

   if(curPl == playlistID){
   
		$('songs_'+curPl).innerHTML = '';
		$('songs_'+curPl).style.display = 'none';
		if (comments=$('comments_'+curPl))
			comments.style.display = 'none'; // 5/7/9
      $('pl_'+curPl).removeClassName('on');
      $('pl_'+curPl).addClassName('off');
      curPl = false;

   }else{

		if(curPl != false){
			$('songs_'+curPl).innerHTML = '';
			$('songs_'+curPl).style.display = 'none';
			if (comments=$('comments_'+curPl))
				comments.style.display = 'none'; // 5/7/9
			
			$('pl_'+curPl).removeClassName('on');
			$('pl_'+curPl).addClassName('off');
		}
	
		curPl = playlistID;
		curSort = false;
		
		$('songs_'+curPl).update("<img src='/playlists/gfx/loading.gif' border='0'>");
		$('songs_'+curPl).setStyle({ display: 'block' });
		if (comments=$('comments_'+curPl))
			comments.style.display = 'block'; // 5/7/9
	
        if (scrollFlag == true){
            new Effect.ScrollTo('pl_'+curPl,{duration: .2, offset: -100});
        }
		new Ajax.Request('/playlists/ajax.php', {
			method: 'get',
			parameters: 'fuse=loadSongs&playlistID='+playlistID,
			onSuccess: function(t) {
				
				$('songs_'+curPl).update(t.responseText);
				$('pl_'+curPl).removeClassName('off');
				$('pl_'+curPl).addClassName('on');
				
				if($('sorting').value == 'on'){

					curSort = Sortable.create('songs_'+curPl,{ tag:'div', only:'slWrapper', 
						onUpdate: function(){
							new Ajax.Request('/playlists/ajax.php', { 
								method: 'get', 
								parameters: 'fuse=updatePlaylistOrder&playlistID='+curPl+'&'+Sortable.serialize('songs_'+curPl)
							});
						}
					});
				
				}
				
			}
		});
	}
			
}

function editPlaylistTitle(id){
   if(curPlayListTitle == false){
      curPlayListTitle = $('plTitle_'+id).innerHTML.split("'").join("&apos;").strip();
      $('plTitle_'+id).update("<form id='plTitleForm' action='javascript: savePlaylistTitle("+id+")'><input type='text' id='newPlaylistTitle' name='newPlaylistTitle' value='"+curPlayListTitle+"'> <input type='submit' value='SAVE' style='background: #F90909; color: white;'> <input type='button' onclick='javascript: cancelPlaylistTitleEdit("+id+");' value='CANCEL'></form>");
      $('newPlaylistTitle').focus();
   }
}

function savePlaylistTitle(id){
   curPlayListTitle = $('newPlaylistTitle').value;
   
	new Ajax.Request('/playlists/ajax.php', {
	  method: 'get',
	  parameters: 'fuse=savePlaylistTitle&playlistID=' + id + '&' + $('plTitleForm').serialize()
	});
   
   $('plTitle_'+id).update(curPlayListTitle);
   curPlayListTitle = false;
}

function cancelPlaylistTitleEdit(id){
   $('plTitle_'+id).update(curPlayListTitle);
   curPlayListTitle = false;
}

function removePlaylist(id){
   whereto = confirm('Are you sure you want to delete this playlist?');
   if(whereto == true){
		new Ajax.Request('/playlists/ajax.php', {
			method: 'get',
			parameters: 'fuse=removePlaylist&playlistID=' + id,
			onSuccess: function(t) {
				new Effect.Fade('pl_'+id, { 
					afterFinish: function(){
						$('pl_'+id).remove();
						$('songs_'+id).remove();
						curPl = false;
					}
				});
			}
		});
   }
}

function editInPlace(prefix,id){
   
   if(cancellingEdit == false){

		if(curEditPrefix != false && (curEditPrefix != prefix || id != curEditID)){
			cancelEditInPlace();
		}
		
	//   alert(curEditPrefix+' - '+prefix);
		
		if(curEditPrefix != prefix){
			curEditPrefix = prefix;
			curEditID = id;
			curEditString = $(curEditPrefix + '_' + curEditID).innerHTML.split("'").join("&apos;").strip();
			$(curEditPrefix+'_'+curEditID).innerHTML = "<form id='editInPlaceForm' action='javascript: saveEditInPlace()'><input type='text' id='newEditString' name='newEditString' value='" + curEditString + "' style='width: 90%;'> <input type='submit' value='SAVE' style='background: #F90909; color: white;'> <input type='button' onclick='javascript: cancelEditInPlace();' value='CANCEL'></form>";
		}

	}
   
   //reset the cancel edit
  	cancellingEdit = false;

}

function saveEditInPlace(){

	var cc = $('newEditString').value;

	var par = 'fuse=editInPlace&prefix=' + curEditPrefix + '&editID=' + curEditID + '&newEditString=' + cc;

   if(cc == ''){
   	alert('The field you are editing cannot be left blank, please try again.');
   }else{
		new Ajax.Request('/playlists/ajax.php', {
			method: 'get',
			parameters: par,
			onSuccess: function(t){
				//alert(t.responseText);
			}
		});
		$(curEditPrefix+'_'+curEditID).update(cc);
		if(curEditPrefix != 'playlistDesc'){
			buildAmazonLink(curEditID);
		}
		curEditPrefix = false;
		curEditID = false;
		curEditString = false;
   }
}

function buildAmazonLink(id){
	var title = $('songTitle_'+id).innerHTML;
	var artist = $('artistTitle_'+id).innerHTML;
	var album = $('albumTitle_'+id).innerHTML;
	new Ajax.Request('/playlists/ajax.php', {
		method: 'get',
		parameters: 'fuse=buildAmazonLink&title='+title+'&artist='+artist+'&album='+album,
		onSuccess: function(t){
			$('amazonLink_'+id).innerHTML = t.responseText;
		}
	});
}

function cancelEditInPlace(){
	
	cancellingEdit = true;

   $(curEditPrefix+'_'+curEditID).update(curEditString);
   curEditPrefix = false;
   curEditID = false;
   curEditString = false;
}

function removeSong(id,playlistID){
   var whereto = confirm('Are you sure you want to remove this song?');
   if(whereto == true){
   
      new Ajax.Request('/playlists/ajax.php', {
         method: 'get',
         parameters: 'fuse=removeSong&id='+id+'&playlistID='+playlistID,
         onSuccess: function(t){
            if(t.responseText.match(/Error/)){
               alert(t.responseText);
            }else{
               new Effect.Fade('sl_'+id, { 
                  afterFinish: function(){
                     $('sl_'+id).remove();
                     $('songCount_'+playlistID).update(t.responseText);
                  }
               });
            }
         }
      });
   
   }
}

function addSong(playlistID){
	new Ajax.Request('/playlists/ajax.php', {
		method: 'get',
		parameters: 'fuse=addSong&playlistID='+playlistID,
		onSuccess: function(t){
			curPl = false;
			loadSongs(playlistID);
		}
	});
}

function refreshPlaylists(){
   new Ajax.Request('/playlists/ajax.php', {
      method: 'get',
      parameters: 'fuse=refreshPlaylists',
      onSuccess: function(t){
         $('plCont').update(t.responseText);
      }
   });
}

function submitPlaylist(playlistID){

//   whereto = confirm('Are you sure you want to submit your playlist? If you have already submitted a playlist, the old submitted playlist will be replaced by this playlist. After it is submitted, you will not be able to make any changes to the playlist');
	// first we need to make sure this playlist has 10 songs exactly
	
	var validSongCount = 10;
	
	new Ajax.Request('/playlists/ajax.php', {
		method: 'get',
		parameters: 'fuse=getSongCount&playlistID='+playlistID,
		onSuccess: function(t){
			if(t.responseText != validSongCount){
				alert('You must have exactly '+validSongCount+' songs to enter this playlist. You currently have '+t.responseText+' songs.');
			}else{
				new Ajax.Request('/playlists/ajax.php', {
					method: 'get',
					parameters: 'fuse=submitPlaylist&playlistID='+playlistID,
					onSuccess: function(t){
						refreshPlaylists();
					}
				});
			}
		}
	});

}

function toggleFav(playlistID){
   new Ajax.Request('/playlists/ajax.php',{
      method: 'get',
      parameters: 'fuse=toggleFav&playlistID='+playlistID,
      onSuccess: function(t){
         $('fav_'+playlistID).update(t.responseText);
      }
   });
}

function playlistInit(){
   new Effect.Fade('plHelper', { duration: 0 });
}
   
function setHelperText(slug){

    new Effect.ScrollTo('plscrollhere',{duration: .2, offset: -100});

    var helpClosebox = "<a onclick=\"javascript: new Effect.Fade('plHelper');\"><font style='font-size: smaller'>[ exit help ]</font></a>";
    var helpOpen = "<div id='playlistHelper'>" + helpClosebox + "<BR>";
    var helpClose = helpClosebox + "</div>";


    if(slug == 'how'){
        
        var text = helpOpen + "<BR><font style='font-weight: bold'>Earwig: A playlist sharing gizmo.</font><BR><UL style='text-align: left;'><LI>Create a new playlist using iTunes, iMeem.com, or by manually typing in song titles and artists.<LI><B>You can edit song information by clicking on the name of the song, artist or album.</B><LI>You can change the order of the playlist by clicking and dragging the songs around.</UL><br><font style='font-weight: bold'>CONTEST RULES</font><br><UL style='text-align: left;'><LI>To submit your mix for the contest, select it in &quot;My Playlists,&quot; then click &quot;JUDGE ME&quot;.<LI>Each playlist entered for the contest must have <I>exactly</I> 10 songs. (Other playlists can have any number of songs.)<LI>You can share as many playlists as you want, but you can only submit one playlist at a time for the Earwig contest. (If you submit a second playlist, it will replace the first one.)</UL><BR><BR>" + helpClose;
        
    }
    
    if(slug == 'itunes'){
        var text = helpOpen + "<OL><LI>Create your playlist in iTunes.<BR><LI>Right-click or Ctrl-click on the playlist title to get a menu with <B>Export Song List&hellip;</B> on it. You can also <B>Export&hellip;</B> from the <B>File</B> drop-down menu.<BR><img src=\"/playlists/gfx/itunes1.gif\"><BR><LI>Be sure to choose <B>XML</B> format. Save your playlist.<img src=\"/playlists/gfx/itunes2.gif\"><BR><LI>Click the Browse&hellip; button below. Select your playlist file.<LI>Describe your mix in the Description blank. This is <B>required</B> for Earwig competitors!</OL>" + helpClose;
    }

    if(slug == 'imeem'){
    
        var text = helpOpen + "<OL><LI>Create your playlist on <a href=\"http://www.imeem.com/createmusicplaylist/\">iMeem.com.</a><BR><img src=\"/playlists/gfx/imeem1.gif\"><BR><LI>Click on <B>View Playlist</B> to get to your playlist page.<BR><LI>Click on <B>Share</B>, then <B>Link to or embed this music playlist</B>. Copy the link (not the embed code) at the bottom of the Share box and paste it into the form below.<BR><img src=\"/playlists/gfx/imeem2.gif\"><LI>Describe your mix in the Description blank. This is <B>required</B> for Earwig competitors!</OL>" + helpClose;
    }

    if(slug == 'muxtape'){
    
        var text = helpOpen + "<OL><LI>Create your playlist on <a href=\"http://muxtape.com\">Muxtape.com.</a><BR><img src=\"/playlists/gfx/muxtape1.gif\"><BR><LI>Copy the URL from your browser's address bar and paste into the form below.<BR><img src=\"/playlists/gfx/muxtape2.gif\"><LI>The import will put your Muxtape caption in the Description blank. You can edit it later if you want. Description is <B>required</B> for Earwig competitors!</OL>" + helpClose;
    }


    if(slug == 'typeit'){
    
        var text = helpOpen + "<OL><LI>Fill in a Title for your playlist<BR><LI>Describe your mix in the Description blank. This is <B>required</B> for Earwig competitors!<BR><LI>Click <B>Save Playlist</B><BR><LI>On the next screen, click your Playlist's title. You can edit the starter Untitled Song by clicking on each element to edit it. Add new songs by clicking <B>Add Song</B></OL>" + helpClose;
    }


    
    $('plHelper').update(text);
    
}

Event.observe(window, 'load', function() {
   playlistInit();
});

