var containerStyle = { };
var playerMaximized = false;

var EventDispatcher = Class.create();
EventDispatcher.prototype = {
  initialize: function(){
    this._listenerMap = {};
  },
  addEventListener : function( type , listener ){
    var map = this._listenerMap ;
    if( !map[ type ] ){
      map[type] = [];
    }
    map[type].push( listener );
  },
  dispatchEvent : function( type , args ){
    var map = this._listenerMap ;
    if( !map[ type ] ){
      return;
    }

    var listeners = map[ type ];
    for( var i = 0 , n = listeners.length ; i < n ; i++ ){
      listeners[i].apply( null , args );
    }
  }
};
var NicoplayerEventDispatcher = new EventDispatcher();

function maximizePlayer() {
	$("siteHeader", "zero_lead_index", "PAGEURGENT", "PAGEHEADER", "WATCHHEADER", "WATCHFOOTER", "PAGEFOOTER").compact().invoke("hide");
	var container = $("flvplayer_container");
	["width", "height", "margin", "padding"].each(function (k) { containerStyle[k] = container.getStyle(k); });
	[container].concat(container.ancestors()).invoke("setStyle", { margin: "0", padding: "0", width: "100%", height: "100%" });
	fitPlayerToWindow();
	Event.observe(window, "resize", fitPlayerToWindow, false);
	if (typeof rotationAdvertisement != "undefined")
		rotationAdvertisement.pause();
}

function fitPlayerToWindow() {
	$("flvplayer").setStyle({ width: "100%", height: "100%" });
}

function restorePlayer() {
	Event.stopObserving(window, "resize", fitPlayerToWindow, false);
	$("flvplayer").setStyle({ width: "", height: "" });
	setTimeout(function () {
		var container = $("flvplayer_container");
		[container].concat(container.ancestors()).invoke("setStyle", { margin: "", padding: "", width: "", height: "" });
		container.setStyle(containerStyle);
		$("siteHeader", "zero_lead_index", "PAGEURGENT", "PAGEHEADER", "WATCHHEADER", "WATCHFOOTER", "PAGEFOOTER").compact().invoke("show");
		Element.scrollTo($("flvplayer_container"));
		if (typeof rotationAdvertisement != "undefined")
			rotationAdvertisement.resume();
	}, 0);
}

function toggleMaximizePlayer() {
	if (playerMaximized) {
		restorePlayer();
	} else {
		maximizePlayer();
	}
	playerMaximized = !playerMaximized;
}

function setMymemoryParameters(ranges, date) {
	resetMymemoryParameters();
	var form = $("mymemory_add_form");
	if (!form) return;
	for (var type in ranges) {
		var range = ranges[type];
		for (var key in range) {
			if (range[key] !== undefined && range[key] !== null) {
				var field = document.createElement("input");
				field.type = "hidden";
				field.name = "ranges[" + type + "][" + key + "]";
				field.value = range[key];
				form.appendChild(field);
			}
		}
	}
	if (date) {
		form["date"].value = date;
	}
}

function resetMymemoryParameters() {
	var form = $("mymemory_add_form");
	if (!form) return;
	form.getInputs("hidden").each(function (field) {
		if (field.name === "date") {
			field.value = "";
		} else if (/^ranges/.test(field.name)) {
			field.parentNode.removeChild(field);
		}
	});
}


var deflistAddMessages = {
	EXIST: '<a href="/my/mylist" style="color:#FFF;">この動画はすでに「とりあえずマイリスト」に登録されています。</a>',
	NOAUTH: 'ログインしてください。',
	MAINTENANCE: 'メンテナンス中です。',
	EXPIRETOKEN: '画面の有効期限が切れました。お手数ですが画面を再読込してください。',
	INVALIDVIDEO: 'この動画は登録できません',
	INTERNALERROR: '登録中にエラーが発生しました'
};

var addVideoToDeflistAdding = false;
function addVideoToDeflist(item_id, token) {
	if (addVideoToDeflistAdding) return;
	addVideoToDeflistAdding = true;
	$("MSG_deflist_success", "MSG_deflist_error").invoke("hide");
	$("MSG_deflist_loading", "MSG_deflist").invoke("show");
	new Ajax.Request("/api/deflist/add", {
		parameters: { item_id: item_id, token: token },
		onComplete: function (res) {
			$("MSG_deflist_loading").hide();
			var data = res.responseText.evalJSON();
			if (data.status == "ok") {
				$("MSG_deflist_success").show();
			} else if (data.error && deflistAddMessages[data.error.code]) {
				$("MSG_deflist_error").update(deflistAddMessages[data.error.code]).show();
			} else {
				$("MSG_deflist_error").update(deflistAddMessages.INTERNALERROR).show();
			}
			setTimeout(function () {
				$("MSG_deflist").hide();
				addVideoToDeflistAdding = false;
			}, 3000);
		}
	});
}

var NicoPlayerReady = function() {
	var funcList = [];
	var execFlag = false;
	
	return {
		"register": function(func) {
			if (execFlag) {
				setTimeout(func, 1);
			} else {
				funcList.push(func);
			}
		},
		"execute": function() {
			execFlag = true;
			var func;
			while (func = funcList.pop()) {
				func();
			}
		}
	}
}();

function onNicoPlayerReady() {
	NicoPlayerReady.execute();
}

function seekNicoPlayer(timestr) {
	var m = /^#(\d+):(\d+)$/.exec(timestr);
	if (m) {
		var min = parseInt(m[1].replace(/^0+(?=[1-9])/, ""));
		var sec = parseInt(m[2].replace(/^0+(?=[1-9])/, ""));
		$("flvplayer").ext_setPlayheadTime(min*60 + sec);
	}
}

function onVideoStarted(){ NicoplayerEventDispatcher.dispatchEvent( "videoStarted",arguments); }
function onVideoPlayed() { NicoplayerEventDispatcher.dispatchEvent( "videoPlayed" ); }
function onVideoStopped(){ NicoplayerEventDispatcher.dispatchEvent( "videoStopped"); }
function onVideoEnded()  { NicoplayerEventDispatcher.dispatchEvent( "videoEnded"  ,arguments); }
