﻿function findPosX(obj)
{
  var curleft = 0;
  if (obj.offsetParent)
  {
    while (obj.offsetParent)
    {
      curleft += obj.offsetLeft
      obj = obj.offsetParent;
    }
  }
  else if (obj.x)
    curleft += obj.x;

  return curleft;
}

function findPosY(obj)
{
  var curtop = 0;
  if (obj.offsetParent)
  {
    while (obj.offsetParent)
    {
      if (obj.style.position != "relative")
        curtop += obj.offsetTop;
      obj = obj.offsetParent;
    }
  }
  else if (obj.y)
    curtop += obj.y;

  return curtop;
}

PlayListItem = function(seq, id, w, h, clipName)
{
  this._id = id;
  this._w = (w) ? w : 425;
  this._h = (h) ? h : 356;
  this._clipName = clipName;
  this._seq      = seq;
  this._isPlayed = false;
  this._playedIterations = 0;
  this._isBad = false;
}

MyYTPlayer = function (mainLayoutId, containerId, playerId, introId, 
                       loadingPanelId, errorPanelId, divClipNameId, divCategoriesId,
                       divPopupBlockerId)
{
  this._curPlayListItem = null;

  this._playList         = new Array();
  this._playListSequence = new Array();
  this._playListItemCount = 0;
  
  this._mainLayoutId = mainLayoutId;
  this._containerId  = containerId;
  this._playerId     = playerId;
  this._player       = null;
  this._errorTimeout = null;
  this._introId      = introId;
  this._loadingPanelId = loadingPanelId;
  this._errorPanelId = errorPanelId;
  this._divClipNameId = divClipNameId;
  this._divCategoriesId = divCategoriesId;
  
  this._allowPopupBlocking = false;
  this._divPopupBlockerId = divPopupBlockerId;
  
  this._scriptSuppressed = false;
  
  this._loadingNewVideo = false;
  
  this._maxPlayIterations = -1;
  
  this._supportsContinuePlaying = false;
  this._supportsRandomPlaying = false;
  this._showControls = false;
  
  this._playerWidth = 425;
  this._playerHeight = 356;
  
  this._currentIdField = $get("current_player_id");
  
  this._playedSequence = new Array();
  
  window.onresize = this.onWinResize;
  
  this._leftTimeout = 0;
  this._enabled = true;
  
  this._playerContainerId = null;
}

MyYTPlayer.prototype = {

    initializePlayerTimeout: function(timeOut, containerId) {
        this._leftTimeout = timeOut;
        this._timeOutContainerId = containerId;

        this.checkTimeout(true);
    },

    checkTimeout: function(displayTimeOnly) {
        var div = $get(this._timeOutContainerId);

        if (!displayTimeOnly) {
            this._leftTimeout--;
        }

        div.innerHTML = "Time&nbsp;remaining:&nbsp;<b>" + this._leftTimeout + "</b>&nbsp;minute" + ((this._leftTimeout == 1) ? "" : "s") + ".";

        if (this._leftTimeout == 0)
            this.disablePlayer();
        else
            setTimeout('ytPlayer.checkTimeout(false);', 1000 * 60);
    },

    disablePlayer: function() {
        this._enabled = false;
        try {
            if (this._player) {
                // stops video and undefines player
                try {
                    this._player.stopVideo();
                    this._player.clearVideo();
                }
                catch (e) {
                    // do nothing
                }
                this._player = null;
                this.setVideoNameHeader("");
            }
        }
        catch (e) { }

        this.hidePanel(this._mainLayoutId);

        if (this._playerContainerId)
            this.hidePanel(this._playerContainerId);

        for (var avcId in this._playList) {
            if (!avcId)
                return;

            var linkId = "lnkPli_" + avcId;
            var lnk = document.getElementById(linkId);
            if (lnk) {
                lnk.className = 'videoText disabledLink';
                lnk.disabled = true;
            }
        }
    },

    AddToPlayList: function(avdId, id, w, h, clipName) {
        var seq = this._playListSequence.length;
        var item = new PlayListItem(seq, id, w, h, clipName);

        this._playListSequence[seq] = String(avdId);
        this._playList[String(avdId)] = item;

        this._playListItemCount = seq + 1;
    },

    hideControls: function(panelId) {
        this._showControls = false;
        this.hidePanel(panelId);

        this.refreshPanelSize(this._mainLayoutId);
    },

    setCurrentItemId: function(id) {
        if (this._currentIdField)
            this._currentIdField.value = id;
    },

    removeCurrentItem: function(id) {
        var avdId = id;
        var linkId = "lnkPli_" + avdId;
        var lnk = $get(linkId);
        if (lnk) {
            lnk.style.display = "none";
            lnk.parentNode.style.display = "none";
        }

        var playListItem = this._playList[String(avdId)];

        if (this._curPlayListItem._id = playListItem._id) {
            this.playNext(false);
        }

        this._playListSequence[playListItem._seq] = null;
        this._playList[String(avdId)] = null;
    },

    initializePopupBlocking: function() {
        this._allowPopupBlocking = true;
    },

    initializeContinuePlaying: function(allow) {
        this._supportsContinuePlaying = allow;
    },

    initializeRandomPlaying: function(allow) {
        this._supportsRandomPlaying = allow;
    },

    changeSize: function(sizeCode, refreshCurrentPlayer) {
        var w, h;

        switch (sizeCode) {
            case "SM":
                w = 360;
                h = 300;
                break;
            case "ST":
                w = 425;
                h = 356;
                break;
            case "LA":
                w = 600;
                h = 486;
                break;
            case "LR":
                w = 800;
                h = 640;
                break;
        }

        this._playerWidth = w;
        this._playerHeight = h;

        if (refreshCurrentPlayer) {
            this.refreshPanelSize(this._mainLayoutId);
            this.refreshPanelSize(this._divPopupBlockerId);
            this.refreshPanelSize(this._loadingPanelId);
            this.refreshPanelSize(this._errorPanelId);
            this.refreshPanelSize(this._introId);
            this.refreshPanelSize(this._containerId);

            this.refreshPanelsPosition();

            this.refreshPlayerSize();
        }
    },

    refreshPlayerSize: function() {
        if (!this._player)
            return;

        var w = this._playerWidth;
        var h = this._playerHeight;

        try {
            if (this._player.width) {
                this._player.width = w;
                this._player.height = h;
            }
        }
        catch (e) { }

        try {
            if (this._player.clientWidth) {
                this._player.clientWidth = w;
                this._player.clientHeight = h;
            }
        }
        catch (e) { }

        try {
            if (this._player.offsetWidth) {
                this._player.offsetWidth = w;
                this._player.offsetHeight = h;
            }
        }
        catch (e) { }

        if (this._player)
            this._player.setSize(Number(this._playerWidth), Number(this._playerHeight));
    },

    initializeMaxPlayIterations: function(v) {
        this._maxPlayIterations = v;
    },

    initializePlayerReference: function() {
        this._player = document.getElementById(this._playerId);

        // initialize events
        this._player.addEventListener("onStateChange", "ytPlayer.onPlayerStateChange");
        this._player.addEventListener("onError", "ytPlayer.onPlayerError");

        this.refreshPlayerSize();

        this.clipLoaded();
    },

    onPlayerError: function(errorCode) {
        if (errorCode == 100) {
            this._curPlayListItem._isPlayed = true;
            this._curPlayListItem._isBad = true;
            this._curPlayListItem._playedIterations = this._maxPlayIterations;

            if (this._errorTimeout) {
                clearTimeout(this._errorTimeout);
            }

            var avcId = this._playListSequence[this._curPlayListItem._seq];

            if (!avcId)
                return;

            var linkId = "lnkPli_" + avcId;
            var lnk = document.getElementById(linkId);
            if (lnk) {
                lnk.style.display = 'none';
            }

            MarkVideoAsBad("MB\n" + this._curPlayListItem._id, "MB");

            this.processPlayedItemLink(this._curPlayListItem);

            if (this._supportsContinuePlaying) {
                setTimeout("ytPlayer.playNext(false);", 100);
            }
            else {
                this.showError();
            }
        }

        if (errorCode > 100) {
            this._curPlayListItem._isPlayed = true;
            this._curPlayListItem._isBad = true;
            this._curPlayListItem._playedIterations = this._maxPlayIterations;

            if (this._errorTimeout) {
                clearTimeout(this._errorTimeout);
            }

            var avcId = this._playListSequence[this._curPlayListItem._seq];

            if (!avcId)
                return;

            var linkId = "lnkPli_" + avcId;
            var lnk = document.getElementById(linkId);
            if (lnk) {
                lnk.style.display = 'none';
            }

            this.processPlayedItemLink(this._curPlayListItem);

            if (this._supportsContinuePlaying) {
                setTimeout("ytPlayer.playNext(false);", 100);
            }
            else {
                this.showError();
            }
        }
    },

    onPlayerStateChange: function(newState) {
        //alert("Player's new state: " + newState);

        this.refreshPlayerSize();

        if (newState == 0) // ended
        {
            if (ytPlayer._loadingNewVideo)
                return;

            this._curPlayListItem._isPlayed = true;
            this._curPlayListItem._playedIterations++;

            this.processPlayedItemLink(this._curPlayListItem);

            if (this._supportsContinuePlaying) {
                setTimeout("ytPlayer.playNext(false);", 100);
            }
            else {
                this.showIntroPanel();

                //          alert('video ends.');
            }
        }
        else {
            if (!this._enabled) {
                try {
                    if (this._player) {
                        // stops video and undefines player
                        try {
                            this._player.stopVideo();
                            this._player.clearVideo();
                        }
                        catch (e) {
                            // do nothing
                        }

                        this._player = null;
                        this.setVideoNameHeader("");
                    }
                }
                catch (e) { }

                this.hidePanel(this._mainLayoutId);
            }
        }
    },

    showIntroPanel: function() {
        this.hidePanel(this._mainLayoutId);
        this.hidePanel(this._divPopupBlockerId);
        this.hidePanel(this._loadingPanelId);
        this.hidePanel(this._errorPanelId);
        this.showPanel(this._introId);
    },

    isPlayerItemUsedAllIterations: function(playListItem) {
        return playListItem._isBad || ((this._maxPlayIterations != -1) && (playListItem._playedIterations >= this._maxPlayIterations));
    },

    processPlayedItemLink: function(playListItem) {
        if (this.isPlayerItemUsedAllIterations(playListItem)) {
            var avcId = this._playListSequence[playListItem._seq];

            if (!avcId)
                return;

            var linkId = "lnkPli_" + avcId;
            var lnk = document.getElementById(linkId);
            if (lnk) {
                lnk.className = 'videoText disabledLink';
                lnk.disabled = true;
            }
        }
    },

    addToPlayedSequence: function(avdId) {
        var l = this._playedSequence.length;
        if ((l > 0) && (this._playedSequence[l - 1] == avdId)) {
            return;
        }

        this._playedSequence[l] = avdId;
    },

    playPrevious: function() {
        var l = this._playedSequence.length;

        if (l <= 1) {
            return;
        }

        var avdId = this._playedSequence[l - 2];
        this._playedSequence = this._playedSequence.splice(0, l - 1);
        this.initializeVideo(avdId);
    },

    playNext: function(isStartUp) {
        if (!this._enabled) {
            this.hidePanel(this._mainLayoutId);
            return;
        }

        if (this._playList.length == 0)
            return;

        var hasNotPlayed = false;
        // checks if not all videos still were played
        for (var i = 0; i < this._playListSequence.length; i++) {
            if (!this._playListSequence[i])
                continue;

            if (this._playList[this._playListSequence[i]]._isBad)
                continue;

            if ((this._maxPlayIterations == -1) || (this._playList[this._playListSequence[i]]._playedIterations < this._maxPlayIterations)) {
                hasNotPlayed = true;
                break;
            }
        }

        if (hasNotPlayed) {
            if (!this._curPlayListItem)
                this._curPlayListItem = this._playList[this._playListSequence[0]];

            // goes to next video
            var curIndex = (this._supportsRandomPlaying)
           ? Math.floor(Math.random() * this._playListSequence.length)
           : ((isStartUp) ? this._curPlayListItem._seq : this._curPlayListItem._seq + 1);

            var resetedToStart = false;

            if (curIndex == this._playListSequence.length) {
                curIndex = 0;
                resetedToStart = true;
            }

            for (var i = curIndex; i < this._playListSequence.length; i++) {
                if (!this._playListSequence[i] || this._playList[this._playListSequence[i]]._isBad) {
                    if ((i == this._playListSequence.length - 1) && (!resetedToStart)) {
                        i = -1;
                        resetedToStart = true;
                    }
                    continue;
                }

                //if (!this._playList[this._playListSequence[i]]._isPlayed)
                if ((this._maxPlayIterations == -1) || (this._playList[this._playListSequence[i]]._playedIterations < this._maxPlayIterations)) {
                    this.initializeVideo(this._playListSequence[i]);
                    return true;
                }
                else {
                    if ((i == this._playListSequence.length - 1) && (!resetedToStart)) {
                        i = -1;
                        resetedToStart = true;
                    }
                }
            }
        }

        this.showIntroPanel();
        return false;
    },

    refreshPanelSize: function(id) {
        var c = document.getElementById(id);
        if (c) {
            if (this._curPlayListItem) {
                c.style.width = this._playerWidth + 'px';
                c.style.height = this._playerHeight + 'px';

                var cat = document.getElementById(this._divCategoriesId);
                if (cat) {
                    cat.style.height = String(Number(this._playerHeight) + ((this._showControls) ? 65 : 0) + 5) + "px";
                }
            }

            if (id != this._mainLayoutId) {
                var m = document.getElementById(this._mainLayoutId);
                c.style.position = "absolute";
                c.style.left = String(findPosX(m)) + "px";
                c.style.top = String(findPosY(m)) + "px";

                var td = document.getElementById(id + "TD");
                if (td) {
                    td.style.width = this._playerWidth + 'px';
                    td.style.height = this._playerHeight + 'px';
                }
            }
        }
    },

    showPanel: function(id) {
        var c = document.getElementById(id);
        if (c) {
            if (this._curPlayListItem) {
                c.style.width = this._playerWidth + 'px';
                c.style.height = this._playerHeight + 'px';

                var cat = document.getElementById(this._divCategoriesId);
                if (cat) {
                    cat.style.height = String(Number(this._playerHeight) + ((this._showControls) ? 65 : 0) + 5) + "px";
                }
            }

            if (id == this._mainLayoutId) {
                c.style.visibility = "visible";
                return;
            }
            else {
                var m = document.getElementById(this._mainLayoutId);
                c.style.position = "absolute";
                c.style.left = String(findPosX(m)) + "px";
                c.style.top = String(findPosY(m)) + "px";

                var td = document.getElementById(id + "TD");
                if (td) {
                    td.style.width = this._playerWidth + 'px';
                    td.style.height = this._playerHeight + 'px';
                }

                c.style.display = "block";
            }
        }
    },

    refreshPanelsPosition: function() {
        if (!this._curPlayListItem)
            return;

        var p1 = document.getElementById(this._introId);
        var p2 = document.getElementById(this._loadingPanelId);
        var p3 = document.getElementById(this._errorPanelId);
        var p4 = document.getElementById(this._divPopupBlockerId);

        if (p1.style.display != "none")
            this.showPanel(this._introId);
        if (p2.style.display != "none")
            this.showPanel(this._loadingPanelId);
        if (p3.style.display != "none")
            this.showPanel(this._errorPanelId);
        if (p4.style.display != "none")
            this.showPopupBloker();
    },

    onWinResize: function() {
        ytPlayer.refreshPanelsPosition();
    },

    hidePanel: function(id) {
        var c = document.getElementById(id);

        if (id == this._mainLayoutId) {
            c.style.visibility = "hidden";
            this.hidePanel(this._divPopupBlockerId);
            return;
        }

        if (c) {
            c.style.display = "none";
        }
    },

    showError: function() {
        this.hidePanel(this._loadingPanelId);
        this.hidePanel(this._mainLayoutId);
        this.showPanel(this._errorPanelId);

        this._curPlayListItem._isPlayed = true;
        this._curPlayListItem._playedIterations++;

        if (this._supportsContinuePlaying) {
            setTimeout("ytPlayer.playNext(false);", 100);
        }
    },

    clipLoading: function() {
        this.setVideoNameHeader(this._curPlayListItem._clipName);

        if (this._scriptSuppressed)
            return;

        if (this._errorTimeout)
            clearTimeout(this._errorTimeout);
        this._errorTimeout = setTimeout("ytPlayer.showError();", 20000);

        this.hidePanel(this._divPopupBlockerId);
        this.hidePanel(this._introId);
        this.hidePanel(this._errorPanelId);
        //this.hidePanel(this._mainLayoutId);
        this.showPanel(this._loadingPanelId);
    },

    showPopupBloker: function() {
        if (this._allowPopupBlocking) {
            // initialize absolute positioned transparent div
            // to revent clicking on the player
            var pb = document.getElementById(this._divPopupBlockerId);
            if (pb && this._curPlayListItem) {
                var m = document.getElementById(this._mainLayoutId);
                pb.style.position = "absolute";
                pb.style.left = String(findPosX(m)) + "px";
                pb.style.top = String(findPosY(m)) + "px";

                pb.style.width = this._playerWidth + 'px';
                pb.style.height = (Number(this._playerHeight) - 30) + 'px';

                pb.style.display = "block";
            }
        }
    },

    clipLoaded: function() {
        if (this._scriptSuppressed)
            return;

        clearTimeout(this._errorTimeout);

        this.hidePanel(this._introId);
        this.hidePanel(this._loadingPanelId);
        this.showPanel(this._mainLayoutId);
        this.showPopupBloker();
    },

    setVideoNameHeader: function(name) {
        var header = document.getElementById("playerHeader");
        if (header) {
            header.innerHTML = "Currently playing:&nbsp;" + name;
        }
        else {
            header.innerHTML = "";
        }
    },

    initializeVideo: function(avdId) {
        var item = this._playList[String(avdId)];

        if (!item) {
            alert("Play list item was not found...");
            return;
        }

        this.refresh(item);
    },

    refresh: function(playListItem) {
        this._loadingNewVideo = true;

        this.hidePanel(this._introId);
        this.hidePanel(this._loadingPanelId);
        this.showPanel(this._mainLayoutId);

        this.setCurrentItemId(this._playListSequence[playListItem._seq]);
        this.addToPlayedSequence(this._playListSequence[playListItem._seq]);

        if (this._player) {
            // stops video and undefines player
            try {
                this._player.stopVideo();
                this._player.clearVideo();
            }
            catch (e) {
                // do nothing
            }
            this._player = null;
            this.setVideoNameHeader("");
        }

        this._curPlayListItem = playListItem;

        //if (this._curPlayListItem._isPlayed)
        if ((this._maxPlayIterations != -1) && (this._curPlayListItem._playedIterations >= this._maxPlayIterations)) {
            //        if (!this.playNext())
            //        {
            //          alert("All videos in playlist were played.");
            //        }
            // SG: only disable link
            this.processPlayedItemLink(playListItem);
            return;
        }

        var params = null;
        if (mac)
            params = { allowScriptAccess: "always", WMode: "window" };
        //params = { allowScriptAccess: "always", WMode: "transparent" };
        else
            params = { allowScriptAccess: "always", WMode: "transparent" };

        var atts = { id: this._playerId };

        var playerUrl = "http://www.youtube.com/v/" + String(playListItem._id) +
                      "&autoplay=1&rel=0&color1=0xd6d6d6&color2=0xf0f0f0&border=0&enablejsapi=1&playerapiid=ytplayer";

        var flashPlayerVersion = "9.0.115";

        if (!document.getElementById(this._containerId)) {
            var main = document.getElementById(this._mainLayoutId);
            main.innerHTML = "<div class=\"playerPanel\" id=\"" + this._containerId + "\"><br /><br /><br /><br /><br /><br /><br />You need Flash player " + flashPlayerVersion + " or latest <br />and JavaScript enabled to view this video.<br /><br /><br /><br /><br />To download latest Adobe Flash player plase click here: <a href='http://www.adobe.com/go/getflashplayer'>http://www.adobe.com/go/getflashplayer</a></div>";
        }

        this._scriptSuppressed = false;

        try {
            swfobject.embedSWF(playerUrl, this._containerId, this._playerWidth, this._playerHeight, "9.0.115", "", "", params, atts);
        }
        catch (e) {
            //alert(e);

            var main = document.getElementById(this._mainLayoutId);

            try {
                var fv = swfobject.getFlashPlayerVersion();
                if ((fv.major >= 9) && (fv.minor >= 0) && ((fv.major == 9 && fv.release >= 115) || ((fv.major > 9 && fv.release >= 0)))) {
                    this._scriptSuppressed = true;

                    var embededHtml = "<object id=\"" + this._playerId + "\" width=\"" + this._playerWidth + "\" height=\"" + this._playerHeight + "\">" +
                                  " <param name=\"movie\" value=\"" + playerUrl + "\"></param>" +
                                  " <param name=\"wmode\" value=\"window\"></param> " +
                                  " <param name=\"allowScriptAccess\" value=\"always\"></param> " +
                                  " <embed src=\"" + playerUrl + "\" type=\"application/x-shockwave-flash\" wmode=\"window\" allowscriptaccess=\"always\" width=\"" + this._playerWidth + "\" height=\"" + this._playerHeight + "\"></embed>" +
                                  " </object>";
                    main.innerHTML = embededHtml;
                }
                else {
                    main.innerHTML = "<div class=\"playerPanelEx\" id=\"" + this._containerId + "\"><br /><br /><br /><br /><br /><br /><br />You need Flash player " + flashPlayerVersion + " or latest <br />and JavaScript enabled to view this video.<br /><br /><br /><br /><br />To download latest Adobe Flash player plase click here: <a href='http://www.adobe.com/go/getflashplayer'>http://www.adobe.com/go/getflashplayer</a></div>";
                }
            }
            catch (e) {
                main.innerHTML = "<div class=\"playerPanelEx\" id=\"" + this._containerId + "\"><br /><br /><br /><br /><br /><br /><br />You need Flash player " + flashPlayerVersion + " or latest <br />and JavaScript enabled to view this video.<br /><br /><br /><br /><br />To download latest Adobe Flash player plase click here: <a href='http://www.adobe.com/go/getflashplayer'>http://www.adobe.com/go/getflashplayer</a></div>";
            }
        }

        if (document.getElementById(this._containerId)) {
            //this.hidePanel(this._mainLayoutId);
            this.hidePanel(this._divPopupBlockerId);
            this.hidePanel(this._loadingPanelId);
            this.hidePanel(this._errorPanelId);
            this.hidePanel(this._introId);

            this.showPanel(this._mainLayoutId);

            this._loadingNewVideo = false;

            return;
        }

        this.clipLoading();

        this._loadingNewVideo = false;
    }
}

var ytPlayer = new MyYTPlayer("divMainLayout", "divPlayer", "myYTPlayer", "divIntro", "divLoading", "divCannotLoad", "divClipNameId", "divCategories", "divPopupBlocker");

function onYouTubePlayerReady(playerId) {
   this._scriptSuppressed = false;
   ytPlayer.initializePlayerReference();
   
   //alert("player ready");
}
