
var _isDebugMode;
function setDebugMode(elm){
	_isDebugMode = (elm.checked) ? true : false;
}
function debugMode(){
    // デバッグモードかどうかを返す
	return _isDebugMode;
}


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

var _none = 0;
var _number = 1;
var _dot = 2;
var _type;
function getType(){
    var type = window.localStorage["docType"];
    
    //alert("getType:"+type); //##
    
    _type = (type) ? type : 0;
}
function putType(){
    _type = checkedRADIO("_radios");
    window.localStorage["docType"] = _type;
}
function type(){
    // センテンスの形式を返す
    return _type;
}

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


////////////////////////////////////////////////////////////////
///// Ajax /////////////////////////////////////////////////////

function gotDir(){
	if ((xmlHttpObject.readyState == 4) && (xmlHttpObject.status == 200)){
		var value = xmlHttpObject.responseText;
		//alert("gotDir ===\n"+value);//##
        
		var array = value.split("<SEPARATOR>");
		if (array.length > 1){
            var array = JSON.parse(array[1]);
            
            showFileNames(array);
		} else {
            alert(value);
        }
		hideMessage("_message");
	} else 
		showMessage("_message", "ファイル・リスト取得中 ... ");
}
function getDir(){
    // HTML ファイルのリストをリクエスト
    xmlHttpObject = createXMLHttpRequest(gotDir);
	if (xmlHttpObject){ // GETパラメータ付きでリクエスト送信
		var array = new Array();
        array["owner"] = owner();
        array["suffix"] = "html";
        
		var st = "./server.php?command=GET_DIR"
		+ "&value=" + encodeObject(array);
		//alert(st); //===
        
		xmlHttpObject.open("GET", encodeURI(st), true);
		xmlHttpObject.send(null);
	}
}

function　got_File(){
	if ((xmlHttpObject.readyState == 4) && (xmlHttpObject.status == 200)){
		var value = xmlHttpObject.responseText;
		//alert("gotFile ===\n"+value);//##
        
		var array = value.split("<SEPARATOR>");
		if (array.length > 1){
            var path = document.getElementById("filePop").value;
            document.getElementById("pathArea").innerHTML = path;
            load(array[1]);
        }
	} 
}
function　read_File(){
    // file を読込む
    xmlHttpObject = createXMLHttpRequest(got_File);
	if (xmlHttpObject){ // GETパラメータ付きでリクエスト送信
		var array = new Array();
        array["owner"] = owner();
		array["filename"] = document.getElementById("filePop").value;
		
		var st = "./server.php?command=GET_FILE"
		+ "&value=" + encodeObject(array);
		//alert(st); //===
        
		xmlHttpObject.open("GET", encodeURI(st), true);
		xmlHttpObject.send(null);
	}
}

function removedFile(){
	if ((xmlHttpObject.readyState == 4) && (xmlHttpObject.status == 200)){
		var value = xmlHttpObject.responseText;
        showFadeoutInfo("message", value, 1000);
	} 
}
function removeFile(){
    // file を削除
    var filename = document.getElementById("filePop").value;
    if (! confirm(filename + " を削除していいですか")) return;
    
    xmlHttpObject = createXMLHttpRequest(removedFile);
	if (xmlHttpObject){ // GETパラメータ付きでリクエスト送信
		var array = new Array();
        array["owner"] = owner();
		array["filename"] = filename;
		
		var st = "./server.php?command=REMOVE_FILE"
		+ "&value=" + encodeObject(array);
		//alert(st); //===
        
		xmlHttpObject.open("GET", encodeURI(st), true);
		xmlHttpObject.send(null);
	}
}

///// Ajax /////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////

////////////////////////////////
///// DOCUMENT EDITOR //////////

var _records;
function records(){
    if (! _records){
        _records = new Array();
        var obj = newRecord(); // ０番目は document title
        _records.push(obj);
    }
    return _records;
}
function setRecordForIndex(obj, num){
    _records[num] = obj;
}
function recordForIndex(num){
    return _records[num];
}
function newRecord(){
    // 新規文章を生成
    var obj = new Object();
    obj.title = "新規タイトル";
    obj.doc = "新規文";
    return obj;
}

var _docTitle;
function setDocTitle(obj){
    _docTitle = obj;
}
function docTitle(){
    if (!_docTitle)
        _docTitle = newRecord();
    
    return _docTitle;
}

var _num;
function setCurrentNum(num){
    _num = num;
}
function currentNum(){
    return _num;
}

function save(){
    // 作成した文章を HTML に整形
    var path = document.getElementById("pathArea").innerHTML;
    var filename = prompt("ファイル名を入力してください", path);
    if (trim(filename).length == 0) return;
    
    var oldNum = currentNum();
    if (oldNum){
        setNoEditable("docTitle", oldNum);
        setNoEditable("docDocument", oldNum);
        setNoEditable("title.", oldNum);
        setNoEditable("doc.", oldNum);
    }
    
    // TITLE
    var obj = docTitle();
    var title = obj.title;
    var doc = obj.doc;
    
    var buff = '<html lang="ja">';
    buff += '<meta http-equiv="Conten-Type" content="text/html; charset=UTF8">';
    buff += '<head>';
    buff += '<title>' + obj.title + '</title>';
    buff += '</head>';
    
    buff += '<body>';
    
    // DOCUMENT TITLE
    buff += '<div style="margin-top:10px;padding:0px 20px;font-size:12pt;weight:bold"><docTitle>';
    buff += obj.title;
    buff += '</docTitle></div>';
    
    // READ
    var doc = trim(obj.doc);
    if (doc == "<br>") doc = "";
    if (doc.length){
        buff += '<div style="padding:0px 50px;font-size:10pt;color:rgb(120,120,120)">';
        buff += '<docDocument>';
        buff += obj.doc;
        buff += '</docDocument>';
        buff += '</div>';
    }
    
    var recs = records();
    for (num in recs){
        var obj = recs[num];
        
        // LABEL
        buff += '<div style="margin-top:10px;padding:0px 10px;font-size:11pt">';
        buff += label(num) + '<title' + num + '>';
        buff += obj.title;
        buff += '</title' + num + '>';
        buff += '</div>';
        
        // DOC
        buff += '<div style="padding:0px 20px;font-size:10pt">';
        buff += '<doc' + num + '>';
        buff += obj.doc;
        buff += '</doc' + num + '>';
        buff += '</div>';
    }
    
    buff += '<!-- <num>' + (num * 1 + 1) + '</num> -->';
    buff += '</body>';
    buff += '</html>';
    
    // buff をサーバへ保存
    if (filename.indexOf(".html") < 0)
        filename = filename + ".html";
    putFile(filename, buff, false, false);
}

function load(buff){
    // html ファイルをエディターに読込み表示
    
    // docTitle を読み込み
    var obj = new Object();
    var val = valueForTag("docTitle");
    obj.title = (val) ? val : "";
    var val = valueForTag("docDocument");
    obj.doc = (val) ? val : "";
    setDocTitle(obj);
    
    // chapter を読み込み
    _records = new Array();
    var num = valueForTag("num") * 1; // chapter 数をゲット
    //alert(num); //##
    
    for (i=0; i < num; i++){
        var obj = new Object();
        var tag = "title" + i;
        obj.title = (valueForTag(tag)) ? valueForTag(tag) : "";
        var tag = "doc" + i;
        obj.doc = (valueForTag(tag)) ? valueForTag(tag) : "";
        setRecordForIndex(obj, i);
    }
    
    // 読込んだデータを表示
    showContents();
    
    function valueForTag(tag){
        var array = buff.split("<" + tag + ">");
        if (array.length > 1){
            var ln = array[1];
            var ary = ln.split("</" + tag + ">");
            if (ary.length > 1){
                return ary[0];
            }
        }
        return null;
    }
}

function addRecord(){
    // 文章を追加
    var obj = newRecord();
    
    // 現在行に新規レコードを挿入
    // ## もし次行に挿入したい場合 row は splice() 外で計算しておかないと
    // ## row が文字列として扱われてしまい、計算結果が正しく反映されないので注意
    var row = currentNum() * 1 + 1;
    _records.splice(row, 0, obj);
    
    showContents();
}
function removeRecord(num){
    // 文章を削除
    delete _records[num];
    
    // 欠落したレコードを詰める
    var newRecs = new Array();
    for (n in _records){
        var obj = _records[n];
        if (obj && obj.title)
            newRecs.push(obj);
    }
    _records = newRecs;
    showContents();
}
function prev(num){
    // レコードを一つ前に移動
    if (num * 1 == 0) return;
    
    var newRecs = new Array();
    for (n in _records){
        if (n == num * 1 - 1){
            newRecs.push(_records[n * 1 + 1]);
        } else if (n == num){
            newRecs.push(_records[n * 1 - 1]);
        } else {
            newRecs.push(_records[n]);
        }
    }
    _records = newRecs;
    showContents();
    showController(num * 1 - 1);
}
function next(num){
    // レコードを一つ後に移動
    if (num * 1 >= _records.length - 1) return;
    
    var newRecs = new Array();
    for (n in _records){
        if (n == num){
            newRecs.push(_records[n * 1 + 1]);
        } else if (n == num * 1 + 1){
            newRecs.push(_records[n * 1 - 1]);
        } else {
            newRecs.push(_records[n]);
        }
    }
    _records = newRecs;
    showContents();
    showController(num * 1 + 1);
}

function showController(num){
    // タイトル右にコントローラを表示
    var td = document.getElementById("ctrl." + num);
    td.innerHTML = "";
    
    var img = newIMAGE(td, "", "./arrowUp.png", "Up");
    img.style.height = "15px";
    img.setAttribute("onclick", "prev('" + num + "')");
    newTEXT(td, " ");
    var img = newIMAGE(td, "", "./arrowDown.png", "Down");
    img.style.height = "15px";
    img.setAttribute("onclick", "next('" + num + "')");
    newTEXT(td, " ");
    var img = newIMAGE(td, "", "./add-field.png", "Add");
    img.style.height = "15px";
    img.setAttribute("onclick", "addRecord()");
    newTEXT(td, " ");
    var img = newIMAGE(td, "", "./remove-field.png", "Remove");
    img.style.height = "15px";
    img.setAttribute("onclick", "removeRecord('" + num + "')");
}
function hideController(num){
    // タイトル右のコントローラを隠す
    var elm = document.getElementById("ctrl." + num);
    if (elm) elm.innerHTML = "";
}

function setEditable(type, num){
    // タイトルを編集状態にする
    if (type == "docTitle"){
        document.getElementById("docTitle").contentEditable = true;
    } else if (type == "docDocument"){
        document.getElementById("docDocument").contentEditable = true;
    } else {
        var oldNum = currentNum();
        if (oldNum && (oldNum != num)){
            hideController(oldNum);
            setNoEditable("docTitle", oldNum);
            setNoEditable("docDocument", oldNum);
            setNoEditable("title.", oldNum);
            setNoEditable("doc.", oldNum);
        }
        setCurrentNum(num);
        
        document.getElementById(type + num).contentEditable = true;
        if (type == "title.") showController(num);
    }
}
function setNoEditable(type, num){
    // タイトルを編集不可状態にする
    if (type == "docTitle"){
        var elm = document.getElementById("docTitle");
        if (!elm) return;
        
        elm.contentEditable = false;
        
        // 変更された内容を記憶
        var obj = docTitle();
        obj.title = elm.innerHTML;
        setDocTitle(obj);
    } else if (type == "docDocument"){
        var elm = document.getElementById("docDocument");
        if (!elm) return;
        
        elm.contentEditable = false;
        
        // 変更された内容を記憶
        var obj = docTitle();
        obj.doc = elm.innerHTML;
        setDocTitle(obj);
    } else {
        var elm = document.getElementById(type + num);
        if (!elm) return;
        
        elm.contentEditable = false;
        
        // 変更された内容を記憶
        var elm1 = document.getElementById("title." + num);
        if (!elm1) return;
        var elm2 = document.getElementById("doc." + num);
        if (!elm2) return;
        
        var obj = recordForIndex(num);
        obj.title = elm1.innerHTML;
        obj.doc = elm2.innerHTML;
        setRecordForIndex(obj, num);
    }
}

function label(num){
    // ラベルの形式を返す
    switch (type() * 1){
        case _number: return (num * 1) + 1 + ". ";
        case _dot: return "・ ";
        default: return "";
    }
}
function showContents(){
	var elm = document.getElementById("contents");
	elm.innerHTML = "";
    
    // DOCUMENT TITLE
    var obj = docTitle();
    var dv = newDIV(elm, "docTitle");
    dv.innerHTML = obj.title;
    dv.style.padding = "0px 15px";
    dv.style.fontSize = "12pt";
    dv.setAttribute("onclick", "setEditable('docTitle')");
    // 必要なら obj.doc の取扱も追加
    // DOCUMENT
    var dv = newDIV(elm, "docDocument");
    dv.style.marginBottom = "10px";
    dv.style.padding = "0px 40px";
    var doc = trim(obj.doc);
    if (doc == "<br>") doc = "";
    if (doc.length){
        dv.innerHTML = obj.doc;
        dv.setAttribute("onclick", "setEditable('docDocument')");
    }
    
    var recs = records();
    for (num in recs){
        var obj = recs[num];
        
        // TITLE
        var dv = newDIV(elm, "");
        var tbl = newTABLE(dv, "frameTable");
        var tr = newTR(tbl, "", "");
        var td = newTD(tr, "", label(num));
        td.setAttribute("onclick", "setEditable('title.','" + num + "')");
        var sp = newSPAN(td, "title." + num);
        sp.innerHTML = obj.title;
        dv.style.padding = "0px 10px";
        // CONTROLLER AREA
        var td = newTD(tr, "ctrl." + num, "");
        td.style.textAlign = "right";
        td.style.padding = "0px 5px";
        
        // DOCUMENT
        var dv = newDIV(elm, "doc." + num);
        dv.style.padding = "0px 25px";
        dv.innerHTML = obj.doc;
        dv.setAttribute("onclick", "setEditable('doc.','" + num + "')");
        dv.style.marginBottom = "5px";
    }
}

function showFileNames(array){
    // ファイル名のリストを表示
	var elm = document.getElementById("dirArea");
	elm.innerHTML = "";
    
    var pu = makePopupMenu(elm, "filePop", array, "");
}

function showPreference(){
    // 初期設定を開く
	var elm = document.getElementById("preferenceArea");
	elm.innerHTML = "箇条形式 ";
    var sp = newSPAN(elm, "");
    var names = ["無","番号","点"];
    var radio = newRADIO(sp, "_radios", "groupName", names, type()+"");
    sp.setAttribute("onclick", "putType()");
}

function editorSelected(elm){
    // EDITOR の種類を切り替える
    var label = (elm) ? elm.value : "メニュー編集";
    
    if (label == "メニュー編集")
        window.open("./editor.php", "contents");
}

function openDocEditorHelp(){
	// ヘルプパネルを表示
	var win = window.open("./docEditorHelp.html","Help"
                          ,"width=450,height=700,scrollbars=yes,resizable=yes");
	win.focus();
}

function initDocEditor(){
	var elm = document.getElementById("base");
	elm.innerHTML = "";
    
    // HEADER
    var dv = newDIV(elm, "");
    dv.style.marginTop = "5px";
    var tbl = newTABLE(elm, "frameTable");
    var tr = newTR(tbl, "titleBar", "");
    // HEADER LEFT
    var td = newTD(tr, "left", "");
    td.style.width = "100px";
    var array = ["メニュー編集","文章編集"];
    var pu = makePopupMenu(td, "editorPop", array, "文章編集");
    pu.setAttribute("onchange", "editorSelected(this)");
    // HEADER MIDDLE
    var td = newTD(tr, "headerMiddleArea", "");
    // HEADER MIDDLE of DOCUMENT EDITOR
    var sp = newSPAN(td, "dirArea");
    var bt = newBUTTON(td, "", "読込");
    bt.setAttribute("onclick", "read_File()");
    var bt = newBUTTON(td, "", "削除");
    bt.setAttribute("onclick", "removeFile()");
    newTEXT(td, " ");
    var sp = newSPAN(td, "pathArea");
    newTEXT(td, "　");
    var sp = newSPAN(td, "preferenceArea");
    var bt = newBUTTON(td, "", "保存");
    bt.setAttribute("onclick", "save()");
    // HEADER RIGHT
    var td = newTD(tr, "right", "");
    var img = newIMAGE(td, "", "./info.png", "help");
    img.style.height = "17px";
	img.setAttribute("onclick","openDocEditorHelp()");
    
    // CONTENTS
    var dv = newDIV(elm, "contents");
    
    // FOOTER
    var dv = newDIV(elm, "");
    var tbl = newTABLE(dv, "frameTable");
    var tr = newTR(tbl, "titleBar", "");
    // LEFT
    var td = newTD(tr, "left", version());
    td.style.height = "25px";
    var sp = newSPAN(td, "");
    sp.innerHTML = " owner ( " + owner() + " )";
    // RIGHT
    var td = newTD(tr, "right", "");
    var sp = newSPAN(td, "footerRightArewa");
    var cb = newCHECKBOX(td, "", "debug", 0);
    cb.setAttribute("onclick", "setDebugMode(this)");
    
    // MESSAGE and DEBUG AREA
    var dv = newDIV(elm, "message");
    var dv = newDIV(elm, "_debug");
    
    getType(); // localStorage
    getDir(); // Ajax
    showContents();
    showPreference();
}

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