var USER_LOGGED_IN = false;
var CONTROLLER_WIDTH = 520;
var VIEWER_LOADED = false;
var LAST_ID = -1;
var LC = generateLine();
var playlistajax = null;
var sortajax = null;
var waitvideoloadinterval;
var scroll_timeout = -1;
var MIN_SCROLL_HEIGHT;
var SEARCH_TYPE_SELECT;
var CURRENT_PLAYLIST;
var DO_SCROLL = true;
var ResultArray = new Array();

function scrollit(){
  var scroll = $(window).getScroll();
  var diff = scroll.y - MIN_SCROLL_HEIGHT;
  var height = $('slider').getCoordinates().height;
  if( diff < 0 ) diff = 0;
  if( diff > $('searchtable').getCoordinates().height - height ) diff = $('searchtable').getCoordinates().height - height;
  var fx = new Fx.Morph( $('slider'), {duration: 1000, transition: Fx.Transitions.linear });
  fx.start({ 'top': diff });
}

function init(){
  $('slider_toggle').addEvent('click', function(){
    if( DO_SCROLL ){
      DO_SCROLL = false; $('slider_toggle').innerHTML = "Start Scroll";
    }else{
      DO_SCROLL = true; $('slider_toggle').innerHTML = "Stop Scroll";
    }
  });

  MIN_SCROLL_HEIGHT = $('searchtable').getCoordinates().top;
  window.onscroll = function(){
    clearTimeout( scroll_timeout );
    if( ! DO_SCROLL  ) return;
    scroll_timeout = setTimeout( "scrollit()", 1000 );
  }
  SEARCH_TYPE_SELECT = new elSelect( {container : 'search_query_type_container', baseClass: 'elSelect2' } );
}

function loadPipes(){
  var flashvars = {};
  var params = { wmode: "transparent", allowScriptAccess:"always" };
  attributes = { id: "yahoopipes1", name: "yahoopipes1" }
  swfobject.embedSWF( statichost + "/swf/YahooPipes.swf", "yahoopipes", "1", "1", "9.0.0", null, flashvars, params, attributes);
}

/*************************************************
* Music Search
*************************************************/
function doSearch(){
  var query = trim( $('search_query').value );
  if( query == '' || query.length == 0 ) return;
  query = query.replace("/", "%252F" );
  var searchtype = $('search_query_type').value;
  var cookie = new Hash.Cookie('searchoptions', {duration:1, domain: 'flashwidgetz.com', path: '/'} );
  if( searchtype == 'all' ){
    cookie.set('searchtype', searchtype );
  }else if( searchtype == 'mp3' ){
    cookie.set('searchtype', searchtype );
  }else if( searchtype == 'video' ){
    cookie.set('searchtype', searchtype );
  }
  if( searchtype == 'all' ){
    document.location.href = "/musicsearch/" + encodeURIComponent( query );
  }else if(  searchtype == 'mp3' ){
    document.location.href = "/musicsearch/mp3/" + encodeURIComponent( query );
  }else if(  searchtype == 'video' ){
    document.location.href = "/musicsearch/video/" + encodeURIComponent( query );
  }
}

function loadSearchType( searchtype ){
  if( searchtype == null || searchtype == '' ) return;
  else{
    SEARCH_TYPE_SELECT.select( searchtype );
    if( searchtype == 'video' ){
      GLOBALSEARCHTYPE.select('video');
    }else{
      GLOBALSEARCHTYPE.select('music');
    }
  }
}

function videoSearch(){
  var html = '<div style="padding-top:50px;" align="center"><img src="'+ statichost + '/images/common/indicator_blue_large.gif"></div>';
  $('loader').innerHTML = html;
  var query = $('search_query').value;
  waitvideoloadinterval = setInterval( "initSearchVideo('"+query+"')", 1000 );
}

function initSearchVideo( query ){
  var isIE = navigator.appName.indexOf("Microsoft") != -1;
  var yahoopipes = (isIE) ? window["yahoopipes1"] : document["yahoopipes1"];
  if( typeof(yahoopipes) == 'undefined' || typeof(yahoopipes.getPipe) == 'undefined'){
  }else{
    clearInterval( waitvideoloadinterval );
    doVideoSearch( query );
  }
}

function doVideoSearch( query ){
  var isIE = navigator.appName.indexOf("Microsoft") != -1;
  var yahoopipes = (isIE) ? window["yahoopipes1"] : document["yahoopipes1"];
  if( typeof(yahoopipes) == 'undefined' || typeof(yahoopipes.getPipe) == 'undefined'   ){
    dialogAlertTimeout('The page is still loading. Please try again in a second', '2000' );
    return;
  }
  var uri = "http://pipes.yahooapis.com/pipes/pipe.run?_id=jpG_8KB_3RGNGO1Epl8axw&_render=json&max-results=50&query="+
            encodeURIComponent(query)+"&start-index=1&format=5";

  var callback = "showMusicVideoResults";
  yahoopipes.getPipe( uri, callback );
}

function generateRow( VideoArray, a ){
  var ftitle = fix4param( VideoArray[a].title );
  var furl   = fix4param( VideoArray[a].link );
  var title  = VideoArray[a].title;

  var html = '<tr>' +
             ' <td class="actions">'+
             '   <a href="#" class="playbutton" id="p' + a + '" onclick="return false">' +
             '   <img src="' + statichost + '/images/createwidget/play_button.gif"></a><br>' +
             '   <a href="#" class="addbutton" id="a' + a + '" onclick="return false"> ' +
             '   <img src="' + statichost + '/images/createwidget/add_button.gif"></a>' +
             ' </td>' +
             ' <td class="image">'+
             '   <img height="60" src="'+ VideoArray[a].thumbnail1+ '">'+
             ' </td>'+
             ' <td class="description">' +
             '   <div class="title">' + title + '</div>' +
             '   <div class="newblue url">' + VideoArray[a].link + '</div>' +
             '   <div class="buttons">' +
             '     <a class="ringtone" id="r' + a + '" href="#"><u>Get Ringtone</u></a> &nbsp;&nbsp;&nbsp;' +
             '     <a class="share" id="s' + a + '" href="#"><u>Share</u></a> &nbsp;&nbsp;&nbsp;' +
             '     <a class="itunes" id="i' + a + '" href="#"><u>iTunes</u></a>' +
             '   </div>' +
             '   <div id="controller' + a + '"></div>' +
             ' </td>' +
             '</tr>';
  return html;
}

function showMusicVideoResults( jsont, code ){
  CONTROLLER_WIDTH = 490;

  var header = '<table class="search_result_table" width="100%" cellpadding="0" cellspacing="0">';
  var footer = '</table>';

  if( code == "true" ){
    var json = eval( '(' + jsont + ')' );
    var videos = json.value.items;
    var VideoArray = parseYoutubeVideoResult( videos );

    var html1 = '';
    var html2 = '';
    var showindex = 2 + parseInt(Math.random() * 3);


    for( var a = 0; VideoArray != null && a < VideoArray.length; a++ ){

      ResultArray[a] = new Object();
      ResultArray[a].title = VideoArray[a].title;
      ResultArray[a].url   = VideoArray[a].link;
      if( a < showindex ){
        html1 += generateRow( VideoArray, a );
      }else{
        html2 += generateRow( VideoArray, a );
      }
    }
    $('loader').innerHTML = '';

    if( VideoArray == null || VideoArray.length == 0 ){
      var html = '<tr><td style="padding-top:20px;padding-bottom:20px;text-align:center">';
      html += 'No results to display';
      html += '</tr></tr>';
      $('video_results_1').innerHTML = header + html + footer;
    }else{
      $('video_results_1').innerHTML = header + html1 + footer;
      $('video_results_2').innerHTML = header + html2 + footer;
      loadbuttons();
    }
  }else{
    var html = '<tr><td style="padding-top:20px;padding-bottom:20px;text-align:center">';
    html += 'Problem getting results';
    html += '</tr></tr>';
    $('loader').innerHTML = '';
    $('video_results_1').innerHTML = header + html + footer;
  }
}

function loadbuttons(){
  $$('.playbutton').each( function(el){
    var index = parseInt( el.id.substring(1, el.id.length) );
    el.src = statichost + '/images/mediaconsole/simple_play_button.gif';
    el.addEvent( 'mouseover', function(){ this.src = statichost + '/images/mediaconsole/simple_play_button_sel.gif'; } );
    el.addEvent( 'mouseout', function(){ this.src = statichost + '/images/mediaconsole/simple_play_button.gif'; } );
    el.addEvent( 'click', function( number ){  testSong( number ); return false; }.pass( index ) );
  });

  $$('.addbutton').each( function(el){
    var index = parseInt( el.id.substring(1, el.id.length) );
    el.src = statichost + '/images/mediaconsole/simple_add_button.gif';
    el.addEvent( 'mouseover', function(){ this.src = statichost + '/images/mediaconsole/simple_add_button_sel.gif'; } );
    el.addEvent( 'mouseout', function(){ this.src = statichost + '/images/mediaconsole/simple_add_button.gif'; } );
    el.addEvent( 'click', function( number ){ addSong( number ); return false; }.pass( index ) );
  });

  $$('.ringtone').each( function(el){
    var index = parseInt( el.id.substring(1, el.id.length) );
    var title = ResultArray[index].title;
    title = title.replace(/&quot;/g, "\"");

    var artist = title;
    var name = "";
    if( title.indexOf("-") != -1 ){
      artist = trim( title.substr(0, title.indexOf("-") ) );
      name = trim( title.substr( title.indexOf("-")+1, title.length ) );
    }
    var ringtone_artist = artist.replace(/\'/g, "").replace(/\"/g, "");
    var ringtone_name   = name.replace(/\'/g, "").replace(/\"/g, "");
    el.href = "http://offers.thumbplay.com/offers/Open_Artist_6843/atb3?" +
              "thpartist="+encodeURIComponent(ringtone_artist).replace( /%26amp%3B/g, '%26') +
              "&thptitle="+encodeURIComponent(ringtone_name).replace( /%26amp%3B/g, '%26') +
              "&thpcampid=widget-search";
    el.target = "_blank";
  });

  $$('.share').each( function(el){
    var index = parseInt( el.id.substring(1, el.id.length) );
    var params = new Object();
    params.title = ResultArray[index].title;
    params.url   = ResultArray[index].url;
    el.addEvent("click", function(p) {   
       openShareDiv( p.title, p.url );
       return false;
    }.pass( params ) );
  });

  $$('.itunes').each( function(el){
    var index = parseInt( el.id.substring(1, el.id.length) );
    var title = ResultArray[index].title;
    title = title.replace(/&quot;/g, "\"");
    title = title.replace(/&amp;/g, "&");

    var artist = title;
    var name = "";
    if( title.indexOf("-") != -1 ){
      artist = trim( title.substr(0, title.indexOf("-") ) );
      name = trim( title.substr( title.indexOf("-")+1, title.length ) );
    }
    var ringtone_artist = artist.replace(/\'/g, "").replace(/\"/g, "");
    var ringtone_name   = name.replace(/\'/g, "").replace(/\"/g, "");
    el.href = "http://phobos.apple.com/WebObjects/MZSearch.woa/wa/advancedSearchResults?" +
              "songTerm=" + encodeURIComponent(ringtone_name).replace( /%26amp%3B/g, '%26') +
              "&artistTerm=" + encodeURIComponent(ringtone_artist).replace( /%26amp%3B/g, '%26');
    el.target = "_blank";
  });
}



/*************************************************
* Song Testing
*************************************************/
function testSong( ID ){
  if( VIEWER_LOADED == false ){
    var videoswf = '<embed src="' + statichost + '/swf/Viewer.swf?lc=' + LC + '" quality="high" bgcolor="#000000" '+
                   '        width="250" height="200" name="Viewer" align="middle" allowScriptAccess="always" '+
                   '        allowFullScreen="false" type="application/x-shockwave-flash" '+
                   '        pluginspage="http://www.macromedia.com/go/getflashplayer" />';
    $('viewer_container').innerHTML = videoswf;
    VIEWER_LOADED = true;
  }
  if( LAST_ID != -1 ){
    $('controller'+LAST_ID).innerHTML = "";
  }
  $('playlist_controller').innerHTML = "";
  LAST_ID = ID;
  var controllerswf = '<embed src="' + statichost + '/swf/Controller.swf?url='+ encodeURIComponent( ResultArray[ID].url ) +'&lc=' + LC + '" ' +
                      '        quality="high" wmode="transparent" bgcolor="#000000" '+
                      '        width="' + CONTROLLER_WIDTH + '" height="15" name="Controller" align="middle" allowScriptAccess="always" '+
                      '        allowFullScreen="false" type="application/x-shockwave-flash" '+
                      '        pluginspage="http://www.macromedia.com/go/getflashplayer" />';

  $('controller'+ID).innerHTML = controllerswf;
}

function playSong( ID ){
  if( CURRENT_PLAYLIST == null || CURRENT_PLAYLIST.songs == null || CURRENT_PLAYLIST.songs[ID] == null ) return;
  if( VIEWER_LOADED == false ){
    var videoswf = '<embed src="' + statichost + '/swf/Viewer.swf?lc=' + LC + '" quality="high" bgcolor="#000000" '+
                   '        width="250" height="200" name="Viewer" align="middle" allowScriptAccess="always" '+
                   '        allowFullScreen="false" type="application/x-shockwave-flash" '+
                   '        pluginspage="http://www.macromedia.com/go/getflashplayer" />';
    $('viewer_container').innerHTML = videoswf;
    VIEWER_LOADED = true;
  }
  if( LAST_ID != -1 ){
    $('controller'+LAST_ID).innerHTML = "";
    LAST_ID = -1;
  }
  var controllerswf = '<embed src="' + statichost + '/swf/Controller.swf?url='+ encodeURIComponent( CURRENT_PLAYLIST.songs[ID].url ) +'&lc=' + LC + '" ' +
                      '        quality="high" wmode="transparent" bgcolor="#000000" '+
                      '        width="' + 240 + '" height="15" name="Controller" align="middle" allowScriptAccess="always" '+
                      '        allowFullScreen="false" type="application/x-shockwave-flash" '+
                      '        pluginspage="http://www.macromedia.com/go/getflashplayer" />';

  $('playlist_controller').innerHTML = controllerswf;
}

function errorNotification(){
  var ajax = new Ajax( null, null );
  var uri = "/media/reportbad!ajax.action?url=" + encodeURIComponent( ResultArray[LAST_ID].url );
  ajax.get( uri, null, false );
}


/*************************************************
* Playlist Selection
*************************************************/
function makeDefaultPlayer( playlistNumber ){
  var cookie = new Hash.Cookie('playlistfocus', {duration:30, domain: 'flashwidgetz.com', path: '/'} );
  cookie.set('playlistNumber', playlistNumber );
  loadplaylist();
}

function showPlaylistSelection(){
  if( playlistajax ) playlistajax.abort();
  playlistajax = new Ajax( showPlaylistSelectionHandler, ajaxError );
  var uri = "/media/listplaylist!ajax.action?"+generateLine()+"=0";
  this.playlistajax.get( uri, null, false );
}

function showPlaylistSelectionHandler( obj, jsont ){
  var sessionplaylistArray = sessionplaylist_getplaylist();
  var sessionplaylisthassongs = ( sessionplaylistArray != null && sessionplaylistArray.length != 0 &&
                                  sessionplaylistArray[0].songs != null && sessionplaylistArray[0].songs.length != 0 );

  var json = eval( '(' + jsont + ')' );
  if(json.status == 'failure'){
    alert( json.errorMessage );
  }else{
    var playlistArray = json.Playlist;
    $('playlist_title').innerHTML = 'Select Playlist';

    var html = '';
    html += '<table>';
    if( sessionplaylisthassongs ){
      html += '<tr><td><a class="blacklink" href="#" onclick="makeDefaultPlayer(0);return false;">Unsaved Playlist</td></tr>';
    }

    for( var a = 0; playlistArray != null && a < playlistArray.length; a++ ){
      html += '<tr><td style="padding-left:4px;font-size:8pt;">'+
              '<a class="blacklink" href="#" onclick="makeDefaultPlayer('+ playlistArray[a].playlist_number + ');return false">'+
              playlistArray[a].name + '</td></tr>';
    }
    if( !sessionplaylisthassongs && playlistArray == null || playlistArray.length == 0 ){
      window.location.reload();
    }
    html += '</table>';
    $('playlist_listing').innerHTML = html;
    $('playlist_change_option').setStyle('display', 'none');
    $('playlist_manage_option').setStyle('display', 'none');
  }
}

/*************************************************
* Playlist Actions
*************************************************/
function createplaylist(){
  if( !USER_LOGGED_IN ) return;
  var html = '<form name="saveplaylistform">'+
             '<table width="100%">'+
             '  <tr><td><b>Please Enter Playlist Name</b></td></tr>'+
             '  <tr><td><input type="text" id="playlistName" name="playlistName" style="border:1px solid #333;width:240px;"></td></tr>'+
             '  <tr><td><div style="color:red;font-size:8pt" id="createplaylisterror"></div><div id="creatingplaylistindicator"></div></td></tr>'+
             '  <tr><td style="padding-top:8px"><div onclick="submitCreatePlaylist()" style="border:1px solid #333" class="blankbutton">Create Playlist</div></td></tr>'+
             '  <tr><td><div onclick="loadplaylist()" style="border:1px solid #333" class="blankbutton">Cancel</div></td></tr>'+
             '</table>';
  $('playlist_listing').innerHTML = html;
}


function submitCreatePlaylist(){
  var value = $('playlistName').value;
  if( value == null || value.length > 26 || value < 1 ){
    $('createplaylisterror').innerHTML = 'The playlist name must be between 1 and 26 characters';
    return false;
  }
  $('creatingplaylistindicator').innerHTML = '<img height="20" src="'+ statichost + '/images/common/indicator_blue_large.gif">';
  var ajax = new Ajax( submitCreatePlaylistHandler, ajaxError );
  var uri = "/media/createplaylist!ajax.action?playlistname=" + encodeURIComponent(value);
  ajax.get( uri, null, false );
}

function submitCreatePlaylistHandler( obj, jsont ){
   $('creatingplaylistindicator').setStyle('display', 'none');
   var json = eval( '(' + jsont + ')' );
   if( json.status == 'success' ){
     dialogAlertTimeout( 'Playlist Created Successfully', 1000 );
     loadplaylist();
   }else{
     $('createplaylisterror').innerHTML = json.errorMessage;
   }
}

function savePlaylist(){
  if( !USER_LOGGED_IN ){
    dialogAlert('You must login or register before you can save playlist');
  }else{
    var Playlist = sessionplaylist_getplaylist();
    if( Playlist == null || Playlist[0] == null || Playlist[0].songs == null || Playlist[0].songs.length == 0 ){
      dialogAlert('You cannot save an empty playlist');
      return;
    }else{
      var html = '<form name="saveplaylistform">'+
                 '<table width="100%">'+
                 '  <tr><td><b>Please Enter Playlist Name</b></td></tr>'+
                 '  <tr><td><input type="text" id="playlistName" name="playlistName" style="border:1px solid #333;width:240px;"></td></tr>'+
                 '  <tr><td><div style="color:red;font-size:8pt" id="saveplaylisterror"></div><div id="savingplaylistindicator"></div></td></tr>'+
                 '  <tr><td style="padding-top:8px"><div onclick="submitSavePlaylist()" style="border:1px solid #333" class="blankbutton">Save Playlist</div></td></tr>'+
                 '  <tr><td><div onclick="loadplaylist()" style="border:1px solid #333" class="blankbutton">Cancel</div></td></tr>'+
                 '</table>';
      $('playlist_listing').innerHTML = html;
    }
  }
}

function submitSavePlaylist(){
  var value = $('playlistName').value;
  if( value == null || value.length > 26 || value < 1 ){
    $('saveplaylisterror').innerHTML = 'The playlist name must be between 1 and 26 characters';
    return false;
  }
  $('saveplaylisterror').innerHTML = '';
  $('savingplaylistindicator').innerHTML = '<img height="20" src="'+ statichost + '/images/common/indicator_blue_large.gif">';
  var ajax = new Ajax( submitSavePlaylistHandler, ajaxError );
  var uri = "/media/savesessionplaylist!ajax.action?playlistname=" + encodeURIComponent(value);
  ajax.get( uri, null, false );
}

function submitSavePlaylistHandler( obj, jsont ){
   $('savingplaylistindicator').innerHTML = '';
   var json = eval( '(' + jsont + ')' );
   if( json.status == 'success' ){
     dialogAlertTimeout( 'Playlist Created Successfully', 1000 );
     loadplaylist();
   }else{
     $('saveplaylisterror').innerHTML = json.errorMessage;
   }
}


/*************************************************
* Playlist Media Actions
*************************************************/
function addSong( ID ){
  if( CURRENT_PLAYLIST == null ){
    dialogAlert('You must first select a playlist to add song to');
    return;
  }
  var url = ResultArray[ID].url;
  var title = ResultArray[ID].title;
  title = encodeURIComponent( title );
  url   = encodeURIComponent( url );
  if( CURRENT_PLAYLIST.playlist_number == 0 ){
    if( sessionplaylist_add( url, title ) ){
       dialogAlertTimeout('Song Added Successfully', 1000);
       loadplaylist();
    }
  }else{
    var ajax = new Ajax( addSongHandler, ajaxError );
    var uri = "/media/addplaylistmedia!ajax.action?"+generateLine()+"=0&playlistNumber="+ CURRENT_PLAYLIST.playlist_number +"&title="+title+"&url="+url;
    ajax.get( uri, null, false );
  }
}

function addSongHandler(  obj, jsont ){
  var json = eval( '(' + jsont + ')' );
  if(json.status == 'success'){
    dialogAlertTimeout('Song Added Successfully', 1000);
    loadplaylist();
  }else{
    dialogAlertTimeout(json.errorMessage, 1000);
  }
}

function deleteSong( songid ){
  var args = { 'playlistnumber':CURRENT_PLAYLIST.playlist_number, 'songid':songid };
  confirmSubmit(null, deleteSongConfirmHandler, args, "Are you sure you want to delete this song" );
  return false;
}

function deleteSongConfirmHandler( value, args ){
  if( value == true ){
    if( args.playlistnumber == 0 ){
      sessionplaylist_delete( args.songid );
      loadplaylist();
    }else{
       var ajax = new Ajax( deleteSongHandler, ajaxError );
       var uri = "/media/deleteplaylistmedia!ajax.action?confirm=true&playlistNumber="+
                 args.playlistnumber+"&songId="+args.songid+"&"+generateLine()+"=0";
       ajax.get( uri, null, false );
    }
  }
}

function deleteSongHandler( obj, jsont ){
  var json = eval( '(' + jsont + ')' );
  if(json.status != 'success'){
      dialogAlert(json.errorMessage);
  }
  loadplaylist();
}


/*************************************************
* Playlist Loader
*************************************************/
function loadplaylist(){
  if( !USER_LOGGED_IN ){
    loadsessionplaylist();
  }else{
    if( playlistajax ) playlistajax.abort();
    playlistajax = new Ajax( loaduserplaylist, playlistloaderror );
    var uri = "/media/listplaylist!ajax.action?"+generateLine()+"=0";
    this.playlistajax.get( uri, null, false );
  }
}

function playlistloaderror(){
}


function loadsessionplaylist(){
  var sessionplaylistArray = sessionplaylist_getplaylist();
  var sessionplaylisthassongs = ( sessionplaylistArray != null && sessionplaylistArray.length != 0 &&
                                  sessionplaylistArray[0].songs != null && sessionplaylistArray[0].songs.length != 0 );
  if( sessionplaylisthassongs ){
    writeplaylist( sessionplaylistArray[0] );
  }else{
    var fakeplaylist = new Object();
    fakeplaylist.playlist_number = 0;
    fakeplaylist.songs = new Array();
    writeplaylist( fakeplaylist );
  }
}

function loaduserplaylist( obj, jsont ){
  var json = eval( '(' + jsont + ')' );
  if(json.status == 'failure'){
    dialogAlert( json.errorMessage );
  }else{
    var sessionplaylistArray = sessionplaylist_getplaylist();
    var sessionplaylisthassongs = ( sessionplaylistArray != null && sessionplaylistArray.length != 0 &&
                                    sessionplaylistArray[0].songs != null && sessionplaylistArray[0].songs.length != 0 );
    var playlistArray = json.Playlist;
    if( playlistArray == null || playlistArray.length == 0 ){
      var sessionplaylistArray = sessionplaylist_getplaylist();
      if( sessionplaylisthassongs ){
        loadsessionplaylist();
      }else{
         var html = '<table>';
         html += '<tr><td><center>' +
            'You currently do not have a playlist created.<br>'+
            'Click <a class="bluelink" href="#" onclick="createplaylist();return false">here</a> to create a playlist<br><br>'+
            'Start searching for songs and click the plus sign to add tracks to your playlist.'+
            '</center></td></tr>';
         html += '</table>';
         $('playlist_listing').innerHTML = html;
         $('playlist_change_option').setStyle('display', 'none');
         $('playlist_manage_option').setStyle('display', 'none');
      }
    }else{
      var cookie = new Hash.Cookie('playlistfocus', {duration:30, domain: 'flashwidgetz.com', path: '/'} );
      var playlistNumber = cookie.get('playlistNumber');
      if( playlistNumber == null ){
        if( sessionplaylisthassongs ){
          loadsessionplaylist();
        }else{
          writeplaylist( playlistArray[0] );
        }
      }else{
        if( playlistNumber == 0 && sessionplaylisthassongs ){
          loadsessionplaylist();
        }else{
          var found = false;
          for( var a = 0; a < playlistArray.length; a++ ){
            if( playlistArray[a].playlist_number == playlistNumber ){
              writeplaylist( playlistArray[a] ); found = true; break;
            }
          }
          if( !found ){
            cookie.set( 'playlistNumber', null );
            writeplaylist( playlistArray[0] );
          }
        }
      }
    }
  }
}


function writeplaylist( playlist ){
  CURRENT_PLAYLIST = playlist;
  var title = playlist.name;
  if( playlist.playlist_number == 0 ){
    title = 'Unsaved Playlist';
  }

  $('playlist_title').innerHTML =  'Playlist (' + title + ')';

  var html = '';
  html += '<div id="playlist-results" width="100%">';
  for( var a = 0; playlist.songs != null && a < playlist.songs.length; a++ ){
    html += '<div id="'+ a + '"><table width="100%" cellspacing="0" cellpadding="0">'+
            '  <tr><td style="width:10px">' + (a+1) + '.</td>'+
            '      <td style="text-align:left"><a class="blacklink" href="#" onclick="playSong(' + a + ' );return false;">' + playlist.songs[a].title + '</a></td>' +
            '  </tr></table>'+
            '<div style="text-align:right"><a href="#" class="palebluelink" onclick="deleteSong(' + playlist.songs[a].id + ');return false">Delete</a></div>' +
            '</div>';
  }
  if( playlist.songs == null || playlist.songs.length == 0 ){
    html += '<center><b>Your playlist is empty.</b><br><br>'+
            'Start searching for songs and click the plus sign to add tracks to your playlist.'+
            '</center>';
  }
  html += '</div>';

  if( playlist.playlist_number == 0 && playlist.songs != null && playlist.songs.length > 0 ){
    html += '<br><center><a class="palebluelink" href="#" onclick="savePlaylist();return false">Save My Playlist</a></center>';
  }
  $('playlist_listing').innerHTML = html;

  makeSortable( playlist.playlist_number );


  if( USER_LOGGED_IN && playlist != null && playlist.playlist_number != 0){
    $('playlist_manage_option').setStyle('display', 'block');
    $('manageplaylist').href = '/playlist/view/' + playlist.eid;
  }else{
    $('playlist_manage_option').setStyle('display', 'none');
  }
  if( USER_LOGGED_IN && playlist != null  ){
    $('playlist_change_option').setStyle('display', 'block');
  }else{
    $('playlist_change_option').setStyle('display', 'none');
  }
}


function makeSortable( playlistNumber ){
  var mySort = new Sortables( $("playlist-results"),
  {
     constrain: true,
     //clone: true,
     revert: true,
     onComplete: function(){
       var result = ""+mySort.serialize();
       var array = result.split(",");
       var order = '';
       var inorder = true;
       for(var a = 0; a < array.length; a++){
         order += array[a].replace(/^s+/, '').replace(/s+$/, '');
         if(a != array.length-1) order += '.';
         if( a < array.length-1 && parseInt(array[a]) > parseInt(array[a+1]) ) inorder = false;
       }
       var index = 0;
       mySort.serialize(function(element){
         element.id = index;
         index++;
       });
       if( inorder == true ) return;
       if( playlistNumber == 0 ){
         sessionplaylist_reorder( order );
         loadplaylist();
       }else{
         var reloadfunc = function(num){ loadplaylist(num) }.pass( playlistNumber );
         if( sortajax ) sortajax.abort();
         sortajax = new Ajax( reloadfunc, ajaxError );
         var uri = "/media/reorderplaylist!ajax.action?playlistNumber="+playlistNumber+
                   "&order="+encodeURIComponent(order)+"&"+ generateLine()+"=0";
         sortajax.get( uri, null, false );
       }
     }
  });
}

function reloadfunc(){
  loadplaylist();
}
