﻿function VLCPlayer() {
    var ver = "0.8.6"

    var target = null;
    var state = 0;
    var time = 0;
    var length = 0;    
    var stateTimeoutID = -1;
    var playlistItemsID = new Array();
    this.events = new Object();
    this.defaultName = 'Penki TV';
    var _this = this;





    this.getLength = function() {
        return length;
    }
    this.getTime = function() {
        return time;
    }

    this.getState = function() {
        return VLCPlayer.Status[state];
    }

    this.setAttribute = function(name, value) {
        this.attributes[name] = value;
    }
    this.addEvent = function(name, callBack) {
        if (!this.events[name]) {
            var array = new Array();
            this.events[name] = array;
            array.push(callBack);
        }
        else {
            this.events[name].push(callBack);
        }
    }
    this.removeEvent = function(name, callBack) {
        if (this.events[name]) {
            var array = this.events[name];
            var i = 0;
            for (i = 0; i < array.length; i++) {
                if (array[i] == callBack) {
                    break;
                }
            }
            if (i < array.length) {
                array.splice(i, 1);
                if (array.length == 0) {
                    delete this.events[name];
                }
            }
        }
    }
    this.raiseEvent = function(name) {
        var array = this.events[name];
        if (array) {
            var i;
            for (i = 0; i < array.length; i++) {
                try {
                    array[i]();
                }
                catch (e) { }
            }
        }
    }
    
    
    this.getAttribute = function(name) {
        return this.attributes[name] || "";
    }
    this.addParam = function(name, value) {
        this.params[name] = value;
    }
    this.getParams = function() {
        return this.params;
    }
    this.addVariable = function(name, value) {
        this.variables[name] = value;
    }
    this.getVariable = function(name) {
        return this.variables[name] || "";
    }
    this.getVariables = function() {
        return this.variables;
    }
    this.getVariablePairs = function() {
        var variablePairs = [];
        var key;
        var variables = this.getVariables();
        for (key in variables) {
            variablePairs[variablePairs.length] = key + "=" + variables[key];
        }
        return variablePairs;
    }
    this.addSource = function(url, name, options) {
        var opt;
        var playlist = this.getPlaylist();
        if (playlist) {
            try {
                if (!options) {
                    opt = ':no-video-title-show';
                }
                else {
                    opt = options;
                }
                var id = playlist.add(url, 'Penki TV', opt);
                playlistItemsID.push(id);
                return id;
            }
            catch (e) { this.traceError(e) }
        }
        return null;
    }

    this.playItem = function(id) {
        var playlist = this.getPlaylist();
        if (playlist) {
            try {
                playlist.playItem(id);
            }
            catch (e) { this.traceError(e) }
            if (length > 0) {
                length = 0;
                _this.raiseEvent("inputLengthChange");
            }
            stopUpdateStateTimeout();
            startUpdateStateTimeout();
        }
    }


    this.play = function() {
        var playlist = this.getPlaylist();
        if (playlist) {
            try {
                playlist.play();
            }
            catch (e) { this.traceError(e) }
            if (length > 0) {
                length = 0;
                _this.raiseEvent("inputLengthChange");
            }
            stopUpdateStateTimeout();
            startUpdateStateTimeout();
        }
    }

    this.clearAndStop = function() {
        this.clear();
        this.stop();
    }

    this.removeNode = function() {
        this.stop();
        this.clear();
        if (target) {
            target.parentNode.removeChild(target);
        }
    }
    

    this.stop = function() {
        var playlist = this.getPlaylist();
        if (playlist) {
            if (state != 0) {
                try {
                    playlist.stop()
                }
                catch (e) { this.traceError(e) }
            }
        }
    }

    this.getPlaylist = function() {
        if (target) {
            if (target.playlist) {
                return target.playlist;
            }
            else {
                alert('no playlist');
            }
        }
        else {
            alert('no target');
        }
        return null;
    }

    this.togglePause = function() {
        var playlist = this.getPlaylist();
        if (playlist) {
            try {
                if (state == 0) {
                    this.play();
                }
                else {
                    playlist.togglePause()
                }
            }
            catch (e) { this.traceError(e) }
        }
    }

    this.clear = function() {
        var playlist = this.getPlaylist();
        if (playlist) {
            try {
                if (playlist.items.count > 0) {
                    playlist.items.clear();
                }
            }
            catch (e) { this.traceError(e) }
        }
    }

    this.getPlaylistCount = function() {
        var playlist = this.getPlaylist();
        if (playlist) {
            try {
                return playlist.items.count
            }
            catch (e) { this.traceError(e) }
        }
    }
    

    this.setVolume = function(volume) {
        if (target && target.audio) {
            try {
                target.audio.volume = volume;
            }
            catch (e) { this.traceError(e) }
        }
        else { this.trace("no target or audio"); }
    }

    this.getVolume = function() {
        if (target && target.audio) {
            try {
                return target.audio.volume;
            }
            catch (e) { this.traceError(e) }
        }
        else { this.trace("no target or audio"); }
        return -1;
    }

    this.toggleMute = function() {
        if (target && target.audio) {
            try {
                return target.audio.toggleMute();
            }
            catch (e) { this.traceError(e) }
        }
        else { this.trace("no target or audio"); }
        return -1;
    }
    this.mute = function() {
        if (target && target.audio) {
            try {
                return target.audio.mute = true;
            }
            catch (e) { this.traceError(e) }
        }
        else { this.trace("no target or audio"); }
        return -1;
    }
    this.unmute = function() {
        if (target && target.audio) {
            try {
                return target.audio.mute = false;
            }
            catch (e) { this.traceError(e) }
        }
        else { this.trace("no target or audio"); }
        return -1;
    }

    this.isMuted = function() {
        if (target && target.audio) {
            try {
                return target.audio.mute;
            }
            catch (e) { this.traceError(e) }
        }
        else { this.trace("no target or audio"); }
        return -1;
    }

    this.getInput = function() {
        if (target) {
            if (target.input) {
                return target.input
            }
            else {
                alert('no input');
            }
        }
        else {
            alert('no target')
        }
        return null;
    }

    this.setPosition = function(value) {
        var input = this.getInput()
        if (input) {
            try {
                input.position = value;
            }
            catch (e) { _this.traceError(e) }
        }
    }

    this.getTime = function() {
        var input = this.getInput()
        if (input) {
            try {
                return input.time;
            }
            catch (e) { _this.traceError(e) }
        }
    }

    this.traceError = function(e) {
        if (typeof e == 'string') {
            this.trace(e);
            return;
        }
        var a;
        var msg = "Error\n";
        for (a in e) {
            msg += "\n" + a + ": " + e[a];
        }
        this.trace(msg);
    }

    this.trace = function(msg) {
        //alert(msg);
    }

    this.getVLCHTML = function() {
        var vlcNode = "";
        if (navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length) { // netscape plugin architecture
            vlcNode = '<embed type="application/x-vlc-plugin" " pluginspage="http://www.videolan.org" version="VideoLAN.VLCPlugin.2" width="' + this.getAttribute('width') + '" height="' + this.getAttribute('height') + '" style="' + (this.getAttribute('style') || "") + '"';
            vlcNode += ' id="' + this.getAttribute('id') + '" name="' + this.getAttribute('id') + '" ';
            var params = this.getParams();
            for (var key in params) { vlcNode += [key] + '="' + params[key] + '" '; }
            vlcNode += ' ShowDisplay="False" ';
            var pairs = this.getVariablePairs().join("&");
            vlcNode += '/>';
        } else { // PC IE
            vlcNode = '<object id="' + this.getAttribute('id') + '"  codebase="http://downloads.videolan.org/pub/videolan/vlc/latest/win32/axvlc.cab"  classid="clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921" width="' + this.getAttribute('width') + '" height="' + this.getAttribute('height') + '" style="' + (this.getAttribute('style') || "") + '">';
            var params = this.getParams();
            for (var key in params) {
                vlcNode += '<param name="' + key + '" value="' + params[key] + '" />';
                
            }
            vlcNode += '<param name="ShowDisplay" value="False" />';
            vlcNode += "</object>";
        }
        return vlcNode;
    }
    this.write = function(elementId) {

        if (!target) {
            if (this.installedVer.versionIsValid(this.getAttribute('version'))) {
                var n = (typeof elementId == 'string') ? document.getElementById(elementId) : elementId;
                n.innerHTML = this.getVLCHTML();
                //trick for IE activex
                target = n.firstChild;

                if (document.all) {
                    target.style.width = this.attributes["width"] + "px";
                    target.style.height = this.attributes["height"] + "px";
                }
                setTimeout(chekInit,250);
                return true;
            } else {
                var n = (typeof elementId == 'string') ? document.getElementById(elementId) : elementId;
                n.innerHTML = "<div style='width:" + this.attributes["width"] + "px;height:" + this.attributes["height"] + "px;border:0px solid red;padding:0px'>Your VLC plugin has not been detected !<br><br>please go to <a href='http://www.videolan.org' target='_blank'>http://www.videolan.org</a> to download your plugin.</div>";
                return false;
            }
        }
        return true;
    }


    function chekInit() {
        if (target.playlist) {
            _this.raiseEvent("init");
        }
        else {
            setTimeout(chekInit, 250);
        }
    }
    
    function playNextItem() {
        if(playlistItemsID.length > 1) {
            var playlist = _this.getPlaylist();
            length = 0;
            _this.playItem(playlistItemsID[1]);
            playlist.removeItem(playlistItemsID[0]);                    
            playlistItemsID.splice(0, 1);
        }
    } 

    function updateState() {
        stateTimeoutID = -1;
        
        var input = _this.getInput();   
        if (input) {
            try 
            {
                var newState = input.state;
                if (newState == 6) {
                    _this.raiseEvent("PlayBackEnded");
                    newState = 0;
                }
                if (state != newState) 
                {
                    if(newState == 0 || newState == 6) {
                        var playlist = _this.getPlaylist();
                        if (playlist.items.count > 1) {
                            setTimeout(playNextItem, 1000);
                            state = newState;
                            return;
                        }
                    }
                    state = newState;
                    _this.raiseEvent("stateChange");
                    if (state == 0) 
                    {
                        return;
                    }
                }
            }
            catch (e) { _this.traceError(e); }
            if (length == 0 && input != null)
            {
                try {
                    var newLength = input.length;
                    if (newLength != length) {
                        length = newLength;
                        _this.raiseEvent("inputLengthChange");
                    }
                }
                catch (e) { 
                    //_this.traceError(e);
                    stopUpdateStateTimeout();
                }
            }
            startUpdateStateTimeout();
        }
    }

    function startUpdateStateTimeout() {
        window.setTimeout(updateState, 200);
    }
    function stopUpdateStateTimeout() {
        if (stateTimeoutID > -1) {
            window.clearTimeout(stateTimeoutID);
            stateTimeoutID = -1;
        }
    }

    this.params = {};
    this.variables = {};
    this.attributes = [];
    this.setAttribute('version', new VLCPlayer.PlayerVersion(ver.toString().split(".")));
    this.installedVer = VLCPlayer.getPlayerVersion();
}
VLCPlayer.PlayerVersion = function(arrVersion) {
    this.major = arrVersion[0] != null ? parseInt(arrVersion[0]) : 0;
    this.minor = arrVersion[1] != null ? parseInt(arrVersion[1]) : 0;
    this.rev = arrVersion[2] != null ? parseInt(arrVersion[2]) : 0;
    this.versionIsValid = function(fv) {
        if (this.major < fv.major) return false;
        if (this.major > fv.major) return true;
        if (this.minor < fv.minor) return false;
        if (this.minor > fv.minor) return true;
        if (this.rev < fv.rev) return false;
        return true;
    }
    this.getInfo = function() {
        return this.major + '.' + this.minor + '.' + this.rev
    }
}

VLCPlayer.playerVersion = null;

VLCPlayer.getPlayerVersion = function() {
    if (!VLCPlayer.playerVersion) {
        var PlayerVersion = new VLCPlayer.PlayerVersion([0, 0, 0]);
        if (navigator.plugins && navigator.mimeTypes.length) {
            var x = navigator.plugins["VLC Multimedia Plug-in"];
            if (!x) {
                // test with "old" plugin name
                x = navigator.plugins["VLC Multimedia Plugin"];
            }
            if (!x) {
                // 0.8.6a at least
                x = navigator.plugins["VLC multimedia plugin"];
            }

            if (x && x.description) {
                PlayerVersion = x.description.substring(0, x.description.indexOf(","));
                PlayerVersion = PlayerVersion.replace("Version ", "");
                PlayerVersion = new VLCPlayer.PlayerVersion(PlayerVersion.split("."));
            }


        } else { // Win IE
            var versionInfo = null;
            try {
                var axo = new ActiveXObject("VideoLAN.VLCPlugin.2");
                versionInfo = axo.versionInfo
            } catch (e) {
                try {
                    var axo = new ActiveXObject("VideoLAN.VLCPlugin.1");
                    versionInfo = axo.versionInfo
                } catch (e) {

                }

            }
            if (versionInfo) {
                var versions = versionInfo.split('.');
                if (versions.length > 2) {
                    PlayerVersion = new VLCPlayer.PlayerVersion([parseInt(versions[0]), parseInt(versions[1]), parseInt(versions[2])]);
                }
            }
        }
        VLCPlayer.playerVersion = PlayerVersion;
    }
    return VLCPlayer.playerVersion;
}
VLCPlayer.Status = new Array("standby", "ouverture", "buffering", "playing", "pause", "stop", "erreur")
VLCPlayer.Options = function() {
    // better options management
    this.options = new Array();

    this.set = function(name, value) {
        this.options[name] = value || null;
    }

    this.del = function(name) {
        delete this.options[name];

    }

    this.get = function(name) {
        return this.options[name];
    }

    this.clear = function() {
        this.options = new Array();
    }

    this.format_for_vlc = function() {
        var tmp_array = new Array();
        var debug_str = "";
        var idx = 0;
        for (var i in this.options) {
            var option_str = ":" + i;
            if (this.options[i]) option_str += "=" + this.options[i];
            tmp_array[idx] = option_str;
            debug_str += option_str + " ";
            idx += 1;
        }
        return debug_str;
    }
}

