/*
 Ajax Chat for TRPG ver.2.6.2.1
 (c)2007-2009 Cake All Rights Reserved.
 Mail : cake_67@users.sourceforge.jp
 Home : http://trpgtools-onweb.sourceforge.jp/
 */
/*****************
 *  JaveScriptライブラリ：index.php用
 *****************/
// 変数
columnId = 'pc_input_0';
formObjId = '0';
var cookieSaveScript = './cookie_save.php';
var cookieLoadScript = './cookie_load.php';

// 発言成形
function comment(Obj, isTextArea) {
    // 発言取得
    if (!isTextArea) {
        var pc_input = Obj.pc_input.value;
    } else {
        var pc_input = Obj.pc_input_textarea.value;
    }
    if (pc_input) {
        //入力チェック
        var name = convert($("#name_on").attr("value"));
        var pc_name = Obj.pc_name.value;
        if (!pc_name) {
            alert("PC名を入力してください。");
            return false;
        }
        var pc_color = Obj.pc_color.value;

        //データ成形
        var params =
            '?n='+name//名前
            +'&c='+convert(pc_name)//PC
            +'&l='+pc_color//色
            +'&m='+convert(pc_input);//本文

        // ささやき
        var whisper_to_name = Obj.whisper_to.value;
        var whisper_to_hash = Obj.whisper_to_hash.value;
        if(whisper_to_name && whisper_to_name != '全員' && whisper_to_hash) {
            params = params
                +'&w='+convert(whisper_to_name)//whisperto
                +'&h='+whisper_to_hash;//whisperto_hash
        }

        //状態表示
        if (Obj.show_status.checked) {
            params = params+'&s='+'1';
        } else {
            params = params+'&s='+'0';
        }

        //状態
        if (Obj.status.value) {
            params = params+'&t='+convert(Obj.status.value);
        }

        //他
//        params = params+'&a='+Obj.status.value;

        if ($("#pwd_on").attr("value")) {
            var pwd = convert($("#pwd_on").attr("value"));
        }
        if (pwd) {
            var params =
            params+'&p='+pwd;//PWD
        }
        var params =
            params+'&y=com'
            +'&e='+(new Date()).getTime();//cacheの更新

        writeComment(params, true);

        //フォームチェンジ
        if (!isTextArea) {
            Obj.pc_input.value = "";
        } else {
            Obj.pc_input_textarea.value = "";
        }
    }
    if (!isTextArea) {
        Obj.pc_input.focus();
    } else {
        Obj.pc_input_textarea.focus();
    }

    return false;
}

// 在室を確認して指定の処理を実行
function isMember(name, action, params, pwd) {
    var flg = false;
    $.ajax({
        type: "get",
        url: now_member,
        ifModified: false,
        cache: false,
        dataType: "text",
        success: function(data) {
            var name_array = new Array();
            var memberData = data.split("\n");
            $.each(memberData, function(i){
                var memberDataDetail = memberData[i].split("<>");
                if (obfuscateLog == '1') {
                    var plName = deObfLog(memberDataDetail[0]);
                } else {
                    var plName = memberDataDetail[0];
                }

                if (name==plName) {
                    flg = true;
                }
            });

            if (flg) {
                if (action=="logout") {
                $("#logout").click();
                return true;
                }
                if (action=="login") {
                    alert('そのお名前でログインはできません。');
                    return false;
                }
            }

            if (action=="login") {
                writeComment(params, false);
                //フォームチェンジ
                $("#online1").show();
                $("#online2").show();
                $("#offline").hide();
                $("#pc_0").show();
                $("#name_on").val(name);
                if (!$("#pc_name_0").val()) {
                    $("#pc_name_0").val(name);
                }
                $("#pwd_on").val(pwd);
                $("#pc_input_0").focus();
                if (userWhisper) {
                    $(".whisper_to").each(function(idx, Obj){
                        Obj.disabled = true;
                        Obj.value ="全員";
                    });
                    $(".whisper_to_hash").each(function(idx, Obj){
                        Obj.value ="";
                    });
                }

                // 更新
                window.mainframe.login();

            }
        },
        error: function(data) {
            alert('参加者情報取得に失敗しました');
            return false;
        }
    });
}

// ウインドウサイズ変更でフォームサイズ変更
function changeSize() {
    var winWidth = getWinWidth();
    var winHeight = getWinHeight() - 80;
    $(".input_comment").css({width: winWidth-295});
    $(".status").css({width: winWidth-313});
    $("#mainframe").css({height: winHeight-30});
    $("#offline_win").css({left: winWidth-280});
}


// カーソル位置に指定文字列を挿入
function insert(Obj, selfId, text, backlength) {
    // 自分自身には挿入できない(ダイスショートカット対応）
    if (Obj.id == selfId) {
        return false;
    }

    Obj.focus();

    var textLength = text.length;
    //FireFoxなど
    if (Obj.selectionStart) {
        var position = Obj.selectionStart;
        Obj.value = Obj.value.substring(0, position)+text+Obj.value.substring(position, Obj.value.length);
        Obj.setSelectionRange(position + textLength, position + textLength - backlength);
    } else {
        // IE
        if (document.selection) {
            var sel = document.selection.createRange();
            sel.text = text;
            sel.move('character', -backlength);
            sel.select();
        // その他
        } else {
            Obj.value = Obj.value+text;
        }
    }
}

// 名前文字色を反映
function changeColor(Obj) {
        Obj.form.pc_color.value = Obj.value;
        Obj.form.pc_color.style.color = Obj.value;
        Obj.form.pc_name.style.color = Obj.value;
        Obj.form.pc_color_select.style.color = Obj.value;
}

// タグ挿入
function insertTag(tag, columnId) {
    insert(document.getElementById(columnId), '','<'+tag+'></'+tag+'>', tag.length+3)
}

// フォントタグ挿入
function insertFontTag(columnId) {
    var size = prompt("フォントサイズを指定してください(1～7または-4～+4)", "");
    var color = prompt("フォント色を指定してください", "");

    if (!size && !color) {
        return false;
    } else {
        var tag = "<font";
        if (size) {
            tag= tag+" size="+size;
        }
        if (color) {
            tag= tag+" color="+color;
        }
        tag = tag+"></font>";
        insert(document.getElementById(columnId), '', tag, 7)
    }
}

// 入室中にリロード・ページ遷移で自動退室
function UnLoad() {
    var name = $("#name_on").attr("value");
    if (name) {
        isMember(name, 'logout', '', '');
    }
}

// 起動時表示系処理
function pageLoad() {
    // フォームON/OFF
    $("#online1").hide();
    $("#online2").hide();
    $("#cfchange").hide();
    if ($("#cfinput")) { 
        $("#cfinput").checked = false;
    }
    $("#name_on").disabled = true;
    $("#pwd_on").disabled = true;
    $("#my_hash").disabled = true;
    $("#name_on").val("");
    $("#pwd_on").val("");
    $("#my_hash").val("");
    if (userWhisper) {
        $(".whisper_to").each(function(idx, Obj){
            Obj.disabled = true;
            Obj.value ="全員";
        });
        $(".whisper_to_hash").each(function(idx, Obj){
            Obj.value ="";
        });
    }
    $("#cfchange").hide();
    if ($("#cfinput")) { 
        $("#cfinput").checked = false;
    }

    // コンソール窓設定
    $(".console").draggable({
        cursor:'move',
        helper:'original'
    });
    $(".console").draggable('enable');
    $(".console").click(function(ev){
        var newZIndex = parseInt((new Date()).getTime()/100);
        newZIndex = newZIndex - preZIndex;
        $(this).css("z-index", newZIndex);
    });

    // ヘルプ窓設定
    $("#help_win").css({left: document.body.clientWidth-380});
    $("#help_win_acc_list").accordion({
        event: 'click',
        alwaysOpen: false,
        autoHeight: false,
        header: 'dt'
    });
}

// ログイン
function doLogin(name, pwd) {
    if (!name || name == noname) {
        alert("お名前を入力してください。");
        return false;
    }

    // 一部記号はNG
    if (name.search(/[\'\"#\$\%&<>\/\\\`\=]/i) != -1) {
        alert("一部の半角記号をお名前に使う事はできません。削除するか全角にしてみてください。");
        return false;
    }

    //特定の名前ではログインできない
    var ngNames = new Array(noname, systemName, '現在のカード', 'deckCardSet', 'deck', 'my', 'plName');
    var ngName = false;
    for(i=0; i<ngNames.length; i++){
        if (name==ngNames[i]){
            var ngName = true;
            break;
        }
    }
    if (ngName) {
        alert("そのお名前ではログインできません");
        return false;
    }

    // パラメータセット
    //データ成形
    var params =
        '?n='+convert(name)//名前
        +'&s='+'0';//状態表示
    var params =
        params+'&p='+convert(pwd);//PWD

    var params =
        params+'&y=in'
        +'&e='+(new Date()).getTime();//cacheの更新

    // 現在の入室者と同じ名前かどうかチェックしてログイン
    isMember(name, 'login', params, pwd);
}

// ログアウト
function doLogout(name) {
    //データ成形
    var params =
        '?n='+name//名前
        +'&s='+'0'//状態表示
    if($("#pwd_on").attr("value")) {
        var params =
        params
        +'&p='+convert($("#pwd_on").attr("value"));//PWD
    }
    var params =
        params+'&y=out'
        +'&e='+(new Date()).getTime();//cacheの更新

    writeComment(params, true);
}
// ログアウト時表示系処理
function pageLogout() {
    $("#online1").hide();
    $("#online2").hide();
    $("#offline").show();
    $("#pc_0").hide();
    $("#dice_shortcut").hide();
    $(".status_column").hide();
    $("#consumer_rule").hide();
    $(".add_pc").hide();
    $(".show_status").each(function(){
        this.checked = false;
    });
    $("#name_on").val("");
    $("#pwd_on").val("");
    $("#my_hash").val("");
    $("#name_off").focus();
    $('span[id^="input_textarea_"]').hide();

}

// 直前に選択していた欄を記録
function selectedColumnId(Obj, isPc) {
    if (Obj) {
        if (columnId!=Obj.id) {
            columnId = Obj.id;
        }
        if (isPc) {
            formObjId = Obj.form.id;
        }
    }
}

// ささやき設定変更(mainから）
function changeWhisperConfig(name, whisperTo) {
    var whisper_to_id = '#whisper_to_'+formObjId;
    var whisper_to_hash_id = '#whisper_to_hash_'+formObjId;
    var whisper_mark_id = '#whisper_mark_'+formObjId;
    var formId = "#"+columnId;

    if (whisper_to_hash_id) {
        var whisperIcon = whisperOnIcon;
    } else {
        if ($(whisper_mark_id).attr("src")==whisperOnIcon) {
        var whisperIcon = whisperOnIcon;
        }
    }
    if (whisper_to_hash_id) {
        $(whisper_to_id).val(name);
        $(whisper_to_hash_id).val(whisperTo);
        $(whisper_mark_id).attr("src", whisperIcon);
        $(whisper_mark_id).attr("title", "クリックでささやき解除");
        $(formId).focus();
    }
}

// ささやき設定変更クリア(indexから）
function changeWhisperConfigClear(Obj) {
    var whisper_to_id = '#whisper_to_'+Obj.form.id;
    var whisper_to_hash_id = '#whisper_to_hash_'+Obj.form.id;
    var whisper_mark_id = '#whisper_mark_'+Obj.form.id;

    $(whisper_to_id).val("全員");
    $(whisper_to_hash_id).val("");
    $(whisper_mark_id).attr("src", whisperOffIcon);
    $(whisper_mark_id).attr("title", "「ささやき」状態を表示");
}

// ダイスショートカット欄にカーソルを当てるとその欄拡張
function expandDiceShortcut(Obj) {
    var winWidth = document.body.clientWidth;

    var diceShortCut = $(".diceShortCut");
    diceShortCut.css('width', '40px');

    Obj.style.width = winWidth-380;
;
}
// ダイスショートカット欄からカーソルを離したら元通り
function shrinkDiceShortcut(Obj) {
    var diceShortCut = $(".diceShortCut");
    diceShortCut.css('width', '');
}

// クッキー関連
// クッキーの書き込み
function cookieWrite() {
    if (!checkCookie()) {
        return false;
    }

    var Expires = (60 * 60 * 24 * 1000 * CookieExpire);

    // 現在のCOOKIE取得
    var cookieValue = get_cookie_content();

    var str = setCookie(cookieValue, Expires);

    document.cookie = str;

    alert("クッキーを記録しました");
    return true;
}

// クッキーの削除
function cookieDelete() {
    if (!checkCookie()) {
        return false;
    }

    var str = setCookie("", "");

    document.cookie = str;

    alert("クッキーを削除しました");
    return true;
}

// クッキー有効か否か
function checkCookie() {
    if (!navigator.cookieEnabled) {
        alert("クッキーが無効になっています。ブラウザの設定を変更してください。");
        return false;
    }
    // クッキー名あるいは有効期限：どちらかがない場合クッキー使用しない
    if (!CookieName || CookieExpire=="0") {
        alert('チャット側の設定により、クッキー機能は無効です。');
        return false;
    }

    return true;
}

// クッキーValueセット
function setCookie(cookieValue, Expires) {
    var str = CookieName+"="+convert(cookieValue);

    // ドメイン
    domain = location.hostname;
    str += "; domain="+domain;
    // パス
    path = location.pathname.replace("index.php", "");
    str += "; path="+path;
    // 有効期限
    if (CookieExpire!='') {
        var nowtime = new Date().getTime();
        expires = new Date(nowtime + Expires);
        expires = expires.toGMTString();
        str += "; expires="+expires;
    } else {
        str += "; expires="+0;
    }

    return str;
}

// クッキーをファイルで保管
function cookiesaveFile() {
    if (!checkCookie()) {
        return false;
    }

    // ファイル名の指定
    var filename = prompt('現在のクッキーをファイルで保管します。\nファイル名を指定して下さい。','');
    if (filename == null) {
        return false;
    }

    // 現在のCOOKIE取得
    var cookieValue = get_cookie_content();

    var url = cookieSaveScript
                +'?'
                +'f='+convert(filename)
                +'&c='+convert(cookieValue);

    location.href = url;

}

// ファイルから読み込む
function isFile(id) {
    var fileName = $(id).val();
    if (!fileName) {
        alert('ファイルを指定して下さい');
        return false;
    }
    return true;
}

// 指定URLを別窓で開く
function openUrl(url, target) {
    if (!target) {
        target = '_blank';
    }
    window.open(url, target);
}

// 別窓で開く
function openNewWindow(location, target, noBar, width, height, scroll) {
    if (!location) {
        return false; 
    }
    if (!target) {
        target = _blank;
    }
    if (!width || width <= 0) {
        width = 600;
    }
    if (!height || height <= 0) {
        height = document.body.clientHeight - 80;
    }
    if (noBar) {
        showBar = 'toolbar=no,location=no,directorybottuns=no,menubar=no';
    } else {
        showBar = 'toolbar=yes,location=yes,directorybottuns=yes,menubar=yes';
    }
    if (scroll) {
        setScroll = 'scrollbars=yes';
    } else {
        setScroll = 'scrollbars=no';
    }
    var options = 'width='+width
                 +',height='+height
                 +','+showBar
                 +','+setScroll
                 +',status=yes,resizable=yes';
    return window.open(location, target, options);
}

// input/textarea フォーカス中
function inputFocus() {
    if (useSe && !isIE) {
        $("#isInputFocus").attr("checked", true);
    }
}
// input/textarea フォーカス解除
function inputBlur() {
    if (useSe && !isIE) {
        $("#isInputFocus").attr("checked", false);
    }
}

// textareaの発言者名更新
function changeTextareaPcName(Obj, id) {
    var  pc_name = Obj.pc_name.value;

    var title_selecter = "#"+id+" span.title";
    $(title_selecter).text(pc_name);
}

