Type.registerNamespace("RFERL.js.custom");
/* Class Playlist 
   operates with playlist actions and stores data about it
 */
 RFERL.js.custom.Playlist = function()
 {
    RFERL.js.custom.Playlist.initializeBase(this);
    
    this.unhilightColor="transparent";
    this.hilightColor="#f9f9f9";
    this.playedColor="#eaeaea";
    this.hilightPlayedColor="#e4e4e4";
    
    //ids of elemnts
    this.playlistId = "playlist";
    this.mediaPlayerId = "MediaPlayer";
    var bottomDDDummyId = "bottom_DD_dummy";
    
    //cutting long names properties
    this.titleMaximumChars=25;
    
    
    
    this.playItem = function(id)
    {
        /// <summary>Starts playing of given item</summary>
        /// <param name="id" type="string">Id of item html element</param>
        /// <returns type="void"/>
        if (this.sucesfulPlayResting!=true) {
            var item = this.selectById(id);
        
            this.playerFailures = 0;
            this.curentlySendedId = item.id;
            
            //send to flash
            var data = $(item).data("playlistItem");
            //playMediaFromPlaylist(data.flashXmlUrl,this.mediaPlayerId,item.id);
            this.playItemInFlash(data.flashXmlUrl,this.mediaPlayerId,item.id,data);
            
            //save id to global variable
            window.currentlyPlayed = item.id;
            
            //mark as played
            this.hilightPlayed(id); 
            
            //scroll to item
            this.scrollToItem(id);
           
            //reset DD
            document.DD.draged_object=null;
            document.DD.underlyingObject=null;
            document.DD.restoreContainer();
            
            //update nowplaying variable
            setNowPlaying(data);
            
            //render item description and links
            document.playingItemDesc.renderAll(data);
            
            fixOperaRedraw("#f4f4f4");
        }
    }
    
    
    this.scrollToItem = function (id)
    {
        /// <summary>Scroll list to current played item</summary>
        /// <returns type="void"/>
        var countedHeight = 0;
        var finCountedHeight = 0;
        var currentlyPlayed = id;

        $('#'+this.playlistId).children().each(function (i) {
                
            if ($(this).attr('id')==currentlyPlayed) {
                finCountedHeight = countedHeight;
            }
            
            countedHeight+=$(this).outerHeight();
        
        });
        if(document.getElementById(this.playlistId))
            document.getElementById(this.playlistId).scrollTop = finCountedHeight;
    }
    
    
    this.playFirstItem  = function()
    {
        /// <summary>Starts playing of first item</summary>
        /// <returns type="void"/>
        var firstItemId = $('#'+this.playlistId).children()[0].id;
        this.playItem(firstItemId);
    }
    
    
    this.playNextItem = function(lastId)
    {
        /// <summary>Starts playing next item of playlist</summary>
        /// <param name="lastId" type="string">Identifier of last played item. Optional, can be null</param>
        /// <returns type="void"/>
        var lastPlayed;
        
        if (lastId==null) {
            if (!window.currentlyPlayed || window.currentlyPlayed=="") {
                //nothing is playing, play first item
                this.playFirstItem();
                return; 
            } else {
                lastPlayed = window.currentlyPlayed;
            }
        } else {
            lastPlayed = lastId;
        }
        
        lastPlayedPos = this.getItemPosition(lastPlayed);
        maxPos = ($('#'+this.playlistId).children().length)-2;
        
        if (lastPlayedPos<maxPos) {
            nextItem = $('#'+this.playlistId).children()[lastPlayedPos+1];
            //play
            this.playItem(nextItem.id);
        }
    }
    
    
    this.playItemOnClick  = function(evt)
    {
        /// <summary>Starts playing track from click event</summary>
        /// <param name="evt" type="object">Event</param>
        /// <returns type="void"/>
        var hoveredItem = $(evt.currentTarget).parent().parent();
        this.playItem(hoveredItem.attr('id'));
    }
    
    
    this.selectById = function(id)
    {
        /// <summary>Selects item by id of its main html element</summary>
        /// <param name="id" type="string">Id of item html element</param>
        /// <returns type="object"/>
        var ret = null;
        $('#'+this.playlistId).children().each(function (i) {
            var item = this;
            if (item.id==id) {
	          ret = item;
	          return false;
	        }
        });
        return ret;
    }
    
    
    this.selectByNowPlayingContent = function() 
    {
        //selects item by contentId property of GLOBAL variable nowPlaying
        if (nowPlaying==null) return null;
        
        var ret = null;
        $('#'+this.playlistId).children().each(function (i) {
            var item = this;
	        var data = $(item).data("playlistItem");
	        if (data!=null) {
	            if (nowPlaying.contentId==data.contentId) {
                    ret = item;
                    return false;
                }
	        }
	    });
        return ret;
    }
    
    
    this.selectLastItem = function ()
    {
        var len = $('#'+this.playlistId).children().length;
        return $('#'+this.playlistId).children()[len-2];
    }
    
    
    this.sendOrderToServer = function(playlistItem, itemReturnReference)
    {
        /// <summary>Sends item order to server as an array</summary>
        /// <param name="playlistItem" type="object">Jquery object with data, droped item</param>
        /// <param name="itemReturnReference" type="object">Return reference DOM object used in case server call returns false to reorder items</param>
        /// <returns type="void"/>
        var id = playlistItem.attr('id');
        var numericId = getIntFromId (id);
        
        var order = [];
        $('#'+this.playlistId).children().each(function (i) {
            if (this.id!=bottomDDDummyId) {
                order.push(getIntFromId(this.id));
            }
        });
  
        www.rferl.org.Services.PlaylistService.SetItemsOrder(order,
            function(param){   
              if (param!=true) {
                //server says error in order so return item to its previous location and dont ask server this time
                alert(Localizations.Multimedia.Playlist.OrderingError);
                document.DD.dropToList(playlistItem, itemReturnReference, false);
              } 
            }
        );
    }

    var getIntFromId = function (id)
    {
        /// <summary>Returns numeric id of item from html elemnt id</summary>
        /// <param name="id" type="string">Id of html item element</param>
        /// <returns type="number"/>
        var ret = 0;
        s = id.split("_");
        for(var i=0; i<s.length; i++){
            if (parseInt(s[i])>0) {
                ret = parseInt(s[i]);
                return ret;
            }
        }
        return ret;
    }
    
    this.getItemPosition = function (id)
    {
        /// <summary>Returns position of item. 0 for first</summary>
        /// <param name="id" type="string">Id of html item element</param>
        /// <returns type="number"/>
        var p = 0;
        var ret = null;
        $('#'+this.playlistId).children().each(function (i) {
            if (this.id==id) {
                ret = p;
                return false;
            }
            p++;
        });
        return ret;
    }
    
    
    this.removeItem = function(evt)
    {
        /// <summary>Removes item from playlist</summary>
        /// <param name="id" type="string">Id of html item element</param>
        /// <returns type="void"/>
        var hoveredItem = $(evt.currentTarget).parent().parent();
        var id = hoveredItem.attr('id');
        
        $('#'+this.playlistId).children().each(function (i) {
            var item = this;
            var data = $(item).data("playlistItem");
            var numericId = getIntFromId (item.id);
	        if (item.id==id) {
	          fade(item.id); //visual change before server request tells user that somenthing is happening after remove click
	          //unbind item events before delete, so user cannot click to remove two times for one item
	          $('#'+item.id).children().children().each(function (i) {
	            $(this).unbind();
	          });

	          www.rferl.org.Services.PlaylistService.RemoveFromPlaylist(numericId,function(){
                    $("#"+id).remove();
                    
                    if (nowPlaying==null) nowPlaying = new Object;
                    if (nowPlaying.contentId==data.contentId) {
                       //unhide add to playlist link
                        document.playingItemDesc.unhideDescPlaylistLink();
                    }
                    
                    fixOperaRedraw("#f4f4f4");
              },handleRemoveItemException);
              return false;
	        }
        });
    }
    
    
    this.clearAll = function (question)
    {
        /// <summary>Removes all items from playlist</summary>
        /// <param name="question" type="string">Question text to confirmation window</param>
        /// <returns type="void"/>
        var answer = confirm(question);
	    var playlistId = this.playlistId;
	    if (answer){
	        $('.playlist_item_remove').unbind();
	        fadeAll(); //visual change before server request tells user that somenthing is happening
	        www.rferl.org.Services.PlaylistService.ClearPlaylist(function(){
                $('#'+playlistId).children().each(function (i) {
                    if (this.id!=bottomDDDummyId) {
                        //remove all except bottom dd dummy
                        $("#"+this.id).remove();  
                    }
                });
                
                //unhide add to playlist link
                document.playingItemDesc.unhideDescPlaylistLink();
                
                fixOperaRedraw("#f4f4f4");
		    },handleRemoveItemException);
		}
    }
    
    
    var handleRemoveItemException = function(error)
    {
        //if remove was unscucesful, rebind previously manipulated events
        unbindItemEvents ();
        bindItemEvents ();
        unfadeAll();
    }
    
    
    this.cutLongTitles = function() 
    {
        //loops all playlist items and calls long title strip function to long ones
        var _this = this;
        $('#'+this.playlistId).children().each(function (i) {
            var itemData = $('#'+$(this).attr('id')).data("playlistItem"); 
            var nameElement = $(this).children("ul").children(".playlist_item_name"); 
            var titleElement = $(nameElement).children()[0]; 
            if (itemData!=null && ($(nameElement).width()<$(titleElement).width())) {
                _this.stripTitleHtml(itemData.name, nameElement, titleElement, 5, 0);
            }
            
            //item with empty title not clickable fix
            if ($(titleElement).width()==0) $(titleElement).html("&nbsp;");
        });
    }
    
    
    this.moveItemUp = function(evt)
    {
        /// <summary>moves item 1 level up in playlist</summary>
        /// <param name="evt" type="object">Event</param>
        /// <returns type="void"/>
        var hoveredItem = $(evt.currentTarget).parent().parent().parent();
        pos = this.getItemPosition(hoveredItem.attr('id'));
        if (pos>0) {
            //find previous item
            var prevItem = $('#'+this.playlistId).children()[pos-1];
            document.DD.dropToList(hoveredItem, prevItem, true);
        }
        this.unhilightUpItem();
        fixOperaRedraw("#f4f4f4");
    }
    
    
    this.moveItemDown = function(evt)
    {
        /// <summary>moves item 1 level down in playlist</summary>
        /// <param name="evt" type="object">Event</param>
        /// <returns type="void"/>
        var hoveredItem = $(evt.currentTarget).parent().parent().parent();
        pos = this.getItemPosition(hoveredItem.attr('id'));
        ln = ($('#'+this.playlistId).children().length)-2;
        if (pos<ln){
            var nextItem = $('#'+this.playlistId).children()[pos+2];
            document.DD.dropToList(hoveredItem, nextItem, true);
        }
        this.unhilightDownItem();
        fixOperaRedraw("#f4f4f4");
    }
    
    
    this.hilightItem = function(evt)
    {
       var hoveredItem = $(evt.currentTarget).parent().parent();
       
       if (window.currentlyPlayed!=null &&  window.currentlyPlayed==hoveredItem.attr('id')) {
            hoveredItem.css("background-color", this.hilightPlayedColor);    
       } else {
            hoveredItem.css("background-color", this.hilightColor);
       } 
    }
    
    
    this.unhilightItem = function(evt)
    {
        var hoveredItem = $(evt.currentTarget).parent().parent();
        
        if (window.currentlyPlayed!=null &&  window.currentlyPlayed==hoveredItem.attr('id')) {
            hoveredItem.css("background-color", this.playedColor);
        } else {
            hoveredItem.css("background-color", this.unhilightColor);
        }
    }
    
    
    this.hilightPlayItem = function(evt)
    { 
        $(evt.currentTarget).addClass("playlist_item_play_hover"); 
    }
    
    this.unhilightPlayItem = function()
    {
        $(".playlist_item_play").removeClass("playlist_item_play_hover");  
    }
    
    
    this.hilightUpItem = function(evt)
    { 
        $(evt.currentTarget).addClass("playlist_item_up_hover");  
    }
    
    this.unhilightUpItem = function()
    {
        $(".playlist_item_up").removeClass("playlist_item_up_hover");  
    }
    
    
    this.hilightDownItem = function(evt)
    { 
        $(evt.currentTarget).addClass("playlist_item_down_hover");  
    }
    
    
    this.unhilightDownItem = function()
    {
        $(".playlist_item_down").removeClass("playlist_item_down_hover");  
    }
    
   
    this.hilightPlayed = function(id)
    {
        /// <summary>Marks item as currently played</summary>
        /// <param name="id" type="string">Id of item html element</param>
        /// <returns type="void"/>
        $(".playlist_item").css("background-color", this.unhilightColor);
        $("#"+id).css("background-color", this.playedColor);
    }
    
    
    this.unhilightPlayed = function()
    {
        $(".playlist_item").css("background-color", this.unhilightColor);
    }
    
    
    var fade = function(id) {
        if (id!=window.currentlyPlayed) {
            $("#"+id).css("background-color", "#ffffff");
        }
        $("#"+id).css("opacity", "0.5");
    }
    
    
    var fadeAll = function() {
        $('.playlist_item').css("background-color", "#ffffff");
        $('.playlist_item').css("opacity", "0.5");
    }
    
    
    var unfadeAll = function() {
        $('.playlist_item').css("opacity", "1");
    }
 }
 
 RFERL.js.custom.Playlist.registerClass('RFERL.js.custom.Playlist', RFERL.js.custom.BaseListComponent);
 