/*
(c) 2011 Naphthalene Co.,Ltd.
tvdog
http://naph.jp

以下のライブラリに依存
jquery-1.4.4.min.js
*/


/*------------------------------------------------------------------------------*/
//googlemapオブジェクト
thai.addBlocks += 1;
thai.youtube = function() {
	var flflag = false;
	var ME = {
		players : null,
		init : function() {
			setTimeout(function(){
				if (!$('.youtube').get(0)) {
					thai.masonry();//--------------------------------------- end
					return;
				}
				
				if (swfobject.hasFlashPlayerVersion("8")) flflag = true;
				ME.players = {};
				$('.youtube').each(function(i){
					var u = $(this).find('a').attr('href');
					var s = u.split('=');
					s = s[1];
					var name = 'yt' + i;
					if (flflag) {
						ME.players[name] = new Youtube(this, s, name);
					} else {
						var h = '<iframe width="300" height="255" src="http://www.youtube.com/embed/'+
							s+'" frameborder="0" allowfullscreen></iframe>';
						$(this).empty().append(h);
						thai.masonry();//--------------------------------------- end
					}
				});
			},1);
		}
		
	};
	
	/*------------------------------------------------------------------------------*/
	//Youtube
	var Youtube = function(obj, id, name) {
		this.init(obj, id, name);
	};
	Youtube.prototype = {
		ytplayer : null,
		obj      : null,
		name     : "",
		id       : "",
		init : function(obj, id, name) {
			this.id = id;
			this.obj = obj;
			this.name = name;
			
			var me = this;
			var youtubeAPI = 'http://gdata.youtube.com/feeds/api/videos?v=2&alt=jsonc';
			var query = id;
			if (query.charAt(0) == '-') query = query.substr(1);
			
			$.get(youtubeAPI,{'q':query},function(response){
				var size = "";
				if (response.data.items) size = response.data.items[0].aspectRatio;
				var ratio = 3/4;
				if(size == "widescreen") ratio = 9/16;
				var w = 300;
				var h = Math.round(w*ratio);
				
				var div = $('<div>',{id:name});
				$(obj).empty().append(div);
				
				var btplay = $('<div>',{className:'yt_play'}).click(me.playVideo);
				$(obj).append(btplay);
				
				var btpause = $('<div>',{className:'yt_pause'}).click(me.pauseVideo);
				$(obj).append(btpause);
				
				var btreplay = $('<div>',{className:'yt_replay'}).click(me.replayVideo);
				$(obj).append(btreplay);
				
				var prog = $('<div>',{className:'yt_prog'}).click(me.seekTo);
				$(obj).append(prog);
				
				var prog_bar = $('<div>',{className:'yt_bar'});
				$(prog).append(prog_bar);
				
				$(obj).css({height:h+"px"});
				
				swfobject.embedSWF(
					"http://www.youtube.com/apiplayer?enablejsapi=1&version=3&playerapiid="+name,
					name,
					w,
					h,
					"8",
					null,
					null,
					{allowScriptAccess:"always",wmode:"transparent"},
					{id:name+"_p"}
				);
				
				thai.masonry();//--------------------------------------- end
				
			},'jsonp');
		},
		
		ready : function() {
			this.ytplayer = $(this.obj).find("object").get(0);
			this.ytplayer.addEventListener("onStateChange", "thai.youtube.players."+this.name+".onPlayerStateChange");
			this.ytplayer.addEventListener("onError", "thai.youtube.players."+this.name+".onPlayerError");
			this.ytplayer.cueVideoById(this.id);
		},
		
		playVideo : function() {
			var v = $(this).parent().find("object").get(0);
			var p =  $(this).parent().find(".yt_prog");
			var b =  $(this).parent().find(".yt_bar");
			var pus =  $(this).parent().find(".yt_pause");
			v.playVideo();
			$(this).parent().removeClass().addClass("youtube play");
			
			var id = setInterval(function(){
				var cur = v.getCurrentTime();
				if (cur < 0) return;
				var sta = v.getPlayerState();
				var w = Math.floor((cur/v.getDuration())*p.width()) - 3;
				b.width(w);
				if (sta != 1) clearInterval(id);
				if (sta == 0) {
					v.stopVideo();
				} else if (sta == -1) {
					pus.click();
				}
			}, 500);
		},
		
		pauseVideo : function() {
			var v = $(this).parent().find("object").get(0);
			v.pauseVideo();
			$(this).parent().removeClass().addClass("youtube pause");
			clearInterval(this.loop);
		},
		
		replayVideo : function() {
			var v = $(this).parent().find("object").get(0);
			v.seekTo(0);
			v.playVideo();
			$(this).parent().find(".yt_bar").width(0);
		},
		
		seekTo : function(e) {
			var v = $(this).parent().find("object").get(0);
			var p =  $(this).parent().find(".yt_prog");
			var b =  $(this).parent().find(".yt_bar");
			var ratio = (e.pageX - p.offset().left)/p.outerWidth();
			var w = Math.floor(ratio*p.width()) - 3;
			b.width(w);
			v.seekTo(Math.round(v.getDuration()*ratio), true);
		},
		
		onPlayerStateChange : function(newState) {
			if (newState == 3) {
				$("#"+this.name+"_p").parent().find(".yt_play").click();
			} else if (newState == 0) {
				$("#"+this.name+"_p").parent().removeClass().addClass("youtube replay");
			}
		},
		
		onPlayerError : function(errorCode) {
			//console.log(errorCode);
		}
	};
	
	return ME;
}();

function onYouTubePlayerReady(playerId) {
	thai.youtube.players[playerId].ready();
}


$(document).ready(thai.youtube.init);
