
////////////////////////////////
///// NOA へ問い合わせて得る値 /////

function parent(){
	// window.opener が NOA なら NOA を、そうでないなら null を返す
    if (window.opener && (window.opener.name == "noa")){
        return window.opener;
    } else if (window.opener && (window.opener.name == "tools")){
        return window.top.noa;
    } else if (window.opener && (window.top.noa)){
        return window.top.noa;
    } else {
        _initDebug(true); //##
        _debug("特定の カルテID は指定されていません");
        return null;
    }
}

function patientId(){
	if (parent()){
        var type = parent().noaType();
		return (type && (type == "NOA8G")) ? parent().patient_id() : parent().patientId();
	} else {
		return "";
    }
}

function anotherId(){
	if (parent()){
		var aid = parent().valueForTag("PatientTable.anotherId");
		return (aid) ? aid : "";
	} else
		return "";
}

function patientName(){
	if (parent() && patientId())
		return parent().valueForTag("NameSection.patientKanjiName");
	else 
		return "";
}

function owner(){
	if (parent())
		return parent().owner();
	else
		return "";
}

///// NOA へ問い合わせて得る値 /////
////////////////////////////////


var _year;
function setYear(yy){
	_year = yy;
}
function year(){
	// 現在選択されている年を返す
	return _year;
}

var _month;
function setMonth(mm){
	_month = mm;
}
function month(){
	// 現在選択されている月を返す
	return _month;
}

var _day;
function setDay(dd){
	_day = dd;
}
function day(){
	// 現在選択されている日を返す
	return _day;
}

var _week;
function setWeek(w){
	_week = w;
}
function week(){
	// 現在選択されている週を返す
	return _week;
}

function isConsultTime(hour, min){
	// hour min が診療時間内なら true を返す
	var time = hour * 100 + min * 1;
	var val = hospitalInfoForKey('診療時間');
    if (val){
        var array = val.split("^");
        for (num in array){
            // 診療時間帯内であれば true を返す
            var st = trim(array[num]);
            var ary = st.split(",");
            
            // array[0] は未使用
            var week = ary[1];
            var begin = ary[2] * 1;
            var end = ary[3] * 1;
            var zone = ary[4];
            if (week == '日') continue;
            if (zone != '時間内') continue;
            if ((begin <= time) && (time < end)) return 1;
        }
    }
	return 0;
}

var _records;
function setRecords(array){
	// [{patientId(10128401)name(伊藤 純子)entryDate(2010-02-06 10:30:00)}
	_records = array;
}
function addRecords(patientId, anotherId, patientName, entryDate){
	// _records に pid に相当するオブジェクトを上書き
	for(var i=0,ct=_records.length; i < ct; i++){
		var obj = _records[i];
		var pid = obj.patientId;
		if (pid == patientId){
			obj.anotherId = anotherId;
			obj.name = patientName;
			obj.entryDate = entryDate;
			return;
		}
	}
	var obj = new Object();
	obj.patientId = patientId;
	obj.anotherId = anotherId;
	obj.name = patientName;
	obj.entryDate = entryDate;
	_records.push(obj);
}
function removeRecordsForPatientId(patientId){
	// _records から pid に相当するオブジェクトを削除
	for(var i=0,ct=_records.length; i < ct; i++){
		var obj = _records[i];
		var pid = obj.patientId;
		if (pid == patientId){
			_records.splice(i, 1);
			return;
		}
	}
}
function records(){
	return _records;
}
function patientForEntryDate(name, date){
	// date に受診予定の患者オブジェクトを返す
	for(var i=0,ct=_records.length; i < ct; i++){
		var obj = _records[i];
		if ((obj.entryDate == date) && (obj.name == name))
			return obj;
	}
	return null;
}

var _selectedDate;
function setSelectedDate(val){
	_selectedDate = val;
}
function selectedDate(){
	return _selectedDate;
}

var _memoItems;
function setMemoItems(array){
	// obj="[{menu=freq},{menu=freq},,,]" 形式
	_memoItems = new Array();
	for (menuItem in array){
		//var freq = array[menuItem];
		_memoItems.push(menuItem);
	}
}
function memoItems(){
	// 予定項目のリストの配列
	return _memoItems;
}
function addMemoItems(val){
	_memoItems.push(val);
}
function removeMemoItem(val){
	// _memoItems から val を削除
	for (var i=0,ct=_memoItems.length; i < ct; i++){
		var item = _memoItems[i];
		if (item == val){
			_memoItems.splice(i, 1);
			return;
		}
	}
}

var _history;
function setHistory(array){
	// 受診予定日 "2010-04-12" の配列
	_history = array;
}
function hasHistory(year, month, day){
	// この年月日に受診予定者があるかどうかを返す
	for (date in _history){
		var array = date.split("-");
		var yy = array[0] * 1;
		var mm = array[1] * 1;
		var dd = array[2] * 1;
		if ((yy == year) && (mm == month) && (dd == day))
			return true;
	}
	return false;
}

function years(){
	// 西暦年の配列を２０年分返す
	var array = new Array();
	for (var i=0; i < 20; i++){
		array.push(2010 + i);
	}
	return array;
}
function months(){
	// 月の配列を返す
	var array = new Array();
	for (var i=1; i <= 12; i++){
		array.push(i);
	}
	return array;
}
function days(){
	// 日の配列を返す
	var array = new Array();
	for (var i=1; i <= 31; i++){
		array.push(i);
	}
	return array;
}
function hours(){
	// 時刻の配列を返す
	var array = new Array();
	for (var i=0; i < 24; i++){
		array.push(i);
	}
	return array;
}
function minutes(){
	// 分の配列を返す
	var array = new Array();
	for (var i=0; i < 60; i += minutesInterval()){
		array.push(i);
	}
	return array;
}

var _interval;
function setMinutesInterval(val){
	_interval = (val) ? val * 1 : 10;
}
function minutesInterval(){
	// 分単位による予約枠の幅を返す
	// この分数の幅で予約枠が設定される
	return _interval;
}

var _holidays;
function setHolidays(val){
	// _holidays = "1/2改行1/3" 形式 -- 区切りは改行
	if (val){
		val = trim(val);
		var array = val.split("\n");
		_holidays = array;
	} else
		_holidays = new Array();
}
function holidays(){
	return _holidays;
}

var _comment1;
var _comment2;
function setComment1(val){
	_comment1 = val;
}
function comment1(){
	return _comment1;
}
function setComment2(val){
	_comment2 = val;
}
function comment2(){
	return _comment2;
}

var _hospitalInfo;
function setHospitalInfo(array){
	_hospitalInfo = array;
}
function hospitalInfoForKey(key){
	return _hospitalInfo[key];
}

var _userInfo;
function setUserInfo(array){
	_userInfo = array;
}
function userNameForLoginName(name){
	for (num in _userInfo){
		var obj = _userInfo[num];
		if (obj.loginName == name)
			return obj.kanjiName;
	}
	return "";
}
function userKanjiNames(){
	var array = new Array();
	for (num in _userInfo){
		var obj = _userInfo[num];
		array.push(obj.kanjiName);
	}
	return array;
}

///////////////////////////
/// Ajax による処理 /////////

function gotBooking(){
	if ((xmlHttpObject.readyState == 4) && (xmlHttpObject.status == 200)){
		var value = xmlHttpObject.responseText;
		//alert("=== gotBooking ===\n"+value); //##
		var array = value.split("<SEPARATOR>");
		if (array.length > 1){
			var ary = eval('(' + array[1] + ')');
			//alert(encodeObject(ary)); //##
            
			setRecords(ary);
			showBookingMatrix();
		} else
			alert("この日の予約はありません");
	} 
}
function getBooking(yy, mm, dd, w){
	// yy, mm, dd の予約患者をサーバへ照会
	setYear(yy);
	setMonth(mm);
	setDay(dd);
	setWeek(w);
	
	xmlHttpObject = createXMLHttpRequest(gotBooking);
	if (xmlHttpObject){ // GETパラメータ付きでリクエスト送信
		// サーバとの約束事
		var array = new Array();
		array["year"] = yy;
		array["month"] = mm;
		array["day"] = dd;
		
		//_receiver = receiver; // 結果を受け付けるメソッドを記憶
		// FRONT など他のアプリからも使えるよう server.php はフルパス指定
		var st = "./server.php?command=GET_BOOKING"
		+ "&value=" + encodeObject(array);
		//alert(st);
		xmlHttpObject.open("GET", encodeURI(st), true);
		xmlHttpObject.send(null);
	}
}

function removedBooking(answer){
	if ((xmlHttpObject.readyState == 4) && (xmlHttpObject.status == 200)){
		var value = xmlHttpObject.responseText;
		//alert("=== removedBooking ===\n"+value); //##
		var array = value.split("<SEPARATOR>");
		if (array.length > 1){
			if (array.length > 1){
				var ary = eval('(' + array[1] + ')');
				//alert(encodeObject(ary)); //##
				setRecords(ary);
				showBookingMatrix();
				closeConfirm();
			}
		} 
	}
}
function removeBooking(){
	// 予約を削除
	var patientId = document.getElementById("ed_pid").value;
	if (patientId.length == 0){
		alert("カルテID が入力されていません");
		return;
	}
    
	if (confirm(patientId + " の予約を削除していいですか")){
		xmlHttpObject = createXMLHttpRequest(removedBooking);
		if (xmlHttpObject){ // GETパラメータ付きでリクエスト送信
			var entrydate = document.getElementById("ed_entrydate").value;
			
			// サーバとの約束事
			var array = new Array();
			array["patientId"] = patientId;
			array["entryDate"] = entrydate;
			
			// records() から patientId 相当オブジェクトを削除
			removeRecordsForPatientId(patientId);
			
			//_receiver = receiver; // 結果を受け付けるメソッドを記憶
			// FRONT など他のアプリからも使えるよう server.php はフルパス指定
			var st = "./server.php?command=REMOVE_BOOKING"
			+ "&value=" + encodeObject(array);
			//alert(st); return; //##
			xmlHttpObject.open("GET", encodeURI(st), true);
			xmlHttpObject.send(null);
		}
	}
}

function savedBooking(answer){
	if ((xmlHttpObject.readyState == 4) && (xmlHttpObject.status == 200)){
		var value = xmlHttpObject.responseText;
		//alert("=== savedBooking ===\n"+value); //##
		var array = value.split("<SEPARATOR>");
		if (array.length > 1){
			if (array.length > 1){
				var ary = eval('(' + array[1] + ')');
				//alert(encodeObject(ary)); //##
				setRecords(ary);
				showBookingMatrix();
				closeConfirm();
			}
		} 
	}
}
function saveBooking(){
	// 変更された予約日をサーバへ記録
	xmlHttpObject = createXMLHttpRequest(savedBooking);
	if (xmlHttpObject){ // GETパラメータ付きでリクエスト送信
		var pid = document.getElementById("ed_pid").value;
		var aid = document.getElementById("ed_anotherId").innerHTML;
		var name = document.getElementById("ed_patientName").innerHTML;
		var entrydate = document.getElementById("ed_entrydate").value;
		var date = dateOfDateTime(selectedDate());
		var hour = document.getElementById("ed_hour").value;
		var min = document.getElementById("ed_min").value;
		var newDate = date+" "+hour+":"+min + ":00";
		var memo = document.getElementById("ed_memo").value;
		
		// patientId が実態なので records() に格納
		addRecords(pid, aid, name, newDate);

		// サーバとの約束事
		var array = new Array();
		array["patientId"] = pid; //patientId();
		array["anotherId"] = aid; //anotherId
		array["name"] = name; //patientName();
		array["entryDate"] = entrydate;
		array["newEntryDate"] = newDate;
		array["plan"] = memo;
		
		//_receiver = receiver; // 結果を受け付けるメソッドを記憶
		// FRONT など他のアプリからも使えるよう server.php はフルパス指定
		var st = "./server.php?command=CHANGE_BOOKING"
		+ "&value=" + encodeObject(array);
		//alert(st); return; //##
		xmlHttpObject.open("GET", encodeURI(st), true);
		xmlHttpObject.send(null);
	}
}

function gotPreference(){
	if ((xmlHttpObject.readyState == 4) && (xmlHttpObject.status == 200)){
		var value = xmlHttpObject.responseText;
		//alert("=== gotPreference ===\n"+value); //##
		var array = value.split("<SEPARATOR>");
		if (array.length > 1){
			if (array.length > 1){
				var objct = eval('(' + array[1] + ')');
				if (objct){
                    //alert("gotPreference->"+encodeObject(objct)); //##
                    
					// メモ項目ポップアップを記憶
					// [{menu=freq},{menu=freq},,,]
                    setMemoItems(objct.planMenu);

					// interval(5)
					if (objct.preference){
						var obj = decodeObject(objct.preference);
						setMinutesInterval(obj.interval);
						setHolidays(obj.holiday);
					} else {
						setMinutesInterval(5);
						setHolidays("1/1\n1/2\n1/3");
					}
					
					// 予約票のコメントを記憶
					if (objct.comment){
						var obj = decodeObject(objct.comment);
						setComment1(obj.comment1);
						setComment2(obj.comment2);
					} else {
						setComment1("予約時間に来院できない場合はご連絡ください");
						setComment2("日曜・祝日：休診");
					}
					
					// hospitalInfo を記憶
					setHospitalInfo(objct.hospitalInfo);
					
					// userInfo を記憶
					setUserInfo(objct.userInfo);
				}
				
				// カレンダーを表示
				var date = new Date();
				var yy = date.getYear();
				if (yy < 2000) { yy += 1900; }
				var mm = date.getMonth() + 1;
				getCalendars(yy, mm);
			}
		} 
	}
}
function getPreference(){
	// 初期設定をサーバへリクエスト
	xmlHttpObject = createXMLHttpRequest(gotPreference);
	if (xmlHttpObject){ // GETパラメータ付きでリクエスト送信
		// FRONT など他のアプリからも使えるよう server.php はフルパス指定
		var array = new Array();
		array['hospitalId'] = window.opener.hospitalId();
		array['owner'] = owner();
		array['groupCode'] = "doctor"; // ドクターのリストのみをリクエスト
		var st = "./server.php?command=GET_BOOKING_PREFERENCE"
		+ "&value=" + encodeObject(array);
        
		xmlHttpObject.open("GET", encodeURI(st), true);
		xmlHttpObject.send(null);
	}
}

function savedPreference(){
	if ((xmlHttpObject.readyState == 4) && (xmlHttpObject.status == 200)){
		var value = xmlHttpObject.responseText;
		//alert("=== savedPreference ===\n"+value); //##
		var array = value.split("<SEPARATOR>");
		if (array.length > 1){
			if (array.length > 1){
				var obj = decodeObject(array[1]);
				//alert(encodeObject(obj)); //##
				setMinutesInterval(obj.interval);
				setHolidays(obj.holiday);

				closeConfirm();

				// 現在の年月日のマトリックスを再表示
				getBooking(year(),month(),day(),week());
			}
		} 
	}
}
function savePreference(){
	// 初期設定をサーバへ保存
	xmlHttpObject = createXMLHttpRequest(savedPreference);
	if (xmlHttpObject){ // GETパラメータ付きでリクエスト送信
		// サーバとの約束事
		var array = new Array();
		array['interval'] = document.getElementById("pr_min").value;
		array['holiday'] = document.getElementById("pr_holiday").value;
		
		// FRONT など他のアプリからも使えるよう server.php はフルパス指定
		var st = "./server.php?command=PUT_BOOKING_PREFERENCE"
		+ "&owner=" + owner()
		+ "&value=" + encodeObject(array);
		//alert(st); //return; //##
		xmlHttpObject.open("GET", encodeURI(st), true);
		xmlHttpObject.send(null);
	}
}

function gotPatients(){
	if ((xmlHttpObject.readyState == 4) && (xmlHttpObject.status == 200)){
		var value = xmlHttpObject.responseText;
		//alert("=== gotPatients ===\n"+value); //##
		var array = value.split("<SEPARATOR>");
		if (array.length > 1){
			var objct = eval('(' + array[1] + ')');
			if (objct){
				showPatientList(objct);
			}
		} 
	}
}
function searchPatient(){
	// 患者を検索
	var patientId = document.getElementById("ed_pid").value;
	if (patientId.length > 0){
		var ch = patientId.charAt(0);
		var array = patientId.split("/");
		if (array.length > 2){ // 生年月日 "s17/3/23","1942/3/23" 形式
			var yst = array[0];
			var yy = yst * 1;
			var mm = array[1] * 1;
			mm = (mm < 10) ? "0" + mm : mm;
			var dd = array[2] * 1;
			dd = (dd < 10) ? "0" + dd : dd;
			var nengou = yst.charAt(0);
			if ((nengou < '0') || ('9' < nengou)){
				// "s17/3/23" 形式の場合
				var warekiYear = yst.substr(1) * 1;
				if (isSame(nengou, "h"))
					yy = warekiYear + 1988;
				else if (isSame(nengou, "s"))
					yy = warekiYear + 1925;
				else if (isSame(nengou, "t"))
					yy = warekiYear + 1911;
				else if (isSame(nengou, "m"))
					yy = warekiYear + 1867;
			}
			if (yy < 1000){
				alert("西暦の入力間違い: " + patientId);
				return;
			}
			mode = "id";
			patientId = "" + mm + dd + (yy % 100);
		} else if (('0' <= ch) && (ch <='9')){
			mode = "id";
		} else if (('a' <= ch) && (ch <='z'))
			var mode = "kana";
		else 
			var mode = "kanji";
		
		// serchKey に一致する患者リストを返す
		// 検索キーにマッチしたカルテのリストを表示
		xmlHttpObject = createXMLHttpRequest(gotPatients);
		if (xmlHttpObject){ // GETパラメータ付きでリクエスト送信
			var array = new Array();
			array["key"] = mode;
			array["val"] = patientId;
			
			var st = "/NOA/server.php?command=GET_PATIENTS"
			+"&value=" + encodeObject(array);
			//alert("searchPatient ====\n"+st); //return; //##
			xmlHttpObject.open("GET", encodeURI(st), true);
			xmlHttpObject.send(null);
		}
	}
}

function changedMemo(){
	if ((xmlHttpObject.readyState == 4) && (xmlHttpObject.status == 200)){
		var value = xmlHttpObject.responseText;
		//alert("=== changedMemo ===\n"+value); //##
		var array = value.split("<SEPARATOR>");
		if (array.length > 1){
			var objct = eval('(' + array[1] + ')');
			if (objct){
				//alert("changedMemo ===\n"+encodeObject(objct)); //##
				// メモ項目ポップアップを記憶
				var records = new Array();
				for (title in objct){
					if (isSame(title, "menuAction")) continue;
					if (isSame(title, "menuType")) continue;
					if (isSame(title, "fieldType")) continue;
					
					var ary = objct[title];
					var freq = ary[3];
					records[title] = freq;
				}
				setMemoItems(records);
				
				// メモ・ポップアップを再表示
				showMemoPopup(); // メモ・ポップアップを再表示
			}
		} 
	}
}
function addMemo(item){
	// 実施予定ポップアップに item を追加
	xmlHttpObject = createXMLHttpRequest(changedMemo);
	if (xmlHttpObject){ // GETパラメータ付きでリクエスト送信
		// すでに同じメニューアイテムが存在すれば頻度をインクリメント
		var array = new Array();
		array["owner"] = owner();
		array["tag"] = "FrontTable.plan";
		array["menuItem"] = item;
		array["public"] = "1";
		array["freq"] = "0";
		//array["menuAction"] = action;
		//array["val"] = encodeSTRING(value);
		
		var st = "/NOA/server.php?command=PUT_MENU"
		+ "&value=" + encodeObject(array);
		//alert("NRPutMenu ==\n"+st); return;//===
		xmlHttpObject.open("GET", encodeURI(st), true);
		xmlHttpObject.send(null);
	}
}
function removeMemo(){
	// メモ項目を削除
	var item = document.getElementById("ed_memo_popup").value;
	if (confirm("ポップアップメニューから「"+item+"」を削除していいですか")){
		//xmlHttpObject = createXMLHttpRequest(NR_debug);
		xmlHttpObject = createXMLHttpRequest(changedMemo);
		if (xmlHttpObject){ // GETパラメータ付きでリクエスト送信
			var array = new Array();
			array["owner"] = owner();
			array["tag"] = "FrontTable.plan";
			array["menuItem"] = item;
			
			var st = "/NOA/server.php?command=REMOVE_MENU"
			+ "&value=" + encodeObject(array);
			//alert("removeMemo ==\n"+st); return;//===
			xmlHttpObject.open("GET", encodeURI(st), true);
			xmlHttpObject.send(null);
		}
	}
}

function savedLayout(){
	if ((xmlHttpObject.readyState == 4) && (xmlHttpObject.status == 200)){
		var value = xmlHttpObject.responseText;
		//alert("=== savedPreference ===\n"+value); //##
		alert("予約票レイアウトを保存しました");
		closeConfirm();
	}
}
function saveLayout(){
	// 予約票のレイアウトを保存
	xmlHttpObject = createXMLHttpRequest(savedLayout);
	if (xmlHttpObject){ // GETパラメータ付きでリクエスト送信
		// サーバとの約束事
		var array = new Array();
		array['comment1'] 
			= document.getElementById("pr_comment1").value;
		array['comment2'] 
			= document.getElementById("pr_comment2").value;
		
		// FRONT など他のアプリからも使えるよう server.php はフルパス指定
		var st = "./server.php?command=PUT_BOOKING_COMMENT"
		+ "&owner=" + owner()
		+ "&value=" + encodeObject(array);
		//alert(st); //return; //##
		xmlHttpObject.open("GET", encodeURI(st), true);
		xmlHttpObject.send(null);
	}
}

function gotCalendars(){
	if ((xmlHttpObject.readyState == 4) && (xmlHttpObject.status == 200)){
		var value = xmlHttpObject.responseText;
		//alert("=== gotCalendars ===\n"+value); //##
		var array = value.split("<SEPARATOR>");
		if (array.length > 1){
			var obj = eval('(' + array[1] + ')');
			if (obj){
				//alert("gotCalendars ===\n"+encodeObject(obj)); //##
                
				var year = obj.year;
				var month = obj.month;
				var history = obj.history;
				setHistory(history);

				// カレンダーを表示
				showCalendars(year, month);
			}
		} 
	}
}
function getCalendars(yy, mm){
	// カレンダーを３連装で表示するに当たり予約状況を問い合わせ
	xmlHttpObject = createXMLHttpRequest(gotCalendars);
	if (xmlHttpObject){ // GETパラメータ付きでリクエスト送信
		// サーバとの約束事
		var array = new Array();
		array['year'] = yy;
		array['month'] = mm;
		
		var st = "./server.php?command=GET_BOOKING_HISTORY"
		+ "&value=" + encodeObject(array);
		//alert("getCalendars ==\n"+st); //return;//===
        
		xmlHttpObject.open("GET", encodeURI(st), true);
		xmlHttpObject.send(null);
	}
}

/// Ajax による処理 /////////
///////////////////////////



////////////////////////////////////////////
/// localStorage ///////////////////////////

function getWindowSize(){
	// Booking のウインドー位置とサイズをサーバへリクエスト
    var size = window.localStorage["bookingWindowSize"];
    
	// サーバから得られたサイズにウインドーを調整する
	if (size){
		var args = size.split(",");
		var x = args[0] * 1;
		var y = args[1];
		var w = args[2];
		var h = args[3];
		// resize を先にしておかないと元が大きいサイズだった場合 moveTo しよう
		// としてもウインドー境界の制限で移動できない場合がある
		window.resizeTo(w, h);
		window.moveTo(x, y);
        
        //alert("getWindowSize->"+size); //##
	}
}
function putWindowSize(){
	// Booking のウインドー位置とサイズをサーバへ記憶
	var x = window.screenLeft;
	var y = window.screenTop - 22;
	var w = window.outerWidth;
	var h = window.outerHeight;
    var array = [x, y, w, h];
    
    window.localStorage["bookingWindowSize"] = array.join(",");
}

/// localStorage ///////////////////////////
////////////////////////////////////////////



///////////////////////////
/// 初期設定 ////////////////

function openPrintSetting(){
	// 予約票設定パネルを開く
	openConfirm(5, 5, "予約票レイアウト設定パネル", "", "");
	
	// confirm パネルの内容を生成
	var obj = new Object();
	makeLayoutPanel(obj);
	//getLayout();
	document.getElementById("pr_comment1").value = comment1();
	document.getElementById("pr_comment2").value = comment2();
	
	function makeLayoutPanel(obj){
		// preference confirm panel の内容を生成
		var elm = document.getElementById("_conrirmContets");
		elm.innerHTML = "";
		var tbl = newTABLE(elm, "");
		tbl.style.width = "100%";
		tbl.style.fontSize = "10pt";
		
		var tr = newTR(tbl, "", "");
		var td = newTD(tr, "", "コメント内容を入力してください");
		td.style.padding = "3px 5px";
		var tr = newTR(tbl, "", "");
		var td = newTD(tr, "", "");
		var st = "コメントを入力";
		var fd = newTEXTAREA(td, "pr_comment1", 40, 6, st);
		fd.style.fontSize = "9pt";
		fd.focus();
		
		var tr = newTR(tbl, "", "");
		var td = newTD(tr, "", "診療受付時間などを入力してください");
		td.style.padding = "3px 5px";
		var tr = newTR(tbl, "", "");
		var td = newTD(tr, "", "");
		var st = "診療受付時間などを入力";
		var fd = newTEXTAREA(td, "pr_comment2", 40, 6, st);
		fd.style.fontSize = "9pt";
		
		var tr = newTR(tbl, "", "");
		var td = newTD(tr, "", "内容は入力欄に収まる程度にとどめてください ");
		td.style.textAlign = "right";
		var bt = newBUTTON(td, "", "確定");
		bt.setAttribute("onclick", "saveLayout()");
	}
}

function openPreference(){
	// 初期設定パネル
	openConfirm(5, 5, "初期設定パネル", "", "");
	//getLayout();

	// confirm パネルの内容を生成
	var obj = new Object();
	obj.interval = minutesInterval();
	makePreferencePanel(obj);
	
	function makePreferencePanel(obj){
		// preference confirm panel の内容を生成
		var elm = document.getElementById("_conrirmContets");
		elm.innerHTML = "";
		var tbl = newTABLE(elm, "");
		tbl.style.width = "100%";
		tbl.style.fontSize = "10pt";
		
		var tr = newTR(tbl, "", "");
		var td = newTD(tr, "", "予約枠の幅 ");
		td.style.textAlign = "right";
		td.style.padding = "5px 5px";
		td.style.borderBottom = "thin solid #aaa";
		var array = [5,10,15,20,30];
		var pu = makePopupMenu(td, "pr_min", array, obj.interval);
		var tx = newTEXT(td, " 分");

		var tr = newTR(tbl, "", "");
		var td = newTD(tr, "", "");
		td.style.textAlign = "right";
		td.style.padding = "5px 5px";
		var bt = newBUTTON(td, "", "予約票レイアウト設定");
		bt.setAttribute("onclick", "openPrintSetting()");
		td.style.borderBottom = "thin solid #aaa";

		var tr = newTR(tbl, "", "");
		var td = newTD(tr, "", "");
		td.innerHTML = "休診日を「12/23」形式で<br/>一行ずつ記入してください";
		td.style.padding = "3px 5px";
		var tr = newTR(tbl, "", "");
		var td = newTD(tr, "", "");
		var st = holidays().join("\n");
		var fd = newTEXTAREA(td, "pr_holiday", 15, 15, st);
		fd.style.fontSize = "9pt";

		var tr = newTR(tbl, "", "");
		var td = newTD(tr, "", "");
		td.style.textAlign = "right";
		var bt = newBUTTON(td, "", "確定");
		bt.setAttribute("onclick", "savePreference()");
	}
}

/// 初期設定 ////////////////
///////////////////////////


/////////////////////////////
///// 予約票の印刷 ////////////

var _printArgs;
function printPDF(){
	// 予約票を印刷
	var array = _printArgs;
	array['doctorName'] = document.getElementById("ed_doctor").value;

	// encodeURI() しないと改行などが正しく印刷されない
	var url = "./printBooking.php?value="+encodeObject(array);
	open(encodeURI(url), "PrintBooking", "");
	
	closeConfirm();
}

function doctorSelected(elm){
	// ドクター名のポップアップメニューが選択された
	document.getElementById("ed_doctor").value = elm.value;
}

function printBooking(){
	// 担当医氏名を選択するパネルを開く
	setPrintArgs(); // 予約編集パネルが消える前にパラメータを取得
	openConfirm(5, 5, "予約票印刷", "", "");
	
	// confirm パネルの内容を生成
	// _conrirmContets は confirm パネル内の予約語
	var elm = document.getElementById("_conrirmContets");
	elm.innerHTML = "";
	var tbl = newTABLE(elm, "");
	tbl.style.width = "100%";
	tbl.style.fontSize = "10pt";
	tbl.style.borderCollapse = "collapse";
	tbl.style.backgroundColor = "#ffc";
	
	var tr = newTR(tbl, "", "");
	var td = newTD(tr, "", "");
	td.style.padding = "5px 5px";
	td.innerHTML = "予約日に診療を行う担当医を選択し<br/>印刷ボタンを押してください";
	
	var tr = newTR(tbl, "", "");
	var td = newTD(tr, "", "担当医 ");
	var doctors = userKanjiNames();
	var defaoultDoctor = userNameForLoginName(owner());
	var pu = makePopupMenu(td, "", doctors, defaoultDoctor);
	pu.setAttribute("onclick", "doctorSelected(this)");
	var fd = newFIELD(td,"ed_doctor","",20,defaoultDoctor);

	var tr = newTR(tbl, "", "");
	var td = newTD(tr, "", "");
	td.style.textAlign = "right";
	td.style.padding = "5px 5px";
	var bt = newBUTTON(td, "", "印刷");
	bt.setAttribute("onclick", "printPDF()");

	function setPrintArgs(){
		var array = new Array();
		array['patientId'] = document.getElementById("ed_pid").value;
		array['anotherId'] 
		= document.getElementById("ed_anotherId").innerHTML;
		array['patientName'] 
		= document.getElementById("ed_patientName").innerHTML;
		var ary = weeks();
		var weekSt = "(" + ary[week()] + ") ";
		array['date'] = year()*1+"年"+month()*1+"月"+day()*1+"日"+weekSt;
		var hour = document.getElementById("ed_hour").value;
		var min = document.getElementById("ed_min").value;
		array['time'] = amPmOf(hour) + "時" + min + "分";
		
		array['comment1'] = comment1();
		array['comment2'] = comment2();
		
		array['address'] = hospitalInfoForKey("住所");
		array['phone'] = hospitalInfoForKey("電話番号");
		array['hospitalName'] = hospitalInfoForKey("施設名");

		_printArgs = array;
	}
	
	function amPmOf(hour){
		// ２４時間表記を１２時間表記に変更
		if (hour * 1 >= 12)
			return "午後" + (hour * 1 - 12);
		else
			return "午前" + hour * 1;
	}
}

///// 予約票の印刷 ////////////
/////////////////////////////


function selectPatient(pid, aid, name){
	// 検索結果から患者が選択された
	document.getElementById("ed_pid").value = pid;
	document.getElementById("ed_anotherId").innerHTML = aid;
	document.getElementById("ed_patientName").innerHTML = name;

	// 確定ボタンを表示
	var sp = document.getElementById("ed_ok_button");
	sp.innerHTML = "";
	var bt = newBUTTON(sp, "", "確定");
	bt.setAttribute("onclick", "saveBooking()");
	
	// 検索結果を消去
	document.getElementById("ed_patientListArea").innerHTML = "";
}
function showPatientList(objct){
	// キーにマッチした患者リストを表示
	var elm = document.getElementById("ed_patientListArea");
	elm.innerHTML = "";

	var tbl = newTABLE(elm, "");
	tbl.style.width = "100%";
	tbl.style.fontSize = "10pt";
	tbl.style.border = "thin solid #aaa";

	var tr = newTR(tbl, "", "");
	var td = newTD(tr, "", "以下の検索結果から選択してください");
	td.setAttribute("colspan","3");

	var tr = newTR(tbl, "", "");
	tr.style.backgroundColor = "#fc0";
	var td = newTD(tr, "", "カルテID");
	var td = newTD(tr, "", "氏名");
	var td = newTD(tr, "", "最終受診日");

	for (num in objct){
		var obj = objct[num];
		
		var tr = newTR(tbl, "", "");
		tr.style.backgroundColor = "#fff";
		tr.setAttribute("onmouseover", "setColor(this, '#ff0', '#00f')");
		tr.setAttribute("onmouseout", "setColor(this, '#000', '#fff')");
		var action = "selectPatient('"+obj.patientId+"','"+obj.anotherId+"','"+obj.patientKanjiName+"')";
		tr.setAttribute("onclick", action);
		var td = newTD(tr, "", obj.patientId);
		var td = newTD(tr, "", obj.patientKanjiName);
		var td = newTD(tr, "", obj.lastVisitDate);
	}
}

function openInfoPanel(patientName, entryDate){
	// 情報を表示するパネルを開く
	obj = patientForEntryDate(patientName, entryDate);
	openInfo(5, 5);
	
	// confirm パネルの内容を生成
	makeInfoContents(obj);
	
	function makeInfoContents(obj){
		// _conrirmContets は confirm パネル内の予約語
		var elm = document.getElementById("_conrirmContets");
		elm.innerHTML = "";
		var tbl = newTABLE(elm, "");
		tbl.style.width = "100%";
		tbl.style.fontSize = "10pt";
		tbl.style.backgroundColor = "#ff0";
		
		var tr = newTR(tbl, "", "");
		var td = newTD(tr, "", "");
		var im = newIMAGE(td, "", "./close.png", "x");
		im.setAttribute("onclick", "closeConfirm()");
		im.style.height = "12px";
		var td = newTD(tr, "", "");
		
		var tr = newTR(tbl, "", "");
		var td = newTD(tr, "", "受診日");
		var td = newTD(tr, "", obj.entryDate);
		
		var tr = newTR(tbl, "", "");
		var td = newTD(tr, "", obj.patientId);
		var td = newTD(tr, "", obj.name);
	}
}

function clickedMemo(elm){
	// メモポップアップが選択された
	if (elm.value == "...その他"){
		var item = prompt("実施予定項目を登録してください");
		if (item){
			// menuItems をサーバに保存し、メモ・ポップアップを再表示
			addMemo(item);
			return;
		}
	} else if (elm.value.length == 0){
        return ;
    }
    
	var buff = document.getElementById("ed_memo").value;
	if (buff.length)
		buff += "\n" + elm.value;
	else
		buff = elm.value;
	document.getElementById("ed_memo").value = buff;
}

function clearMemo(){
	// 実施予定欄を空欄にする
	document.getElementById("ed_memo").value = "";
}

function showMemoPopup(){
	// メモ用ポップアップ・メニューを生成
	var elm = document.getElementById("ed_memo_popupArea");
	elm.innerHTML = "";
	var items = [""];
	var array = memoItems();
	for (key in array){
		items.push(array[key]);
	}
	items.push("...その他");
	var pu = makePopupMenu(elm, "ed_memo_popup", items, "");
	pu.setAttribute("onchange", "clickedMemo(this)");
}

function openChart(){
    // このカルテを開く
    var pid = document.getElementById("ed_pid").value;
    var name = document.getElementById("ed_patientName").innerHTML;

    parent().openChart(pid, name);
}

function openBookingEditor(patName, entryDate, isActive){
	// 分区画がクリックされた
	var isBlank = false;
	if (isActive == 0){
		if (!confirm("診療時間外ですが、ここに予約を入れますか？")) return;
	}
	
	var obj = new Object();
	if (entryDate.length > 10){ // entryDate = "2010-01-30 09:15:00"
		// 予約済みデータを編集
		// 記憶された records から患者オブジェクトを取り出す
		obj = patientForEntryDate(patName, entryDate);
		obj.anotherId = (obj.anotherId) ? obj.anotherId : "";
	} else { // entryDate = "09:15:00"
		// 空欄データを編集
		isBlank = true;
		var date = selectedDate().substr(0,11) + entryDate;
		obj.entryDate = date;
		if (patientId().length){
			// 予約ツールが NOA から起動された
			obj.patientId = patientId();
			obj.anotherId = anotherId();
			obj.name = patientName();
		} else {
			// 予約ツールが FRONT から起動された
			obj.patientId = "";
			obj.anotherId = "";
			obj.name = "";
		}
	}
	
	openConfirm(5, 5, "予約編集パネル", "", "");
	
	// confirm パネルの内容を生成
	makeConfirmPanelContents(obj, isBlank);
	
	function makeConfirmPanelContents(obj, isBlank){
		// confirm panel の内容を生成
		var year = yearOfDateTime(obj.entryDate);
		var month = monthOfDateTime(obj.entryDate);
		var day = dayOfDateTime(obj.entryDate);
		var hour = hourOfDateTime(obj.entryDate);
		var min = minutesOfDateTime(obj.entryDate);
		
		// _conrirmContets は confirm パネル内の予約語
		var elm = document.getElementById("_conrirmContets");
		elm.style.backgroundColor = "#ffc";
		elm.innerHTML = "";
		var tbl = newTABLE(elm, "");
		tbl.style.width = "100%";
		tbl.style.fontSize = "10pt";
		tbl.style.borderCollapse = "collapse";
		
		var tr = newTR(tbl, "", "");
		var td = newTD(tr, "", "カルテID");
		td.style.textAlign = "right";
		td.style.padding = "0px 5px";
		var td = newTD(tr, "", "");
		var sp = newSPAN(td, "ed_patientId");
        // ID 検索フィールド
        var fd = newFIELD(sp,"ed_pid","",10,obj.patientId);
        fd.setAttribute("onchange", "searchPatient()");
        fd.focus();
        var bt = newBUTTON(sp, "", "検索");
        bt.setAttribute("onclick", "searchPatient()");

		var tx = newTEXT(td, " ");
		var im = newIMAGE(td, "", "./Help.png", "?");
		
		var tx = newTEXT(td, " ");
		im.setAttribute("onclick", "editorHelp()");
		im.style.height = "20px";
		im.style.verticalAlign = "bottom";
		
		var tr = newTR(tbl, "", "");
		var td = newTD(tr, "", "anotherId");
		td.style.textAlign = "right";
		td.style.padding = "0px 5px";
		var td = newTD(tr, "", "");
		var sp = newSPAN(td, "ed_anotherId");
		var tx = newTEXT(td, " ");
		var tx = newTEXT(sp, obj.anotherId);
		
		var tr = newTR(tbl, "", "");
		var td = newTD(tr, "", "氏名");
		td.style.textAlign = "right";
		td.style.padding = "0px 5px";
		var td = newTD(tr, "", "");
		var sp = newSPAN(td, "ed_patientName");
		var tx = newTEXT(td, " ");
		var tx = newTEXT(sp, obj.name);
		
		var tr = newTR(tbl, "", "");
		var td = newTD(tr, "", "年月日");
		td.style.textAlign = "right";
		td.style.padding = "0px 5px";
		var hd = newHIDDEN(td,"ed_entrydate", obj.entryDate);
		var st = year + "年 " + month + "月 " + day + "日 ";
		var td = newTD(tr, "", st);
		var pu = makePopupMenu(td, "ed_hour", hours(), hour);
		var tx = newTEXT(td, "時");
		var m = nearValue(minutes(), min);
		var pu = makePopupMenu(td, "ed_min", minutes(), m);
		var tx = newTEXT(td, "分");

		var tr = newTR(tbl, "", "");
		tr.style.verticalAlign = "top";
		var td = newTD(tr, "", "実施予定");
		td.style.textAlign = "right";
		td.style.padding = "0px 5px";
		var td = newTD(tr, "", "");
		var sp = newSPAN(td, "ed_memo_popupArea");
		showMemoPopup();
		var im = newIMAGE(td, "", "./remove-field.png", "x");
		im.setAttribute("onclick", "removeMemo()");
		im.style.height = "14px";
		im.style.verticalAlign = "bottom";

		var tr = newTR(tbl, "", "");
		var td = newTD(tr, "", "");
		td.style.fontSize = "9pt";
        var a = newA(td, "空欄にする", "#", "");
        a.setAttribute("onclick", "clearMemo()");
		td.style.verticalAlign = "top";
		td.style.textAlign = "right";
		var td = newTD(tr, "", "");
		var memo = (obj.plan) ? obj.plan : "";
		var fd = newTEXTAREA(td, "ed_memo", 35, 5, memo);
		fd.style.fontSize = "9pt";

		var tr = newTR(tbl, "ed_footer", "");
		tr.style.backgroundColor = "#ec9";
		var td = newTD(tr, "", "");
		td.style.textAlign = "right";
		var td = newTD(tr, "", "　");
		td.style.textAlign = "right";
        if (parent()){
            var bt = newBUTTON(td, "", "カルテを開く");
            bt.setAttribute("onclick", "openChart()");
        }
		if (!isBlank){
			var bt = newBUTTON(td, "", "削除");
			bt.setAttribute("onclick", "removeBooking()");
			var bt = newBUTTON(td, "", "予約票発行");
			bt.setAttribute("onclick", "printBooking()");
		}
		var sp = newSPAN(td, "ed_ok_button");
		if (obj.patientId.length){
			var bt = newBUTTON(sp, "", "確定");
			bt.setAttribute("onclick", "saveBooking()");
		}

		
		// 検索結果表示エリア
		var dv = newDIV(elm, "ed_patientListArea");
	}
	
	function nearValue(array, val){
		// popup 値である array に該当する値を返す
		var oldVal = array[0];
		for (var i=0,ct=array.length; i < ct; i++){
			if (val < array[i]) return oldVal;
			oldVal = array[i];
		}
		return oldVal;
	}
}


function isPast(){
	// 選択された日付が過去なら true を返す
	var date = dateOfDateTime(selectedDate());
	var today = dateOfDateTime(todayAndTime());
	
	return (date < today) ? true : false;
}

function cellIdFor(yy, mm, dd){
	// カレンダー日付セルの ID を返す
	if ((mm * 1) < 10) mm = "0" + (mm * 1);
	if ((dd * 1) < 10) dd = "0" + (dd * 1);
	
	return "day" + yy + mm + dd;
}

var _oldColor;
var _oldBGColor;
function clickedCalendar(yy, mm, dd, w){
	// カレンダー日付がクリックされると、その日の予約状況を表示
	if ((mm * 1) < 10) mm = "0" + (mm * 1);
	if ((dd * 1) < 10) dd = "0" + (dd * 1);
	setSelectedDate(yy+"-"+mm+"-"+dd+" 00:00:00");
	
	// カレンダーの選択部分を移動
	if (day()){
		// 以前に選択されていた日付の色を非選択色に戻す
		var cid = cellIdFor(year(), month(), day());
		var td = document.getElementById(cid);
		td.style.color = _oldColor;
		td.style.backgroundColor = _oldBGColor;
	}
	
	// 選択された日付の色を選択色にする
	var td = document.getElementById(cellIdFor(yy, mm, dd));
	_oldColor = td.style.color;
	_oldBGColor = td.style.backgroundColor;
	td.style.color = "#ff0";
	td.style.backgroundColor = "#00f";

	//	alert(yy+"/"+mm+"/"+dd); //##

	// yy, mm, dd の予約患者をサーバへ照会
	getBooking(yy, mm, dd, w);
}

function showBookingMatrix(){
	// 予約マトリックスを表示
	var mm = month() * 1;
	var dd = day() * 1;
	var bgcolor = "#fff";
	if (isPast())
		bgcolor = "#eee";
	else if (week() == 0)
		bgcolor = "#fcc";
	else if (isHoliday(mm, dd))
		bgcolor = "#fcc";
	
	// マトリックス・エリアを生成
	var base = document.getElementById("editorArea");
	base.innerHTML = "";
	var table = newTABLE(base, "matrixTable");
	
	// 分ヘッダー
	var tr = newTR(table, "", "");
	var td = newTD(tr, "", "");
	td.innerHTML = mm + "月<br/>" + dd + "日";
	td.style.width = "60px";
	td.style.fontSize = "15pt";
	td.style.textAlign = "right";
	td.style.padding = "0px 2px";
	td.style.backgroundColor = bgcolor;
		
    // タイトル
	for (var i=0; i < 60; i += minutesInterval()){
		var td = newTD(tr, "", i + "分");
		td.style.backgroundColor = "#aec";
		td.style.textAlign = "center";
	}
	
	// 時間マトリックス
	var begin = 7;
	var end = 22;
	for (var hour=begin; hour <= end; hour++){
		// 時刻行を生成
		var tr = newTR(table, "", "");
		tr.style.borderTop = "1px solid #eee";
		var td = newTD(tr, "timeTD", hour + "時 ");
		td.style.backgroundColor = bgcolor;
		td.style.textAlign = "right";
		for (var min=0; min < 60; min += minutesInterval()){
			// 分カラムを生成
			// 割り当てられた「年月日・時刻・分範囲」に相当する予約患者を表示
			var td = newTD(tr, "", "");
			setContents(td, hour, min);
		}
	}
	
	function setContents(elm, hour, min){
		// records() 中の指定時刻枠にあてはまる患者名を割り当てて返す
		var table = newTABLE(elm, "simpleTable");
		var isActive = isConsultTime(hour, min);
		if (isActive == 0)
			table.style.backgroundColor = "efe";
		
		var hasBooking = false;
		var array = records();
		for (var i=0,ct=array.length; i < ct; i++){
			var obj = array[i];
			var edate = obj.entryDate;
			var hr = hourOfDate(edate);
			var mn = minutesOfDate(edate);
			if (hour*1 == hr*1){
				if ((min <= mn) && (mn < min + minutesInterval())){
					var tr = newTR(table, "", "");
					var td = newTD(tr, "cell", obj.name);
					td.style.textAlign = "center";
					if (isPast()){
						var action = "openInfoPanel('"+obj.name+"','"+edate+"')";
					} else {
						var action = "openBookingEditor('"+obj.name+"','"+edate+"','" + isActive + "')";
					}
					td.setAttribute("onclick",action);
					hasBooking = true;
				}
			}
		}
		if (isPast() || hasBooking) return;
		
		// 空枠を生成
		var tr = newTR(table, "", "");
		if (isActive == 1)
			var td = newTD(tr, "cell", "　");
		else
			var td = newTD(tr, "", "　");
		var action = "openBookingEditor('','"+hour+":"+min+":00','" + isActive + "')";
		td.setAttribute("onclick",action);
	}
}

function hourOfDate(date){
	// "2010-02-06 10:30:00" 形式から時刻 "10" を返す
	var array = date.split(" ");
	if (array.length > 1){
		var st = array[1];
		var ary = st.split(":");
		return ary[0];
	}
	return "0";
}
function minutesOfDate(date){
	// "2010-02-06 10:30:00" 形式から分 "30" を返す
	var array = date.split(" ");
	if (array.length > 1){
		var st = array[1];
		var ary = st.split(":");
		if (ary.length > 1)
			return ary[1];
	}
	return "0";
}

function isHoliday(month, day){
	// preference で設定された休診日なら true を返す
	var array = holidays();
	for (var i=0,ct=array.length; i < ct; i++){
		var st = array[i]; // "3/23" 形式
		var ary = st.split("/");
		if (ary.length > 1){
			var mm = ary[0];
			var dd = ary[1];
			if ((mm == month) && (dd == day)) return true;
		}
	}
	return false;
}

function prevMonth(yy, mm){
	if (--mm < 1){
		--yy;
		mm = 12;
	}
	getCalendars(yy, mm);
}

function nextMonth(yy, mm){
	if (++mm > 12){
		++yy;
		mm = 1;
	}
	getCalendars(yy, mm);
}

function showCalendars(yy, mm){
	// カレンダーを３連装で表示

    if (patientId()){
		var st = patientId()+" "+patientName()+" さんの予約";
        document.getElementById("idAndNameArea").innerHTML = st;
    }
   
	var elm = document.getElementById("calendarArea");
	elm.innerHTML = "";
	var table = newTABLE(elm, "table");
	
	// １段目のカレンダー
	var tr = newTR(table, "", "");
	var td = newTD(tr, "", "");
	showCalendar(td, yy, mm, true);
	
	// ２段目のカレンダー
	var tr = newTR(table, "", "");
	var td = newTD(tr, "", "");
	if (++mm > 12){
		++yy;
		mm = 1;
	}
	showCalendar(td, yy, mm);
	
	//　３段目のカレンダー
	var tr = newTR(table, "", "");
	var td = newTD(tr, "", "");
	if (++mm > 12){
		++yy;
		mm = 1;
	}
	showCalendar(td, yy, mm);
}

function showCalendar(elm, yy, mm, hasButton){
	// yy, mm, dd のカレンダーを表示
	var weeks = new Array("日","月","火","水","木","金","土");
	
	// １日の曜日を得る
	date = new Date(yy, mm-1, 1);
	var firstWeek = date.getDay();
	// 月の日数を得る
	date = new Date(yy, mm, 0);
	var lastday = date.getDate();
	
	// カレンダーのフレームを表示
	var table = newTABLE(elm, "calendarTable");
	
	// タイトルを表示
	var tr = newTR(table, "", "");
	var td = newTD(tr, "label", "");
	td.setAttribute("colspan","7");
	if (hasButton){
		// 月後戻りボタンを表示
		var bt = newBUTTON(td, "", "＜");
		var action = "prevMonth("+yy+","+mm+")";
		bt.setAttribute("onclick", action);
		// 年月を表示
		var tx = newTEXT(td, " " + yy + " / " + mm + " ");
		// 月先送りボタンを表示
		var bt = newBUTTON(td, "", "＞");
		var action = "nextMonth("+yy+","+mm+")";
		bt.setAttribute("onclick", action);
	} else {
		// 年月を表示
		var tx = newTEXT(td, " " + yy + " / " + mm + " ");
	}

	// 曜日を表示
	var tr = newTR(table, "week", "");
	for (var w=0; w < 7; w++){
		var td = newTD(tr, "", weeks[w]);
		td.style.textAlign = "center";
	}
	
	// カレンダーの日付を表示
	for (var i=0, d=0; d < lastday; ){
		if (i % 7 == 0){
			// １週間分を表示
			var tr = newTR(table, "", "");
			for (w=0; w < 7; w++){
				if (i++ < firstWeek){
					// 空白を表示
					var td = newTD(tr, "day", "");
				} else if (d >= lastday){
					// 空白を表示
					var td = newTD(tr, "day", "");
				} else {
					// 日付を表示
					d++;
					// 日付エレメントを特定出来るよう年月日による ID を振る
					var cid = cellIdFor(yy, mm, d);
					var td = newTD(tr, cid, d+"");
					var action 
						= "clickedCalendar("+yy+","+mm+","+d+","+w+")";
					td.setAttribute("onmouseup", action);
					td.style.textAlign = "center";
					if (w == 0)
						td.style.backgroundColor = "#fdd";
					else if (isHoliday(mm, d))
						td.style.backgroundColor = "#fdd";
					else
						td.style.backgroundColor = "#fff";
					
					if (hasHistory(yy, mm, d)){
						// 予約者の存在する日付
						td.style.backgroundColor = "#ffa";
						td.style.borderBottom = "thin solid #888";
						td.style.borderRight = "2px solid #ccc";
					}
				}
			}
		}
	}
}

function help(){
	// 別途ヘルプをパネル表示
	window.open("./bookingHelp.html","Help"
				,"width=450,height=700,scrollbars=yes,resizable=yes");
}
function editorHelp(){
	// 別途ヘルプをパネル表示
	window.open("./bookingEditorHelp.html","Help"
				,"width=450,height=700,scrollbars=yes,resizable=yes");
}

function initBooking(){
	var elm = document.getElementById("base");
    	
	// header
    var div = newDIV(elm, "tool-header");
    var dv = newDIV(div, "left-side");
    var sp = newSPAN(dv, "idAndNameArea");
    sp.style.paddingLeft = "10px";
    var dv = newDIV(div, "right-side");
	var img = newIMAGE(dv, "icon", "zoomfit.png", "zoom");
	img.setAttribute("onclick","putWindowSize()");
	img.style.height = "16px";
    newTEXT(dv, " ");
	var im = newIMAGE(dv, "", "./Help.png", "?");
	im.setAttribute("onclick", "help()");
	im.style.height = "18px";
	im.style.verticalAlign = "bottom";
    im.style.position = "relative";
    im.style.bottom = "3px";

	// カレンダー表示エリア
    var div = newDIV(elm, "");
	var tbl = newTABLE(elm, "bodyTable");
	var tr = newTR(tbl, "", "");
	var td = newTD(tr, "calendarArea", "calendar");
	var td = newTD(tr, "editorArea", "");
	td.style.width = "1000px";
	
	// footer
    var div = newDIV(elm, "tool-footer");
    var dv = newDIV(div, "left-side");
	var im = newIMAGE(dv, "", "./hammer.png", "?");
	im.setAttribute("onclick", "openPreference()");
	im.style.height = "15px";
    var dv = newDIV(div, "right-side");
    dv.innerHTML = version();

    // ウインドー・サイズをサーバから読み込みサイズ調整
    getWindowSize();

    // 初期設定値を読み込むとともにカレンダーを表示
    getPreference();
}

function version(){
	return "Ver.130102";
}

