// fujiplayer.js

function fp_getcookie(key) { 
	var strCookie = document.cookie;
	var arrData = strCookie.split(";");
	var objExp = new RegExp(" ", "g");
	key = key.replace(objExp, "");
	var i = 0;
	while ( arrData[i] ) {
		var arrWord = arrData[i].split("=");
		arrWord[0] = arrWord[0].replace(objExp, "");
		if ( key == arrWord[0] ) return unescape(arrWord[1]);
		if ( ++i >= arrData.length ) break;
	}
	return "";
}


// ***********************************
// constant
// ***********************************
var fp_loading = "/timetable/img/loadingAnimation.gif"; // image of loading.

var fp_infourl; // oainfo base url.
var fp_xmldir = "/bangumi/movie/"; // oainfo base directry.
var fp_mailform = "https://wwws.fujitv.co.jp/safe/mail/index.html"; // mailform url.
var fp_closebutton = "/images/player/close.png";

var isIE  = ( navigator.appVersion.indexOf("MSIE") != -1 ) ? true: false;
var isWin = ( navigator.appVersion.toLowerCase().indexOf("win") != -1 ) ? true: false;
var isOpera = ( navigator.userAgent.indexOf("Opera") != -1 ) ? true: false;

var boolAndroid = ( navigator.userAgent.match(/Android/i) ) ? true: false;
var booliOS = ( navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/iPad/i) ) ? true: false;

var isPC = ( fp_getcookie("CX_SMARTPHONE_VIEW_TYPE") == "PC" ) ? true: false;

// ***********************************
// fujiplayer
// ***********************************
var fujiplayer = new Object;

// background-color of overlay.
fujiplayer.overlay_bgcolor = "#000000"; 

// if [moviebox]element is dynamically generated,
// init() write to generated place.
fujiplayer.init = function(tags) {
	$(tags).unbind("click").click(function() {
		var p = $(this).attr("pgmcode") || null;
		var a = $(this).attr("movie") || $(this).attr("href") || this.href || this.alt;
		var g = this.rel || false;
		var rtkey = $(this).attr("rtkey") || "movieplayer";
		rtmetrics("/_onclick/"+rtkey, location.href);
		fujiplayer.show(p,a,g);
		this.blur();
		return false;
	});

	// for mailform  close.
	$("body").append('<script type="text/javascript">function _remove() { fujiplayer.mailformremove(); }</script>');

}

fujiplayer.show = function(pgmcode, url, movieType) {

	try {
		// pgmcode check.
		//movieType = ( pgmcode ) ? movieType: movieType + "_noinfo";
		movieType = ( boolAndroid && !isPC ) ? movieType + "_noinfo": ( booliOS ) ?  movieType + "_noinfo": ( pgmcode ) ? movieType: movieType + "_noinfo"; 
		
		// set overlay & window.
		fujiplayer.setbase();

		// show loading image.
		$("body").append("<div id='div_loading'><img src='"+imgLoader.src+"' /></div>");
		$('#div_loading').show();

		// defaults { height: 630, width: 440 }
		TB_WIDTH = ( movieType.indexOf("noinfo") !== -1 ) ? 506: 740; 
		TB_HEIGHT = ( movieType.indexOf("noinfo") !== -1 ) ? 295: 295;

		fp_infourl = fp_xmldir + pgmcode + "/" + pgmcode + ".xml?"+Math.round(Math.random()*1000);

		// make frame html.
		var _html = fujiplayer.getframehtml(pgmcode, url, movieType);

		// show frame.
		$("#div_window").html(_html);
		$("#div_loading").remove();
		$("#div_window").css({display:"block"});

		// change frame position.
		fujiplayer.setposition();
		
		// iOS can't play spot movie.
		if ( booliOS && movieType.indexOf("spot") !== -1 ) {
			$("#div_movie").css({"background-image":"url(/images/player/out_of_service.jpg)"});
		} else {
			// get movie.
			fujiplayer.getmovie(url, movieType);
	
			// set youtube panel.
			if ( movieType.indexOf("youtube") !== -1 ) { fujiplayer.setyoutube(); }
	
			// get program information.
			if ( movieType.indexOf("noinfo") === -1 ) { fujiplayer.getoainfo(pgmcode, url, movieType); }
		}

		// set <remove> to img & [esc]key.
		$("#a_closebutton").click(fujiplayer.remove);
		document.onkeyup = function(e) {
			keycode = ( e == null ) ? event.keyCode: e.which;
			if ( keycode == 27 ) { fujiplayer.remove(); }	
		};
	} catch(e) {
		var a = 1;
	}
}

fujiplayer.getframehtml = function(pgmcode, url, movieType) {
	var _html = "";
	var _type = ( movieType.indexOf("noinfo") === -1 ) ? true: false;

	_html += ( _type ) ? "<div id=\"mpcontents\">": "<div id=\"mpcontents\" class=\"noinfo\">";
	_html += "<div class=\"close\"><a href=\"javascript:void(0);\" id=\"a_closebutton\"><img src=\""+fp_closebutton+"\" alt=\"close\" /></a></div>";
	_html += ( _type ) ? "<div class=\"main\">": "<div class=\"main noinfo\">";
	_html += "<div id=\"div_movie\" class=\"mpmovie\"></div>";
	_html += "</div>";
	if ( _type ) {
		_html += "<div class=\"right\">";
		_html += "<div class=\"box\">";
		_html += "<div id=\"div_title\" class=\"title\"></div>";
		_html += "<div id=\"div_text\" class=\"text\"></div>";
		_html += "</div>";
		_html += "<div id=\"div_oatime\" class=\"oatime\"></div>";
		_html += "<ul>";
		_html += "<li id=\"li_official\" class=\"officialsite\"></li>";
		_html += "<li id=\"li_fod\" class=\"oldmovie\"></li>";
		_html += "</ul>";
		_html += "<div class=\"social\">";
		_html += "<div id=\"fp_social\"></div>";
		_html += "</div>";
		_html += "</div>";
	}
	_html += "</div>";
	
	return _html;
}

fujiplayer.mailbox = function(pgmcode, url, movieType) {

	try {
		// make mailform html.
		var _html = "";
		_html += "<div id='div_overlay_mail'></div>";
		_html += "<div id='div_mailform'>";
		_html += "<a href='#' id='a_mailclose' title='Close'><img title='close' src='"+fp_closebutton+"' alt='close'></a>";
		_html += "<iframe id='if_mail' frameborder='0' hspace='0' src='"+fp_mailform+"?p="+pgmcode+"&t="+movieType+"&m="+url+"'></iframe>";
		_html += "</div>";

		// show frame.
		$("body").append(_html);
		var overlaybg = ( fujiplayer.isMacFF() ) ? "div_overlaybghack": "div_overlaybg";
		$("#div_overlay_mail").addClass(overlaybg);

		// change frame position.
		fujiplayer.setposition("m");

		// set <remove> to overlay & img.
		$("#div_overlay_mail").click(fujiplayer.mailformremove);
		$("#a_mailclose").click(fujiplayer.mailformremove);
	} catch(e) {}
}

fujiplayer.setbase = function() {
	if ( typeof document.body.style.maxHeight === "undefined" ) {//if IE 6
		$("body","html").css({height: "100%", width: "100%"});
		$("html").css({overflow: "hidden"});
		if ( document.getElementById("div_hideselect") === null ) {//iframe to hide select elements in ie6
			$("body").append("<iframe id='div_hideselect'></iframe><div id='div_overlay'></div><div id='div_window'></div>");
			$("#div_overlay").click(fujiplayer.remove);
		}
	} else {//all others
		if ( document.getElementById("div_overlay") === null ) {
			$("body").append("<div id='div_overlay'></div><div id='div_window'></div>");
			$("#div_overlay").click(fujiplayer.remove);
		}
	}

	var overlaybg = ( fujiplayer.isMacFF() ) ? "div_overlaybghack": "div_overlaybg";
	$("#div_overlay").addClass(overlaybg);
	
	// overlay's background-color
	$(".div_overlaybg").css({"background-color": fujiplayer.overlay_bgcolor});
}

// remove movie window.
fujiplayer.remove = function() {
	$("#a_closebutton").unbind("click");
	$("#div_window").fadeOut("fast",function(){$('#div_window,#div_overlay,#div_hideselect').trigger("unload").unbind().remove();});
	$("#div_loading").remove();
	if ( typeof document.body.style.maxHeight == "undefined" ) {//if IE 6
		$("body","html").css({height: "auto", width: "auto"});
		$("html").css({overflow: ""});
	}
	document.onkeydown = "";
	document.onkeyup = "";
	clearInterval(ytFn.nowTimeWrite);
	clearInterval(ytFn.nowTimeSlide);
	return false;
}

// remove mail window.
fujiplayer.mailformremove = function() {
	$("#a_mailclose").unbind("click");
	$("#div_mailform").fadeOut("fast",function(){$('#div_mailform,#div_overlay_mail').trigger("unload").unbind().remove();});
	return false;
}

// window position settings.
fujiplayer.setposition = function() {
	var _i = ( arguments.length > 0 ) ? '#div_mailform': '#div_window';
	var _l = ( arguments.length > 0 ) ? '-250px': '-' + parseInt((TB_WIDTH / 2),10) + 'px';
	var _w = ( arguments.length > 0 ) ? '500px': TB_WIDTH + 'px';
	var _t = ( arguments.length > 0 ) ? '-190px': '-' + parseInt((TB_HEIGHT / 2),10) + 'px';

	if ( booliOS ) { $("#mpcontents").before("<div class=\"mpspace\"></div>");$(_i).css({marginLeft: "-130px", marginTop: "100px"}); } else { $(_i).css({marginLeft: _l, width: _w}); }
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7) ) { $(_i).css({marginTop: _t}); }
}

fujiplayer.parsequery = function(query) {
	var Params = {};
	if ( ! query ) { return Params; }
	var Pairs = query.split(/[;&]/);
	for ( var i = 0; i < Pairs.length; i++ ) {
		var KeyVal = Pairs[i].split('=');
		if ( ! KeyVal || KeyVal.length != 2 ) { continue; }
		var key = unescape( KeyVal[0] );
		var val = unescape( KeyVal[1] );
		val = val.replace(/\+/g, ' ');
		Params[key] = val;
	}
	return Params;
}

fujiplayer.isMacFF = function() {
	var userAgent = navigator.userAgent.toLowerCase();
	if ( userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox') != -1 ) { return true; }
}

fujiplayer.getmovie = function(url, movieType) {
	
	var _html = "";
	
	switch ( movieType ) {
		case 'spot':
		case 'spot_noinfo':
			if ( ( url.slice(-1) === "a" || url.slice(-1) === "b" ) && !fujiplayer.checklimit(url.slice(-9, -1), url.slice(-1)) ) {
				$("#div_movie").css({"background-image":"url(/images/player/no_playing2.jpg)"});
				break;
			}
		
			$("#div_movie").html("<div id=\"div_movie_target\"></div>")
			
			var swfVersionStr = "9.0.124";
			var xiSwfUrlStr = "";

			var flashvars = {};
			flashvars.width = "480";
			flashvars.height = "272";
			flashvars.flv = url;
			flashvars.autoStart = "true";
			flashvars.useMetadata = "true";
			flashvars.hideMetadata = "true";
			flashvars.noClear = "true";
			
			var params = {};
			params.allowFullScreen = "true"
			params.allowScriptAccess = "sameDomain"
			params.menu = "false"
			params.wmode = "opaque"

			var attributes = {};
			swfobject.embedSWF("/GPplayer/e/player_v3.swf", "div_movie_target", "480", "270", swfVersionStr, xiSwfUrlStr, flashvars, params, attributes);
			
			break;
		case 'youtube':
		case 'youtube_noinfo':
			if ( boolAndroid || booliOS ) {
				_html += '<object style="height: 270; width: 480">';
				_html += '<param name="movie" value="http://www.youtube.com/v/'+url+'?version=3">';
				_html += '<param name="wmode" value="opaque">';
				_html += '<param name="allowFullScreen" value="true">';
				_html += '<param name="allowScriptAccess" value="always">';
				_html += '<embed src="http://www.youtube.com/v/'+url+'?version=3" type="application/x-shockwave-flash" allowfullscreen="true" allowScriptAccess="always" width="480" height="270"></object>';
			} else {
				$("#div_movie").html("<div id=\"div_movie_in\"><div id=\"div_movie_target\"></div></div>")
	
				ytFn.mvPass = url;
				var params = { allowScriptAccess: "always", wmode: "opaque" };
				var params = { allowScriptAccess: "always", wmode: "transparent" };
				var atts = { id: "myytplayer" };
				swfobject.embedSWF("http://gdata.youtube.com/apiplayer?key="+ytFn.val.devkey+"&enablejsapi=1&playerapiid=ytplayer&html5=True&version=3", "div_movie_target", "480", "270", "8", null, null, params, atts);
	
				_html += "<div id=\"ytpanelWrap\">";
				_html += "<div id=\"ytpanel\">";
				_html += "<a class=\"pause\" href=\"javascript:void(0);\" title=\"pause\" style=\"display: none;\" onclick=\"ytFn.pause();\">PAUSE</a>";
				_html += "<a class=\"play\" href=\"javascript:void(0);\" title=\"play\" onclick=\"ytFn.play();\">PLAY</a>";
				_html += "<a class=\"stop\" href=\"javascript:void(0);\" title=\"stop\" onclick=\"ytFn.playstop();\">STOP</a>";
				_html += "<div id=\"youtubeSlider\" class=\"ui-slider ui-slider-horizontal ui-widget ui-widget-content ui-corner-all\"></div>";
				_html += "<p class=\"time\"><span id=\"nowPositon\"></span>/<span id=\"totalTime\"></span></p>";
				_html += "<a class=\"mute\" href=\"javascript:void(0);\" title=\"mute\" onclick=\"ytFn.playermute();\">MUTE</a>";
				_html += "<a class=\"unmute\" href=\"javascript:void(0);\" title=\"unmute\" onclick=\"ytFn.playerunmute();\" style=\"display: none;\">UNMUTE</a>";
				_html += "</div>";
				_html += "</div>";
			}
			break;
		default:
			break;
	}

	$("#div_movie").append(_html)

	return false;

}

fujiplayer.spot = function() {
	var ret = fujiplayer.getargs(arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000", "application/x-shockwave-flash");
	return fujiplayer.makespot(ret.objAttrs, ret.params, ret.embedAttrs);
}

fujiplayer.makespot = function(objAttrs, params, embedAttrs) { 
	var str = '';
	if ( isIE && isWin && !isOpera ) {
		str += '<object ';
		for (var i in objAttrs) { str += i + '="' + objAttrs[i] + '" '; }
		str += '>';
		for (var i in params) { str += '<param name="' + i + '" value="' + params[i] + '" /> '; }
		str += '</object>';
	} else {
		str += '<embed ';
		for (var i in embedAttrs) { str += i + '="' + embedAttrs[i] + '" '; }
		str += '> </embed>';
	}
	return str;
}

fujiplayer.getargs = function(args, ext, srcParamName, classid, mimeType) {
	var ret = new Object();
	ret.embedAttrs = new Object();
	ret.params = new Object();
	ret.objAttrs = new Object();
	for (var i=0; i < args.length; i=i+2){
		var currArg = args[i].toLowerCase();    
		switch (currArg){	
			case "classid":
				break;
			case "pluginspage":
				ret.embedAttrs[args[i]] = args[i+1];
				break;
			case "src":
			case "movie":	
				args[i+1] = ( args[i+1].indexOf('?') != -1 ) ? args[i+1].replace(/\?/, ext+'?'): args[i+1] + ext;
				ret.embedAttrs["src"] = args[i+1];
				ret.params[srcParamName] = args[i+1];
				break;
			case "onafterupdate":
			case "onbeforeupdate":
			case "onblur":
			case "oncellchange":
			case "onclick":
			case "ondblclick":
			case "ondrag":
			case "ondragend":
			case "ondragenter":
			case "ondragleave":
			case "ondragover":
			case "ondrop":
			case "onfinish":
			case "onfocus":
			case "onhelp":
			case "onmousedown":
			case "onmouseup":
			case "onmouseover":
			case "onmousemove":
			case "onmouseout":
			case "onkeypress":
			case "onkeydown":
			case "onkeyup":
			case "onload":
			case "onlosecapture":
			case "onpropertychange":
			case "onreadystatechange":
			case "onrowsdelete":
			case "onrowenter":
			case "onrowexit":
			case "onrowsinserted":
			case "onstart":
			case "onscroll":
			case "onbeforeeditfocus":
			case "onactivate":
			case "onbeforedeactivate":
			case "ondeactivate":
			case "type":
			case "codebase":
			case "id":
				ret.objAttrs[args[i]] = args[i+1];
				break;
			case "width":
			case "height":
			case "align":
			case "vspace": 
			case "hspace":
			case "class":
			case "title":
			case "accesskey":
			case "name":
			case "tabindex":
				ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
				break;
			default:
				ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
		}
	}
	ret.objAttrs["classid"] = classid;
	if ( mimeType ) ret.embedAttrs["type"] = mimeType;
	return ret;
}
			
fujiplayer.getoainfo = function(pgmcode, url, movieType) {
	var _mpage="http://www.fujitv.co.jp/index.html";
	$.ajax({
		type: "GET", url: fp_infourl, dataType: "xml", cache: true, success: function(xml) {
			$(xml).find("onair").each(function(i) {
				var rgexp = new RegExp(/<("[^"]*"|'[^']*'|[^'">])*>/g);
				var _x = fujiplayer.xml(this);
				
				_x.title = ( _x.title.replace(rgexp, "").length > 30 ) ? _x.title.replace(rgexp, "").substring(0, 29) + "…": _x.title.replace(rgexp, "");
				_x.overview = ( _x.overview.replace(rgexp, "").length > 64 ) ? _x.overview.replace(rgexp, "").substring(0, 63) + "…": _x.overview.replace(rgexp, "");
				
				$("#div_title").html(_x.title);
				$("#div_text").html(_x.overview);
				// Quick Date Check
				
				if( _x.end == undefined || _x.end == '' || _x.end == null ){
						$("#div_oatime").html(_x.date.replace(rgexp, ""));
				}else{
					var chkDate = new Date(_x.date.replace(rgexp, "").substring(0,11).split("日")[0].replace("年","/").replace("月","/"));
					if ( isNaN(chkDate.getYear()) ) {
						$("#div_oatime").html(_x.date.replace(rgexp, "")+" " +_x.start+"～"+_x.end);
					} else {
						$("#div_oatime").html(_x.date.replace(rgexp, "").split("年")[1]+" "+_x.start+"～"+_x.end);
					}
				}

				if ( _x.ourl && _x.ourl.indexOf(".fujitv.co.jp") !== -1 ) {
					$("#li_official").html("<a href=\""+_x.ourl+"\" onclick=\"rtmetrics('/_onclick/movieplayer/"+pgmcode+"','"+location.href+"')\">オフィシャルサイト</a>");
					$("#li_official").addClass("officialsite");
					$("#li_official").removeClass("basic");
				} else if ( _x.url ) {
					$("#li_official").html("<a href=\""+_x.url+"\">番組基本情報</a>");
					$("#li_official").addClass("basic");
					$("#li_official").removeClass("officialsite");
				}
				if ( _x.fod === "" ) { $("#li_fod").remove(); } else { $("#li_fod").html("<a href=\""+_x.fod+"\">過去の本編を見る</a>"); }
				//$("#li_overview").html(_html);
				//$("#li_imatsubu").html(_html);
				//$("#li_video").html(_html);
				//$("#li_eshop").html(_html);
				
				_mpage = ( location.pathname.indexOf("timetable") !== -1 ) ? _x.url: location.protocol + "//" + location.host + location.pathname;
				WriteSB2_MoviePlayer(_x.url + "?p="+pgmcode+"&t="+movieType+"&m="+url, "");
				$("#div_send").html("<div class=\"mail\"><a class=\"mailbox\" pgmcode=\""+pgmcode+"\" href=\""+url+"\" rel=\""+movieType+"\"><img src=\"/images/player/b_mail.gif\" width=\"90\" height=\"20\" alt=\"メールで送る\" /></a></div>");
				
			});

		}, error: function() {
			$("#div_title").html("※番組情報が取得出来ませんでした。");
			WriteSB2_MoviePlayer(_mpage + "?p="+pgmcode+"&t="+movieType+"&m="+url, "");
			$("#div_send").html("<div class=\"mail\"><a class=\"mailbox\" pgmcode=\""+pgmcode+"\" href=\""+url+"\" rel=\""+movieType+"\"><img src=\"/images/player/b_mail.gif\" width=\"90\" height=\"20\" alt=\"メールで送る\" /></a></div>");
			/*
			$("#mpcontents .right").remove();
			$("#mpcontents").addClass("noinfo");
			$("#mpcontents .main").addClass("noinfo");
			*/
			
		}, complete: function(){
			$("a.mailbox").click(function() {
				var p = $(this).attr("pgmcode") || null;
				var a = $(this).attr("href") || this.href || this.alt;
				var g = this.rel || false;
				fujiplayer.mailbox(p,a,g);
				this.blur();
				return false;
			});
		}
	});
	
}

fujiplayer.checklimit = function(_day,_flg) {
	_day = ( _flg === "a" ) ? new Date(_day.slice(0, 4), _day.slice(4, 6) - 1, _day.slice(6, 8), 12, 0, 0): new Date(_day.slice(0, 4), _day.slice(4, 6) - 1, _day.slice(6, 8), 23, 59, 59);
	var _now = new Date();
	return ( _now < _day ) ? true: false;
}

fujiplayer.xml = function(_this) {
	var _r = {
		"date": $(_this).find("oadate").text(),
		"start": $(_this).find("start").text(),
		"end": $(_this).find("end").text(),
		"title": $(_this).find("title").text(),
		"subtitle": $(_this).find("subtitle").text(),
		"overview": $(_this).find("overview").text(),
		"cast": $(_this).find("cast1").text(),
		"mplus": $(_this).find("mplus").text(),
		"movie": $(_this).find("movie").text(),
		"fod": $(_this).find("fod").text(),
		"imatsubu": $(_this).find("imatsubu").text(),
		"video": $(_this).find("video").text(),
		"eshop": $(_this).find("eshop").text(),
		"url": $(_this).find("url").text(),
		"ourl": $(_this).find("ourl").text()
	}
	return _r;
}

fujiplayer.setyoutube = function() {
	// css.
	$("head").append("<link>");
	css = $("head").children(":last");
	css.attr({ type: "text/css", rel: "stylesheet", href: "/javascripts/css/jquery-ui-1.8.13.custom.css" });

	//slider
	$('#youtubeSlider').slider({
		range : 'min',
		min   : 0,
		max   : 100,
		slide : function(event, ui) { ytFn.player.pauseVideo(); },
		change : function(event, ui) {
			var jumpTime = ytFn.totalRealtime * ( ui.value / 100 );
			ytFn.player.seekTo(jumpTime, true);

			switch( ytFn.player.getPlayerState() ){
				case 2:
					ytFn.player.playVideo();
					break;
				case 5:
					ytFn.player.playVideo();
					break;
			}
		}
	});

	// overout
	$("#div_movie").mouseover(function(){
		$("#ytpanelWrap").css({ top: "-38px" });
	}).mouseout(function(){
		$("#ytpanelWrap").css({ top: "38px" });
	});
}

// ***********************************
// For YouTube.
// ***********************************
var ytFn = {
	val: {
		devkey: 'AI39si5h1X_1raWYLpPLf63Sj6w8XeCIIsxJDqbTHwTtPsFLa3VFWr9jI8JpZlp91HCQ3NymR2jDL9Bb03s_j3t19FWwOlytOg'
	}
}
// playtime convert.
ytFn.timeConvert = function(timeString){
		var m = Math.floor(timeString / 60);
		var s = Math.round(timeString % 60);
		if ( s == 60 ) {
			m++;
			s = 0;
		}
		if ( s < 10 ) s = '0' + s;

		return m + ':' + s;
}
// output playtime.
ytFn.nowTimeState = function(){
	if ( typeof ytFn.player.getCurrentTime !== "function" ) { clearInterval(ytFn.nowTimeWrite); return; } 
	$('#nowPositon').html(ytFn.timeConvert(ytFn.player.getCurrentTime()));
}
// timebar slide.
ytFn.slideMove = function(){
	if ( typeof ytFn.player.getCurrentTime !== "function" ) { clearInterval(ytFn.nowTimeSlide); return; } 
	var nowSliderPosition = (ytFn.player.getCurrentTime() / ytFn.totalRealtime) * 100;
	$('.ui-slider-handle').css({left: nowSliderPosition + '%'});
	$('.ui-slider-range').css({width: nowSliderPosition + '%'});

	// 動画の長さを取得
	ytFn.totalRealtime = ytFn.player.getDuration();
	ytFn.totaltime = ytFn.timeConvert(ytFn.player.getDuration());
	$('#totalTime').html(ytFn.totaltime);
}
// check status.
ytFn.onytplayerStateChange = function( newState ){
		// 起動中のタイマーをクリア
		clearInterval(ytFn.nowTimeWrite);
		clearInterval(ytFn.nowTimeSlide);

		ytFn.status = 1;
		switch( newState ){
			case 1: // 1:再生

				ytFn.nowTimeWrite = setInterval(ytFn.nowTimeState, 250);
				ytFn.nowTimeSlide = setInterval(ytFn.slideMove, 100);
				$('#ytpanel .play').hide();
				$('#ytpanel .pause').show();

				break;
	
			case 0: // 0:終了
				$('.ui-slider-handle').css({left: '0%'});
				$('.ui-slider-range').css({width: '0%'});
				$('#nowPositon').html('0:00');
				$('#ytpanel .pause').hide();
				$('#ytpanel .play').show();
				//ytFn.playstop();
				break;
		}
	
}
// YouTube Control panels.
ytFn.play = function() {//再生
	ytFn.player.playVideo();
	$('#ytpanel .play').hide();
	$('#ytpanel .pause').show();
}
ytFn.pause = function() {//一時停止
	ytFn.player.pauseVideo();
	$('#ytpanel .pause').hide();
	$('#ytpanel .play').show();
}
ytFn.playstop = function() {//停止
	ytFn.player.seekTo(1, true);
	ytFn.player.playVideo();
	ytFn.player.pauseVideo();
	$('.ui-slider-handle').css({left: '0%'});
	$('.ui-slider-range').css({width: '0%'});
	$('#nowPositon').html('0:00');
	$('#ytpanel .pause').hide();
	$('#ytpanel .play').show();
}
ytFn.playermute = function() {//ミュート
	ytFn.player.mute();
	$('#ytpanel .mute').hide();
	$('#ytpanel .unmute').show();
}
ytFn.playerunmute = function() {//ミュート解除
	ytFn.player.unMute();
	ytFn.player.setVolume(100);
	$('#ytpanel .unmute').hide();
	$('#ytpanel .mute').show();
}

var onYouTubePlayerReady = function(playerid) {
	ytFn.player = document.getElementById('myytplayer');
	ytFn.player.loadVideoById(ytFn.mvPass);//自動再生

	// 動画の状態が変更された場合に実行する関数
	ytFn.player.addEventListener('onStateChange', 'ytFn.onytplayerStateChange');
}

try {
	$(document).ready(function(){
		if ( typeof swfobject === "undefined" ) {
			var _css = document.createElement('script');
			_css.setAttribute('type', "text/javascript");
			_css.setAttribute('src', "/javascripts/swfobject2.js");
			document.getElementsByTagName("head")[0].appendChild(_css);
			//$("body").append('<script type="text/javascript" src="/javascripts/swfobject2.js"></scri'+'pt>');
		}
		
		var _css = document.createElement('link');
		_css.setAttribute('type', "text/css");
		_css.setAttribute('rel', "stylesheet");
		_css.setAttribute('href', "/css/fujiplayer.css");
		document.getElementsByTagName("head")[0].appendChild(_css);
	
		// if [moviebox]element is dynamically generated,
		// init() write to generated place.
		// fujiplayer.init('a.moviebox');
	
		imgLoader = new Image();
		imgLoader.src = fp_loading;
	
		// if call with query, show frame.
		if ( location.search.indexOf("m=") !== -1 ) {
			var _q = fujiplayer.parsequery(location.search.substring(1));
			fujiplayer.show(_q["p"],_q["m"],_q["t"]);
			return false;
		}
	});
} catch(e) {}

