// YOUTUBE - JAVASCRIPT API:
// http://code.google.com/intl/de/apis/youtube/js_api_reference.html

// https://teamsite.bayerbbs-hosting.com/iw-mount/default/main/MarketingSites/BSP/YourLife/International/WORKAREA/htdocs/scripts/pages/en/home/youth_task_force/?post=44be055462

if (typeof (youtubePlayers) == "undefined") {
	// admin object for all youtube players on page
	var youtubePlayers = new function () {
		// unique pointer to this - because in some cases like timeout/intervall-calls the regular this object is different
		var _this = this;
		
		// list for all initialized players (key is player id)
		this.players = {};
		
		// with this method anew player is added to this list
		this.addNewPlayer = function (_playerId) {
			// create player object
			this.players[_playerId] = new youtubePlayer(_playerId);
			// call init function to initialize a few value
			this.players[_playerId].init();
		};
		
		// sometimes youtube players are deleted from page - in that case they also have to get deleted from array
		this.removePlayer = function (_player) {
			try { delete _this.players[_player.playerId]; } catch (e) {};
		};
	}


	var youtubePlayer = function (_playerId) {
		// unique pointer to this - because in some cases like timeout/intervall-calls the regular this object is different
		var _this = this;
//alert('inside: adding new player ' + _playerId);
		// youtube only gives cryptic event ID - this array and the getStateName method are mappiung the ids to names
		this.STATE_NAMES = {'-1':'unstarted' , '0':'ended' , '1':'playing' , '2':'paused' , '3':'buffering' , '5':'cued'};
		this.getStateName = function (_state) {return _this.STATE_NAMES[String(_state)];};

		// variable to save the referecne to the interval object
		this.updateInterval = null;
		
		// save the player id of this object
		this.playerId = _playerId;
		
		// initialize player object - mainly setting event listeners
		this.init = function() {
			if (_this.getPlayerObj()) {
				// wrap onStateChange event listener - to be able to call object specific function - this is needed, because youtube api doesn't pass the playerId into the onStateChange handler function
				// like http://blog.jcoglan.com/2008/05/22/dispatching-youtube-api-events-to-individual-javascript-objects/
				var stateChangeCallback = 'videoStateChangeHandler' + _this.playerId;
				window[stateChangeCallback] = function (_newStateId) {
					_this.handleStateChange (_newStateId);
				};
				//alert('added event listener for state id: ' + _newStateId);
				_this.getPlayerObj().addEventListener("onStateChange", stateChangeCallback);
			}
		};
		
		// destructor to clean up
		this.destroy = function (){
			window.clearInterval(_this.updateInterval);
			youtubePlayers.removePlayer(_this);
		};
		
		// grap HTML reference to the HTML <object>
		this.getPlayerObj = function(){
			var playerObj = document.getElementById(_this.playerId);
			if (!playerObj) { _this.destroy(); }
			return playerObj;
		};
		
		this.getTitle = function () {
			return _this.getPlayerObj().getAttribute("_title");
		};

		this.getYoutubeId = function () {
			return _this.getPlayerObj().getAttribute("_youtubeid");
		};
		
		// check current state of player in a regular interval to find out when web tracking is needed
		this.updatePlayerInfo = function () {
			if (_this.getPlayerObj()) {
				webTracker.trackVideoPlaying (_this);
			}
		};
		
		this.getPlayerState = function () {
			return _this.getStateName(_this.getPlayerObj().getPlayerState());
		};
		
		// return percentage of video the player has played
		this.getPlayedPercentage = function() {
			// Returns 0% if the player hasn't started yet to avoid reporting error
			return (_this.getPlayerObj().getCurrentTime() <= 0 ? 0 : parseInt(_this.getPlayerObj().getCurrentTime() / _this.getPlayerObj().getDuration() * 100));
	    };
		
		// event handler if the state of the player changes
		this.handleStateChange = function (_newStateId) {
			// if player state is changed for the first time - start cecking for updates every second
			if (_this.updateInterval == null && _this.getPlayerState() != "cued") {
				_this.updateInterval = window.setInterval(_this.updatePlayerInfo, 2000);
			}
			// console.log ("Player (" + _this.playerId + ") state change to: " + _this.getStateName(_newStateId) + "(" + _newStateId + ")");
			// console.log (_this);
		};
	}
}

// when youtube player is loaded - add the new player to the list of players. This method is directly called by youtube api
function onYouTubePlayerReady(_playerId) {
	youtubePlayers.addNewPlayer(_playerId);
}