function post(){
    try{
        var content = $("msg_content");
        if(content.value.trim()=="") {
            content.focus();
            flashNotice2(WORD_1,"postNoticer");
            return false;
        }
        var url = "/normal_message/new_thread";
        var parms = "content="+content.value.trim()+"&sent_way=0";
        new Ajax.Request(url, 
        {
            asynchronous:true,
            evalScripts:true, 
            onLoading:function(request){
                postLoading(request)
            },
            onComplete:function(request){
                postComplete(request)
            },
            parameters:parms
        }
        );
        return false;
    }catch(e){
        alert(e);
        return false;
    }
}

function postLoading(request){
    showCentralNoticer(WORD_2);
    $("broadCast").disabled = true;
}

function postComplete(request){
    try{   
        if(request.status=="200") {
            var respInfos = eval("("+request.responseText+")");
            var newMsg = createNewMsg(respInfos);
            new Insertion.Top('msg_section',newMsg);
            new Effect.Highlight("thread_"+respInfos.tid);
            updateCentralNoticer(WORD_3);
            hideCentralNoticer(1);
            $("all_count").innerHTML = respInfos.all_count;
            $("sent_count").innerHTML = respInfos.sent_count;
            $("msg_content").value = "";
            $("broadCast").disabled = false;
        }
        else if (request.status=="403"){
            updateCentralNoticer(WORD_4);
            hideCentralNoticer(1);
            $("broadCast").disabled = false;
        }
        else if (request.status=="500"){
            updateCentralNoticer(WORD_5);
            hideCentralNoticer(1);
            $("broadCast").disabled = false;
        }
    }catch(e){
        alert(e);
    }
}

function createNewMsg(msg_json){
    msg = "<tr class='read' id='thread_"+msg_json.tid+"'>";
    if(msg_json.starred == '1'){
        msg += "<td class='icon'><img src='/images/starred.gif' alt='Starred' /></td>";
    }else{
        msg += "<td class='icon'><img src='/images/unstarred.gif' alt='Unstarred' /></td>";
    }
    msg += "<td class='content'><h3><a href='"+DMS_HOST+"/message/"+msg_json.tid+"'>"+msg_json.subject+"</a></h3>";
    msg += "<p class='hint'>Topic started by <a href='/user/"+msg_json.creator_name+"'>"+msg_json.creator_name+"</a> "+msg_json.created_at+"</p></td>";   
    msg += "<td class='update'><img src='"+RESOURCE_HOST+"/resources_mana/user_avatar?user_name="+msg_json.creator_name+"&amp;size=16' alt='"+msg_json.creator_name+"' /></td>";
    msg += "<td class='delete'><img src='"+RESOURCE_HOST+"/images/delete.gif' alt='delete' /></td>";
    msg += "</tr>";
    return msg;
}

/******************************************
 * Reply thread post
 *******************************************/

/******************************************
 * addReply: init and display add reply form
 * tid: thread message id,
 * pid: post id,
 * r_pos: reply position,
 * r_user_name: reply username if is Diigo user,
 * r_user_info: reply user info(email) if is non-Diigo user
 *******************************************/
function addReply(tid,pid,r_pos,r_user_name,r_user_info,r_user_real_name){
    try{
        var reply_post = $("reply_"+pid);
        var edit_post = $("edit_"+pid);
        if(reply_post.innerHTML == "") {
            reply_post.appendChild(createRFEditor(tid,pid,r_pos,r_user_name,r_user_info,r_user_real_name));
        }
        if(reply_post.style.display=="") {
            reply_post.hide();
        }else {
            reply_post.show();
            edit_post.hide();
        }
    }catch(e){
        alert(e);
    }
}

/******************************************
 * createRFEditor: init reply form
 * tid: thread message id,
 * pid: post id,
 * r_pos: reply position,
 * r_user_name: reply username if is Diigo user,
 * r_user_info: reply user info(email) if is non-Diigo user
 *******************************************/
function createRFEditor(tid,pid,r_pos,r_user_name,r_user_info,r_user_real_name){
    var form = document.createElement("form");
    form.id = "reply_post_form_" + pid;
    form.pid = pid;
    form.onsubmit = postComment;
    form.action = "/normal_message/add_reply";
    form.method = "post";
    form.innerHTML += "<input type='hidden' name='tid' value='"+tid +"'/>";
    form.innerHTML += "<input type='hidden' name='reply_pos' value='"+r_pos +"'/>";
    form.innerHTML += "<input type='hidden' name='reply_user_name' value='"+r_user_name +"'/>";
    form.innerHTML += "<input type='hidden' name='reply_user_info' value='"+r_user_info +"'/>";
    reply_content = reply_post_ref(r_user_name,r_user_real_name,pid);
    form.innerHTML += "<ul class='postForm'><li><div class='alert' id='postNoticer_"+pid+"' style='display:none'></div></li><li class='rich_editor_w'><a href='javascript:toggleEditor("+pid+")' id='rich_editor_w_"+pid+"'>Rich formatting &raquo</a></li><li><label for='comment_"+pid+"'>Reply</label><textarea id='comment_"+pid+"' name='comment' cols='50' rows='10'>"+reply_content+"</textarea></li><li class='postFormSubmit'><input type='submit' value='Add Reply'/>or <a href='javascript:void(0);' onclick='switchRFEditor("+pid+")'>Cancel</a></li></ul>";
    return form;
}

function reply_post_ref(r_user_name, r_user_real_name,r_pid){
    try {
        var full_text = "\n" + r_user_real_name + " wrote:\n";
        var comment = $("post_comment_"+r_pid).down('div.trim_content').innerHTML.trim();
        comment = comment.replace(/<br>/gi, '\n');
        comment = comment.replace(/&gt;/gi, ' >');
        full_text += quote(comment);
        return "";
    } 
    catch (e) {
        return "";
    }
}

function quote(text){
    var s = text.split("\n");
    var r_s = "";
    for (var i = 0; i < s.length; i++) {
        if (s[i].match(/^>/) != null) {
            s[i] = ">" + s[i] + "\n";
        }
        else {
            s[i] = "> " + s[i] + "\n";
        }
        r_s += s[i];
    }
    return r_s;
}

function switchRFEditor(pid){
    try{
        var reply_post = $("reply_"+pid);
        if(reply_post.style.display=="") {
            reply_post.style.display = "none";
        }else {
            reply_post.style.display = "";
        }
    }catch(e){
        alert(e);
    }	
}

function postComment(){
    try{
        var msg_content_id = "comment_"+this.pid;
        if(tinyMCE.getInstanceById(msg_content_id) != null){
            $(msg_content_id).value = tinyMCE.get(msg_content_id).getContent();
        }
        if($(msg_content_id).value.trim() == ""){
            //$(msg_content_id).focus();
            flashNotice2(WORD_1,"postNoticer_"+this.pid,"alert");
            return false;
        }
        return true;
    }catch(e){
        alert(e);
        return false;
    }
}

/******************************************
 * Edit thread post - 2008-01-09 by vincent
 *******************************************/

/******************************************
 * addReply: init and display add reply form
 * tid: thread message id,
 * pid: post id,
 * r_pos: reply position,
 * r_user_name: reply username if is Diigo user,
 * r_user_info: reply user info(email) if is non-Diigo user
 *******************************************/
function editPost(tid,pid,p_pos,p_creator_name){
    try{
        var edit_post = $("edit_"+pid);
        var reply_post = $("reply_"+pid);
        if(edit_post.innerHTML == "") {
            edit_post.appendChild(createEFEditor(tid,pid,p_pos,p_creator_name));
        }
        if(edit_post.style.display=="") {
            edit_post.hide();
        }else {
            edit_post.show();
            reply_post.hide();
        }
    }catch(e){
        alert(e);
    }
}

/******************************************
 * createEFEditor: init edit post form
 * tid: thread message id,
 * pid: post id,
 * r_pos: reply position,
 * r_user_name: reply username if is Diigo user,
 * r_user_info: reply user info(email) if is non-Diigo user
 *******************************************/
function createEFEditor(tid,pid,p_pos,p_creator_name){
    var form = document.createElement("form");
    form.id = "edit_post_form_" + pid;
    form.pid = pid;
    form.onsubmit = function(){
        try{
            var msg_content_id = "edit_comment_"+pid;
            if(tinyMCE.getInstanceById(msg_content_id) != null){
                $(msg_content_id).value = tinyMCE.get(msg_content_id).getContent();
            }
            if($(msg_content_id).value.trim() == ""){
                //$(msg_content_id).focus();
                flashNotice2(WORD_1,"postNoticer_"+pid,"alert");
                return false;
            }
            //            var comment = $("edit_comment_" + pid);
            //            if(comment.value.trim()=="") {
            //                comment.focus();
            //                flashNotice2(WORD_1,"postNoticer_"+pid,"alert");
            //                return false;
            //            }
            return true;
        }catch(e){
            alert(e);
            return false;
        }
    };
    form.action = "/normal_message/edit_thread_post";
    form.method = "post";
    form.innerHTML += "<input type='hidden' name='tid' value='"+tid+"'/>";
    form.innerHTML += "<input type='hidden' name='pid' value='"+pid+"'/>";
    form.innerHTML += "<input type='hidden' name='p_pos' value='"+p_pos+"'/>";
    form.innerHTML += "<input type='hidden' name='p_creator_name' value='"+p_creator_name+"'/>";
    post_comment_ref = edit_post_ref(pid);
    form.innerHTML += "<ul class='postForm'><li><div class='alert' id='postNoticer_"+pid+"' style='display:none'></div></li><li class='rich_editor_w'><a href='javascript:toggleEditor_2("+pid+")' id='rich_editor_w_2_"+pid+"'>Rich formatting &raquo</a></li><li><label for='edit_comment_"+pid+"'>Edit Post</label><textarea id='edit_comment_"+pid+"' name='comment' cols='50' rows='10'>"+post_comment_ref+"</textarea></li><li class='postFormSubmit'><input type='submit' value='Save Edit'/>or <a href='javascript:void(0);' onclick='switchEFEditor("+pid+")'>Cancel</a></li></ul>";
    return form;
}

function switchEFEditor(pid){
    try{
        var edit_post = $("edit_"+pid);
        if(edit_post.style.display=="") {
            edit_post.hide();
        }else {
            edit_post.show();
        }
    }catch(e){
        alert(e);
    }	
}

//function editPostComment(){
//    try{
//        var comment = $("edit_comment_" + this.pid);
//        if(comment.value.trim()=="") {
//            comment.focus();
//            flashNotice2(WORD_1,"postNoticer_"+this.pid,"alert");
//            return false;
//        }
//        return true;
//    }catch(e){
//    alert(e);
//    return false;
//}
//}

function edit_post_ref(post_position){
    try{
        var comment = $("post_comment_"+post_position).select("div")[0].innerHTML.trim();
        comment = comment.replace(/<br>/gi,'\n');
        comment = comment.replace(/&gt;/gi,' >');
        return comment;
    }catch(e){
        alert(e);
        return "";
    }
}

function renderPending(){
    var contactList = "";
    var toList = "";
    for(var i=0;i<_contact_list.length;i++){
        if(!_contact_list[i].checked){
            contactList += renderItem(i);            	
        }else{
            if(_contact_list[i].type == "1"){
                toList += "<li><span>list:"+_contact_list[i].real_name+"<a href='javascript:void(0);' onclick='onPendingRemove("+i+");'>x</a><wbr/></span></li>";		   	
            }
            else if(_contact_list[i].type == "0" && _contact_list[i].friend == "1"){
                toList += "<li><span>"+_contact_list[i].real_name+"<a href='javascript:void(0);' onclick='onPendingRemove("+i+");'>x</a><wbr/></span></li>";		   	
            }else{
                toList += "<li><span>"+_contact_list[i].details+"<a href='javascript:void(0);' onclick='onPendingRemove("+i+");'>x</a><wbr/></span></li>";
            }
        }
    }
    $("contactList").innerHTML = contactList;
    if(toList == ""){
        $("toList").innerHTML = WORD_6;	
    }else{
        $("toList").innerHTML = toList;	
    }
}

function showListItem(index){
    list = $("list_" + index);
    if(!list){
        return;
    }
    list.innerHTML = "";
    for(var i=0;i<_contact_list.size();i++){
        if(_contact_list[i].type == 0 && _contact_list[i].belong_list_id.split(",").indexOf(_contact_list[index].list_id) != -1){
            list.innerHTML += "<li>"+_contact_list[i].real_name+"</li>"; 
        }
    }
    if (list.style.display == ""){
        list.style.display = "none";
    }else{
        list.style.display = "";
    }
}		

function filterContactItem(){
    var filter = $("filter").value;
    var contactList = "";
    if(typeof(filter)!="undefined" && filter !=''){
        var itemRegExp = new RegExp("^("+filter+").+","i"); 
        for(var i=0;i<_contact_list.size();i++){
            if(!_contact_list[i].checked && (itemRegExp.test(_contact_list[i].name) || itemRegExp.test(_contact_list[i].real_name))){
                contactList += renderItem(i); 
            }
        }
    }else{
        for(var i=0;i<_contact_list.size();i++){
            if(!_contact_list[i].checked){
                contactList += renderItem(i); 
            }
        }
    }
    $("contactList").innerHTML = contactList;
}

function renderItem(index){
    var contactList = ""
    if(_contact_list[index].type == 0){
        if(_contact_list[index].friend == 1){
            contactList += "<li class='friend'><a href='javascript:void(0)' onclick='onPendingAdd("+index+");'><h3>"+_contact_list[index].real_name+"</h3><p>";
            details= _contact_list[index].details.split(",");
            contactList += _contact_list[index].name;
            if(details[0] != ""){
                contactList += ", " + details[0];
            }
            if(details[1] != "-1"){
                contactList += ", " + GENDER[details[1]];
            }
            contactList += "</p></a></li>"; 
        }else{
            contactList += "<li><a href='javascript:void(0)' onclick='onPendingAdd("+index+");'><h3>"+_contact_list[index].real_name+"</h3><p>"+_contact_list[index].details+"</p></a></li>";          
        }  
    }else{
        contactList += "<li class='list'><span onclick='showListItem("+index+");'>[View]</span> <a href='javascript:void(0)' onclick='onPendingAdd("+index+");'><h3>"+_contact_list[index].real_name+"</h3></a><ul id='list_"+index+"' style='display:none;'></ul></li>";
    }
    return contactList;   
}

function onPendingAdd(index){
    if(typeof(_contact_list[index])!='undefined' && !_contact_list[index].checked){
        _contact_list[index].checked = true;
    }
    renderPending();
}

function onPendingRemove(index){
    if(typeof(_contact_list[index])!='undefined' && _contact_list[index].checked){
        _contact_list[index].checked = false;
    }
    renderPending();
}

function getListItem(list){
    var contactItems = [];
    for(var i=0;i<_contact_list.size();i++){
        if(_contact_list[i].type == 0 && _contact_list[i].belong_list_id.split(",").indexOf(list.list_id) != -1){
            contactItems.push(_contact_list[i]);
        }   
    }
    return contactItems;
}

function fillSendTo(contactItem,usernames,emails,contact_list){
    if(contactItem.type == 0 && contactItem.friend == 1){// if friend
        if(usernames.indexOf(contactItem.name) == -1){
            usernames.push(contactItem.name);
        }
    }else if(contactItem.type == 0 && (contactItem.friend == 0 || contactItem.friend == "")){ // not friend and not contact list
        if(emails.indexOf(contactItem.details) == -1){
            emails.push(contactItem.details);
        }
    }else if(contactItem.type == 1){ // contact list
        if(contact_list.indexOf(contactItem.list_id) == -1){
            contact_list.push(contactItem.list_id);
        }
    }
}


function showNoticer(noticerID,content){
    var noticer = $(noticerID);
    if(noticer){
        noticer.style.display = "";
        noticer.innerHTML = content;
        noticer.onclick = quickFadeFlashNoticer;
        setTimeout("new Effect.Fade('"+noticerID+"')",DURATION_1);
    }
}

function addSubject(){
    $("addSubject").style.display = "none";
    $("onAddSubject").style.display = "";
}

function cancelSubject(){
    $("addSubject").style.display = "";
    $("onAddSubject").style.display = "none";
}

function changeStarred(elm){
    if(_starred == '0'){
        _starred = '1';
        elm.className = "check cStar";

    }else{
        _starred = '0';
        elm.className = "check cUnstar";
    }
    elm.innerHTML = WORD_24[_starred];
    elm.title = WORD_26[_starred];
}

function changeMode(elm){
    if(_mode == '0'){
        _mode = '2';
        elm.className = "check cPri";
    }else{
        _mode = '0';
        elm.className = "check cPub";
    }
    elm.innerHTML = WORD_23[_mode];
    elm.title = WORD_25[_mode];
}

function changePrivacy(elm){
    if(elm.checked){
        _mode = '0';
    }else{
        _mode = '2';
    }
}

function changePriority(elm){
    if(elm.checked){
        _starred = '1';
    }else{
        _starred = '0';
    }
}

function beforeNewThread(msg_content_id){
    try{
        if(tinyMCE.getInstanceById(msg_content_id) != null){
            $(msg_content_id).value = tinyMCE.get(msg_content_id).getContent();
        }
        if($(msg_content_id).value.trim() == ""){
            showNoticer("noticer",WORD_1);
            return false;
        }
        //send_way: 0: all friends, 1:frinds/email/contact items
        switch($("id_note_to").value){
            case "allFriends":{
                $("send_way").value = 0;
            }break;
            case "someone":{
                var acc_contacts = _GLOBAL_VAR[_GLOBAL_VAR["bACCID"]+"_instance"].getRecItems();
                if(!acc_contacts || (acc_contacts['friends'].size() == 0 && acc_contacts['emails'].size() == 0 && acc_contacts['usernames'].size() == 0 && acc_contacts['lists'].size() == 0)){
                    showNoticer("noticer",WORD_7);
                    return false;
                }
                $("send_to").value = acc_contacts['friends'].join(",");
                $("send_to_usernames").value = acc_contacts['usernames'].join(",");
                $("send_to_emails").value = acc_contacts['emails'].join(",");
                $("send_to_contact_list").value = acc_contacts['lists'].join(",");
            }break;
            case "myself":break;
            default:{//send to contact list
                $("send_to_contact_list").value = $("id_note_to").value;
            }break;
        }
        //        var acc_contacts = _GLOBAL_VAR[_GLOBAL_VAR["bACCID"]+"_instance"].getRecItems();
        //        if(!acc_contacts || (acc_contacts['friends'].size() == 0 && acc_contacts['emails'].size() == 0 && acc_contacts['lists'].size() == 0)){
        //            showNoticer("noticer",WORD_7);
        //            return false;
        //        }
        //        $("send_to").value = acc_contacts['friends'].join(",");
        //        $("send_to_emails").value = acc_contacts['emails'].join(",");
        //        $("send_to_contact_list").value = acc_contacts['lists'].join(",");
        $("send_starred").value = _starred;
        $("send_mode").value = _mode;
        var msgSubjcect = $("inputSubject");
        if(msgSubjcect && msgSubjcect.value.trim() == WORD_11){
            msgSubjcect.value = "";
        }
        return true;	
    }catch(e){
        alert(e);
        return false;
    }	
}

function beforeSpread(){
    try{
        //send_way: 0: all friends, 1:frinds/email/contact items
        switch($("id_note_to").value){
            case "allFriends":{
                $("send_way").value = 0;
            }break;
            case "someone":{
                var acc_contacts = _GLOBAL_VAR[_GLOBAL_VAR["bACCID"]+"_instance"].getRecItems();
                if(acc_contacts && acc_contacts['friends'].size() == 0 && acc_contacts['usernames'].size() == 0 && acc_contacts['emails'].size() == 0 && acc_contacts['lists'].size() == 0){
                    showNoticer("noticer",WORD_7);
                    return false;
                }
                $("send_to").value = acc_contacts['friends'].join(",");
                $("send_to_usernames").value = acc_contacts['usernames'].join(",");
                $("send_to_emails").value = acc_contacts['emails'].join(",");
                $("send_to_contact_list").value = acc_contacts['lists'].join(",");
            }break;
            default:{//send to contact list
                $("send_to_contact_list").value = $("id_note_to").value;
            }break;
        }
        $("send_starred").value = _starred;
        $("send_mode").value = _mode;     
        //        alert("u_name:" + $("send_to").value);
        //        alert("emails:" + $("send_to_emails").value);
        //        alert("contact_list:" + $("send_to_contact_list").value);
        //        alert("starred:" + $("send_starred").value);
        //        alert("mode:" + $("send_mode").value);
        //        alert("send_way:" + $("send_way").value);
        return true;	
    }catch(e){
        alert(e);
        return false;
    }
}

function beforeBroadcast(){
    try{
        if($("msg_content").value.trim() == ""){
            showNoticer("noticer",WORD_1);
            return false;
        }
        $("msg_content").value.replace(/<br\s*\/?>/gi, '\n');
        return true;	
    }catch(e){
        alert(e);
        return false;
    }	
}

function resetStarred(tid){
    try{
        var url = "/normal_message/reset_starred";
        var parms = "tid="+tid;
        var el = $("starred_"+tid);
        if(el.hasClassName("iconUnstarred")){
            el.className = "icon iconStarred iconClickable";
            el.title = WORD_26[1];
        }else{
            el.className = "icon iconUnstarred iconClickable";
            el.title = WORD_26[0];
        }
        new Ajax.Request(url, 
        {
            asynchronous:true,
            evalScripts:true, 
            onLoading:function(request){
                resetStarredLoading(request,tid)
            },
            onComplete:function(request){
                resetStarredComplete(request,tid)
            },
            parameters:parms
        }
        );
        return false;
    }catch(e){
        alert(e);
        return false;
    }
}

function resetStarredLoading(request,index){
}

function resetStarredComplete(request,index){
    try{
        if(request.status=="200"){
        }else if(request.status=="403"){
        }
        else if(request.status=="500"){
    }
    }catch(e){
        alert(e);
    }
}

function resetThreadPrivacy(tid){
    try{
        var url = "/normal_message/reset_thread_privacy";
        var parms = "tid="+tid;
        var el = $("mode_"+tid);
        if(el.hasClassName("iconUnlock")){
            el.className = "icon iconLock iconClickable";
            el.title = WORD_27[1];
        }else{
            el.className = "icon iconUnlock iconClickable";
            el.title = WORD_27[0];
        }
        new Ajax.Request(url, 
        {
            asynchronous:true,
            evalScripts:true, 
            onLoading:function(request){
                resetThreadPrivacyLoading(request,tid)
            },
            onComplete:function(request){
                resetThreadPrivacyComplete(request,tid)
            },
            parameters:parms
        }
        );
        return false;
    }catch(e){
        alert(e);
        return false;
    }
}

function resetThreadPrivacyLoading(request,index){
}

function resetThreadPrivacyComplete(request,index){
    try{
        if(request.status=="200"){
        }else if(request.status=="403"){
        }
        else if(request.status=="500"){
    }
    }catch(e){
        alert(e);
    }
}

function deleteThread(tid){
    try{
        var url = "/normal_message/delete_thread";
        var parms = "tid="+tid;
        new Ajax.Request(url, 
        {
            asynchronous:true,
            evalScripts:true, 
            onLoading:function(request){
                deleteThreadLoading(request,tid)
            },
            onComplete:function(request){
                deleteThreadComplete(request,tid)
            },
            parameters:parms
        }
        );
        return false;
    }catch(e){
        alert(e);
        return false;
    }
}

function deleteThreadLoading(request,index){
    showCentralNoticer(WORD_2);
}

function deleteThreadComplete(request,index){
    try{
        if(request.status=="200"){
            new Effect.Fade("thread_"+index);
            var respInfos = eval("("+request.responseText+")");
            updateCentralNoticer(WORD_3);
            hideCentralNoticer(1);
        }else if(request.status=="403"){
            updateCentralNoticer(WORD_4);
            hideCentralNoticer(1);
        }
        else if(request.status=="500"){
            updateCentralNoticer(WORD_5);
            hideCentralNoticer(1);
        }
    }catch(e){
        alert(e);
    }
}

function resetBlockThread(tid){
    try{
        var url = "/normal_message/reset_block_thread";
        var parms = "tid="+tid;
        new Ajax.Request(url, 
        {
            asynchronous:true,
            evalScripts:true, 
            onLoading:function(request){
                resetBlockThreadLoading(request,tid)
            },
            onComplete:function(request){
                resetBlockThreadComplete(request,tid)
            },
            parameters:parms
        }
        );
        return false;
    }catch(e){
        alert(e);
        return false;
    }
}	

function resetBlockThreadLoading(request,index){
    showCentralNoticer(WORD_2);
}

function resetBlockThreadComplete(request,index){
    try{
        if(request.status=="200"){
            new Effect.Highlight("thread_"+index);
            var respInfos = eval("("+request.responseText+")");
            if(respInfos.status == '0'){
                $("block_"+index).innerHTML = "Block";
            }else if(respInfos.status == '2'){
                $("block_"+index).innerHTML = "Unblock";
            } 
            updateCentralNoticer(WORD_3);
            hideCentralNoticer(1);
        }else if(request.status=="403"){
            updateCentralNoticer(WORD_4);
            hideCentralNoticer(1);
        }
        else if(request.status=="500"){
            updateCentralNoticer(WORD_5);
            hideCentralNoticer(1);
        }
    }catch(e){
        alert(e);
    }
}

function msgPath(tid){
    try{
        var msgPathBox = $("centralContainer_box");
        if(msgPathBox){
            msgPathBox.style.display = "";
        }else{
            var url = "/normal_message/msg_path";
            var parms = "tid="+tid;
            new Ajax.Request(url, 
            {
                asynchronous:true,
                evalScripts:true, 
                onLoading:function(request){
                    msgPathLoading(request)
                },
                onComplete:function(request){
                    msgPathComplete(request)
                },
                parameters:parms
            }
            );
        }
        return false;
    }catch(e){
        alert(e);
        return false;
    }
}

function msgPathLoading(request){
}

function msgPathComplete(request){
    try{   
        if(request.status=="200") {
            var respInfos = request.responseText;
            makeMsgPath(respInfos);
        }
        else if (request.status=="403"){
        }
        else if (request.status=="500"){
    }
    }catch(e){
        alert(e);
    }
}

function makeMsgPath(respInfos){
    try{
        if(typeof(noticerID)=='undefined') containerID = "centralContainer";
        var msgPathBox = $(containerID+"_box");
        var noticerContent = $(containerID+"_content");
        if(!msgPathBox) {
            msgPathBox = document.createElement("div");
            msgPathBox.className = "lightWin";
            msgPathBox.id = containerID+"_box";
            msgPathBox.innerHTML = respInfos;
            document.body.appendChild(msgPathBox);
        }
        msgPathBox.style.display = "block";
        var pos = Position.cumulativeOffset($("view_to_me_path"));
        msgPathBox.style.left = pos[0]- msgPathBox.offsetWidth - 30 + "px";//width/2 - (msgPathBox.offsetWidth/2) + "px";
        msgPathBox.style.top = pos[1] - 40 + "px"//"100px";
        if(msgPathBox.offsetHeight<100) {
            msgPathBox.style.height = "300px";
        }
    }catch(e){
        alert(e);
    }
}

function closeMsgPath(){
    var msgPathBox = $("centralContainer_box");
    if(msgPathBox){
        msgPathBox.style.display = "none";
    }
}

function beforeReadMsg(u_name,tab){
    try{
        var url = "/normal_message/read_messages";
        unread_msg_ids = [];

        $("messageListTable").select('tr[class="unread odd"]').each(function(e) {
            unread_msg_ids.push(e.id.split("_")[1])
        });
        $("messageListTable").select('tr[class="unread even"]').each(function(e) {
            unread_msg_ids.push(e.id.split("_")[1])
        });
        
        if(unread_msg_ids.size() == 0){
            $("markReadNoticer").className = "";
            $("markReadNoticer").toggleClassName("alert").update(WORD_13).show();
            return false;
        }
        var parms = "t_ids="+unread_msg_ids.join(",");
        new Ajax.Request(url, 
        {
            asynchronous:true,
            evalScripts:true, 
            onLoading:function(request){
                readMsgLoading(request)
            },
            onComplete:function(request){
                readMsgComplete(request,u_name,tab)
            },
            parameters:parms
        }
        );
        return false;
    }catch(e){
        alert(e);
        return false;
    }
}

function readMsgLoading(request){}

function readMsgComplete(request,u_name,tab){
    try{
        if(request.status=="200"){
            window.location.href = DIIGO_DMS + "/user/" + u_name + "?tab=" + tab;
        } 
        else if(request.status=="403"){
            $("markReadNoticer").className = "";
            $("markReadNoticer").toggleClassName("alert").update(WORD_4).show();
        }
        else if(request.status=="500"){
            $("markReadNoticer").className = "";
            $("markReadNoticer").toggleClassName("alert").update(EXC_1).show();
        }
    }catch(e){
        alert(e);
    }
}

function filterStarredMsg(u_name){
    $("starFilter").toggleClassName("starFilted");
    if(_filter_open == true){
        _filter_open = false;
        $("starFilter").title = WORD_16;
    }else{
        _filter_open = true;
    }
    getFilterMsgs(_filter_open,u_name);
}

//get unread-starred or unread message
function getFilterMsgs(filter_open,u_name){
    try{
        var url = "/normal_message/load_filter_messages";
        var parms = "filter_open="+filter_open;
        new Ajax.Request(url, 
        {
            asynchronous:true,
            evalScripts:true, 
            onLoading:function(request){
                getFilterMsgsLoading(request)
            },
            onComplete:function(request){
                getFilterMsgsComplete(request,u_name)
            },
            parameters:parms
        }
        );
        return false;
    }catch(e){
        alert(e);
        return false;
    }
}

function getFilterMsgsLoading(){
    showCentralNoticer(WORD_15);
}

function getFilterMsgsComplete(request,u_name){
    try{
        hideCentralNoticer();
        if(request.status=="200"){
            var respInfos = eval("("+request.responseText+")");
            temp = "<tr id=\"msg_#{tid}\" class=#{readClass}>";
            temp += "<td class=\"tdStar\"><span onclick=\"return(resetStarred(#{tid}));\" title=\"Click to #{star_action} this message\" id=\"starred_#{tid}\" class=\"icon #{star_action_class} iconClickable\"/>#{first_post_body}</td>";
            temp += "<td class=\"tdSub\"><h3><a title=\"#{subject}\" href=\"/#{current_user_name}/message/#{tid}\">#{subject}</a></h3><p class=\"summary\"><a title=\"#{last_post_body}\" href=\"/#{last_poster_name}/message/#{tid}?page_num=#{page_num}&opt_pos=1##{last_pos}\">#{last_post_body}</a></p></td>"
            temp += "<td class=\"tdRnV\">#{post_count}</td>";
            temp += "<td class=\"tdAuthor\"><a title=\"View #{creator_real_name}'s messages\" href=\"/user/#{creator_name}\">#{creator_real_name}</a><span class=\"time\">#{started_at}</span></td>";
            temp += "<td class=\"tdLP\"><a title=\"View #{last_poster_real_name}'s messages\" href=\"/user/#{last_poster_name}\">#{last_poster_real_name}</a><span class=\"time\">#{last_p_created_at}</span></td>";
            temp += "</tr>";
            var rowTemplate = new Template(temp);
            $("messageItems").update("");
            readClass = "";
            star_action = "";
            star_action_class = "";
            for(var i=0;i<respInfos.size();i++){
                if(respInfos[i].unread == 1){
                    readClass = "unread";
                }else{
                    readClass = "";
                }
                if(respInfos[i].starred == 1){
                    star_action = "unstar";
                    star_action_class = "iconStarred";
                }else{
                    star_action = "star";
                    star_action_class = "iconUnstarred";
                }
                $("messageItems").insert(
                    rowTemplate.evaluate({
                        tid: respInfos[i].tid,
                        readClass: readClass,
                        star_action: star_action,
                        star_action_class: star_action_class,
                        current_user_name: u_name,
                        post_count: respInfos[i].post_count,
                        page_num: calc_page_num(respInfos[i].post_count,LIST_COUNT),
                        subject: respInfos[i].subject,
                        creator_name: respInfos[i].creator_name,
                        creator_real_name: respInfos[i].creator_real_name,
                        started_at: respInfos[i].started_at,
                        last_post_body: respInfos[i].last_post_body,
                        last_poster_name: respInfos[i].last_poster_name,
                        last_poster_real_name: respInfos[i].last_poster_real_name,
                        last_p_created_at: respInfos[i].last_p_created_at,
                        last_pos: respInfos[i].last_pos
                    })
                    )
            }
        } 
        else if(request.status=="403"){
            $("markReadNoticer").className = "";
            $("markReadNoticer").toggleClassName("alert").update(WORD_4).show();
        }
        else if(request.status=="500"){
            $("markReadNoticer").className = "";
            $("markReadNoticer").toggleClassName("alert").update(EXC_1).show();
        }
    }catch(e){
        alert(e);
    }
}

function calc_page_num(total,count_per_page){
    page_num = total/count_per_page;
    mod = total%count_per_page;
    if(mod==0){
        page_num -= 1 ;
    }
    page_num = page_num < 0 ? 0 : page_num;
    return page_num.ceil();
    
}

function setSendFilter(){
    try{
        var url = "/setting_mana/send_filter_setting";
        new Ajax.Request(url, 
        {
            asynchronous:true,
            evalScripts:true, 
            onLoading:function(request){
                setSendFilterLoading(request)
            },
            onComplete:function(request){
                setSendFilterComplete(request)
            },
            parameters:$("send_filter_form").serialize()
        }
        );
        return false;
    }catch(e){
        alert(e);
        return false;
    }
}

function setSendFilterLoading(request){
    showCentralNoticer(WORD_2);
}

function setSendFilterComplete(request){
    try{
        hideCentralNoticer(1);
        if(request.status=="200"){
            var respInfos = request.responseText.evalJSON();
            $("send_filter_noticer").className = "";
            var alertWords = "";
            if(respInfos.send_filter == 2){// Anyone can send
                alertWords += WORD_19[respInfos.send_filter].replace("?","<a href='"+DIIGO_DMS+"/inbox/"+respInfos.u_name+"'>" + DIIGO_DMS + "/inbox/" + respInfos.u_name +"</a>")+"</p>";
            }else{
                alertWords += WORD_19[respInfos.send_filter];
            }
            $("send_filter_noticer").toggleClassName("success").update(alertWords).show();
        }else if(request.status=="403"){
            $("send_filter_noticer").className = "";
            $("send_filter_noticer").toggleClassName("alert").update(WORD_4).show();
        }else if(request.status=="500"){
            $("send_filter_noticer").className = "";
            $("send_filter_noticer").toggleClassName("alert").update(EXC_1).show();
        }
    }catch(e){
        alert(e);
    }
}

function setEmailAlert(){
    try{
        var url = "/setting_mana/email_alert_setting";
        new Ajax.Request(url, 
        {
            asynchronous:true,
            evalScripts:true, 
            onLoading:function(request){
                setEmailAlertLoading(request)
            },
            onComplete:function(request){
                setEmailAlertComplete(request)
            },
            parameters:$("email_alert_form").serialize()
        }
        );
        return false;
    }catch(e){
        alert(e);
        return false;
    }
}

function setEmailAlertLoading(request){
    showCentralNoticer(WORD_2);
}

function setEmailAlertComplete(request){
    try{
        hideCentralNoticer(1);
        if(request.status=="200"){
            var respInfos = request.responseText.evalJSON();
            $("email_alert_noticer").className = "";
            $("email_alert_noticer").toggleClassName("success").update(WORD_20[respInfos.email_alert]).show();
        }else if(request.status=="403"){
            $("email_alert_noticer").className = "";
            $("email_alert_noticer").toggleClassName("alert").update(WORD_4).show();
        }else if(request.status=="500"){
            $("email_alert_noticer").className = "";
            $("email_alert_noticer").toggleClassName("alert").update(EXC_1).show();
        }
    }catch(e){
        alert(e);
    }
}

function deleteMsg(index){
    try{
        if(!confirm("Delete this message?")){
            return false;
        }
        var tid = _items[index].tid;
        var url = "/normal_message/delete_thread_3";
        new Ajax.Request(url,
        {
            asynchronous:true,
            evalScripts:true,
            onLoading:function(request){
                showCentralNoticer("Deleting this message...");
            },
            onComplete:function(request){
                hideCentralNoticer();
                $("msg_" + index).remove();
            },
            parameters:{
                tid:tid
            }
        }
        );
        return false;
    }catch(e){
        alert(e);
        return false;
    }
}

function deleteMsg2(tid, user_name){
    try{
        if(!confirm("Leave this conversation?")){
            return false;
        }
        var url = "/normal_message/delete_thread_3";
        new Ajax.Request(url,
        {
            asynchronous:true,
            evalScripts:true,
            onLoading:function(request){
                showCentralNoticer("Processing...");
            },
            onComplete:function(request){
                self.location = "/user/" + user_name;
            },
            parameters:{
                tid:tid
            }
        }
        );
        return false;
    }catch(e){
        alert(e);
        return false;
    }
}

/*=====================================
 * Bulk edit actions
 *=====================================*/

function bulkEdit(){
    var bulkEditActions = $("bulk_edit_actions");
    if(bulkEditActions.style.display == "none"){
        showBulkEdit();
    }else{
        hideBulkEdit();
    }
}

function showBulkEdit(){
    $("bulk_edit_actions").show();
    $("bulk_edit_th").show();
    $("messageListTable").select('td[class="itemChecker"]').each(function(e){e.show()});
}

function hideBulkEdit(){
    $("bulk_edit_actions").hide();
    $("bulk_edit_th").hide();
    $("messageListTable").select('td[class="itemChecker"]').each(function(e){e.hide()});
}


/************ Bulk delete msgs ************/

function bulkDeleteMsgs(){
    var checkedItems = whichItemsChecked();
    var tids = [];
    var indexes = [];
    for(var i=0; i<checkedItems.length; i++) {
        tids.push(checkedItems[i].tid);
        indexes.push(checkedItems[i].index);
    }
    if(tids.join(",").blank()){
        flashNotice(DMS_ALE_1, "noticeBar", DURATION_3);
        resetAllChecker();
        return false;
    }
    if(!confirm(DMS_ALE_2)){
        return false;
    }
    var url ="/normal_message/bulk_delete_msgs";
    showCentralNoticer(DIS_10);
    new Ajax.Request(url,
    {
        asynchronous:true,
        evalScripts:false,
        onComplete:function(request){
            for(var j=0;j<indexes.length;j++){
                delete(_items[indexes[j]]);
                $("msg_"+indexes[j]).remove();
            }
            if(_items.compact().length==0) {
                self.location.reload();
            }else{
                hideBulkEdit();
                resetAllChecker();
                hideCentralNoticer();
                flashNotice(WORD_DONE, "noticeBar", DURATION_3);
            }
        },
        parameters:{
            tids : tids.join(",")
        }
    }
    );
    return false;
}

/************ Bulk read msgs ************/

function bulkReadMsgs(){
    var checkedItems = whichItemsChecked();
    if(checkedItems.length == 0){
        flashNotice(DMS_ALE_1, "noticeBar", DURATION_3);
        resetAllChecker();
        return false;
    }
    var tids = [];
    var indexes = [];
    for(var i=0; i<checkedItems.length; i++) {
        if(checkedItems[i].unread == 0) continue;
        tids.push(checkedItems[i].tid);
        indexes.push(checkedItems[i].index);
    }
    if(tids.join(",").blank()){
        flashNotice(DMS_ALE_4, "noticeBar", DURATION_3);
        resetAllChecker();
        return false;
    }
    if(!confirm(DMS_ALE_3)){
        return false;
    }
    var url ="/normal_message/bulk_read_msgs";
    showCentralNoticer(DIS_10);
    new Ajax.Request(url,
    {
        asynchronous:true,
        evalScripts:false,
        onComplete:function(request){
            self.location.reload();
        },
        parameters:{
            tids : tids.join(",")
        }
    }
    );
    return false;
}

/*=====================================
 * init checker
 *=====================================*/
var _checkedItemCount = 0;

function initChecker(){
    for(var i=0; i<_items.length; i++) {
        var checker = $("item_checker_"+i);
        if(!checker){continue;}
        checker.checked = false;
        checker.disabled = false;
        checker.onclick = checkItem.bind(this,i);
    }
    var allChecker = $("items_check_all");
    allChecker.checked = false;
    allChecker.disabled = false;
    allChecker.onclick = checkItems;
}

function checkItems() {
    var allChecker = this;
    for(var i=0; i<_items.length; i++) {
        var checker = $("item_checker_"+i);
        if(!checker) continue;
        if(checker.checked!=allChecker.checked) checker.click();
    }
}

function checkItem(index){
    var checker = $("item_checker_"+index);
    var allChecker = $("items_check_all");
    if(checker.checked) {
        _items[index].checked = true;
        _checkedItemCount++;
        if(isAllSelected()) allChecker.checked = true;
    }else {
        allChecker.checked = false;
        _items[index].checked = false;
        _checkedItemCount--;
    }
}

function isAllSelected() {
    if(_checkedItemCount == _items.compact().length) return true;
    else return false;
}

function whichItemsChecked(){
    var checkedItems = [];
    for(var i=0; i<_items.length; i++) {
        if(!_items[i]) continue;
        if(_items[i].checked){
            checkedItems.push(_items[i]);
        }
    }
    return checkedItems;
}

function resetAllChecker() {
    for(var i=0; i<_items.length; i++) {
        resetChecker(i);
    }
}

function resetChecker(index) {
    var checker = $("item_checker_"+index);
    if(checker == null) return;
    if(checker.checked) checker.click();
}