
var _consultKey;
function setConsultKey(key){
    _consultKey = key;
}
function consultKey(){
    // record を記憶から引き出すためのキー：実際には'診療時間'の文字列
    return _consultKey;
}

function weeks(){
	return ["日","月","火","水","木","金","土"];
}
function hours(){
	return ["00","01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24"];
}

function minutes(){
	return ["00","05","10","15","20","25","30","35","40","45","50","55"];
}

var _conditions
function initConditions(){
	// 設定条件を初期化
	_conditions = new Array();
	
	// default 条件を生成
	var obj = new Object();
	obj.from = "0000";
	obj.to = "0600";
	obj.timeZone = "深夜";
	_conditions.push(obj);
	
	var obj = new Object();
	obj.from = "2200";
	obj.to = "2400";
	obj.timeZone = "深夜";
	_conditions.push(obj);
	
	var obj = new Object();
	obj.week = "日";
	obj.from = "0000";
	obj.to = "2400";
	obj.timeZone = "休日";
	_conditions.push(obj);
	
	var obj = new Object();
	obj.from = "0900";
	obj.to = "1200";
	obj.timeZone = "時間内";
	_conditions.push(obj);
}
function conditions(){
	// 設定条件の配列を返す
	return _conditions;
}
function setConditions(row){
	// 設定条件をオブジェクトとして記憶
	var obj = new Array();
	setField(row, 'num', obj);
	setField(row, 'week', obj);
	setField(row, 'from', obj);
	setField(row, 'to', obj);
	setField(row, 'timeZone', obj);
	_conditions[row] = obj;

    // 設定値を CSV で表示
    var csv = encodeCSV(conditions());;
    var elm = document.getElementById("consultResultArea");
    elm.innerHTML = csv;

    // 診療時間の CSV を changeValue() が呼ばれなくても保存されるようにする
    setValueForKey(csv, "診療時間");

	function setField(row, field, obj){
		if (field == "from"){
			var hour = document.getElementById(row+".fromHour").value;
			var min = document.getElementById(row+".fromMin").value;
			var val = hour + min;
		} else if (field == "to"){
			var hour = document.getElementById(row+".toHour").value;
			var min = document.getElementById(row+".toMin").value;
			var val = hour + min;
		} else {
			var id = row + "." + field;
			var val = document.getElementById(id).value;
		}
		
		obj[field] = (val == "全て") ? "" : val;
	}
}
function changeConditions(row){
	// 設定条件をオブジェクトとして記憶し、変更あったことを register へ知らせる
    setConditions(row);
    
    // 値に変更のあったことを register 本体に伝える
	var rec = moduleForId(consultKey());
//    rec.value = encodeCSV(conditions());
	setModuleForId(rec, consultKey()); // dom.js

    changeValue(consultKey()); // consultKey() は '診療時間' の文字列
}

function conditionsAtRow(row){
	// row 行目の条件オブジェクトを返す
	return (row < _conditions.length) ? _conditions[row] : null;
}

function removeConditionsAtRow(row){
    // 選択行を削除
    _conditions.splice(row,1);
    showEditor();
    changeValue(consultKey()); // save ボタンを表示
}

function insertConditionsAtRow(row){
    // 選択行を挿入
    _conditions.splice(row, 0, new Array());
    showEditor();
    changeValue(consultKey()); // save ボタンを表示
}

////////////////////////////////////////////////////
///// Ajax /////////////////////////////////////////

function loaded(answer){
    //alert("loaded ===\n"+answer);//###

    answer = trim(answer);
    if (answer.length > 0){
        initConditions(); // default 値で _conditions 初期化
        var records = JSON.parse(answer);
        for (no in records){
            // hospitalInfo record から hospitalId の配列を作成
            var record = records[no];
            var hid = record.hospitalId;
            if (hid == hospitalId()){
                if (record.key == '診療時間'){
                    var csv = record.value;
                    if (csv){
                        //document.getElementById("message").innerHTML = csv;
                        var array = decodeCSV(csv);
                        
                        // CSV を正確に解読できたらそれで置換
                        if (array.length)
                            _conditions = array;
                        break;
                    }
                }
            }
        }
        showEditor();
    }
}
function load(){
	// 設定を読込
	// csv = ",,0000,0600,深夜\n,,2200,2400,深夜\n,日,0000,2400,休日";
    var args = new Object();
    args["hospitalId"] = hospitalId();
    
	_callServer("GET_HOSPITAL_TABLE", "sysServer.php", args, loaded);
}

///// Ajax /////////////////////////////////////////
////////////////////////////////////////////////////

function openEvaluation(){
    // 診療時間設定の評価テスト・ペーンを開く
    var elm = document.getElementById("evaluationArea");
    if (elm.innerHTML.length){
        elm.innerHTML = "";
        return;
    }
    elm.innerHTML = "";
    
	// comment
    var div = newDIV(elm, "");
    div.style.color = "#a63"; // brown
    div.style.marginTop = "5px";
    div.style.borderTop = "thin solid #aaa";
    div.style.paddingTop = "5px";
    div.style.paddingLeft = "5px";
    div.innerHTML = "設定条件は上から評価され、条件にマッチすれば以後の行は評価されません。<br>順序をよく考え設定してください。いずれにもマッチしない場合は時間外として評価されます。<br>最後に上記設定により、以下の日時が正しく評価されるか条件を変えテストしてください。"; // 適当な長さで切っておかないと elment 幅が必要以上に伸びてしまう
	
	// 評価テスト・エリア
    var div = newDIV(elm, "testArea");
    var tbl = newTABLE(elm, "base-table");
    var tr = newTR(tbl, "", "");
    // 年月日ポップアップ
    var td = newTD(tr, "", "");
    var pu = newPopupMenu(td, "year", ["2009","2010","2011"], "");
    pu.setAttribute("onchange", "setWeek()");
    var pu = newPopupMenu(td, "month", ["1","2","3","4","5","6","7","8","9","10","11","12"], "");
    pu.setAttribute("onchange", "setWeek()");
    var pu = newPopupMenu(td, "day", ["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31"], "");
    pu.setAttribute("onchange", "setWeek()");
    // 曜日ポップアップ
    var year = document.getElementById("year").value;
    var month = document.getElementById("month").value;
    var day = document.getElementById("day").value;
    var date = new Date(year,month + 1,day);
    var week = date.getDay();
    var array = weeks();
    var sp = newSPAN(td, "");
    var pu = newPopupMenu(sp, "week", array, array[week]);
    // 時刻ポップアップ
    var pu = newPopupMenu(td, "hour", hours(), "");
    var tx = newTEXT(td, ":");
    var pu = newPopupMenu(td, "min", minutes(), "");
    var bt = newBUTTON(td, "", "評価テスト");
    bt.setAttribute("onclick","checkConditions()");
    // 評価結果表示エリア
    var tr = newTR(tbl, "", "");
    var td = newTD(tr, "consultResultsArea", "");
    td.style.fontSize = "9pt";
    td.style.color = "#00f";
}

function encodeCSV(array){
	// array オブジェクトを CSV へ変換
	var buff = "";
	for (var row=0,rows=array.length; row < rows; row++){
		var rec = "";
		var obj = array[row];
		for (key in obj){
			rec += obj[key] + ",";
		}
		rec = rec.substr(0, rec.length - 1); // 末尾のカンマを削除
		buff += rec + "^";
	}
	return buff;
}
function decodeCSV(csv){
	// csv を conditions オブジェクトへ変換
	var results = new Array();
	var array = csv.split("^");
	for (var row=0,rows=array.length; row < rows; row++){
		var ln = trim(array[row]);
		var ary = ln.split(",");
		if (ary.length == 5){
			var obj = new Object();
			obj.weekNum = ary[0];
			obj.week = ary[1];
			obj.from = ary[2];
			obj.to = ary[3];
			obj.timeZone = ary[4];
			results.push(obj);
		}
	}
	return results;
}

function checkConditions(){
	// 指定した日時の時間区分をチェックする
	var buff = "";
	var result = "";
    for (row in conditions()){
		result = eval(makeScript(row));
		buff += makeScript(row) + "<br/>";
		if (result.length > 0){
			showResult(buff, result);
			break;
		}
	}
	if (result.length == 0)
		showResult(buff, "時間外");
	
	function showResult(buff, result){
		document.getElementById("consultResultsArea").innerHTML
        = buff + "=== 上記チェックの結果 ( " + result + " ) と判定 ===";
	}
    
    function makeScript(i){
        // 設定された条件のもとに判定用スクリプトを生成
        var day = document.getElementById("day").value;
        var week = document.getElementById("week").value;
        var weekNum = Math.ceil(day / 7);
        var hour = document.getElementById("hour").value;
        var min = document.getElementById("min").value;
        var time = hour + min;
        var buff = "";
        var array = new Array();
        var obj = conditionsAtRow(i);
        if (obj.num)
            array.push("(" + weekNum + " == " + obj.num + ")");
        if (obj.week)
            array.push("(\"" + week + "\" == \"" + obj.week + "\")");
        var st = "(" + obj.from + " <= " + time + ")";
        st += " && (" + time + " <= " + obj.to + ")";
        array.push(st);
        buff += "(" + array.join(" && ") + ")";
        buff += " ? \"" + obj.timeZone + "\" : \"\"; ";
        return buff;
    }
}

function showEditor(){
	// 条件設定エディターを表示
	var elm = document.getElementById("editorArea");
	elm.innerHTML = "";
	var tbl = newTABLE(elm, "base-table");
    tbl.style.fontSize = "9pt";
	
	// title
	var tr = newTR(tbl, "yellow-bar", "");
	var td = newTD(tr, "", "");
	var td = newTD(tr, "label-left", "何週目");
	var td = newTD(tr, "label-left", "曜日");
	var td = newTD(tr, "label-left", "診療時間");
	var td = newTD(tr, "label-left", "時間区分");
	var td = newTD(tr, "label-left", "");
	
	// condition rows
	var rows = conditions().length;
	for (var row=0; row < rows; row++){
		showLine(tbl, row);
		setConditions(row); // 条件を記憶
	}
	
	// insert row button
	showBlankLine(tbl);
    
    // 評価エリア
    var div = newDIV(elm, "evaluationArea");
    
    // Ajax の結果が返ってきたところで次のリクエストを発出
	if (records().length){
        // 施設が登録済みなら職員リストを表示
        getStaffList(); // Ajax
    }
    
    function showLine(tbl, row){
        // editing line
        var obj = conditionsAtRow(row);
        var tr = newTR(tbl, "", "");
        
        // 追加ボタン
        var td = newTD(tr, "", "");
        td.style.width = "20px";
        var img = newIMAGE(td, "", "./add-field.png", "add");
        img.style.height = "15px";
        img.style.verticalAlign = "middle";
        img.setAttribute("onclick", "insertConditionsAtRow('" + row + "')");
        
        // 何週目
        var td = newTD(tr, "", "");
        var id = row + ".num";
        var pu = newPopupMenu(td, id, ["全て","1","2","3","4","5"],obj.num);
        pu.setAttribute("onchange", "changeConditions('" + row + "')");
        
        // 曜日
        var td = newTD(tr, "", "");
        var id = row + ".week";
        var pu = newPopupMenu(td, id, ["全て","日","月","火","水","木","金","土"], obj.week);
        pu.setAttribute("onchange", "changeConditions('" + row + "')");
        
        // 診療時間
        var td = newTD(tr, "", "");
        var id = row + ".fromHour";
        var from = obj.from;
        var fromHour = (from) ? from.substr(0, 2) : "09";
        var fromMin = (from) ? from.substr(2, 2) : "00";
        var pu = newPopupMenu(td, id, hours(), fromHour);
        pu.setAttribute("onchange", "changeConditions('" + row + "')");
        var id = row + ".fromMin";
        var pu = newPopupMenu(td, id, minutes(), fromMin);
        pu.setAttribute("onchange", "changeConditions('" + row + "')");
        var tx = newTEXT(td, "から");
        var id = row + ".toHour";
        var to = obj.to;
        var toHour = (to) ? to.substr(0, 2) : "12";
        var toMin = (to) ? to.substr(2, 2) : "0";
        var pu = newPopupMenu(td, id, hours(), toHour);
        pu.setAttribute("onchange", "changeConditions('" + row + "')");
        var id = row + ".toMin";
        var pu = newPopupMenu(td, id, minutes(), toMin);
        pu.setAttribute("onchange", "changeConditions('" + row + "')");
        var tx = newTEXT(td, "まで");
        
        // 時間区分
        var td = newTD(tr, "", "");
        var id = row + ".timeZone";
        var pu = newPopupMenu(td, id, ["時間内","時間外","深夜","休日",""], obj.timeZone);
        pu.setAttribute("onchange", "changeConditions('" + row + "')");
        
        // 削除ボタン
        var td = newTD(tr, "", "");
        td.style.width = "20px";
        var img = newIMAGE(td, "", "./remove-field.png", "add");
        img.style.height = "15px";
        img.style.verticalAlign = "middle";
        img.setAttribute("onclick", "removeConditionsAtRow('" + row + "')");
    }
    
    function showBlankLine(tbl){
        // 最終行の追加ボタン
        var tr = newTR(tbl, "", "");
        
        // 追加ボタン
        var td = newTD(tr, "", "");
        td.style.width = "20px";
        var img = newIMAGE(td, "", "./add-field.png", "add");
        img.style.height = "15px";
        img.style.verticalAlign = "middle";
        img.setAttribute("onclick", "insertConditionsAtRow('" + row + "')");
        
        // 空列
        var td = newTD(tr, "", "");
        td.setAttribute("colspan", "5");
        td.style.color = "#a63"; // brown
        td.innerHTML = "ここで設定した診療時間区分は診療費計算で使われます。";
        
        // 評価テスト・アンカー
        var sp = newSPAN(td, "");
        sp.style.paddingLeft = "10px";
        var a = newA(sp, "設定した時間帯が正しく評価されるかテスト", "#", "");
        a.setAttribute("onclick", "openEvaluation()");
    }
}

function makeConsultationHours(key){
    // 診療時間帯設定ペーン: key = "診療時間"
    //alert("== makeConsultationHours->"+key); //##
    
    var elm = document.getElementById("timeEditArea");
    if (elm.innerHTML.length){
        elm.innerHTML = "";
        return;
    }
    elm.innerHTML = "";
    setConsultKey(key); // 実際には '診療時間' の文字列
    
	// 編集エリア
    var div = newDIV(elm, "editorArea");
    div.style.border = "thin solid #ccc";
    div.style.padding = "5px 5px";

	load(); // Ajax にアクセス
}