var player = {
    jwplayer : null,
    div_playlist_id:  'd_playlist_song',
    current_index: 0,
    index_before_reload: 0,
    current_position: 0,
    tmp_count: 0,
    is_reload: false,
    playlist_loaded: false,
    need_reload: false,   // danh dau de khi next bai hat se reload lai player
    jumpby_sid: false,
    is_play_next: true,
    before_sid: 0,
    checkPlaylistLoaded: function(obj) {
        var p = document.getElementById(obj['id']);
        var jsPlaylist = p.getPlaylist();
        var playlist = $('#'+player.div_playlist_id);
        if (jsPlaylist.length > 0 && playlist.html() !== '') {
            player.populatePlaylist(p, playlist);
            p.addControllerListener("PLAYLIST","player.playlistHandler");
            p.addControllerListener("ITEM","player.itemHandler");
            player.playlist_loaded = true;
        } else {
            setTimeout(function(){player.checkPlaylistLoaded(obj);}, 150);
        }
    },
    populatePlaylist: function(p, playlist){
        var playlistItem = 0;
        playlist.children().each(function(){
            var currentItem = playlistItem;
            $(this).find('a.name').click(function () {
                $(this).addClass('playing');
                p.sendEvent("ITEM", currentItem);
            });
            playlistItem++;
        });
    },
    playlistHandler: function (obj){
        var p = document.getElementById(obj['id']);
        var playlist = $('#'+player.div_playlist_id);
        player.populatePlaylist(p, playlist);
    },
    itemHandler: function(obj) {
        var item = obj['index'];
        
        //if(player.need_reload){
        if(player.isNeedReload()){
            player.callReload();
            return true;
        }
        player.current_index = item;
        
        var swfPlayer = document.getElementById(obj['id']);
        var jsPlaylist = swfPlayer.getPlaylist();
        var jsItem = jsPlaylist[item];
        
        if(typeof(jsItem) === 'object') {
            player.setPlayTime(jsItem['duration']);
        }
        
        var playlist = $('#'+player.div_playlist_id);
        var currentItem = 0;
        playlist.children().each(function(){
            if (currentItem === item) {
                $(this).find('a.name').addClass("playing");
                $(this).find('a.remove').hide();
            } else {
                $(this).find('a.name').removeClass("playing");
                $(this).find('a.remove').show();
            }
            currentItem++;
        });
        
    },
    setPlayTime: function(duration){
        var currentDate  = new Date();
        var time = currentDate.valueOf();
        $.cookie('play_time',time,{path:'/'});
        $.cookie('duration',duration,{path:'/'});
    },
    resetPlayTime: function(){
        $.cookie('play_time',0,{path:'/'});
        $.cookie('duration',0,{path:'/'});
    },
    isPlaying: function(){
        var play_time = $.cookie('play_time');
        var duration = $.cookie('duration');
        var currTime = new Date();
        
        if(play_time === 0 || currTime.valueOf() - play_time > duration*1000){
            return false;
        }
        return true;
    },
    setJumpBySid: function(){
        player.jumpby_sid = true;
        $.cookie('jumpby_sid',true,{path:'/'});
    },
    clearJumpBySid: function(){
        player.jumpby_sid = false;
        $.cookie('jumpby_sid',false,{path:'/'});
    },
    isJumpBySid: function(){
        if(player.jumpby_sid === true || $.cookie('jumpby_sid') === 'true'){
            return true;
        }
        return false;
    },
    setPlayAgainCurrentSong: function(){
        this.is_play_next = false;
    },
    setPlayNextSong: function(){
        this.is_play_next = true;
    },
    isNeedReload: function(){
        if(player.need_reload || $.cookie('need_reload') === 'true'){
            return true;
        }
        return false;
    },
    setNoNeedReload: function(){
        player.need_reload = false;
        $.cookie('need_reload',false,{path:'/'});
    },
    callReload: function(){
        if(player.isJumpBySid()){
            player.before_sid = music_playlist.getPlayingSid(player.current_index);
        }
        //player.need_reload = false;
        player.setNoNeedReload();
        music_playlist.reload();
    },
    reloadPlaylist: function(){
        this.is_reload = true;
        
        this.current_position = this.jwplayer.getPosition();
        if(this.current_position === undefined){
            this.current_position = 0;
        }
        this.index_before_reload = this.current_index;
        
        this.playlist_loaded = false;
        this.jwplayer.remove();
    },
    afterReloadPlaylist: function(){
        var jsPlaylist = this.jwplayer.getPlaylist();
        var jsItem = jsPlaylist[0];
        
        if(typeof(jsItem) === 'object') {
            player.setPlayTime(jsItem['duration']);
        }
        
        if(this.is_reload){
            if((this.index_before_reload === 0 && (this.isJumpBySid() && this.before_sid > 0) && 
                this.current_position === 0 && !this.is_play_next) || !this.jwplayer){
                this.is_reload = false;
                return false;
            }
            
            var resetReloadFlag = true;
            if(this.index_before_reload !== 0 || (this.isJumpBySid() && this.before_sid > 0)){
                
                if (this.playlist_loaded){
                    var jump_to_index = this.index_before_reload;
                    if(this.isJumpBySid() && this.before_sid > 0){
                        tmp_index = music_playlist.getIndexInCurrentPlaylist(this.before_sid);
                        if(tmp_index !== false){
                            if(this.is_play_next){
                                jump_to_index = tmp_index+1;
                            }
                            else{
                                jump_to_index = tmp_index;
                            }
                            if(jump_to_index > music_playlist.getTotalInCurrentPlaylist()){
                                jump_to_index = 0;
                            }
                        }
                    }

                    this.jwplayer.playlistItem(jump_to_index);
                    var playlist = $('#'+player.div_playlist_id);
                    var playlistItem = 0;
                    playlist.children().each(function(){
                        if(playlistItem === jump_to_index){
                            $(this).find('a.name').trigger('click');
                        }
                        playlistItem++;
                    });
                    this.index_before_reload = 0;
                    this.clearJumpBySid();
                    this.before_sid = 0;
                    this.is_play_next = true;
                    
                    jsItem = jsPlaylist[jump_to_index];
                    
                    if(typeof(jsItem) === 'object') {
                        player.setPlayTime(jsItem['duration']);
                    }
                } else {
                    resetReloadFlag = false;
                    setTimeout(function(){player.afterReloadPlaylist();}, 150);
                }
            }
            
            if(this.current_position !== 0 && resetReloadFlag){
                this.jwplayer.seek(this.current_position);
                this.current_position = 0;
            }
            if(resetReloadFlag){
                this.is_reload = false;
            }
        }
    },
    // set need load
    setNeedReload: function(){
        $.cookie('need_reload', true, {path:'/'});
    },
    setNeedReloadForCurrentPage: function(){
        player.need_reload = true;
    },
    test2: function(){
        alert('test2');
        alert(this.jwplayer.getPosition());
        //this.jwplayer.stop();
        //alert('test 2 - stop');
        this.jwplayer.playlistItem(2);
        //this.jwplayer.play();
        this.jwplayer.seek(20);
    },
    
    jumpToSong: function(item){
        this.flashplayer.sendEvent("ITEM",item);
        return false;
    },

    createPlayer: function(servername, filepath) {
        var flashvars = {
            file:filepath,  
            autostart:"true",
            repeat:"always"
        };

        var params = {
            allowfullscreen:"true", 
            allowscriptaccess:"always",
            menu: "false",
            wmode:"transparent"
        };

        var attributes = {
            id:"song_player",  
            name:"song_player"
        };
        swfobject.embedSWF("http://"+servername+"/players/player.swf?skin=http://"+servername+"/players/five.swf", "song_player", "460", "24", "9.0.115", false, flashvars, params, attributes, player.flashLoaded);
    },
    createPlayer2: function(servername, filepath) {
        jwplayer("song_player").setup({
            flashplayer: "http://"+servername+"/players/player.swf?skin=http://"+servername+"/players/five.swf",
            file: filepath,
            height: 24,
            width: 460,
            autostart:"true",
            repeat:"always",
            controlbar:"bottom",
            events: {
                onReady: function() {
                    makeOuterHtml();
                    player.jwplayer = jwplayer();
                    player.afterReloadPlaylist();
                },
                onComplete: function(){
                    //if(player.need_reload){
                    if(player.isNeedReload()){
                        player.callReload();
                        return true;
                    }
                }
            }
        });
    },
    createGiftPlayer: function(servername, filepath, did) {
        jwplayer(did).setup({
            flashplayer: "http://"+servername+"/players/player.swf?skin=http://"+servername+"/players/five.swf",
            file: filepath,
            height: 24,
            width: 250,
            autostart:"true",
            repeat:"always",
            controlbar:"bottom",
            events: {
                onReady: function() {
                    makeOuterHtml();
                    //player.jwplayer = jwplayer();
                },
                onComplete: function(){}
            }
        });
    },
    createRadioPlayer: function(filepath, did, w) {
        var flashvars = {
            file:filepath,
            type:"sound",
            provider:"sound",
            autostart:"true", 
            repeat:"always",
            duration:999999,
            bufferlength:100
        };

        var params = {
            allowfullscreen:"true", 
            allowscriptaccess:"always",
            menu: "false"
        };

        var attributes = {
            id:"player1",  
            name:"player1"
        };
        
        swfobject.embedSWF("http://music.tamtay.vn/players/player.swf?skin=http://music.tamtay.vn/players/five.swf", did, w, "24", "9.0.115", false, flashvars, params, attributes);
    },
    flashLoaded: function(e){
        player.jwplayer = jwplayer(e.ref);
    },
    test: function(){
        if(!this.jwplayer){
            alert('flash not loaded');
        }
        else{
            alert(this.jwplayer.getPosition());
        }
            
    },
    next: function(){
        if(!this.jwplayer){
            alert('flash not loaded');
        }
        else{
            alert(this.jwplayer.playlistNext());
        }
            
    },
    item: function(index){
        if(!this.jwplayer){
            alert('flash not loaded');
        }
        else{
            alert(this.jwplayer.playlistNext(index));
        }
            
    },
    seek: function(p){
        if(!this.jwplayer){
            alert('flash not loaded');
        }
        else{
            alert(this.jwplayer.seek(p));
        }
            
    },
    addItemToPlaylist: function(newItem) {
        if(!this.jwplayer){
            alert('flash not loaded');
        }
        else{
            var playlist = this.jwplayer.getPlaylist();
            playlist.push(newItem);
            this.jwplayer.load(playlist);
        }
    }
    
};


try {
    var playlistReady = playerReady;
} catch (err){
}

playerReady = function(obj) {
    setTimeout(function(){player.checkPlaylistLoaded(obj);}, 1);
    try {
        playlistReady(obj);
    } catch (err){
    }
};
