//==========================================================================================================
// PC home Online 網路家庭的文字、圖片、資料、商標、標識、及網頁設計等皆受中華民國相關智慧財產權法令的保護。
// 嚴禁任何未經事先同意的非法轉載和使用。若經查知，PC home Online 網路家庭將採取必要之法律行動
//==========================================================================================================

//gcode驗證用
var m_authRandnum="";
var m_authRandcode="";
var m_authAddr="";
var m_Auth_Code="";

// 共用函式區
if(typeof($) == "undefined"){
    eval("function $(obj){return document.getElementById(obj);}");
}

function my_check_null(obj,obj_name) {
    if(obj.value == "")
        return obj_name + " 尚未填寫\n\n";
    else
        return "";
}

function my_check_radio(obj,obj_name){
    var flag = false;
    for(var i = 0;i<obj.length;i++){
        if(obj[i].checked == true) flag = true;
    }
    if(flag)
        return "";
    else
        return obj_name + " 必須選擇\n\n";
}

function my_select_all(obj,tar_obj){
    var chk = obj.checked;
    var arr = document.getElementsByTagName("INPUT");
    for(var i = 0;i<arr.length;i++){
        if(arr[i].id == tar_obj)
            arr[i].checked = chk
    }

}

function select_all(obj,tar_obj){
    var chk = obj.checked;
    var arr = document.getElementsByTagName("INPUT");
    for(var i = 0;i<arr.length;i++){
        if(arr[i].name == tar_obj)
            arr[i].checked = chk
    }

}

function check_pchome_id(pcid){
    if(pcid.value.match(/[^a-zA-Z0-9\_]/) || pcid.value.length <4 || pcid.value.length>16){
        show_msg("帳號請填入 4 至 16 個字元，組成限英文、數字以及 _ 符號");
        pcid.focus();
    }
}
function show_msg_box(mb_id){
    if(document.body.scrollTop){
        document.body.scrollTop = 0;
    }else {
        document.documentElement.scrollTop = 0;
    }
    $(document.body).setStyle({scroll:"no",overflow:"hidden"});
    var w = parseInt($(document.body).getStyle('width'))-12;
    var h = parseInt($(document.body).getStyle('height'));
    if(h>950)h=800;
    var obj = $(mb_id);

    var w1 = (w-parseInt(obj.getStyle("width")))/2;
    var h1 = (h-parseInt(obj.getStyle("height")))/3;
    obj.setStyle({left:w1+"px",top:h1+"px"});
    $('cover_layer').setStyle({left:w1+"px",top:h1+"px"});

    $('cover_layer').style.display = 'block';


    obj.style.display = 'block';
    obj.style.zIndex = parseInt($('cover_layer').getStyle("zIndex"))+1;
    $('cover_iframe').width = parseInt($(mb_id).getStyle("width"))-5+"px";
    $('cover_iframe').height = $(mb_id).getStyle("height");

    if(navigator.appVersion.indexOf("MSIE 6.0"))//ie6 div width 100% 似乎被設定到css了~
        $('mask_layer').setStyle({width:$(document.body).getStyle('width')});

    $('mask_layer').style.display = 'block';
    if(navigator.appVersion.indexOf("MSIE")>0){//ie無法隱藏scroll bar暫時將mask長度設成跟body長度一樣長
        $('mask_layer').setStyle({height:$(document.body).getStyle('height')});
        obj.setStyle({left:w1+"px",top:"150px"});
        $('cover_layer').setStyle({left:w1+2+"px",top:"154px"});
        if(mb_id == "fwd"){
            var obj = $($('fwd'));
            var obj1 = $($('fwd').childNodes[0]);
            var w = parseInt(obj.getStyle("width"))+"px";
            var h = parseInt(obj.getStyle("height"))+12+"px";
            obj1.setStyle({width:w,height:h});

        }
    }

}

function close_msg(mb_id){
    $(mb_id).style.display = 'none';
    $('cover_layer').style.display = 'none';
    $('mask_layer').style.display = 'none';
    $(document.body).setStyle({scroll:"",overflow:""});
}

function show_msg(msg){//暫時用show_msg的方式
    alert(msg);
}

function editor_getHTML(){
    var tar_string;
    if(editor._editMode == "text")
        tar_string = $('Content').value;
    else {
        if(HTMLArea.is_ie)
            tar_string = editor_iframe.document.body.innerHTML;
        else
            tar_string = document.getElementById('editor_iframe').contentDocument.body.innerHTML;
    }
    return tar_string;
}


// post.html
// 預覽
function preview(){
    if($('Subject').value == "" || editor_getHTML().replace(/[ |\r\n]/gim,"").length <= 0){
        show_msg('請先填寫標題及內容');
        return false;
    }
    $('preview_subject').innerHTML = $('Subject').value;
    $('preview_content').innerHTML = editor_getHTML();
    $('preview_area').style.display = "block";
    location.hash='preview';
    CurrentStatus.ResizeEvent();
}

//回覆頁的預覽
function preview_reply(){
    if(editor_getHTML().replace(/[ |\r\n]/gim,"").length <= 0){
        show_msg('請先填內容');
        return false;
    }
    $('preview_content').innerHTML = "";
    if(document.Reply_Form.use_ori_content[1].checked == true){
        $('preview_content').innerHTML = "<div class=\"cite\">"+$('reply_content_block').innerHTML+"</div>";
    }
    $('preview_content').innerHTML += editor_getHTML();
    $('preview_area').style.display = "block";
    location.hash='preview';
    CurrentStatus.ResizeEvent();
}

//重新編輯的預覽
function preview_edit(no){
    if(editor_getHTML().replace(/[ |\r\n]/gim,"").length <= 0){
        show_msg('請先填內容');
        return false;
    }
    if(no == 0) $('preview_subject').innerHTML = $('Subject').value;
    $('preview_content').innerHTML = "";
    if($('use_ori_content') != null){
        if(document.Post_Form.use_ori_content[1].checked == true){
            $('preview_content').innerHTML = "<div class=\"cite\">"+$('reply_content_block').innerHTML+"</div>";
        }
    }
    $('preview_content').innerHTML += editor_getHTML();
    $('preview_area').style.display = "block";
    location.hash='preview';
    CurrentStatus.ResizeEvent();
}


//快速回文的預覽
function preview_quick(){
    if(editor_getHTML().replace(/[ |\r\n]/gim,"").length <= 0){
        show_msg('請先填內容');
        return false;
    }
    $('preview_content').innerHTML = "";
    $('preview_content').innerHTML += editor_getHTML();
    $('preview_area').style.display = "block";
    location.hash='preview';
    CurrentStatus.CodeSection = "ResizeSection1";
    CurrentStatus.ResizeEvent();
    CurrentStatus.CodeSection = "ResizeSection";
}


function choose_tag(the_tag) {
    if($('tags').value == "")
        $('tags').value = the_tag.innerHTML;
    else
        $('tags').value += ','+the_tag.innerHTML;
    check_tags($('tags').value);
}

//發文前的檢查
function post_check(){
    if($('Subject').value == ""){
        show_msg('標題尚未填寫');
        $('Subject').focus();
        return false;
    }
    if(editor._editMode == "text")
        tar_string = $(Editor_Field_Name).value;
    else {
        if(HTMLArea.is_ie)
            tar_string = editor_iframe.document.body.innerHTML;
        else
            tar_string = document.getElementById('editor_iframe').contentDocument.body.innerHTML;
    }
    if(String_Min_Limit > 0 && tar_string.stripTags().length < String_Min_Limit) {
        alert('至少需輸入 '+String_Min_Limit+' 個字');
        return false;
    }
    var art_type = document.getElementsByName("article_type");

    if(art_type.length > 0 && document.getElementsByName("article_type")[1].checked == true ) {
        if($('read_limit_reply').checked == false && $('read_limit_points_chk').checked == false) {
            alert('請至少要選擇一種閱讀限制');
            return false;
        }
        if($('read_limit_points_chk').checked == true) {
            if(!$('read_limit_points').value.match(/^\d*$/)) {
                alert('積分只能輸入數字');
                $('read_limit_points').focus();
                return false;
            }
            if($('read_limit_points').value == 0) {
                alert('請輸入積分');
                $('read_limit_points').focus();
                return false;
            }
        }
    }

    var flag = true;
    new Ajax.Request("/editor/check_html.php", {
        parameters: $H({html: tar_string}),
        asynchronous:false,
        onSuccess: function(transport) {
            if(transport.responseText.substr(0,1) == 0){
                alert(transport.responseText.substr(1,transport.responseText.length));
                flag = false;
            } else {
                $(Editor_Field_Name).value = transport.responseText.substr(1,transport.responseText.length);
                flag = true;
            }
        }
    });
    if(!flag) return false;
    if(tar_string.replace(/[ |\r\n]/gim,"").length == 0) {
        show_msg('您尚未輸入任何內容');
        editor.focusEditor();
        return false;
    }
    if(!check_tags($('tags').value)){
        $('tags').focus();
        return false;
    }
    if(gcode_test("Gcode_Space") == 0) return false;
    document.Post_Form.action = "/post_do.php";
    document.Post_Form.submit();
}

function re_post_check(){
    var tf = document.Post_Form;
    if( typeof(tf.Subject) != "undefined"){
        if($('Subject').value == ""){

            show_msg('標題尚未填寫');
            $('Subject').focus();
            return false;
        }
    var art_type = document.getElementsByName("article_type");
       if(art_type.length > 0 && document.getElementsByName("article_type")[1].checked == true) {
            if($('read_limit_reply').checked == false && $('read_limit_points_chk').checked == false) {
                alert('請至少要選擇一種閱讀限制');
                return false;
            }
            if($('read_limit_points_chk').checked == true) {
                if(!$('read_limit_points').value.match(/^\d*$/)) {
                    alert('積分只能輸入數字');
                    $('read_limit_points').focus();
                    return false;
                }
                if($('read_limit_points').value == 0) {
                    alert('請輸入積分');
                    $('read_limit_points').focus();
                    return false;
                }
            }
        }
    }
    if(editor._editMode == "text")
        tar_string = $(Editor_Field_Name).value;
    else {
        if(HTMLArea.is_ie)
            tar_string = editor_iframe.document.body.innerHTML;
        else
            tar_string = document.getElementById('editor_iframe').contentDocument.body.innerHTML;
    }
    if(String_Min_Limit > 0 && tar_string.stripTags().length < String_Min_Limit) {
        alert('至少需輸入 '+String_Min_Limit+' 個字');
        return false;
    }
    var flag = true;
    new Ajax.Request("/editor/check_html.php", {
        parameters: $H({html: tar_string}),
        asynchronous:false,
        onSuccess: function(transport) {
            if(transport.responseText.substr(0,1) == 0){
                alert(transport.responseText.substr(1,transport.responseText.length));
                flag = false;
            } else {
                $(Editor_Field_Name).value = transport.responseText.substr(1,transport.responseText.length);
                flag = true;
            }
        }
    });
    if(!flag) return false;
    if(tar_string.replace(/[ |\r\n]/gim,"").length == 0) {
        show_msg('您尚未輸入任何內容');
        editor.focusEditor();
        return false;
    }
    if( typeof(tf.tags1) != "undefined"){
        if(!check_tags($('tags1').value)){
            $('tags1').focus();
            return false;
        }
    }
    document.Post_Form.action = "/edit_do.php";
    document.Post_Form.submit();
}

//回文前的檢查
function reply_quick_check(){
    if(editor_getHTML().length == 0) {
        show_msg('您尚未輸入任何內容');
        editor.focusEditor();
        return false;
    }
    if(editor._editMode == "text")
        tar_string = $(Editor_Field_Name).value;
    else {
        if(HTMLArea.is_ie)
            tar_string = editor_iframe.document.body.innerHTML;
        else
            tar_string = document.getElementById('editor_iframe').contentDocument.body.innerHTML;
    }
    if(String_Min_Limit > 0 && tar_string.stripTags().length < String_Min_Limit) {
        alert('至少需輸入 '+String_Min_Limit+' 個字');
        return false;
    }
    var flag = true;
    new Ajax.Request("/editor/check_html.php", {
        parameters: $H({html: tar_string}),
        asynchronous:false,
        onSuccess: function(transport) {
            if(transport.responseText.substr(0,1) == 0){
                alert(transport.responseText.substr(1,transport.responseText.length));
                flag = false;
            } else {
                $(Editor_Field_Name).value = transport.responseText.substr(1,transport.responseText.length);
                flag = true;
            }
        }
    });
    if(!flag) return false;
    if(tar_string.replace(/[ |\r\n]/gim,"").length == 0) {
        show_msg('您尚未輸入任何內容');
        editor.focusEditor();
        return false;
    }
    if(gcode_test("Gcode_Space") == 0) return false;
    document.Reply_Form.action = "/reply_quick_do.php";
    document.Reply_Form.submit();
}

//回文前的檢查
function reply_check(){
    if(editor._editMode == "text")
        tar_string = $(Editor_Field_Name).value;
    else {
        if(HTMLArea.is_ie)
            tar_string = editor_iframe.document.body.innerHTML;
        else
            tar_string = document.getElementById('editor_iframe').contentDocument.body.innerHTML;
    }
    if(String_Min_Limit > 0 && tar_string.stripTags().length < String_Min_Limit) {
        alert('至少需輸入 '+String_Min_Limit+' 個字');
        return false;
    }
    var flag = true;
    new Ajax.Request("/editor/check_html.php", {
        parameters: $H({html: tar_string}),
        asynchronous:false,
        onSuccess: function(transport) {
            if(transport.responseText.substr(0,1) == 0){
                alert(transport.responseText.substr(1,transport.responseText.length));
                flag = false;
            } else {
                $(Editor_Field_Name).value = transport.responseText.substr(1,transport.responseText.length);
                flag = true;
            }
        }
    });
    if(!flag) return false;
    if(tar_string.replace(/[ |\r\n]/gim,"").length == 0) {
        show_msg('您尚未輸入任何內容');
        editor.focusEditor();
        return false;
    }
    if(gcode_test("Gcode_Space") == 0) return false;
    document.Reply_Form.action = "/reply_do.php";
    document.Reply_Form.submit();
}

// 標查標籤格式是否合法：長度最多100字元
function check_tags(tag){
    var n = 1;
    var a = tag.match(/"/gmi);
    var pass_check = true;
    if(a != null){
        if(a.length % 2 != 0) {
            show_msg('標籤裡的 " 必需成對!');
            pass_check = false;
        }
    }
    var reg = /\"[^\"]*[\"\ |\"$]/gmi;
    var b = tag.match(reg);
    var tag1 = tag.replace(reg,"");
    var c = tag1.match(/[^\ ]+/gmi);
    var len = 0;
    var total_len = 0;
    var limit_len = 100;
    if(b != null) {
        len += b.length;
        for(var i=0;i<b.length;i++){
            b[i] = b[i].replace(/\"/gim,"");
            total_len += b[i].length;
            if(b[i].length > limit_len) {
                show_msg("單一標籤的長度限制\n\""+b[i]+"\"的長度："+b[i].length);
                pass_check = false;
            }
        }
    }
    if(c != null) {
        len += c.length;
        for(var i=0;i<c.length;i++){
            total_len += c[i].length;
            if(c[i].length > limit_len) {
                show_msg("單一標籤的長度超過限制\n\""+c[i]+"\"的長度："+c[i].length);
                pass_check = false;
            }
        }
    }
    if(total_len > limit_len){
        show_msg("標籤的長度超過限制");
        pass_check = false;
    }
    //限制組數
    //if(len > 5) {
    //    show_msg("您輸入了 " + len + " 組標籤\n\n系統只允許輸入5組標籤");
    //    pass_check = false;
    //}
    return pass_check;
}

function print_friendly(){
    $('for_friend_print').value = document.body.innerHTML;
    $('print_form').target="print_win";
    $('print_form').action = "/print/";
    $('print_form').method="post";
    $('print_form').submit();
    $('for_friend_print').value = "";
}

function my_print(){//友善列印頁用
    window.print();

    //window.close();
}

function c_f_s(size){ //改變字型大小-單文頁用
    var arr = document.getElementsByTagName("div");
    for(var i = 0;i<arr.length;i++){
        if(arr[i].id == "SizeToChange")
            arr[i].className = size;
    }
    var arr1 = document.getElementsByTagName("a");
    $A(document.getElementsByName("csl_s")).each(function(s){
        s.style.backgroundColor = "#FFFFFF";
    });
    $A(document.getElementsByName("csl_m")).each(function(s){
        s.style.backgroundColor = "#FFFFFF";
    });
    $A(document.getElementsByName("csl_l")).each(function(s){
        s.style.backgroundColor = "#FFFFFF";
    });
    if(size == "say_s") {
        $A(document.getElementsByName("csl_s")).each(function(s){
            s.style.backgroundColor = "#F1F1F1";
        });
    }
    if(size == "say_m") {
        $A(document.getElementsByName("csl_m")).each(function(s){
            s.style.backgroundColor = "#F1F1F1";
        });
    }
    if(size == "say_l") {
        $A(document.getElementsByName("csl_l")).each(function(s){
            s.style.backgroundColor = "#F1F1F1";
        });
    }
}

function forward_content(fid,tid){// 轉寄給好友
    document.body.scroll = "no";
    document.body.style.overflow = "hidden";
    document.onmousemove = function () { return false; };
    fwd_iframe.location.href="/forward/" + fid + "/" + tid;
    window.setTimeout("$(\"fwd\").style.display = \"block\";", 1000);


}


function search_tag(obj){// 點了某個標籤查詢
    var tf = document.ts_form;
    tf.search_keyword.value = obj.innerHTML;
    tf.submit();
}
function tag_search_index(tag_name) {
    var tf = document.Search_Form;
    tf.search_type[2].checked = true;
    tf.search_keyword.value = tag_name;
    tf.boards.selectedIndex = 0;
    tf.submit();

}

function reply_btn_click(reply_tid,reply_floors,reply_posttime,reply_user_id){
    var tf = document.reply_form;
    tf.reply_tid.value = reply_tid;
    tf.reply_floors.value = reply_floors;
    tf.reply_posttime.value = reply_posttime;
    tf.reply_user_id.value = reply_user_id;
    var reply_content1 = document.getElementById('ContentToUse'+reply_tid).innerText;
    if(reply_content1.length > 150) reply_content1 = reply_content1.substring(0,147)+"...";
    tf.reply_content.value = reply_content1;
    tf.reply_subject.value = $('SubjectToReply').innerText;
    tf.submit();
}

function report_btn_click(report_tid,report_user_id){
    var tf = document.Report_Form;
    tf.tid.value = report_tid;
    tf.author.value = report_user_id;
    tf.subject.value = $('SubjectToReply').innerText;
    tf.submit();
}

var rbt = "";
function chg_disp(rb,obj,disp){
    rbt = rb.value;
    $(obj).style.display = disp;
}

function report_check(){
    var tf = document.Report_Form;
    var check_str = "";
    check_str += my_check_radio(tf.reply_type,"回報類型");
    check_str += my_check_null(tf.memo,"附加訊息");
    if(tf.reply_type[0].checked == true){
        if(tf.advise_area.value == "-1"){
            check_str += "建議分區尚未選擇\n\n";
        }
    }
    if(check_str != ""){
        show_msg(check_str);
        return false;
    } else {
        new Ajax.Request("/site_report_do.php", {
        parameters: $H({reply_type: rbt,
                        advise_area:tf.advise_area.value,
                        subject:encodeURI(tf.subject.value),
                        memo: encodeURI(tf.memo.value),
                        author:encodeURI(tf.author.value),
                        tid:tf.tid.value,
                        fid:tf.fid.value,
                        my_type:"add",
                        floor:tf.floor.value,
                        ori_tid:tf.ori_tid.value}).toQueryString(),
        onSuccess: function(transport) {
            if(transport.responseText == "success") {
                show_msg('感謝您提供寶貴的資料');
                if($F('ori_tid') != "0")
                    location.href="/content/"+tf.fid.value+"/"+$F('ori_tid')+"/rt-"+$F('tid');
                else
                    location.href="/content/"+tf.fid.value+"/"+tf.tid.value;
            } else
                show_msg(transport.responseText);
        }
        });
    }
}



//黑名單
//新增黑名單
function black_list_add(bn,bm){
    if(bn.value == "輸入帳號ID" || bn.value == ""){
        show_msg("輸入帳號ID");
        bn.focus();
        return false;
    }
    if(bm.value == "輸入備註 （最多20個字）" || bm.value == ""){
        show_msg("輸入備註");
        bn.focus();
        return false;
    }

    new Ajax.Request("/member/admin/my_black_list_do.php", {
    parameters: $H({bk_name: bn.value, bk_mark: bm.value,my_type:"add"}).toQueryString(),
    onSuccess: function(transport) {
        if(transport.responseText == "add success")
            location.href="/my_admin/black_list/";
        else
            show_msg(transport.responseText);
    }
    });

}

function black_list_add_fast(bn){
    if(bn == ""){
        show_msg("error test");
        return false;
    }
    new Ajax.Request("/member/admin/my_black_list_do.php", {
    parameters: $H({bk_name: bn, bk_mark: "",my_type:"add"}).toQueryString(),
    onSuccess: function(transport) {
        if(transport.responseText == "add success"){
            alert('已成功將 ' + bn + " 加入黑名單");
            location.reload();
        } else
            show_msg(transport.responseText);
    }
    });

}

//刪除黑名單
function black_list_del(bid){
    var arr = document.getElementsByTagName('INPUT');
    var have_data=0
    var have_check = 0;
    var bid_string = "";
    for(var i = 0;i<arr.length;i++){
        if(arr[i].id == bid){
            have_data++;
            if(arr[i].checked == true) {
                have_check++;
                bid_string += ","+arr[i].value;
            }
        }
    }
    if(have_data <=0) {
        show_msg('沒有任何黑名單');
        return false;
    }
    if(have_check <=0) {
        show_msg('您尚未勾選任何黑名單');
        return false;
    }
    bid_string = bid_string.substr(1,bid_string.length);
    if(confirm('確定要解除封鎖?')){
        new Ajax.Request("/member/admin/my_black_list_do.php", {
        parameters: $H({bids: bid_string,my_type:"del"}).toQueryString(),
        onSuccess: function(transport) {
            if(transport.responseText == "del success"){
                show_msg("已成功解除封鎖");
                location.href="/my_admin/black_list/";
            } else
                show_msg(transport.responseText);
        }
        });
    }
}

function black_list_del_fast(bid){
    new Ajax.Request("/member/admin/my_black_list_do.php", {
    parameters: $H({bids: bid,my_type:"del"}).toQueryString(),
    onSuccess: function(transport) {
        if(transport.responseText == "del success"){
            show_msg("已成功解除封鎖");
            location.reload();
        } else
            show_msg(transport.responseText);
    }
    });

}

//修改黑名單
function black_list_edit(){
    var arr = document.getElementsByTagName('INPUT');
    var have_data=0
    var bid_string = "";
    var params;
    //組合開頭為bk_mark所有input的值
    for(var i = 0;i<arr.length;i++){
        if(arr[i].id.substr(0,7) == "bk_mark"){
            have_data++;
            bid_string += "," + arr[i].id + "=" + encodeURI(arr[i].value);
        }
    }
    if(have_data <=0) {
        show_msg('沒有任何黑名單');
        return false;
    }

    bid_string = bid_string.substr(1,bid_string.length);
    new Ajax.Request("/member/admin/my_black_list_do.php", {
    parameters: $H({params: bid_string,my_type:"edit"}).toQueryString(),
    onSuccess: function(transport) {
        if(transport.responseText == "edit success"){
            show_msg("更新成功!");
            location.reload();
        }else
            show_msg(transport.responseText);
    }
    });
}

//功能 type1 : 1=>收藏 2=>推薦 3=>訂閱單文 4=>訂閱版
function collect(type1,fid1,tid1){
    var msg_arr = new Array("","本文章已加入我的收藏","推薦成功!","訂閱成功!","訂閱成功!","停止訂閱成功!","停止訂閱成功!");
    var span_arr = new Array("","blu_","blu_1");
    new Ajax.Request("/collect_do.php", {
    parameters: $H({type: type1,fid:fid1,tid:tid1}).toQueryString(),
    onSuccess: function(transport) {
        if(transport.responseText == "success"){
            show_msg(msg_arr[type1]);
            $A($$('span.'+span_arr[type1])).each(function(s){s.innerHTML = parseInt(s.innerHTML)+1;});
        }else {
            var aaa = location.href.split("/");
            if(transport.responseText == "此為會員專屬功能，請先登入。") {
                location.href="/oops/login/1/"+aaa[aaa.length-3]+"_"+aaa[aaa.length-2]+"_"+aaa[aaa.length-1];
            } else
                show_msg(transport.responseText);
        }
    }
    });
}


function check_modify_file(){

    if($('is_mysex').checked == true) var isms = 1;
    else var isms = 0;

    if($('is_mybirth').checked == true) var ismb = 1;
    else var ismb = 0;

    if($('mypaper_link').value == "-1") var mpl = "";
    else var mpl = $('mypaper_link').value;

    var mpn = $('mypaper_name').value;


    //josh mod 10/21 相簿應pm要求更改成只有開跟關 =皿=
    var mptl = "";
    $A($$("input.myphoto_link")).each(function(s){if(s.checked == true) mptl = s.value;});

//alert($('Photo_Nick_Name').value);


 // if($('myphoto_link').value == "-1") var mptl = "";
 // else var mptl = $('Photo_Nick_Name').value + "/" + $('myphoto_link').value;

    var mptn = $('Photo_Name').value;


    //等級5以上 簽名檔字數限制 300，不到5級的100
    //          簽名檔可用html，不到5級的濾掉

    if($('level').value >= 5) {
        var sing_max = 300;
        //var sn = $('sign').value;
    }else{
        var sing_max = 100;
        //var sn = $('sign').value.replace(/</g,'&lt;');
    }
    sn = $F('sign');

    if($('sign').value.length > sing_max) {
        show_msg('簽名檔長度超過限制');
        $('sign').focus();
        return false;
    }


    var tf = document.mmf;

    if(tf.is_mail_alert[0].checked == true) var ima = 1;
    else var ima = 0;

    if(tf.is_myfriend[0].checked == true) var imf = 1;
    else var imf = 0;

    if(tf.is_mypost[0].checked == true) var imp = 1;
    else var imp = 0;

    if(tf.is_myreply[0].checked == true) var imrp = 1;
    else var imrp = 0;

    if(tf.is_footstep[0].checked == true) var imfs = 1;
    else var imfs = 0;

    var the_uid = $('uid').value;

    if(tf.is_mymsg[0].checked == true) var ismmg = 1;
    else var ismmg = 0;



    new Ajax.Request("/member/admin/my_modify_file_do.php", {
        parameters: $H({is_mysex        :isms,
                        is_mybirth      :ismb,
                        mypaper_link    :mpl,
                        mypaper_name    :mpn,
                        myphoto_link    :mptl,
                        myphoto_name    :mptn,
                        sign            :sn,
                        is_mail_alert   :ima,
                        is_myfriend     :imf,
                        is_mypost       :imp,
                        is_myreply      :imrp,
                        is_mymsg        :ismmg,
                        is_footstep     :imfs,
                        level           :$F('level'),
                        uid             :the_uid}).toQueryString(),
        onSuccess: function(transport) {
            if(transport.responseText == "success"){
                show_msg("更新成功!");
                location.href=location.href;
            }else
                show_msg(transport.responseText);
        }
    });
}

//刪除文章
function delete_article(fid1,tid1,rp,flr,first_tid){
    if(confirm('確定要刪除')){
        new Ajax.Request("/delete_article_do.php", {
        parameters: $H({fid:fid1,tid:tid1}).toQueryString(),
        onSuccess: function(transport) {
            if(transport.responseText == "success"){
                show_msg("已成功刪除");
                if(flr == 1)
                    location.href= '/forum_index/'+fid1;
                else
                    location.href= '/content/'+fid1+'/'+first_tid;
            }else
                show_msg(transport.responseText);
        }
        });
    }
}



//gcode驗證用
function gcode_test(Gcode_Space){
    var flag = 0;
    new Ajax.Request("/Gcode_Auth.php", {
        parameters: $H({authRandnum: $('authRandnum').value,
                        authRandcode:$('authRandcode').value,
                        authAddr:$('authAddr').value}).toQueryString(),
        asynchronous: false,
        onSuccess: function(transport) {
            if(transport.responseText.substr(0,1) == "1") {
                flag = 1;
                $('Auth_Code').value = transport.responseText.substr(2,transport.responseText.length);
            } else {
                flag = 0;
                alert('驗證失敗！驗證碼重新產生');
                reset_gcode(Gcode_Space);
            }
        }
    });
    return flag;
}

//gcode重設
function reset_gcode(Gcode_Space){
    new Ajax.Request("/Gcode_Api1.php", {
        parameters: $H({abc: "def"}).toQueryString(),
        onSuccess: function(transport) {
            $(Gcode_Space).innerHTML = transport.responseText;
            //Gcode_Space為存放gcode的容器（div or td or 其它tag的id)
        }
    });

}



function check_email(email){
    return email.match(/^\S+@\S+\.\S+$/);
}

function fwd(obj){
    obj.disabled = true;
    obj.value = "傳送中";
    var flag = true;
    if($('fname').value == ""){
        alert('請輸入您的名字');
        $('fname').focus();
        flag = false;
    }
    if(flag == true && check_email($('femail').value) == null){
        alert('您的e-mail格式不正確');
        $('femail').focus();
        flag = false;
    }
    if(flag == true && $('tname').value == ""){
        alert('請輸入收件者名字');
        $('tname').focus();
        flag = false;
    }
    if(flag == true && check_email($('temail').value) == null){
        alert('收件者e-mail格式不正確');
        $('temail').focus();
        flag = false;
    }
    if(flag == true)
        if(gcode_test("Gcode_Space") == 0) flag = false;
    if(flag == false){
        obj.disabled = false;
        obj.value = "確認送出";
        return flag;
    }
    var pqsb = parent.window.location.href;
    var pqsa = pqsb.split("?");
    pqs = pqsa[1];
    new Ajax.Request("/forward_do.php", {
    parameters: $H({fname       :$('fname').value,
                    femail      :$('femail').value,
                    tname       :$('tname').value,
                    temail      :$('temail').value,
                    qs          :pqs,
                    Auth_Code   :$('Auth_Code').value,
                    subject     :parent.$('fwd_subject').value,
                    content     :parent.$('fwd_content').value,
                    ref_page    :parent.$('fwd_page').value}).toQueryString(),
    onSuccess: function(transport) {
        if(transport.responseText == "success"){
            show_msg('轉寄成功!');
            $('tname').value = "";
            $('temail').value= "";
            obj.disabled = false;
            obj.value = "確認送出";
            reset_gcode('Gcode_Space');
            parent.close_msg('fwd');
        }else
            show_msg(transport.responseText);
            obj.disabled = false;
            obj.value = "確認送出";
        }
    });
}

function fwd_reset(){
    $('fname').value = $('fname').defaultValue;
    $('femail').value= $('femail').defaultValue;
    $('tname').value = "";
    $('temail').value= "";
    reset_gcode('Gcode_Space');
}

function check_checkbox(){
    var flag = false;
    $A(document.getElementsByTagName("INPUT")).each(function(s){if(s.name=="tid_ary[]" && s.checked == true)flag = true});
    if(flag == false) alert('您尚未勾選任何主題');
    return flag;
}

function addLoadListener(fn) {
    if (typeof window.addEventListener != 'undefined') {
        window.addEventListener('load', fn, false);
    }  else if (typeof document.addEventListener != 'undefined') {
        document.addEventListener('load', fn, false);
    } else if (typeof window.attachEvent != 'undefined') {
        window.attachEvent('onload', fn);
    } else {
        var oldfn = window.onload;
        if (typeof window.onload != 'function') {
            window.onload = fn;
        } else {
            window.onload = function() {
                oldfn();
                fn();
            };
        }
    }
}

function getPosition(theElement) {
	var positionX = 0;
	var positionY = 0;
	while (theElement != null) {
		positionX += theElement.offsetLeft;
		positionY += theElement.offsetTop;
		theElement = theElement.offsetParent;
	}
	return [positionX, positionY];
}

function getPageScroll(){
	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll)
	return arrayPageScroll;
}

function getPageSize() {
	var xScroll, yScroll;

	if (window.innerHeight && window.scrollMaxY) {
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}

	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}

	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else {
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
	return arrayPageSize;
}

function KeyDownSearch2(evt){
	if (evt.keyCode == 13) nextlink(document.getElementById('objfrm'));
}

function SearchBlur() {
	var selTxt = document.getElementById("search_txt").value;
	if (selTxt.length == 0) document.getElementById("search_txt").value = '請輸入關鍵字';
}

function nextlink(obj){
	var sLink = "";
	var chid = 'forum';
	var site_kind = document.getElementById("site_kind").value
	var selTxt = document.getElementById("search_txt").value;
	sLink = 'http://google.pchome.com.tw/channel/ch2_header.jsp?chid=' + chid + '&site_kind=' + site_kind + '&q=' + selTxt;
	sLink = encodeURI(sLink);
	if(site_kind == "local")
	    obj.action = "/search_result/";
	else
	    obj.action = sLink;
}

var recmdPos = 0;
function recmdMoveTo(no) {
    if($A($$('div.hdtab_on')).length > 0)
        $A($$('div.hdtab_on'))[0].className = "hdtab";
    if(typeof $A($$('div.hdtab'))[no] != "object") return;
    $A($$('div.hdtab'))[no].className = "hdtab_on";
    recmdPos = 0-(no*660);
    $('recmd_area').style.left = recmdPos+"px";
    //recmdMove();
}

function recmdMove() {
    var maxPos = 200;
    var minPos = 5;
    var np = parseInt($('recmd_area').style.left);
    if(np == recmdPos) {
        $('mask').style.display='none';
        return;
    }

    $('mask').style.display='';
    var mp = Math.abs((np-recmdPos)/3);
    mp = mp > maxPos ? maxPos : mp < minPos ? minPos : mp;
    if(np > recmdPos){
        if(np-mp<recmdPos)
            $('recmd_area').style.left = recmdPos+"px";
        else
            $('recmd_area').style.left = np-mp+"px";
    } else {
        if(np+mp>recmdPos)
            $('recmd_area').style.left = recmdPos+"px";
        else
            $('recmd_area').style.left = np+mp+"px";
    }

    setTimeout(recmdMove,25);
}


function setOpacity(obj, opacity) {
    opacity = (opacity >= 100)?99.999:opacity;

    // IE/Win
    obj.style.filter = "alpha(opacity:"+opacity+")";

    // Safari<1.2, Konqueror
    obj.style.KHTMLOpacity = opacity/100;

    // Older Mozilla and Firefox
    obj.style.MozOpacity = opacity/100;

    // Safari 1.2, newer Firefox and Mozilla, CSS3
    obj.style.opacity = opacity/100;
}

function identifyBrowser() {
  var agent = navigator.userAgent.toLowerCase();

  if (typeof navigator.vendor != "undefined" && navigator.vendor == "KDE" &&
      typeof window.sidebar != "undefined")
  {
    return "kde";
  }
  else if (typeof window.opera != "undefined")
  {
    var version = parseFloat(agent.replace(/.*opera[\/ ]([^ $]+).*/, "$1"));

    if (version >= 7)
    {
      return "opera7";
    }
    else if (version >= 5)
    {
      return "opera5";
    }

    return false;
  }
  else if (typeof document.all != "undefined")
  {
    if (typeof document.getElementById != "undefined")
    {
      var browser = agent.replace(/.*ms(ie[\/ ][^ $]+).*/, "$1").replace(/ /, "");

      if (typeof document.uniqueID != "undefined")
      {
        if (browser.indexOf("5.5") != -1)
        {
          return browser.replace(/(.*5\.5).*/, "$1");
        }
        else
        {
          return browser.replace(/(.*)\..*/, "$1");
        }
      }
      else
      {
        return "ie5mac";
      }
    }

    return false;
  }
  else if (typeof document.getElementById != "undefined")
  {
    if (navigator.vendor.indexOf("Apple Computer, Inc.") != -1)
    {
      if (typeof window.XMLHttpRequest != "undefined")
      {
        return "safari1.2";
      }

      return "safari1";
    }
    else if (agent.indexOf("gecko") != -1)
    {
      return "mozilla";
    }
  }
  return false;
}
function trim(str){
  return str.replace(/^\s*|\s*$/g,"");
}
function CalculateTxt(EventTitle) {
	var lengthTmp = 0;
	for (var i=0;i<EventTitle.length;i++) {
		if ((EventTitle.charCodeAt(i) >= 33 && EventTitle.charCodeAt(i) <= 255) || (EventTitle.charAt(i) == ' ')) {
			lengthTmp += 1;
		} else {
			lengthTmp += 2;
		}
	}
	return lengthTmp;
}
function TextLengthLimit(Content, LengthLimit) {
	var NewContent = '';
	var LengthTmp = 0;
	var LimitSet =  (LengthLimit) ? LengthLimit : 20;
	for (var i=0;i<Content.length;i++) {
		LengthTmp = ((Content.charCodeAt(i) >= 33 && Content.charCodeAt(i) <= 255) || Content.charAt(i) == ' ') ? LengthTmp + 1 : LengthTmp + 2;
		if (LengthTmp <= LimitSet) NewContent += Content.charAt(i);
		else { NewContent += '...'; break; }
	}//end for
	return NewContent;
}

function RollingNotice(id, DataObj) {
    this.id = id;
    this.DataObj = DataObj;
    this.CodeSection = this.DataObj.CodeSection;
    this.ElementWidth = this.DataObj.ElementWidth;
    this.ElementHeight = this.DataObj.ElementHeight;
    this.ElementRowAmt = (this.DataObj.ElementRowAmt) ? this.DataObj.ElementRowAmt : 1;
    this.NoticeAmt =  this.DataObj.NoticeInfo.length;
    this.TotalAmt = Math.ceil(this.NoticeAmt/this.ElementRowAmt);
    this.ColAmt = this.DataObj.ColAmt;
    this.SectionHeight = this.ElementRowAmt * this.ElementHeight;
    this.Timer = this.DataObj.Timer; //ms
    this.TodatTime = new Date();
    this.TetxLength = [Math.floor(this.Element  /6)-3, Math.floor((this.ElementWidth-22)/6)-3];
    this.FuncID = -1;
    this.getNoticeSet = '';
    this.getNoticeElement = [];
    this.BlockAction = (this.TotalAmt == 1) ? true : false;
    this.IntervalID = '';
    this.TimerIntervalID = '';
    //method
    this.SignConfirm = function(SerialID) {
        var DateArray = this.DataObj.NoticeInfo[SerialID].regidate.split('-');
        var FuncDate = new Date(DateArray[0], parseInt(DateArray[1], 10) - 1, DateArray[2]);
        return ((this.TodatTime.getTime()-FuncDate.getTime())/86400000 > 7) ? false : true;
    }
    this.CalculateTxt = function(Content) {
        var LengthTmp = 0;
        for (var i=0; i<Content.length; i++) {
            if (Content.charCodeAt(i) == ' ') LengthTmp += 1;
            else if (Content.charCodeAt(i) >= 33 && Content.charCodeAt(i) <= 255) {
                LengthTmp = (Content.charCodeAt(i) >= 65 && Content.charCodeAt(i) <= 90) ? LengthTmp + 2 : LengthTmp + 1;
            } else LengthTmp += 2;
        }//end for
        return LengthTmp;
    }
    this.TextLengthLimit = function(Content, LengthLimit) {
        var NewContent = '';
        var LengthTmp = 0;
        var LengthNow = this.CalculateTxt(Content);
        if (LengthNow > LengthLimit) {
            for (var i=0; i<Content.length; i++) {
                if (Content.charCodeAt(i) == ' ') LengthTmp += 1;
                else if (Content.charCodeAt(i) >= 33 && Content.charCodeAt(i) <= 255) {
                    LengthTmp = (Content.charCodeAt(i) >= 65 && Content.charCodeAt(i) <= 90) ? LengthTmp + 2 : LengthTmp + 1;
                } else LengthTmp += 2;
                if (LengthTmp <= LengthLimit) NewContent += Content.charAt(i); else break;
            }
            NewContent += '...';
        } else NewContent = Content;
        return NewContent;
    }
    this.VaryAction = function() {
        if (this.BlockAction) return;
        this.FuncID++;
        if (this.FuncID > this.getNoticeElement.length-1) this.FuncID = 0;
        this.getNoticeSet.MoveFlagX = false;
        this.getNoticeSet.MoveFlagY = false;
        this.getNoticeSet.GoalX = this.getNoticeElement[this.FuncID].GoalX;
        this.getNoticeSet.GoalY = this.getNoticeElement[this.FuncID].GoalY;
        //doMove
        var speed = 10;
        clearInterval(this.IntervalID);
        this.IntervalID = setInterval('RollingNotice'+this.id+'.realMoveNew('+speed+')', 15);
        this.BlockAction = true;
    }
    this.realMoveNew = function(speed) {
        var ObjX = this.getNoticeSet.PosX;
        var ObjY = this.getNoticeSet.PosY;

        var a = this.getNoticeSet.GoalX - ObjX;
        var speedx = a/speed;
        var SignX = (speedx < 0) ? -1 : 1;
        speedx = Number(SignX * ((Math.abs(speedx) <= 1) ? 1 : Math.abs(speedx)));

        var b = this.getNoticeSet.GoalY - ObjY;
        var speedy = b/speed;
        var SignY = (speedy < 0) ? -1 : 1;
        speedy = Number(SignY * ((Math.abs(speedy) <= 1) ? 1 : Math.abs(speedy)));

        //check x position
        if (!this.getNoticeSet.MoveFlagX) {
            if (Math.abs(ObjX-this.getNoticeSet.GoalX) <= Math.abs(speedx)) { this.getNoticeSet.PosX = this.getNoticeSet.GoalX; this.getNoticeSet.MoveFlagX = true;    }
            else this.getNoticeSet.PosX = ObjX + speedx;
        }

        //check y position
        if (!this.getNoticeSet.MoveFlagY) {
            if (Math.abs(ObjY-this.getNoticeSet.GoalY) <= Math.abs(speedy)) { this.getNoticeSet.PosY = this.getNoticeSet.GoalY; this.getNoticeSet.MoveFlagY = true;    }
            else this.getNoticeSet.PosY = ObjY + speedy;
        }

        this.getNoticeSet.style.left = this.getNoticeSet.PosX + 'px';
        this.getNoticeSet.style.top = this.getNoticeSet.PosY + 'px';

        if (this.getNoticeSet.MoveFlagX && this.getNoticeSet.MoveFlagY) {
            clearInterval(this.IntervalID);
            this.BlockAction = false;
            clearTimeout(this.TimerIntervalID);
            this.TimerIntervalID = setTimeout('RollingNotice'+this.id+'.VaryAction()', this.Timer);
        }
    }
    this.constructor = RollingNoticeConstructor;
    this.constructor();
    $('run_news').style.display='block';
}

function RollingNoticeConstructor() {
    if (!$(this.CodeSection)) return;
    var RollingNotice = $(this.CodeSection);
    while (RollingNotice.childNodes.length > 0) RollingNotice.removeChild(RollingNotice.firstChild);
    RollingNotice.style.width = this.ElementWidth + 'px';
    RollingNotice.style.height = this.SectionHeight + 'px';
    RollingNotice.style.clip = 'rect(3px, ' + this.ElementWidth + 'px, ' + (parseInt(this.SectionHeight)+3) + 'px, 0px)';

    var NoticeSet = document.createElement('div');
    NoticeSet.className = 'RollingNotice';
    NoticeSet.style.left = '0px';
    NoticeSet.style.top = '0px';
    NoticeSet.PosX = 0;
    NoticeSet.PosY = 0;
    NoticeSet.MoveFlagX = false;
    NoticeSet.MoveFlagY = false;
    NoticeSet.GoalX = 0;
    NoticeSet.GoalY = 0;
    RollingNotice.appendChild(NoticeSet);
    this.getNoticeSet = NoticeSet;
    this.getNoticeElement = [];
    for (var i=0; i<this.TotalAmt; i++) {
        var Column = i % this.ColAmt;
        var Row = Math.floor(i/this.ColAmt);
        var PosX = Column * this.ElementWidth;
        var PosY = Row * this.SectionHeight;
        var BaseValue = i * this.ElementRowAmt;
        var RollingNoticeElement = document.createElement('div');
        RollingNoticeElement.style.position = 'absolute';
        RollingNoticeElement.style.width = this.ElementWidth + 'px';
        RollingNoticeElement.style.height = this.SectionHeight + 'px';
        RollingNoticeElement.style.left = PosX + 'px';
        RollingNoticeElement.style.top = PosY + 'px';
        RollingNoticeElement.ClassID = this.id;
        RollingNoticeElement.Serial = i;
        RollingNoticeElement.GoalX = PosX * -1;
        RollingNoticeElement.GoalY = PosY * -1;

        for (var j=0; j<this.ElementRowAmt; j++) {
            var SerialID = BaseValue + j;
            if (!this.DataObj.NoticeInfo[SerialID]) break;
            var TextL = this.TetxLength[0];
            var NoticeElement = document.createElement('div');
            NoticeElement.className = 'NoticeElement';
            NoticeElement.style.width = this.ElementWidth + 'px';
            NoticeElement.style.height = this.ElementHeight + 'px';
            NoticeElement.style.lineHeight = this.ElementHeight + 'px';
            var LinkSet = document.createElement('div');
            LinkSet.style.width="100%";
            //LinkSet.style.overflow = "hidden";
            LinkSet.innerHTML = this.DataObj.NoticeInfo[SerialID].textset;
            NoticeElement.appendChild(LinkSet);
            RollingNoticeElement.appendChild(NoticeElement);
        }//end for

        RollingNoticeElement.onmouseover = function() {
            var ObjMapping = eval('RollingNotice'+this.ClassID);
            if (ObjMapping.BlockAction) return;
            clearTimeout(ObjMapping.TimerIntervalID);
        }
        RollingNoticeElement.onmouseout = function() {
            var ObjMapping = eval('RollingNotice'+this.ClassID);
            if (ObjMapping.BlockAction) return;
            clearTimeout(ObjMapping.TimerIntervalID);
            ObjMapping.TimerIntervalID = setTimeout('RollingNotice'+ObjMapping.id+'.VaryAction()', ObjMapping.Timer);
        }
        NoticeSet.appendChild(RollingNoticeElement);
        this.getNoticeElement.push(RollingNoticeElement);
    }//end for
    if(navigator.appVersion.toLowerCase().indexOf("msie")<0) {
        //$(this.CodeSection).style.marginLeft = "140px";
    }
    //VaryAction
    this.VaryAction();
}

//檢查選擇一般文章或是特殊文章
function article_type_chk(i){
     if (i == 1){
         if (document.getElementsByName("article_type")[0].checked == true){
             document.getElementById("read_limit_reply").disabled = true;
             document.getElementById("read_limit_points_chk").disabled = true;
             document.getElementById("read_limit_points").disabled = true;
             document.getElementById("special_article_use").style.display = "none";

         }else {
             document.getElementById("read_limit_reply").disabled = false;
             document.getElementById("read_limit_points_chk").disabled = false;
             document.getElementById("read_limit_points").disabled = false;
             document.getElementById("special_article_use").style.display = "block";
         }
     }else {
         if (document.getElementsByName("article_type")[1].checked == true)
            alert('提醒您:積分須超過300才能使用此功能.');
         document.getElementsByName("article_type")[0].checked = true;
         document.getElementsByName("article_type")[1].checked = false;

     }

}