/* 
author: Trevor Thompson
dependencies: /dynaboss/script/video/mtvn_player_control.js  // lives in parentsconnect-dynaboss
issues: 
 - first video will start to load before playIndex is called
 - only supports one player
*/

var video = (typeof video === "undefined") ? {} : video;

video.Randomizer = function (playerId, instanceName) {
	var _controller,
	    _playerId = playerId,
	    _instanceName = instanceName,
	    _player,
	    _initPlayer = false,
	    _checkPlayerInterval,
		_init = function(){
			_playerId = (typeof playerId === null) ? 'videoPlayerPrime' : playerId;
			_controller = new MTVNPlayerController(_playerId, _onVideoPlayerLoaded);
			mtvnPlayerLoaded(_playerId);
		},
		_onVideoPlayerLoaded = function(){
			_player = _controller.player;
			
			if(typeof _player.addEventListener !== "undefined"){
				_player.addEventListener('READY', _instanceName + '.onPlayerReady');
				
				clearInterval(_checkPlayerInterval);
				_checkPlayerInterval = setInterval(function(){window[_instanceName].checkPlayer();}, 1000); // we don't awlays capture the first ready state so we need to poll
			}else{
				_checkPlayerInterval = setTimeOut(function(){window[_instanceName].onVideoPlayerLoaded();}, 1000);
			}
		},
	  	_checkPlayer = function(){
			if(_player.getPlaylist().isReady && _player.getMetadata() != null && !_initPlayer && _player.getMetadata() != null && !_isPlayingAd()){
				clearInterval(_checkPlayerInterval);
				_checkPlayerInterval = undefined;
				_onPlayerReady();
			}
	 	},
	 	_onPlayerReady = function(){
	 		_randomize();
	 	},
	 	_isPlayingAd = function(){
			return (_player.getMetadata().isAd || _player.getMetadata().isBumper);
		},
		_randomize = function(){
	  		if(_player.getPlaylist().isReady){ // ...not sure what to do if this isn't ready.  For now, just let it play 1st video
                var count = _player.getPlaylist().length - 1; // TODO: pretty sure we don't need - 1 then + 1
                var i = Math.floor(Math.random() * count + 1);
	            _player.playIndex(i);
	        }
	    }
    return {
    	randomize:_init,
    	onVideoPlayerLoaded:_onVideoPlayerLoaded,
    	checkPlayer:_checkPlayer
    };
}

