/*

name         Verkeer-In-Zicht 2010
author       Mark de Jong (http://www.spellcoder.nl)
copyright    (c) Senna Multimedia / Mark de Jong
website      http://www.senna.nu
version      september 2010



Mediatypes:
1	picture
2	YouTube movie
3	streetview
4	HTML				(experimental)
5	URL (for iframe)	(experimental)
6	Joomla quiz			(not implemented yet)


Youtube

		3D
		
		YouTube Pete (Google Employee) @ 7/21/09
		(Pete Bradshaw, de ontwikkelaar die de 3D functie in zijn 20% other projects tijd heeft gemaakt)
		"Embedding the 3D player is not currently supported. I'm unsure when this will be available."

		Zie ook:
		http://www.gizmodo.com.au/2010/05/how-youtube-3d-came-to-be/
		

StreetView

		Streetview thumbnails:
		- http://jamiethompson.co.uk/web/2010/05/15/google-streetview-static-api/

		Streetview docs
		- http://code.google.com/intl/en-US/apis/maps/documentation/javascript/reference.html - Generic API reference
		- http://code.google.com/intl/en-US/apis/maps/documentation/javascript/services.html  - Services and more specific streetview info

*/

function spcGallery(settings)
{
	this.name = 'Gallery';
	this.movie = null;			// movieplayer object
	this.container = null;
	this.previtemtype = null;
	this.currentviewer = null;

	this.itemlist = [];
	this.settings = settings;
	this.imagepath = settings.imagepath;
}

spcGallery.prototype.querymediaitems = function( pointID , keywordID )
{
/*
	console.log('Getting media for point '+pointID);
	console.log(mapmeta.items[pointID]);
*/	
	var mapitem = mapmeta.getItemById(pointID);
	
	if (!mapitem.media)
		return [];

	var galitems = medialist.getMediaItemsById( mapitem.media );
	
	// find any media items matching our query
	//console.log('Found '+galitems.length+' items.');

	var itemlist = [];
	for(var tel=0; tel<galitems.length; tel++)
	{
		var item = galitems[tel];
		itemlist.push(item);
	}
	
	return itemlist;
}

spcGallery.prototype.show = function( container, pointID , keywordID )
{
currentgallery = this; // HACK


	var self = this;
	this.itemlist = this.querymediaitems(pointID, keywordID);

	this.container = container;
	this.pointid = pointID;
	
// FIXME	
window.debugpointid = pointID;

	/*
	if ( itemlist.length == 0 )
	{
		container.style.cssText = '-moz-box-sizing: border-box; padding: 14px;';
		container.innerHTML = 'Geen plaatjes of video beschikbaar bij dit punt.';
		return;
	}
	*/

	this.createDOM();

    this.selector = new slidingselector(
    						{ thumbcontainer:		this.selthumbcont
							, items:         		this.itemlist
							, generatethumb:		function(itemdata)
													{
														return self.getthumb(itemdata);
													}
							, onselect:       		function(itemdata,galleryinfo)
													{
														self.showitem(itemdata);//.data);
													}
							, orientation:			'horizontal'
							, wrap:					true
							, thumbs_autoresize:	false
							, allowkeyboardnav:		true
							});

	this.handleResize();					
}

spcGallery.prototype.update = function()
{
	this.selector.setImageList(this.itemlist);
	
	// FIXME: restart/review current selection
}

spcGallery.prototype.createDOM = function()
{
	/*
		<div class="thumbbrowser_horizontal"> <-- contains selector, prev/next buttons, fades
			<div class="selectorwidget"> <-- the real sliding selector container
			  <div class="thumblistcontainer" id="thumblist"></div> <-- the scrolling container
			</div>
		</div>
	*/
	this.selcontainer = document.createElement('div');
	this.selcontainer.className = 'thumbbrowser_horizontal';

	this.selscrollviewport = document.createElement('div');
	this.selscrollviewport.className = 'selectorwidget';
	
	this.selthumbcont = document.createElement('div');
	this.selthumbcont.className = 'thumblistcontainer';
	
	if (product.state.devmode)
		this.selthumbcont.style.paddingTop = "14px"; // MAKE ROOM FOR THE EDIT BUTONS!
	
	
	this.selcontainer.appendChild(this.selscrollviewport);
	this.selscrollviewport.appendChild(this.selthumbcont);
	
	this.container.appendChild(this.selcontainer);

	var selfgallery = this;
/*
	if (product.state.devmode)
	{
		this.addmovielink = document.createElement('a');
		this.addmovielink.appendChild(document.createTextNode("YouTube movie toevoegen..."));
		this.addmovielink.onclick = function()
						{
							product.openYouTubeImportDialog({ pointid: selfgallery.pointid });
						}
		this.container.appendChild(this.addmovielink);
	}
*/
	this.mediaviewer = document.createElement('div');
	this.mediaviewer.className = 'mediaviewer';
	
	var tbl = document.createElement('table');
	tbl.style.width = '100%';
	tbl.style.height = '100%';
	var tbody = document.createElement('tbody');
//tbl.style.cssText = 'width: 100%; height: 100%; background-color: #0f0;';
	tbl.appendChild(tbody);

	var tr = document.createElement('tr');
	var td1 = document.createElement('td');
	var td2 = document.createElement('td');
	var td3 = document.createElement('td');
	td1.style.width = '100%';
	td2.style.cssText = 'width: 32px; min-width: 32px; max-width; 32px;';
	//td3.style.width = '100%'; // take all space not taken bij media
	tbody.appendChild(tr);
	tr.appendChild(td1);
	tr.appendChild(td2);
	tr.appendChild(td3);
	this.mediaviewer.appendChild(tbl);

	this.mediacontainer = document.createElement('div');
//	this.mediacontainer.style.cssText = 'margin: 0 auto;';
	this.mediacontainer.style.cssText = 'position: absolute; top: 0; left: 0; right: 0; bottom: 0;';

	/*
	this.mediacomments = document.createElement('div');
	this.mediacomments.className = 'mediacomments';

	this.mheader = document.createElement('h1');
	this.mheader.appendChild(document.createTextNode('Opmerkingen'));
	this.mediacomments.appendChild(this.mheader);
*/
	td1.appendChild(this.mediacontainer);
//	td3.appendChild(this.mediacomments);
	
	this.container.appendChild(this.mediaviewer);

/*
	<table style="width: 100%; height: 100%;"><tr><td></td></tr><tr>
	<td id="mediacontainertd"><div id="mediacontainer" style="margin: 0 auto;"></div></td>
	<td id="mediacomments"></td>
	</tr></table>
*/
}



spcGallery.prototype.showitem = function(itemdata)
{
	console.log('Playback requested for media #'+itemdata.id);

	if (this.previtemtype != itemdata.type)
	{
		if (this.currentviewer)
			this.currentviewer.deinit();
		
		this.previtemtype = itemdata.type;

		switch(itemdata.type)
		{
			// picture
			case 1:			this.currentviewer = new viewerImage(this);
							break;

			// YouTube video
			case 2:			this.currentviewer = new viewerYouTube(this);
							break;

			// Google Maps StreetView
			case 3:			this.currentviewer = new viewerStreetView(this);
							break;

			// include HTML (at own risk)
			case 4:			this.currentviewer = new viewerHTML(this);
							break;

			// include URL in iFrame (at own risk)
			case 5:			this.currentviewer = new viewerURL(this);
							break;
							
			default:		console.error('Gallery / Unknown gallery item type '+objItem.type);
							console.log(itemdata);
							return;
							break;
		}	
	}

	this.currentviewer.show(this, itemdata);
	this.currentviewer.onresize();
}

spcGallery.prototype.getthumb = function( objItem )
{
	var _this = this;
	var _vid = objItem;//.data;

	var objContC = document.createElement('span');			
	objContC.className = 'thumbcont';

	if (product.state.devmode)
	{
		objContC.style.position = "relative";

		var buttonbar = document.createElement("div");
		buttonbar.className = "gallery_buttonbar";
		buttonbar.style.cssText = '';

		if (objItem.type == 2 || objItem.type == 3)
		{
			var btn_edit = document.createElement('img');
			btn_edit.src = 'gfx/icons/image_edit.png';
			buttonbar.appendChild(btn_edit);

			btn_edit.onclick = function(e)
				{
					stopEvent(e);
					console.log(_vid);

					if (_vid.type == 2)
						var editdialog = new videoEditDialog({item:_vid});

					if (_vid.type == 3)
						var editdialog = new streetviewEditDialog({item:_vid});
					
					return false;
				};
			buttonbar.appendChild(btn_edit);
		}

		var btn_delete = document.createElement('img');
		btn_delete.src = 'gfx/icons/delete.png';
		btn_delete.onclick = function(e)
			{
				if (confirm("Weet je zeker dat je het YouTube filmpje bij dit punt wil verwijderen?"))
					medialist.removeFromMapPoint(_vid.id, _this.pointid);

				stopEvent(e);
			}
		buttonbar.appendChild(btn_delete);

		objContC.appendChild(buttonbar);
	}

	
	
	var objCaption = document.createElement('div');
	objCaption.className = 'galItemCaption';
    if (objItem.data.title != undefined)
		objCaption.innerHTML = objItem.data.title;

	var pic	= document.createElement('img');
	pic.onerror	= _this.picLoadError;

	switch (objItem.type)
	{	
		case 1: // 1=image, 4=html, 5=urliniframe
			pic.className	= 'galItemThumbC';
			pic.instance	= objItem;
			//pic.src			= objItem.thumb.src;
			pic.src = this.imagepath+product.map+'/w160/'+objItem.data.src;
			
			objContC.appendChild(pic);
			break;

		case 2: // video
			if (pic.src != "")
			{
				// thumbnail hosted by self
				pic.src = this.imagepath+'youtube/'+objItem.data.src+'.jpg';
			}
			else
			{
				// hotlink to thumnail on youtube
				// FIXME how to know if it's the default thumbnail on YouTube?
//http://i1.ytimg.com/vi/LiIboq6XCOg/default.jpg
// 0 = 480x360
// 1/2/3 = 128x96
				pic.src = 'http://img.youtube.com/vi/'+objItem.data.src+'/2.jpg';
			}

			var picPlay	= document.createElement('div');
			picPlay.className = 'btnGalPlay';

			var objCont = document.createElement('div');
			objCont.className = 'galItemThumbC';
			objCont.instance = objItem;

			objCont.appendChild( pic );
			objCont.appendChild( picPlay );

			objContC.appendChild(objCont);
			
			break;

		case 3: // streetview
		case 4: // HTML
		case 5: // URL in iframe
			if(!objItem.data.src || objItem.data=="")
			{
				pic.className	= 'galItemThumbC';
				pic.instance	= objItem;
				pic.src = 'gfx/gallery/street_view.png';
				
				objContC.appendChild(pic);
			}
			
			var txt = document.createTextNode('StreetView');
			objContC.appendChild(txt);
			break;
			
		default:
			console.error('Gallery / Unknown gallery item type '+objItem.type);
			break;
	}

	objContC.appendChild(objCaption);
	
	return objContC;
}

spcGallery.prototype.picLoadError = function()
{
	console.warn('Failed to load thumbnail.');
	this.onerror = null;
	this.setAttribute('failedsrc', this.src);
	this.src = this.imagepath+'placeholder_160x128.png';
}


// use an iframe to use Google Maps V2 API's Flash version of StreetView
viewerStreetView = function(galinstance)
{
	this.galinstance = galinstance;

	this.pcontainer = document.createElement('iframe');
	this.pcontainer.frameBorder = "0";
	this.pcontainer.style.cssText = 'width: 100%; height: 100%;';// border: 1px solid #f00;';
	galinstance.mediacontainer.appendChild(this.pcontainer);
}

viewerStreetView.prototype.deinit = function()
{
	this.pcontainer.parentNode.removeChild(this.pcontainer);
}

viewerStreetView.prototype.show = function(galinstance, iteminstance)
{
	this.pcontainer.src = "content/flashstreetview.php?lat="+iteminstance.data.lat+"&lng="+iteminstance.data.lng+"&yaw="+iteminstance.data.yaw+"&pitch="+iteminstance.data.pitch+"&zoom="+iteminstance.data.zoom;
	//this.pcontainer.document.set(iteminstance);

	// IE and Opera will only resize with width/height 100% to it's container if it's an absolute size
	// not when it's sized with top+bottom & left+right.
	var newwidth = this.galinstance.mediacontainer.clientWidth;
	var newheight = this.galinstance.mediacontainer.clientHeight;
	this.pcontainer.style.cssText = 'width: '+newwidth+'px; height: '+newheight+'px';
}

viewerStreetView.prototype.onresize = function()
{
}


/*
Google Maps V3 StreetView

viewerStreetView = function(galinstance)
{
	this.pinstance = null;
	this.galinstance = galinstance;

	this.pcontainer = document.createElement('div');
	this.pcontainer.style.cssText = 'position: absolute; top: 0; bottom: 0; left: 0; right: 0; border: 1px solid #f00;';
	galinstance.mediacontainer.appendChild(this.pcontainer);
}

viewerStreetView.prototype.deinit = function()
{
	if (this.pinstance)
	{	
		//this.pinstance.remove();// FIXME: not needed anymore for Google Maps V3 ?
		this.pcontainer.parentNode.removeChild(this.pcontainer);
		this.pinstance = null;
	}
}

viewerStreetView.prototype.show = function(galinstance, iteminstance)
{
	// since we don't support jumping to a new position yet, we recreate a panoramic instance
	//this.deinit();

	var svdata = iteminstance.data;

	var optLatLng = new google.maps.LatLng(svdata.lat, svdata.lng);
	var optPOV = { heading:		svdata.yaw // yaw in GMaps V2
			, pitch:	svdata.pitch
			, zoom:		svdata.zoom
			};
	
	if (!this.pinstance)
	{
		var options = {
			  position: optLatLng
			, pov: optPOV
			, visible: true
				};
	
		this.pinstance = new google.maps.StreetViewPanorama(this.pcontainer, options);
	}
	else
	{
		this.pinstance.setPosition(optLatLng);
		this.pinstance.setPov(optPOV);
	}

	// IE and Opera will only resize with width/height 100% to it's container if it's an absolute size
	// not when it's sized with top+bottom & left+right.
	var newwidth = this.pcontainer.clientWidth;
	var newheight = this.pcontainer.clientHeight;
	this.pcontainer.style.cssText = 'width: '+newwidth+'px; height: '+newheight+'px';
	
	//pano = this.pinstance; // for debugging
}

viewerStreetView.prototype.onresize = function()
{
// FIXME: is this still needed for Google Maps V3 ?
//	this.pinstance.checkResize();
}
*/


viewerImage = function(galinstance)
{
	this.galinstance = galinstance;

	this.domcreated = false;
	
	var container_image = document.createElement('div');
	container_image.className = 'galPaper';
	
	var galGZ = document.createElement('img');
	galGZ.className = 'galZoom';

	var galTXT = document.createElement('div');
	galTXT.className = 'galZoomTxt';
	
	//var frag = document.createDocumentFragment();
	galinstance.mediacontainer.appendChild(container_image); //(galDisplay);

	//galDisplay.appendChild(container_image);
	container_image.appendChild(galGZ);
	container_image.appendChild(galTXT);

	//container.appendChild(this.mediacontainer);
	
	this.container_image	= container_image;//galDisplay;	// can be used to determine max avail width/height

	this.elempaper		= container_image;
	this.elemzoom		= galGZ;		// the enlarged picture
	this.elemtext		= galTXT;		// description

	this.elemzoomnext	= null;

	this.elemloading	= document.createElement('div');
	this.elemloading.className = 'galLoading';
	this.elemloading.appendChild( document.createTextNode('de volgende afbeelding wordt geladen...') );
	container_image.appendChild(this.elemloading);
}

viewerImage.prototype.deinit = function()
{
	this.container_image.style.display = 'none';
}

viewerImage.prototype.show = function(galinstance,iteminstance)
{
	this.container_image.style.display = 'block';

	this.elemloading.innerHTML = 'De volgende afbeelding wordt geladen.';
	this.elemloading.style.display = 'block';

	this.elempaper.style.display = '';

	
	var nextimg = document.createElement('img');
//    var nextimg = new Image();

	nextimg.className = 'galZoom';
	this.elemzoomnext = nextimg;
	
	// show later when size is known
/*	if (!useragent.csssupport.maxsize) */
    var _this = this; // galinstance
	nextimg.onload = function() {
		// if the browser doesn't support naturalWidth (FF2 & SF3.1 do, IE and OP don't)
		// add this info (because later on the width/height won't be the original size anymore)
		if (_this.naturalWidth == undefined) {
			_this.naturalWidth = _this.width;
			_this.naturalHeight = _this.height;
		}

		_this.resizePic(this);

		_this.elempaper.replaceChild(this, _this.elemzoom);
		_this.elemzoom = this;
//	var marginTop = (maxheight-sizeH)/2;
//	elem.parentNode.style.marginTop = marginTop+'px;';

		_this.elemloading.style.display = 'none';
	}
	nextimg.onerror = function() {
//		_this.elemzoom.parentNode.removeChild(_this.elemzoom);
//		_this.elemloading.innerHTML = 'Kon de afbeelding niet inladen.';
		_this.elemloading.style.display = 'none';
	}

	nextimg.src = this.imagepath+product.map+'/large/'+iteminstance.data.src;
//	if (spcApp.maxsizeSupport) imgPic.style.display = 'block'; // show now, the browser will handle resizing

	if (iteminstance.description)
		this.elemtext.innerHTML = objPic.description;
}

viewerImage.prototype.onresize = function()
{
	//resizePic()
}

viewerImage.prototype.resizePic = function(elem)
{	
	var sizecontainer = this.galinstance.mediaviewer; // determine how much room we have based on the mediaviewer div

	var availwidth = sizecontainer.clientWidth - 7*2; /* 7=padding */
	var availheight = sizecontainer.clientHeight - 7*2;

	this.resizePicture(elem, availwidth, availheight);
}

viewerImage.prototype.resizePicture = function(elem, maxwidth, maxheight)
{
	// 7*2 borders
	maxwidth -= 14;
	maxheight -= 14+10;

	var shrinkW = elem.width  / maxwidth;
	var shrinkH = elem.height / maxheight;
	var shrink  = (shrinkW > shrinkH) ? shrinkW : shrinkH;

	var sizeW = elem.width  / shrink;
	var sizeH = elem.height / shrink;
	
//	var marginTop = (maxheight-sizeH)/2;

/*	alert('<img> src: '+elem.src+'\n'+
		'new size: '+sizeW+'x'+sizeH);
*/

//	elem.style.cssText = 'width: '+sizeW+'px; height: '+sizeH+'px; -ms-interpolation-mode: bicubic;';
//	elem.style.cssText = 'width: '+sizeW+'px; height: '+sizeH+'px; margin-top: '+marginTop+'px;';

	elem.style.cssText = 'width: '+sizeW+'px; height: '+sizeH+'px;';

//	if (elem.style.cssText == '')
//	  alert('failure');
}




viewerHTML = function(galinstance)
{
	this.galinstance = galinstance;

	this.container = document.createElement('div');
	//container.className = 'galPaper';
	//container.innerHTML = "";
	this.container.style.display = "none";
	galinstance.mediacontainer.appendChild(this.container);
}

viewerHTML.prototype.deinit = function()
{
	this.container.parentNode.removeChild(this.container);
}

viewerHTML.prototype.show = function(galinstance,iteminstance)
{
	this.container.innerHTML = iteminstance.data.src;
	this.container.style.display = "block";
}

viewerHTML.prototype.onresize = function()
{
  // ADDME?
}



viewerURL = function(galinstance)
{
	this.galinstance = galinstance;

	this.ifrm = document.createElement('iframe');
	this.ifrm.style.cssText = "width: 100%; height: 100%;";
	if (useragent.isIE)
	{
		this.ifrm.allowTransparency = 'true'; // so IE won't force #FFFFFF as default background color
		this.ifrm.frameBorder = '0';          // IE has an extra border within the iFrame which also needs to be disabled
	}
	
	this.ifrm.style.display = "none";
	galinstance.mediacontainer.appendChild(this.ifrm);
}

viewerURL.prototype.deinit = function()
{
	this.ifrm.parentNode.removeChild(this.ifrm);
}

viewerURL.prototype.show = function(galinstance,iteminstance)
{
	this.ifrm.src = iteminstance.data.src;
	this.ifrm.style.display = "block";
}

viewerURL.prototype.onresize = function()
{
  // ADDME?
}






spcGallery.prototype.handleResize = function()
{
	if (this.currentviewer)
		this.currentviewer.onresize();

return;
//	if (this.thumbstripver == undefined)
//	  return;

//	if (useragent.isIE)
//		this.thumbstripver.style.height = (this.container.clientHeight)+'px'; //wndMedia.getBodyHeight()

	if (!this.mediacontainer)
	{
		console.log('Gallery / onresize called before mediagallery was ready.');
		return;
	}

	this.resizePic( this.elemzoom );
/*	
	if (this.video != null)
	{
		var availwidth = this.container.clientWidth - 245; // body width - paddings
		var availheight = this.container.clientHeight + 4;
		this.video.player.setSize(availwidth, availheight);
	}	
*/
}





function onYouTubePlayerReady(playerid)
{
	playerid = parseInt(playerid);

	viewerYouTubeInstances[playerid].isready = true;
	viewerYouTubeInstances[playerid].onplayerready();

	console.log('YouTube player with id '+playerid+' reporting for duty');
}

/*
function onYouTubePlayerReady(playerId)
{
    ytplayer = document.getElementById('myytplayer');
    setInterval(updateytplayerInfo, 250);
    updateytplayerInfo();
    ytplayer.addEventListener('onStateChange', 'onytplayerStateChange');
    document.getElementById('controls').style.display = 'block';
}
*/

/*****************
YouTube support
*****************/

viewerYouTubeIDcount = 0;
viewerYouTubeInstances = [];

viewerYouTube = function(galinstance)
{
	viewerYouTubeIDcount++;
	viewerYouTubeInstances[viewerYouTubeIDcount] = this;
	this.youtubeviewerid = viewerYouTubeIDcount;
	this.initvideocode = '';
	this.isfirst = true; // first time to be run
	this.isready = false;

	this.container_video = document.createElement('div');
	this.container_video.className = 'galDisplay videoYouTube';
	this.container_video.style.display = 'block';

	this.galinstance = galinstance;
	galinstance.mediacontainer.appendChild(this.container_video);
}

viewerYouTube.prototype.onplayerready = function()
{
	console.log('viewerYouTube instance recieved ready');

	this.player = document.getElementById('ytplayer_'+this.youtubeviewerid);
	
	if (this.initvideocode)
	{
		this.player.loadVideoById(this.initvideocode, 0, 'large');
		this.player.setPlaybackQuality('large');
//getAvailableQualityLevels
		this.initvideocode = '';
	}
}

viewerYouTube.prototype.deinit = function()
{
	viewerYouTubeInstances[viewerYouTubeIDcount] = null;
//FIXME: slice?
	delete viewerYouTubeInstances[viewerYouTubeIDcount]; // possible??

	this.container_video.style.display = 'none';
	this.container_video.innerHTML = ''; // destroy
	this.container_video.parentNode.removeChild(this.container_video);
}

viewerYouTube.prototype.show = function(galinstance, item)
{
//	if (this.isfirst)
//	{	
		//this.generateYouTubeEmbed(item);
		this.generateEmbed2(item);
		this.isfirst = false;
/*
	}
	else
	{
		if (this.isready)
		{		
			this.player.loadVideoById(item.data.src, 0, 'large');
			this.player.setPlaybackQuality('large');
		}
		else
			this.initvideocode = item.data.src;
	}
*/
}

viewerYouTube.prototype.onresize = function()
{
	var commentsbarminwidth = 150;

	var sizecontainer = this.galinstance.mediaviewer; // determine how much room we have based on the mediaviewer div
	
	var availwidth = sizecontainer.clientWidth - commentsbarminwidth;
	var availheight = sizecontainer.clientHeight;
	
	// grow to fit but keep aspect ratio of 16:9
	var multiplyerforwidth = availwidth/16;//*9;
	var multiplyerforheight = availheight/9;//*16;
	
	if (multiplyerforwidth < multiplyerforheight)
	{
		var newwidth = availwidth;
		var newheight = availwidth/16*9;
	}
	else
	{
		var newwidth = availheight/9*16;
		var newheight = availheight;
	}

	//console.log('Resizing mediacontainer to '+newwidth+'x'+newheight);
	//console.log('Based on available room of '+availwidth+'('+multiplyerforwidth+')x'+availheight+'('+multiplyerforheight+')');
	
	this.container_video.style.width = newwidth+'px';
	this.container_video.style.height = newheight+'px';	
}

/*
viewerYouTube.prototype.pause = function()
{
	if (this.youtubeplayer && this.youtubeplayer.pauseVideo)
	{
		this.youtubeplayer.pauseVideo();
	}
}
*/


viewerYouTube.prototype.generateEmbed2 = function(mediaitem)
{
	//<iframe title="YouTube video player" class="youtube-player" type="text/html" width="640" height="390" src="http://www.youtube.com/embed/QDe6MZQjpho" frameborder="0"></iframe>
	var ifrm = document.createElement("iframe");
	ifrm.type = "text/html"
	ifrm.style.width = "100%";
	ifrm.style.height = "100%";
	ifrm.style.border = "0";
	ifrm.frameborder = "0"; // needed for IE
	ifrm.src = "http://www.youtube.com/embed/"+mediaitem.data.src+"?"+this.getYouTubeArgs(mediaitem);
	
	this.container_video.innerHTML = "";
	this.container_video.appendChild(ifrm);
}

/*
http://code.google.com/intl/de-DE/apis/youtube/js_api_reference.html
http://code.google.com/apis/youtube/chromeless_example_1.html
*/
viewerYouTube.prototype.getYouTubeArgs = function(mediaitem)
{
	/*
	YouTube Embedded Player Parameters
	http://code.google.com/apis/youtube/player_parameters.html
	*/

	var options =	{ hl:			'nl'
					, fs:			true				// enable the fullscreen button
					, autoplay:		true
					, loop:			false
					, enablejsapi:	true
					, disablekb:	false				// disable player keyboard controls
					, rel:			false				// show related movies =0(false)
					, showsearch:	false				// show search box (if rel is also on)
					, egm:			false				// Enhanced Genie Menu (appears when mouse enters the video display area)
					, showinfo:		false
			//		, iv_load_policy: 1					// 1=always show annotations, 3=never show annotations
			//		, cc_load_policy: 1					// 1=force closed captions
					, hd:			product.config.use_hq_video	// High Definition   (doesn't take the higher def one but only high as in 720p ?)
					, playerapiid:	/*'ytplayer_'+*/''+this.youtubeviewerid
					,"yt3d:enable":	"true"
					,"yt3d:aspect":	"16:9"
					};

//yt3d:swap=
//yt3d:left/right ?
					
	var optarr = [];
	for(var opt in options)
	{
		var type = typeof options[opt];
		switch(type)
		{
			case 'string':	optarr.push(opt+'='+options[opt]);
							break;
			case 'number':	optarr.push(opt+'='+options[opt]);
							break;
			case 'boolean':	optarr.push(opt+'='+(options[opt]==true?'1':'0'));
							break;
		}
	}
	var optionsstring = optarr.join('&');
	return optionsstring;
}
viewerYouTube.prototype.generateYouTubeEmbed = function(mediaitem)
{
	/*
	Setting quality
	
	&ap=%2526fmt%3D18 	Changing the quality
	&autoplay=1		Autoplay on
	
	
	Quality API-Code	Bandwidth	Videosize	FPS		Codec			Audio Codec/Frequency/Kbps
	normal				200 kbps	320x240		30fps	Flash Sorenson	MP3, 22KHz 64 kbps Mono ABR
	fmt=6				900 kbps	480x360		30fps	Flash Sorenson	MP3, 44.1KHz 96 kbps Mono CBR
	fmt=18				512 kbps	480×360		24fps	H264			AAC, 44.1KHz 128 kbps Stereo
	fmt=22										(HD)

	Player-API JS
	small  -  < 640 x 360
	medium -    640 x 360 +
	large  -    854 x 480 +
	hd720  -   1280 x 720
	default

	*/
	
	var mdata = mediaitem.data;
	
	// find the highest available video format
	if (mdata.formatlist != null) {
		var formatlist = mdata.formats.split(',');
		var fcode=0;
	
		for(var nr=0; nr<formatlist.length; nr++)
		  if (formatlist[nr] > fcode)
		    fcode=formatlist[nr];
	
		if (fcode==0)
			var qualitycode = '';
		else
			var qualitycode = '&ap=%2526fmt%3D'+fcode;
	}
	else
		qualitycode = '';
	
			
    var optionsstring = this.getYouTubeArgs(mediaitem)
	var vidurl = 'http://www.youtube.com/v/'+mdata.src+'?'+optionsstring;
	//var vidurl = 'http://www.youtube.com/v/?'+optionsstring;
	//console.log(vidurl);
	

	/*
	- Firefox wants type="application/x-shockwave-flash" and the vidurl in object as data attribute instead of param
	- Internet Explorer needs the vidurl to be in <param name="movie" value="..."></param>
	*/
	this.container_video.innerHTML =
	  '<object id="ytplayer_'+this.youtubeviewerid+'" class="videoplayer" style="width:100%;height:100%;" type="application/x-shockwave-flash" data="'+vidurl+'">'
	 +'<param name="bgcolor" value="#555555">'
	 +'<param name="wmode" value="opaque"></param>'
	 +'<param name="movie" value="'+vidurl+'"></param>'
	 +'<param name="allowScriptAccess" value="always"></param>'
	 +'<param name="allowFullScreen" value="true"></param>'
	 +'<p><a href="http://get.adobe.com/flashplayer">Get Flash</a> to see this player.</p>'
	 +'</object>';
/*
	// youtube default embedcode
	this.container_video.innerHTML =
		  '<object class="videoplayer" style="width:100%;height:100%;">'
		 +'<param name="bgcolor" value="#555555">'
		 +'<param name="wmode" value="opaque"></param>'
		 +'<param name="movie" value="'+vidurl+'"></param>'
		 +'<param name="allowScriptAccess" value="always"></param>'
		 +'<param name="allowFullScreen" value="true"></param>'
		 +'<embed style="width:100%;height:100%;" src="'+vidurl+'" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" class="videoplayer" wmode="opaque" bgcolor="#555555"></embed>'
		 +'</object>';
*/
}
