// flag global
$(function() {
	if ($.LiVE.youtubePlayerFuncs) return;
	$.LiVE.isYouTubeAPILoaded = false;
	$.LiVE.isVimeoAPILoaded = false;
	$.LiVE.youtubePlayerFuncs = [];
	$.LiVE.vimeoPlayerFuncs = [];
});

function loadYouTubeAPI() {
	/*
	!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=$.LiVE.util.getEmbedProtocol()+"//www.youtube.com/player_api";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","ytapi");
	*/
	!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=$.LiVE.util.getEmbedProtocol()+"//www.youtube.com/iframe_api";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","ytapi");
}

$.fn.movieDEFAULT = function(initW,initH) {
	// 連携キット、local時はexit
	if ($.LiVE.bdkit && location.protocol=="file:") return;
	
	//editモードだったら画像を代替表示する
	if ($.LiVE.mode.edit.activate) {
		var movie = $.LiVE.Elements.PANELS.movie;
			movieFrameWra = movie.find('div.box').find('div.block').find('div.board').find('div.wrapper'),
			movieFrame = movieFrameWra.find('div.tile');

		movie.each( function() {
			var	id = $(this).attr("id"),
				posterImg = $.LiVE.panel[id].data.poster.use;
			if ( posterImg ) {
				return;
			} else {
				movieFrame.hide();
				movieFrameWra.append('<img src="core/tile/movie/common/editmode.jpg" alt="※ブラウザでプレビューすると正しく表示されます。" width="100%" height="100%">');
			}
		});
		
	}
	
	this.each(function() {
		var $this = $(this),
			$board = $this.find(".board"),
			$wrapper = $this.find(".wrapper"),
			id = $this.find(".board").attr("id").match(/id[0-9]+/),
			data = $.LiVE.panel[id].data;
		
		if (!data.url) return;	//url無しは処理終了
		
		var videoid = $.LiVE.util.getVideoId(data.url);
		
		var container = "player" + id,
			w = initW || data.width || 480,
			h = initH || data.height || 270,
			interval = 5000;
		
		// mobile：
		if ($.LiVE.mobile.check) {
			var winW = $(window).width();
			if (w > winW) {
				var ratio = winW / w;
				w = winW;
				h = h * ratio;
			}
		}
		
		$wrapper.css({ width: w, height: h });
		
		if (data.poster.use && (!$.LiVE.mobile.check || ($.LiVE.mobile.check && $.LiVE.mobile.type == "ipad"))) {
		
			//ポスターセット
			var _top = $this.find(".board").offset().top - $this.offset().top,
				_current = 0,
				$poster = $("<div/>").addClass("posterlayer").css({
					width: w,
					height: h
				}),
				loop = {
					timer: "",
					interval: interval,
					speed: "slow",
					move: function() {
						var _img = $poster.find("img[data-current='"+_current+"']");
						_img.animate({
							opacity:0
						},{
							duration: this.speed,
							complete: function() {
								_img.remove();
								var _newimg = $("<img/>").attr({
										src: data.poster.images[_current],
										width: w
									}).css({
										height: 'auto'
									}).attr("data-current", _current);
								_newimg.prependTo($poster);
								_current = _current+1 == data.poster.images.length ? 0 : _current+1;
							}
						});
					},
					set: function() {
						return this.timer = setInterval(function() {
							loop.move();
						},this.interval);
					}
				};
			
			for (var i=data.poster.images.length-1; i>-1; i--) {
				var _img = $("<img/>").attr({
						src: data.poster.images[i],
						width: w
					}).css({
						height: 'auto'
					}).attr("data-current", i);
				_img.appendTo($poster);
			}
			$poster.appendTo($wrapper);
			
			if (data.poster.images.length>1) loop.set();
			
			function trigger(evnt) {
				if ($.LiVE.mode.edit.activate == false) {
					//BGM,se 強制オフ
					if ($.LiVE.panelsound.useSound) {
						$.LiVE.panelsound.mute(true);
						// TODO: widget feedback
					}
					
					// その場で表示
					if (data.play == "0") {
						$poster.remove();
						$play.remove();
						
						if (data.url.match(/youtu/)) {
							playYouTube(container, videoid, w, h, true, data.loop);
						} else if (data.url.match(/vimeo/)) {
							playVimeo(container, videoid, w, h, true, data.loop);
						}
						
					// 拡大表示
					} else {
						$.LiVE.popupMovie.play(data.url, false);
						
					}
				}
			}
			
			//プレイボタン
			var $play = $("<div/>").addClass("play").appendTo($wrapper);
			$play.css({ left: w/2 - $play.width()/2, top: h/2 - $play.height()/2 });
			
			//クリック再生セット
			$poster.bind("click",trigger);
			$play.bind("click",trigger);
			
			
		} else {
			
			// ポスターを使用しない埋め込み
			if (data.url.match(/youtu/)) {
				playYouTube(container, videoid, w, h, data.autoplay, data.loop);
			} else if (data.url.match(/vimeo/)) {
				playVimeo(container, videoid, w, h, data.autoplay, data.loop);
			}
		}
	});
	
	function playYouTube(container, videoid, width, height, auto, loop) {
		var func = function() {
			var player = new YT.Player(container, {
				width: width,
				height: height,
				videoId: videoid,
				playerVars: { 'autoplay' : ((auto) ? 1:0)},
				events: {
					'onStateChange': function(e) {
						if (e.data == YT.PlayerState.PLAYING) {
							$.LiVE.panelsound.mute(true);
						}
						
						if (e.data == YT.PlayerState.ENDED || e.data == YT.PlayerState.PAUSED) {
							$.LiVE.panelsound.mute(false);
						}
					}
				}
			});
		};
		if ($.LiVE.isYouTubeAPILoaded) {
			func();
		} else {
			$.LiVE.youtubePlayerFuncs.push(func);
			loadYouTubeAPI();
		}
	}
	
	function playVimeo(container, videoid, width, height, auto, loop) {
		if (navigator.userAgent.indexOf('MSIE 10') > -1) {
			$.lazyLoad('core/common/js/plugin/swfobject/swfobject.js')
				.done(function(scr, status) {
					$('<div id="' + container + '"/>').appendTo(container);
					
					var params = { allowScriptAccess: "always" };
					var atts = { id: "popupPlayer" };
					swfobject.embedSWF("http://vimeo.com/moogaloop.swf?clip_id=" + videoid + 
										"&server=vimeo.com&autoplay=" + ((auto) ? "1":"0") + "&loop=" + ((loop) ? "1":"0"),
										container, width, height, "9", null, null, params, atts);
				});
		} else {
			var player = document.createElement("iframe"),
				appnd = document.getElementById(container);
			player.setAttribute("src", "http://player.vimeo.com/video/" + videoid + "?autoplay=" + ((auto) ? "1":"0") + "&loop=" + ((loop) ? "1":"0"));
			player.setAttribute("id", container);
			player.setAttribute("width", width);
			player.setAttribute("height", height);
			player.setAttribute("frameborder", 0);
			appnd.appendChild(player);
			
			$(appnd).attr("id","");	//avoid ID conflict (containerID and iframeID)
		}
	}
};


/**
 * ポップアップ再生
 */
$(function(){
	$.LiVE.popupMovie = {
		play: function(url, duration) {
			function finish() {
				var player = document.getElementById("popupPlayer");
				if (player) player.parentNode.removeChild(player);
				
				base.animate({
					opacity: 0
				},{
					duration: "slow",
					complete: function() {
						base.remove();
						delete base;
					}
				});
				if (location.search.match(/mode=presentation/)) {
					$.LiVE.mode.presentation.activate == true;
					$.LiVE.mode.presentation.main();
				}
				if (typeof(soundManager) == 'undefined') {
					return;
				} else {
					$.LiVE.panelsound.mute(false);
				}
			}
			
			var videoid = $.LiVE.util.getVideoId(url),
				w = 1920,
				h = 1080,
				$win = $(window),
				minW = $win.width() - 80,
				minH = $.LiVE.winHeight() - 20;
			
			if (w > minW) {
				var ratio = minW / w;
				w = minW;
				h = h * ratio;
			}
			
			if (h > minH) {
				var ratio = minH / h;
				h = minH;
				w = w * ratio;
			}
			
			var base = $("<div/>").css({
					position: "fixed",
					left: 0,
					top: 0,
					width: "100%",
					height: "100%",
					background: "url(core/tile/movie/common/bg.png)",
					zIndex:999,
					cursor: "pointer"
				}).appendTo("body").bind("click", finish);
			
			var container = $("<div/>").attr({
					id: "LiVE-popupMovie"
				}).css({
					position: "relative",
					overflow: "hidden",
					margin: "0 auto",
					width: w,
					height: h,
					display: "block",
					backgroundColor: "#333",
					marginTop: $.LiVE.winHeight()/2 - h/2
				}).appendTo(base);
			
			var loop = {
					timer: "",
					set: function() {
						this.timer = setTimeout(function() {
							finish();
						}, duration * 1000);
					}
				};
			
			// for callback
			$.data(container[0], "args", {
				videoid: videoid,
				loop: loop,
				finish: finish,
				duration: duration,
				width: w,
				height: h
			});
			
			/********
			youtube iframe api
			//@youtube player api
			********/
			if (url.match(/youtube/)) {
				// ie8
				if ($.LiVE.browser.name=="ie8") {	//ie8
					$.lazyLoad('core/common/js/plugin/swfobject/swfobject.js')
						.done(function(scr, status) {
							$('<div id="ytplayer"/>').appendTo(container);
							
							var params = { allowScriptAccess: "always" };
							var atts = { id: "popupPlayer" };
							swfobject.embedSWF("http://www.youtube.com/v/" + videoid + 
												"?version=3&enablejsapi=1&playerapiid=player1&autoplay=1",
												"ytplayer", w, h, "9", null, null, params, atts);
						});
				} else {
					var func = function() {
						var isFirst = true;
						var player = new YT.Player("LiVE-popupMovie", {
							width: w,
							height: h,
							videoId: videoid,
							playerVars: { 'autoplay' : 1, 'controls': 0 },
							events: {
								'onStateChange': function(e) {
									if (e.data == YT.PlayerState.PLAYING) {
										$.LiVE.panelsound.mute(true);
										if (isFirst) {
											if (duration) loop.set();
											isFirst = false;
										}
									}
									
									if (e.data == YT.PlayerState.ENDED || e.data == YT.PlayerState.PAUSED) {
										$.LiVE.panelsound.mute(false);
										finish();
									}
								}
							}
						});
					};
					if ($.LiVE.isYouTubeAPILoaded) {
						func();
					} else {
						$.LiVE.youtubePlayerFuncs.push(func);
						loadYouTubeAPI();
					}
					
				}
			}
			
			/********
			vimeo initialize
			@froogaloop
			********/
			else if (url.match(/vimeo/)) {
				if (navigator.userAgent.indexOf('MSIE 10') > -1) {
					$.lazyLoad('core/common/js/plugin/swfobject/swfobject.js')
						.done(function(scr, status) {
							$('<div id="live_vimeo"/>').appendTo(container);
							
							var params = { allowScriptAccess: "always" };
							var atts = { id: "popupPlayer" };
							swfobject.embedSWF("http://vimeo.com/moogaloop.swf?clip_id=" + videoid + 
												"&server=vimeo.com&autoplay=1",
												"live_vimeo", w, h, "9", null, null, params, atts);
							});
				} else {
					var player = document.createElement("iframe"),
						player_id = "live_vimeo",
						appnd = document.getElementById("LiVE-popupMovie");
					
					player.setAttribute("id", player_id);
					player.setAttribute("width", w);
					player.setAttribute("height", h);
					player.setAttribute("frameborder", 0);
					player.setAttribute("style", "position:absolute");
					player.setAttribute("src", $.LiVE.util.getEmbedProtocol() + "//player.vimeo.com/video/" + videoid + "?api=1&player_id=" + player_id + "&autoplay=1");
					//player.setAttribute("src", $.LiVE.util.getEmbedProtocol() + "//player.vimeo.com/video/" + videoid + "?api=1&player_id=" + player_id + "");
					appnd.appendChild(player);
					
					if (typeof($f) == 'undefined') {
						$.lazyLoad($.LiVE.util.getEmbedProtocol()+"//a.vimeocdn.com/js/froogaloop2.min.js")
							.done(function(){
								
								$f(player).addEvent('ready', function(pid){
									// play !
									if (duration) {
										if (location.protocol != 'file:') {
											$f(player).addEvent('play', function(){
												loop.set();
											});
										} else {
											loop.set();
										}
									}
									$f(pid).addEvent('finish', function(playerId){
										finish();
									});
									
									//$f(pid).api('play');
								});
								$.data($("#LiVE-popupMovie")[0], "player", player);
								$.LiVE.panelsound.mute(true);
							})
							.fail(function(){
								// 失敗時
							});
					}
				}
			}
		}
	};
});

// YouTube callback.
function onYouTubeIframeAPIReady() {
	$.LiVE.isYouTubeAPILoaded = true;
	var len = $.LiVE.youtubePlayerFuncs.length;
	for (var i=0; i<len; i++) {
		$.LiVE.youtubePlayerFuncs[i]();
	}
}

// YouTube Callback (IE8)
function onYouTubePlayerReady(playerId) {
	var ytplayer = document.getElementById("popupPlayer");
	ytplayer.addEventListener("onStateChange", "onYouTubeStateChange");
	ytpopup_1st = true;
}

var ytpopup_1st = false;
function onYouTubeStateChange(newState) {
	var param = $.data($("#LiVE-popupMovie")[0], "args");
	if (newState == 1) {
		$.LiVE.panelsound.mute(true);
		if (ytpopup_1st) {
			ytpopup_1st = false;
			param.loop.set();
		}
	} else if (newState == 0 || newState == 2) {
		$.LiVE.panelsound.mute(false);
		param.finish();
	}
}