var youtube = new Object;
var ytPlayer;

function Youtube(target, searchString, width) {
	// methods
	this.getData        = getYoutubeData;
	this.handleData     = handleYoutubeData;
	this.appendData     = appendYoutubeData;
	this.appendVideo    = appendYoutubeVideo;
	this.createPlayer   = ytCreatePlayer;
	
	// attributes
	this.id             = target;
	this.target         = document.getElementById(target);
	this.search         = searchString;
	
	this.elementCount   = 5;
	
	this.width          = width;
	this.height         = Math.round(this.width*0.75);
	this.videos;
	this.videoIndex     = new Array();
	
	this.scroller = new cellScroller();
	
	// adds youtube-instance to target
	this.target.youtube = this;
	eval("youtube." + this.id + " = document.getElementById('" + target + "').youtube;");
	
	
	// start plugin
	$('document').ready(function(){
		youtube.youtube.createPlayer();
	});
	this.getData();
}


function getYoutubeData() {
	// define YoutubeQuery
	var YoutubeQuery = 'http://gdata.youtube.com/feeds/api/videos/-/Music/?vq=' + encodeURIComponent(this.search) + '&start-index=1&max-results=' + (this.elementCount*2) + '&alt=json-in-script&callback=youtube.' + this.id + '.handleData&orderby=relevance&racy=include';
	
	// define script-element
	var getScript = document.createElement('script');
	getScript.setAttribute('type', 'text/javascript');
	getScript.setAttribute('src', YoutubeQuery);
	
	// append script-element to head
	document.getElementsByTagName('head')[0].appendChild(getScript);
}


function handleYoutubeData(data) {
	this.videos = data.feed.entry;
	
	// if no videos found -> delete youtube-div including headline-div
	if(this.videos)
		this.appendData();
	else
		this.target.parentNode.parentNode.parentNode.removeChild(this.target.parentNode.parentNode);
}


function appendYoutubeData() {
	var VideoContainer = document.createElement('div');
	VideoContainer.setAttribute('id', this.id + 'Container');
	VideoContainer.setAttribute('style', 'border-top: 1px solid #DDF8CB; clear: both; margin: 3px 0px 0px; width: 288px;');
	
	for(i = 0; i < this.videos.length; i++)
	{
		if(this.videos[i].media$group.media$content && this.videos[i].media$group.media$content[0].type == 'application/x-shockwave-flash' && this.elementCount > 0)
		{
			// split url
			var movieId = this.videos[i].media$group.media$player[0].url.split('=');
			movieId = movieId[movieId.length-1];
			
			VideoContainer.innerHTML += this.appendVideo(movieId, i);
			this.elementCount--;
		}
	}
	this.target.appendChild(VideoContainer);
	
	$(document).ready(function(){
		youtube.youtube.scroller.set('ytPlayerInfo');
		youtube.youtube.scroller.init();
	});
}

function ytCreatePlayer() {
	/*var object    = document.createElement('object');
	object.id     = 'ytPlayer';
	object.type   = 'application/x-shockwave-flash';
	object.data   = 'http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=ytplayer';
	object.height = '150';
	object.width  = '280';
	
	var params  = new Array(
		new Array('movie', 'http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=ytplayer'), 
		new Array('allowScriptAccess', 'always'), 
		new Array('bgcolor', '#000000')
	);
	
	var paramElements = new Array();
	
	for(var i = 0; i < params.length; i++) {
		paramElements[i] = document.createElement('param');
		paramElements[i].name = params[i][0];
		paramElements[i].value = params[i][1];
		
		object.appendChild(paramElements[i]);
	}
	
	this.target.appendChild(object);
	*/
	this.target.innerHTML = '<div id="ytPlayerContainer" style="height: 160px; padding: 0px 0px 0px 5px;"><object width="278" height="140" id="ytPlayer" data="http://www.youtube.com/apiplayer?enablejsapi=1&amp;playerapiid=ytPlayer" type="application/x-shockwave-flash" wmode="transparent"><param name="movie" value="http://www.youtube.com/apiplayer?enablejsapi=1&amp;playerapiid=ytPlayer"/><param name="allowScriptAccess" value="always"/><param name="wmode" value="transparent"/></object></div>' + this.target.innerHTML;
}


function appendYoutubeVideo(movieId, i) {
	if(!this.tmpI)
		this.tmpI = 1;
	
	var TrackDurationSeconds = Math.floor((this.videos[i].media$group.media$content[0].duration/60)%60 * 6);
	var TrackDurationMinutes = Math.floor(this.videos[i].media$group.media$content[0].duration/60);
	
	var hrefVideo = this.videos[i].link[0].href;
	var thumb     = this.videos[i].media$group.media$thumbnail[0].url;
	
	this.videoIndex[movieId] = i;
	
	
	
	var ElementInfo;
	var playerId = (this.id + 'VideoObject' + i);
	
	this.videos[i].movieId = movieId;
	
	ElementInfo  = '<img alt="" src="' + thumb + '" style="float: left; width: 75px;" /><div style="float: left; margin: 0px 0px 0px 5px; overflow: hidden; width: 200px;"><div id="VideoTitel' + i + '" style="display: inline;"><a href="javascript: void(0);" onclick="ytPlayer.loadVideo(\'' + movieId + '\',0);" style="font-weight: bold; text-decoration: none; white-space: nowrap;">' + this.videos[i].title.$t + '</a></div><div>' + TrackDurationMinutes + ':' + TrackDurationSeconds + '<br />Views: ' + separator(this.videos[i].yt$statistics.viewCount) + '</div></div>';
	ElementInfo += (this.videos[i].gd$rating) ? '<div style="position: absolute; top: ' + (this.height-10) + 'px; left: 0px;"></div>' : '';
	
	
	var url = '';
	var re = '';
	
	// output in innerHTML. ie does not know how to handle createElement...
	re = '<div id="VideoElement' + i + '" onclick="ytPlayer.loadVideo(\'' + movieId + '\',0);" style="background: #' + (this.tmpI%2 == 0 ? 'ffffff' : 'edfbe3') + '; clear: both; cursor: pointer; height: 56px; font-size: 0.9em; line-height: 1.3; overflow: hidden; padding: 3px; width: 282px;">';
	  re += ElementInfo;
	re += '</div>';
	
	this.tmpI++;
	
	
	// set cellscroller
	this.scroller.set('VideoTitel' + i);
	
	
	return re;
}

function ytAppendControls() {
	var ctrl = document.createElement('div');
	ctrl.id  = 'ytPlayerControl';
	ctrl.style.margin   = '2px 0px 0px';
	ctrl.style.position = 'relative';
	ctrl.style.width    = '278px';
	
	var href  = document.createElement('a');
	href.href = 'javascript: void(0);';
	var btn   = document.createElement('img');
	btn.src   = '/images/yt';
	
	var hrefPlay           = href.cloneNode(true);
	hrefPlay.onclick       = function() { ytPlayer.togglePlay(); }
	var btnPlay            = btn.cloneNode(true);
	btnPlay.id             = 'ytPlayButton';
	btnPlay.src           += 'Play.gif';
	btnPlay.style.position = 'absolute';
	btnPlay.style.top      = '0px';
	btnPlay.style.left     = '0px';
	hrefPlay.appendChild(btnPlay);
	
	
	var volumeCtrl    = document.createElement('div');
	volumeCtrl.style.position   = 'absolute';
	volumeCtrl.style.right      = '0px';
	volumeCtrl.style.top        = '0px';
	volumeCtrl.style.width      = '54px';
	
	
	var hrefMinus     = href.cloneNode(true);
	hrefMinus.onclick = function() { ytPlayer.vol(-1); }
	var btnMinus      = btn.cloneNode(true);
	btnMinus.src     += 'Minus.gif';
	hrefMinus.appendChild(btnMinus);
	
	
	var hrefMute      = href.cloneNode(true);
	hrefMute.onclick  = function() { ytPlayer.toggleMute(); }
	var btnMute       = btn.cloneNode(true);
	btnMute.id        = 'ytMuteButton';
	btnMute.src      += (ytPlayer.isMuted() == true ? 'Unmute.gif' : 'Mute.gif');
	hrefMute.appendChild(btnMute);
	
	
	var hrefPlus      = href.cloneNode(true);
	hrefPlus.onclick  = function() { ytPlayer.vol(1); }
	var btnPlus       = btn.cloneNode(true);
	btnPlus.src      += 'Plus.gif';
	hrefPlus.appendChild(btnPlus);
	
	
	var infoDiv              = document.createElement('div');
	infoDiv.id               = 'ytPlayerInfo';
	infoDiv.style.fontSize   = '0.8em';
	infoDiv.style.height     = '18px';
	infoDiv.style.left       = '22px';
	infoDiv.style.lineHeight = '18px';
	infoDiv.style.overflow   = 'hidden';
	infoDiv.style.position   = 'absolute';
	infoDiv.style.width      = '196px';
	
	volumeCtrl.appendChild(hrefMinus);
	volumeCtrl.appendChild(hrefMute);
	volumeCtrl.appendChild(hrefPlus);
	
	ctrl.appendChild(hrefPlay);
	ctrl.appendChild(infoDiv);
	ctrl.appendChild(volumeCtrl);
	
	document.getElementById('ytPlayerContainer').appendChild(ctrl);
}


function ytPlay() {
	var btn = document.getElementById('ytPlayButton');
	if(this.getPlayerState() == 1) {
		btn.src = '/images/ytPlay.gif';
		this.pauseVideo();
	}
	else {
		btn.src = '/images/ytPause.gif';
		this.playVideo();
	}
}

function ytMute() {
	var btn = document.getElementById('ytMuteButton');
	if(this.isMuted() == true) {
		btn.src = '/images/ytMute.gif';
		this.unMute();
	}
	else {
		btn.src = '/images/ytUnmute.gif';
		this.mute();
	}
}

function ytVolumeControl(i) {
	var vol = this.getVolume();
	vol = (vol+(i*10) > 0 || vol+(i*10) < 100) ? vol + (i*10) : vol;
	
	this.setVolume(vol);
}

function ytLoadVideo(movieId) {
	this.updateInfo(movieId);
	this.cueVideoById(movieId, 0);
	this.togglePlay();
}

function ytUpdateInfo(movieId) {
	info = document.getElementById('ytPlayerInfo');
	
	// set video-title
	info.innerHTML = '<div id="ytPlayerInfoTitel" style="cursor: default; display: inline; white-space: nowrap;">' + this.parent.videos[this.parent.videoIndex[movieId]].title.$t + '</div>';
	this.parent.scroller.set('ytPlayerInfoTitel');
	this.parent.scroller.init();
	
	// change selected items style
	var i = 1;
	for(var x in this.parent.videoIndex) {
		var id  = this.parent.videoIndex[x];
		var div = document.getElementById('VideoElement' + id);
		
		if(x == movieId)
			div.style.background = '#FFC299';
		else
			div.style.background = '#' + (i%2 == 0 ? 'ffffff' : 'edfbe3');
		
		i++;
	}
}

function onYouTubePlayerReady(playerId) {
	ytPlayer            = document.getElementById(playerId);
	ytPlayer.toggleMute = ytMute;
	ytPlayer.togglePlay = ytPlay;
	ytPlayer.loadVideo  = ytLoadVideo;
	ytPlayer.updateInfo = ytUpdateInfo;
	ytPlayer.vol        = ytVolumeControl;
	ytPlayer.parent     = document.getElementById('youtube').youtube;
	
	// append controls
	ytAppendControls();
	
	ytPlayer.cueVideoById(ytPlayer.parent.videos[0].movieId, 0);
	ytPlayer.updateInfo(ytPlayer.parent.videos[0].movieId);
}









function cellScroller(delay) {
	this.itemList = new Array();
	
	this.delay    = delay;
	
	this.set      = cellScrollerSetItem;
	this.init     = cellScrollerInit;
}

function cellScrollerSetItem(itemId) {
	this.itemList[this.itemList.length] = itemId;
}

function cellScrollerInit() {
	var tmpList = new Array();
	
	for(x in this.itemList) {
		if(document.getElementById(this.itemList[x])) {
			var obj = document.getElementById(this.itemList[x]);
			var clone = obj.cloneNode(true);
			
			// get real measures
			var maxWidth  = obj.offsetWidth;
			var viewWidth = obj.parentNode.offsetWidth;
			
			// content > view
			
			if(maxWidth > viewWidth) {
				// create new div for positioning
				var posDiv = document.createElement('div');
				posDiv.style.overflow = 'hidden';
				posDiv.style.position = 'relative';
				posDiv.style.width    = (obj.parentNode.offsetWidth) + 'px';
				//posDiv.style.height   = (obj.parentNode.offsetHeight) + 'px';
				posDiv.style.height   = '20px';
				
				// create tmp-node
				var tmp = obj.parentNode;
				
				clone.style.width = 'auto';
				
				// set object-id if not already set
				if(clone.id == '') {
					do {
						var randId = Math.random();
					} while(document.getElementById(randId));
					clone.id = 'sT' + Math.random();
				}
				
				clone.delay          = this.delay;
				clone.direction      = -1;
				clone.overflowWidth  = (maxWidth-viewWidth);
				clone.pos            = 0;
				clone.slide          = slideText;
				clone.style.position = 'absolute';
				
				clone.onmouseover = function() { this.stop = 0; this.slide(1); }
				clone.onmouseout = function() { this.stop = 1; }
				
				// append content to new div, than append new div to tmp-node
				posDiv.appendChild(clone);
				tmp.replaceChild(posDiv, obj);
			}
			
			tmpList.splice(x, 1);
		}
	}
	this.itemList = tmpList;
}

function slideText(event) {
	if(event && this.direction == 1)
		this.direction = -1;
	
	// if animation should not be stopped
	if(this.stop == 0 || (this.stop == 1 && this.pos != 0)) {
		
		// config
		var stepWidth = 2;
		var pause     = 10;
		
		
		if(this.stop == 1 && ((this.pos > 0 && this.direction == 1) || (this.pos < 0 && this.direction == -1)))
			this.direction = this.direction * (-1);
		
		
		// check if reached endpoint. if true -> set pause; if false switch direction and restart moving
		 if(this.pause == 0 && (this.interval && this.interval != -1) && (this.pos == 0 || this.pos == (-1)*this.overflowWidth || this.pos == (-1)*this.overflowWidth-1)) {
			this.pause = 1;
			this.pauseSteps++;
		}
		else if(this.pause == 1 && this.pauseSteps <= pause) {
			this.pauseSteps++;
		}
		else {
			this.pause      = 0;
			this.pauseSteps = 0;
			
			// check if border is reached
			if(this.direction == (-1) && this.pos > (this.overflowWidth*(-1))) {
				this.pos = this.pos - stepWidth;
			}
			else if(this.direction == 1 && this.pos < 0) {
				this.pos = this.pos + stepWidth;
			}
			// if border reached -> switch direction
			else {
				this.direction = this.direction * (-1);
			}
		}
		
		// set new position
		this.style.left = this.pos + 'px';
		
		// set interval
		if(!this.interval || this.interval == -1)
			this.interval = window.setInterval("document.getElementById('" + this.id + "').slide()", 30);
	}
	// if animation should be stopped
	else {
		this.stop             = 1;
		this.direction        = -1;
		this.pos              = 0;
		
		// clear interval
		window.clearInterval(this.interval);
		this.interval = -1;
	}
}



function separator(num) {
	var separated = '';
	
	var modulo = num.length % 3;
	
	if(modulo > 0)
		separated = num.substr(0, modulo);
	
	for(var substr = num.substr(modulo, 3); modulo < Math.round(num.length/3)+2; substr = num.substr(modulo, 3)) {
		separated = (separated.length > 0 ? separated + '.' : '') + substr;
		modulo = modulo+3
	}
	
	return separated;
}
