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

function showSearchResult(answer){
    // サーバから返された保険者番号に相当する "保険者名_|_電話番号" を表示
    var obj = JSON.parse(answer);
    //elmFor("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 confirmed(){
    // 保険証確認のタイムスタンプを打つ
    var fd = elmFor("HealthInsurance.confirmation");
    var timestamp = fd.value;
    // 保険証確認フィールドが空ならタイムスタンプを自動入力
    // フィールドが空でも、前回のタイムスタンプが placeholder として表示されている
    if (timestamp.length == 0)
        fd.value = todayAndTime() + " " + parent().owner(); // lib.js
}

function savedIns(answer){
    // 保険情報をサーバから読込み
    // これを NRPutPage() 前に実行してしまうと、データ・ソースがないので何も返ってこない
    var elm = elmFor("contentsArea");
    var sp = newSPAN(elm, "");
    sp.innerHTML = "再読込中 ...";
    sp.style.fontSize = "10pt";
    sp.style.fontColor = "#faa";
    sp.style.padding = "5px";
    
    get_page(owner(), patientId(), currentDate(), showInsurance);
}
function saveIns(){
    // 確定された値をサーバへ保存
    closeFloatPanel();
    confirmed(); // 保険証確認のタイムスタンプを打ち、保存するデータへ反映
    put_page(owner(), patientId(), currentDate(), "", tagAndVals(), savedIns);
    
    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;
        }
    }
}

/// 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 ins_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 を開く
    kick_window("../OrcaAgent", "_blank", kickedWindow);
}

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

function showInsurance(answer){
    // 保険情報をサーバから読み直す：InsViewer での更新を反映させるため
    
    // サーバから得た保険情報をメモリーに再読込
    var obj = JSON.parse(answer);
    setHealthInsuranceObj(obj.healthInsurance);
    setPublicInsuranceObj(obj.publicInsurance);
    //console.log("showInsurance", encodeObject(obj)); //##

    var elm = elmFor("insContentsArea");
    elm.innerHTML = "";

    // === ALERT AREA =======================
    var div = newDIV(elm, "alertArea/alert");
    
    // === 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, "", currentDate()); // 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("onkeyup", "search()");
    fd.focus();
    
    setInsField(obj, tbl, "保険者番号", "HealthInsurance.ownerNumber", null, "#dfe","#ffd");
    setInsPopup(obj, tbl, "保険種別", "HealthInsurance.shubetsu", insArray(), "#dfe");
    setInsField(obj, tbl, "保険者名", "HealthInsurance.ownerName", 30, "#dfe","#ffd");
    setInsField(obj, tbl, "電話番号", "HealthInsurance.ownerPhone", null, "#dfe");
    
    var tr = newTR(tbl, "", "");
    var td = newTD(tr, "/insLabel", "区分"); // LABEL
    var td = newTD(tr, "", ""); // VALUE
    var array = ["本人","家族"];
    var val = value_for_tag(obj, "HealthInsurance.kubun");
    newRADIO(td, "HealthInsurance.kubun", "kubunButtons", array, val);
    
    var items = ["0","1","2","3","10"];
    setInsPopup(obj, tbl, "負担率", "HealthInsurance.paymentRatio", items);
    
    setInsField(obj, tbl, "割引(%)", "HealthInsurance.discountRatio", 5);
    setInsField(obj, tbl, "記号", "HealthInsurance.kigou",null,null,"#ffd");
    setInsField(obj, tbl, "番号", "HealthInsurance.bangou",null,null,"#ffd");
    setInsDate(obj, tbl, "資格取得日", "HealthInsurance.startDate");
    setInsDate(obj, 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, "", "");
    var bt = newDIV(td, "/blueButton");
    bt.innerHTML = "保険証確認";
    bt.setAttribute("onclick", "confirmeClicked()");
    bt.style.marginLeft = "3px";
    var td = newTD(tr, "", "");
    var st = value_for_tag(obj, "HealthInsurance.confirmation");
    var fd = newFIELD(td, "HealthInsurance.confirmation", "", 40, "");
    fd.setAttribute("placeholder", st); // 前回のタイムスタンプを表示
    checkDateOfConfirmation(fd, st, 31); // 確認から31日以上過ぎていれば警告色
    
    // 公費
    var items = publicInsItems();
    var pm = setInsPopup(obj, tbl, "公費種別", "PublicInsurance.shubetsu", items);
    pm.setAttribute("onchange", "changeKouhi(this)");
    
    setInsField(obj, tbl, "公費名称", "PublicInsurance.ownerName",null,null,"#ffd");
    setInsField(obj, tbl, "負担番号", "PublicInsurance.ownerNumber",null,null,"#ffd");
    setInsField(obj, tbl, "受給番号", "PublicInsurance.recipientNumber",null,null,"#ffd");
    
    var items = [" ","0","1","2","3","10"];
    var pm = setInsPopup(obj, tbl, "負担率", "PublicInsurance.paymentRatio", items);
    
    setInsField(obj, tbl, "負担額", "PublicInsurance.payment");
    setInsDate(obj, tbl, "交付年月日", "PublicInsurance.startDate");
    setInsDate(obj, tbl, "有効年月日", "PublicInsurance.expiredDate");
    
    // === FOOTER =================================
    var div = newDIV(elm, "");
    div.style.textAlign = "right";
    div.style.marginTop = "8px";
    div.style.paddingRight = "20px";
    var bt = newDIV(div, "/listMember");
    bt.innerHTML = "ORCA";
    bt.style.marginRight = "10px";
    bt.setAttribute("onclick", "openORCAAgent()");
    var bt = newDIV(div, "/fixButton");
    bt.innerHTML = "確定";
    bt.setAttribute("onclick", "saveIns()");
    bt.style.position = "relative";
    bt.style.bottom = "5px";
    
    // メッセージ・エリア
    var dv = newDIV(elm, "message");

    // 保険証画像のスキャンされた日付をリクエスト
    var args = new Object();
    args["patientId"] = trim(patientId());
    NRCall("GET_INS_IMAGE", args, gotInsScanDate);
    
    
    
    function value_for_tag(obj, tag){
        // tag に対応する値を返す
        // ### parent().valueForTab(tag,currentDate()) では更新に追いつかない ###
        var ary = tag.split(".");
        // Table 名の頭文字は obj 中では小文字になっているので変換
        var table = ary[0];
        if (table == "HealthInsurance") table = "healthInsurance";
        if (table == "PublicInsurance") table = "publicInsurance";
        var field = ary[1];
        var rec = obj[table][field];
        
        return (rec && rec.val) ? rec.val : "";
    }

    function setInsField(obj, tbl, label, tag, fieldLength, bgColor, fieldColor){
        // フィールドを生成
        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, value_for_tag(obj, tag));
        fd.style.fontSize = "12pt";
        if (fieldColor) fd.style.backgroundColor = fieldColor;
    }
    
    function setInsPopup(obj, 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 = value_for_tag(obj, tag);
        if (val.length == 0) val = "3"; // default 値
        var pm = newPopupMenu(td, tag, items, val);
        
        return pm;
    }
    
    function setInsDate(obj, tbl, label, tag){
        // 年月日ポップアップを生成
        var tr = newTR(tbl, "", "");
        var td = newTD(tr, "/insLabel", label); // LABEL
        var val = value_for_tag(obj, 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", "ins_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 getInsurance(){
    // 保険情報ページを開く前に保険情報をサーバから取り直す：InsViewer での更新に対応
    var elm = elmFor("insContentsArea");
    if (elm.style.display != "none"){
        elm.style.display = "none"; // 非表示
    } else {
        elm.style.display = "block"; // 表示
        get_page(owner(), patientId(), currentDate(), showInsurance);
    }
}

