
var _nodeName; // Global 変数

function setTagetField(nodeName){
	_nodeName = nodeName;
}
function targetField(){
	return _nodeName;
}

var _scanDataURL;
function setScanDataURL(url){
    _scanDataURL = url;
}
function scanDataURL(){
    // 保険証画像データの URL を返す
    return _scanDataURL;
}

/////////////////////////
///// カルテからの継承値 ///

function noa(){
    if (window.opener.name == "noa"){
        return window.opener;
    } else if (window.opener.name == "tools"){
        return window.opener.top.noa;
    } else if (window.top.noa){
        return window.top.noa;
    } else {
        alert("ERROR *** insurance.js: window.opener としての NOA が見つかりません");
        return null;
    }
}

///// カルテからの継承値 ///
/////////////////////////

////////////////////////////////
/// neuron.js による処理 /////////

function showSearchResult(answer){
	// サーバから返された保険者番号に相当する "保険者名_|_電話番号" を表示
    var obj = JSON.parse(answer);

    for (fieldname in obj){
        var value = obj[fieldname];
        
        if (fieldname == "shubetsu"){
            shubetsuSelected(value);
        } else {
            if (value.indexOf("HealthInsurance") >= 0) value = "";
            
            var tag = "HealthInsurance." + fieldname;
            document.getElementById(tag).value = value;
        }
    }
}
function search(){
	// 保険者番号に一致する保険者名・電話番号を検索し表示
	var ownerNumber = document.getElementById("_ownerNumber").value;
    
    if (trim(ownerNumber).length > 0)
        NRGetInsurance(ownerNumber, showSearchResult);
}

function setValueToDatePopup(tag, val){
	// 年月日入力フィールドにデータをセット
	var yy = 0;
	var mm = 0;
	var dd = 0;
	if (val.length){
		var array = val.split("-");
		var yy = array[0] * 1;
		var mm = (array.length > 1) ? array[1] * 1 : 0;
		var dd = (array.length > 2) ? array[2] * 1 : 0;
	}
	
	//var label = "平成"; // (yy > 0) ? nengou(yy) : "平成"; // 西暦に相当する年号
    var elm = document.getElementById(tag+"_area");
    
    // newDatePopUp() は tag+"_pop" を id とする隠しフィールドに値を保持
    newDatePopUp(elm, tag+"_pop", "平成", yy, mm, dd, false);
}
function showValues(answer){
	// {'table.field':'value','table.field':'value'},{'table.field':'value'} 形式
	//alert("=== showValues ===\n"+answer); //##
	var obj = eval('(' + answer + ')');
	//alert("=== showValues ===\n"+encodeObject(obj)); //##
	for (tag in obj){
		// 'table.field':'value' 形式
		if (typeof(obj[tag]) != "string") continue;
		
		var val = trim(obj[tag]);
		val = pureValue(val); // "<PAST></PAST>" を削除
		if (val.length > 0){
			var elm = document.getElementById(tag);
			if (elm) elm.value = val;
		}
		if (isSame(tag, "PublicInsurance.startDate"))
			setValueToDatePopup(tag, val);
		else if (isSame(tag, "PublicInsurance.expiredDate")) 
			setValueToDatePopup(tag, val);
		else if (isSame(tag, "HealthInsurance.startDate")) 
			setValueToDatePopup(tag, val);
		else if (isSame(tag, "HealthInsurance.expiredDate")) 
			setValueToDatePopup(tag, val);
	}

    // 保険証画像のスキャンされた日付をリクエスト
    getInsScanDate();
}
function getValues(){
	// 保険証データをサーバから取得し表示
    var owner = noa().owner();
    var pid = noa().patient_id();
    var date = noa().currentDate();
	NRGetPage(owner, pid, date, "", tags(), showValues);
	
	function tags(){
		// 保険証のDBタグをカンマ区切りの配列にして返す
		var array = new Array();
		array.push("HealthInsurance.shubetsu");
		array.push("HealthInsurance.kubun");
		array.push("HealthInsurance.paymentRatio");
		array.push("HealthInsurance.discountRatio");
		array.push("HealthInsurance.kigou");
		array.push("HealthInsurance.bangou");
		array.push("HealthInsurance.ownerNumber");
		array.push("HealthInsurance.ownerName");
		array.push("HealthInsurance.ownerPhone");
		array.push("HealthInsurance.confirmation");
		array.push("HealthInsurance.startDate");
		array.push("HealthInsurance.expiredDate");
		array.push("PublicInsurance.shubetsu");
		array.push("PublicInsurance.ownerName");
		array.push("PublicInsurance.ownerNumber");
		array.push("PublicInsurance.recipientNumber");
		array.push("PublicInsurance.paymentRatio");
		array.push("PublicInsurance.payment");
		array.push("PublicInsurance.startDate");
		array.push("PublicInsurance.expiredDate");
		return array.join(",");
	}
}

function gotInsScanDate(answer){
    // 保険証画像のスキャンされた日付を表示
    //alert("gotInsScanDate->"+answer); //##
    var obj = JSON.parse(answer);
    //alert("gotInsScanDate->"+encodeObject(obj)); //##
    
    // obj.files[0] は "02288001_20120412155531.JPG" 形式
    var fileNames = obj.files;
    var idAndDateTime = "";
    for (num in fileNames){
        idAndDateTime = fileNames[num];

        var array = idAndDateTime.split("_");
        if (array.length > 2) continue;
        
        // 最新の日付順になっているので最初のレコードを取得
        break;
    }
    
    var elm = document.getElementById("scanDateArea");
    elm.innerHTML = "";

    if (idAndDateTime.length){
        var array = idAndDateTime.split("_");
        var datetime = array[1];
        if (datetime.length){
            var yyyy = datetime.substr(0, 4);
            var mm = datetime.substr(4, 2);
            var dd = datetime.substr(6, 2);
            var hour = datetime.substr(8, 2);
            var min = datetime.substr(10, 2);
            var sec = datetime.substr(12, 2);
            var date = yyyy+"-"+mm+"-"+dd+" "+hour+":"+min+":"+sec;
            
            var dv = newDIV(elm, "");
            dv.style.padding = "0px 2px";
            dv.innerHTML = date;
            dv.setAttribute("onclick", "showScanData()");
            setChangeColor(dv, '#000', '#dfe');
        }
        
        // 保険証画像の URL を記憶
        setScanDataURL(obj.path + "/" + idAndDateTime);
    }
}
function getInsScanDate(){
    // 保険証画像のスキャンされた日付をリクエスト
    NRGetInsrance(noa().patient_id(), gotInsScanDate);
}

function saved(answer){
	// rowid のレコードをサーバから読込み
	// answer は debug 用メッセージのみ

	// 基本情報画面を reload
//    noa().setCurrentBasicId(null); // toggle を抑止
//	noa().getBasicPage(noa().currentDate());
}
function saveIns(){
	// 確定された値をサーバへ保存
	document.getElementById("message").innerHTML = "";
	
    var owner = noa().owner();
    var pid = noa().patient_id();
    var date = noa().currentDate();
	NRPutPage(owner, pid, date, "", tagAndVals(), saved);
	makeConfirmation();
	
	function tagAndVals(){
		// server の command 受け側との約束ごと
		var array = new Array();
		setKeyAndValue(array, "HealthInsurance.shubetsu");
		setKeyAndValue(array, "HealthInsurance.kubun");
		setKeyAndValue(array, "HealthInsurance.paymentRatio");
		setKeyAndValue(array, "HealthInsurance.discountRatio");
		setKeyAndValue(array, "HealthInsurance.kigou");
		setKeyAndValue(array, "HealthInsurance.bangou");
		setKeyAndValue(array, "HealthInsurance.ownerNumber");
		setKeyAndValue(array, "HealthInsurance.ownerName");
		setKeyAndValue(array, "HealthInsurance.ownerPhone");
		setKeyAndValue(array, "HealthInsurance.confirmation");
		setKeyAndValueForDate(array, "HealthInsurance.startDate");
		setKeyAndValueForDate(array, "HealthInsurance.expiredDate");
		setKeyAndValue(array, "PublicInsurance.shubetsu");
		setKeyAndValue(array, "PublicInsurance.ownerName");
		setKeyAndValue(array, "PublicInsurance.ownerNumber");
		setKeyAndValue(array, "PublicInsurance.recipientNumber");
		setKeyAndValue(array, "PublicInsurance.paymentRatio");
		setKeyAndValue(array, "PublicInsurance.payment");
		setKeyAndValueForDate(array, "PublicInsurance.startDate");
		setKeyAndValueForDate(array, "PublicInsurance.expiredDate");
		return array;
		
		function setKeyAndValue(arry, tag){
			array[tag] = document.getElementById(tag).value;
		}
		
		function setKeyAndValueForDate(arry, tag){
            // newDatePopUp() は tag+"_pop" を id とする隠しフィールドに値を保持
            array[tag] = document.getElementById(tag+"_pop").value;
		}
	}
	
	function makeConfirmation(){
		// 保険情報の確認パネルを生成
		var elm = document.getElementById("_confirm");
		elm.innerHTML = "";
		var tbl = newTABLE(elm, "");
		makeLine(tbl, "保険者番号", "HealthInsurance.ownerNumber");
		makeLine(tbl, "保険者名", "HealthInsurance.ownerName");
		makeLine(tbl, "保険種別", "HealthInsurance.shubetsu");
		makeLine(tbl, "区分", "HealthInsurance.kubun");
		makeLine(tbl, "負担率", "HealthInsurance.paymentRatio","#ec9");
		makeLine(tbl, "割引率(%)", "HealthInsurance.discountRatio");
		makeLine(tbl, "記号", "HealthInsurance.kigou");
		makeLine(tbl, "番号", "HealthInsurance.bangou");
		makeLine(tbl, "資格取得", "HealthInsurance.startDate", null, true);
		makeLine(tbl, "有効期限", "HealthInsurance.expiredDate", null, true);
		
		makeLine(tbl, "公費種別", "PublicInsurance.shubetsu");
		makeLine(tbl, "公費名称", "PublicInsurance.ownerName");
		makeLine(tbl, "負担番号", "PublicInsurance.ownerNumber");
		makeLine(tbl, "受給番号", "PublicInsurance.recipientNumber");

        var tr = newTR(tbl, "", "");
        var td = newTD(tr, "right-side", "");
        td.setAttribute("colspan", "2");
        var dv = newDIV(td, "/closeButton");
        dv.innerHTML = "X";
        dv.style.color = "#000";
        dv.setAttribute("onclick", "closeFloatPanel()");

		openFloatPanel(tbl, 5, 10, "保険証確認パネル");
		
		function makeLine(tbl, key, tag, bgcolor, isDate){
			if (isDate){
                // newDatePopUp() は tag+"_pop" を id とする隠しフィールドに値を保持
                var val = document.getElementById(tag+"_pop").value;
				val = wareki(val);
			} else
                var val = trim(document.getElementById(tag).value);
			// label
			var tr = newTR(tbl, "", "");
			var td = newTD(tr, "", key);
			td.style.fontSize = "9pt";
			td.style.width = "70px";
			td.style.backgroundColor = "ec9"; //＃light brown
			
			// value
			if (val.length){
				var td = newTD(tr, "", val);
				td.style.fontSize = "18pt";
				td.style.color = "#000";
				td.style.fontWeight = "bold";
				td.style.padding = "1px 10px";
				if (bgcolor) td.style.backgroundColor = bgcolor;
			} else {
				var td = newTD(tr, "", "* データがありません *");
				td.style.fontSize = "12pt";
				td.style.color = "#f06"; //red
			}
		}
	}
}

/// neuron.js による処理 /////////
////////////////////////////////

function showScanData(){
    // 保険証画像を表示
    //var url = "../InsViewer?patientId=" + patientId()+"&currentDate="+currentDate();
    //window.open(url, "_blank");
    
    window.open(scanDataURL(), "_blank");
}

function confirmed(){
	var td = document.getElementById("HealthInsurance.confirmation");
	var st = todayAndTime() + " " + noa().owner(); // lib.js
	td.value = st;
}

function shubetsuSelected(item){
	var js = document.getElementById("_shubetsuArea");
	js.innerHTML = "";
	var pm = makePopupMenu(js, "HealthInsurance.shubetsu", insArray(), item);
}

function help(){
	window.open("./insHelp.html","Help"
				,"width=450,height=700,scrollbars=yes,resizable=yes");
}

function changeKouhi(elm){
	// 公費種別ポップアップが変更された時の動作
	var item = elm.value;
	if (isSame(item, " ")){
		// 公費種別：なし で全部をクリアする
		document.getElementById("PublicInsurance.shubetsu").value = " ";
		document.getElementById("PublicInsurance.ownerName").value = " ";
		document.getElementById("PublicInsurance.ownerNumber").value = " ";
		document.getElementById("PublicInsurance.recipientNumber").value = " ";
		document.getElementById("PublicInsurance.paymentRatio").value = " ";
		document.getElementById("PublicInsurance.payment").value = " ";
		// 以下の実態は DatePopup() に存在
		document.getElementById("PublicInsurance.startDate").value = " ";
		document.getElementById("PublicInsurance.expiredDate").value = " ";
	} else {
		// 公費種別に伴い、公費名称・負担率を自動入力
		var array = publicInsObjects();
		var ratio = array[item];
		document.getElementById("PublicInsurance.ownerName").value = item;
		document.getElementById("PublicInsurance.paymentRatio").value = ratio;
	}
}

function checkIns(){
    // 保険の整合性をチェック：必要に応じ自動入力
    var bangou = document.getElementById("HealthInsurance.ownerNumber").value;
    var shubetsu = document.getElementById("HealthInsurance.shubetsu").value;
    
    if ((bangou.substr(0,2) == "39") && (shubetsu == "後期高齢")){
        var td = document.getElementById("kubunArea");
        td.innerHTML = "";
        var array = ["", "本人","家族"];
        var pm = makePopupMenu(td, "HealthInsurance.kubun", array, "本人");
    }
}

function openPanelEditor(){
    // 基本情報パネル・エディターを開く
    window.open("panelEditor.php", "tools");
}

var _hasField;
function showOwnerNumberField(){
	// elm に保険証番号入力フィールドを開く
	if (! _hasField){
		var elm = document.getElementById("showOwnerNumber");
		elm.innerHTML = "";
		var fd = newFIELD(elm, "_ownerNumber", "", 23, "");
        fd.setAttribute("type", "search");
		fd.setAttribute("onkeyup", "search()");
		fd.focus();
		_hasField = true;
	}
}
function initInsurance(){
	var elm = document.getElementById("base");
    elm.innerHTML = "";

    // === HEADER ===
    var div = newDIV(elm, "tool-header");
    div.style.padding = "4px 0 4px 10px";
    // --- LEFT SIDE ---
    var dv = newDIV(div, "/left-side");
    var dv = newDIV(div, "/greenButton");
    dv.innerHTML = "基本情報";
    dv.setAttribute("onclick", "openPanelEditor()");
    var dv = newDIV(div, "/titleLabel");
    dv.innerHTML = "保険情報";
    // --- RIGHT SIDE ---
	var dv = newDIV(div, "/right-side2");
    dv.style.width = "20px";
    // HELP ICON
	var img = newIMAGE(dv, "", "./Help.png", "?");
	img.style.height = "18px";
    img.setAttribute("onclick", "help()");

	// === BODY ===
	var tbl = newTABLE(elm, "base-table");
    tbl.style.fontSize = "9pt";
	var tr = newTR(tbl, "", "");
	var td = newTD(tr, "label", "受診年月日");
	var td = newTD(tr, "", noa().currentDate());

	var tr = newTR(tbl, "", "");
	var td = newTD(tr, "", "");
	var td = newTD(tr, "orcaArea", "");

	var tr = newTR(tbl, "", "");
	var td = newTD(tr, "label", "検索キー");
	var td = newTD(tr, "showOwnerNumber", "");
	var fd = newFIELD(td, "", "", 28, "");
    fd.setAttribute("placeholder", "保険者番号を入れて下さい"); // 入力ヒントを表示
    fd.setAttribute("type", "search");
	fd.setAttribute("onchange", "showOwnerNumberField()");
	fd.setAttribute("onmouseover", "showOwnerNumberField()");
	fd.focus();
	
	var tr = newTR(tbl, "greenField", "");
	var td = newTD(tr, "label", "保険者番号");
	var td = newTD(tr, "", "");
	var fd = newFIELD(td, "HealthInsurance.ownerNumber", "", 15, "");
    fd.setAttribute("class", "cellValue");
	
	var tr = newTR(tbl, "greenField", "");
	var td = newTD(tr, "label", "保険種別");
	var td = newTD(tr, "_shubetsuArea", "");
	var pm = makePopupMenu(td, "HealthInsurance.shubetsu", insArray(), "");
	
	var tr = newTR(tbl, "greenField", "");
	var td = newTD(tr, "label", "保険者名");
	var td = newTD(tr, "", "");
	var fd = newFIELD(td, "HealthInsurance.ownerName", "", 23, "");
    fd.setAttribute("class", "cellValue");
	
	var tr = newTR(tbl, "greenField", "");
	var td = newTD(tr, "label", "電話番号");
	var td = newTD(tr, "", "");
	var fd = newFIELD(td, "HealthInsurance.ownerPhone", "", 15, "");
	fd.setAttribute("type", "tel"); // 電話番号専用入力: Safari は対応せず
    fd.setAttribute("class", "cellValue");
	
	var tr = newTR(tbl, "", "");
    var td = newTD(tr, "label", "区分");
    td.setAttribute("onclick", "checkIns()");
    var td = newTD(tr, "kubunArea", "");
	var array = ["", "本人","家族"];
	var pm = makePopupMenu(td, "HealthInsurance.kubun", array, "");
	
	var tr = newTR(tbl, "", "");
    var td = newTD(tr, "label", "負担率");
	var td = newTD(tr, "", "");
	var array = ["0","1","2","3","10"];
	var pm = makePopupMenu(td, "HealthInsurance.paymentRatio", array, "3");
	
	var tr = newTR(tbl, "", "");
    var td = newTD(tr, "label", "割引(%)");
    var td = newTD(tr, "", "");
	var fd = newFIELD(td, "HealthInsurance.discountRatio", "", 5, "");
    fd.setAttribute("class", "cellValue");
	
	var tr = newTR(tbl, "", "");
    var td = newTD(tr, "label", "記号");
	var td = newTD(tr, "", "");
	var fd = newFIELD(td, "HealthInsurance.kigou", "", 15, "");
    fd.setAttribute("class", "cellValue");
	
	var tr = newTR(tbl, "", "");
    var td = newTD(tr, "label", "番号");
	var td = newTD(tr, "", "");
	var fd = newFIELD(td, "HealthInsurance.bangou", "", 15, "");
    fd.setAttribute("class", "cellValue");
	
	var tr = newTR(tbl, "", "");
	var td = newTD(tr, "label", "資格取得日");
	var td = newTD(tr, "HealthInsurance.startDate_area", "");
	
	var tr = newTR(tbl, "", "");
	var td = newTD(tr, "label", "有効年月日");
	var td = newTD(tr, "HealthInsurance.expiredDate_area", "");
	
    // 保険証イメージ・スキャン日付
	var tr = newTR(tbl, "greenField", "");
	var td = newTD(tr, "label", "保険証画像");
	var td = newTD(tr, "scanDateArea", "年月日");
	// 保険証確認
	var tr = newTR(tbl, "", "");
    tr.style.backgroundColor = "#aec";
	var td = newTD(tr, "label", "");
	var bt = newBUTTON(td, "", "保険証確認");
	bt.setAttribute("onclick", "confirmed()");
	var td = newTD(tr, "", "");
    var st = todayAndTime() + " " + noa().owner(); // lib.js
	var fd = newFIELD(td, "HealthInsurance.confirmation", "", 30, st);
	
	// 公費
	var tr = newTR(tbl, "", "");
    var td = newTD(tr, "label", "公費種別");
	var td = newTD(tr, "", "");
	var items = publicInsItems();
	var pm = makePopupMenu(td, "PublicInsurance.shubetsu", items, "");
	pm.setAttribute("onchange", "changeKouhi(this)");
	
	var tr = newTR(tbl, "", "");
    var td = newTD(tr, "label", "公費名称");
	var td = newTD(tr, "", "");
	var fd = newFIELD(td, "PublicInsurance.ownerName", "", 15, "");
    fd.setAttribute("class", "cellValue");
	
	var tr = newTR(tbl, "", "");
    var td = newTD(tr, "label", "負担番号");
	var td = newTD(tr, "", "");
	var fd = newFIELD(td, "PublicInsurance.ownerNumber", "", 15, "");
    fd.setAttribute("class", "cellValue");
	
	var tr = newTR(tbl, "", "");
    var td = newTD(tr, "label", "受給番号");
	var td = newTD(tr, "", "");
	var fd = newFIELD(td, "PublicInsurance.recipientNumber", "", 15, "");
    fd.setAttribute("class", "cellValue");
	
	var tr = newTR(tbl, "", "");
    var td = newTD(tr, "label", "負担率");
	var td = newTD(tr, "", "");
	var array = [" ","0","1","2","3","10"];
	var pm = makePopupMenu(td, "PublicInsurance.paymentRatio", array, " ");
	
	var tr = newTR(tbl, "", "");
    var td = newTD(tr, "label", "負担額");
	var td = newTD(tr, "", "");
	var fd = newFIELD(td, "PublicInsurance.payment", "", 15, "");
    fd.setAttribute("class", "cellValue");
	
	var tr = newTR(tbl, "", "");
	var td = newTD(tr, "label", "交付年月日");
	var td = newTD(tr, "PublicInsurance.startDate_area", "");
	
	var tr = newTR(tbl, "", "");
	var td = newTD(tr, "label", "有効年月日");
	var td = newTD(tr, "PublicInsurance.expiredDate_area", "");
	
	// === FOOTER ===
    var div = newDIV(elm, "tool-footer");
	var tbl = newTABLE(div, "base-table");
	var tr = newTR(tbl, "", "");
	var td = newTD(tr, "right-side", "");
	td.style.paddingRight = "20px";
	var bt = newBUTTON(td, "", "確定");
	bt.setAttribute("onclick", "saveIns()");
	
	// メッセージ・エリア
	var dv = newDIV(elm, "message");
	
	getValues();
}
