var PlCounter = {
    _state    : 'on',
    _total    : 0,
    _advance  : 0,
    _pid      : 0,

    togglestate : function(){
        switch(this._state){
            case 'on':
                this._state = 'off';
                break;
            case 'off':
                this._state = 'on';
                break;
        }
    },

    setNewPid   : function(){
        do{
            pid = Math.round(Math.random()*1000);
        }while(pid == this._pid);
        this._pid = pid;
    },

    kill        : function(){
        this.setNewPid();
    },

    launch   : function(total,callback){
        this._total = total;
        this._advance = 0;
        this._state = 'on';
        this._callback = callback;
        this.setNewPid();
        cmd = "PlCounter.tick("+this._pid+")";
        setTimeout(cmd,1000);
    },

    tick     : function(pid){
        if(pid !=this._pid){
            return;
        }
        if(this._state == 'on'){
            this._advance ++;
            //console.log(this._advance+" with pid "+this._pid);
        }
        if(this._advance < this._total){
            cmd = "PlCounter.tick("+this._pid+")";
            setTimeout(cmd,1000);
        }else{
            this.end();
        }
    },

    end     : function(){
        //console.log("ended");
        if(this._callback != undefined){
            eval(this._callback);
        }
    }
}

var Playlist = {
    _current_row : 0,
    _playlist    : Array(), //truc de la forme {"id" : id_source, "duration" : duree du clip}
    _type        : "public",
    _playlist_id : 0,
    _current_item: null,


    load    : function(data,andplayrow){
        this._playlist      = data.playlist;
        this._type          = data.type;
        this._playlist_id   = data.id;
        this._current_row   = 0;
        this._current_item  = this._playlist[0];
        if(andplayrow == undefined){
            this.stop();
        }else{
            this.play(andplayrow);
        }
    },
    
    loadfromdb: function(playlist_id,andplayrow){
                $.get("/playlist/load",
                        {"playlist_id":playlist_id},
                        function(data){Playlist.load(data,andplayrow)},
                        "json"
                     );
    },

    add     : function(articles_id,playlist_id){
                if((playlist_id==undefined && this._playlist_id != 0)|| (playlist_id == this._playlist_id)){
                    //playlist_id = this._playlist_id;
                    playlist_id = 0;
                    process = function(data){
                        if(data!= null && data.errorLogin != undefined && data.errorLogin == true){
                            showDialog('dialogLogin','Jukebo Login',300);
                        }else if(data == null){
                            confirmAlert("Not Playlistable","#f00");
                        }else{
                            var item = data.item;
                            if(item!= null && item.id != undefined && item.duration != undefined && item.duration > 0)
                            {
                                Playlist._playlist.push(item);
                                confirmAlert(data.message,"#060");
                            }
                        }
                    };
                }else{
                    process = function(data){
                        if(data!= null && data.errorLogin != undefined && data.errorLogin == true){
                            showDialog('dialogLogin','Jukebo Login',300);
                        }else{
                            var item = data.item;
                            if(item!= null && item.id != undefined && item.duration != undefined && item.duration > 0)
                            {
                                confirmAlert(data.message,"#060");
                            }
                        }
                    };
                }
                
                $.post("/playlist/add",
                        {"playlist_id":playlist_id,"articles_id":articles_id},
                        process,
                        "json"
                     );
             },

    remove  : function(row,playlist_id,element_id){
                if(
                    (playlist_id==undefined && this._playlist_id != 0)
                 || (playlist_id == this._playlist_id)
                   ){
                    playlist_id = this._playlist_id;
                    process = function(done){
                        if(done===true){
                            Playlist._playlist.splice(row,1);
                            if(element_id!=undefined){
                                $('#'+element_id).hide();
                            }
                        }
                    };
                }else{
                    process = function(done){
                        if(done===true){
                            if(element_id!=undefined){
                                    $('#'+element_id).hide();
                            }
                        }
                    };
                }

                $.post("/playlist/remove",
                        {"playlist_id":playlist_id,"row":row},
                        process,
                        "json"
                     );
            },

    play    : function(row,playlist_id){
                if(playlist_id != undefined){
                    this.loadfromdb(playlist_id,row);
                    return;
                }
                
                if(row != undefined){
                    this._current_row = row;
                }
                if(this._playlist[this._current_row] == undefined){
                    this._current_row = 0;
                }
                this._current_item = this._playlist[this._current_row];
                var urlpreview = '/preview/playlist/id/'+ this._current_item.id +'/autoplay/yes/';
                this.updateDiv('embed',urlpreview);
                PlCounter.launch(this._current_item.duration,"Playlist.next()");
              },

    stop    : function(){
                var urlpreview = '/preview/playlist/id/'+ this._current_item.id +'/autoplay/no/';
                this.updateDiv('embed',urlpreview);
                PlCounter.kill();
            },

    pause   : function(){
                PlCounter.togglestate();
            },

    first   : function(){
                this._current_row = 0;
                if(this._playlist[this._current_row] == undefined){
                    this._current_row = 0;
                }
                this.play();
             },
    next     : function(){
                this._current_row++;
                if(this._playlist[this._current_row] == undefined){
                    this._current_row = 0;
                }
                this.play();
             },
    prev     : function(){
                this._current_row--;
                if(this._playlist[this._current_row] == undefined){
                    this._current_row = this._playlist.length-1;
                }
                this.play();
             },
    updateDiv: function(div,url){
                  
                $('#loader').show();
                $('#'+div).load(url, function() {
                  $('#loader').hide();
                   addLayer("playlistVideo","videoLayer",0.1);
                   //Duplication de la barre de controles
                   if ($("#LayerPlaylistBar").length == 0)
            	   {
            	        var html = $("#playlistBar").html();
            			$("#videoLayer").before("<div id='LayerPlaylistBar' class='center'>"+html+"</div>");
            		    var position = $("#videoLayer").position();
            		    var top = (position.top+359);
            		    $('#LayerPlaylistBar').css("left", position.left+"px");
            		    $('#LayerPlaylistBar').css("top", top+"px");
            		    $('#LayerPlaylistBar').append("<span>[Playlist]</span>");
            	   }
            		
            		
                   	
                });
               }
}
