﻿///////////////////////////////////////////////////////////////////////////////////
// 非同期通信部分については
// Toshirou Takahashi さんのを jslb_ajax_c.js を利用させてもらっています
// http://jsgt.org/mt/01/
// 使用の際には jslb_ajax_c.js を一緒にインクルードしてください

//////////////////////////
//   グローバルなモノ   //
scene_info = new SceneInfo();
action_info = new Array();//memo:ActionInfoの配列

main_window = document.getElementById("main_window");

default_text_layer = "text";// デフォルトのテキスト表示先
script_count = 0;// 現在実行中のスクリプト
text_pointer = 0;// 現在のテキスト読み込み位置
inner_count = 0;// スクリプト内部用のカウンター
action_count = 0;// アクション内部用のカウンター
text_cycle = 3;// 何step毎にテキスト書き出しするか
step_cycle = 10;//Loopのmsec

action_file = "action.xml";// 読み込むアクション定義ファイル

mainLoopId = 0// 別シーン行った時にタイマー止める為

text_wait_flag = false;
click_stop_flag = false;
window_width = 0;
window_height = 0;
///////////////////////////////

//////////////////////////////
// test用                   //
count = 0;

//////////////////////////////

//////////////////////////////////////////////////////////////////////////////////
// class宣言

function SceneInfo(){
	this.layer = new Array();
	this.script = new Array();
}

function ActionInfo(){
	this.name;
	this.script = new Array();
}

function LayerInfo(){
	// XML定義の取得
	this.name = "";
	this.type = "normal";
	this.order = 1;
	this.image = "";
	this.visible = "visible";
	this.fromy = 0;// 画像の表示始点
	this.fromx = 0;// 画像の表示始点
	this.width = 0;// 画像の幅
	this.height = 0;// 画像の高さ
	this.x = 0;// 画像の表示位置
	this.y = 0;// 画像の表示位置
	this.event = null;// レイヤをクリックされた時の飛び先
	//type:image
	this.img_width = 0;// 画像の元サイズ
	this.img_height = 0;// 画像の元サイズ
	this.zoom = 1;
	this.zoom_flag = false;
	this.last_zoom = null;
	//type:text
	this.textcolor = "#000";// テキストカラー
	this.textsize = "12px";// テキストサイズ
	this.bgcolor = "";// 背景色
	this.opacity = "100%";// 不透明度
}

function ScriptInfo(){
	this.type = null;
	this.target = null;
	this.value = null;
	this.name = null; // action name & goto label
	// 以下レイヤ情報
	this.order = null;
	this.image = null;
	this.visible = null;
	this.from = null;// 画像の表示始点("*,*")
	this.size = null;// 画像の幅("*,*")
	this.imgsize = null;// 画像の元幅("*,*")
	this.to = null;// 画像の表示位置("*,*")
	this.textcolor = null;// テキスト色指定
	this.textsize = null;// テキストサイズ指定
	this.bgcolor = null;// 背景色指定
	this.opacity = null;// 不透明度
	this.zoom = null;//画像の倍率
}

//////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////
// 初期化、設定用関数
function readScene(scene_file){
	if(!setMainWindow()){
		return
	}
	reflesh();
	count = 0; // test用
	// メインウィンドウ確認できたら、シーン情報の取得リクエスト
	sendRequest(getSceneInfo, '', 'GET', scene_file,true);
}

function reflesh(){
	var i,j;
	while(scene_info.layer.pop() != null);
	while(scene_info.script.pop() != null);
	while(action_info.pop() != null);
	main_window = document.getElementById("main_window");
	clearInterval(mainLoopId);

	main_window.innerHTML = "";
	main_window.style.width = 0;
	main_window.style.height = 0;
	script_count = 0;
	text_pointer = 0;
	inner_count = 0;
	action_count = 0;
	text_wait_flag = false;
}

function setMainWindow(){
	main_window = document.getElementById("main_window");
	if(main_window){
		if(main_window.style.width == "auto" || main_window.style.height == "auto"){
			alert("main_windowのwidth.heightを指定してください");
			return false;
		}
		window_width = main_window.style.width;
		window_height = main_window.style.height;

	} else {
		alert("main_windowを作成してください");
		return false;
	}
	// イベントのセット
	clearEvent(main_window, getMessage, "click");
	setEvent(main_window, getMessage, "click");
	return true;
}

// イベントハンドラの設定
function setEvent(elem, func, type){
	if(elem.addEventListener){
		elem.addEventListener(type, func, true);
	} else if(elem.attachEvent){
		elem.attachEvent("on" + type, func);
	} else {
		alert("Not supported");
	}
}

// イベントハンドラの解除
function clearEvent(elem, func, type){
	if(elem.removeEventListener){
		elem.removeEventListener(type, func, true);
	} else if(elem.attachEvent){
		elem.detachEvent("on" + type, func);
	} else {
		alert("Not Supported");
	}
}

// シーン情報取得
function getSceneInfo(oj){
	// レスポンスの取得
	var xmlDoc = oj.responseXML; // コールバック関数内でojは受信している
	if(xmlDoc.documentElement.hasChildNodes()){
		var num_of_doc_child = xmlDoc.documentElement.childNodes.length;
		for(var i=0; i < num_of_doc_child; i++){
			var doc_child = xmlDoc.documentElement.childNodes[i];
			switch(doc_child.nodeName){
				case "window":
					getWindowInfo(doc_child);
					break;
				case "layer":
					scene_info.layer.push(getLayerInfo(doc_child));
					break;
				default:
					break;
			}
			if(doc_child.hasChildNodes()){
				switch(doc_child.nodeName){
					case "script":
						getScriptInfo(doc_child);
						break;
					default:
						break;
				}
			}
		}
	} else {
		alert("Don't have child nodes");
	}

	main_window.style.width = window_width;
	main_window.style.height = window_height;

	// アクション情報の取得リクエスト
	sendRequest(getActionInfo, '', 'GET', action_file, true);
	mainLoopId = setInterval('mainLoop()',step_cycle);// 10ms毎にメッセージループ
}


// 全体の設定
function getWindowInfo(doc_child){
	if(doc_child.getAttribute("size") != null){
		tmp_str = doc_child.getAttribute("size");
		tmp_array = tmp_str.split(",",2);
		window_width = convPosition(window_width, tmp_array[0]);
		window_height = convPosition(window_height, tmp_array[1]);
	}
	if(doc_child.getAttribute("step_cycle") != null){
		step_cycle = Number(doc_child.getAttribute("step_cycle"));
	}
	if(doc_child.getAttribute("text_cycle") != null){
		text_cycle = Number(doc_child.getAttribute("text_cycle"));
	}
	if(doc_child.getAttribute("action_file") != null){
		action_file = doc_child.getAttribute("action_file");
	}
}

CommonLayerAttributes = ["order","image","event","opacity","zoom","bgcolor","textcolor","textsize"];

// レイヤ情報の取得
function getLayerInfo(doc_child){
	// LayerInfoに代入
	var layer_data = new LayerInfo();
	var tmp_str;
	var tmp_array;

	if(doc_child.getAttribute("name") != null){
		layer_data.name = doc_child.getAttribute("name");
	} else {
		alert("nameの無いレイヤは作成できません");return;
	}

	layer_data.type = (doc_child.getAttribute("type") != null) ?
											doc_child.getAttribute("type"):
											"normal";

	for(var i=0;i<CommonLayerAttributes.length; i++){
		if(doc_child.getAttribute(CommonLayerAttributes[i]) != null){
			layer_data[CommonLayerAttributes[i]] = doc_child.getAttribute(CommonLayerAttributes[i]);
		}
	}

	if(doc_child.getAttribute("show") != null){
		layer_data.visible = showToVisible(doc_child.getAttribute("show"));
	}

	if(doc_child.getAttribute("from") != null){
		tmp_str = doc_child.getAttribute("from");
		tmp_array = tmp_str.split(",",2);
		layer_data.fromx = convPosition(layer_data.fromx, tmp_array[0]);
		layer_data.fromy = convPosition(layer_data.fromy, tmp_array[1]);
	}

	if(doc_child.getAttribute("imgsize") != null){
		tmp_str = doc_child.getAttribute("imgsize");
		tmp_array = tmp_str.split(",",2);
		layer_data.img_width = convPosition(layer_data.img_width, tmp_array[0]);
		layer_data.img_height = convPosition(layer_data.img_height, tmp_array[1]);
		layer_data.width = layer_data.img_width;
		layer_data.height = layer_data.img_height;
	}

	if(doc_child.getAttribute("size") != null){
		tmp_str = doc_child.getAttribute("size");
		tmp_array = tmp_str.split(",",2);
		layer_data.width = convPosition(layer_data.width, tmp_array[0]);
		layer_data.height = convPosition(layer_data.height, tmp_array[1]);
	}

	if(doc_child.getAttribute("position") != null){
		tmp_str = doc_child.getAttribute("position");
		tmp_array = tmp_str.split(",",2);
		layer_data.x = convPosition(layer_data.x, tmp_array[0], window_width);
		layer_data.y = convPosition(layer_data.y, tmp_array[1], window_height);
	}

	// レイヤ作成
	makeNewLayer(layer_data);
	// レイヤ表示更新
	updateLayer(layer_data);
	return layer_data;
}

// スクリプト情報の取得
function getScriptInfo(doc_child){
	// ScriptInfoに代入
	var num_of_script_child = doc_child.childNodes.length;
	for(var i=0; i < num_of_script_child; i++){
		var script_data = new ScriptInfo();
		var script_child = doc_child.childNodes[i];
		if(script_child.hasChildNodes()){
			switch(script_child.nodeName){
				case "text":
					script_data.type = "text";
					script_data.target = (script_child.getAttribute("target") != null) ?
															script_child.getAttribute("target"):
															default_text_layer;
					script_data.name = (script_child.getAttribute("goto") != null) ?
															script_child.getAttribute("goto"):
															null;
					script_data.textcolor = (script_child.getAttribute("textcolor") != null) ?
															script_child.getAttribute("textcolor"):
															null;
					script_data.textsize = (script_child.getAttribute("textsize") != null) ?
															script_child.getAttribute("textsize"):
															null;
					if(script_child.nodeValue != ""){
						script_data.value = convertScript(script_child.firstChild.nodeValue);
					} else {
						delete script_data;
						continue
					}
					break;

				default:
					delete script_data;
					continue;
			}
		} else {
			switch(script_child.nodeName){
				case "action":
					script_data.type = "action";
					script_data.target = (script_child.getAttribute("target") != null) ?
															script_child.getAttribute("target"):
															null;
					script_data.name = (script_child.getAttribute("name") != null) ?
															script_child.getAttribute("name"):
															null;
					break;
			
				case "#text":
					//テキスト部分
					script_data.type = "text";
					script_data.target = default_text_layer;
					var tmpstr;
					tmpstr = script_child.nodeValue;
					if(tmpstr.replace(/\s/g,"") == ""){
						delete script_data;
						continue;
					} else {
						script_data.value = convertScript(tmpstr.replace(/[\f\n\r\t\u2028\u2029]/g,""));
					}
					break;

				case "wait":
					script_data.type = "wait";
					break;

				case "clear":
					script_data.type = "clear";
					script_data.target = (script_child.getAttribute("target") != null) ?
															script_child.getAttribute("target"):
															default_text_layer;
					break;

				case "sleep":
					script_data.type = "sleep";
					script_data.value = (script_child.getAttribute("time") != null) ?
															script_child.getAttribute("time"):
															0;
					break;

				case "label":
					script_data.type = "label";
					if(script_child.getAttribute("name") != null){
						script_data.name = script_child.getAttribute("name");
					} else {
						delete script_data;
						continue;
					}
					break;

				case "goto":
					script_data.type = "goto";
					if(script_child.getAttribute("name") != null){
						script_data.name = script_child.getAttribute("name");
					} else {
						delete script_data;
						continue;
					}
					break;

				case "stop":
					script_data.type = "stop";
					break;

				case "move":
				case "change":
					script_data = getOperationAttribute(script_child);


					break;

				default:
					delete script_data;
					continue;

			}
		}
		scene_info.script.push(script_data);
	}
}

//////////////////////////////////////////////////////////////////////////////////
// アクション情報の取得
function getActionInfo(oj){
	// レスポンスの取得
	var xmlDoc = oj.responseXML; // コールバック関数内でojは受信している
	if(xmlDoc.documentElement.hasChildNodes()){
		var num_of_doc_child = xmlDoc.documentElement.childNodes.length;
		for(var i=0; i < num_of_doc_child; i++){
			var doc_child = xmlDoc.documentElement.childNodes[i];
			var action_data = new ActionInfo();
			if(doc_child.nodeName == "action"){
				// action情報の取得
				if(doc_child.getAttribute("name") != null){
					action_data.name = doc_child.getAttribute("name");
				} else {
					delete action_data;
					continue;
				}
				if(doc_child.hasChildNodes()){
					var num_of_script_child = doc_child.childNodes.length;
					for(var j=0; j < num_of_script_child; j++){
						// script部の取得
						var script_data = new ScriptInfo();
						var script_child = doc_child.childNodes[j];
							switch(script_child.nodeName){
							case "#text":
								// ゴミは削除
								delete script_data;
								continue;

							case "sleep":
								script_data.type = "sleep";
								script_data.value = (script_child.getAttribute("time") != null) ?
																		script_child.getAttribute("time"):
																		0;
								break;

							case "move":
							case "change":
								script_data = getOperationAttribute(script_child);
								break;

							default:
								delete script_data;
								continue;

						}
						action_data.script.push(script_data);
					}
				}
			} else {
				delete action_data;
				continue;
			}
			action_info.push(action_data);
		}
	} else {
		alert("Don't have child nodes");
	}
}

CommonScriptAttributes = ["target","image","event","imgsize","order","to","from",
						  "size","bgcolor","textcolor","textsize","opacity","zoom"];

function getOperationAttribute(script_child){

	script_data = new ScriptInfo();
	script_data.type = "operation";

	for(var i=0;i<CommonScriptAttributes.length; i++){
		if(script_child.getAttribute(CommonScriptAttributes[i]) != null){
			script_data[CommonScriptAttributes[i]] = script_child.getAttribute(CommonScriptAttributes[i]);
		}
	}
	if(script_child.getAttribute("position") != null){
		// toとpositionではpositionを優先する
		script_data.to = script_child.getAttribute("position");
	}
	if(script_child.getAttribute("show") != null){
		script_data.visible = showToVisible(script_child.getAttribute("show"));
	}
	return script_data;

}

//////////////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////////
// レイヤ関連処理

// 新レイヤ作成
function makeNewLayer(layer_data){
	if(!document.getElementById('layer_' + layer_data.name)){
		if(main_window){
			if(layer_data.type == "image"){
				main_window.innerHTML += (
						'<img id="layer_' + layer_data.name +
						'" onclick="layerEvent(' + "'" + layer_data.name + "'" + ')">');
			} else {
				main_window.innerHTML += (
						'<div id="layer_' + layer_data.name +
						'" onclick="layerEvent(' + "'" + layer_data.name + "'" + ')">' + 
						'</div>');
			}
		}
	}
}

// レイヤ表示更新
function updateLayer(layer_data){
	var target_layer;
	var div_width = Number(0);
	var div_height = Number(0);
	target_layer = getLayer(layer_data.name);

	// 共通部分
	var top = Number(layer_data.y) - Number(layer_data.fromy);
	var left = Number(layer_data.x) - Number(layer_data.fromx);
	// 不透明度の設定(ブラウザで異なる)
	var par = layer_data.opacity.match(/\d+/);

	var new_style;

	new_style = 'z-index: ' + layer_data.order + ';' +
				'position: ' + 'absolute;' + 
				'visibility: ' + layer_data.visible + ';' +
				'top: ' + top + 'px;' + 
				'left: ' + left + 'px;' +
				'filter: ' + 'alpha(opacity=' + par + ');' + 
				'MozOpacity: ' + par/100 + ';' +
				'opacity: ' + par/100 + ';';

	var layer_width = Number(0);
	var layer_height = Number(0);

	// レイヤの種類で分ける処理
	if(layer_data.type == "image"){
		if(target_layer.src.search(layer_data.image) == -1){
			//新たな画像の読み込み
			target_layer.width = layer_data.img_width;
			target_layer.height = layer_data.img_height;
			target_layer.src = layer_data.image;
			if(layer_data.zoom_flag){
				// 画像変更時に、zoomが設定されていなければ1倍に設定
				layer_data.zoom = 1;
				layer_data.last_zoom = 1;
			}
		}
		if(!target_layer.complete){
			// 読み込み終了するまで、ループ
			setTimeout("updateLayerByName('" + layer_data.name+ "')",100);
			return;
		}
		if(!layer_data.zoom_flag){
			target_layer.width = layer_data.img_width * layer_data.zoom;
			target_layer.height = layer_data.img_height * layer_data.zoom;
			layer_width = layer_data.width * layer_data.zoom;
			layer_height = layer_data.height * layer_data.zoom;
			layer_data.last_zoom = layer_data.zoom;
			layer_data.zoom_flag = true;
		} else {
			target_layer.width = layer_data.img_width * layer_data.last_zoom;
			target_layer.height = layer_data.img_height * layer_data.last_zoom;
			layer_width = layer_data.width * layer_data.zoom;
			layer_height = layer_data.height * layer_data.zoom;
		}
	} else {
		new_style += 'background-image: ' + 'url(' + layer_data.image + ');' +
						'background-repeat: ' + "norepeat;" + 
						'background-color: ' + layer_data.bgcolor + ';' + 
						'width: ' + layer_data.width + 'px;' + 
						'height: ' + layer_data.height + 'px;' +
						'color: ' + layer_data.textcolor + ';' +
						'font-size: ' + layer_data.textsize + ';' ;

		target_layer.innerHTML = "";
		layer_width = layer_data.width;
		layer_height = layer_data.height;
	}
	{
	// はみ出た分を切り取る (上、左方向)
	// clip::rect(上端,右端,下端,左端)で表示部分を調整
		
		//top
		var tp = Number(layer_data.fromy);
		if(layer_data.y < 0){ tp -= Number(layer_data.y);}
		//right
		div_width = Number(window_width) - Number(left);
		if(div_width < 0){div_width = 0;}
		var rp = (div_width > layer_width) ? Number(layer_width) : (Number(layer_data.fromx)+ Number(div_width));
		//bottom
		div_height = Number(window_height) - Number(top);
		if(div_height < 0){div_height = 0;}
		var bp = (div_height > layer_height) ? Number(layer_height) : (Number(layer_data.fromy) + Number(div_height));
		//left
		var lp = Number(layer_data.fromx);
		if(layer_data.x < 0){ lp -= Number(layer_data.x);}

		new_style += 'clip: ' + 'rect(' + tp + ',' + rp + ',' + bp + ',' + lp + ');' ;
	}

	if(typeof(target_layer.style.cssText) != 'undefined'){
		target_layer.style.cssText = new_style;
	} else {
		target_layer.setAttribute('style',new_style);
	}

}

function updateLayerByName(layer_name){
	//レイヤ名からupdateLayerを呼びなおす
	for(var i=0; i<scene_info.layer.length; i++){
		if(scene_info.layer[i].name == layer_name){
			updateLayer(scene_info.layer[i]);
		}
	}
}


// レイヤ実体の取得
// memo:LayerInfoに、要素を直接持たせたかったけど、参照の仕方わかんない…
function getLayer(name){
	return document.getElementById('layer_' + name);
}

//////////////////////////////////////////////////////////////////////////////////


//////////////////////////////////////////////////////////////////////////////////
// イベント関連処理
// メインループ
function mainLoop(){

	if(script_count >= scene_info.script.length){
		// シーンファイルの最後まで到達したら終わり
		return false;
	} 

	// スクリプトの読み込み
	readScript(scene_info.script[script_count]);
}

// クリックされた
function getMessage(e){
	// IE の場合イベントが引数として渡されていないので代入
	if(navigator.appName.indexOf("NetScape")){
		e = window.event;
	}

	if(script_count >= scene_info.script.length){
		// overしていたら何もしない
		return;
	}

	if(click_stop_flag){
		// click禁止なら何もしない
		return;
	}

	// テキスト停止していたら解除して次のステップへ
	if(text_wait_flag){
		text_wait_flag = false;
		text_pointer = 0;
		script_count++;
	} else {
		var script = scene_info.script[script_count];
		switch(script.type){
			case "text":
				//強制テキスト書き出し
				addString(script,true);
				text_pointer = 0;
				script_count++;
				break;

			default:
				break;
		}
	}

}

//////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////
// ステップ毎の処理

// script解釈
function readScript(script_data){

	if(script_data.type == "stop"){
		// stop中はクリック禁止
		click_stop_flag=true;
		return;
	} else {
		click_stop_flag=false;
	}

	switch(script_data.type){
		case "text":
			if(putString(script_data)){
				script_count++;
			}
			break;

		case "operation":
			layerOperation(script_data);
			script_count++;
			break;

		case "action":
			if(layerAction(script_data)){
				script_count++;
			}
			break;

		case "wait":
			text_wait_flag = true;
			break;

		case "clear":
			clearString(script_data);
			script_count++;
			break;

		case "sleep":
			if(sleep(script_data.value)){
				script_count++;
			}
			break;

		case "goto":
			var index = getLabelIndex(script_data.name);
			if(index == -1){
				alert("存在しないラベルを指定されたので無視します");
				script_count++;
			} else {
				script_count = index;
			}
			break;

		default:
			script_count++;
			break;
	}
}

// Textの表示
function putString(script){

	if(text_wait_flag){
		return false;
	}
	var printstr = "";

	if(text_cycle == 0){
		// cycleゼロはnowait
		addString(script,true);
		text_pointer = 0;
		return true;
	}

	if(inner_count < text_cycle){
		inner_count++;
		return false;
	} else {
		inner_count = 0;
	}

	if(text_pointer<script.value.length){
		addString(script)
		text_pointer++;
	} else {
		text_pointer=0;
		return true;
	}
	return false;

}

function convertScript(str){
	var word_tmp = "";
	var ret = str;
	// まずは特殊文字の置き換え
	var words = ret.match( /\\[^\\]*;/g );
	if(words != null){
		for(var i=0; i<words.length; i++){
			word_tmp = words[i].replace("\\","<");
			word_tmp = word_tmp.replace(";",">");
			ret = ret.replace(words[i],word_tmp);
		}
	}
	// 次に\.の置き換え
	words = ret.match( /\\./g );
	if(words != null){
		for(var i=0; i<words.length; i++){
			word_tmp = words[i].replace("\\","<");
			word_tmp += ">";
			ret = ret.replace(words[i],word_tmp);
		}
	}
	return ret;
}

function convertHTML(str){
	//<.*>の中身を必要な形に戻す
	var ret;
	var word_tmp = "";
	var ret = str;
	var words = ret.match( /<[^<]*>/g );
	if(words != null){
		for(var i=0; i<words.length; i++){
			// <>外してから中の文字列によって置き換え
			word_tmp = words[i].replace("<","");
			word_tmp = word_tmp.replace(">","");
			word_tmp = convertSpChar(word_tmp);
			ret = ret.replace(words[i],word_tmp);
		}
	}
	return ret;
}

function convertSpChar(str){
	var ret = "";
	if(str.length == 1){
		switch(str){
			case "n":
				ret = "<br>";
				break;

			case "\\":
				ret = "&yen;";
				break;

			default:
				ret = str;
				break;
		}
	} else {
		ret = "&" + str + ";";
	}
	return ret;
}

function showToVisible(str){
	var ret = "visible";
	if(str == "off" || str == "hidden"){
		ret = "hidden";
	}
	return ret;
}


function addString(script,finish_flag){

	var first_flag = false;
	var new_value = script.value.substr(0,text_pointer+1);
	if(text_pointer == 0){first_flag = true;}
	if(new_value.charAt(text_pointer) == "<"){
		while(new_value.charAt(text_pointer) != ">"){
				text_pointer++;
				new_value = script.value.substring(0, text_pointer+1);
		}
	}
	if(finish_flag != null){
		if(finish_flag == true){
			new_value = script.value.substr(0,script.value.length);
		}
	}
	var print_str = convertHTML(new_value);
	if(first_flag){
		//初回書き出し時に必要ならspanタグ入れて書き出し終わり
		var func = "";
		var text_color = "";
		var text_size = "";
		if(script.name != null){
			func = 'onclick="gotoLabel(' + "'" + script.name + "'" + ')" ';
		}
		if(script.textcolor != null){
			text_color = "color:" + script.textcolor + ";";
		}
		if(script.textsize != null){
			text_size = "font-size:" + script.textsize + ";";
		}
		getLayer(script.target).innerHTML += ("<span " + func + ' style="' + text_color + text_size + '">' + print_str + "</span>");
		return;
	}
	// 最後にvalueと一致したものを1文字分増やして書き換える
	var inner_str = getLayer(script.target).innerHTML;
	// IEとFireFoxでinnerHTML通した時に、勝手にそれぞれ
	// 大文字、小文字にそろえられてしまい、lastIndexOfが使えない
	var last_index = 0;
	var index_tmp = 0;
	var index_end = 0;
	var tmp_str = inner_str;
	var index_count = 0;
	while(index_tmp != -1){
		index_tmp = tmp_str.search(/<span[^<]*>/i);
		if(index_tmp != -1){
			tmp_str = tmp_str.substr(index_tmp);
			index_end = (tmp_str.search(">") + 1);
			tmp_str = tmp_str.substr(index_end);
			last_index += (index_tmp + index_end);
		}
	}
	//innerHTMLだと&*;は変換済みで返ってきてしまうので、一致しなくなってしまうため
	//一文字ずつ置き換えるというよりは、最後のSPANの中身を書き換える
	var left_str = inner_str.substr(0,last_index);
	var right_str = print_str + "</span>";
	getLayer(script.target).innerHTML = (left_str + right_str);
}

// Textのクリア
function clearString(script){
	getLayer(script.target).innerHTML = "";
	text_pointer=0;
}

// Changeで指定された属性の書き換え
function layerOperation(script){
	var target_layer;
	var tmp_str;
	var tmp_array;

	target_layer = getTargetLayer(script.target);
	if(target_layer == null){ return; } 

	if(script.order != null){target_layer.order = script.order;}
	if(script.image != null){target_layer.image = script.image;}
	if(script.name != null){target_layer.event = script.name;}else{target_layer.event = null;}
	if(script.visible != null){target_layer.visible = script.visible;}
	if(script.opacity != null){target_layer.opacity = script.opacity;}
	if(script.zoom != null){target_layer.zoom = script.zoom; target_layer.zoom_flag = false;}
	if(script.bgcolor != null){target_layer.bgcolor = script.bgcolor;}
	if(script.textcolor != null){target_layer.textcolor = script.textcolor;}
	if(script.textsize != null){target_layer.textsize = script.textsize;}
	if(script.from != null){
		tmp_str = script.from;
		tmp_array = tmp_str.split(",",2);
		target_layer.fromx = convPosition(target_layer.fromx, tmp_array[0]);
		target_layer.fromy = convPosition(target_layer.fromy, tmp_array[1]);
	}
	if(script.imgsize != null){
		tmp_str = script.imgsize;
		tmp_array = tmp_str.split(",",2);
		target_layer.img_width = convPosition(target_layer.width, tmp_array[0]);
		target_layer.img_height = convPosition(target_layer.height, tmp_array[1]);
		target_layer.width = target_layer.img_width;
		target_layer.height = target_layer.img_height;
	}
	if(script.size != null){
		tmp_str = script.size;
		tmp_array = tmp_str.split(",",2);
		target_layer.width = convPosition(target_layer.width, tmp_array[0]);
		target_layer.height = convPosition(target_layer.height, tmp_array[1]);
	}
	if(script.to != null){
		tmp_str = script.to;
		tmp_array = tmp_str.split(",",2);
		target_layer.x = convPosition(target_layer.x, tmp_array[0], window_width);
		target_layer.y = convPosition(target_layer.y, tmp_array[1], window_height);
	}

	updateLayer(target_layer);
	
}

// 座標への変換
function convPosition(num, str, max){
	var ret_num = 0;
	var last_char = str.slice(str.length-1);
	var first_char = str.substr(0,1);
	var num_str_tmp = str.match(/\d+/);//数値の取り出し
	var num_str;
	if(last_char == "%" && max != null){
		// %指定かつ、最大値が引数で与えられていれば、割合を数値に変換
		num_str = Number(max) * Number(num_str_tmp)/100;
	} else {
		num_str = Number(num_str_tmp);
	}
	switch(first_char){
		case '+':
			ret_num = Number(num) + Number(num_str);
			break;
		case '-':
			ret_num = Number(num) - Number(num_str);
			break;
		case '*':
			ret_num = Number(num);
			break;
		default:
			ret_num = Number(num_str);
			break;
	}
	return ret_num;
}

// ターゲットレイヤ情報の取得
function getTargetLayer(target_name){
	for(var i=0; i<scene_info.layer.length; i++){
		if(scene_info.layer[i].name == target_name){
			return scene_info.layer[i];
		}
	}
	return null;
}

// sleep
function sleep(sleep_step){
	if(inner_count < sleep_step){
		inner_count++;
		return false;
	} else {
		inner_count = 0;
		return true;
	}
}


// action
function layerAction(script){
	var action_index = getActionIndex(script.name);
	if(action_index == -1){ 
		alert("存在しないactionを指定されたので無視します");
		action_count = 0;
		return true;
	}
	if(action_count < action_info[action_index].script.length){
		var inner_script = action_info[action_index].script[action_count];
		switch(inner_script.type){
			case "operation":
				if(script.target != null){
					inner_script.target = script.target;
				}
				layerOperation(inner_script);
				action_count++;
				break;

			case "sleep":
				if(sleep(inner_script.value)){
					action_count++;
				}
				break;

			default:
				action_count++;
				break;
		}
		return false;
	} else {
		action_count = 0;
		return true;
	}
}

function getActionIndex(name){
	for(var i=0;i<action_info.length;i++){
		if(action_info[i].name == name){
			return i;
		}
	}
	return -1;
}

function getLabelIndex(name){
	for(var i=0; i<scene_info.script.length; i++){
		if(scene_info.script[i].type == "label"){
			if(scene_info.script[i].name == name){
				return i;
			}
		}
	}
	return -1;
}

function gotoLabel(name){
	var index = getLabelIndex(name);
	if(index == -1){
		alert("存在しないラベルを指定されたので無視します");
		script_count++;
	} else {
		script_count = index;
	}
}

function layerEvent(layer_name){
	var layer = getTargetLayer(layer_name);
	var index = -1;
	if(layer.event != null){
		index = getLabelIndex(layer.event);
	}
	if(index != -1){
		script_count = index;
	}
}
