/* ----------------------------------------
	Initialize
---------------------------------------- */
var id_mv = {
	img: "#mv_img_base",			// メイン画像ID
	imgDissolve: "#mv_img_front",	// ディゾルブ用の画像ID

	titleBox: "#mv_titleBox",
	title: "#mv_title",
	lead: "#mv_lead",
	playBtn: "#mv_playBtn",
	moreURL: "#mv_more",

	player: "#mv_bc"
}
var id_th = {
	thumb: "#mvt_slideBoxInner",
	bk: "#mvt_backBtn",
	next: "#mvt_nextBtn"
}
var th = {
	xmlURL: "top/mainvisual/setting.xml",
	speedD: 1000,					// ディゾルブのスピード
	speed: 500,						// スクロールのスピード
	speedSlide: 5000,				// 次のサムネールに移動するスピード
	nonAvailable: 0.1,

	number: 5,						// 一度に表示する個数
	height: 55,

	playerW: 608,					// BCプレーヤーの幅
	playerH: 342,					// BCプレーヤーの高さ

	timerID: 0
}
th.scrollH = 1 * th.height;
th.offset = 2 * th.height;
var flag = {
	bcRead: false,			// BCに一度でも動画が読み込まれたかどうか
	bcReading: false,		// BC動画読み込み中
	
	//current: 0,				// 不要なはず
	firstVisibleID: 0,		// 表示枠の一番上の画像のID

	scroll: false,			// スクロール中
	dissolve: false,			// ディゾルブ中
	readVdTimerID: 0
}

/* ----------------------------------------
	Program Using
---------------------------------------- */
var bcExp;
var modVP;
var modExp;
var modCon;

function onTemplateLoaded(experienceID) {
 
    bcExp = brightcove.getExperience(experienceID);
 
    modVP = bcExp.getModule(APIModules.VIDEO_PLAYER);
    modExp = bcExp.getModule(APIModules.EXPERIENCE);
    modCon = bcExp.getModule(APIModules.CONTENT);
	
	modVP.addEventListener("mediaComplete", hidePlayer);
    modVP.addEventListener("mediaBegin", mediaBegin);
	//modExp.addEventListener(BCExperienceEvent.TEMPLATE_READY, onTemplateReady);
	
   // modExp.addEventListener(BCExperienceEvent.CONTENT_LOAD, function() {});
}

/* ----------------------------------------
	Main
---------------------------------------- */
$(function() {
	init();
	writeImages();

	// サムネールクリック監視
	$(id_th.thumb + " > li").click(function() {
		if (!flag.bcReading) {
			rewriteMain(this.id);
		}
	});

	// 視聴ボタンのクリック監視
	$(id_mv.playBtn + " > span").click(function() {
		flag.bcReading = true;
		bcPlay(this.id);
	});

	// 上下矢印のクリック監視
	$(id_th.bk + "," + id_th.next).click(function() {
		if (!flag.bcReading) {
			scrollNextBack(this.id);
		}
	});
});

/* ----------------------------------------
	Functions
---------------------------------------- */
// 初期化
function init() {
	$(id_th.bk + "," + id_th.next).css("opacity", th.nonAvailable);
	$(id_mv.img).hide();
	$(id_mv.titleBox).hide();
	hidePlayer();

}

// プレーヤーを隠す
function hidePlayer() {
	if (flag.bcRead) {
		if (modVP.isPlaying()) {
			modVP.stop();
		}
	}
	$(id_mv.player).width(1);
	$(id_mv.player).height(1);
	$(id_mv.player).css("opacity", 0);
}

// プレーヤーの表示
function showPlayer() {
	$(id_mv.player).width(th.playerW);
	$(id_mv.player).height(th.playerH);
	$(id_mv.player).css("opacity", 1);
	flag.dissolve = false;
}

function mediaBegin() {
	flag.bcReading = false;
}
// xmlよりサムネール書き出し
function writeImages() {
	var i;
	var strHTML = "";
	var dataRandom = new Array();

	var http = new JKL.ParseXML(th.xmlURL);
    th.data = http.parse().mainVisual.titleList;
	th.randomSW = http.parse().mainVisual.randomSW;
	var defaultLength = th.data.length;
	
	// ランダム処理
	if (th.randomSW == "on") {
		var cnt = 0;
		var rdnm;
		while (th.data.length > 0) {
			rdnm = Math.floor(Math.random() * th.data.length);
			dataRandom[cnt] = th.data[rdnm];
			th.data.splice(rdnm, 1);
			cnt++;
		}
		for (i in dataRandom) {
			th.data[i] = dataRandom[i]
		}
	}

	// 永久ループ対応、データ複製
	var loopCount = th.data.length;
	while (loopCount <= th.number) {
		for (i = 0; i < defaultLength; i++){
			th.data[loopCount] = th.data[i];
			loopCount++;
		}
	}
	
	for (i = 0; i < th.data.length * 2; i++) {
		if(i < th.data.length) {
			strHTML += '<li class="mv_thumb" id="mv' + i + '"><img src="' + th.data[i].thumbURL + '" /></li>';
		} else {
			strHTML += '<li class="mv_thumb" id="mv' + i + '"><img src="' + th.data[i - th.data.length].thumbURL + '" /></li>';
		}
	}
	
	$(id_th.thumb).html(strHTML);

	flag.firstVisibleID = th.data.length - 2;

	// CSSの書き換え
	$(id_th.thumb).height(th.data.length * 2 * th.height - 10);
	$(id_th.thumb + " > li").each(function() {
		$(this).css("top", this.id.replace("mv", "") * th.height);
	});
	$(id_th.thumb).css("top", flag.firstVisibleID * th.height * -1); 

	// 最初の画像の表示
	$(id_mv.img).attr("src", th.data[0].imgURL);
	rewriteMain("mv" + th.data.length);

	// 表示するサムネールの個数が表示枠からあふれる場合のスクロール矢印
	if (th.number < th.data.length) {
		$(id_th.bk).css("opacity", 1);
		$(id_th.next).css("opacity", 1);
	};
	
}

// メイン画像の表示処理
function rewriteMain(id) {
	if (flag.dissolve || flag.scroll) return;

	if (id || id == 0) {
 		clearInterval(th.timerID);
 		th.timerID = 0;
		id = parseInt(id.replace("mv", ""));
	}

	flag.dissolve = true;
	scrollID(id);
	hidePlayer();

	if (id >= th.data.length) id -= th.data.length;
	
	
	//	メイン画像のディゾルブ
	$(id_mv.imgDissolve).attr("src", th.data[id].imgURL);
	$(id_mv.imgDissolve).fadeIn(th.speedD, function() {
		$(id_mv.img).attr("src", th.data[id].imgURL);
		setTimeout(function() {
			$(id_mv.img).show();
			$(id_mv.imgDissolve).hide();
			flag.dissolve = false;
		}, 10);
	});
	
	$(id_mv.titleBox).slideUp(th.speedD/2, function() {
		$(id_mv.title).html(tag(th.data[id].title));
		$(id_mv.lead).html(tag(th.data[id].lead));
		if (th.data[id].videoID) {
			$(id_mv.playBtn + " > span").attr("id", "bctid" + th.data[id].videoID);
			$(id_mv.playBtn).show();
		} else $(id_mv.playBtn).hide();
		if (th.data[id].moreURL) {
			$(id_mv.moreURL + " > a").attr("href", th.data[id].moreURL);
			$(id_mv.moreURL).show();
		} else $(id_mv.moreURL).hide();
		if (th.data[id].moreURLtarget) {
			$(id_mv.moreURL + " > a").attr("target", th.data[id].moreURLtarget);
		} else {
			$(id_mv.moreURL + " > a").attr("target", "_self");
		}
		$(id_mv.titleBox).slideDown(th.speedD/2);
	});

	// スライドショーの処理
	if (!th.timerID) {
		th.timerID = setInterval(function() {
			if (!flag.bcReading && !modVP.isPlaying()) {
				flag.firstVisibleID++;
				rewriteMain("mv" + parseInt(flag.firstVisibleID + 2));
			}
		}, th.speedSlide);
	}
}

// 動画の再生
function bcPlay(id) {
	if (!flag.readVdTimerID) {
		flag.readVdTimerID = setInterval(function() {
			if (modVP) {
				modVP.loadVideo(id.replace("bctid", ""));
				showPlayer();
				flag.bcRead = true;
				clearInterval(flag.readVdTimerID);
				flag.readVdTimerID = 0;
			}
		}, 1000);
	}
}

// xml内タグ処理（現在は改行のみ）
function tag(str) {
	str = str.replace("/tag.br/", "<br />");
	return str;
}

// ネクストバックボタンのスクロール処理
function scrollNextBack(id) {
	if (flag.scroll) return;
	if (id_th.bk.indexOf(id) != -1) offset = -1;
	if (id_th.next.indexOf(id) != -1) offset = 1;
	
	flag.firstVisibleID += offset;
	rewriteMain("mv" + parseInt(flag.firstVisibleID + 2));
}

// idによるスクロール
function scrollID(id) {
	flag.firstVisibleID = id - 2;
	scroll();
}

function scroll() {
	var totalH = th.scrollH * th.data.length;
	flag.scroll = true;
	
	if (flag.firstVisibleID < 0) {
		flag.firstVisibleID += th.data.length;
		$(id_th.thumb).css("top", parseInt($(id_th.thumb).css("top")) - totalH);
	}

	var offsetY = -1 * flag.firstVisibleID * th.height;
	
	$(id_th.thumb).animate({
		top: offsetY
	}, {
		duration: th.speed,
		easing: "easeOutQuad",
		complete: function () {
			if (flag.firstVisibleID >= th.data.length) {
				flag.firstVisibleID -= th.data.length;
				$(id_th.thumb).css("top", parseInt($(id_th.thumb).css("top")) + totalH);
			}
			flag.scroll = false;
		}
	});
}
