
var _records;
function setRecords(array){
	_records = array;
}
function records(){
	return _records;
}
function recordForItem(item){
	// item に相当するレコードを返す
	for (num in _records){
		var rec = _records[num];
		if (rec.item == item) return rec;
	}
	return null;
}

function target(){
	var item = document.getElementById("target").value;
	if (item == "主訴") 
		return "ProgressSection.subject";
	if (item == "病名")
		return "ProgressSection.disease";
	else if (item == "診療内容")
		return "ProgressSection.treatment";
	else if (item == "曜日")
		return "week";
	else
		return "";
}

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

function checkedUp(){
	if ((xmlHttpObject.readyState == 4) && (xmlHttpObject.status == 200)){
		var value = xmlHttpObject.responseText;
		//alert("=== checkedUp ===\n"+value); //##
		var array = value.split("<SEPARATOR>");
		if (array.length > 1){
			var obj = eval('(' + array[1] + ')');
			//alert(encodeObject(obj)); //##
			var recs = new Array();
			for (subject in obj){
				// SUBJECT
				var sbj = (subject.length > 20)
				? subject.substr(0,20) + " ..." : subject;
				if (sbj.length == 0) sbj = "*** 再来 ***";
				
				// FREQUENCY
				var count = 0;
				var subjObj = obj[subject];
				for (num in subjObj){ count++; }
				
				// RECORD
				var rec = new Object();
				rec.item = sbj;
				rec.freq = count;
				rec.children = subjObj;
				
				recs.push(rec);
			}
			recs.sort(compareFreq);
			setRecords(recs);

			showResults();
		}
		hideMessage("_message");
	} else 
		showMessage("_message", "Loading records ...");
}
function checkUp(){
	xmlHttpObject = createXMLHttpRequest(checkedUp);
	if (xmlHttpObject){ // GETパラメータ付きでリクエスト送信
		// サーバとの約束事
		var array = new Array();
		array["fromDate"] = document.getElementById("from").value;
		array["toDate"] = document.getElementById("to").value;
		array["target"] = target();
		
		//_receiver = receiver; // 結果を受け付けるメソッドを記憶
		var st = "./server.php?command=GET_STATISTICS"
		+ "&value=" + encodeObject(array);
		//alert(st); //return; //##
		xmlHttpObject.open("GET", encodeURI(st), true);
		xmlHttpObject.send(null);
	}
}

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

			showPatient(obj);
		}
		hideMessage("_message");
	} else 
		showMessage("_message", "Loading records ...");
}
function getPatient(pid, date){
	// pid, date の ProgressSection をサーバへリクエスト
	xmlHttpObject = createXMLHttpRequest(gotPatient);
	if (xmlHttpObject){ // GETパラメータ付きでリクエスト送信
		// サーバとの約束事
		var array = new Array();
		array["patientId"] = pid;
		array["entryDate"] = date;
		array["target"] = target();
		
		//_receiver = receiver; // 結果を受け付けるメソッドを記憶
		var st = "./server.php?command=GET_PATIENT"
		+ "&value=" + encodeObject(array);
		//alert(st); //return; //##
		xmlHttpObject.open("GET", encodeURI(st), true);
		xmlHttpObject.send(null);
	}
}

function gotTable(){
	if ((xmlHttpObject.readyState == 4) && (xmlHttpObject.status == 200)){
		var value = xmlHttpObject.responseText;
		//alert("=== gotTable ===\n"+value); //##
        
		var array = value.split("<SEPARATOR>");
		if (array.length > 1){
			if (array[1].length > 0){
				var array = eval('(' + array[1] + ')');
                
				// 高精度検索の場合は１行目に "高精度" が入っている
				if (array[0] == "高精度"){
					setPrecision(1);
					array.splice(0, 1);
				} else
					setPrecision(0);
				setPreference(array);
			}
		}
	}
}
function getTable(){
	// テーブルの内容をサーバへリクエスト
	xmlHttpObject = createXMLHttpRequest(gotTable);
	if (xmlHttpObject){ // GETパラメータ付きでリクエスト送信
		// サーバとの約束事
		var array = new Array();
		array["tableName"] = tableName();
		
		//_receiver = receiver; // 結果を受け付けるメソッドを記憶
		var st = "./server.php?command=GET_TABLE_CONTENTS"
		+ "&value=" + encodeObject(array);
		
        //alert(st); //return; //##
		xmlHttpObject.open("GET", encodeURI(st), true);
		xmlHttpObject.send(null);
	}
}

function savedTable(){
	if ((xmlHttpObject.readyState == 4) && (xmlHttpObject.status == 200)){
		var value = xmlHttpObject.responseText;
		//alert("=== savedTable ===\n"+value); //##
		alert("設定はサーバに保存されました");
	}
}
function saveTable(){
	// 初期設定のテーブルをサーバへ保存
	xmlHttpObject = createXMLHttpRequest(savedTable);
	if (xmlHttpObject){ // GETパラメータ付きでリクエスト送信
		var array = source();
		if (precision() && (precision() > 0)){
			// 高精度検索の場合は１行目に "高精度" が入る
			array.splice(0, 0, "高精度");
		}
		var value = encodeObject(source());
		// サーバとの約束事
		var array = new Array();
		array["tableName"] = tableName();
		array["value"] = encodeSTRING(value);
		array["precision"] = precision(); // 精度
		
		//_receiver = receiver; // 結果を受け付けるメソッドを記憶
		var st = "./server.php?command=PUT_TABLE_CONTENTS"
		+ "&value=" + encodeObject(array);
		//alert(st); //return; //##
		xmlHttpObject.open("GET", encodeURI(st), true);
		xmlHttpObject.send(null);
	}
}

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

function compareItem(a, b){
	// a, b を主訴でソート
	var st1 = a.item;
	var st2 = b.item;
	for (var i=0,ct=st1.length; i < ct; i++){
		if (st2.length < i) return 0;
		var ch1 = st1.charAt(i);
		var ch2 = st2.charAt(i);
		if (ch1 < ch2)
			return -1;
		else if (ch2 < ch1)
			return 1;
	}
	
	return 1;
}
function compareFreq(a, b){
	// a, b を freq でソート
	return (b.freq - a.freq);
}

function sortWithItem(){
	// 主訴でソート
	var recs = records();
	recs.sort(compareItem);
	setRecords(recs);
	
	showResults();
}
function sortWithFreq(){
	// 頻度でソート
	var recs = records();
	recs.sort(compareFreq);
	setRecords(recs);
	
	showResults();
}

function graph(item, max){
	// item に相当する頻度のグラフを返す
	var obj = recordForItem(item);

	// 最高値が星１００個以内におさまるよう星１個がカバーする範囲を調整
	var width = (max > 0) ? (max / 100) : 1;
	if (width < 1) width = 1;
	
	for (var ln="",i=0; i < obj.freq; i+=width) ln += "*";

	return ln;
}

var _patientObj;
function showPatient(obj){
	// 主訴欄の内容を表示
	var elm = document.getElementById(obj.entryDate);
	var len = elm.innerHTML.length;
	elm.innerHTML = "";
	
	// 開いている患者情報があれば閉じる
	if (_patientObj){
		_patientObj.elm.innerHTML = _patientObj.value;
		if (_patientObj.elm == elm) return;
	}
	
	var tbl = newTABLE(elm, "baseTable");
	tbl.style.backgroundColor = "#fff";
	tbl.style.border = "thin solid #888";
	
	var tr = newTR(tbl, "title", "");
	var td = newTD(tr, "", obj.patientId + " " + obj.patientName);
	td.style.width = "150px";
	
	var buff = replaceAll(obj.subject, '\n', '<br/>');
	var tr = newTR(tbl, "", "");
	var td = newTD(tr, "", "");
	td.innerHTML = buff;
	td.style.backgroundColor = "#ffd";
	
	_patientObj = new Object();
	_patientObj.elm = elm;
	_patientObj.value = obj.patientId;
}

var _dateObj;
function showDate(num, item, max){
	// item に相当する全レコードの 受診日・カルテID を表示
	var elm = document.getElementById("graph." + num);
	elm.innerHTML = "";
	
	// 開いている患者情報があれば閉じる
	if (_dateObj){
		_dateObj.elm.innerHTML = _dateObj.value;
		if (_dateObj.elm == elm) return;
	}
	
	var tbl = newTABLE(elm, "baseTable");
	tbl.style.backgroundColor = "#fff";
	
	var tr = newTR(tbl, "title", "");
	var td = newTD(tr, "", "受診年月日");
	td.style.width = "150px";
	var td = newTD(tr, "", "カルテID");
	
	// 受診日・カルテID をリストアップ
	var record = recordForItem(item);
	var children = record.children;
	for (num in children){
		var rec = children[num];
		var tr = newTR(tbl, "", "");
		var td = newTD(tr, "", rec.date);
		td.setAttribute("onmouseout","resetColor(this,'#000','#fff')");
		td.setAttribute("onmouseover","setColor(this,'#ff0','#00f')");
		td.style.width = "150px";
		var action = "getPatient('"+rec.id+"','"+rec.date+"')"
		td.setAttribute("onclick", action);
		// ### ここで名前検索を行うと検索範囲が広いためパフォーマンスがかなり落ちる
		var value = rec.id; // + " " + rec.name;
		var td = newTD(tr, rec.date, value);
	}
	_dateObj = new Object();
	_dateObj.elm = elm;
	_dateObj.value = graph(item, max);
}

function showResults(){
	// 結果を表示
	var elm = document.getElementById("resultArea");
	elm.innerHTML = "";
	var tbl = newTABLE(elm, "baseTable");
	
	var tr = newTR(tbl, "tool-bar", "");
	var td = newTD(tr, "", "");
	var a = newA(td, "項目", "#", "");
	a.setAttribute("onclick", "sortWithItem()");
	var td = newTD(tr, "", "");
	var a = newA(td, "頻度", "#", "");
	a.setAttribute("onclick", "sortWithFreq()");
	var td = newTD(tr, "", "グラフ");
	
	// 最高頻度を検出
	var max = 0;
	var array = records();
	for (num in array){
		var obj = array[num];
		if (max < obj.freq) max = obj.freq;
	}

	// 結果を表示
	for (num in array){
		var obj = array[num];
		
		// 主訴
		var tr = newTR(tbl, "", "");
		var td = newTD(tr, "cell", obj.item);
		var action = "showDate('"+num+"','"+obj.item+"','"+max+"')";
		td.setAttribute("onclick", action);
		td.setAttribute("onmouseout","resetColor(this,'#000','#fff')");
		td.setAttribute("onmouseover","setColor(this,'#ff0','#00f')");
		
		// 頻度
		var td = newTD(tr, "cell", "" + obj.freq);
		td.style.textAlign = "right";
		
		// グラフ
		var td = newTD(tr, "graph."+num, graph(obj.item, max));
	}
}

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

function initStatistics(){
	var elm = document.getElementById("base");
    
    // === HEADER ===============
    var div = newDIV(elm, "tool-header");
    var dv = newDIV(div, "left-side");
    var tl = newDIV(dv, "/titleBar");
    tl.innerHTML = "診療統計";
    tl.style.paddingTop = "0px";
    var dv = newDIV(div, "right-side");
	var im = newIMAGE(dv, "", "./hammer.png", "?");
	im.setAttribute("onclick", "openPreference()");
	im.style.height = "15px";
    im.style.position = "relative";
    im.style.bottom = "1px";
    var sp = newSPAN(dv, "");
    sp.style.paddingLeft = "5px";
	var im = newIMAGE(sp, "", "./Help.png", "?");
	im.setAttribute("onclick", "help()");
	im.style.height = "18px";
	im.style.verticalAlign = "bottom";
    im.style.position = "relative";
    im.style.bottom = "2px";
    
    // === CONTENTS ===============
	var tbl = newTABLE(elm, "baseTable");
	var array = today().split("-");
	var yyyy = array[0];
	
	// 年月日範囲指定エリア
	var tr = newTR(tbl, "", "");
	var td = newTD(tr, "", "");
	var sp = newSPAN(td, "fromDate");
    newDatePopUp(sp, "from", "", yyyy, 1, 1, false);
	var tx = newTEXT(td, "から ");
	var sp = newSPAN(td, "toDate");
    newDatePopUp(sp, "to", "", yyyy, 12, 31, false);
	var tx = newTEXT(td, "の範囲で");

	// 項目指定エリア
	var tr = newTR(tbl, "", "");
	var td = newTD(tr, "", "");
	var array = ["主訴","病名","診療内容","曜日"];
	var pu = makePopupMenu(td, "target", array, "");
	var tx = newTEXT(td, " を ");
	var bt = newDIV(td, "/whiteButton");
    bt.innerHTML = "リストアップ";
	bt.setAttribute("onclick", "checkUp()");
	
	// 統計表示エリア
	var tr = newTR(tbl, "", "");
	var td = newTD(tr, "resultArea", "");
	
    // === FOOTER ===============
    var div = newDIV(elm, "tool-footer");
    var dv = newDIV(div, "left-side");
    dv.innerHTML = version();
    dv.style.position = "relative";
    dv.style.top = "3px";
	
	// メッセージ・エリア
	var dv = newDIV(elm, "message");
}

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

