/**
 * YouTube Feed Reader v1.0 <http://www.mauricesnip.nl/etc/ytfeedreader/>
 */

var YTFeedReader = function() {
	var DEBUG = false,
		PLAYERURL = 'http://gdata.youtube.com/apiplayer',
		
		xhr = null,
		xmlDoc = null,
		videoIds = []
		videoItems = [],
		currentVideo = null,
		
		ytContainer = null,
		ytPlayer = null,
		ytPlayList = null,
		ytAutoPlay = false;
		
		apiKey = null,
		feedURL = null,

		videoLimit = null,
		videoWidth = null,
		videoHeight = null,
		createPlayList = true,
		installerFile = null,
		flashVars = null,
		params = { allowScriptAccess: 'always', bgcolor: '#000000', wmode: 'transparent' },
		attributes = { id: 'yt-player' };
		
		// IE doesn't have Array.indexOf implemented
		if (!Array.indexOf) {
			Array.prototype.indexOf = function(obj) {
				for (var i = 0; i < this.length; i++) {
					if (this[i] == obj) {
					return i;
				}
			}
			return -1;
			}
		}
		
	return {
		initialize: function(sApiKey, sFeedURL, sYtContainer, nVideoLimit, nVideoWidth, nVideoHeight, bCreatePlayList, bYtAutoPlay, sVideoId) {
		
			if (!swfobject || !sApiKey || !sFeedURL) {
				
				return;
			}
			
			apiKey = sApiKey;
			feedURL = sFeedURL;
			ytContainer = sYtContainer || 'yt-container';
			videoLimit = nVideoLimit || 3;
			videoWidth = nVideoWidth || 480;
			videoHeight = nVideoHeight || 263;
			createPlayList = bCreatePlayList;
			ytAutoPlay = bYtAutoPlay;
			videoId = sVideoId;
						
			this.createPlayer();
		},
		getXMLHttpObj: function() {
			return window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') :
				window.XMLHttpRequest ? new XMLHttpRequest() : this.log('Could not create XHR object');
		},
		makeRequest: function() {
			var self = this;
			xhr = this.getXMLHttpObj();
			
			if (xhr) {
				xhr.onreadystatechange = function() {
					self.getVideoItems();
				}
				xhr.open('POST', feedURL, true);
				xhr.send(null);
			}
			else {
				this.log('XMLHTTP object is empty or not of typ Object: ' + typeof xhr);
				return false;
			}
		},
		getVideoItems: function() {
			var items;
			
			if (xhr.readyState == 4) {
				if (xhr.status == 200) {
					if (window.XMLHttpRequest) {
						items = xhr.responseXML.getElementsByTagName('entry');
					}
					// IE doesn't recognize application/rss+xml as XML, so responseXML will be empty
					// The following code builds a DOM document from scratch using responseText as content
					if (typeof xhr.responseXML == 'undefined' || window.ActiveXObject) {
						xmlDoc = new ActiveXObject('MSXML2.DOMDocument.3.0');
						xmlDoc.loadXML(xhr.responseText);
						items = xmlDoc.getElementsByTagName('entry');
					}
					if (items) {
						for (var i = 0; i < items.length; i++) {
							videoIds.push(this.getItemProperty(items[i], 'link', "true", "href").split('=')[1]);
							videoItems.push(items[i]);
						}
/*
XmPbVl0vorI						
NJy32USIENY

NHaTDfSKcFo
Zrb-5z7MpgI 

10-02
G7Gti789kjU

02-03
NJy32USIENY


eSj0hgkp0Q0

*/						

						// Aanpassing GJ : 13-01-2009
						for (var i = 0; i < items.length; i++) {
							if(videoIds[i] == '6oKelTTbh54')
							{
	//							OldId = i;
							}
						}
						
//						videoIds.unshift(videoIds[OldId]);
//						videoItems.unshift(videoItems[OldId]);
		//				videoItems.splice(OldId+1,1);
			//			videoIds.splice(OldId+1,1);
/*						videoIds.unshift(videoIds[OldId +1]);
						videoItems.unshift(videoItems[OldId +1]);
						videoIds.unshift(videoIds[OldId3]);
						videoItems.unshift(videoItems[OldId3]);

						videoItems.splice(OldId+3,1);
						videoIds.splice(OldId+3,1);
						videoItems.splice(OldId+4,1);
						videoIds.splice(OldId+4,1);
						videoItems.splice(OldId3,1);
						videoIds.splice(OldId3,1);
*/						
					}
					if (createPlayList) {
						this.createPlayList();
					}
					if (ytAutoPlay) {
						if(videoIds[0] == '6oKelTTbh54') {
						//	videoIds[0] = '5NtayyqrESA';
						}
						this.loadVideo(videoIds[0]);
						//lvJ2C6k0Z9c
					}
					else {
						this.cueVideo();
					}
					this.bindControls();
				}
				else {
					this.log('Could not make the request! XMLHTTP status: ' + xhr.status);
				}
			}
			else {
				this.log('XMLHTTP not ready yet, readyState is: ' + xhr.readyState);
			}
		},
		createPlayer: function() {
			var self = this;
			
			swfobject.embedSWF(PLAYERURL + '?key=' + apiKey + '&enablejsapi=1&playerapiid=yt-player',
				ytContainer, videoWidth, videoHeight, '8', installerFile, flashVars, params, attributes
			);
			
			onYouTubePlayerReady = function(playerId) {
				ytPlayer = document.getElementById('yt-player');
				ytPlayer.addEventListener('onStateChange', 'YTFeedReader.stateChange');
				
				// enkele video laden en afspelen met controls
				if(videoId) {
					self.loadVideo(videoId);
					self.bindControls();
				} else {
					self.makeRequest();
				}
			}
		},
		stateChange: function(state) {
			this.log('Player state: ' + state);
			if (state == 0) {
				var nextIndex = videoIds.indexOf(currentVideo) + 1;
				
				if (nextIndex < videoIds.length) {
					this.loadVideo(videoIds[nextIndex]);
				}
				else {
					this.loadVideo();
				}
			}
		},
		createPlayList: function() {
			var self = this;
			ytPlayList = document.getElementById('yt-playlist');
			
			for (var i = 0; i < (videoItems.length < videoLimit ? videoItems.length : videoLimit); i++) {
				var videoId = this.getItemProperty(videoItems[i], 'link', 'true', 'href').split('=')[1]; 
				if(videoId == '6oKelTTbh54') {
				//	videoId = '5NtayyqrESA';
				}
				var videoName = this.getItemProperty(videoItems[i], 'title',"false");
				var videoDate = this.getItemProperty(videoItems[i], 'published', "false");
				
				//window.console.log(videoId);
				
				var listItem = document.createElement('li');
				var anchor = document.createElement('a');
				var anchorText = document.createTextNode(videoName.substring(0, 32));
				var span = document.createElement('span');
				var spanText = document.createTextNode(this.prettyDate(videoDate, '.'));
				
				listItem.appendChild(anchor);
				anchor.appendChild(span);
				anchor.appendChild(anchorText);
				span.appendChild(spanText);
				anchor.id = videoId;
				anchor.href = '#';
				anchor.title = videoName;
				anchor.onclick = function() {
					self.loadVideo(this.id);
					currentVideo = this.id;
					return false;
				}
				ytPlayList.appendChild(listItem);
			}
		},
		bindControls: function() {
			var controls = {
				'yt-play-control': this.play,
				'yt-pause-control': this.pause,
				'yt-stop-control': this.stop,
				'yt-mute-control': this.mute,
				'yt-unmute-control': this.unMute,
				'yt-toggleplay-control': this.togglePlay,
				'yt-togglemute-control': this.toggleMute
			};
			
			for (var control in controls) {
				if (document.getElementById(control)) {
					this.bindControl(document.getElementById(control), controls[control]);
				}
			}
		},
		bindControl: function(el, fn) {
			var self = this;
			el.onclick = function() {
				fn.apply(self, [this]);
				return false;
			}
		},
		// Deprecated
/*		getItemProperty: function(item, prop) {
		},
*/		getItemProperty: function(item, prop, mode, attrib) {
			if(mode == "true"){
				return item.getElementsByTagName(prop)[0].getAttribute(attrib);
			} else {
				return item.getElementsByTagName(prop)[0].firstChild.nodeValue;
			}
		},
		loadVideo: function(videoId) {
			if (ytPlayer) {
				if (videoId) {
					currentVideo = videoId;
					ytPlayer.loadVideoById(videoId);
				}
				// Load latest video
				else if(videoItems) {
					var id = this.getItemProperty(videoItems[0], 'link').split('=')[1];
					currentVideo = id;
					ytPlayer.loadVideoById(id);
				}
			}
		},
		cueVideo: function(videoId) {
			if (ytPlayer) {
				if (videoId) {
					ytPlayer.cueVideoById(videoId);
				}
				// Cue latest video
				else if(videoItems) {
					ytPlayer.cueVideoById(this.getItemProperty(videoItems[0], 'link').split('=')[1]);
				}
			}
		},
		currentVideo: function() {
			return currentVideo;
		},
		play: function() {
			if (ytPlayer) {
				ytPlayer.playVideo();
			}
		},
		pause: function() {
			if (ytPlayer) {
				ytPlayer.pauseVideo();
			}
		},
		stop: function() {
			if (ytPlayer) {
				ytPlayer.stopVideo();
			}
		},
		mute: function() {
			if (ytPlayer) {
				ytPlayer.mute();
			}
		},
		unMute: function() {
			if (ytPlayer) {
				// Somehow you have to double click to unMute, this breaks the toggleMute function
				// Calling unMute twice fixes the problem in this case
				ytPlayer.unMute();
				ytPlayer.unMute();
			}
		},
		togglePlay: function (el) {
			if (ytPlayer) {
				if (ytPlayer.getPlayerState() != 1) {
					this.play();
					if (el) el.className = 'playing';
				}
				else if (ytPlayer.getPlayerState() != 2) {
					this.pause();
					if (el) el.className = 'paused';
				}
			}
		},
		toggleMute: function(el) {
			if (ytPlayer) {
				if (ytPlayer.isMuted()) {
					this.unMute();
					if (el) el.className = 'unmuted';
				}
				else {
					this.mute()
					if (el) el.className = 'muted';
				}
			}
		},
		prettyDate: function(dateString, separator)
		{
			var months = { Jan: '01', Feb: '02', Mar: '03', Apr: '04', May: '05', Jun: '06',
							Jul: '07', Aug: '08', Sep: '09', Oct: '10', Nov: '11', Dec: '12' };
			var dateArr = dateString.split('-');
			return dateArr[2].split('T')[0] + separator + dateArr[1] + separator + dateArr[0];
		},
		log: function(msg) {
			if (DEBUG) {
				console.log(msg);
			}
		}
	}
}();