
/////////////////////////////////////////////////////////
///// FRONT からパラメータ渡し /////////////////////////////

function owner(){
    return document.getElementById("_owner").value;
}

function patientKanjiName(){
    return document.getElementById("_patientKanjiName").value;
}

function patient_id(){
    return document.getElementById("_patientId").value;
}

var _currentDate;
function setCurrentDate(date){
    _currentDate = date;
}
function currentDate(){
    if (_currentDate)
        return _currentDate;
    else
        return document.getElementById("_currentDate").value;
}

///// FRONT からパラメータ渡し /////////////////////////////
/////////////////////////////////////////////////////////

var _viewerRecords;
function setViewerRecords(obj){
    // viewer のデータを記憶
    _viewerRecords = obj;
}
function setViewRecordForTag(value, tag){
    // tag に相当する値を value で置換
    _viewerRecords[tag] = value;
}
function viewerValueForTag(tag){
    // tag に相当する値を返す
    return _viewerRecords[tag];
}


function labelForKey(key){
    // key に対応するラベルを決め打ちで返す
    if (key == "ProgressSection.entryDate") return "日付";
    else if (key == "ProgressSection.subject") return "主訴";
    else if (key == "ProgressSection.object") return "所見";
    else if (key == "ProgressSection.assessment") return "考察";
    else if (key == "ProgressSection.plan") return "予定";
    else if (key == "ProgressSection.examination") return "検査";
    else if (key == "ProgressSection.prescription") return "処方";
    else if (key == "ProgressSection.disease") return "病名";
    else if (key == "ProgressSection.treatment") return "治療";
    
    else if (key == "AddressSection.address") return "住所";
    else if (key == "AddressSection.phone") return "電話";
    else if (key == "AddressSection.email") return "e-mail";

    else if (key == "HealthInsurance.ownerName") return "保険者名";
    else if (key == "HealthInsurance.ownerNumber") return "保険者番号";
    else if (key == "HealthInsurance.ownerPhone") return "保険者電話";
    else if (key == "HealthInsurance.shubetsu") return "種別";
    else if (key == "HealthInsurance.kubun") return "区分";
    else if (key == "HealthInsurance.kigou") return "記号";
    else if (key == "HealthInsurance.bangou") return "番号";
    else if (key == "HealthInsurance.continuedDiseases") return "継続疾病";
    else if (key == "HealthInsurance.paymentRatio") return "負担率";
    else if (key == "HealthInsurance.discountRatio") return "割引(%)";
    else if (key == "HealthInsurance.confirmation") return "保険証確認";
    else if (key == "HealthInsurance.startDate") return "資格取得日";
    else if (key == "HealthInsurance.expiredDate") return "有効年月日";
    
    else if (key == "PublicInsurance.ownerName") return "公費名称";
    else if (key == "PublicInsurance.ownerNumber") return "負担番号";
    else if (key == "PublicInsurance.recipientNumber") return "受給番号";
    else if (key == "PublicInsurance.shubetsu") return "公費種別";
    else if (key == "PublicInsurance.paymentRatio") return "負担率";
    else if (key == "PublicInsurance.payment") return "負担額";
    else if (key == "PublicInsurance.startDate") return "交付日";
    else if (key == "PublicInsurance.expiredDate") return "有効期限";
    else return key;
}

////////////////////////////////////////////////////////////
///// viewer エディター //////////////////////////////////////

function selected_town(elm){
    // 町村が選択された：ポップアップの当道府県・市区・町村を編集欄に転記
    var pref = elmFor("prefPop").value;
    var city = elmFor("cityPop").value;
    var town = elm.value;
    
    var fd = elmFor("AddressSection.address.field");
    fd.value = pref + " " + city + " " + town + " ";
}
function got_town(answer){
    // 町村メニューを表示
    var menus = [""];
    var array = JSON.parse(answer);
    for (num in array){
        var rec = array[num];
        menus.push(rec.menu);
    }
    
    // 記録された住所から町村名を取り出す
    var st = viewerValueForTag("AddressSection.address");
    var item = "";
    if (st.length > 0){
        var ary = st.split(" ");
        if (ary.length > 2) item = ary[2];
    }
    
    var elm = elmFor("townArea");
    elm.innerHTML = "";
    var pu = newPopupMenu(elm, "townPop", menus, item);
    pu.setAttribute("onchange", "selected_town(this)");
}
function get_town(elm){
    // ポップアップから選択された市区に対応する町村メニューをリクエスト
    var city = elm.value;

    var elm = elmFor("townArea");
    elm.innerHTML = "";
    var sp = newSPAN(elm, "");
    sp.innerHTML = "メニュー読込中...";
    sp.style.color = "#f00";
    sp.style.fontSize = "9pt";
    
    get_address(owner(), city, got_town);
}

function got_city(answer){
    // 都道府県メニューを表示
    var menus = [""];
    var array = JSON.parse(answer);
    for (num in array){
        var rec = array[num];
        menus.push(rec.menu);
    }
    
    // 記録された住所から市区名を取り出す
    var st = viewerValueForTag("AddressSection.address");
    var item = "";
    if (st.length > 0){
        var ary = st.split(" ");
        if (ary.length > 1) item = ary[1];
    }
    
    var elm = elmFor("cityArea");
    elm.innerHTML = "";
    var pu = newPopupMenu(elm, "cityPop", menus, item);
    pu.setAttribute("onchange", "get_town(this)");
    if (item.length > 0) get_town(pu);
}
function get_city(elm){
    // ポップアップから選択された都道府県に対応する市区メニューをリクエスト
    var pref = elm.value;

    var elm = elmFor("cityArea");
    elm.innerHTML = "";
    var sp = newSPAN(elm, "");
    sp.innerHTML = "メニュー読込中...";
    sp.style.color = "#f00";
    sp.style.fontSize = "9pt";

    get_address(owner(), pref, got_city);
}

function got_prefecture(answer){
    // 都道府県メニューを表示
    var menus = [""];
    var array = JSON.parse(answer);
    for (num in array){
        var rec = array[num];
        menus.push(rec.menu);
    }
    
    // 記録された住所から都道府県名を取り出す
    var st = viewerValueForTag("AddressSection.address");
    var item = "";
    if (st.length > 0){
        var ary = st.split(" ");
        item = ary[0];
    }
    
    var elm = elmFor("prefArea");
    elm.innerHTML = "";
    var pu = newPopupMenu(elm, "prefPop", menus, item);
    pu.setAttribute("onchange", "get_city(this)");
    if (item.length > 0) get_city(pu);
}

var _currentTag;
function savedViewerValue(answer){
    // 更新後のデータで CELL を再表示
    var obj = JSON.parse(answer); 
    var tag = _currentTag;
    var value = obj[tag];
    setViewRecordForTag(value, tag);
    
    var elm = elmFor(tag + ".value");
    elm.innerHTML = value;
    
}
function saveViewerValue(tag){
    // エディターの編集内容でサーバを更新
    _currentTag = tag;
    var pid = patient_id();
    var dateTime = currentDate();
    var timeLimit = "24 * 60 * 60"; // 修正可能範囲の秒数を決め打ち
    var container = new Object();
    var value = elmFor(tag + ".field").value;
    container[tag] = value;
    
    // 保存中のメッセージ：value を取得後に実行
    var elm = elmFor(tag + ".value");
    elm.innerHTML = "";
    var sp = newSPAN(elm, "");
    sp.style.color = "#f00";
    sp.innerHTML = "データを保存中...";
        
    NRPutPage(owner(), pid, dateTime, timeLimit, container, savedViewerValue);
}

function openViewEditor(tag){
    // tag に相当する記述欄のエディターを開く
    var elm = elmFor(tag + ".value");
    if (elm.childNodes.length < 2){
        // エディターを開く
        var val = elm.innerHTML;
        elm.innerHTML = "";
        var dv = newDIV(elm, "viewerPopupArea");
        var fd = newFIELD(elm, tag+".field", "", 40, val);
        fd.style.fontSize = "11pt";
        var bt = newBUTTON(elm, "", "確定");
        bt.setAttribute("onclick", "saveViewerValue('" + tag + "')");
        
        if (tag == "AddressSection.address"){
            var sp = newSPAN(dv, "prefArea");
            sp.innerHTML = "メニュー読込中...";
            sp.style.color = "#f00";
            sp.style.fontSize = "9pt";
            var sp = newSPAN(dv, "cityArea");
            var sp = newSPAN(dv, "townArea");
            get_address(owner(), "都道府県", got_prefecture);
        }
    } else {
        // 編集内容を破棄しエディターを閉じる
        elm.innerHTML = viewerValueForTag(tag);
    }
}

///// viewer エディター //////////////////////////////////////
////////////////////////////////////////////////////////////

function gotViewer(answer){
    // Viewer を表示
    //alert("gotViewer->"+answer); //##
    var obj = eval('(' + answer + ')');
    setViewerRecords(obj); // obj を記憶
    //alert("gotViewer->"+encodeObject(obj)); //##

    // 受診日
    var elm = document.getElementById("contentsArea");
    elm.innerHTML = "";
    var tbl = newTABLE(elm, "/base-table");
    tbl.style.fontSize = "11pt";

    for (tag in obj){
        if (tag.indexOf("object") > 0) continue;
        if (tag.indexOf("assessment") > 0) continue;
        
        var value = obj[tag];
        var tr = newTR(tbl, "/viewRow", "");
        if (tag.indexOf("HealthInsurance") >= 0)
            tr.style.backgroundColor = "#ffe";
        else if (tag.indexOf("AddressSection") >= 0)
            tr.style.backgroundColor = "#ffc";
        else
            tr.style.backgroundColor = "#fff";
        
        // LABEL
        var td = newTD(tr, "/labelCol", labelForKey(tag));
        if (tag.indexOf("AddressSection") >= 0){
            td.setAttribute("onclick", "openViewEditor('" + tag + "')");
            td.setAttribute("class", "labelCol2");
        }
        
        // VALUE
        var td = newTD(tr, tag + ".value/valueCol", "");
        td.innerHTML = transferCR(value); // '\n' を <br> に変換
    }
}
function initViewer(){
    // FRONT から起動する電子カルテビューア
    //_initDebug(true); //##
    
    window.document.title = patient_id();

    var elm = document.getElementById("base");
    // HEADER =================================
    var div = newDIV(elm, "/tool-header");
    var dv = newDIV(div, "/labelCol");
    dv.innerHTML = patient_id();
    var dv = newDIV(div, "/valueCol");
    dv.innerHTML = patientKanjiName();
    
    // CONTENTS ===============================
    var div = newDIV(elm, "contentsArea");
    // 読込中のメッセージを示す
    var sp = newSPAN(div, "");
    sp.innerHTML = "サーバへ接続中 ...";
    sp.style.color = "#f00";
    sp.style.fontSize = "10pt";
    
    // FOOTER =================================
    var div = newDIV(elm, "/tool-footer");
    var dv = newDIV(div, "/labelCol");
    dv.innerHTML = version();
    
    _debug("initViewer->"+owner()+"->"+patient_id()+"->"+currentDate()); //##
    
    // FRONT での登録時刻 currentDate() と同日以前直近のレコードをリクエスト
    var args = new Object();
	args["patientId"] = patient_id();
	args["dateTime"] = currentDate();
    NRCall("GET_VIEWER", args, gotViewer);
}

function version(){
    // FRONT から NOA の概要を表示させるためのツール
    return "Ver.140112";
}