// -----------------------------------------------------------------------------------
//	Video Light v0.82
// by Christoph Hofmann - http://www.its-hofmann.de
//
// based on 
//	Lightbox 
//	by Lokesh Dhakar - http://www.lokeshdhakar.com
//
//	Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/


//
//  Configurationl
//
LightvideoOptions = Object.extend({
    fileLoadingImage:        'typo3conf/ext/its_youtube_overlay/res/loading.gif',
    fileLoadingImage1:        'typo3conf/ext/its_youtube_overlay/res/overlay.gif',
    fileBottomNavCloseImage: 'typo3conf/ext/its_youtube_overlay/res/closelabel.gif',
    fileBottomNavCloseImageTR: 'typo3conf/ext/its_youtube_overlay/res/close.gif',

    overlayOpacity: 0.8,   // controls transparency of shadow overlay

    animate: true,         // toggles resizing animations
    resizeSpeed: 2,        // controls the speed of the image resizing animations (1=slowest and 10=fastest)

    borderSize: 0,         //if you adjust the padding in the CSS, you will need to update this variable

	// When grouping images this is used to write: Image # of #.
	// Change it for non-english localization
	labelImage: "Image",
	labelOf: "of"
}, window.LightvideoOptions || {});

// -----------------------------------------------------------------------------------
  function onYouTubePlayerReady(playerId) {

		ytplayer = document.getElementById("video2");
		mylightvid.updatevideoDetails();

		if (ytplayer) {			
			ytplayer.setPlaybackQuality('hd720');
			ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
			hdpic  = document.getElementById("videoloading1");
		
			
		}
	}
	
	function onytplayerStateChange(newState) {
		if (newState == 0) {
		   mylightvid.end();
		 }
	}

	
var Lightvideo = Class.create();

Lightvideo.prototype = {
    videoArray: [],
    activeVideo: undefined,
    currentWidth:undefined,
    currentHeight:undefined,
    currentID:undefined,
    none:undefined,
    isiPad:undefined,
    
    
    
    trim: function (strvar) {
      // Erst führende, dann Abschließende Whitespaces entfernen
      // und das Ergebnis dieser Operationen zurückliefern
      return strvar.replace (/^\s+/, '').replace (/\s+$/, '');
    },

    // initialize()
    // Constructor runs on completion of the DOM loading. Calls updateIVideoList and then
    // the function inserts html at the bottom of the page which is used to display the shadow 
    // overlay and the image container.
    //
    initialize: function() {    
        
        this.updateIVideoList();
        
        this.isiPad = navigator.userAgent.match(/iPad/i) != null;
	if ( ! this.isiPad) {
	        this.isiPad = navigator.userAgent.match(/Win64; x64/i) != null;
	}



        if (LightvideoOptions.resizeSpeed > 10) LightvideoOptions.resizeSpeed = 10;
        if (LightvideoOptions.resizeSpeed < 1)  LightvideoOptions.resizeSpeed = 1;

	    this.resizeDuration = LightvideoOptions.animate ? ((11 - LightvideoOptions.resizeSpeed) * 0.15) : 0;
	    this.overlayDuration = LightvideoOptions.animate ? 0.2 : 0;  // shadow fade in/out duration

        // When Lightvideo starts it will resize itself from 250 by 250 to the current image dimension.
        // If animations are turned off, it will be hidden as to prevent a flicker of a
        // white 250 by 250 box.
        var size = (LightvideoOptions.animate ? 250 : 1) + 'px';
        

        var objBody = $$('body')[0];
        var element = Builder.node('p', { className:'error' }, 'An error has occurred');


	objBody.appendChild(Builder.node('div',{id:'overlay'}));
	objBody.appendChild(Builder.node('div',{id:'videobox'},[
		Builder.node('div',{id:'outerVideoContainer'}, [
		Builder.node('div',{id:'videoloading1'}, 
				Builder.node('a',{id:'videoloadingLink1', href: '#' }, 
				Builder.node('img', {src: LightvideoOptions.fileLoadingImage1})
		)),
		Builder.node('div',{id:'bottomNavTR'},
			Builder.node('a',{id:'bottomNavCloseTR', href: '#' },
			Builder.node('img', { src: LightvideoOptions.fileBottomNavCloseImageTR }))
		),
		Builder.node('div',{id:'video2'}),
			Builder.node('div', {id:'videoDataContainer'},
			
				Builder.node('div',{id:'videoData'}, [
					Builder.node('span',{id:'video_caption'}),
					
					Builder.node('div',{id:'bottomNav'},
						Builder.node('a',{id:'bottomNavClose', href: '#' },
						Builder.node('img', { src: LightvideoOptions.fileBottomNavCloseImage })
					)					
				
			)
			])
			),
			
			
		Builder.node('div',{id:'videoloading'}, 
			Builder.node('a',{id:'videoloadingLink', href: '#' }, 
			Builder.node('img', {src: LightvideoOptions.fileLoadingImage})
			)),

	
		]),

	]));
	

	

		$('overlay').hide().observe('click', (function() { this.end(); }).bind(this));
		$('bottomNavCloseTR').observe('click', (function(event) { event.stop(); this.end(); }).bind(this));
		$('bottomNavClose').observe('click', (function(event) { event.stop(); this.end(); }).bind(this));
		$('videobox').hide().observe('click', (function(event) { if (event.element().id == 'videobox') this.end(); }).bind(this));
		$('bottomNavCloseTR').hide();
		
	
		$('videoloadingLink').observe('click', (function(event) { event.stop(); this.end(); }).bind(this));
		$('outerVideoContainer').observe('click', (function(event) { event.stop(); this.end(); }).bind(this));
		$('video2').observe('click', (function(event) { alert('2'); event.stop(); this.end(); }).bind(this));


        var th = this;
        (function(){
            var ids = 
                'overlay outerVideoContainer lightvideoObject lightvideoObject2 videoloading loadingLink video2 ' + 
                'videobox videoData videoDataContainer videoDetails video_caption numberDisplay bottomNav bottomNavClose bottomNavCloseTR';   
            $w(ids).each(function(id){ th[id] = $(id); });
        }).defer();
    },

    //
    // updateIVideoList()
    // Loops through anchor tags looking for 'lightbox' references and applies onclick
    // events to appropriate links. You can rerun after dynamically adding images w/ajax.
    //
    updateIVideoList: function() {   
        this.updateIVideoList = Prototype.emptyFunction;

        document.observe('click', (function(event){
            var target = event.findElement('a[rel^=lightvideo]') || event.findElement('area[rel^=lightvideo]');
            if (target) {
                event.stop();
                this.start(target);
            }
        }).bind(this));
      
    },
    
    //
    //  start()
    //  Display overlay and lightbox. If image is part of a set, add siblings to imageArray.
    //
	start: function(imageLink) {
		$$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden' });
		this.videoArray = [];
      this.videoNum = 0;       
	 	if ((imageLink.rel == 'lightvideo')){
	            // if image is NOT part of a set, add single image to videoArray
            this.videoArray.push([imageLink.href, imageLink.title,imageLink.target]);    
      }
    	this.initvideo(this.videoArray[this.videoNum][2]);
    	
		
		this.videoDataContainer.hide();
		var arrayPageScroll = document.viewport.getScrollOffsets();
		var videoboxTop = arrayPageScroll[1] + (document.viewport.getHeight() / 10);
		var videoboxLeft = arrayPageScroll[0];
		this.videobox.setStyle({ top: videoboxTop + 'px', left: videoboxLeft + 'px' }).show();
		var arrayPageSize = this.getPageSize();
		if (LightvideoOptions.animate) this.videoloading.show();
		$('overlay').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' });
		this.overlay.setStyle({opacity: .0001});
		this.outerVideoContainer.setStyle({opacity: .0001});
		
		new Effect.Opacity(this.overlay,{from:0,to: 0.8,duration: this.overlayDuration});
		//eval("alert('2')");
		eval(LightvideoOptions.onload);
   	this.overlay.show();
   	this.outerVideoContainer.style.display='block';

   	new Effect.Opacity(this.outerVideoContainer,{
		from:0,
		to: 1,
		duration: this.overlayDuration,
		afterFinish: (function(){
			
		 	this.resizeVideoContainer( this.currentWidth , this.currentHeight);
		 	
	   			
		
		}).bind(this)
   	});
   	

	
    },
  
	initvideo: function (target) {
	
		dataarray=  target.split("::");
		for(i = 0; i < dataarray.length; i++){			
			localdataarray=  this.trim(dataarray[i]).split(":");			
			for(j = 0; j < localdataarray.length; j++){
				if (j==0) {
					if (localdataarray[j] == 'width' ) {
						if (localdataarray[1]) { this.currentWidth = parseInt(localdataarray[1]) ;}
					}
					else if (localdataarray[j] == 'height' ) {
						if (localdataarray[1]) { this.currentHeight= parseInt(localdataarray[1]) ;}
					}
					else	if (localdataarray[j] == 'id' ) {
						if (localdataarray[1]) { this.currentID = localdataarray[1] ;}
					}
				}
				
				
			}
		}

		

	},
 

    //
    //  resizeVideoContainer()
    //
    resizeVideoContainer: function(imgWidth, imgHeight) {
    
    	

		widthCurrent  = this.outerVideoContainer.getWidth();
		heightCurrent = this.outerVideoContainer.getHeight();
			  // get new width and height
		widthNew  = (imgWidth  + LightvideoOptions.borderSize * 2);
		var heightNew = (imgHeight + LightvideoOptions.borderSize * 2);
		  var xScale = (widthNew  / widthCurrent)  * 100;
		yScale = (heightNew / heightCurrent) * 100;
		wDiff = widthCurrent - widthNew;
		hDiff = heightCurrent - heightNew;
		
		if (this.isiPad) {
			this.currentHeight-=23;
		}
		
	
		if (hDiff != 0) new Effect.Scale(this.outerVideoContainer, yScale, {
			scaleX: false,
			duration: this.resizeDuration, 
			scaleContent:false,
			queue: 'front'
			
			});
			
		if (wDiff != 0) new Effect.Scale(this.outerVideoContainer, xScale, {
			scaleY: false, 
			duration: this.resizeDuration,
			delay: this.resizeDuration,
			scaleContent:false,
			afterFinish: (function(){ 
		
				var params = { allowScriptAccess: "always" };
				var atts = { id: "video2" };
				
				if (this.isiPad) {
				
					$('video2').innerHTML='<iframe width="'+this.currentWidth+'" height="'+this.currentHeight+'" frameborder="0" src="http://www.youtube.com/embed/'+this.currentID+'?autoplay=0&border=0" type="text/html" class="youtube-player"></iframe>';
				} else {
				swfobject.embedSWF("http://www.youtube.com/v/"+  this.currentID + "?enablejsapi=1&playerapiid=ytplayer", 
				"video2", this.currentWidth,  this.currentHeight, "8", null, null, params, atts); 
				}
				this.videoloading.hide();
				this.bottomNavCloseTR.setStyle({position: 'absolute', left: this.currentWidth - 5 +'px'});
				this.bottomNavCloseTR.setStyle({ top: '-25px'});
				this.bottomNavCloseTR.setStyle({ zIndex: 0});
		 		this.bottomNavCloseTR.show();
				
				}).bind(this)
		}); 
	
	},
	
 	updatevideoDetails: function() {
 		
 		
 		
 		widthCurrent  = this.outerVideoContainer.getWidth();
 		heightCurrent = this.outerVideoContainer.getHeight();
 	
 		
 		if (this.videoArray[this.videoNum][1] != "" ) { 		
			this.video_caption.update(this.videoArray[this.videoNum][1]).show();
 		}
 		
 	
 		
 		
 	
 		heightNew = heightCurrent + 10;
 	
 		yScale = (heightNew / heightCurrent) * 100; 		
 		hDiff = heightCurrent - heightNew;
 		if (hDiff != 0) new Effect.Scale(this.outerVideoContainer, yScale, {
				scaleX: false,
				duration: this.resizeDuration, 
				delay:1,
				afterFinish: (function () {
					this.bottomNavClose.show();
					this.videoDataContainer.show();
				}).bind(this)
				
		})
	

		
	},
	 
    
    //
    //  end()
    //
	end: function() {
		$$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' });
		
		swfobject.removeSWF('video2');
		if (this.isiPad) {
			var d = document.getElementById('outerVideoContainer');
			var olddiv = document.getElementById('video2');
			d.removeChild(olddiv);
		}


		
		var newvideo2 = new Element('div', { id: 'video2'});
		this.outerVideoContainer.insert({top:newvideo2});
		this.videobox.hide();
		this.bottomNavCloseTR.hide();
		this.outerVideoContainer.setStyle({height:'250px'});
		this.outerVideoContainer.setStyle ({width:'250px'});
		//this.overlay.hide();
		  new Effect.Opacity(this.overlay,{from:0.8,to: 0,
		        	duration: this.overlayDuration*2,
		        	afterFinish:(function() {
		        		this.overlay.hide()
		        	}).bind(this)
		        	
        });
        eval(LightvideoOptions.onunload);
        
        
		return;
	
		
	
	
		
		this.video2.hide();
		this.video2.style.visibility = 'hidden' ;
		var heightCurrent = this.outerVideoContainer.getHeight();
		var heightNew = heightCurrent - 180;
		var yScale = (heightNew / heightCurrent) * 100; 		
		var hDiff = heightCurrent - heightNew;
		if (hDiff != 0) new Effect.Scale(this.outerVideoContainer, yScale, {
			scaleX: false,
			duration: this.resizeDuration, 
			queue: 'front',
			afterFinish: (function () {
		this.videobox.hide();
		this.overlay.hide();
		this.outerVideoContainer.setStyle({height:'250px'});
		this.outerVideoContainer.setStyle ({width:'250px'});
		this.videobox.setStyle({ top: '0px', left: '0px' }).hide();
		
			}).bind(this)

			}); 
     
        
    },

    //
    //  getPageSize()
    //
    getPageSize: function() {
	        
	     var xScroll, yScroll;
		
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
		
		var windowWidth, windowHeight;
		
		if (self.innerHeight) {	// all except Explorer
			if(document.documentElement.clientWidth){
				windowWidth = document.documentElement.clientWidth; 
			} else {
				windowWidth = self.innerWidth;
			}
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}	
		
		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else { 
			pageHeight = yScroll;
		}
	
		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){	
			pageWidth = xScroll;		
		} else {
			pageWidth = windowWidth;
		}

		return [pageWidth,pageHeight];
	}
}
var mylightvid = '2';
function loadvideo () {
	mylightvid=  new Lightvideo();
}


if(window.addEventListener){
	window.addEventListener('load', loadvideo, false);
} else {
	window.attachEvent('onload', loadvideo);	
}
		

