﻿function VLCHTML(vlcDivID, width, height, novlcDivId) {

    var pageLoaded = false;

    /* PlayListo busenos */
    var suffle = false;
    var repeat = false;
    var repeatAll = false;
    var current = 0;
    var playlistID = 0;
    var PlaylistTable;
    var PenkiPlayListMode = false;
    var afterSwich = false;
    var dinamicalMode = false;
    var playOnlyMarked = false;
    var playOnlyUnMarked = false;
    /*-------------------*/

    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 vlc_vlcObjectFail() {
        //alert('vlc_vlcObjectFail');
        var novlcdivEl = document.getElementById(novlcDivId);
        if (novlcdivEl) {
            novlcdivEl.style.display = "block"
            document.getElementById(vlcDivID).style.position = "absolute";
        }
        
    }

    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.getRepeat = function() {
        return repeat;
    }
    
    this.getSuffle = function() {
        return suffle;
    }
    
    this.getRepeatAll = function() {
        return repeatAll;
    }

    this.setRepeat = function(value) {
        repeat = value;
        if (value == true) {
            suffle = !value;
            repeatAll = !value;
        }
    }

    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;
        }
    }

    this.setPlayOnlyMarked = function(value) {
        if (value) {
            playOnlyUnMarked = !value;
        }
        playOnlyMarked = value;
    }

    this.setPlayOnlyUnMarked = function(value) {
        if (value) {
            playOnlyMarked = !value;  
        }
        playOnlyUnMarked = value;
    }

    /*padiidnt grojima*/

    this.increasePlayCount = function(mediaID) {
        var r = new Date().getTime();
        var handlerAdr = '/Playlists/Handlers/PlaylistPlayHandler.ashx?Action=IncreasePlayCount&PlaylistID=' + playlistID + '&CurrentID=' + mediaID + '&r=' + r;
        $.getScript(handlerAdr, function() {
        });
        var rows = PlaylistTable.tBodies[0].rows;
        var i = 0;
        while (i < rows.length && rows[i].cells[0].id != mediaID ) {
            i++;
        }

        if (rows[i].cells[0].id == mediaID) {
            rows[i].cells[5].innerHTML = parseInt(rows[i].cells[5].innerHTML) + 1;
        }
    }



    /* Dainos pakeitimas is isores */

    this.GetCurrent = function()
    {
        return current;
    }

    this.PlaySong = function(mediaID, pID, playlistTable, markingMode) {

        if (current != 0) {
            //alert("in change");
            afterSwich = true;
        }

        if (!PenkiPlayListMode) {
            vlc.addEvent("PlayBackEnded", vlc_PlayEndeded);
            PenkiPlayListMode = true;
            playlistID = pID;
            PlaylistTable = playlistTable;
            dinamicalMode = false;
        }
        current = mediaID;
        if (!markingMode) {
            playOnlyMarked = false;
            playOnlyUnMarked = false;
        }
        this.increasePlayCount(mediaID);
        _this.setContent('rtsp://vvn1.penki.tv:8081/Video?' + mediaID, 'Video', false);
    }

    this.PlaySongInMode = function(mediaID, pID, playlistTable, markingMode) {
       // alert("dinplay");
        if (current != 0) {
         //   alert("in change");
            afterSwich = true;
        }

        if (!PenkiPlayListMode) {
            vlc.addEvent("PlayBackEnded", vlc_PlayEndeded);
            PenkiPlayListMode = true;
            PlaylistTable = playlistTable;
            playlistID = pID;
            dinamicalMode = true;
        }
        current = mediaID;
        if (!markingMode) {
            playOnlyMarked = false;
            playOnlyUnMarked = false;
        }
        this.increasePlayCount(mediaID);
        _this.setContent('rtsp://vvn1.penki.tv:8081/Video?' + mediaID, 'Video', false);
    }


    /* Groti sekancia daina */
    this.PlayNextPlayListItem = function() {
      //  alert("play");

        if (!PenkiPlayListMode) {
            vlc.addEvent("PlayBackEnded", vlc_PlayEndeded);
            PenkiPlayListMode = true;
        }
        _this = this;
        var r = new Date().getTime();
        var handlerAdr = '/Playlists/Handlers/PlaylistPlayHandler.ashx?Action=GetNext&Var=NextItem&PlaylistID=' + playlistID + '&CurrentID=' + current + '&r=' + r;
        if (playOnlyMarked) {
           // alert("marked only next");
            handlerAdr += "&SpecialPlayMode=Marked";
        }
        if (playOnlyUnMarked) {
          //  alert("unmarked marked only next");
            handlerAdr += "&SpecialPlayMode=UnMarked";
        }

        $.getScript(handlerAdr, function() {
           // alert(NextItem);
            if (NextItem) {
                current = NextItem;
                _this.increasePlayCount(current);
                _this.setContent('rtsp://vvn1.penki.tv:8081/Video?' + current, 'Video', false);
            }
            else {
               // alert("end");
            }
        });
    }

    /* Groti sekancia daina dinamiskai */
    this.PlayNextDinamicalPlayListItem = function() {
       // alert("playdin2");
        var seted = false;

        if (!PenkiPlayListMode) {
            vlc.addEvent("PlayBackEnded", vlc_PlayEndeded);
            PenkiPlayListMode = true;
        }

        var rows = PlaylistTable.tBodies[0].rows;

        if (repeat) {
            //  alert("repeta dinamic");
            _this.increasePlayCount(current);
            _this.setContent('rtsp://vvn1.penki.tv:8081/Video?' + current, 'Video', false);
            seted = true;
        }

        if (suffle) {
            var rand = Math.ceil(rows.length * Math.random())

            if (playOnlyMarked) {
                while (rand == current && rows[i].cells[6].firstChild.checked != 1) {
                    var rand = Math.ceil(rows.length * Math.random())
                }
            }

            if (playOnlyUnMarked) {
                while (rand == current && rows[i].cells[6].firstChild.checked != 0) {
                    var rand = Math.ceil(rows.length * Math.random())
                }
            }

            current = rows[rand].cells[0].id;
            this.increasePlayCount(current);
            _this.setContent('rtsp://vvn1.penki.tv:8081/Video?' + current, 'Video', false);
            seted = true;
        }

        if (rows[rows.length - 1].cells[0].id == current && repeatAll) {

            var i = 0;

            if (playOnlyMarked) {
                while (rows[i].cells[6].firstChild.checked == 0) {
                    i++;
                }
            }

            if (playOnlyUnMarked) {
                while (rows[i].cells[6].firstChild.checked == 1) {
                    i++;
                }
            }
            current = rows[i].cells[0].id;
            _this.increasePlayCount(current);
            _this.setContent('rtsp://vvn1.penki.tv:8081/Video?' + rows[i].cells[0].id, 'Video', false);
            seted = true;
        }

        if (!seted && (rows[rows.length - 1].id != current)) {
            var i = 0;
            while (i < rows.length && rows[i].cells[0].id != current) {
                i++;
            }

            i++;
         //   alert(i);

            if (playOnlyMarked) {
                while (rows[i].cells[6].firstChild.checked == 0) {
                    i++;
                }
            }

            if (playOnlyUnMarked) {
                while (rows[i].cells[6].firstChild.checked == 1) {
                    i++;
                }
            }

            if (i != rows.length) {
                current = rows[i].cells[0].id;
                _this.increasePlayCount(current);
              //  alert("seting "+ rows[i].cells[0].id);
                _this.setContent('rtsp://vvn1.penki.tv:8081/Video?' + rows[i].cells[0].id, 'Video', false);
              //  alert("seting2");
                seted = true;
            }
            else {
            }
        }

    }
    
    /*End of game */
    function vlc_PlayEndeded() {
  //      alert("end");
        if (!afterSwich) {
            if (dinamicalMode) {
                _this.PlayNextDinamicalPlayListItem();
            } else {
                _this.PlayNextPlayListItem();
            }
        }
        afterSwich = false;
    }

    /*isjungti playlista */
    this.closePlaylist = function() {
        if (inited) {
            if (!enabled) { return; }
            content = null;
            afterSwich = true;
            vlc.clearAndStop();
        }
    }

    /*Perjunkti daina atgal*/
    this.PlayPrev = function() {
    }

    /*Perjunkti daina pirmyn*/
    this.PlayNext = function() {
    }


    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);
    vlc.addEvent("vlcObjectFail", vlc_vlcObjectFail);
    
    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 && false) {
                    _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, playlistID) {
        var handlerAdr = '/Playlists/Handlers/GetPlayListHandler.ashx?var=PlaylistItems&optVar=PlayListOptions&playlistID=' + playlistID;
        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
            }
        }
    }
}
