/* ロード完了時の処理 */
addEvent(window, "load", function() {
	var mainBox = document.getElementById("main");	
	
	/* 出現・消失アニメーション */
	var theRadicals = new Array();	//描画する部首のリスト。
	var theDate = new Date();
	var theTime = theDate.getTime();
	setInterval(function() {
		theDate = new Date();
		for (var i = 0; i < theRadicals.length; i++) {
			theRadicals[i]["passage"] = theRadicals[i]["passage"] + (theDate.getTime() - theTime) / 1000;
			
			if (theRadicals[i]["passage"] < theRadicals[i]["appear"]) {
				setOpacity(theRadicals[i]["div"], theRadicals[i]["passage"] / theRadicals[i]["appear"] * theRadicals[i]["alpha"]);
				
			} else if ((theRadicals[i]["passage"] >= theRadicals[i]["appear"]) && (theRadicals[i]["passage"] < theRadicals[i]["appear"] + theRadicals[i]["duration"])) {
				setOpacity(theRadicals[i]["div"], theRadicals[i]["alpha"]);
				
			} else if ((theRadicals[i]["passage"] >= theRadicals[i]["appear"] + theRadicals[i]["duration"]) && (theRadicals[i]["passage"] < theRadicals[i]["appear"] + theRadicals[i]["duration"] + theRadicals[i]["vanish"])) {
				setOpacity(theRadicals[i]["div"], (1 - Math.pow((theRadicals[i]["passage"] - theRadicals[i]["appear"] - theRadicals[i]["duration"]) / theRadicals[i]["vanish"], 2)) * theRadicals[i]["alpha"]);
				
			} else {
				theRadicals[i]["div"].style.visibility = "hidden";
				theRadicals.splice(i, 1);
				i--;
			}
		}
		theTime = theDate.getTime();
	}, 100);


	
	/* 画像の読み込み */
	var imageComplete = false;
	var theImages = new Array();
	setTimeout(function() {
		for (var i = 0; i < 30; i++) {
			theImages[i] = new Image();
			theImages[i].src = "images/radical" + (i + 1)+ ".png";
		}
		var theInterval = setInterval(function() {
			for (var i = 0; i < theImages.length; i++) {
				if (!(theImages[i].complete)) {
					return;
				}
			}
			imageComplete = true;
			mainBox.style.overflow = "hidden";		
			clearInterval(theInterval);
		}, 500);
	}, 1000);


	
	/* 部首追加の関数 */
	function addRadical(theX, theY, theZ, theAlpha, theDuration, appearDuration, vanishDuration) {
		if (imageComplete) {
			var theImage = theImages[Math.floor(Math.random() * theImages.length)];
			var theDiv = mainBox.appendChild(document.createElement("div"));
			if (navigator.appName == "Microsoft Internet Explorer") {	//IEではfilterを使った90°毎の回転。
				var theAngle = Math.floor(Math.random() * 4);
				if (theAngle == 0 || theAngle == 2) {
					var theWidth = theImage.width;
					var theHeight = theImage.height;
				} else {
					var theWidth = theImage.height;
					var theHeight = theImage.width;
				}
				with (theDiv.style) {
					position = "absolute";
					left = theX - theWidth / 2 + "px";
					top = theY - theHeight / 2 + "px";
					width = ((theWidth > theHeight) ? theWidth : theHeight) + "px";
					height = ((theWidth > theHeight) ? theWidth : theHeight) + "px";
					zIndex = theZ;
				}
				var imageDiv = theDiv.appendChild(document.createElement("div"));
				theImg = imageDiv.appendChild(document.createElement("img"));
				theImg.width = ((theWidth > theHeight) ? theWidth : theHeight);
				theImg.height = ((theWidth > theHeight) ? theWidth : theHeight);
				theImg.src = "images/blank.gif";
				theImg.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + theImage.src + "',sizingMethod=image)";
				imageDiv.style.filter = "progid:DXImageTransform.Microsoft.BasicImage(rotation=" + theAngle + ")";				
				imageDiv.style.width = ((theWidth > theHeight) ? theWidth : theHeight) + "px";
				imageDiv.style.height = ((theWidth > theHeight) ? theWidth : theHeight) + "px";
			} else {	//それ以外
				var theSize = Math.ceil(Math.sqrt(Math.pow(theImage.width, 2) + Math.pow(theImage.height, 2)));
				with (theDiv.style) {
					position = "absolute";
					left = theX - theSize / 2 + "px";
					top = theY - theSize / 2 + "px";
					zIndex = theZ;
				}
				if (typeof(theDiv.style.webkitTransform) != "undefined") {	//-webkit-transformで描画
					with (theDiv.style) {
						width = theSize + "px";
						height = theSize + "px";
						background = "url('" + theImage.src + "') no-repeat center center";
						webkitTransform = "rotate(" + (Math.random() * 360) + "deg)";
					}
				} else {	//Canvasで描画
					var theCanvas = theDiv.appendChild(document.createElement("canvas"));
					theCanvas.width = theSize;
					theCanvas.height = theSize;
					var theContext = theCanvas.getContext("2d");
					if (navigator.appName == "Opera") {	//OperaのCanvasで半透明画像を描画するとなぜか明度が落ちるので、背景色を画像で切り抜く。
						var theColors = new Array("rgb(255, 255, 54)", "rgb(153, 192, 134)", "rgb(189, 240, 54)", "rgb(164, 149, 217)", "rgb(255, 206, 78)", "rgb(54, 109, 143)", "rgb(59, 127, 78)", "rgb(174, 204, 231)", "rgb(226, 60, 81)", "rgb(250, 98, 118)");
						theContext.fillStyle = theColors[Math.floor(Math.random() * theColors.length)];
						with (theContext) {
							fillRect(0, 0, theSize, theSize);
							globalCompositeOperation = "destination-atop";
						}
					}
					with (theContext) {
						translate(theSize / 2, theSize / 2);
						rotate(Math.random() * Math.PI * 2);
						translate(-(theSize / 2), -(theSize / 2));
						drawImage(theImage, (theSize - theImage.width) / 2, (theSize - theImage.height) / 2, theImage.width, theImage.height);
					}
				}
			}
			
			if (appearDuration <= 0) {
				setOpacity(theDiv, theAlpha);
			} else {
				setOpacity(theDiv, 0);
			}

			theRadicals[theRadicals.length] = {"div": theDiv, "alpha": theAlpha, "passage": 0, "duration": theDuration, "appear": appearDuration, "vanish": vanishDuration};
			setTimeout(function() {
				mainBox.removeChild(theDiv);
			}, (theDuration + appearDuration + vanishDuration + 1) * 1000);
		}
	}



	/* クリック時の処理 */
	addEvent(document.getElementById("container"), "click", function(theEvent) {
		if (!theEvent) {	//IE
			theEvent = window.event;
		}
		if (typeof(theEvent.pageX) != "undefined") {
			var mousedownPoint = {"x": theEvent.pageX, "y":theEvent.pageY};
		} else {	//IE
			var mousedownPoint = {"x": theEvent.clientX, "y":theEvent.clientY};
		}
		playmp3.playFile("sounds/sound.mp3");
		addRadical(mousedownPoint["x"], mousedownPoint["y"], 1, 1, Math.floor(Math.random() * 10) + 40,  0.2, 2);
	});
	
	
	
	/* 研究紹介 */
	var boxDisplay = "hidden";	//詳細が表示中かどうか。
	var theBox = document.getElementById("box");		//詳細の表示領域。
	addEvent(document.getElementById("container"), "click", function() {
		if (boxDisplay == "visible") {
			boxDisplay = "animate";
			var theDate = new Date();
			var theTime = theDate.getTime();
			var n = 0;
			var theDuration = 0.5;
			var theInterval = setInterval(function() {
				theDate = new Date();
				n = n + ((theDate.getTime() - theTime) / 1000 / theDuration);
				if (n < 1) {
					setOpacity(theBox, 1 - n);
					theBox.style.top = n * 3 + "px";
				} else {
					setOpacity(theBox, 0);
					theBox.style.visibility = "hidden";
					boxDisplay = "hidden";
					clearInterval(theInterval);
				}
				theTime = theDate.getTime();
			}, 50);
		}
	});

	var titleDiv = document.getElementById("popuptitle");	//自動で出現するタイトル。
	addEvent(titleDiv, "click", function() {
		if (boxDisplay != "hidden") {
			return;
		}
		boxDisplay = "animate";
		
		theBox.style.visibility = "inherit";
		setOpacity(theBox, 0);
		var theDate = new Date();
		var theTime = theDate.getTime();
		var n = 0;
		var theDuration = 0.5;
		var theInterval = setInterval(function() {
			theDate = new Date();
			n = n + ((theDate.getTime() - theTime) / 1000 / theDuration);
			if (n < 1) {
				setOpacity(titleDiv, 1 - n);
				theBox.style.top = (1 - n) * -3 + "px";
				setOpacity(theBox, n);
			} else {
				theBox.style.top = "0";
				setOpacity(theBox, 1);
				titleDiv.style.visibility = "hidden";
				boxDisplay = "visible";
				clearInterval(theInterval);
			}
			theTime = theDate.getTime();
		}, 50);
	});
	
	var theXML;
	getResponse("data.xml", "", "xml", function(theData) {
		theXML = theData;
		setTimeout(setAutoTitle, Math.floor(Math.random() * 3000) + 3000);
	});
	
	function setAutoTitle() {
		/* 詳細表示中は出現しない */
		if (boxDisplay != "hidden") {
			setTimeout(setAutoTitle, 5000);
			return;
		}
		
		/* タイトルテキスト */
		titleDiv.innerHTML = "";
		setOpacity(titleDiv, 1);
		titleDiv.style.visibility = "inherit";
		var titleNode = theXML.getElementsByTagName("title")[Math.floor(Math.random() * theXML.getElementsByTagName("title").length)];
		var theTitle = titleNode.firstChild.nodeValue;
		for (var i = 0; i < theTitle.length; i++) {(function(){
			var theSpan = titleDiv.appendChild(document.createElement("span"));
			theSpan.innerHTML = theTitle.charAt(i);
			setOpacity(theSpan, 0);
			theSpan.style.display = "inline-block";	//IEではインライン要素に透明度を設定できない。
			var theDelay = Math.floor(Math.random() * 2000) + 3000;
			var durationLost = (Math.floor(Math.random() * 1 * 10) / 10);
			setTimeout(function(){
				theRadicals[theRadicals.length] = {"div": theSpan, "alpha": 1, "passage": 0, "duration": 10 - theDelay / 1000 - durationLost, "appear": 2, "vanish": (Math.floor(Math.random() * 1 * 10) / 10) + 0.5 + durationLost};
			}, theDelay);
		})();}
		var theMargin = 120;	//表示領域の端からの最小の余白
		var theLeft = Math.floor(Math.random() * (mainBox.offsetWidth - titleDiv.offsetWidth - theMargin * 2)) + theMargin;
		var theTop = Math.floor(Math.random() * (mainBox.offsetHeight - titleDiv.offsetHeight - theMargin * 2)) + theMargin;
		var theWidth = titleDiv.offsetWidth;
		with (titleDiv.style) {
			left = theLeft + "px";
			top = theTop + "px";
		}
		
		/* 詳細を設定 */
		//タイトル
		while (theTitle.indexOf("\n") != -1) {
			theTitle = theTitle.replace("\n", "<br>");
		}
		document.getElementById("maintitle").innerHTML = theTitle;
		//サブタイトル
		if (titleNode.parentNode.getElementsByTagName("subtitle").length == 1) {
			document.getElementById("subtitle").innerHTML = "-" + titleNode.parentNode.getElementsByTagName("subtitle")[0].firstChild.nodeValue + "-";
		} else {
			document.getElementById("subtitle").innerHTML = "";
		}
		//概要
		var theSummary = titleNode.parentNode.getElementsByTagName("summary")[0].firstChild.nodeValue;
		while (theSummary.indexOf("\n") != -1) {
			theSummary = theSummary.replace("\n", "<br>");
		}
		document.getElementById("summary").innerHTML = theSummary;
		//名前
		document.getElementById("name").innerHTML = titleNode.parentNode.getElementsByTagName("names")[0].getElementsByTagName("name")[0].firstChild.nodeValue;
		for (var i = 1; i < titleNode.parentNode.getElementsByTagName("names")[0].getElementsByTagName("name").length; i++) {
			document.getElementById("name").innerHTML = document.getElementById("name").innerHTML + "&nbsp;" + titleNode.parentNode.getElementsByTagName("names")[0].getElementsByTagName("name")[i].firstChild.nodeValue;
		}

		/* もとから存在する重なる部首の消失 */
		for (var i = 0; i < theRadicals.length; i++) {
			if ((theRadicals[i]["div"].offsetLeft + theRadicals[i]["div"].offsetWidth > theLeft) && (theRadicals[i]["div"].offsetLeft < theLeft + titleDiv.offsetWidth) && (theRadicals[i]["div"].offsetHeight + theRadicals[i]["div"].offsetTop > theTop) && (theRadicals[i]["div"].offsetTop < theTop + titleDiv.offsetHeight)) {
				if (theRadicals[i]["passage"] < theRadicals[i]["duration"] + theRadicals[i]["appear"] - 5) {
					theRadicals[i]["passage"] = theRadicals[i]["duration"] + theRadicals[i]["appear"] - 5;
				}
			}
		}
		
		/* 部首出現 */
		var theDensity = 0.05;	//部首の密度
		for (var i = 0; i < theWidth * theDensity; i++) {
			setTimeout(function() {
				var theX = Math.floor(Math.random() * theWidth) + theLeft;
				var theY = Math.floor(Math.random() * titleDiv.offsetHeight) + theTop;
				var theDuration = 4 - 2 * (i / (theWidth * theDensity));
				addRadical(theX, theY, 3, 1, theDuration,  1, 1);
			}, 2700 * (i / (theWidth * theDensity)));
		}

		setTimeout(setAutoTitle, Math.floor(Math.random() * 5000) + 15000);
	}

	
	
	/* 自動部首出現 */
	function setAuto() {
		var theX = Math.floor(Math.random() * mainBox.offsetWidth);
		var theY = Math.floor(Math.random() * mainBox.offsetHeight);
		addRadical(theX, theY, 1, 1, Math.floor(Math.random() * 10) + 30, 2, 2);
		setTimeout(setAuto, Math.floor(Math.random() * 3000000000 / mainBox.offsetWidth / mainBox.offsetHeight));
	}
	setAuto();
});
	