var _item_types = ["bookmark","topic"];
var _item_type_h = {"bookmark":1, "topic":2};

//constants for edit mode blow
var _checkedItemCount = 0;
var _moreActionSelectCount = 2;
var _shareToGroupSelectCount = 2;
var _batchActionEnabled = true;

/****************************************
 * Bookmark Page Comment Methods
 ****************************************/
function addBComment(item_index){
    $("details_" + item_index).removeClassName("hide");
    $("add_comment_" + item_index).show();
     $("c_l_" + item_index).hide();
    $("c_btn_" + item_index).show();
    $("comment_content_"+item_index).focus();
}

function createCEditor(index){
    var form = new Element('form',{'method':'post'});
    form.id = "CForm_" + index;

    var div_text = new Element('div',{'class':'commentText'});
    var textarea = new Element('textarea',{'name':'comment_content'});
    textarea.id = "comment_content_" + index;
    textarea.onkeypress = function(e){resiseTextArea(e,index)};
    div_text.appendChild(textarea);

    var div_loading = new Element('div',{'id':'c_l_'+index,'class':'commentLoading','style':'display:none'}).update("...");

    var div_btn = new Element('div',{'id':'c_btn_'+index,'class':'commentBtn'});
    var input = new Element('input',{'type':'submit','value':'Post'});
    var a_href = new Element('a',{'href':'javascript:void(0);'}).update('Cancel');
    a_href.onclick = function(){clearCommentForm(index)};
    div_btn.appendChild(input);
    div_btn.appendChild(a_href);

    var div_hidden = new Element('div',{'style':'position:absolute;visibility:hidden'})
    div_hidden.id = 'comment_div_'+index;

    form.appendChild(div_text);
    form.appendChild(div_loading);
    form.appendChild(div_btn);
    form.appendChild(div_hidden);

    form.onsubmit = postBComment.bind(this,{"index":index});

    return form;
}

function clearCommentForm(comment_id,from){
    from = from ? from : "item_page";
    $("add_comment_" + comment_id).hide();
    $("comment_content_" + comment_id).value = "";
    $("comment_content_" + comment_id).setStyle({height : "60px"})
}

function postBComment(args){
    try{
        var item_index = args.index;
        if($("comment_content_" + item_index).value.trim() == ''){
            return false;
        }
        var url = "/site/add_page_comment";
        var params = $("CForm_" + item_index).serialize() + "&g_l_id=" +_items[item_index].g_l_id + "&item_index=" + item_index + "&page_comments_size=" + _items[item_index].page_comments.length;
        _postBCLoading(item_index);
        new Ajax.Request(url,
        {
            method:"post",
            asynchronous:true,
            evalScripts:true,
            onSuccess:function(request){
                var respInfos = request.responseText.evalJSON();
                newBComment(respInfos,item_index);
                clearCommentForm(item_index);
                new AvatarPopup();
                enableEmailAlertOnPage(item_index);
            },
            parameters:params
        }
    );
        return false;
    }catch(e){
        alert(e);
        return false;
    }
}

function _postBCLoading(index){
    $("c_btn_"+index).hide();
    $("c_l_"+index).show();
}

function newBComment(resp,item_index){
    //1. javascript model
    _items[item_index].page_comments.push(resp.obj);
    _items[item_index].p_c_count++;

    //2. page element
    $("comment_" + item_index).insert({"bottom": resp.html_str});

    //3. update page content
    renderBDCount(item_index);
}

function editBComment(item_index,comment_index){
    var el_id = item_index + "_" + comment_index;

    $("e_c_l_"+ el_id).hide();
    $("e_c_btn_" + el_id).show();
    $("cContent_" + el_id).hide();
    var html_content = $("cContent_" + el_id).select('[class="cContentInner"]')[0].innerHTML;
    $("edit_comment_content_" + el_id).value = displayInputContent(html_content); //_items[item_index].page_comments[comment_index].content;
    $("edit_comment_" + el_id).show();
}

function cancelEditBComment(item_index, comment_index){
    var el_id = item_index + "_" + comment_index;
     $("edit_comment_" + el_id).hide();
     $("edit_comment_content_" + el_id).setStyle({height : "60px"});
     $("cContent_" + el_id).show();
     $("add_comment_" + item_index).hide();
}

function postEditBComment(item_index, comment_index){
    try{
        if($("edit_comment_content_" + item_index + "_" + comment_index).value.trim() == ''){
            return false;
        }
        var url = "/site/edit_page_comment";
        var params = $("edit_CForm_" + item_index + "_" + comment_index).serialize() + "&p_c_id=" +_items[item_index].page_comments[comment_index].id + "&group_id=" + _items[item_index].group_id + "&user_id=" + _items[item_index].page_comments[comment_index].user_id;
        _postEditBCommentLoading(item_index,comment_index);
        new Ajax.Request(url,
        {
            method:"post",
            asynchronous:true,
            evalScripts:true,
            onSuccess:function(request){
                var respInfos = request.responseText.evalJSON();
                refreshBComment(respInfos,item_index,comment_index);
            },
            parameters:params
        }
        );
        return false;
    }catch(e){
        alert(e);
        return false;
    }
}

function _postEditBCommentLoading(item_index,comment_index){
    var el_id = item_index + "_" + comment_index;
    $("e_c_l_"+ el_id).show();
    $("e_c_btn_" + el_id).hide();
}

function refreshBComment(respInfos,item_index,comment_index){
    //1. update page comment js model
    _items[item_index].page_comments[comment_index].content = respInfos.content;

    var html_content = displayContent(processComment(respInfos.content));
    //2. show new html
    var el_id = item_index + "_" + comment_index;
    $("edit_comment_" + el_id).hide();
    $("cContent_" + el_id).update(html_content).show();
    //$("comment_" + item_index + "_" + comment_index).show();
}

function editBIComment(item_index,ann_index,comment_index){
    var el_id = item_index + "_" + ann_index + "_" + comment_index;
    //$("inline_comment_" + el_id).hide();

    $("e_c_l_"+ el_id).hide();
    $("e_c_btn_" + el_id).show();
    $("cContent_" + el_id).hide();
    var html_content = $("cContent_" + el_id).select('[class="cContentInner"]')[0].innerHTML;
    $("edit_comment_content_" + el_id).value = displayInputContent(html_content); //_items[item_index].annotations[ann_index].inline_comments[comment_index].content;
    $("edit_comment_" + el_id).show();
}

function cancelEditBIComment(item_index,ann_index,comment_index){
    var el_id = item_index + "_" + ann_index + "_" + comment_index;
    $("edit_comment_" + el_id).hide();
    $("edit_comment_content_" + el_id).setStyle({height : "60px"});
    $("cContent_" + el_id).show();
}

function postEditBIComment(item_index,ann_index,comment_index){
    try{
        var el_id = item_index + "_" + ann_index + "_" + comment_index;
        if($("edit_comment_content_" + el_id).value.trim() == ''){
            return false;
        }
        var url = "/site/edit_sticky_note";
        var params = $("edit_CForm_" + el_id).serialize() + "&i_c_id=" +_items[item_index].annotations[ann_index].inline_comments[comment_index].id + "&group_id=" + _items[item_index].group_id + "&user_id=" + _items[item_index].annotations[ann_index].inline_comments[comment_index].user_id;
        _postEditBICommentLoading(item_index,ann_index,comment_index);
        new Ajax.Request(url,
        {
            method:"post",
            asynchronous:true,
            evalScripts:true,
            onSuccess:function(request){
                var respInfos = request.responseText.evalJSON();
                refreshBIComment(respInfos,item_index,ann_index,comment_index);
            },
            parameters:params
        }
        );
        return false;
    }catch(e){
        alert(e);
        return false;
    }
}

function _postEditBICommentLoading(item_index,ann_index,comment_index){
    var el_id = item_index + "_" + ann_index + "_" + comment_index;
    $("e_c_l_"+ el_id).show();
    $("e_c_btn_" + el_id).hide();
}

function refreshBIComment(respInfos,item_index,ann_index,comment_index){
    var el_id = item_index + "_" + ann_index + "_" + comment_index;
    
    //1. update inline comment js model
    _items[item_index].annotations[ann_index].inline_comments[comment_index].content = respInfos.content;
    
    //2. show new html
    var html_content = displayContent(processComment(respInfos.content));
    $("edit_comment_" + el_id).hide();
    $("cContent_" + el_id).update(html_content).show();
    $("inline_comment_" + el_id).show();
}

function removeBComment(item_index,comment_index){
    if(!confirm(ALE_21)) return false;
    var id = _items[item_index].page_comments[comment_index].id;
    _removeBCLoading(item_index,comment_index);
    try{
        var url = '/site/delete_page_comment';
        new Ajax.Request(url,
        {
            method:"post",
            asynchronous:true,
            evalScripts:true,
            onComplete:function(request){
                delete(_items[item_index].page_comments[comment_index]);
                _items[item_index].p_c_count--;
                $("comment_" + item_index + "_" + comment_index).remove();
                renderBDCount(item_index);
            },
            parameters:{
                p_c_id:id,
                g_l_id:_items[item_index].g_l_id,
                user_id:_items[item_index].page_comments[comment_index].user_id
            }
        }
    );
        return false;
    }catch(e) {
        alert(e);
        return false;
    }
}

function _removeBCLoading(item_index,comment_index){
    var el_id = item_index + "_" + comment_index;
    $("r_bc_a_" + el_id).update("...").addClassName("removeCLoading");
}

/****************************************
 * Bookmark Annotation, Inline Comment Methods
 ****************************************/

function addBInlineComment(index){
    $("ann_" + index).removeClassName("hover");
    $("ann_" + index).stopObserving('mouseover');
    $("div_i_c_" + index).show();
    $("add_comment_" + index).show();
    $("comment_content_"+index).focus();
}

function createICEditor(index){
    var form = new Element('form',{
        'method':'post'
    });
    form.id = "ICForm_" + index;

    var div_text = new Element('div',{
        'class':'commentText'
    });
    var textarea = new Element('textarea',{
        'name':'comment_content'
    });
    textarea.id = "comment_content_" + index;
    textarea.onkeypress = function(e){resiseTextArea(e,index)};
    div_text.appendChild(textarea);

    var div_loading = new Element('div',{
        'id':'c_l_'+index,
        'class':'commentLoading',
        'style':'display:none'
    }).update("...");

    var div_btn = new Element('div',{
        'id':'c_btn_'+index,
        'class':'commentBtn'
    });
    var input = new Element('input',{
        'type':'submit',
        'value':'Post'
    });
    var a_href = new Element('a',{
        'href':'javascript:void(0);'
    }).update('Cancel');
    a_href.onclick = function(){
        clearICommentForm(index)
    };
    div_btn.appendChild(input);
    div_btn.appendChild(a_href);

    var div_hidden = new Element('div',{
        'style':'position:absolute;visibility:hidden'
    })
    div_hidden.id = 'comment_div_'+index;

    form.appendChild(div_text);
    form.appendChild(div_loading);
    form.appendChild(div_btn);
    form.appendChild(div_hidden);

    form.onsubmit = postBIComment.bind(this,{"index":index});

    return form;
}

function postBIComment(args){
    try{
        var index = args.index; // index: "item_index" + "ann_index"
        var item_index = index.split("_")[0];
        var ann_index = index.split("_")[1];
        if($("comment_content_" + index).value.trim() == ''){return false;}
        var url = '/site/add_sticky_note';
        var params = $("ICForm_" + index).serialize() + "&g_l_id=" + _items[item_index].g_l_id + "&ann_id=" + _items[item_index].annotations[ann_index].id + "&item_index=" + item_index + "&ann_index=" + ann_index + "&inline_comments_size=" + _items[item_index].annotations[ann_index].inline_comments.length;
        _postBICLoading(index);
        new Ajax.Request(url,
        {
            method:"post",
            asynchronous:true,
            evalScripts:true,
            onSuccess:function(request){
                var respInfos = request.responseText.evalJSON();
                newBIComment(respInfos,item_index,ann_index);
                clearICommentForm(index);
                new AvatarPopup();
                enableEmailAlertOnPage(item_index);
            },
            parameters:params
        }
    );
        return false;
    }catch(e){
        alert(e);
        return false;
    }
}

function _postBICLoading(index){
    $("c_btn_"+index).hide();
    $("c_l_"+index).show();
}

function clearICommentForm(index){
    $("ann_" + index).observe('mouseover',hoverAnnItem.bindAsEventListener(this, ("ann_" + index)));
    $("add_comment_" + index).hide();
    $("comment_content_" + index).value = "";
    $("comment_content_" + index).setStyle({height : "60px"});
    if($("inline_comment_" + index).innerHTML.trim().blank()){$("div_i_c_" + index).hide();}
    $("c_l_" + index).hide();
    $("c_btn_" + index).show();
    $("cContent_" + index).show();
}

function newBIComment(resp,item_index,ann_index){
    //1. javascript model
    _items[item_index].annotations[ann_index].inline_comments.push(resp.obj);
    _items[item_index].annotations[ann_index].c_count++;
    _items[item_index].i_c_count++;

    //2. page element: bookmark item annotaions ul element
    $("inline_comment_" + item_index + "_" + ann_index).insert({"bottom":resp.html_str});

    //3. render count
    renderBDCount(item_index);
}

function removeBIComment(bm_index,ann_index,ic_index){
    if(!confirm(ALE_23)) return false;
    var index = [bm_index,ann_index,ic_index].join("_");
    var id = _items[bm_index].annotations[ann_index].inline_comments[ic_index].id;
    _removeBICLoading(index);
    try{
        var url = '/site/delete_sticky_note';
        new Ajax.Request(url,
        {
            method:"post",
            asynchronous:true,
            evalScripts:true,
            onSuccess:function(request){
                delete(_items[bm_index].annotations[ann_index].inline_comments[ic_index]);
                _items[bm_index].annotations[ann_index].c_count--;
                _items[bm_index].i_c_count--
                $("inline_comment_" + index).remove();
                var i_c_add_el_id = bm_index + "_" + ann_index;
                if($("inline_comment_" + i_c_add_el_id).innerHTML.trim().blank()){$("div_i_c_" + i_c_add_el_id).hide();}
                renderBDCount(bm_index);
            },
            parameters:{
                i_c_id:id,
                g_l_id:_items[bm_index].g_l_id,
                user_id:_items[bm_index].annotations[ann_index].inline_comments[ic_index].user_id
            }
        }
    );
    return false;
    }catch(e) {
        alert(e);
        return false;
    }
}

function _removeBICLoading(index){
    $("r_bc_a_" + index).update("...").addClassName("removeCLoading");
}

function removeAnn(index){
    if(!confirm(WORD_10)) return false;
    var indexA = index.split("_");
    var item_index = indexA[0];
    var ann_index = indexA[1];
    var ann = _items[indexA[0]].annotations[ann_index];

    var url = '/site/delete_highlight';
    _removeAnnLoading();
    new Ajax.Request(url,
    {
        method:"post",
        asynchronous:true,
        evalScripts:true,
        onSuccess:function(request){
            delete(ann);
            _items[indexA[0]].ann_count--;
            _items[indexA[0]].i_c_count -= ann.c_count;
            $("ann_" + index).remove();
            renderBDCount(item_index);
        },
        parameters:{
            ann_id : ann.id,
            g_l_id : ann.g_l_id,
            user_id : ann.user_id
        }
    }
);
    return false;
}

function _removeAnnLoading(){

}

function editB(args) {
    var pw;
    var winTitle = "Edit Item";
    var root = "leftColumn";
    var index = args.index;
    var b = $("item_"+index);
    var top = b.positionedOffset()[1]-180;
    pw = new PopWindow({
        optEnabled: true,
        left:120,
        top:top,
        width:500,
        title:winTitle,
        root:root
    });
    pw.appendNode(createBEditTemp(index));
    pw.cancel = function(){
        resetMoreAction();resetAllChecker();
    }
    pw.submitBtn.value = "Submit";
    pw.cancelBtn.value = "Cancel";
    pw.submit = submitEditB.bind(this, args);
    initBEditor(index);
}

function switchBToEditMode(index) {
    hideDisplayTemp(index);
    showEditTemp(index);
    initEditor(index);
}
function initBEditor(index) {
    var title;
    var tags;
    //var desc;

    title = _items[index].title;
    tags = _items[index].tags.split(",");
    //desc = _items[index].desc;

    $("bTxtTitle").value = title;
    var t_t = [];
    for(var i=0; i<tags.length; i++) {
        if(tags[i] !=  "no_tag"){
            tags[i].indexOf(" ")!=-1 ? t_t.push("\""+tags[i]+"\"") : t_t.push(tags[i])
        }
    }
    var t_name = t_t.join(" ");
    $("bTxtTags").value = t_name.trim();
    //$("bTxtDesc").value = desc.trim();
}

function switchBToDisplayMode(index){
    showDisplayTemp(index);
    hideEditTemp(index);
    hideItemNoticer(index);
    initDisplayTemp(index);
    if(_checkedItemCount==0) {
        hideBatchEditBBB();
        showBListOB();
        resetMoreAction();
    }
}

function initDisplayTemp(index) {
    $("titleLink_"+index).innerHTML = _items[index].title;
    var tagsEl = $("tags_"+index);
    tagsEl.innerHTML = "";
    var tags = _items[index].t_name.split(",");
    for(var i=0; i<tags.length; i++) {
        var a = document.createElement("a");
        a.href= "/" + _items[index].g_name + "/bookmark/tag/"+escape(tags[i]);
        a.innerHTML = tags[i];
        tagsEl.appendChild(a);
    }
    var desc = _items[index].description;
    if(!desc.blank()) {
        $("descContent_"+index).update(desc);
        $("desc_"+index).show();
    }else {
        $("desc_"+index).hide();
    }
}
function cancelEditB(){
    var index = this.id.split("_")[1];
    showDisplayTemp(index);
    hideEditTemp(index);
    hideItemNoticer(index);
    var checker = $("bookmarkChecker_"+index);
    if(checker.checked) {
        checker.click();
    }
    if(_checkedItemCount==0) {
        hideBatchEditBBB();
        showBListOB();
        resetMoreAction();
    }
}
function showDisplayTemp(index) {
    $("bDisplayTemp_"+index).style.display = "";
    _floatMenu.switchMenu2(true, index);
}
function hideDisplayTemp(index) {
    $("bDisplayTemp_"+index).style.display = "none";
}
function showEditTemp(index) {
    var winTitle = "Edit Item";
    var root = "leftColumn";
    pw = new PopWindow({
        optEnabled: true,
        left:120,
        top:top,
        width:500,
        title:winTitle,
        root:root
    });
    pw.appendNode(createBEditTemp(index));
    pw.cancel = function(){
        resetMoreAction();resetAllChecker();
    }
    pw.submitBtn.value = "Submit";
    pw.cancelBtn.value = "Cancel";
}
function hideEditTemp(index) {
    $("bEditTemp_"+index).style.display = "none";
}
function loadDisplayTemp(index) {
    return _items[index].bDisplayTemp;
}

function loadBEditTemp(index) {
    if(typeof(_items[index].bEditTemp)=="undefined") {
        _items[index].bEditTemp =  createBEditTemp(index);
    }
    return _items[index].bEditTemp;
}

function createBEditTemp(index) {
    var index = index;

    var table = new Element("table", {
        className: "editBTable"
    });
    var tbody = new Element("tbody");
    // title row
    var tr = new Element("tr");
    tr.appendChild(new Element("th").update("Title:"));
    tr.appendChild(new Element("td").update("<input type='text' id='bTxtTitle' class='inputTxt2' name='title' size='70' maxlength='255' />"));
    tbody.appendChild(tr);
    // tags row
    tr = new Element("tr");//.setStyle({display : "none"});
    tr.appendChild(new Element("th").update("Tags:"));
    tr.appendChild(new Element("td").update("<input type='text' id='bTxtTags' class='inputTxt2' name='tags' size='70' maxlength='255' /><br/><span style='font-size:8pt;color:#999;'>space separated. Use \" \" for tag with multiple words.</span>"));
    tbody.appendChild(tr);

    table.appendChild(tbody);
    return table;
}

/* submit bookmark editing */
function submitEditB(args) {
    try{
        var index = args.index;
        var titleTxt = $("bTxtTitle");
        if(titleTxt.value.trim()=="") {
            titleTxt.focus();
            //showItemNoticer(index, WORD_1);
            return false;
        }
        var tagsTxt = $("bTxtTags");
//        if(tagsTxt.value.trim()=="") {
//            tagsTxt.focus();
//            showItemNoticer(index, WORD_2);
//            return false;
//        }
        //var descTxt = $("bTxtDesc");
        var url = '/site/edit_bookmark';
        var json = {
            "g_l_id" : _items[index].g_l_id,
            "user_id" : _items[index].last_user_id,
            "title" : titleTxt.value,
            //"desc" : descTxt.value,
            "tags" : tagsTxt.value
        };

        PopWindow.instance.onLoading();
        new Ajax.Request(url,
        {
            asynchronous:true,
            evalScripts:false,
            onComplete:function(request){
                PopWindow.instance.onComplete({
                    status:request.status
                });
                if(request.status=="200") {
                    var r = request.responseText.evalJSON();
                    var b = _items[index];
                    b.title = r["title"];
                    b.tags = r["tags"].join(",");
                    //b.description = r["desc"];
                    refreshBookmark(index);
                }
            },
            parameters:"json="+encodeURIComponent(Object.toJSON(json))
        }
    );
        return false;
    }catch(e) {
        alert(e);
    }
}

function refreshBookmark(index) {
    $("title_link_"+index).update(_items[index].title);
    var tagsEl = $("tags_"+index).update("");
    var tags = _items[index].tags.split(",");
    for(var i=0; i<tags.length; i++) {
        var a = document.createElement("a");

        if(tags[i].strip() == "" || tags[i].strip() == "no_tag"){
            continue;
        }

        if(tags[i].indexOf(" ")!=-1) {
            a.href= "/group/" + _items[index].g_name +"/content/tag/"+encodeURIComponent("\""+tags[i]+"\"");
        }else {
            a.href="/group/" + _items[index].g_name +"/content/tag/"+encodeURIComponent(tags[i]);
        }
        a.innerHTML = tags[i];
        tagsEl.appendChild(a);
//        if(i<tags.length-1) {
//            tagsEl.innerHTML += ", "
//        }
    }
//    var desc = _items[index].description;
//    if(!desc.blank()) {
//        $("desc_"+index).update(desc).show();
//    }else {
//        $("desc_"+index).hide();
//    }
}

function resetAllChecker() {
    for(var i=0; i<_items.length; i++) {
        resetChecker(i);
    }
}

function resetChecker(index) {
    var checker = $("bookmarkChecker_"+index);
    if(checker.checked) checker.click();
    if(_checkedItemCount==0) {
        resetMoreAction();
    }
}

/* submit bookmark editing */

function renderBDCount(item_index){
    var dCount = _items[item_index].p_c_count + _items[item_index].ann_count + _items[item_index].i_c_count;
    if($("dCount_" + item_index) != null){$("dCount_" + item_index).update(dCount);}
}

function moderateB(item_index){
    if($("item_" + item_index) == null) return;

    $("item_" + item_index).select('[class="commentItem"]','[class="commentItem "]', '[class="commentItem hide"]').each(function(li){
        var index = li.id.split("t_")[1];
        var manage_span = $("manage_comment_" + index);
        if(manage_span != null){
            manage_span.removeClassName("hide");
        };
    });
}

function forwardB(index_a) {
    forwardItem({'type':'bookmark', 'index_a':index_a});
}

/*======================================
 * forward bookmark item: send to 
 *======================================*/
function forwardItem(args) {
    var toggler = this;
    var pw;
    /*------------------------------------
     * init for each type
     *------------------------------------*/
    var root="leftColumn";
    var p = $("leftColumn").viewportOffset();
    var top = 0;
    //var index_a = args.index_a;
    if(p[1]<0) {top = 0 - p[1];}
    pw = new PopWindow({optEnabled: true, left:120, top:top+20, width:500, title:"Send To", root:root});
    pw.cancel = function(){resetMoreAction();resetAllChecker();}
    //index_a.each(function(index){switchDetails(index, "collapse");})

    pw.appendNode(loadForwardTemp(args));
    pw.submit = function(){
        var url = BOOKMARK_HOST + "/message_mana/send_msg";
        var sendTo = $("sendToSelector").value;
        var json = {};
        switch(sendTo) {
            case "all":{
                    json["send_type"] = "all";
                }break;
            case "some":{
                    json["send_type"] = "some";
                    json["send_to"] = _GLOBAL_VAR[_GLOBAL_VAR["bACCID"]+"_instance"].getRecItems();
                }break;
            case "myself":{
                    json["send_type"] = "myself";
                }break;
            default: {
                    json["send_type"] = "list";
                    json["send_to"] = sendTo;
                }break;
        }
        json["privacy"] = $("sendToPrivate").checked ? "public" : "private";
        json["star"] = "no";//$("sendToImportant").checked ? "yes" : "no";
        var ff = $("forwardForm");
        json["subject"] = ff.subject.value;
        json["message"] = ff.message.value;
        if(ff.includeA.checked){json["quotes"] = $("forwardPreview").innerHTML;}
        this.onLoading();
        CrossSubDomainAjax.request(url,
        {asynchronous:true,
            evalScripts:false,
            onComplete:function(request){
                PopWindow.instance.onComplete({status:request.status});
                resetMoreAction();
                resetAllChecker();
            },parameters:"json="+encodeURIComponent(Object.toJSON(json))});
        return false;
    }.bind(pw);

    /*--------------------------------
     * init contacts
     *--------------------------------*/
    if(!ACContact.contacts || ACContact.contacts.length==0){
        pw.onLoading();
        var url = BOOKMARK_HOST + "/user_mana2/load_contacts";
        CrossSubDomainAjax.request(url,
        {asynchronous:true,
            evalScripts:false,
            method:'get',
            onComplete:function(request){
                if(request.status=="200") {
                    var contacts = request.responseText.evalJSON();
                    _GLOBAL_VAR[_GLOBAL_VAR["bACCID"]+"_instance"] = new ACContact({rec:$(_GLOBAL_VAR["bACCID"]), contacts:contacts});
                    initContactsSelect();
                    PopWindow.instance.noticer.hide();
                    PopWindow.instance.content.show();
                    PopWindow.instance.opt.show();
                    PopWindow.instance.reCalShadowRange();
                }}});
        return false;
    }else {
        _GLOBAL_VAR[_GLOBAL_VAR["bACCID"]+"_instance"] = new ACContact({rec:$(_GLOBAL_VAR["bACCID"])});
        initContactsSelect();
    }
}

/*=================================
 * forward template
 *=================================*/
function loadForwardTemp(args) {

    var table = new Element("table", {
        id:"forwardTable"
    });
    var tbody = new Element("tbody");

    // send to
    var tr = new Element("tr");
    tr.appendChild(new Element("th").update("Send to:"));
    var td = new Element("td", {
        id:"sendToTD"
    });
    tr.appendChild(td);

    // options
    td = new Element("td", {
        id:"forwardOptions"
    });

    td.appendChild(new Element("label").update("<input type='checkbox' id='sendToPrivate' /> Add it to my EasyBlog?"));
    //td.appendChild(new Element("label").update("<input type='checkbox' id='sendToImportant' /> Important?"));
    td.appendChild(new Element("label").update("<input type='checkbox' checked='checked' name='includeA' onclick='includeAnnotations.bind(this)();' /> Include quotes"));
    tr.appendChild(td);
    tbody.appendChild(tr);

    // contacts
    tr = new Element("tr", {
        id:"contactRow"
    });
    tr.appendChild(new Element("th"));
    td = new Element("td", {
        "colspan":"2"
    });
    var div = new Element("div", {
        className:"accOuter"
    });
    div.appendChild(new Element("div", {
        id:_GLOBAL_VAR["bACCID"],
        className:"autocompleteContacts"
    }).show());
    td.appendChild(div);
    tr.appendChild(td);
    tbody.appendChild(tr);

    // subject
    tr = new Element("tr", {
        id:"subjectRow"
    });
    tr.appendChild(new Element("th").update("Subject:"));
    var subEl = new Element("input", {
        type:"text",
        name:"subject",
        maxlength:255,
        className:"inputTxt"
    });

    subEl.value = _items[args.index_a[0]].title.truncate(75);
    
    td = new Element("td", {
        "colspan":"2"
    });
    td.appendChild(subEl);
    tr.appendChild(td);
    tbody.appendChild(tr);


    tr = new Element("tr");
    tr.appendChild(new Element("th").update("Message:"));
    tbody.appendChild(tr);

    // message
    tr = new Element("tr");
    td = new Element("td", {
        "colspan":"3"
    });
    td.appendChild(new Element("textarea", {
        "name":"message",
        className:"inputTxt"
    }));
    tr.appendChild(td);
    tbody.appendChild(tr);
    table.appendChild(tbody);

    var form = new Element("form", {
        id:"forwardForm"
    });
    form.setAttribute('autocomplete', 'off');
    form.appendChild(table);

    // preview box
    var preBox = new Element("div", {
        "id":"forwardPreview"
    });
    preBox.appendChild(loadAnnotations(args.index_a))

    form.appendChild(preBox);
    return form;

}

function loadAnnotations(index_a) {
    var contentOutter = new Element("div", {className:"extraAContentOutter", id:"extraAContentOutter"});
    var content = new Element("dl", {className:"extraAContent", id:"extraAContent"});
    for(var k=0; k<index_a.length; k++) {
        var item_index = index_a[k];
        var title = $("title_link_"+item_index);
        var t = new Element("a", {href:title.href,className:"eTitle"}).update(title.innerHTML);
        var dt = new Element("dt");
        dt.appendChild(t);
        content.appendChild(dt);
        var dd = new Element("dd");

        // make annotations
        var aUL = new Element("ul", {className:"eAUL"});
        //var anns = $("ann_"+item_index);
        var anns = _items[item_index].annotations;
        if(_items[item_index].ann_count > 0){
            //var a = anns.down();
            for(var j=0;j<anns.length;j++){
                //if(a.className == "clickShowMore"){a = a.next();continue;}
                //var h = a.down();
                var a = anns[j];
                if(a == null) continue;
                var el_id = item_index + "_" + j;
                var ann_content = $("ann_" + el_id).select('[class="content"]')[0].innerHTML;
                var aLI = new Element("li");
                aLI.appendChild(new Element("div",{className:"eHContent"}).update(ann_content));
                var sUL = new Element("ul",{className:"eSUL"});
                var inline_comments = _items[item_index].annotations[j].inline_comments;
                // make inline comments
                if(_items[item_index].annotations[j].c_count > 0){
                    for(var m=0; m<inline_comments.length;m++) {
                        var i_c = inline_comments[m];
                        if(i_c == null) continue;
                        var el_id = item_index + "_" + j + "_" + m;
                        var sLI = new Element("li")
                        sLI.appendChild(new Element("span", {className:"eSContent"}).update($("cContent_" + el_id).innerHTML));
                        var tail = new Element("span", {className:"eSTail"}).update(" - by ");
                        tail.appendChild(new Element("a", {href:BOOKMARK_HOST+"/user/"+i_c.user_name}).update(i_c.user_real_name));
                        sLI.appendChild(tail);
                        sUL.appendChild(sLI);
                    }
                    aLI.appendChild(sUL);
                }

                aUL.appendChild(aLI);
            }
        }
        dd.appendChild(aUL);

        // make page comments
        var page_comments = _items[item_index].page_comments;
        if(_items[item_index].p_c_count > 0){
            var cUL =  new Element("ul",{className:"eSUL"});
            for(var i=0; i<page_comments.length;i++) {
                var c = page_comments[i];
                if(c == null) continue;
                var el_id = item_index + "_" + i;
                var cLI = new Element("li")
                cLI.appendChild(new Element("span", {className:"eSContent"}).update($("cContent_" + el_id).innerHTML));
                var tail = new Element("span", {className:"eSTail"}).update(" - by ");
                tail.appendChild(new Element("a", {href:BOOKMARK_HOST+"/user/"+c.user_name}).update(c.user_real_name));
                cLI.appendChild(tail);
                cUL.appendChild(cLI);
            }
            dd.appendChild(cUL);
        }

        content.appendChild(dd);
    }
    contentOutter.appendChild(content);
    return contentOutter;
}

function includeAnnotations(){
    var preBox = $("forwardPreview");
    if(this.checked){
        preBox.show();
    }else {
        preBox.hide();
    }
}

function initContactsSelect() {
    var select = new Element("select", {id:"sendToSelector"});
    select.onchange = function(){
        if(this.value=="some") {
            $(_GLOBAL_VAR["bACCID"]).show();
            _GLOBAL_VAR[_GLOBAL_VAR["bACCID"]+"_instance"].showTipInBox();
        }else {
            _GLOBAL_VAR[_GLOBAL_VAR["bACCID"]+"_instance"].recBox.reset();
            _GLOBAL_VAR[_GLOBAL_VAR["bACCID"]+"_instance"].hideTipInBox();
            $(_GLOBAL_VAR["bACCID"]).hide();
        }
    }.bind(select);
    select.appendChild(new Element("option", {value:"some", "selected":"selected"}).update("My mutual friends or emails"));
    select.appendChild(new Element("option", {value:"all"}).update("All my mutual friends"));
    select.appendChild(new Element("option", {value:"myself"}).update("No one. Just a note"));
    
    select.setAttribute("autocomplete", "off");
    if(ACContact.contactListsID.length>0) {
        select.appendChild(new Element("option", {className:"sep", "disabled":"disabled"}).update("--My Contact Lists--"));
        ACContact.contactListsID.each(function(cIndex){
            var list = ACContact.contacts[cIndex];
            select.appendChild(new Element("option", {value:list.id}).update(list.extra.title));
        });
    }
    var sendTo = $("sendToTD");
    sendTo.update("");
    sendTo.appendChild(select);
}

/*===========================================
 * Save Item
 * args:
 * index - item index
 * type - 'bookmark', 'list'
 * saveType - 'create', 'edit'
 *===========================================*/
function saveItem(args) {
    var pw;
    _GLOBAL_VAR["saveBType"] = args.saveType;
    var index = args.index;
    var root = "leftColumn";
    var b = $("item_"+index);
    var top = b.positionedOffset()[1]-180;
    var winTitle = "Save Bookmark";
    pw = new PopWindow({
        optEnabled: true,
        left:120,
        top:top,
        width:500,
        title:winTitle,
        root:root
    });
    //switchDetails(index, "collapse");

    pw.appendNode(createSaveItemTemp(args));
    pw.cancel = function(){resetMoreAction();resetAllChecker();}
    pw.submitBtn.value = "Submit";
    pw.cancelBtn.value = "Cancel";
    pw.submit = submitSaveItem.bind(this, args);
    initSaveItemEditor(args);
}

function createSaveItemTemp(args) {
    var index = args.index;
    var type = args.saveType;

    var table = new Element("table", {
        className: "editBTable"
    });
    var tbody = new Element("tbody");
    // title row
    var tr = new Element("tr");
    tr.appendChild(new Element("th").update("Title:"));
    tr.appendChild(new Element("td").update("<input type='text' id='bTxtTitle' name='title' size='70' maxlength='255' />"));
    tbody.appendChild(tr);
    // options row
    tr = new Element("tr");
    tr.appendChild(new Element("th"));
    tr.appendChild(new Element("td").update("<label><input id='bPriPrivate' type='checkbox' />Private</label> <label><input type='checkbox' id='bUnread' />Unread</label>"));
    tbody.appendChild(tr);
    // desc row
    tr = new Element("tr");
    tr.appendChild(new Element("th").update("Description:"));
    tr.appendChild(new Element("td").update("<textarea id='bTxtDesc' name='desc' rows='3' cols='67' ></textarea>"));
    tbody.appendChild(tr);
    // tags row
    tr = new Element("tr");
    tr.appendChild(new Element("th").update("Tags:"));
    tr.appendChild(new Element("td").update("<input type='text' id='bTxtTags' name='tags' size='70' maxlength='255' /><span style='font-size:8pt;color:#999;'>space separated. Use \" \" for tag with multiple words.</span>"));
    tbody.appendChild(tr);
    // add to list
    tr = new Element("tr");
    tr.appendChild(new Element("th"));
    var td = new Element("td").update("<label for='bAddToList'><input type='checkbox' id='bAddToList' onclick='switchSelectAddToList(this);' />Add to a List</label>");
    td.appendChild(new Element("div", {
        className: "addToHolder",
        id:"addToListHolder"
    }).hide());
    tr.appendChild(td);
    tbody.appendChild(tr);
    // share to group
    tr = new Element("tr");
    tr.appendChild(new Element("th"));
    td = new Element("td").update("<label for='bAddToGroup'><input type='checkbox' id='bAddToGroup' onclick='switchSelectAddToGroup(this);' />Share to a Group</label>");
    td.appendChild(new Element("div", {
        className: "addToHolder",
        id:"addToGroupHolder"
    }).hide());
    tr.appendChild(td);
    tbody.appendChild(tr);
    table.appendChild(tbody);
    return table;
}
function switchSelectAddToList() {
    var h = $("addToListHolder");
    if(!_GLOBAL_VAR["my_lists"]) {
        // load my lists
        var url = BOOKMARK_HOST + '/bookmark_list/load_user_b_list?u_name='+_GLOBAL_VAR['my_name'];
        h.update("<img src='/images/loading.gif' alt='loading...' />").show();
        CrossSubDomainAjax.request(url,
        {
            asynchronous:true,
            evalScripts:false,
            onComplete:function(request){
                if(request.status=="200") {
                    _GLOBAL_VAR["my_lists"] = request.responseText.evalJSON();
                    renderListSelecotr(h);
                }
            }
        });
        return false;
    }else {
        h.visible() ? h.hide() : h.show();
        //if (!$("addToListSelector")) {
        renderListSelecotr(h);
    //}
    }
}
function renderListSelecotr(h) {
    var s = new Element("select", {
        id:"addToListSelector"
    });
    s.appendChild(new Element("option", {
        "value":-1
    }).update("------------"));
    for(var i=0; i<_GLOBAL_VAR["my_lists"].length; i++) {
        var o = new Element("option", {
            "value":i
        }).update(_GLOBAL_VAR["my_lists"][i].title);
        s.appendChild(o);
    }
    h.update("Add to a List").appendChild(s);
    s.value = -1;
}

function switchSelectAddToGroup(groupChecker){
    var h = $("addToGroupHolder");
    if(!_GLOBAL_VAR["my_groups"]) {
        // load my groups
        var url = BOOKMARK_HOST + '/group_mana/load_groups?u_name='+_GLOBAL_VAR['my_name'];
        h.update("<img src='/images/loading.gif' alt='loading...' />").show();
        CrossSubDomainAjax.request(url,
        {
            asynchronous:true,
            evalScripts:false,
            onComplete:function(request){
                if(request.status=="200") {
                    _GLOBAL_VAR["my_groups"] = request.responseText.evalJSON();
                    renderGroupSelector(h);
                }
            }
        });
        return false;
    }else {
        h.visible() ? h.hide() : h.show();
        if (!$("addToGroupSelector")) {
            renderGroupSelector(h);
        }
    }
}
function renderGroupSelector(h) {
    var s = new Element("select", {
        id:"addToGroupSelector"
    });
    s.appendChild(new Element("option", {
        "value":-1
    }).update("------------"));
    for(var i=0; i<_GLOBAL_VAR["my_groups"].length; i++) {
        var o = new Element("option", {
            "value":i
        }).update(_GLOBAL_VAR["my_groups"][i].display_name);
        s.appendChild(o);
    }
    h.update("Share to").appendChild(s);
    s.value = -1;
}

function initSaveItemEditor(args) {
    var title;
    var tags;
    //var desc;
    var index = args.index;
    title = _items[index].title; //_GLOBAL_VAR['bookmarks'][index].title;
    tags = _items[index].tags.split(","); //_GLOBAL_VAR['bookmarks'][index].tags.split(",");
    //desc = _GLOBAL_VAR['bookmarks'][index].desc;
    $("bTxtTitle").value = title;
    var t_t = [];
    for(var i=0; i<tags.length; i++) {
        tags[i].indexOf(" ")!=-1 ? t_t.push("\""+tags[i]+"\"") : t_t.push(tags[i])
    }
    var t_name = t_t.join(" ");
    $("bTxtTags").value = t_name.trim();
    //$("bTxtDesc").value = desc.trim();
}

function submitSaveItem(args) {
    var index = args.index;
    var titleTxt = $("bTxtTitle");
    if(titleTxt.value.trim()=="") {
        titleTxt.focus();
        return false;
    }
    var tagsTxt = $("bTxtTags");
    if(tagsTxt.value.trim()=="") {
        tagsTxt.focus();
        return false;
    }
    var descTxt = $("bTxtDesc");
    var url = BOOKMARK_HOST + '/toolbar_wrap/save_bookmark';//bookmark_mana2/submit_b_edit';
    var itemURL;
    var unread;
    var mode;
    if($("bUnread")){
        unread = $("bUnread").checked;
    }
    if($("bPriPrivate")){
        mode = $("bPriPrivate").checked ? 2 : 0;
    }

    itemURL = _items[index].url; //_GLOBAL_VAR['bookmarks'][index].url;
    var json = {
        "title" : titleTxt.value,
        "desc" : descTxt.value,
        "tags" : tagsTxt.value,
        "url" : itemURL,
        "mode" : mode,
        "unread" : unread
    };

    if($("bAddToGroup").checked) {
        var g = _GLOBAL_VAR['my_groups'][$F("addToGroupSelector")];
        if(g) {
            json["groups"] = [g.g_name];
        }
    }
    if($("bAddToList").checked) {
        var l = _GLOBAL_VAR['my_lists'][$F("addToListSelector")];
        if(l) {
            json["lists"] = [l.id];
        }
    }
    if(_GLOBAL_VAR["saveBType"]=="create") {
        json["save_from_bid"] = _items[index].b_id2;
    }
    //    var wa = $("addToGroupWithA");
    //    if(wa && wa.checked){
    //        json["shareExistingAnnotations"] = true
    //    }
    //    var gp = $("addToGroupComment");
    //    if(gp && !gp.value.blank() && gp.value!=_GLOBAL_VAR["pgHint"]) {
    //        json["pageComment"] = {content:encodeURIComponent(gp.value),
    //            groups:json["groups"],
    //            justForGroups:true};
    //    }
    //    if(_GLOBAL_VAR["type"]=='bookmark' && _GLOBAL_VAR["saveBType"]=="create") {
    //        json["save_from_bid"] = _GLOBAL_VAR['bookmarks'][index].b_id2;
    //    }

    PopWindow.instance.onLoading();
    CrossSubDomainAjax.request(url,{
        asynchronous:true,
        evalScripts:false,
        onComplete:function(request){
            PopWindow.instance.onComplete({
                status:request.status
            });
            if(request.status=="200") {
                if(args.type=='bookmark') {
                    if(_GLOBAL_VAR["saveBType"]=="edit") {
//                        var r = request.responseText.evalJSON();
//                        var b = _GLOBAL_VAR['bookmarks'][index];
//                        b.title = titleTxt.value;
//                        b.t_name = r["tags"].join(",");
//                        b.description = r["desc"];
//                        if(r["lists"]) {
//                            b.lists_id = b.lists_id.concat(r["lists"]).uniq();
//                        }
//                        if(r["groups"]) {
//                            b.groups = b.groups.concat(r["groups"]);
//                        }
//                        refreshBookmark(index);
                    }else if(_GLOBAL_VAR["saveBType"]=="create") {
                        $("item_action_save_" + index).remove();
//                        var saveMenu = $("menu_item_"+index+"_save");
//                        if(saveMenu) {
//                            saveMenu.onclick = null;
//                            saveMenu.update("Saved");
//                        }
//                        var quickSaveMenu = $("menu_item_"+index+"_qcopy");
//                        if(quickSaveMenu) {
//                            quickSaveMenu.hide();
//                        }
                    }
                }else if(args.type=='list') {
            // after save
            }
            }
        },
        parameters:"json="+encodeURIComponent(Object.toJSON(json))
    }
    );
    return false;
}

/****************************************
 * Topic Methods
 ****************************************/
function addTComment(item_index){
    $("details_" + item_index).removeClassName("hide");
    $("add_comment_" + item_index).show();
    $("c_l_" + item_index).hide();
    $("c_btn_" + item_index).show();
    $("comment_content_"+item_index).focus();
}

function createTCEditor(index,item_id){
    var form = new Element('form',{
        'method':'post'
    });
    form.id = "CForm_" + index;

    var input_post_info = new Element('input',{
        'name':'item_id',
        'value':item_id,
        'type':'hidden'
    });
    var div_text = new Element('div',{
        'class':'commentText'
    });
    var textarea = new Element('textarea',{
        'name':'comment_content'
    });
    textarea.id = "comment_content_" + index;
    textarea.onkeypress = function(e){resiseTextArea(e,index)};
    div_text.appendChild(textarea);

    var div_loading = new Element('div',{
        'id':'c_l_'+index,
        'class':'commentLoading',
        'style':'display:none'
    }).update("...");

    var div_btn = new Element('div',{
        'id':'c_btn_'+index,
        'class':'commentBtn'
    });
    var input = new Element('input',{
        'type':'submit',
        'value':'Post'
    });
    var a_href = new Element('a',{
        'href':'javascript:void(0);'
    }).update('Cancel');
    a_href.onclick = function(){
        clearCommentForm(index)
    };
    div_btn.appendChild(input);
    div_btn.appendChild(a_href);

    var div_hidden = new Element('div',{
        'style':'position:absolute;visibility:hidden'
    });
    div_hidden.id = 'comment_div_'+index;

    form.appendChild(input_post_info);
    form.appendChild(div_text);
    form.appendChild(div_loading);
    form.appendChild(div_btn);
    form.appendChild(div_hidden);
    form.onsubmit = postTComment.bind(this,{"index":index});

    return form;
}

function postTComment(args){
    try{
        var item_index = args.index;
        var from = args.from ? args.from : "item_page";
        if($("comment_content_" + item_index).value.trim() == ''){
            return false;
        }
        var url = "/site/add_topic_comment";
        var params = $("CForm_" + item_index).serialize() + "&group_id=" + _items[item_index].group_id + "&item_index=" + item_index + "&topic_posts_size=" + _items[item_index].posts.length;
        if(from == "entry_page") params += "&from=entry_page";
        _postTCLoading(item_index);
        new Ajax.Request(url,
        {
            method:"post",
            asynchronous:true,
            evalScripts:true,
            onSuccess:function(request){
                var respInfos = request.responseText.evalJSON();
                newTComment(respInfos,item_index,from);
                if(from == "item_page"){
                    clearCommentForm(item_index);
                }else if(from == "entry_page"){
                    cancelPostComment(item_index);
                }
                new AvatarPopup();
                enableEmailAlertOnPage(item_index);
            },
            parameters:params
        }
        );
        return false;
    }catch(e){
        alert(e);
        return false;
    }
}

function newTComment(resp, item_index){
    //1. javascript model
    _items[item_index].posts.push(resp.obj);
    _items[item_index].post_count++;
    //2. page element
    $("comment_" + item_index).insert({"bottom":resp.html_str});

    //3. update page content
    renderTDCount(item_index);
}

function _postTCLoading(index){
    $("c_btn_"+index).hide();
    $("c_l_"+index).show();
}

function cancelPostComment(item_index){
    $("comment_content_" + item_index).value = "";
    $("c_l_" + item_index).hide();
    $("c_btn_" + item_index).show();
    
}

function editTComment(item_index, comment_index, from){
    from = from ? from : "item_page";
    var el_id = item_index + "_" + comment_index;
    if(from == "item_page"){
        $("comment_" + el_id).hide();
    }else if(from == "entry_page"){
        $("cContent_" + el_id).hide();
    }

    var html_content = $("cContent_" + el_id).select('[class="cContentInner"]')[0].innerHTML; //$("cContent_" + el_id).innerHTML.replace(/<br>/gi, '\n'); //displayContent(_items[item_index].posts[comment_index].content);
    $("edit_comment_content_" + el_id).value = displayInputContent(html_content);
    $("e_c_l_"+ el_id).hide();
    $("e_c_btn_" + el_id).show();
    $("edit_comment_" + el_id).show();

    if($("cContent_" + el_id).getHeight() > 50) $("edit_comment_content_" + el_id).setStyle({height : "180px"});
}

function cancelEditTComment(item_index, comment_index, from){
    from = from ? from : "item_page";
    var el_id = item_index + "_" + comment_index;
    $("edit_comment_" + el_id).hide();
    $("edit_comment_content_" + el_id).setStyle({height : "60px"});
    if(from == "entry_page"){
        $("cContent_" + el_id).show();
    }else if(from == "item_page"){
        $("comment_" + el_id).show();
    }
}

function postEditTComment(item_index, comment_index, from){
    try{
        from = from ? from : "item_page";
        var el_id = item_index + "_" + comment_index;
        if($("edit_comment_content_" + el_id).value.trim() == ''){
            return false;
        }
        var url = "/site/edit_topic_post";
        var params = $("edit_CForm_" + el_id).serialize() + "&p_id=" +_items[item_index].posts[comment_index].id + "&group_id=" + _items[item_index].group_id + "&user_id=" + _items[item_index].posts[comment_index].user_id;
        _postEditTCommentLoading(item_index,comment_index);
        new Ajax.Request(url,
        {
            method:"post",
            asynchronous:true,
            evalScripts:true,
            onSuccess:function(request){
                var respInfos = request.responseText.evalJSON();
                refreshTComment(respInfos,item_index,comment_index,from);
            },
            parameters:params
        }
        );
        return false;
    }catch(e){
        alert(e);
        return false;
    }
}

function _postEditTCommentLoading(item_index,comment_index){
     var el_id = item_index + "_" + comment_index;
     $("e_c_l_"+ el_id).show();
     $("e_c_btn_" + el_id).hide();
}

function refreshTComment(respInfos,item_index,comment_index,from){
    //1. update topic comment js model
    _items[item_index].posts[comment_index].content = respInfos.content;

    var html_content = displayContent(processComment(respInfos.content));

    //2. show new html
    if(from=="entry_page"){
       $("edit_comment_" + item_index + "_" + comment_index).hide();
       $("cContent_" + item_index + "_" + comment_index).update(html_content).show();
       //$("comment_" + item_index + "_" + comment_index).show();
    }else if(from == "item_page"){
       $("edit_comment_" + item_index + "_" + comment_index).hide();
       $("cContent_" + item_index + "_" + comment_index).update(html_content);
       $("comment_" + item_index + "_" + comment_index).show();
    }
}

function removeTComment(item_index,post_index){
    if(!confirm(ALE_21)) return false;
    var el_id = item_index + "_" +post_index;
    _removeTCLoading(item_index, post_index);
    try{
        var url = '/site/delete_topic_post';
        new Ajax.Request(url,
        {
            method:"post",
            asynchronous:true,
            evalScripts:true,
            onSuccess:function(request){
                delete(_items[item_index].posts[post_index]);
                _items[item_index].post_count--;
                
                if(_items[item_index].posts.compact().length == 0){
                    delete(_items[item_index]);
                    $("item_" + item_index).remove();
                    if(_items.compact().lenght == 0){self.location.reload();}
                }else{
                    $("comment_" + el_id).remove();
                    renderTDCount(item_index);
                }
            },
            parameters:{
                group_id : _items[item_index].group_id,
                tid : _items[item_index].tid,
                pid : _items[item_index].posts[post_index].id,
                user_id : _items[item_index].posts[post_index].user_id
            }
        }
    );
        return false;
    }catch(e) {
        alert(e);
        return false;
    }
}

function _removeTCLoading(item_index, comment_index){
    var el_id = item_index + "_" + comment_index;
    $("r_tc_a_" + el_id).update("...").addClassName("removeCLoading");
}

function editT(args){
    var pw;
    var winTitle = "Edit Item";
    var root = "leftColumn";
    var index = args.index;
    var b = $("item_"+index);
    var top = b.positionedOffset()[1]-180;
    pw = new PopWindow({
        optEnabled: true,
        left:120,
        top:top,
        width:500,
        title:winTitle,
        root:root
    });
    pw.appendNode(createTEditTemp(index));
    pw.cancel = function(){
        resetMoreAction();resetAllChecker();
    }
    pw.submitBtn.value = "Submit";
    pw.cancelBtn.value = "Cancel";
    pw.submit = submitEditT.bind(this, args);
    initTEditor(index);
}

function createTEditTemp(index){
    var index = index;

    var table = new Element("table", {
        className: "editBTable"
    });
    var tbody = new Element("tbody");
    // title row
    var tr = new Element("tr");
    tr.appendChild(new Element("th").update("Title:"));
    tr.appendChild(new Element("td").update("<input type='text' id='tTxtTitle' class='inputTxt2' name='title' size='70' maxlength='255' />"));
    tbody.appendChild(tr);
    // tags row
    tr = new Element("tr");//.setStyle({dislay : "none"});
    tr.appendChild(new Element("th").update("Tags:"));
    tr.appendChild(new Element("td").update("<input type='text' id='tTxtTags' class='inputTxt2' name='tags' size='70' maxlength='255' />"));
    tbody.appendChild(tr);

    table.appendChild(tbody);
    return table;
}

function initTEditor(index){
    var title;
    var tags;

    title = _items[index].title;
    tags = _items[index].tags.split(",");

    $("tTxtTitle").value = title;
    var t_t = [];
    for(var i=0; i<tags.length; i++) {
        if(tags[i] != "no_tag"){
            tags[i].indexOf(" ")!=-1 ? t_t.push("\""+tags[i]+"\"") : t_t.push(tags[i])
        }
    }
    var t_name = t_t.join(" ");
    $("tTxtTags").value = t_name.trim();
}

function submitEditT(args){
    try{
        var index = args.index;
        var titleTxt = $("tTxtTitle");
        if(titleTxt.value.trim()=="") {
            titleTxt.focus();
            showItemNoticer(index, WORD_1);
            return false;
        }
        var tagsTxt = $("tTxtTags");
//        if(tagsTxt.value.trim()=="") {
//            tagsTxt.focus();
//            showItemNoticer(index, WORD_2);
//            return false;
//        }
        var url = '/site/edit_topic';
        PopWindow.instance.onLoading();
        new Ajax.Request(url,
        {
            asynchronous:true,
            evalScripts:false,
            onComplete:function(request){
                PopWindow.instance.onComplete({
                    status:request.status
                });
                if(request.status=="200") {
                    var r = request.responseText.evalJSON();
                    var t = _items[index];
                    t.title = r["title"];
                    t.tags= r["tags"].join(",");
                    refreshTopic(index);
                }
            },
            parameters:{
                "group_id" : _items[index].group_id,
                "tid"  : _items[index].tid,
                "title" : titleTxt.value,
                "tags" : tagsTxt.value
            }
        }
    );
        return false;
    }catch(e) {
        alert(e);
    }
}

function refreshTopic(index){
    $("title_link_"+index).update(_items[index].title);
    var tagsEl = $("tags_"+index).update("");
    var tags = _items[index].tags.split(",");
    for(var i=0; i<tags.length; i++) {
        var a = document.createElement("a");

        if(tags[i].strip() == "" || tags[i].strip() == "no_tag"){
            continue;
        }

        if(tags[i].indexOf(" ")!=-1) {
            a.href= "/group/" + _items[index].g_name +"/content/tag/"+encodeURIComponent("\""+tags[i]+"\"");
        }else {
            a.href="/group/" + _items[index].g_name +"/content/tag/"+encodeURIComponent(tags[i]);
        }
        a.innerHTML = tags[i];
        tagsEl.appendChild(a);
        if(i<tags.length-1) {
            tagsEl.innerHTML += ""
        }
    }
}

function deleteT(index, admin) {
    if(canDeleteT(index,admin) == false){
        alert(ALE_113);
        return false;
    }
    if(confirm(ALE_25)) {
        doDeleteT([_items[index]]);
        return false;
    }else {
        resetMoreAction();
        return false;
    }
}

function canDeleteT(index, admin){
    admin = admin ? admin : "false";
    if(admin == "true"){return true;}
    var comments = _items[index].posts;
    for(var i=0;i<comments.size();i++){
        if(comments[i] == null) continue;
        if(comments[i].user_id != _GLOBAL_VAR['current_user'].user_id){
            return false;
        }
    }
    return true;
}

function doDeleteT(TA) {
    var delete_item_infos = [];
    for(var i=0; i<TA.length; i++) {
        delete_item_infos.push({
            tid : TA[i].tid,
            user_id : TA[i].user_id
        });
    }
    var url = '/site/delete_topic';
    showCentralNoticer(WORD_105);
    new Ajax.Request(url,
    {
        method: "post",
        asynchronous:true,
        evalScripts:true,
        onSuccess:function(request){
            hideCentralNoticer();
            for(var i=0; i<TA.length; i++){
                var t = TA[i];
                delete(_items[t.index]);
                $("item_"+t.index).remove();
            }
            resetMoreAction();
            resetAllChecker();
            flashNotice(WORD_DONE, "noticeBar", DURATION_3);
        },
        parameters:{
            group_id:TA[0].group_id,
            delete_items:delete_item_infos.toJSON()
        }
    }
);
    return false;
}

function renderTDCount(item_index){
    var dCount = _items[item_index].post_count;
    if($("dCount_" + item_index) != null){$("dCount_" + item_index).update(dCount);}
}

function moderateT(item_index){
    if($("item_" + item_index) == null) return;

    $("item_" + item_index).select('[class="commentItem"]','[class="commentItem "]', '[class="commentItem hide"]').each(function(li){
        var index = li.id.split("t_")[1];
        var manage_span = $("manage_comment_" + index);
        if(manage_span != null){
            manage_span.removeClassName("hide");
        };
    });
}

/****************************************
 * Post Item form
 ****************************************/
function iniPostItemForm(){
    for(var index=0; index < _item_types.length;index++){
        var post_a = $("post_item_"+_item_types[index]);
        if(post_a == null) continue;
        post_a.observe('click',createPostItemForm.bindAsEventListener(post_a, _item_types[index]));
    }
}

function createPostItemForm(e){
    var args = $A(arguments);
    args.shift();
    var item_type = args;
    if($("post_item_"+item_type).innerHTML != ""){clearPostItemForm();}
    $("post_item_" + item_type).toggleClassName("current");

    var form = new Element("form", {"id" : "post_item_form", "method":"post", "class":"postForm"});
    var table = new Element("table");
    if(item_type == _item_types[0]){// bookmark item
        table_str = "<tr><th>URL:</th><td><input name=\"url\" class=\"inputTxt2\" id=\"bookmark_item_url\" autocomplete=\"off\"></td></tr>"
        table_str += "<tr><th>Title:</th><td><input type=\"text\" name=\"title\" class=\"inputTxt2\" id=\"bookmark_item_title\" autocomplete=\"off\"></td></tr>";
        table_str += "<tr id=\"\"><th style=\"vertical-align:top;\">Comment:</th><td><textarea name=\"comment\" class=\"inputTxt2\" id=\"bookmark_item_content\" onkeypress=\"resiseTextArea2(this,event)\" autocomplete=\"off\"></textarea></td></tr>";
        table_str += "<div style=\"position: absolute; visibility: hidden;\" id=\"bookmark_item_content_div\"></div></td></tr>";
        table_str += "<tr><th>Tags:</th><td><input type=\"text\" name=\"tags\" class=\"inputTxt2\" id=\"link_item_tags\" autocomplete=\"off\"></td></tr>";
        if(_group_tags.length > 0){ table_str += makeTagDict("link_item_tags")}
        table_str += "<tr><td></td><td><input type=\"submit\" class=\"firstIBtn\" value=\"Post\"><a href=\"javascript:void(0);\" onclick=\"clearPostItemForm();\">Cancel</a></td></tr>";
        table.update(table_str);

        form.action="/site/new_bookmark";
    }else{// topic item
        table_str = "<tr><th>Title:</th><td><input type=\"text\" name=\"title\" class=\"inputTxt2\" id=\"topic_item_title\" autocomplete=\"off\"></td></tr>";
        table_str += "<tr><th style=\"vertical-align:top;\">Comment:</th><td><textarea name=\"content\" class=\"inputTxt2\" id=\"topic_item_content\" onkeypress=\"resiseTextArea2(this,event)\" autocomplete=\"off\"></textarea>";
        table_str += "<div style=\"position: absolute; visibility: hidden;\" id=\"topic_item_content_div\"></div></td></tr>";
        table_str += "<tr><th>Tags:</th><td><input type=\"text\" name=\"tags\" class=\"inputTxt2\" id=\"topic_item_tags\" autocomplete=\"off\"></td></tr>";
        if(_group_tags.length > 0){ table_str += makeTagDict("topic_item_tags")}
        table_str += "<tr><td></td><td><input type=\"submit\" class=\"firstIBtn\" value=\"Post\"><a href=\"javascript:void(0);\" onclick=\"clearPostItemForm();\">Cancel</a></td></tr>";
        table.update(table_str);

        form.action="/site/new_topic";
    }

    form.onsubmit = postItem.bind(this,{"item_type":item_type});
    form.appendChild(table);
    $("post_item_area").appendChild(form);
    $("post_item_area").show();
    
    if(item_type == _item_types[0]){
        $("bookmark_item_url").focus();
    }else{
        $("topic_item_title").focus();
    }
}

function makeTagDict(input_id){
    var str = "";
    if(_group_tags.length > 0){
        str += "<tr><th>";
        if(_tag_dict_mode == '1'){// top 10 tags
            str += "Top 10:";
        }else{// recmmended tags
            str += "Recom'ded:";
        }
        str += "</th><td><ul class=\"recTags\">";
        for(var i=0; i< _group_tags.length; i++){
            str += "<li><a href=\"javascript:void(0);\" onclick=\"addTag(this,"+i+", '"+input_id+"')\">"+_group_tags[i]+"</a></li>";
        }
        str += "</ul><td></tr>";
    }
    return str;
}

function addTag(el,index,input_id){
  if(_group_tags[index] == null) return;
  var tag = _group_tags[index].replace('"',"&#34");
  var tagInput = $(input_id);
  var tagArray = ParseTags.parseTags(tagInput.value, true);
  if(tagArray.include(tag)) {
    tagArray = tagArray.without(tag);
    el.className = "off";
  }else {
    tagArray.push(tag);
    el.className = "on";
  }
  tagInput.value = ParseTags.unparseTags(tagArray)+" ";
}

function hidePostItemForm(){
    $("post_item_area").hide();
}

function clearPostItemForm(){
    for(var index=0; index < _item_types.length;index++){
        $("post_item_" + _item_types[index]).removeClassName("current");
    }
    $("post_item_area").update("").hide();
}

function postItem(args){
    try{
        var item_type = args.item_type;
        var url = "";
        if(item_type == _item_types[0]){// bookmark item
            url = "/site/new_bookmark_item";
            if($("bookmark_item_url").value.trim() == ""){$("bookmark_item_url").focus();return false;}
            if($("bookmark_item_title").value.trim() == ""){$("bookmark_item_title").focus();return false;}
        }else{//topic item
            url = "/site/new_topic_item";
            if($("topic_item_title").value.trim() == ""){$("topic_item_title").focus();return false;}
            if($("topic_item_content").value.trim() == ""){$("topic_item_content").focus();return false;}
        }
        var params = $("post_item_form").serialize() + "&group_id=" + _GLOBAL_VAR["group_id"] + "&items_size=" + _items.length;
        _postItemLoading();
        var invoke_url_param = getURLParam("view");
        var item_display_mode = loadCusData()['item_display_mode'];
        new Ajax.Request(url,
        {
            method:"post",
            asynchronous:true,
            evalScripts:true,
            onSuccess:function(request){
                try{
                    var respInfos = request.responseText.evalJSON();
                    if(invoke_url_param != "popular" && item_display_mode != "advanced"){
                        newGroupItem(respInfos);
                        new ContextMenu("leftColumn",{eventType:"click",backgroundColor:'#E0EDFE',color:'#000'});
                        new AvatarPopup();
                    }else{
                        var item_url = respInfos.item_url
                        var word = GROUP_WORD_3.replace("?", item_url);
                        flashNotice(word, "noticeBar", DURATION_3);
                    }
                     var alertTip = $("alert_tip");
                     if(alertTip != null) alertTip.remove();
                     clearPostItemForm();
                }catch(e){
                    alert(e);
                }
                
            },
            parameters:params
        }
    );
        return false;
    }catch(e){
        alert(e);
        return false;
    }
}

function _postItemLoading(){
    $("post_item_form").disable();
}

function newGroupItem(resp){
    //1. javascript model
    _items.push(resp.obj);

    //2. page element
    $("content_header").insert({"after": resp.html_str});
}

/*=====================================
 * batch actions: init checker, delete
 *=====================================*/
function initChecker(){
    if(_items.length == 0) return

    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 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--;
}
switchBatchAction();
}

function switchBatchAction() {
if(_checkedItemCount==0 && _batchActionEnabled) {
    var batchActions = getBatchActions();
    for(var i=0; i<batchActions.length; i++) {
        batchActions[i].disabled = true;
        batchActions[i].className = "disabled";
    }
    _batchActionEnabled = false;
    return true;
}

if(_checkedItemCount>0 && !_batchActionEnabled) {
    var batchActions = getBatchActions();
    for(var i=0; i<batchActions.length; i++) {
        batchActions[i].disabled = false;
        batchActions[i].className = "";
    }
    _batchActionEnabled = true;
    return true;
}
}

function getBatchActions() {
var batchActions = [];
var range = document;
var options = range.getElementsByTagName("option");
for(var j=0; j<options.length; j++) {
    var name = options[j].getAttribute("name");
    if(name=="batchAction") {
        batchActions.push(options[j]);
    }
}
return batchActions;
}

function isAllSelected() {
if(_checkedItemCount == _items.compact().length) return true;
else return false;
}

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 initMoreAction() {
    var i=0;
    while($("moreAction_"+i)) {
        var action = $("moreAction_"+i);
        action.disabled = false;
        action.value = "-1";
        action.onchange = doAction;
        i++;
    }
    switchBatchAction();
}

function doAction() {
var cmd = this.value;
switch(cmd) {
    case 'delete':{batchDeleteItems();}break;
    case 'send_to':{batchSendTo();}break;
    case 'edit_items_tags':{batchEditItemsTags();}break;
    case 'generate_report':{batchGenerateReport();}break;
}
}

/**** batch actions: delete items   ****/
function batchDeleteItems() {
    if(confirm(ALE_115)) {
        doDeleteItems(whichItemChecked());
        return true;
    }else {
        resetMoreAction();
        resetAllChecker();
        return false;
    }
}

function doDeleteItems(items){
    if(items.bookmark_items.length != 0) doDeleteB(items.bookmark_items);
    if(items.topic_items.length != 0) doDeleteT(items.topic_items);
}

function canDelete(index, admin){
    admin = admin ? admin : "false";
    if(admin == "true"){
        return true;
    }
    var comments = _items[index].page_comments;
    for(var i=0;i<comments.size();i++){
        if(comments[i] == null) continue;
        if(comments[i].user_id != _GLOBAL_VAR['current_user'].user_id){
            return false;
        }
    }

    var annotations = _items[index].annotations;
    for(var j=0;j<annotations.size();j++){
        if(annotations[j] == null) continue;
        if(annotations[j].user_id != _GLOBAL_VAR['current_user'].user_id){
            return false;
        }

        var stickyNotes = annotations[j].inline_comments;
        for(var k=0;k<stickyNotes.size();k++){
            if(stickyNotes[k] == null) continue;
            if(stickyNotes[k].user_id != _GLOBAL_VAR['current_user'].user_id){
                return false;
            }
        }
    }
    return true;
}

function deleteB(index,admin) {
    if(canDelete(index,admin) == false){
        alert(ALE_113);
        return false;
    }
    if(confirm(ALE_25)) {
        doDeleteB([_items[index]]);
        return true;
    }else {
        resetMoreAction();
        return false;
    }
}

function doDeleteB(bA) {
    var delete_bm_infos = [];
    for(var i=0; i<bA.length; i++) {
        delete_bm_infos.push({
            link_id:bA[i].link_id,
            user_id:bA[i].last_user_id
        });
    }
    var url = '/site/delete_bookmark';
    showCentralNoticer(WORD_105);
    new Ajax.Request(url,
    {
        method: "post",
        asynchronous:true,
        evalScripts:true,
        onSuccess:function(request){
            hideCentralNoticer();
            for(var i=0; i<bA.length; i++){
                var b = bA[i];
                delete(_items[b.index]);
                $("item_" + b.index).remove();
            }
            resetMoreAction();
            resetAllChecker();
            flashNotice(WORD_DONE, "noticeBar", DURATION_3);
        },
        parameters:{
            group_id:bA[0].group_id,
            delete_bms:delete_bm_infos.toJSON()
        }
    }
);
    return false;
}

/**** batch actions: delete items   ****/
function batchSendTo(){
    var index_a = checkedItemIndexA().bookmark_item_indexs;
    forwardItem({'type':'bookmark', 'index_a':index_a});
}

/**** batch actions: extract annotions   ****/
function batchGenerateReport() {
    var checkedItems = whichItemChecked().all_items;
    if(checkedItems.length==0) {
        flashNotice2(GROUP_ALE_8);
        resetMoreAction();
        return false;
    }
    var group_id = checkedItems[0].group_id;
    item_ids = [];
    for(var i=0; i<checkedItems.length; i++) {
        item_ids.push(checkedItems[i].item_id);
    }
    window.open('/site/generate_report?item_ids='+item_ids.join(',')+'&group_id='+group_id, 'Generate report', 'scrollbars=no,menubar=no,width=640,height=420,resizable=no,toolbar=no,location=no,status=no,screenX=200,screenY=100,left=200,top=100');
    resetMoreAction();
    return true;
}

//function batchExtract() {
//    var checkedItems = whichItemChecked().bookmark_items;
//    if(checkedItems.length==0) {
//        alert("No item(s) selected");
//        resetMoreAction();
//        return false;
//    }
//    var index_a = [];
//    for(var i=0; i<checkedItems.length; i++) {
//        index_a.push(checkedItems[i].index);
//    }
//    extraA(index_a);
//    return true;
//}
//
//function extraA(i) {
//    var index_a = [];
//    var root = "leftColumn";
//    if(typeof(i)=="number"){index_a.push(i);root = "bookmarkItem_"+i;
//    }else{index_a = i;root = "bookmarkItem_" + i[0]}
//    var pw = new PopWindow({optEnabled: true, left:120, top:20, width:500, title:"Extract Annotations", root:root});
//    pw.appendNode(loadAnnotations(index_a));
//    pw.cancel = function(){resetMoreAction();resetAllChecker();}
//    pw.submitBtn.value = "Copy";
//    pw.cancelBtn.value = "Close";
//    pw.submit = function(){
//        _copy("<dl>"+$("extraAContent").innerHTML+"</dl>");
//        pw.submitBtn.value = "Copied";
//    }
//}

/**** batch actions: edit items tags   ****/
function batchEditItemsTags() {
    var checkedItems = whichItemChecked().all_items;
    if(checkedItems.length==0) {
        flashNotice(GROUP_ALE_8, "noticeBar", DURATION_3);
        resetMoreAction();
        return false;
    }

    var pw = new PopWindow({
        optEnabled: true,
        left:150,
        top:100,
        title:"Revise tags",
        root:"leftColumn"
    });
    pw.show();
    pw.appendNode(loadTagEditor());
    pw.submit = doTagsEdit.bind(pw, $("tagEditForm"));
    pw.cancel = function(){resetMoreAction();resetAllChecker();}
    $("editTags").clear().focus();
    $("tagEditOption_2").checked = true;
    return true;
}

function loadTagEditor() {
    if(_GLOBAL_VAR['tagEditor']) {
        return _GLOBAL_VAR['tagEditor'];
    }else {
        var editor = new Element("form", {
            id:"tagEditForm",
            method:"post",
            "onsubmit":"return false;"
        });
        row = new Element("div", {
            className:"teItem"
        });
        row.appendChild(new Element("input", {
            type:"text",
            name:"editTags",
            maxlength:255,
            id:"editTags",
            className:"inputTxt"
        }));
        editor.appendChild(row);
        row = new Element("div", {
            className:"teItem"
        });
        row.appendChild(new Element("label", {
            "for":"tagEditOption_2"
        }).update("<p style='margin-top:5px;'><input type='radio' value='1' id='tagEditOption_2' name='editTagOption' />Add additional tags to selected items</p>"));
        row.appendChild(new Element("label", {
            "for":"tagEditOption_1"
        }).update("<p style='margin-top:5px;'><input type='radio' value='0' id='tagEditOption_1' name='editTagOption' />Replace all tags on selected items by</p>"));
        editor.appendChild(row);
        _GLOBAL_VAR['tagEditor'] = editor;
        return _GLOBAL_VAR['tagEditor'];
    }
}

function doTagsEdit() {
    var pw = this;
    var form = arguments[0];
    var tags = $F("editTags").trim();
    if(tags=="") return false;
    var checkedItems = whichItemChecked().all_items;
    if(checkedItems.length==0) return false;
    var item_ids = [];
    for(var i=0; i<checkedItems.length; i++) {
        item_ids.push(checkedItems[i].item_id);
    }
    var url = "/site/edit_items_tags";
    pw.onLoading();
    new Ajax.Request(url,
    {
        asynchronous:true,
        evalScripts:false,
        onComplete:function(request){
            doTagsEditComplete(request, checkedItems, pw)
        },
        parameters : Form.serialize(form) + "&item_ids=" + item_ids.join(",") + "&group_id=" + checkedItems[0].group_id
    }
    );
    return false;
}
function doTagsEditComplete(request, checkedItems, pw) {
    pw.onComplete({
        status:request.status
    });
    resetMoreAction();
    resetAllChecker();
    if(request.status=="200"){
        var tags = request.responseText.evalJSON();
        var optionA = document.getElementsByName("editTagOption");
        var option;
        for(var i=0; i<optionA.length; i++) {
            if(optionA[i].checked) option = optionA[i].value;
        }
        for(var j=0; j<checkedItems.length; j++) {
            var index = checkedItems[j].index;
            if(option=="0" || checkedItems[j].t_name=="no_tag") {
                checkedItems[j].tags = tags.uniq().join(",");
            } else if(option=="1") {
                t = (checkedItems[j].tags.split(",").concat(tags)).uniq();
                checkedItems[j].tags = t.join(",");
            }
            if(_items[j].obj_type == _item_type_h.bookmark){refreshBookmark(index);}
            else if(_items[j].obj_type == _item_type_h.topic){refreshTopic(index);}
        }
    }
}


/**** batch actions: share to groups   ****/
function doShareToGroupAction() {
    var cmd = this.value;
    switch(cmd) {
        case '-1':{
            }break;
        default:{
            doShareToGroup(cmd);
        }
    }
}

function doShareToGroup(cmd) {
    lockShareToGroup();
    var checkedBA = whichItemChecked().bookmark_items;
    var have_topics = whichItemChecked().topic_items.size() > 0;
    var link_ids = "";
    for(var i=0; i<checkedBA.length; i++) {
        if(i==0){
            link_ids += checkedBA[i].link_id;
        }else{
            link_ids += ","+checkedBA[i].link_id;
        }
    }
    if(link_ids.blank()){
        flashNotice(GROUP_ALE_4, "noticeBar", DURATION_3);
        resetAllChecker();
        resetShareToGroup();
        return false;
    }
    var g_name = cmd;
    var url ="/site/share_link_items_to_group";
    showCentralNoticer(DIS_10);
    new Ajax.Request(url,
    {
        asynchronous:true,
        evalScripts:false,
        onComplete:function(request){
            doShareToGroupComplete(request, g_name, have_topics);
        },
        parameters:{
            link_ids : link_ids,
            from_group_name : _GLOBAL_VAR['group_name'],
            to_group_name: g_name
        }
    }
    );
}

function doShareToGroupComplete(request, g_name, have_topics) {
    if(request.status=="200") {
        var notice_content = ALE_37.replace("?", "<a href='"+GROUP_HOST+"/group/"+g_name+"' style='text-decoration:underline;'>"+g_name+"</a>");
        if(have_topics){
            notice_content += GROUP_ALE_1;
        }
        flashNotice(notice_content, "noticeBar", DURATION_3);
    }else if(request.status=="400") {
    }else {
        flashNotice(EXC_1, "noticeBar", DURATION_3);
        //alert(EXC_1);
    }
    resetAllChecker();
    hideCentralNoticer();
    resetShareToGroup();
}

function resetShareToGroup() {
    for(var i=0; i<_shareToGroupSelectCount; i++) {
        var action = $("share_to_groups_"+i);
        action.value = "-1";
        action.disabled = false;
        action.blur();
    }
}

function lockShareToGroup() {
    for(var i=0; i<_shareToGroupSelectCount; i++) {
        var action = $("share_to_groups_"+i);
        action.disabled = true;
    }
}

function whichItemChecked(){
    var checkedBA = [];
    var checkedTA = [];
    var checkedItems = [];
    for(var i=0; i<_items.length; i++) {
        if(!_items[i]) continue;
        if(_items[i].checked){
            checkedItems.push(_items[i]);
            if(_items[i].obj_type == _item_type_h.bookmark){checkedBA.push(_items[i]);}
            else if(_items[i].obj_type == _item_type_h.topic){checkedTA.push(_items[i]);}
        }
    }
    return {"bookmark_items":checkedBA, "topic_items":checkedTA, "all_items":checkedItems};
}

function checkedItemIndexA(){
    var b_index_a = [];
    var t_index_a = [];
    for(var i=0; i<_items.length; i++) {
        if(_items[i] != null && _items[i].checked){
           if(_items[i].obj_type == _item_type_h.bookmark){b_index_a.push(i);}
            else if(_items[i].obj_type == _item_type_h.topic){t_index_a.push(i);}
        }
    }
    return {"bookmark_item_indexs":b_index_a, "topic_item_index":t_index_a};
}

function resetMoreAction() {
    for(var i=0; i<_moreActionSelectCount; i++) {
        var action = $("moreAction_"+i);
        if(action == null) continue;
        action.value = "-1";
        action.disabled = false;
    }
}

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();
    if(_checkedItemCount==0) {
        resetMoreAction();
    }
}

/****************************************
 * Common Method
 ****************************************/

function hoverAnnItem(){
    var args = $A(arguments);
    args.shift();
    var ann = document.getElementById(args);
    ann.className += " hover";
    ann.setStyle({"position":"relative"});
}

function outAnnItem(){
    var args = $A(arguments);
    args.shift();
    var ann = document.getElementById(args);
    ann.className = ann.className.replace(/\shover/g, "");
    ann.setStyle({"position":""});
}

function toggleGroupDesc(el){
    if($("hide_group_desc").hasClassName("hide")){
        $("hide_group_desc").removeClassName("hide");
        el.innerHTML = "hide";
    }else{
        $("hide_group_desc").addClassName("hide");
        el.innerHTML = "more&raquo;";
    }
}

function click_show_more(index,type){
    type = type ? type : "comment";
    if(type == "comment"){
        $("comment_"+index).select("li").each(function (i){i.removeClassName("hide")});
        $("hide_comment_"+index).remove();
    }else if(type == "ann"){
        $("ann_"+index).select("li").each(function (i){i.removeClassName("hide")});
        $("hide_ann_"+index).remove();
    }
}

function likeIt(item_index,type){
    //$("details_" + item_index).removeClassName("hide");
    _likeItemLoading(item_index);
    try{
        var url = '/site/like_item';
        new Ajax.Request(url,
        {
            method:"post",
            asynchronous:true,
            evalScripts:true,
            onSuccess:function(request){
                var respInfos = request.responseText.evalJSON();
                $("like_span_" + item_index).hide();
                $("like_details_" + item_index).update(respInfos.sentence).show();
                if(type == "2"){ //pupular tab
                    $("like_info_" + item_index).setStyle({
                        paddingBottom:"0px"
                    });
                    $("vote_count_" + item_index).update(respInfos.vote_count);
                }
                enableEmailAlertOnPage(item_index);
            },
            parameters:{
                item_index: item_index,
                item_id: _items[item_index].item_id,
                group_id: _items[item_index].group_id
            }
        }
    );
    return false;
    }catch(e) {
        alert(e);
        return false;
    }
}

function _likeItemLoading(item_index){
    $("like_" + item_index).update("......").addClassName("likeLoading");
}

function _undoLikeItemLoading(item_index){
    $("undo_like_" + item_index).update("......").addClassName("likeLoading");
}

function undoLikeItem(item_index){
    _undoLikeItemLoading(item_index);
    try{
        var url = '/site/undo_like_item';
        new Ajax.Request(url,
        {
            method:"post",
            asynchronous:true,
            evalScripts:true,
            onSuccess:function(request){
                var respInfos = request.responseText.evalJSON();
                $("undo_like_" + item_index).remove();
                if($("like_" + item_index) != null) $("like_" + item_index).update("like").removeClassName("likeLoading");
                if($("like_span_" + item_index) != null) $("like_span_" + item_index).show();
                if(!respInfos.sentence.blank()){
                    $("like_details_" + item_index).update(respInfos.sentence).show();
                }else{
                    $("like_details_" + item_index).hide();
                }
//                if(type == "2"){ //pupular tab
//                    $("like_info_" + item_index).setStyle({
//                        paddingBottom:"0px"
//                    });
//                    $("vote_count_" + item_index).update(respInfos.vote_count);
//                }
            },
            parameters:{
                item_index: item_index,
                item_id: _items[item_index].item_id,
                group_id: _items[item_index].group_id
            }
        }
    );
    return false;
    }catch(e) {
        alert(e);
        return false;
    }
}

function resiseTextArea(el,e,comment_id){
    var prefix = "";
    if(el.id.split("_")[0] == "edit") prefix += "edit_";
    
    var textArea = $(prefix + "comment_content_"+comment_id);
    var div_hidden = $(prefix + "comment_div_"+comment_id);
    
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if(e) keycode = e.which;

    div_hidden.update(displayContent(textArea.value.escapeHTML()));
    var current_div_height = div_hidden.getHeight();
    var current_txt_height = textArea.getHeight();
    if(keycode == Event.KEY_RETURN && current_div_height > 50 && current_div_height < 150 && current_txt_height < 180){
        textArea.setStyle({height : "180px"});
    }
}

function resiseTextArea2(el,e){
    var textArea = $(el.id);
    var div_hidden = $(el.id + "_div");

    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if(e) keycode = e.which;

    div_hidden.update(displayContent(textArea.value.escapeHTML()));
    var current_div_height = div_hidden.getHeight();
    var current_txt_height = textArea.getHeight();
    if(keycode == Event.KEY_RETURN && current_div_height > 50 && current_div_height < 150 && current_txt_height < 180){
        textArea.setStyle({height : "180px"});
    }
}

function _escape_content(content){
    return content.replace(/\r\n|\n|\r/g,"<br/>").replace(/<script/i, "&lt;script").replace(/<\/script/i, "&lt;/script");
}

function getURLParam(strParamName){
    var strReturn = "";
    var strHref = window.location.href;
    if( strHref.indexOf("?") > -1 ){
        var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
        var aQueryString = strQueryString.split("&");
        for(var iParam = 0; iParam < aQueryString.length; iParam++ ){
            if(aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 ){
                var aParam = aQueryString[iParam].split("=");
                strReturn = aParam[1];
                break;
            }
        }
    }
    return unescape(strReturn);
}

function addVisitRecord(item_id){
    var url = '/site/add_item_visit_record';
    new Ajax.Request(url,
    {
        method:"post",
        asynchronous:true,
        evalScripts:true,
        parameters:{
            item_id:item_id
        }
    }
    );
    return false;
}

function displayContent(content){
    content = content.replace(/\r*\n/gi, '<br/>');
    content = content.replace(/&lt;/gi, '<');
    content = content.replace(/&gt;/gi, ' >');
    return content;
}

function displayInputContent(content){
    content = content.replace(/<br>/gi, '\n');
    return content;
}

function processComment(content){
    content = "<div class=\"cArrow\">&nbsp;</div><div class=\"cContentInner\">" + content + "</div>";
    return content
}

function Validator(){
    this.isEmail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
    this.isEmail2 = /^.+<\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*>$/;
    this.isTags = /^[^%&]+$/;
    this.isTag = /^[^%&\s]*$/;
    this.isUsername = /^[a-zA-Z]([0-9a-zA-Z\-_]{5,15})$/;
    this.isUrl = /^https?:\/\/.+$/;
    this.IsEmail = function (email) { re = this.isEmail; return (re.test(email)); };
    this.IsEmail2 = function (email) { re = this.isEmail2; return (re.test(email)); };
    this.IsTags = function (tags) { re = this.isTags; return (re.test(tags)); };
    this.IsTag = function (tag) { re = this.isTag; return (re.test(tag)); };
    this.IsUsername = function (username) { re = this.isUsername; return (re.test(username)) }; this.IsPwd = function (pwd) { if(pwd.length>=6 && pwd.length<=32) { return true; }else { return false; } };
    this.IsRealname = function(realname){if(realname.length>=1 && realname.length<=64){return true; }else{ return false; } }
    this.IsTitle = function(title){if(title.length<=255){return true; }else { return false; } }
    this.IsSignature = function(signature) {if(signature.length<=255){ return true; }else { return false; } }
    this.IsUrl = function(url) {re = this.isUrl; return (re.test(url)) }
}

function changeListCount(count) {
    var cusData = loadCusData();
    cusData['count'] = count;
    cusData.store();
    self.location.reload();
}

function changeDisplayMode(mode){
    var cusData = loadCusData();
    cusData['item_display_mode'] = mode;
    cusData.store();
}

function loadCusData() {
    var domain = getCookieDomain();
    var cusData = new Cookie(document, "g_cus_data", 240, '/', domain);
    cusData.load();
    return cusData;
}

function toTop(id_of_element){
    Effect.ScrollTo(id_of_element);
}

/****************************************
 * Expand / Collapse Items Method
 ****************************************/
function expandOrCollapse(index){
    $("details_"+index).toggleClassName("hide");
}

/****************************************
 * enable/disable email alert
 ****************************************/
function enableEmailAlert(index){
    showCentralNoticer(DIS_10);
    try{
        var url = '/site/enable_item_email_alert';
        new Ajax.Request(url,
        {
            method:"post",
            asynchronous:true,
            evalScripts:true,
            onSuccess:function(request){
                hideCentralNoticer();
                flashNotice(GROUP_ALE_2, "noticeBar", DURATION_3);
                enableEmailAlertOnPage(index);
            },
            parameters:{
                item_id: _items[index].item_id
            }
        }
    );
    return false;
    }catch(e) {
        alert(e);
        return false;
    }
}
function disableEmailAlert(index){
    showCentralNoticer(DIS_10);
    try{
        var url = '/site/disable_item_email_alert';
        new Ajax.Request(url,
        {
            method:"post",
            asynchronous:true,
            evalScripts:true,
            onSuccess:function(request){
                hideCentralNoticer();
                flashNotice(GROUP_ALE_3, "noticeBar", DURATION_3);
                disableEmailAlertOnPage(index);
            },
            parameters:{
                item_id: _items[index].item_id
            }
        }
    );
    return false;
    }catch(e) {
        alert(e);
        return false;
    }
}

function enableEmailAlertOnPage(index){
    if($("email_alert_" + index)){
        $("email_alert_" + index).update(GROUP_ALE_6).onclick = function(){disableEmailAlert(index)};
    }
}

function disableEmailAlertOnPage(index){
    if($("email_alert_" + index)){
        $("email_alert_" + index).update(GROUP_ALE_5).onclick = function(){enableEmailAlert(index)};
    }
}