
var _orca;
function setORCA(obj){
	// ORCA 接続条件を記憶
    //alert("setORCA->"+obj); //##
	_orca = obj;
}
function ORCA(){
	//var ip = obj.IP;
	//var uid = obj.ID;
	//var pwd = obj.PWD;
    
	return _orca;
}

var _checkStatus;
function setCheckStatus(array){
    _checkStatus = array;
}
function checkStatus(){
    return _checkStatus;
}

var _tags;
function initTags(){
    _tags = new Array();
}
function addTags(obj){
    _tags.push(obj)
}
function tags(){
    // ここで使用されている DB タグ名の配列を返す
    return _tags;
}

function debugMode(){
    // デバッグ・モードか否かを返す
    if (!elmFor("debugBox")) return false;
    
    return (elmFor("debugBox").checked) ? true : false;
}

var _records;
function setRecord(obj){
    _records = obj;
}
function records(){
    // 解析されたデータ・オブジェクトを返す
    return _records;
}

function nemeForTagname(tag){
    // タグ名に対する実名を返す
    var array = dictForTagname(tag);
    if (array){
        return array[0];
    } else {
        return tag;
    }
}
function tablefieldForTagname(tag){
    // タグ名に対する table.field を返す
    var array = dictForTagname(tag);
    if (array && (array[1].length > 1)){
        return array[1];
    } else {
        return "";
//        return tag;
    }
}
function dictForTagname(tag){
    // タグ名に対する辞書オブジェクトを返す
    if (tag == "Patient_ID") 
        return ["患者番号","PatientTable.patientId"];
    else if (tag == "WholeName") 
        return ["漢字氏名","NameSection.patientKanjiName"];
    else if (tag == "WholeName_inKana") return ["カナ氏名",""];
    else if (tag == "Sex") 
        return ["性別","PatientTable.sex"]; // 1:男性、2:女性
    else if (tag == "Address_ZipCode") return ["郵便番号",""];
    else if (tag == "WholeAddress1") 
        return ["住所1","AddressSection.address"];
    else if (tag == "WholeAddress2") return ["住所2",""];
    else if (tag == "PhoneNumber1")
        return ["自宅電話番号","AddressSection.phone"];
    else if (tag == "PhoneNumber2") return ["連絡先電話番号",""];

    else if (tag == "InsuranceProvider_Class") return ["保険の種類",""];
    else if (tag == "Insurance_Combination_Number") return ["保険組合せ番号",""];
    else if (tag == "InsuranceProvider_WholeName")
        return ["保険の制度名称","HealthInsurance.shubetsu"];
    else if (tag == "InsuranceProvider_Number") 
        return ["保険者番号","HealthInsurance.ownerNumber"];
    else if (tag == "HealthInsuredPerson_Symbol") 
        return ["記号","HealthInsurance.kigou"];
    else if (tag == "HealthInsuredPerson_Number")
        return ["番号","HealthInsurance.bangou"];
    else if (tag == "RelationToInsuredPerson") 
        return ["本人家族区分",""]; // 1:本人、 2:家族
    else if (tag == "Certificate_StartDate") 
        return ["適用開始日","HealthInsurance.startDate"];
    else if (tag == "Certificate_ExpiredDate")
        return ["適用終了日","HealthInsurance.expiredDate"];

    else if (tag == "PublicInsurance_Class") return ["公費の種類",""];
    else if (tag == "PublicInsurance_Name") 
        return ["公費の種類名称","PublicInsurance.ownerName"];
    else if (tag == "PublicInsurer_Number")
        return ["負担者番号","PublicInsurance.ownerNumber"];
    else if (tag == "PublicInsuredPerson_Number") 
        return ["受給者番号","PublicInsurance.recipientNumber"];

    else if (tag == "Medical_Class") return ["----- 診療種別区分",""];
    else if (tag == "Medical_Class_Name") return ["診療種別区分名称",""];
    else if (tag == "Medical_Class_Number") return ["回数",""];
    else if (tag == "Medical_Class_Point") return ["剤点数",""];
    else if (tag == "Medical_Class_Money") return ["剤金額（自費金額 労災の円）",""];
    else if (tag == "Medical_Class_code") return ["剤区分(１：包括 ２：治験薬評)",""];
    else if (tag == "Medication_info") return ["診療行為詳細（繰り返し ５０）",""];
    else if (tag == "Medication_Code") return ["コード",""];
    else if (tag == "Medication_Name") return ["名称",""];
    else if (tag == "Medication_Number") return ["数量",""]; // 薬剤・器材の数量、きざみ値以外は１

    else if (tag == "Disease_Information") return ["----- 病名情報",""];
    else if (tag == "Disease_Name") return ["病名",""];
    else if (tag == "Disease_StartDate") return ["開始日",""];
    else if (tag == "Disease_EndDate") return ["転帰日",""];
    else if (tag == "Disease_OutCome") return ["転帰",""]; // F:治癒、D:死亡、C:中止、S:移行
    else return null;
}


////////////////////////////////////////////
/// localStorage ///////////////////////////

function getWindowSize(){
	// Booking のウインドー位置とサイズをサーバへリクエスト
    var size = window.localStorage["orcaWindowSize"];
    
	// サーバから得られたサイズにウインドーを調整する
	if (size){
		var args = size.split(",");
		var x = args[0] * 1;
		var y = args[1];
		var w = args[2];
		var h = args[3];
		// resize を先にしておかないと元が大きいサイズだった場合 moveTo しよう
		// としてもウインドー境界の制限で移動できない場合がある
		window.resizeTo(w, h);
		window.moveTo(x, y);
	}
}
function putWindowSize(){
	// Booking のウインドー位置とサイズをサーバへ記憶
	var x = window.screenLeft;
	var y = window.screenTop - 22;
	var w = window.outerWidth;
	var h = window.outerHeight;
    var array = [x, y, w, h];
    window.localStorage["orcaWindowSize"] = array.join(",");
}

function putOrcaCheckArray(){
    var results = new Array();
    var array = checkList();
    for (num in array){
        var obj = array[num];
        results.push();
        var cb = elmFor(obj.key + ".cb");
        
        if (cb.checked)
            results.push(obj.key);
    }
    //alert("results->"+results); //return; //###
    window.localStorage["orcaCheckedArray"] = results.join(",");
}
function getOrcaCheckArray(){
    // NOA へ転送のため項目がチェックされたキーの配列を返す
    var st = window.localStorage["orcaCheckedArray"];
    return (st) ? st.split(",") : [];
}

/// localStorage ///////////////////////////
////////////////////////////////////////////


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

var _mode;
function setMode(mode){
    _mode = mode;
}
function mode(){
    // POST に添えるコマンド名を返す
    return _mode;
}

function showDom(obj, elment){
    // obj 構造を展開して表示
    if (obj.children){
        var rec = obj.children[0];
        if ((rec.key == "Patient_ID") && (!rec.value)) return;
        if ((rec.key == "Disease_Single_Code") && (!rec.value)) return;
        var rec = obj.children[1];
        if (rec && (rec.key == "Department_Code") && (!rec.value)) return;
    }

	var elm = (elment) ? elment : document.getElementById("contentsArea");
	elm.innerHTML = "";

    var div = newDIV(elm, "");
    div.style.fontSize = "10pt";
    div.style.paddingLeft = "5px";
    div.style.borderTop = "thin solid #aaa";
    if (obj.key == "Medical_Information_child")
        div.style.backgroundColor = "#ec9";
    
    if (obj.key.length > 0){
        // LABEL
        var sp = newSPAN(div, "");
        sp.style.color = "#00f";
        sp.style.fontWeight = "bold";
        sp.innerHTML = obj.key;
        
        // VALUE
        sp = newSPAN(div, "value");
        sp.style.padding = "0 5px";
        sp.innerHTML = obj.value;
        
        if (obj.key == "Medical_Class_Name")
            sp.style.backgroundColor = "#ec9";
        else if (obj.key == "Medication_Name")
            sp.style.backgroundColor = "#ff0";
        else if (obj.key == "Medical_Class_Point") // 点数
            sp.style.backgroundColor = "#faa";
        // 患者一覧
        else if (obj.key == "Patient_ID")
            sp.style.backgroundColor = "#ffa";
        else if (obj.key == "WholeName")
            sp.style.backgroundColor = "#ff0";
        // 病名
        else if (obj.key == "Disease_Name")
            sp.style.backgroundColor = "#ff0";
    }

    // CHILDREN
    if (obj.children){
        // [ 決め打ち ] patientId が空のレコードは表示しない
        // 子供のレコードを表示
        for (num in obj.children){
            var rec = obj.children[num];
            
            // child
            var div = newDIV(elm, "");
            div.style.fontSize = "10pt";
            div.style.paddingLeft = "5px";
            showDom(rec, div);
        }
    }
}

function valueForKeyInRecord(obj, key){
    // obj 構造から key に相当する value を返す
    if (obj.key.length > 0){
        // key に合致するものがあった
        if (obj.key == key)
            return obj.value;
    }
    
    // CHILDREN
    if (obj.children){
        // [ 決め打ち ] patientId が空のレコードは表示しない
        // 子供のレコードを表示
        for (num in obj.children){
            var rec = obj.children[num];
            
            // child
            var val = valueForKeyInRecord(rec, key);
            if (val) return val;
        }
    }

    return "";
}
function childrenForKeyInRecord(obj, key){
    // obj 構造から key に相当する children を返す
    if (obj.key.length > 0){
        // key に合致するものがあった
        if (obj.key == key)
            return obj.children;
    }
    
    // CHILDREN
    if (obj.children){
        // [ 決め打ち ] patientId が空のレコードは表示しない
        // 子供のレコードを表示
        for (num in obj.children){
            var rec = obj.children[num];
            
            // child
            var array = childrenForKeyInRecord(rec, key);
            if (array && array.length) return array;
        }
    }
    
    return null;
}

function domToObject(key, dom){
    // XML 型式の Dom 構造をオブジェクトに変換して返す
    var obj = new Object();
    obj.key = key;
    
    var children = new Array();
    var array = dom.childNodes;
    for (num in array){
        var node = array[num];
        if (node.nodeType == Node.ELEMENT_NODE){
            _debug("name->"+node.nodeName); //##
            
            var attr = node.attributes.getNamedItem("name");
            var name = (attr) ? attr.nodeValue : "";
            _debug("name attribute->"+name); //##
            
            var cld = domToObject(name, node);
            children.push(cld);
        } else if (node.nodeType == Node.TEXT_NODE){
            obj.value = node.nodeValue;
            _debug("value->"+node.value); //##
        }
    }
    if (children.length > 0)
        obj.children = children;
    
    _debug("=== "+encodeObject(obj)); //##
    return obj;

    /* NodeType
    const unsigned short      ELEMENT_NODE                   = 1;
    const unsigned short      ATTRIBUTE_NODE                 = 2;
    const unsigned short      TEXT_NODE                      = 3;
    const unsigned short      CDATA_SECTION_NODE             = 4;
    const unsigned short      ENTITY_REFERENCE_NODE          = 5;
    const unsigned short      ENTITY_NODE                    = 6;
    const unsigned short      PROCESSING_INSTRUCTION_NODE    = 7;
    const unsigned short      COMMENT_NODE                   = 8;
    const unsigned short      DOCUMENT_NODE                  = 9;
    const unsigned short      DOCUMENT_TYPE_NODE             = 10;
    const unsigned short      DOCUMENT_FRAGMENT_NODE         = 11;
    const unsigned short      NOTATION_NODE                  = 12;
     */
}
function dom2ToObject(key, dom){
    // XML2 形式の Dom 構造をオブジェクトに変換して返す
    var obj = new Object();
    obj.key = key;
    
    var children = new Array();
    var array = dom.childNodes;
    for (num in array){
        var node = array[num];
        if (node.nodeType == Node.ELEMENT_NODE){
            var cld = dom2ToObject(node.nodeName, node);
            children.push(cld);
        } else if (node.nodeType == Node.TEXT_NODE){
            obj.value = node.nodeValue;
            _debug(key+"->"+obj.value); //##
        }
    }
    if (children.length > 0)
        obj.children = children;
    
    _debug("=== "+encodeObject(obj)); //##
    return obj;
    
    /* NodeType
     const unsigned short      ELEMENT_NODE                   = 1;
     const unsigned short      ATTRIBUTE_NODE                 = 2;
     const unsigned short      TEXT_NODE                      = 3;
     const unsigned short      CDATA_SECTION_NODE             = 4;
     const unsigned short      ENTITY_REFERENCE_NODE          = 5;
     const unsigned short      ENTITY_NODE                    = 6;
     const unsigned short      PROCESSING_INSTRUCTION_NODE    = 7;
     const unsigned short      COMMENT_NODE                   = 8;
     const unsigned short      DOCUMENT_NODE                  = 9;
     const unsigned short      DOCUMENT_TYPE_NODE             = 10;
     const unsigned short      DOCUMENT_FRAGMENT_NODE         = 11;
     const unsigned short      NOTATION_NODE                  = 12;
     */
}

function gotWithPOST(answer){
    //alert("gotWithPOST ->"+answer);//##
    
    if (window.DOMParser){
        var parser=new DOMParser();
        var xmlDoc=parser.parseFromString(answer,"text/xml");
    } else { // Internet Explorer
        var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async="false";
        xmlDoc.loadXML(answer); 
    }
    
    if (_isXML2){
        var obj = dom2ToObject("root", xmlDoc); // XML2
    } else {
        var obj = domToObject("root", xmlDoc); // XML
    }
    if (debugMode()) alert("obj ===\n"+encodeObject(obj));//##
    
    setRecord(obj);
    if (debugMode()){
        switch(_itemNumber){
            case _basicNumber: showBasicInfo(); break;
            case _patientInfoNumber: showProgressInfo(); break;
            case _diseaseNumber: showDiseaseInfo(); break;
        }
    }
    showDom(obj.children[0]);
}
function getWithPOST(uri, mode, receiver){
    // ORCA へリクエストを POST
    setMode(mode);
    
    var dateTime = parent().currentDate();
    var array = dateTime.split(" ");
    var date = array[0];
    
    var args = new Object();
    args["mode"] = mode;
    args["uri"] = uri;
    args["user"] = ORCA().ID;
    args["pwd"] = ORCA().PWD;
    args["patientId"] = parent().receiptId();
    args["entryDate"] = date;
    
    _postServer("POST_ORCA", "postServer.php", args, receiver);
}

function loadedPreference(answer){
	_debug("loadedPreference->"+answer); //##
    
	var objct = JSON.parse(answer);
	if (objct){
        /*
        {"menuItems":[["ohashi","IP(202.17.213.202)ID(ormaster)PWD(ormaster)","0","15","preference"],["ohashi","1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1","0","2","check"]]}
         ### この配列の順序が上とは異なる可能性あり ###
         */
        
        //alert(encodeObject(objct)); //##
        
        for (num in objct){
            var rec = objct[num];
            var val = rec.value;
            var menuItem = rec.menu;
            
           if (menuItem == "preference"){
                // val:'IP(202.17.213.202)ID(ormaster)PWD(ormaster)'
                var obj = decodeObject(val);
                setORCA(obj);
            } else if (menuItem == "check"){
                // val:"1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1"
                var array = val.split(",");
                setCheckStatus(array);
            }
        }
	}
    
    // window size を読み込む
    getWindowSize();
}
function loadPreference(){
	// 初期設定パネルの内容をサーバへリクエスト
    var owner = parent().owner();
    if (!owner){
        alert("loadPreference *** owner() cannot found");
        return;
    }
    
    get_menu(owner, "ORCA", loadedPreference);
}

function savePreference(){
	// 初期設定パネルの内容をサーバへ保存
	var array = new Array();
	array['IP'] = document.getElementById("ipF").value;
	array['PORT'] = document.getElementById("portF").value;
	array['ID'] = document.getElementById("uidF").value;
	array['PWD'] = document.getElementById("pwdF").value;
	var value = encodeObject(array);
	//alert(value); //##
	
	closeFloatPanel();
	
    var owner = parent().owner();
	put_menu(owner, "ORCA", "preference", "", value, loadedPreference);
}

function savedCheck(answer){
    showFadeoutInfo("infoArea", "転記しました", 2000);
}
function saveCheck(){
    // チェックボックスのチェック状況をサーバへ記憶
    var array = new Array();
    var ary = tags();
    for (num in ary){
        var rec = ary[num];
        var check = (document.getElementById(rec.check+".check").checked) ? 1 : 0;
        array.push(check);
    }
    var value = array.join(",");
	
    var owner = parent().owner();
	put_menu(owner, "ORCA", "check", "", value, savedCheck);
}

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


function showBasicInfo(){
    // NOA の患者基本情報を上書き
    var obj = records();
    var array = new Array();
    
    setKeyAndValue(array, obj, "Patient_ID");
    setKeyAndValue(array, obj, "WholeName");
    setKeyAndValue(array, obj, "WholeName_inKana");
    array.push("-----");
    setKeyAndValue(array, obj, "Insurance_Combination_Number");
    setKeyAndValue(array, obj, "InsuranceProvider_Class");
    setKeyAndValue(array, obj, "InsuranceProvider_Number");
    setKeyAndValue(array, obj, "InsuranceProvider_WholeName");
    setKeyAndValue(array, obj, "HealthInsuredPerson_Symbol");
    setKeyAndValue(array, obj, "HealthInsuredPerson_Number");
    setKeyAndValue(array, obj, "RelationToInsuredPerson");
    setKeyAndValue(array, obj, "Certificate_StartDate");
    setKeyAndValue(array, obj, "Certificate_ExpiredDate");
    array.push("-----");
    setKeyAndValue(array, obj, "PublicInsurance_Class");
    setKeyAndValue(array, obj, "PublicInsurance_Name");
    setKeyAndValue(array, obj, "PublicInsurer_Number");
    setKeyAndValue(array, obj, "PublicInsuredPerson_Number");

    var elm = elmFor("resultsArea");
    elm.innerHTML = array.join("<br>");
    
    function setKeyAndValue(array, obj,tag){
        // array に key:value のオブジェクトを追加
        var val = valueForKeyInRecord(obj, tag);
        var name = nemeForTagname(tag);
        array.push(name + "： "+val); 
    }
}
function showProgressInfo(){
    // 受診履歴を表示
    var obj = records();
    var array = new Array();
    
    array.push("患者基本情報"); 
    var val = valueForKeyInRecord(obj, "Patient_ID");
    array.push("カルテID： "+val); 
    var val = valueForKeyInRecord(obj, "WholeName");
    array.push("受診者氏名： "+val); 

    var children = childrenForKeyInRecord(obj, "HealthInsurance_Information");
    array.push("----- 保険情報 -----"); 
    for (num in children){
        var rec = children[num];
        var name = nemeForTagname(rec.key);
        array.push(name + "： " + rec.value); 
    }

    // 診療情報の繰り返し
    var children = childrenForKeyInRecord(obj, "Medical_Information");
    for (num in children){
        var rec = children[num];
        var ary = childrenForKeyInRecord(rec, "Medical_Information_child");
        for (nm in ary){
            var rc = ary[nm];
            if (rc.key == "Medical_Class_Money") continue;
            if (rc.key == "Medical_Class_code") continue;

            if (rc.key == "Medication_info"){
                var ar = childrenForKeyInRecord(rc, "Medication_info_child");
                for (n in ar){
                    var rec = ar[n];
                    if (rec.key == "Medication_Code") continue;

                    var name = nemeForTagname(rec.key);
                    array.push("　" + name + "： " + rec.value); 
                }
            } else {
                var name = nemeForTagname(rc.key);
                array.push(name + "： " + rc.value); 
            }
        }
    }

    var elm = elmFor("resultsArea");
    elm.innerHTML = array.join("<br>");
}
function showDiseaseInfo(){
    // 病名一覧を表示
    var obj = records();
    var array = new Array();
    
    array.push("患者基本情報"); 
    var val = valueForKeyInRecord(obj, "Patient_ID");
    array.push("カルテID： "+val); 
    var val = valueForKeyInRecord(obj, "WholeName");
    array.push("受診者氏名： "+val); 
    
    // 病名情報の繰り返し
    array.push("----- 病名 -----"); 
    var children = childrenForKeyInRecord(obj, "Disease_Information");
    for (num in children){
        var rec = children[num];
        var cld = rec.children;
        for (nm in cld){
            var rc = cld[nm];
            if ((rc.key == "Disease_Name") && rc.value){
                var name = nemeForTagname(rc.key);
                array.push(name + "： " + rc.value); 
            }
            if ((rc.key == "Disease_StartDate") && rc.value){
                var name = nemeForTagname(rc.key);
                array.push("　" + name + "： " + rc.value); 
            }
            if ((rc.key == "Disease_EndDate") && rc.value){
                var name = nemeForTagname(rc.key);
                array.push("　" + name + "： " + rc.value); 
            }
            if ((rc.key == "Disease_OutCome") && rc.value){
                var name = nemeForTagname(rc.key);
                array.push("　" + name + "： " + rc.value); 
            }
        }
    }
    
    var elm = elmFor("resultsArea");
    elm.innerHTML = array.join("<br>");
}

function sentToNOA(answer){
    // NOA を再読み込みするためブラウザーをリロード
    parent().window.location.reload(true);
}
function fixButtonClicked(){
    // チェックされた項目データを NOA へ転記
    var container = new Object(); // NOA へ転帰すべきデータを container に記憶

    putOrcaCheckArray(); // チェック状態を localStorage に記憶

    var diseases = new Array();
    var array = checkList();
    for (num in array){
        var obj = array[num];
        var cb = elmFor(obj.key + ".cb");
        
        // ##### NOA とのデータの整合性をとるため、ここでデータをモディファイ #####
        if (obj.key == "RelationToInsuredPerson"){
            var tag = "HealthInsurance.kubun";
            var val = (obj.value == "1") ? "本人" : "家族";
        } else if (obj.key.indexOf("Certificate_ExpiredDate") == 0){
        } else if (obj.key.indexOf("InsuranceProvider_WholeName") == 0){
            var tag = tablefieldForTagname(obj.key);
            var val = obj.value;
            if (val.indexOf("国公") >= 0) val = "国家共済";
        } else if (obj.key.indexOf("Disease_EndDate") == 0){
            var tag = tablefieldForTagname(obj.key);
            var val = obj.value;
            if (val.indexOf("9999") >= 0) val = "";
        } else if (obj.key.indexOf("Disease_Information") >= 0){
            var st = obj.value[0];
            if (obj.value.length > 1) st += " " + obj.value[1];
            if (obj.value.length > 2) st += " -- " + obj.value[2];
            diseases.push(obj.value.join(" "));
        } else {
            var tag = tablefieldForTagname(obj.key);
            var val = obj.value;
        }
        
        if (tag.length > 1)
            container[tag] = val;
    }
    container["ProgressSection.disease"] = diseases.join("<br>");

    // デバッグ表示
    if (debugMode()){ //## DEBUG
        _initDebug(true);
        for (tag in container)
            _debug(tag+"==>"+container[tag]);
    }
   
    // NOA へ container 内容を送る
    var owner = parent().owner();
    var pid = parent().receiptId();
    var date = parent().currentDate();
    var limit = parent().timeLimit();
    NRPutPage(owner, pid, date, limit, container, sentToNOA);
}

function openPreference(){
	// 初期設定パネルを開く
	var elm = document.getElementById("_floatPanel");
	elm.innerHTML = "";
	var tbl = newTABLE(elm, "");
	tbl.style.width = "100%";
	tbl.style.fontSize = "9pt";
	
    // comment
	var tr = newTR(tbl, "", "");
	var td = newTD(tr, "", "");
    td.setAttribute("colspan", "2");
    td.innerHTML = "NOA は ORCA へクライアントとして接続しますので<br>通常の ORCA クライアントと同じ設定をしてください";
    td.style.padding = "0px 10px";
    td.style.color = "#c36";

	// IP Address
	var tr = newTR(tbl, "", "");
	var td = newTD(tr, "", "ORCA の IPアドレス");
	var td = newTD(tr, "", "");
	var ip = (ORCA() && ORCA().IP) ? ORCA().IP : "";
	var fd = newFIELD(td, "ipF", "", 30, ip);
    // comment
	var tr = newTR(tbl, "", "");
	var td = newTD(tr, "", "");
    td.setAttribute("colspan", "2");
    td.innerHTML = "例）168.0.0.1 のように ORCA の IP を入力<br>";
    td.innerHTML += "foo.bar のようなホスト表記も可能です";
    td.style.padding = "0px 10px";
    td.style.color = "#c36";
	// PORT Number
	var tr = newTR(tbl, "", "");
	var td = newTD(tr, "", "ORCA の ポート番号");
	var td = newTD(tr, "", "");
	var port = (ORCA() && ORCA().PORT) ? ORCA().PORT : "";
	var fd = newFIELD(td, "portF", "", 20, port);
    fd.setAttribute("placeholder", "8000"); // 入力ヒントを表示

	// USER ID
	var tr = newTR(tbl, "", "");
	var td = newTD(tr, "", "ORCA のユーザ");
	var td = newTD(tr, "", "");
	var uid = (ORCA() && ORCA().ID) ? ORCA().ID : "";
	var fd = newFIELD(td, "uidF", "", 20, uid);
	// USER ID
	var tr = newTR(tbl, "", "");
	var td = newTD(tr, "", "ORCA のパスワード");
	var td = newTD(tr, "", "");
	var pwd = (ORCA() && ORCA().PWD) ? ORCA().PWD : "";
	var fd = newPASSWORD_FIELD(td, "pwdF", "", 20, pwd);
	
	// フッター
	var tr = newTR(tbl, "", "");
	var td = newTD(tr, "", "");
	var td = newTD(tr, "", "");
	td.style.textAlign = "right";
	var bt = newBUTTON(td, "", "確定");
	bt.setAttribute("onclick", "savePreference()");
	
	var buff = elm.innerHTML;
	openFloatPanel(tbl, 30, 50, "ORCA への接続条件設定");
}

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

var _isXML2;
var _itemNumber;
var _menus = ["患者一覧","患者基本情報","病名情報","受診履歴"]; // "症状詳記"
var _patientListNumber = 0; // _menus の順番と整合性が必要
var _basicNumber = 1;
var _diseaseNumber = 2;
var _patientInfoNumber = 3;
function callORCA(){
    var label = document.getElementById("popup").value;
    var uri = "http://" + ORCA().IP + ":" + ORCA().PORT;
    
    //_initDebug(true); //#
    _debug("callORCA->"+label+"->"+uri); //##
    
    _itemNumber = (-1);
    for (num in _menus){
        var menu = _menus[num];
        if (menu == label) _itemNumber = num * 1; // num は文字列
    }
    if (_itemNumber < 0) return;
    
    _debug("_itemNumber-> "+_itemNumber); //##
    _debug("receiptId-> "+parent().receiptId()); //##
    
    // ### ORCA 仕様変更により変わる可能性あり ###
    _isXML2 = true;
    switch (_itemNumber){
        case _patientListNumber: // 患者一覧
            _isXML2 = false;
            getWithPOST(uri, "PATIENT_LIST", gotWithPOST);
            break;
        case _basicNumber: // 患者基本情報
            getWithPOST(uri, "BASIC_INFO", gotWithPOST);
            break;
        case _diseaseNumber: // 病名情報を返却
            _isXML2 = false;
            getWithPOST(uri, "DISEASE_INFO", gotWithPOST);
            break;
        case _patientInfoNumber: // 受診履歴
            getWithPOST(uri, "PATIENT_INFO", gotWithPOST);
            break;
        default:
            alert("この処理は未対応です");
            break;
    }
    
    // window size を記憶
    putWindowSize();
}

function popupChanged(){
    // ポップアップ・メニューが選択された
    elmFor("resultsArea").innerHTML = "";
    elmFor("contentsArea").innerHTML = "";
    elmFor("fixButtonArea").innerHTML = "";
}

///////////////////////////////////////////////////
///// ALL_INFO ////////////////////////////////////

var _srcObj;
function setSrcObj(obj){
    _srcObj = obj;
}
function srcObj(){
    // NOA に必要なタグ・値を記憶するオブジェクト
    return _srcObj;
}

var _checkList;
var _checkedKeys;
function initCheckList(){
    // checkList を初期化
    _checkedKeys = getOrcaCheckArray(); // チェックされたキーの配列
    _checkList = new Array();
}
function checkStatusForKey(key){
    // key がチェックされていれば 1 を返す
    if (key.indexOf("Disease_Information") >= 0){
        for (num in _checkedKeys){
            var st = _checkedKeys[num];
            if (st.indexOf("Disease_Information") >= 0) return 1;
        }
        return 0;
    } else {
        return (indexOfArray(_checkedKeys, key) < 0) ? 0 : 1;
    }
}
function addCheckList(key, value){
    var obj = new Object();
    obj.key = key;
    obj.value = value;
    _checkList.push(obj);
}
function checkList(){
    // チェック行オブジェクトの入った配列を返す
    return _checkList;
}

function showChildren(tbl, obj){
    // srcObj の内容をリカーシブルに表示
    for (key in obj){
        var val = obj[key];
        if (val && (typeof(val) == "object")){
            // 病名を一行に表示する形式
            // showChildren(tbl, val); // 病名を一行にしないならこの形式
            for (ky in val){
                var rec = val[ky];
                var disease = rec.Disease_Name;
                var start = (rec.Disease_StartDate) ? rec.Disease_StartDate : "";
                var end = (rec.Disease_EndDate) ? rec.Disease_EndDate : "";
                var outcome = (rec.Disease_OutCome) ? rec.Disease_OutCome : "";
                
                var tr = newTR(tbl, "", "");
                var td = newTD(tr, "", "");
                td.setAttribute("colspan", "2");
                var sp = newSPAN(td, key+"."+ky+".cbArea");
                var status = checkStatusForKey(key); // 個々の病名でなく病名情報全体としての status
                var cb = newCHECKBOX(sp, key+"."+ky+".cb", "", status);
                var sp = newSPAN(td, "");
                sp.style.paddingLeft = "5px";
                sp.innerHTML = start + " " + disease + " " + end + " " + outcome;
                
                // checkList に登録
                var ary = new Array();
                ary.push(start);
                ary.push(disease);
                ary.push(end);
                addCheckList(key+"."+ky, ary);
            }
        } else {
            var tr = newTR(tbl, "", "");
            if (val == null){
                tr.style.backgroundColor = "#eee";
                var td = newTD(tr, "", key);
                td.style.paddingLeft = "30px";
                td.style.width = "150px";
                td.setAttribute("colspan", "2");
                continue;
            }
            
            var td = newTD(tr, "", "");
            var sp = newSPAN(td, key+".cbArea");
            var status = checkStatusForKey(key);
            var cb = newCHECKBOX(sp, key+".cb", "", status);
            var sp = newSPAN(td, "");
            sp.innerHTML = nemeForTagname(key);
            sp.style.paddingLeft = "5px";
            var td = newTD(tr, key+".val", val);
            
            // checkList に登録
            addCheckList(key, val);
        }
    }
}

function showSrcObj(){
    // srcObj を表示
    var elm = elmFor("resultsArea");
    elm.innerHTML = "";
    var elm = elmFor("contentsArea");
    elm.innerHTML = "";
    var tbl = newTABLE(elm, "/base-table");
    tbl.style.fontSize = "10pt";

    initCheckList(); // checkList を初期化
    showChildren(tbl, srcObj());
}

function setSourceValue(src, obj, key){
    // sobj へ key に対応する値を記憶
    if (obj)
        src[key] = valueForKeyInRecord(obj, key);
    else
        src[key] = null;
}

function gotDiseaseInfo(){
	// サーバから返された病名情報を処理
	if ((xmlHttpObject.readyState == 4) && (xmlHttpObject.status == 200)){
		var value = xmlHttpObject.responseText;
		var array = value.split("<SEPARATOR>");
		if ((array.length > 1) && (array[1].length)){
            if (window.DOMParser){
                var parser=new DOMParser();
                var xmlDoc=parser.parseFromString(array[1],"text/xml");
            } else { // Internet Explorer
                var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
                xmlDoc.async="false";
                xmlDoc.loadXML(array[1]); 
            }
            
            var obj = domToObject("root", xmlDoc); // XML
            if (debugMode()) alert("obj ===\n"+encodeObject(obj));//##

            //_initDebug(true); //##

            // 病名情報
            var sobj = srcObj();
            setSourceValue(sobj, null, "病名情報");
            // showDom() と同様の仕組みでリカーシブルに処理 
            var parent = new Object(); // 親を作っておく
            var children = childrenForKeyInRecord(obj, "Disease_Information");
            for (num in children){
                var rec = children[num];
                var cld = rec.children;
                var hasChild = false;
                var child = new Object();
                for (nm in cld){
                    var rc = cld[nm];

                    if ((rc.key == "Disease_Name") && rc.value){
                        child[rc.key] = rc.value;
                        hasChild = true;
                    }
                    if ((rc.key == "Disease_StartDate") && rc.value){
                        child[rc.key] = rc.value;
                    }
                    if ((rc.key == "Disease_EndDate") && rc.value){
                        child[rc.key] = rc.value;
                    }
                    if ((rc.key == "Disease_OutCome") && rc.value){
                        child[rc.key] = rc.value;
                    }
                }
                if (hasChild){
                    parent[num] = child;
                }
            }
            sobj["Disease_Information"] = parent;
        }
        hideMessage("_message");
	} else
		showMessage("_message", "ORCA で処理中です ...");
    
    //_debug("sobj->"+encodeObject(sobj)); //return; //##
    
    showSrcObj();
    
    // 確定ボタンを表示
    var elm = elmFor("fixButtonArea");
    elm.innerHTML = "";
    var bt = newDIV(elm, "/fixButton");
    bt.innerHTML = "チェックした項目のデータを NOA へ転記";
    bt.setAttribute("onclick", "fixButtonClicked()");
    bt.style.marginLeft = "10px";
}
function gotBasicInfo(answer){
    //alert("gotBasicInfo->"+answer); //##
    if (answer && (answer.length > 0)){
        if (window.DOMParser){
            var parser=new DOMParser();
            var xmlDoc=parser.parseFromString(answer,"text/xml");
        } else { // Internet Explorer
            var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.async="false";
            xmlDoc.loadXML(answer); 
        }
        
        var obj = dom2ToObject("root", xmlDoc); // XML2
        var sobj = new Object();
        setSrcObj(sobj);
        // 健康保険
        setSourceValue(sobj, null, "健康保険");
        setSourceValue(sobj, obj, "InsuranceProvider_Class");
        setSourceValue(sobj, obj, "InsuranceProvider_Number");
        setSourceValue(sobj, obj, "InsuranceProvider_WholeName");
        setSourceValue(sobj, obj, "HealthInsuredPerson_Symbol");
        setSourceValue(sobj, obj, "HealthInsuredPerson_Number");
        setSourceValue(sobj, obj, "RelationToInsuredPerson");
        setSourceValue(sobj, obj, "Certificate_StartDate");
        setSourceValue(sobj, obj, "Certificate_ExpiredDate");
        // 公費
        setSourceValue(sobj, null, "公費");
        setSourceValue(sobj, obj, "PublicInsurance_Class");
        setSourceValue(sobj, obj, "PublicInsurance_Name");
        setSourceValue(sobj, obj, "PublicInsurer_Number");
        setSourceValue(sobj, obj, "PublicInsuredPerson_Number");
        
        setSrcObj(sobj);
        if (debugMode()) alert("sobj ===\n"+encodeObject(sobj));//##
        
        var uri = "http://" + ORCA().IP + ":" + ORCA().PORT;
        getWithPOST(uri, "DISEASE_INFO", gotDiseaseInfo);
    }
}
function getORCAInfo(){
    // NOA に必要な ORCA 情報をまとめてリクエスト
    var uri = "http://" + ORCA().IP + ":" + ORCA().PORT;
    //alert("getORCAInfo->"+uri); //##
    
    getWithPOST(uri, "BASIC_INFO", gotBasicInfo);
}

///// ALL_INFO ////////////////////////////////////
///////////////////////////////////////////////////


//////////////////////////////////////////////////////
///// TEST ///////////////////////////////////////////

function test(){
    // 確定ボタンを表示
    if (debugMode() == false) return;
    
    var elm = elmFor("fixButtonArea");
    elm.innerHTML = "";
    var bt = newDIV(elm, "/fixButton");
    bt.innerHTML = "チェックした項目のデータを NOA へ転記";
    bt.setAttribute("onclick", "fixButtonClicked()");
    bt.style.fontSize = "9pt";
}

///// TEST ///////////////////////////////////////////
//////////////////////////////////////////////////////



function initOrcaAgent(){
	var elm = document.getElementById("base");
    
    // === HEADER ===
    var div = newDIV(elm, "/tool-header");
    // --- LEFT SIDE ---
    var dv = newDIV(div, "/left-side");
    dv.style.width = "80%";
    dv.innerHTML = "ORCA 接続ツール　";
    var sp = newSPAN(dv, "pidArea");
    sp.style.paddingRight = "5px";
    var sp = newSPAN(dv, "patientNameArea");
    // --- RIGHT SIDE ---
    var dv = newDIV(div, "/right-side");
	var im = newIMAGE(dv, "", "./Help.png", "?");
	im.style.height = "15px";
	im.setAttribute("onclick", "help()");
    im.style.position = "relative";
    im.style.top = "2px";

    // === SELECTOR ===
    var div = newDIV(elm, "/clearfix");
    div.style.padding = "10px";
    // --- LEFT SIDE ---
    var dv = newDIV(div, "/left-side");
    dv.style.width = "120px";
    var bt = newDIV(dv, "/whiteButton");
    bt.innerHTML = "ORCA から読込";
    bt.setAttribute("onclick", "getORCAInfo()");
    bt.style.position = "relative";
    bt.style.top = "3px";
    // --- RIGHT SIDE ---
    var dv = newDIV(div, "/right-side");
    var pu = newPopupMenu(dv, "popup", _menus, "");
    pu.setAttribute("onchange", "popupChanged()");
    var sp = newSPAN(dv, "");
    sp.innerHTML = "を";
    sp.style.position = "relative";
    sp.style.top = "3px";
    var bt = newDIV(dv, "/whiteButton");
    bt.innerHTML = "表示";
	bt.setAttribute("onclick", "callORCA()");
    bt.style.padding = "3px 8px";
    
    // === RESULTS =================
    var div = newDIV(elm, "resultsArea");
    div.style.margin = "0 0 10px 10px";
    div.style.fontSize = "10pt";
    
    // === CONTENTS =================
    var div = newDIV(elm, "contentsArea");
    div.style.marginBottom = "5px";

    // === FOOTER ======================
    var div = newDIV(elm, "/tool-footer");
    var dv = newDIV(div, "/left-side");
    dv.style.width = "75px";
    var sp = newSPAN(dv, "");
    sp.style.paddingRight = "10px";
    sp.innerHTML = version();
    sp.setAttribute("onclick", "test()"); //##
    var dv = newDIV(div, "/right-side");
    dv.style.paddingRight = "5px";
    var sp = newSPAN(dv, "fixButtonArea");
    
    // === COMMENT ======================
    var div = newDIV(elm, "/clearfix");
    div.style.margin = "5px 15px";
    div.style.fontSize = "9pt";
    div.style.color = "#aaa";
    var dv = newDIV(div, "/left-side");
    dv.style.width = "40%";
    var sp = newSPAN(dv, "");
    var cb = newCHECKBOX(sp, "debugBox", "debug", 0);  // ### DEBUG ###
    var sp = newSPAN(dv, "");
	var im = newIMAGE(sp, "", "./hammer.png", "P");
	im.style.height = "12px";
	im.style.marginLeft = "5px";
	im.setAttribute("onclick", "openPreference()");
    var dv = newDIV(div, "/right-side");
    var sp = newSPAN(dv, "");
    sp.style.paddingLeft = "5px";
    sp.innerHTML = " for ORCA Version.4.7.0";
    
    var pid = parent().patientId();
    elmFor("pidArea").innerText = (pid) ? pid : "*** カルテID不明 ***";
    var name = parent().patientKanjiName();
    elmFor("patientNameArea").innerText = (name) ? name : "";
    if (pid == null){
        alert("対象となるカルテを開き、やり直してください");
    } else {
        loadPreference();
    }
}

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