﻿function VLCHTML(vlcDivID, width, height) {

    var pageLoaded = false;

    /* PlayListo busenos */
    var suffle = false;
    var repeat = false;
    var repeatAll = false;
    var current = 0;
    var PenkiPlayListMode = false;
    var afterSwich = true;
    /*-------------------*/

    HookEvent(window, "load", windowLoad);


    function windowUnload() {
        _this.close();
    }

    function windowLoad() {
        pageLoaded = true;
        if (inited) {
            initControls();
        }
    }

    function vlc_onInit() {
        inited = true;

        if (soundSlider) {
            soundSlider.enable();
        }

        if (progressSlider) {
            progressSlider.disable();
        }

        if (mediaControls) {
            mediaControls.style.display = 'block'
        }

        if (pageLoaded) {
            initControls();
        }
    }

    function initControls() {

        if (soundSlider) {
            var volume = parseInt(GetCookie("Media_VOLUME"));
            if (volume > -1 && volume < 101) {
                soundSlider.setValue(volume / 100);
            }
            else {
                soundSlider.setValue(vlc.getVolume() / 100);
            }
        }
        if (content) {
            _this.setContent(content.Uri, content.Name);
        }

    }

    
    function vlc_onStateChange() {
        state = vlc.getState();
        //document.getElementById("stateDIV").innerHTML = state;
        if (state == "playing") {
            if (soundSlider) {
                vlc.setVolume(soundSlider.getValue() * 100);
            }
            if (toggleMuteButtons) {
                if (toggleMuteButtons.getState() == 0) {
                    vlc.unmute();
                }
                else {
                    vlc.mute();
                }
            }

            if (totalTime > 0) {
                startProgressInterval();
            }
            if (playControlButtons) {
                playControlButtons.setState(1);
            }

        }
        else if (state == "standby") {
            playTime = 0;
            stopProgressInterval()
            vlc_showProgress(0, totalTime);
            if (playControlButtons) {
                playControlButtons.setState(0);
            }
            if (content) {
                _this.setContent(content.Uri, content.Name);
            }
        }
        else {
            if (playControlButtons) {
                playControlButtons.setState(0);
            }
        }
    }


    function vlc_inputLengthChange() {
        totalTime = vlc.getLength();
        if (totalTime > 0) {
            if (state == "playing") {
                playTime = 0;
                startProgressInterval();
            }
        }
        else {
            stopProgressInterval()
            
        }
        vlc_showProgress(playTime, totalTime);
    }

    function startProgressInterval() {
        stopProgressInterval()
        timer = new Date();
        proggressIntervalID = window.setInterval(progressIntervalTimeout, 1000);
        if (progressSlider && seekEnabled) {
            progressSlider.enable();
        }
        
    }

    function stopProgressInterval() {
        if (proggressIntervalID > -1) {
            window.clearInterval(proggressIntervalID);
            proggressIntervalID = -1;
            if (progressSlider) {
                progressSlider.disable();
            }
        }
    }

    function progressIntervalTimeout() {
        if (state != "playing") {
            stopProgressInterval();
            if (state == "pause") {
                if (progressSlider && seekEnabled) {
                    progressSlider.enable();
                }
            }
            return;
        }
        playTime += (new Date()).getTime() - timer.getTime();
        vlc_showProgress(playTime, totalTime);
        timer = new Date();
    }


    function vlc_showProgress(time, total) {
        if (total > 0 && total > time) {
            if (progressSlider && !progressSlider.isDraging) {
                progressSlider.setValue(time / total);
            }
        }
        else {
            stopProgressInterval();
            progressSlider.setValue(0);
        }
        //document.getElementById("progressDIV").innerHTML = formatTime(current) + "/" + formatTime(total) + ' (' + (new Date()) + ')';
    }

    /*Playlisto setingu valdymas */

    this.setRepeat = function(value) {
        repeat = value;
        if(value == true)
        {
            suffle = !value;
            repeatAll = !value;
        }
    }

    this.getRepeat = function() {
        return repeat;
    }
    
    this.getSuffle = function() {
        return suffle;
    }
    
    this.getRepeatAll = function() {
        return repeatAll;
    }

    this.setSuffle = function(value) {
        suffle = value;
        if(value == true)
        {
            repeat = !value;
            repeatAll = !value;
        }
    }

    this.setRepeatAll = function(value) {
        repeatAll = value;
        if(value == true)
        {
            repeat = !value;
            suffle = !value;
        }
    }
    

    /* Dainos pakeitimas is isores */

    this.SwichSongs = function(position) {
        current = position-1;
        afterSwich = true;
        _this.setContent(PlaylistItems[current], 'Video', false);
    }

    /* Groti sekancia daina */
    this.PlayNextPlayListItem = function() {
        var seted = false;
        if (suffle && !afterSwich) {
            var rand = Math.ceil(PlaylistItems.length * Math.random())
            while (rand == current) {
                var rand = Math.ceil(PlaylistItems.length * Math.random())
            }
            current = rand;
            _this.setContent(PlaylistItems[current], 'Video', false);
            seted = true;
        }
        if (repeat && !seted && !afterSwich) {
            _this.setContent(PlaylistItems[current], 'Video', false);
            seted = true;
        }
        if ((PlaylistItems.length == current + 1) && repeatAll && !seted && !afterSwich) {
            current = 0;
            _this.setContent(PlaylistItems[current], 'Video', false);
            seted = true;
        }
        if (!seted && !afterSwich && (PlaylistItems.length > current + 1)) {
            current++;
            _this.setContent(PlaylistItems[current], 'Video', false);
            seted = true;
        }
        afterSwich = false;
    }
    
    /*End of game */
    function vlc_PlayEndeded() {
        _this.PlayNextPlayListItem();
    }


    function formatTime(timeVal) {
        var timeHour = Math.round(timeVal / 1000);
        var timeSec = timeHour % 60;
        if (timeSec < 10)
            timeSec = '0' + timeSec;
        timeHour = (timeHour - timeSec) / 60;
        var timeMin = timeHour % 60;
        if (timeMin < 10)
            timeMin = '0' + timeMin;
        timeHour = (timeHour - timeMin) / 60;
        if (timeHour > 0)
            return timeHour + ":" + timeMin + ":" + timeSec;
        else
            return timeMin + ":" + timeSec;

    }

    function SetCookie(name, value, expires, path, domain, secure) {
        // set time, it's in milliseconds
        var today = new Date();
        today.setTime(today.getTime());

        /*
        if the expires variable is set, make the correct 
        expires time, the current script below will set 
        it for x number of days, to make it for hours, 
        delete * 24, for minutes, delete * 60 * 24
        */
        if (expires) {
            expires = expires * 1000 * 60 * 60 * 24;
        }
        var expires_date = new Date(today.getTime() + (expires));

        document.cookie = name + "=" + escape(value) +
        ((expires) ? ";expires=" + expires_date.toGMTString() : "") +
        ((path) ? ";path=" + path : "") +
        ((domain) ? ";domain=" + domain : "") +
        ((secure) ? ";secure" : "");
    }



    function GetCookie(check_name) {
        // first we'll split this cookie up into name/value pairs
        // note: document.cookie only returns name=value, not the other components
        var a_all_cookies = document.cookie.split(';');
        var a_temp_cookie = '';
        var cookie_name = '';
        var cookie_value = '';
        var b_cookie_found = false; // set boolean t/f default f

        for (i = 0; i < a_all_cookies.length; i++) {
            // now we'll split apart each name=value pair
            a_temp_cookie = a_all_cookies[i].split('=');


            // and trim left/right whitespace while we're at it
            cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

            // if the extracted name matches passed check_name
            if (cookie_name == check_name) {
                b_cookie_found = true;
                // we need to handle case where cookie has no value but exists (no = sign, that is):
                if (a_temp_cookie.length > 1) {
                    cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
                }
                // note that in cases where cookie is initialized but no value, null is returned
                return cookie_value;
                break;
            }
            a_temp_cookie = null;
            cookie_name = '';
        }
        if (!b_cookie_found) {
            return null;
        }
    }

    function DeleteCookie(name, path, domain) {
        if (ReportWebControlsGetCookie(name)) document.cookie = name + "=" +
        ((path) ? ";path=" + path : "") +
        ((domain) ? ";domain=" + domain : "") +
        ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
    }    
    var _this = this;

    var playTime = 0;
    var totalTime = 0;
    var timer = new Date();
    var proggressIntervalID = -1;
    var state = "standby";
    var drawed = false;
    var playControlButtons = null;
    var toggleMuteButtons = null;
    var progressSlider = null;
    var soundSlider = null;

    var inited = false;
    var seekEnabled = true;

    var vlcDiv = document.getElementById(vlcDivID);
    var mediaControls = null;

    var content = null;

    var enabled = true;

    var vlc = new VLCPlayer();
    vlc.setAttribute("width", width);
    vlc.setAttribute("height", height);
    vlc.addEvent("init", vlc_onInit);
    vlc.addEvent("stateChange", vlc_onStateChange);
    vlc.addEvent("inputLengthChange", vlc_inputLengthChange);
    
    var fistSource;
    var keepPlayInterval = null;

    this.addEvent = function(eventName, callBack) {
        if (!enabled) { return; }
        vlc.addEvent(eventName, callBack);
    }

    this.removeNode = function() {
        if (!enabled) { return; }
        vlc.removeNode();
    }

    this.getState = function() {
        return state;
    }
    
    

    this.setContent = function(uri, name, showFirst) {
        if(showFirst != undefined) {
            _this.fistSource = showFirst;
        }
        if (!enabled) { return; }
        content = new Object();
        content.Uri = uri;
        content.Name = name;
        
        if (inited) {
        
            vlc.clear();
            vlc.stop();
            
            if (state == "standby" || state == "erreur") {
                var id, id2;
                var all = false;
                
                if(_this.fistSource) 
                {           
                    _this.fistSource = false;
                    vlc.addSource("http://mediaplayer.penki.lt/flashplayer/PenkiTV_idomiam_laisvalaikiui.flv", "Advertisment");
                    vlc.addSource(content.Uri, content.Name);
                    all = true;
                }
                else
                {
                    id = vlc.addSource(content.Uri, content.Name);
                    all = false;
                }
                stopProgressInterval();
                totalTime = 0;
                playTime = 0;
                if (all)
                {
                    vlc.play();
                }
                else
                {
                    vlc.playItem(id);
                }
                //vlc_showProgress(playTime, totalTime);
                content = null;
                delete content;
            }
        }
        if (!drawed) {
            this.draw();
        }
    }

    this.disable = function() {
        enabled = false;
    }

    this.close = function() {
        if (inited) {
            if (!enabled) { return; }
            content = null;
            vlc.clearAndStop();
        }
    }


    this.enableSeek = function() {
        if (!seekEnabled) {
            seekEnabled = true;
        }
    }

    this.disableSeek = function() {
        if (seekEnabled) {
            seekEnabled = false;
            if (progressSlider) {
                progressSlider.disable();
            }
        }
    }

//////////////////////////////////////////////////////////////////////


    this.populatePlayList = function(itemToPlay) {
        var handlerAdr = '/Playlists/Handlers/GetPlayListHandler.ashx?var=PlaylistItems&optVar=PlayListOptions';
        var _this = this;
        var vlcIn = vlc;
        $.getScript(handlerAdr, success);
        function success() {
            _this.setSuffle(PlayListOptions[0]);
            _this.setRepeat(PlayListOptions[1]);
            _this.setRepeatAll(PlayListOptions[2]);
            vlcIn.addEvent("PlayBackEnded", vlc_PlayEndeded);             ///////////Playlist events
            current = itemToPlay;
            _this.setContent(PlaylistItems[itemToPlay], 'Video', true);
        }
    }
    
///////////////////////////////////////////////////////////////////////
    this.draw = function() {
        if (!enabled) { return; }
        if (!drawed) {
            enabled = vlc.write(vlcDiv);
            drawed = true;
        }
    }

    this.initPlayControlButtons = function(buttons) {
        if (!enabled) { return; }
        if (playControlButtons == null) {
            playControlButtons = buttons;
            HookEvent(playControlButtons.owner, "click", playControlButtons_click);
        }
    }

    this.initProgressSlider = function(slider) {
        if (!enabled) { return; }
        if (progressSlider == null) {
            progressSlider = slider;
            progressSlider.addEvent("stopDrag", progressChangeEnd);
        }
    }
    this.initSoundSlider = function(slider) {
        if (!enabled) { return; }
        if (soundSlider == null) {
            soundSlider = slider;
            soundSlider.addEvent("change", soundChange);
            soundSlider.addEvent("stopDrag", soundChangeEnd);
        }
    }
    

    this.initToggleMuteButtons = function(buttons) {
        if (!enabled) { return; }
        if (toggleMuteButtons == null) {
            toggleMuteButtons = buttons;
            HookEvent(toggleMuteButtons.owner, "click", toggleMuteButtons_click);
        }
    }

    this.setControlsBar = function(elementID) {
        if (!enabled) { return; }
        mediaControls = document.getElementById(elementID);
    }

    function soundChange() {
        if (!enabled) { return; }
        vlc.setVolume(Math.round(soundSlider.getValue() * 100));
        drawMute();
    }

    function soundChangeEnd() {
        SetCookie("Media_VOLUME", vlc.getVolume() + '', 100);
    }

    function drawMute() {
        if (!enabled) { return; }
        if (toggleMuteButtons) {
            if (vlc.isMuted()) {
                toggleMuteButtons.setState(1);
            }
            else {
                toggleMuteButtons.setState(0);
            }
        }
    }

    function progressChangeEnd() {
        if (!enabled) { return; }
        vlc.setPosition(progressSlider.getValue());
        playTime = vlc.getTime();
        if (state != "playing") {
            vlc.togglePause();
        }
    }

    function playControlButtons_click() {
        if (state == "playing" && totalTime == 0) {
            vlc.stop();
            return;
        }
        vlc.togglePause();
    }
    function toggleMuteButtons_click() {
        if (!enabled) { return; }
        vlc.toggleMute();
        SetCookie("Media_VOLUME_MUTED", vlc.isMuted() + '', 100);
        drawMute()
    }

    function HookEvent(element, eventName, callback) {
        if (typeof (element) == "string")
            element = document.getElementById(element);
        if (element == null)
            return;
        if (element.addEventListener) {
            element.addEventListener(eventName, callback, false);
        }
        else if (element.attachEvent)
            element.attachEvent("on" + eventName, callback);
    }
    
    
}
VLCHTML.buttons = function(ownerID, tagName) {
    this.owner = document.getElementById(ownerID);
    this.states = this.owner.getElementsByTagName(tagName);
    var state = 0;

    this.setState = function(newState) {
        if (newState != state) {
            var i;
            for (i = 0; i < this.states.length; i++) {
                this.states[i].style.display = 'none';
            }
            state = newState;
            this.states[state].style.display = 'block';
        }
    }
    this.getState = function() {
        return state;
    }
}

VLCHTML.slider = function(backgroundID, thumbID, mode) {
    this.background = document.getElementById(backgroundID);
    this.thumb = document.getElementById(thumbID);

    this.events = new Object();

    var _this = this;

    var enabled = false;
    var value = 0;

    var backgroundWidth = 0;
    var backgroundLeft = 0;


    this.isDraging = false;


    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.getValue = function() {
        return value;
    }
    this.setValue = function(val) {
        if (val < 0) val = 0;
        if (val > 1) val = 1;
        if (!(val >= 0) && !(val <= 1)) val = 0
        value = val;
        draw_value();
    }


    this.enable = function() {
        if (!enabled) {
            if (mode == 'progressLine') {
                HookEvent(this.background, "mousedown", slider_mousedown);
                enabled = true;
            }
            else {
                alert("unknown mode: " + mode);
            }
        }
    }
    this.disable = function() {
        if (enabled) {
            if (mode == 'progressLine') {
                UnhookEvent(this.background, "mousedown", slider_mousedown);
                enabled = false;
            }
            else {
                alert("unknown mode: " + mode);
            }
        }
    }


    function slider_mousedown(e) {
        if (mode == 'progressLine') {
            HookEvent(document, "mouseup", slider_mouseup);
            _this.isDraging = true;
            _this.raiseEvent("startDrag");
        }
        HookEvent(document, "mousemove", slider_mouseMove);
        slider_mouseMove(e);
        cacelEvent(e);
    }
    function slider_mouseup(e) {
        _this.isDraging = false;
        if (mode == 'progressLine') {
            UnhookEvent(document, "mouseup", slider_mouseup);
            _this.raiseEvent("stopDrag");
        }
        UnhookEvent(document, "mousemove", slider_mouseMove);
        cacelEvent(e);
    }

    function draw_slider(x, y) {
        if (mode == 'progressLine') {
            value = Math.max(0, Math.min(1, (x - getBackgroundLeft()) / getBackgroundWidth()));
            _this.raiseEvent("change");
            draw_value();
        }
    }



    function draw_value() {
        if (mode == 'progressLine') {
            var bgWidth = getBackgroundWidth()
            if (bgWidth > 0) {
                _this.thumb.style.width = Math.max(1, Math.round(value * getBackgroundWidth())) + 'px';
            }

        }
    }

    function getBackgroundWidth() {
        if (backgroundWidth > 0) {
            return backgroundWidth;
        }
        backgroundWidth = _this.background.offsetWidth;
        return backgroundWidth;
    }

    function getBackgroundLeft() {
        if (backgroundLeft > 0) {
            return backgroundLeft;
        }
        backgroundLeft = GetNodeLeft(_this.background, null);
        return backgroundLeft;
    }


    function slider_mouseMove(e) {
        draw_slider(e.clientX, e.clientY);
    }
    function GetNodeLeft(node, parentNode) {
        var returnValue = Number.MIN_VALUE;
        if (node) {
            returnValue = node.offsetLeft;
            if (parentNode || parentNode == null) {
                node = node.offsetParent;
                while (node && node != parentNode) {
                    returnValue += node.offsetLeft;
                    node = node.offsetParent;
                }
            }
        }
        return returnValue;
    }
    function HookEvent(element, eventName, callback) {
        if (typeof (element) == "string")
            element = document.getElementById(element);
        if (element == null)
            return;
        if (element.addEventListener) {
            element.addEventListener(eventName, callback, false);
        }
        else if (element.attachEvent)
            element.attachEvent("on" + eventName, callback);
    }
    function UnhookEvent(element, eventName, callback) {
        if (typeof (element) == "string")
            element = document.getElementById(element);
        if (element == null)
            return;
        if (element.removeEventListener)
            element.removeEventListener(eventName, callback, false);
        else if (element.detachEvent)
            element.detachEvent("on" + eventName, callback);
    }

    function cacelEvent(e) {
        if (e) {
            if (e.preventDefault) {
                e.preventDefault(); // Mozilla and Opera
            }
            else {
                e.cancelBubble = true; // IE and Opera
                e.returnValue = false; // IE and Opera
            }
        }
    }
}