/*--------------------------------------------------
Y O U T U B E  P L A Y E R
http://extranet.websolute.it/jfe/
http://www.websolute.it
--------------------------------------------------*/


	/* PROTOTYPE */
	
	String.prototype.contains = function ($s,$case) {
		if ($case) {
			return (this.indexOf($s)!=-1);
		} else {
			return (this.toLowerCase().indexOf($s.toLowerCase())!=-1);
		}
	}

	/* SETTINGS */
	
	var ytkCustom 				= null;
	var ytkDebug 				= false;
	var ytkGlobal 				= this;
	var ytkUa 					= navigator.userAgent;
	var ytkFlagIOS 				= (ytkUa.contains("iPad") || ytkUa.contains("iPhone"));
	var ytkFlagSafariOnWindows 	= (ytkUa.contains("Safari") && ytkUa.contains("Win") && !ytkUa.contains("Chrome"));
	var ytkFps			 		= 20;
	var ytkFriction		 		= .25;
	var ytkVideoAutoPlay		= false;
	
	var ytkBaloonStartX 		= 93;
	var ytkTimelineDiffWidth 	= 91;
	var ytkMiddleDiffWidth 		= 111;
	var ytkTrackDiffWidth 		= 211;
	
	/* UTILS */
	
	function trace() {
		if (ytkDebug) {
			var i = 0;
			var t = arguments.length;
			var str = "";
			while (i < t) {
				str += arguments[i].toString() + " ";
				i++;
			}
			alert (str);
		}
	}
	
	function numToTen ($num) {
		if ($num < 10) {
			return '0' + $num;
		} else {
			return $num;
		}
	}
	function secToTime ($secs) {
		var secs = $secs % 60;
		var mins = ($secs-secs) / 60;
		return numToTen(Math.floor(mins)) + ':' + numToTen(Math.floor(secs));
	}
	
	/* SETUP EVENTS on YouTube Player Ready */
	
	function onYouTubePlayerReady($pid) {
		ytkGlobal['on'+$pid+'StateChange'] = function($state) {
			// trace ('on'+$pid+'StateChange to ' +  $state);
			switch ($state) {
				case -1:
					// unstarted
					onPause ($pid);
				break;
				case 0:
					// ended
					onPause ($pid);
				break;			   
				case 1:
					// playing
					onPlay ($pid);
				break;				
				case 2:
					// paused
					onPause ($pid);
				break;				
				case 3:
					// buffering
					onPlay ($pid);
				break;				
				case 5:
					// video cued
				break;
			}
		}
		// trace("onYouTubePlayerReady: " + $pid);
		var yt = $('#'+$pid);
		
		yt.parent().hover(
			function(){
				if ($(this).find('.bigplay').size() == 0) {
					$(this).find('.controls').fadeIn ();
				}
			}, 
			function () {
				$(this).find('.controls').fadeOut ();
			}
		);
		var track = yt.next('.controls').find('.track');
		track.hover(
			function(){
				$(this).mousemove(function($e){
					var p = ($e.pageX-$(this).offset().left) / $(this).width ();
					p = Math.max ( 0 , Math.min ( 1, p ) );
					$(this).data('dx',p);
				});				
			}, 
			function () {
				$(this).unbind('mousemove');
				$(this).data('dx',null);
			}
		);
		// trace (yt.offset().left + ", " + yt.offset().top + ", " + yt.height());
		var progress = track.find('.progress');
		track.click(function($e) {
			if (yt_obj) {
				var p = ($e.pageX-$(this).offset().left) / $(this).width();
				p = Math.max ( 0, Math.min ( 1 , p ) );
				yt_obj.seekTo(p * yt_obj.getDuration());
			}
		});	
		var baloon = yt.next('.controls').find('.baloon');
		var bx = parseInt ( ytkBaloonStartX - baloon.width() / 2 + 1);
		// var by = parseInt ( yt.parent().offset().top + yt.height() - 32 - baloon.height () );
		// trace (baloon.text() + ", " + bx + ", " + by);
		baloon.css ({'left': bx+'px'});
		baloon.text(secToTime(0));
		
		var audio_off = yt.next('.controls').find('.audio_off');
		var audio_on = yt.next('.controls').find('.audio_on');
		var aover = function(){
			$(this).mousemove(function($e){
				var p = ($e.pageX-$(this).offset().left) / audio_off.width ();
				p = Math.max ( 0 , Math.min ( 1, p ) );
				audio_off.data('dx',p);
			});				
		}
		var aout = function () {
			$(this).unbind('mousemove');
			$(this).data('dx',null);
		}
		var aclick = function ($e) {
			if (yt_obj) {
				var p = ($e.pageX-$(this).offset().left) / audio_off.width();
				p = Math.max ( 0, Math.min ( 1 , p ) );
				yt_obj.setVolume(p * 100);
			}
		}
		audio_off.hover( aover, aout );
		audio_on.hover( aover, aout );
		audio_off.click( aclick );	
		audio_on.click( aclick );	
		
		var quality = yt.next('.controls').find('.quality');
		quality.hover( 	function(){
							var qu = $(this).data('quality');
							if (qu == 'hd') {
							    $(this).addClass("qualityOff").removeClass("qualityOn");								
								// high
							} else {
							    $(this).addClass("qualityOn").removeClass("qualityOff");                                
								// low
							}
						}, 
						function () {
							var qu = $(this).data('quality');
							if (qu == 'hd') {
							    $(this).addClass("qualityOn").removeClass("qualityOff");								
								// high
							} else {
							    $(this).addClass("qualityOff").removeClass("qualityOn");										
								// low
							}		
						} );
						
		quality.click( 	function ($e) {
							if (yt_obj) {
								var qu = $(this).data('quality');
								if (qu == 'hd') {
									$(this).data('quality','low');
									yt_obj.setPlaybackQuality('small');
									// low
								} else {
									$(this).data('quality','hd');
									yt_obj.setPlaybackQuality('hd720');
									// high
								}								
							}
						} );	
		
		var fullscreen = yt.next('.controls').find('.fullscreen');
		fullscreen.hover( 	function(){
							var size = $(this).data('fullscreen');
							if (size == 'fullscreen') {
							    $(this).addClass("fullscreenOff").removeClass("fullscreenOn");		
								// high
							} else {
							    $(this).addClass("fullscreenOn").removeClass("fullscreenOff");	
								// low
							}
						}, 
						function () {
							var size = $(this).data('fullscreen');
							if (size == 'fullscreen') {
							    $(this).addClass("fullscreenOn").removeClass("fullscreenOff");			
							} else {
							    $(this).addClass("fullscreenOff").removeClass("fullscreenOn");	
							}		
						} );
						
		fullscreen.click( 	function ($e) {
							if (yt_obj) {
								var size = $(this).data('fullscreen');
								if (size == 'fullscreen') {
									$(this).data('fullscreen','normal');
									// go normal!
									var player = yt.parent();
									var ox = player.data('ox');
									var oy = player.data('oy');
									var ow = player.data('ow');
									var oh = player.data('oh');
									player.css({'position':'relative', 'z-index':'1', 'top':ox+'px','left':oy+'px','width':ow+'px','height':oh+'px'});
									
									player.find('.timeline').css({'width':(ow-ytkTimelineDiffWidth)+'px'});
									player.find('.middle').css({'width':(ow-ytkMiddleDiffWidth)+'px'});
									player.find('.track').css({'width':(ow-ytkTrackDiffWidth)+'px'});									
									
								} else {
									$(this).data('fullscreen','fullscreen');
									// go fullscreen!
									var player = yt.parent();
									player.data('ox',parseInt(player.css('left')));
									player.data('oy',parseInt(player.css('top')));
									player.data('ow',player.width());
									player.data('oh',player.height());
									player.css({'position':'absolute', 'z-index':'9999', 'top':'0px','left':'0px','width':'100%','height':'100%'});
																		
									var nw = player.width();
									
									player.find('.timeline').css({'width':(nw-ytkTimelineDiffWidth)+'px'});
									player.find('.middle').css({'width':(nw-ytkMiddleDiffWidth)+'px'});
									player.find('.track').css({'width':(nw-ytkTrackDiffWidth)+'px'});									
									
								}								
							}
						} );	
		
		var yt_obj = yt[0];
		if (yt_obj) {
			yt_obj.addEventListener('onStateChange','on'+$pid+'StateChange');
			// alert("loadVideoById " + $pid);
			if (ytkVideoAutoPlay) {
				yt_obj.loadVideoById($pid, 0, 'small');
			} else {
				yt_obj.cueVideoById($pid, 0, 'small');
			}
			audio_on.width ( parseInt ( audio_off.width() / 100 * yt_obj.getVolume () ) + 'px' ); 
			yt.parent().find('.bigplay').click(function() {
				Play($pid);
			});			
		}
	}
	
	/* PLAYER FUNCTIONS */
	
	function onPlay($pid) {
		// trace ('onPlay ' + $pid);
		var yt = $('#'+$pid);
		var yt_obj = yt[0];
		if (yt_obj) {
			var track = yt.next('.controls').find('.track');
			// trace (yt.offset().left + ", " + yt.offset().top + ", " + yt.height());
			var progress = track.find('.progress');
			var baloon = yt.next('.controls').find('.baloon');
			var bigplay = yt.parent().find('.bigplay').remove();
			var audio_off = yt.next('.controls').find('.audio_off');
			var audio_on = yt.next('.controls').find('.audio_on');
			var yti = yt.data('yti') || setInterval (function(){
				// trace('track dx ' + track.data('dx') );
				try {
					var dx = track.data('dx');
					var currentTime = yt_obj.getCurrentTime();
					if (dx) {
						currentTime = yt_obj.getDuration() * dx;
					}
					var ct = track.data('ct') || 0;
					ct += (currentTime-ct) * ytkFriction;
					track.data('ct', ct);
					progress.width ( track.width() / yt_obj.getDuration() * ct );
					var bx = parseInt ( ytkBaloonStartX + progress.width() - baloon.width() / 2 + 1);
					// var by = parseInt ( yt.parent().offset().top + yt.height() - 32 - baloon.height () );
					// trace (baloon.text() + ", " + bx + ", " + by);
					baloon.css ({'left': bx+'px'});
					baloon.text(secToTime(currentTime));
					var vx = audio_off.data('dx');
					var currentVol = yt_obj.getVolume();
					if (vx) {
						currentVol = 100 * vx;
					}
					var cv = track.data('cv') || 0;
					cv += (currentVol-cv) * ytkFriction;
					track.data('cv', cv);
					audio_on.width ( parseInt ( audio_off.width() / 100 * cv ) + 'px' ); 
					
				} catch ($e) {
					// alert ($e);
				}
			}, 1000/ytkFps);
			yt.data('yti',yti);
			yt.next('.controls').find('.play a .img').addClass("playOn").removeClass("playOff");
		}
	}
	
	function onPause($pid) {
		// trace ('onPause ' + $pid);
		var yt = $('#'+$pid);
		var yt_obj = yt[0];
		if (yt_obj) {
			var yti = yt.data('yti');
			yti ? clearInterval (yti) : null;
			yt.data('yti',null);
			yt.next('.controls').find('.play a .img').addClass("playOff").removeClass("playOn");	
		}
	}
	
	function Play($pid) {
		var yt = $('#'+$pid);
		var yt_obj = yt[0];
		if (yt_obj) {
			yt_obj.playVideo();
			yt.next('.controls').find('.play a .img').addClass("playOn").removeClass("playOff");
			var bigplay = yt.parent().find('.bigplay').remove();			
		}
	}
	
	function Pause($pid) {
		var yt = $('#'+$pid);
		var yt_obj = yt[0];
		if (yt_obj) {
			yt_obj.pauseVideo();
			yt.next('.controls').find('.play a .img').addClass("playOff").removeClass("playOn");
		}
	}
	
	function Swap($pid,$nid) {
		if (ytkFlagIOS || ytkFlagSafariOnWindows) {
			var yt = $('#'+$pid);
			// alert('size ' + yt.size());
			var pw = yt.width();
			var ph = yt.height();
			var source = 	'<iframe width="' + pw + '" height="' + ph + '" src="http://www.youtube.com/embed/' + $nid + '" frameborder="0" allowfullscreen></iframe>';
			// $(this).attr('id',null);
			yt.html(source);
		} else {
			var yt = $('#'+$pid);
			// alert("killing " + yt.html());
			var yt_obj = yt[0];
			if (yt_obj) {
				var yti = yt.data('yti');
				yti ? clearInterval (yti) : null;
				yt.data('yti',null);
				try {
					yt_obj.loadVideoById($nid, 0, 'small');
				} catch ($e) {
					// alert($e);
				}
				yt.next('.controls').find('.play a .img').addClass("playOff").removeClass("playOn");
			}
		}
	}
	
	function Kill($pid) {
		if (ytkFlagIOS || ytkFlagSafariOnWindows) {
			var yt = $('#'+$pid);
			// alert('size ' + yt.size());
			yt.html('');
		} else {
			var yt = $('#'+$pid);
			// alert("killing " + yt.html());
			var yt_obj = yt[0];
			if (yt_obj) {
				// yt_obj.removeEventListener('onStateChange','on'+$pid+'StateChange');
				var yti = yt.data('yti');
				yti ? clearInterval (yti) : null;
				yt.data('yti',null);
				try {
					yt_obj.stopVideo();
					yt_obj.clearVideo();
				} catch ($e) {
					// alert($e);
				}
				yt.next('.controls').find('.play a .img').addClass("playOff").removeClass("playOn");
			}
		}
	}
	
	function PlayPause($pid) {
	  var yt = $('#'+$pid);
	  var yt_obj = yt[0];
	  if (yt_obj) {
		// trace (yt_obj.getPlayerState());
		switch (yt_obj.getPlayerState()) {
			case -1:
				// unstarted
				Play ($pid);
			break;
			case 0:
				// ended

				Play ($pid);
			break;			   
			case 1:
				// playing
				Pause ($pid);
			break;				
			case 2:
				// paused
				Play ($pid);
			break;				
			case 3:
				// buffering
			break;				
			case 5:
				// video cued
			break;
		}
	  }
	}
	
	function ytPlayerInitializer () {
		
		var pid = $(this).attr('id');
		var pw = $(this).width();
		var ph = $(this).height();
		
		if (ytkFlagIOS || ytkFlagSafariOnWindows) {
			var source = 	'<iframe width="' + pw + '" height="' + ph + '" src="http://www.youtube.com/embed/' + pid + '" frameborder="0" allowfullscreen></iframe>';
			// $(this).attr('id',null);
			$(this).html(source);
		} else {
			var source = 	'<div class="youtube">You need Flash player 8+ and JavaScript enabled to view this video.</div>';
			source += 		'<div class="controls">';
			source += 		'	<div class="play"><a href="javascript:void(0);" onclick="PlayPause(\''+pid+'\');"><div class="img"/></a></div>';
			source += 		'	<div class="timeline" style="width:'+(pw-ytkTimelineDiffWidth)+'px;">';
			source += 		'		<div class="left_cap"></div>';
			source += 		'		<div class="middle" style="width:'+(pw-ytkMiddleDiffWidth)+'px;">';
			source += 		'			<div class="track" style="width:'+(pw-ytkTrackDiffWidth)+'px;">';
			source += 		'				<div class="progress"></div>';
			source += 		'			</div>';
			source += 		'			<div class="audio_off"></div>';
			source += 		'			<div class="audio_on"></div>';
			source += 		'			<div class="quality"></div>';
			source += 		'			<div class="fullscreen"></div>';
			source += 		'		</div>';
			source += 		'		<div class="right_cap"></div>';
			source += 		'	</div>';
			source += 		'	<div class="baloon">00:00</div>';
			source += 		'</div>';
			source += 		'<div class="bigplay"><div class="smallplay"></div></div>';
			
			$(this).attr('id',null);
			$(this).html(source);
			$(this).find('.youtube').attr('id',pid);
			
			$(this).find('*').each(function() { 
				this.onselectstart = function() { return false; };
			});
	
			var pars = { allowScriptAccess: "always", wmode: "opaque", background: "#fff" };
			var attr = { id: pid };
			
			swfobject.embedSWF ("http://www.youtube.com/apiplayer?wmode=opaque&enablejsapi=1&version=3&controls=0&enablejsapi=1&fs=1&showinfo=0&feature=player_embedded&playerapiid=" + pid, pid, pw, ph, "8", null, null, pars, attr);
			// swfobject.embedSWF ("http://www.youtube.com/e/" + pid + "?version=3&controls=0&enablejsapi=1&fs=1&showinfo=0&feature=player_embedded&playerapiid=" + pid, pid, pw, ph, "8", null, null, pars, attr);
			// swfobject.embedSWF ("http://www.youtube.com/e/" + pid + "?version=3&controls=0&enablejsapi=1&fs=1&feature=player_embedded&playerapiid=" + pid, pid, pw, ph, "8", null, null, pars, attr);
			
		}
		
	}	
	
	function ytStopAllPlay () {
		$('.ytPlayer').each(function() {
			if (ytkFlagIOS || ytkFlagSafariOnWindows) {
				// alert ('iOs ytStopAllPlay');	
				Kill ($(this).attr('id'));	
			} else {
				if ($(this).attr('id') != null) {
					// alert ('not initialized ' + $(this).attr('id'));				
				} else {
					// alert ('initialized ' + $(this).children().eq(0).attr('id'));
					Kill ($(this).children().eq(0).attr('id'));			
				}
			}
		});		
	}

	
	function ytActivateByYTId ($ytId) {
		$('#' + $ytId).each(function() {
			ytPlayerInitializer.call(this);
		});
	}


	function ytReadyInit() {

	    $('.ytPlayer').each(function () {
	        ytPlayerInitializer.call(this);
	    });

	    /* WIN RESIZE */

	    $(window).resize(function () {
	        $('.ytPlayer').each(function () {
	            var nw = $(this).width();
	            $(this).find('.timeline').css({ 'width': (nw - ytkTimelineDiffWidth) + 'px' });
	            $(this).find('.middle').css({ 'width': (nw - ytkMiddleDiffWidth) + 'px' });
	            $(this).find('.track').css({ 'width': (nw - ytkTrackDiffWidth) + 'px' });
	        });
	    });

	    $('#ytButtonKill').click(function () {
	        // ytStopAllPlay ();
	        Swap('PwYoJ211mOY', 'GHpaxgpfpPY');
	    });
    }
    /* DOC READY */

    //$('body').ready(function () {
    //ytReadyInit();
    //});
	
