/*
	Copyright James Matteson 2011. All rights reserved.
*/
var myPlaylist = new playlist();

function playlist(){
   var oThis = this;
   var currentIndex = -1;
   var items = [];
   var dragStartIndex = -1;
   var dragEndIndex = -1;
   
   /* Constructor */
   document.observe('dom:loaded', function(){
      jQuery("#playlist").sortable({
         axis: 'y',
         start: function(e, ui){
            ui.helper.width($(ui.helper.attr('id')).getWidth() - 10); // Make the dragged element appear the same width
            jQuery(ui.helper).addClass('drag');
            dragStartIndex = jQuery('#playlist').children().index(ui.item[0]);
         },
         stop: function(e, ui){ 
            jQuery(ui.helper).removeClass('drag');
            dragEndIndex = jQuery('#playlist').children().index(ui.item[0]);
            
            // Fix sort
            if (dragStartIndex != dragEndIndex){
               var clone = Object.clone(items[dragStartIndex]);
               
               items.splice(dragStartIndex, 1);
               items.splice(dragEndIndex, 0, clone);
               
               // Correct the current index
               if (dragStartIndex == currentIndex){
                  currentIndex = dragEndIndex;
               }else if (dragStartIndex < currentIndex){
                  if (dragEndIndex < currentIndex){
                     // Ignore
                  }else if (dragEndIndex >= currentIndex){
                     currentIndex--;
                  }
               }else if (dragStartIndex > currentIndex){
                  if (dragEndIndex <= currentIndex){
                     currentIndex++;
                  }else{
                     // Ignore
                  }
               }
            }
         }
      });
   });
   document.observe('error:notfound', function(e){
      if (e.memo.error == 100){
         //var p = $('playlist_' + items[currentIndex].id).select('p')[0]
         //p.innerHTML = 'Video not found.';
      } 
      
      if (items.length > 1)
         oThis.playNext();
   });
   
   /* Private */
   function indexOf(id){
      for(var i = 0, len = items.length; i < len; i++){
         if (items[i].id == id)
            return i;
      }
      
      return -1;
   }
   function createItem(item){
      var li = new Element('li', {
         id: 'playlist_' + item.id
      });
      var div = new Element('div', {});
      var title = new Element('p', {});
      var cancel = new Element('img', {
         src: imgPath + 'cancel-disabled.png'
      });
      
      jQuery(li).hover(
         function(){
            li.addClassName('hover');
         }, 
         function(){
            li.removeClassName('hover');
         }
      );
      li.observe('dblclick', function(){
         oThis.play(item.id);
      }); 
      cancel.observe('mouseover', function(){
         cancel.src = imgPath + 'cancel.png';
      });
      cancel.observe('mouseout', function(){
         if (!cancel.hasClassName('playing')){
            cancel.src = imgPath + 'cancel-disabled.png';
         }else{
            cancel.src = imgPath + 'disabledplay.png';
         }
      });
      cancel.observe('click', function(){
         if (cancel.hasClassName('playing')){
            changingQuality = true;
            oThis.clear();
            currentIndex = -1;
            $('playingTitle').innerHTML = '';
            $('playingTitle2').innerHTML = '';            
         }
         
         oThis.remove(item.id);
         li.remove();
         changingQuality = false;
      });
      
      myUtils.noSelect(li);
      myUtils.noSelect(div);
      myUtils.noSelect(title);
      myUtils.noSelect(cancel);
      
      title.innerHTML = item.title;
      div.insert(cancel);
      div.insert(title);
      li.insert(div);
      
      return li;
   }
   
   /* Public */
   this.add = function(id, title, img){
      if (indexOf(id) < 0){
         var item = {'id': id, 'title': title, 'img': img};
         items.push(item);
         $('playlist').insert(createItem(item));
         jQuery("#playlist").sortable("refresh");
         myUI.resize();
      }
   }
   this.addSharedItem = function(id, title, img){
      if (indexOf(id) < 0){
         var sharedItems = myUtils.getSharedItems();
         var item = {'id': id, 'title': title, 'img': img};
         var lastItem = null;
         var lastItemID = null;
         
         // Find the correct place for the new item
         for(var i = 0, len = sharedItems.length; i < len; i++){
            var itemID = sharedItems[i].strip();
            
            if (id == itemID){
               // Found the current item in the list
               break;
            }else{
               // See if the item already loaded
               var temp = $('playlist_' + itemID);
               
               if (temp != null){
                  lastItem = temp;
                  lastItemID = itemID;
               }
            }
         }
         
         // Insert the new item
         if (lastItem == null){
            // There were no items before this one, append to top
            items.splice(0, 0, item);
            $('playlist').insert({'top' : createItem(item)});
         }else{
            // Previous item found, append after
            for(var i = 0, len = items.length; i < len; i++){
               if (items[i].id == lastItemID){
                  // Insert after the previous item in our items array
                  items.splice(i + 1, 0, item);
                  break;
               }
            }
            lastItem.insert({'after' : createItem(item)});
         }
      
         jQuery("#playlist").sortable("refresh");
         myUI.resize();
      }
   }
   this.remove = function(id){
      var i = indexOf(id);
      
      if (i >= 0){
         if (i < currentIndex){
            currentIndex -= 1;
         }
         
         items.splice(i, 1);
         jQuery("#playlist").sortable("refresh");
         myUI.resize();
      }
   }
   this.play = function(id){
      var i = indexOf(id);
      
      if (i >= 0){
         var itemImg = $('playlist_' + id).select('img')[0];
         
         // Current index
         currentIndex = i;
         
         // Title
         $('playingTitle').innerHTML = items[i].title;
         $('playingTitle2').innerHTML = items[i].title;
         
         // Playlist image
         $('playlist').select('img.playing').each(function(img){
            img.removeClassName('playing');
            img.src = imgPath + 'cancel-disabled.png';
         });
         itemImg.src = imgPath + 'disabledplay.png';
         itemImg.addClassName('playing');
                  
         // Play
         myUI.setSwitchingVideos(true);
			ytplayer.loadVideoById(id, 0);
      }
   }
   this.playPause = function(){
      var state = ytplayer.getPlayerState();
      
      if (currentIndex < 0){
         oThis.playNext();
      }else if (state == 1 || state == 3){
         ytplayer.pauseVideo();
      }else if (state == 2 || state == 5){
         ytplayer.playVideo();
      }
   }
   this.playPrev = function(){
      if (currentIndex > 0){
         oThis.play(items[currentIndex - 1].id);
      }else if (items.length > 0){
         oThis.play(items[items.length - 1].id);
      }
   }
   this.playNext = function(){
      if (currentIndex < items.length - 1){
         oThis.play(items[currentIndex + 1].id);
      }else if (items.length > 0){
         oThis.play(items[0].id);
      }
   }
   this.clear = function(){
      ytplayer.stopVideo();
      ytplayer.clearVideo();
   }
   this.reload = function(){
      if (currentIndex >= 0){
         ytplayer.cueVideoById(items[currentIndex].id, 0);
      }
   }
   this.getUrl = function(callbackFunctionName){
      var url = '';
      var list = '';
      
      for(var i = 0, len = items.length; i < len; i++){
         if (list.length > 0) list += ',';
         list += items[i].id;
      }
      
      url = "http://remysharp.com/tinyurlapi?";
      url += "callback=" + callbackFunctionName;
      url += "&url=http://www.movielouvre.com/?pl=" + list;
      myUtils.attachScript(url);
   }
}
