
var _nodeName; // Global 変数
function setTagetField(nodeName){
	_nodeName = nodeName;
}
function targetField(){
	return _nodeName;
}

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

function patientId(){
    return parent().patientId();
}

function currentDate(){
    return parent().currentDate();
}

function owner(){
    return parent().owner();
}

function layouts(){
    return parent().layoutForMode(_ins_);
}

function valForTag(tag){
    // tag に対応する本日の値を返す
    var obj = parent().valueForTag(tag, currentDate());
    
    //if (tag == "HealthInsurance.paymentRatio") alert(tag+"->"+encodeObject(obj)); //##
    
    return (obj && obj.value) ? obj.value : "";
}

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

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

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

    for (fieldname in obj){
        var value = obj[fieldname];
        
        if (fieldname == "shubetsu"){
            shubetsuSelected(value);
        } else {
            if (value.indexOf("HealthInsurance") >= 0) value = "";
            
            var tag = "HealthInsurance." + fieldname;
            var elm = document.getElementById(tag);
            if (elm){
                elm.value = value;
            } else {
                // 該当する保険者が見つからなかった
                var st = document.getElementById("_ownerNumber").value;
                document.getElementById("HealthInsurance.ownerNumber").value = st;
            }
        }
    }
}
function search(){
	// 保険者番号に一致する保険者名・電話番号を検索し表示
	var st = document.getElementById("_ownerNumber").value;
    
    if (trim(st).length > 0){
        // 保険者番号から該当保険者レコードを検索：insurance.js
        var args = new Object();
		args["HealthInsurance.ownerNumber"] = st;
        NRCall("GET_HEALTHINSURANCE_WITH_KEY", args, showSearchResult);
    }
}

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];
        //_debug(num+"->"+idAndDateTime); //##

        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;
            
            elm.innerHTML = date;
        }
    } else {
        elm.innerHTML = "画像読込ツールを起動";
    }
}

function openInsurancePage(answer){
    // 保険証ページを開く
    var obj = JSON.parse(answer);
    parent().setHealthInsuranceObj(obj.healthInsurance);
    parent().setPublicInsuranceObj(obj.publicInsurance);
    
	// 保険情報画面を reload
    initInsurance();
}
function confirmed(){
    // 保険証確認のタイムスタンプを打つ
	var fd = document.getElementById("HealthInsurance.confirmation");
    var timestamp = fd.value;
    // 保険証確認フィールドが空ならタイムスタンプを自動入力
    // フィールドが空でも、前回のタイムスタンプが placeholder として表示されている
    if (timestamp.length == 0)
        fd.value = todayAndTime() + " " + parent().owner(); // lib.js
}

function saved(answer){
	// 保険情報をサーバから読込み
    //alert("saved->"+answer); //##
    
    // これを NRPutPage() 前に実行してしまうと、データ・ソースがないので何も返ってこない
    var elm = document.getElementById("contentsArea");
    var sp = newSPAN(elm, "");
    sp.innerHTML = "再読込中 ...";
    sp.style.fontSize = "10pt";
    sp.style.fontColor = "#faa";
    sp.style.padding = "5px";
    
    get_page(owner(), patientId(), currentDate(), openInsurancePage);
}
function saveIns(){
	// 確定された値をサーバへ保存
    closeFloatPanel();
    confirmed(); // 保険証確認のタイムスタンプを打ち、保存するデータへ反映
    put_page(owner(), patientId(), currentDate(), "", tagAndVals(), saved, true);
	
	function tagAndVals(){
		// server の command 受け側との約束ごと
		var array = new Array();
		setKeyAndValue(array, "HealthInsurance.shubetsu");
		setKeyAndValueForRadio(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");
		setKeyAndValue(array, "HealthInsurance.confirmation");
		setKeyAndValueForDate(array, "PublicInsurance.startDate");
		setKeyAndValueForDate(array, "PublicInsurance.expiredDate");
		return array;
		
		function setKeyAndValue(arry, tag){
			array[tag] = document.getElementById(tag).value;
		}
		
		function setKeyAndValueForRadio(arry, tag){
			array[tag] = checkedRADIO(tag);
		}
		
		function setKeyAndValueForDate(arry, tag){
            // newDatePopUp() は tag+"_pop" を id とする隠しフィールドに値を保持
            array[tag] = document.getElementById(tag+"_pop").value;
		}
	}
}
function fixIns(){
	// 確定された値を確認し保存するかどうか尋ねる
	document.getElementById("message").innerHTML = "";

    // エラーチェック
    var val = trim(document.getElementById("HealthInsurance.shubetsu").value);
    if (val.length == 0){
        alert("保険種別 が空です");
        return;
    }

    // 保険情報の確認パネルを生成
    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");
    td.style.textAlign = "right";
    td.style.paddingBottom = "10px";
    td.style.paddingRight = "10px";
    var dv = newDIV(td, "/whiteButton");
    dv.innerHTML = "とりやめ";
    dv.setAttribute("onclick", "closeFloatPanel()");
    var dv = newDIV(td, "/redButton");
    dv.innerHTML = "保存";
    dv.setAttribute("onclick", "saveIns()");

    openFloatPanel(tbl, 5, 25, "保険証確認パネル");
    
    function makeLine(tbl, key, tag, bgcolor, isDate){
        if (isDate){
            // newDatePopUp() は tag+"_pop" を id とする隠しフィールドに値を保持
            var val = document.getElementById(tag+"_pop").value;
            val = wareki(val);
        } else if (tag == "HealthInsurance.kubun"){
            var val = checkedRADIO(tag);
        } 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 shubetsuSelected(item){
    var tag = "HealthInsurance.shubetsu";
	var elm = document.getElementById(tag + ".area");
	elm.innerHTML = "";
	var pm = newPopupMenu(elm, tag, insArray(), item);
}

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 = newPopupMenu(td, "HealthInsurance.kubun", array, "本人");
    }
}

function openBasicPage(){
    // 基本情報パネル・エディターを開く
	parent().closeTool();
}

function setNow(tag){
    // tag の年月日ポップアップに本日の年月日を設定
    var dv = document.getElementById(tag+".dateArea");
    dv.innerHTML = "";
    
    // 日付ポップアップを表示
    var dateArray = arrayWithDateTime(todayAndTime());
    var yy = dateArray[0];
    var mm = dateArray[1];
    var dd = dateArray[2];
    newDatePopUp(dv, tag+"_pop", "平成", yy, mm, dd, false);
}

function openORCAAgent(){
    // OrcaAgent を開く
    _log(["== openORCAAgent"]); //##
    kick_window("../OrcaAgent", "_blank", kickedWindow);
}

function confirmeClicked(){
    // 保険証確認のタイムスタンプを打つ
	var fd = document.getElementById("HealthInsurance.confirmation");
    // タイムスタンプを自動入力
    fd.value = todayAndTime() + " " + parent().owner(); // lib.js
}

var _hasField;
function showOwnerNumberField(){
	// elm に保険証番号入力フィールドを開く
	if (! _hasField){
		var elm = document.getElementById("showOwnerNumber");
		elm.innerHTML = "";
		var fd = newFIELD(elm, "_ownerNumber", "", 32, "");
        fd.setAttribute("type", "search");
		fd.setAttribute("onkeyup", "search()");
		fd.focus();
		_hasField = true;
	}
}
function showInsurance(answer){
    // 保険情報をサーバから読み直す：InsViewer での更新を反映させるため

    // サーバから得た保険情報をメモリーに再読込
    var obj = JSON.parse(answer);
    for (name in obj.healthInsurance){
        var tag = "HealthInsurance." + name;
        var rec = obj.healthInsurance[name];
        parent().setValueForTag(tag, currentDate(), rec.val);
    }
    for (name in obj.publicInsurance){
        var rec = obj.publicInsurance[name];
        var tag = "PublicInsurance." + name;
        parent().setValueForTag(tag, currentDate(), rec.val);
    }

    // 保険情報を表示
    var elm = document.getElementById("base");
    elm.innerHTML = "";
    var div = newDIV(elm, "alertArea");

    // === HEADER ============================
    var div = newDIV(elm, "/tool-header");
    // --- LEFT SIDE ---
    var dv = newDIV(div, "/left-side");
	var img = newIMAGE(dv, "icon", "./close.png", "X");
    img.style.height = "14px";
	img.setAttribute("onclick", "openBasicPage()");
    img.setAttribute("class", "expandIcon");
    img.style.position = "relative";
    img.style.top = "2px";
    var dv = newDIV(dv, "/title-label");
    dv.innerHTML = "保険情報";
    // --- RIGHT SIDE ---
	var dv = newDIV(div, "/right-side");
    dv.style.width = "20px";
    // HELP ICON
	var img = newIMAGE(dv, "", "./help.png", "?");
	img.style.height = "17px";
    img.setAttribute("onclick", "openHelp('insHelp.html')");
    img.setAttribute("class", "expandIcon");
    img.style.position = "relative";
    img.style.top = "2px";

	// === CONTENTS =========================
    var div = newDIV(elm, "contentsArea");
    
    var div = newDIV(div, "");
    var tbl = newTABLE(div, "/base-table");
    tbl.style.fontSize = "9pt";

    var tr = newTR(tbl, "", "");
    var td = newTD(tr, "/insDateLabel", "受診日"); // LABEL
    var td = newTD(tr, "", valForTag("ProgressSection.entryDate")); // VALUE

    var tr = newTR(tbl, "", "");
    var td = newTD(tr, "/insLabel", "検索キー"); // LABEL
    var td = newTD(tr, "showOwnerNumber", ""); // VALUE
	var fd = newFIELD(td, "_ownerNumber", "", 32, "");
    fd.setAttribute("placeholder", "保険者番号を入れて下さい"); // 入力ヒントを表示
    fd.setAttribute("type", "search");
	fd.setAttribute("onchange", "showOwnerNumberField()");
	fd.setAttribute("onmouseover", "showOwnerNumberField()");
	fd.focus();

    setInsField(tbl, "保険者番号", "HealthInsurance.ownerNumber", null, "#dfe");
    setInsPopup(tbl, "保険種別", "HealthInsurance.shubetsu", insArray(), "#dfe");
    setInsField(tbl, "保険者名", "HealthInsurance.ownerName", 20, "#dfe");
    setInsField(tbl, "電話番号", "HealthInsurance.ownerPhone", null, "#dfe");
    
    var tr = newTR(tbl, "", "");
    var td = newTD(tr, "/insLabel", "区分"); // LABEL
    var td = newTD(tr, "", ""); // VALUE
	var array = ["本人","家族"];
    var val = valForTag("HealthInsurance.kubun");
    newRADIO(td, "HealthInsurance.kubun", "kubunButtons", array, val);
    
	var items = ["0","1","2","3","10"];
    setInsPopup(tbl, "負担率", "HealthInsurance.paymentRatio", items);
    
    setInsField(tbl, "割引(%)", "HealthInsurance.discountRatio", 5);
    setInsField(tbl, "記号", "HealthInsurance.kigou");
    setInsField(tbl, "番号", "HealthInsurance.bangou");
    setInsDate(tbl, "資格取得日", "HealthInsurance.startDate");
    setInsDate(tbl, "有効年月日", "HealthInsurance.expiredDate");

    var tr = newTR(tbl, "", "");
    var td = newTD(tr, "/insLabel", "保険証画像"); // LABEL
	var td = newTD(tr, "scanDateArea", "年月日");
    var pid = patientId();
    var date = currentDate();
    td.setAttribute("onclick", "openInsViewer('" + pid + "','" + date + "')");

    var tr = newTR(tbl, "greenField", "");
    var td = newTD(tr, "/insLabel", ""); // LABEL
	var bt = newBUTTON(td, "", "保険証確認");
	bt.setAttribute("onclick", "confirmeClicked()");
	var td = newTD(tr, "", "");
    var st = valForTag("HealthInsurance.confirmation");
	var fd = newFIELD(td, "HealthInsurance.confirmation", "", 40, "");
    fd.setAttribute("placeholder", st); // 前回のタイムスタンプを表示
    checkDateOfConfirmation(fd, st, 31); // 確認から31日以上過ぎていれば警告色

	// 公費
	var items = publicInsItems();
    var pm = setInsPopup(tbl, "公費種別", "PublicInsurance.shubetsu", items);
	pm.setAttribute("onchange", "changeKouhi(this)");

    setInsField(tbl, "公費名称", "PublicInsurance.ownerName");
    setInsField(tbl, "負担番号", "PublicInsurance.ownerNumber");
    setInsField(tbl, "受給番号", "PublicInsurance.recipientNumber");

	var items = [" ","0","1","2","3","10"];
    var pm = setInsPopup(tbl, "負担率", "PublicInsurance.paymentRatio", items);

    setInsField(tbl, "負担額", "PublicInsurance.payment");
    setInsDate(tbl, "交付年月日", "PublicInsurance.startDate");
    setInsDate(tbl, "有効年月日", "PublicInsurance.expiredDate");
    
	// === 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 = newDIV(td, "/listMember");
    bt.innerHTML = "ORCA";
    bt.style.marginRight = "10px";
	bt.setAttribute("onclick", "openORCAAgent()");
	var bt = newDIV(td, "/whiteButton");
    bt.innerHTML = "確定";
	bt.setAttribute("onclick", "fixIns()");
	
	// メッセージ・エリア
	var dv = newDIV(elm, "message");
    
    // 保険証画像のスキャンされた日付をリクエスト
    var args = new Object();
    args["patientId"] = trim(patientId());
    NRCall("GET_INS_IMAGE", args, gotInsScanDate);

   
    
    function setInsField(tbl, label, tag, fieldLength, bgColor){
        // フィールドを生成
        var tr = newTR(tbl, "", "");
        if (bgColor) tr.style.backgroundColor = bgColor;
        var td = newTD(tr, "/insLabel", label); // LABEL
        var td = newTD(tr, "", "");
        var len = (fieldLength) ? fieldLength : 15;
        var fd = newFIELD(td, tag, "", len, valForTag(tag));
    }
    
    function setInsPopup(tbl, label, tag, items, bgColor){
        // ポップアップを生成
        var tr = newTR(tbl, "", "");
        if (bgColor) tr.style.backgroundColor = bgColor;
        var td = newTD(tr, "/insLabel", label); // LABEL
        var td = newTD(tr, tag + ".area", ""); // VALUE
        var val = valForTag(tag);
        if (val.length == 0) val = "3"; // default 値
        var pm = newPopupMenu(td, tag, items, val);
        
        return pm;
    }
    
    function setInsDate(tbl, label, tag){
        // 年月日ポップアップを生成
        var tr = newTR(tbl, "", "");
        var td = newTD(tr, "/insLabel", label); // LABEL
        var val = valForTag(tag);
        if (val && (val.length > 0)){
            var array = separateYYMMDD(val);
            var yy = array[1];
            var mm = array[2];
            var dd = array[3];
        } else {
            yy = ""; mm = ""; dd = "";
        }
        
        var td = newTD(tr, tag + "_area", ""); // VALUE
        var sp = newSPAN(td, "");
        sp.innerHTML = "";
        sp.style.paddingRight = "5px";
        var img = newIMAGE(sp, "", "./timer-set.png", "time");
        img.style.height = "14px";
        img.setAttribute("onclick", "setNow('" + tag +"')");
        img.style.position = "relative";
        img.style.top = "5px";
        img.setAttribute("class", "expandIcon");
        var dv = newSPAN(td, tag+".dateArea");

        // newDatePopUp() は tag+"_pop" を id とする隠しフィールドに値を保持
        newDatePopUp(dv, tag+"_pop", "平成", yy, mm, dd, false);
    }
    function checkDateOfConfirmation(elm, dateAndName, days){
        // 確認から30日以上過ぎていれば警告色
        var dateTime = dateAndName.substr(0, 19); // 取扱者名を排除し日時のみ取り出す
        var diffDays = daysBetween(dateTime, todayAndTime());
        if (diffDays > days){
            elm.style.backgroundColor = "#fee";
        }
    }
}
function initInsurance(){
    // 保険情報ページを開く前に保険情報をサーバから取り直す：InsViewer での更新に対応
    get_page(owner(), patientId(), currentDate(), showInsurance);
}

