// JavaScript Document
var _bookmarks = [];
var _checkedItemCount = 0; 
function Bookmark() {
    this.index = null;
    this.group_id = null;
    this.link_id = null;
    this.g_l_id = null;
    this.url = null;
    this.title = null;
    this.desc = null;
    this.tags = null;
    this.first_user_id = null;
    this.first_user_name = null;
    this.first_user_real_name = null;
    this.last_user_id = null;
    this.last_user_name = null;
    this.last_user_real_name = null;
    this.user_count = 0
    this.checked = false;
    this.comments = [];
    this.p_c_count = 0;
    this.ann_count = 0;
    this.i_c_count = 0;
    this.annotations = [];
    this.details_count = function() {
        return (this.p_c_count + this.ann_count + this.i_c_count);
    }
}
function Comment() {
    this.id = null;
    this.group_id = null;
    this.link_id = null;
    this.g_l_id = null;
    this.user_id = null;
    this.user_name = null;
    this.user_real_name = null;
    this.index = null;
}                  
function Annotation() {
    this.id = null;
    this.group_id = null;
    this.link_id = null;
    this.g_l_id = null;
    this.user_id = null;
    this.user_name = null;
    this.user_real_name = null;
    this.i_c_count = 0;
    this.stickyNotes = [];
    this.index = null;
}
function StickyNote() {
    this.id = null;
    this.group_id = null;
    this.link_id = null;
    this.g_l_id = null;
    this.user_id = null;
    this.user_name = null;
    this.user_real_name = null;
    this.ann_id = null;
    this.index = null;
}

/*
var Comment = {"id"           :   null,
"mode"         :   null,
"u_name"       :   null};

var Annotation = {"h_id"         : null,
"mode"         : null,
"u_name"       : null,
"stickyNotes"  : [],
"s_count"      : 0}

var StickyNote = {"id"       :   null,
"u_name"   :   null,
"mode"     :   null};
 */
function initcolorListItem() {
    if(_GLOBAL_VAR['expand']) {
        colorListItem(1);
    }else {
        colorListItem(0);
    }
}
function colorListItem(type) {
    // alternate
    if(type==0) {
        var j=0
        for(i=0; i<_bookmarks.length; i++) {
            var bItem = $("bookmarkItem_"+i);
            if(bItem) {
                if(j%2==0) {
                    bItem.className += " Dark";
                }else {
                    bItem.className = bItem.className.replace("Dark", "");
                }
                j++;
            }
        }
    }else {
        var j=0
        for(i=0; i<_bookmarks.length; i++) {
            var bItem = $("bookmarkItem_"+i);
            if(bItem) {
                bItem.className += " Dark";
            }
        }
    }
}
// expand/collapse 
// comment, annotations
function switchDetails(index, eoc) {
    var el = $("bookmarkDetails_"+index);
    var eocItem = $("eoc_"+index);
    if(typeof(eoc)=="undefined") eoc = null;
    if(eoc) {
        if(eoc=="collapse") {
            el.style.display = "none";
            eocItem.innerHTML = eocItem.innerHTML.replace(DIS_6, DIS_7);
            _bookmarks[index].expand = false;
            switchCEditor(index, "collapse");
        }else {
            el.style.display = "";
            eocItem.innerHTML = eocItem.innerHTML.replace(DIS_7, DIS_6);
            _bookmarks[index].expand = true;
        }
    }else {
        if(el.style.display=="") {
            el.style.display = "none";
            eocItem.innerHTML = eocItem.innerHTML.replace(DIS_6, DIS_7);
            _bookmarks[index].expand = false;
            switchCEditor(index, "collapse");
    
        }else {
            el.style.display = "";
            eocItem.innerHTML = eocItem.innerHTML.replace(DIS_7, DIS_6);
            _bookmarks[index].expand = true;
        }
    }
    checkEOCStatus();
}

function expandOrCollapse() {
    switchDetails(this.index);
}

// expand/collapse
// sticky notes
function switchSticky(index) {
    var el = $("sticky_"+index);
    if(el.style.display=="") {
        el.style.display = "none";
    }else {
        el.style.display = "";
    }
}
function checkItem() {     
    var index = this.id.split("_")[1];
    var checker = $("bookmarkChecker_"+index);
    var allChecker = $("bookmarkCheckerAll");
    if(checker.checked) {
        //$("bookmarkItem_"+index).style.backgroundColor = "#f5f5f5";
        _bookmarks[index].checked = true;
        _checkedItemCount++;
        if(isAllSelected()) allChecker.checked = true;
    }else {
        //$("bookmarkItem_"+index).style.backgroundColor = "#fff";
        allChecker.checked = false;
        _bookmarks[index].checked = false;
        _checkedItemCount--;
    }
    switchBatchAction();
}
function isAllSelected() {
    if(_checkedItemCount==_bookmarks.length)
        return true;
    else
        return false;
}
function checkItems() {
    var allChecker = this;
    var index = 0;
    for(var i=0; i<_bookmarks.length; i++) {
        var checker = $("bookmarkChecker_"+i);
        if(!checker) continue;
        if(checker.checked!=allChecker.checked) checker.click();
    }
}


/* init function */
function initChecker() {
    for(var i=0; i<_bookmarks.length; i++) {
        var checker = $("bookmarkChecker_"+i);
        checker.checked = false;
        checker.disabled = false;
        checker.onclick = checkItem;
    }
    var allChecker = $("bookmarkCheckerAll");
    allChecker.checked = false;
    allChecker.disabled = false;
    allChecker.onclick = checkItems;
}
/* init function */

/* reset checker */
function resetChecker(index) {
    var checker = $("bookmarkChecker_"+index);
    if(checker.checked) checker.click();
    if(_checkedItemCount==0) {
        resetMoreAction();
    }
}

function hideAllChecker() {
    for(var i=0; i<_bookmarks.length; i++) {
        var checker = $("bookmarkChecker_"+i);
        if(checker) checker.style.display = "none";
    }
    $("bookmarkCheckerAll").style.display = "none";
}
function showAllChecker() {
    for(var i=0; i<_bookmarks.length; i++) {
        var checker = $("bookmarkChecker_"+i);
        if(checker) checker.style.display = "";
    }
    $("bookmarkCheckerAll").style.display = ""
}

function comment(index) {
    switchCEditor(index);
}
function cancelCEditor() {
    switchCEditor(this.index);
}
function switchCEditor(index, eoc) {
    if(typeof(eoc)=="undefined") eoc=null;
    var cEditor = $("cEditor_"+index);
    if($("cEditor_"+index).innerHTML == "") {
        $("cEditor_"+index).appendChild(createCEditor(index));
        initCEditorMode(index, DEFAULT_C_MODE);
    }
    if(eoc) {
        if(eoc=="collapse") {
            cEditor.style.display = "none";
        }else {
            cEditor.style.display = "";
            initCEditor(index);
            switchDetails(index, "expand");
        }
    }else {
        if(cEditor.style.display=="") {
            cEditor.style.display = "none";
        }else {
            cEditor.style.display = "";
            initCEditor(index);
            switchDetails(index, "expand");
        }
    }
}

function createCEditor(index) {
    var form = document.createElement("form");
    form.id = "cEditForm_"+index;
    form.method = "post";
    form.onsubmit = postComment;
    var noticer = document.createElement("div");
    noticer.id = "cEditorNoticer_"+index;
    noticer.className = "cEditTop";
    noticer.style.display = "none";
    form.appendChild(noticer);
    var txtA = document.createElement("textarea");
    txtA.className = "inputTxt";
    txtA.name = "comment_content";
    txtA.id ="cContent_"+index;
    form.appendChild(txtA);
    var bottom = document.createElement("div");
    bottom.className = "cEditorBottom";
    bottom.id = "cEditorBottom_"+index;
    var cancelBtn = document.createElement("input");
    cancelBtn.type = "button";
    cancelBtn.value = "Cancel";
    cancelBtn.className = "cancelBtn";
    cancelBtn.index = index;
    cancelBtn.onclick = cancelCEditor;
    bottom.appendChild(cancelBtn);
    var submitBtn = document.createElement("input");
    submitBtn.type = "submit";
    submitBtn.value = "Post";
    submitBtn.className = "postBtn"
    bottom.appendChild(submitBtn);
    /*
    var selectItem = document.createElement("select");    
    selectItem.id = "cModeSelector_"+index;
    selectItem.onchange = changeCMode;
    selectItem.index = index;
    selectItem.name = "cMode";
    selectItem.className = "cModeSelector";
    var option = document.createElement("option");
    option.value = "0";
    option.innerHTML = "Public";
    selectItem.appendChild(option);
    option = document.createElement("option");
    option.value = "2";
    option.innerHTML = "* Private";
    selectItem.appendChild(option);
    bottom.appendChild(selectItem);
     */
    
    form.appendChild(bottom);
    return form
}   
function initCEditorMode(index, mode) {
    /*if(mode=="0") {
    $("cModeSelector_"+index).value = "0";
    showNoticer($("cEditorNoticer_"+index), WORD_8);
    }else {   
    $("cModeSelector_"+index).value = "2";
    hideNoticer($("cEditorNoticer_"+index));
    }*/
    showNoticer($("cEditorNoticer_"+index), WORD_104);
}                  

function changeCMode() {       
    doCMode(this.index, $F("cModeSelector_"+this.index));
}                                      
function doCMode(index, mode) {
    if(mode=="0") {
        showNoticer($("cEditorNoticer_"+index), WORD_8);
    }else {
        hideNoticer($("cEditorNoticer_"+index));
    }
}

function showNoticer(noticer, word) {
    noticer.style.display = "";
    noticer.innerHTML = word;
}  
function hideNoticer(noticer) {                 
    noticer.style.display = "none";
}                                             

function postComment() {       
    try{
        var index = this.id.split("_")[1];
        var cContent = $("cContent_"+index);
        if(cContent.value.trim()=="") {
            cContent.focus();
            showNoticer($("cEditorNoticer_"+index), WORD_9);
            return false;
        }
        var url = '/site/add_page_comment';
        var params = Form.serialize(this) + "&g_l_id=" +_bookmarks[index].g_l_id
        new Ajax.Request(url,
        {
            asynchronous:true,
            evalScripts:true,
            onLoading:function(request){
                postCommentLoading(request, index)
            },
            onComplete:function(request){
                postCommentComplete(request, index, cContent.value)
            },
            parameters:params
        }
        );
        return false;
    }catch(e) {
        alert(e);
        return false;
    }
} 
function postCommentLoading(request, index) {  
    showNoticer($("cEditorNoticer_"+index), WORD_3);
    switchCEditorToPosting(index);
}
function switchCEditorToPosting(index) {     
    $("cContent_"+index).disabled = true;
    $("cEditorBottom_"+index).style.display = "none";
}    
function switchCEditorToEdit(index) {     
    $("cContent_"+index).disabled = false;
    $("cEditorBottom_"+index).style.display = "";
    doCMode(index, $F("cModeSelector_"+index));
}

function postStickyNote() {       
    try{
        var index = this.id;
        var index = index.substring(index.indexOf("_")+1, index.length);
        var indexA = index.split("_");
        var sContent = $("sContent_"+index);
        if(sContent.value.trim()=="") {
            sContent.focus();
            showNoticer($("sEditorNoticer_"+index), WORD_9);
            return false;
        }
        var url = '/site/add_sticky_note';
        var parms = Form.serialize(this) + "&g_l_id=" + _bookmarks[indexA[0]].g_l_id + "&ann_id=" + _bookmarks[indexA[0]].annotations[indexA[1]].id;
        new Ajax.Request(url,
        {
            asynchronous:true,
            evalScripts:true,
            onLoading:function(request){
                postStickyNoteLoading(request, index)
            },
            onComplete:function(request){
                postStickyNoteComplete(request, index, sContent.value)
            },
            parameters:parms
        }
        );
        return false;
    }catch(e) {
        alert(e);
        return false;
    }
} 
function postStickyNoteLoading(request, index) {  
    showNoticer($("sEditorNoticer_"+index), WORD_3);
    switchSEditorToPosting(index);
}
function switchSEditorToPosting(index) {     
    $("sContent_"+index).disabled = true;
    $("sEditorBottom_"+index).style.display = "none";
}    
function switchSEditorToEdit(index) {     
    $("sContent_"+index).disabled = false;
    $("sEditorBottom_"+index).style.display = "";
    doSMode(index, $F("sModeSelector_"+index));
} 

function postStickyNoteComplete(request, index, content) {
    if(request.status == "200") {
        var respInfos = eval("("+request.responseText+")");
        respInfos.content = displayCContent(content);
        indexA = index.split("_");
        // create new comment
        // depend on your view
        var newComment = createNewStickyNote(respInfos, index);
        //alert(newComment.innerHTML);
        if(newComment) {
            var comments = $('stickyUL_'+index);
            comments.appendChild(newComment);
            if(comments.style.display=="none") comments.style.display = "";
            switchSEditor(index);
            renderCount();
            countDetails(indexA[0]);
        }else {
            switchSEditorToEdit(index);
            showNoticer($("sEditorNoticer_"+index), WORD_4);
        }
    }else {
        switchSEditorToEdit(index);
        showNoticer($("sEditorNoticer_"+index), WORD_4);
    }
} 
function createNewStickyNote(respInfos, index) {  
    try{
        indexA = index.split("_");
        sIndex = index+"_"+_bookmarks[indexA[0]].annotations[indexA[1]].stickyNotes.length;
        var li = document.createElement("li");
        li.className = "sItem";
        li.id = "sticky_"+sIndex;
        var div = document.createElement("div");
        div.className = "sContent";
        div.innerHTML = respInfos.content;
        var span = document.createElement("span");
        spanOption = document.createElement("span");
        spanOption.className = "commentOption";
        spanOption.innerHTML = "<span id='removeStickyNote_"+sIndex+"' onclick=\"doRemoveStickyNote('"+sIndex+"')\">Remove</span>";
        //        spanLink = document.createElement("span");
        //        spanLink.innerHTML = "Remove";
        //        spanLink.index = sIndex;
        //        spanLink.id = "removeStickyNote_"+sIndex;
        //        spanLink.onclick = removeStickyNote;
        //        spanOption.appendChild(spanLink);
        span.appendChild(spanOption);
        span.className = "tail";
        span.innerHTML += "posted by ";
        var a = document.createElement("a");
        a.href = GROUP_HOST + "/" + respInfos.g_name + "/bookmark/"+respInfos.user_name;
        a.title = "View " + respInfos.user_real_name + "'s bookmarks in " + respInfos.display_name;
        a.innerHTML = respInfos.user_real_name;
        span.appendChild(a);
        span.innerHTML += " " + respInfos.created_at;
        li.appendChild(div);
        li.appendChild(span);
        // make json stickyNote
        var stickyNote = new StickyNote();
        stickyNote.id = respInfos.id;
        stickyNote.u_name = respInfos.u_name;
        stickyNote.mode = respInfos.mode;
        addStickyNoteToJson(stickyNote, index);
        return li;
    }catch(e) {
        alert(e);
        return null;
    }
} 

// add json comment to client model
function addStickyNoteToJson(stickyNote, index) {
    var indexA = index.split("_");
    if(_bookmarks[indexA[0]].annotations[indexA[1]].s_count==0) {
        _bookmarks[indexA[0]].annotations[indexA[1]]['mode'] = stickyNote['mode'];
        changeHighlightColor(indexA[0]+"_"+indexA[1], stickyNote['mode']);
    }
    _bookmarks[indexA[0]].annotations[indexA[1]].stickyNotes.push(stickyNote);
    _bookmarks[indexA[0]].annotations[indexA[1]].s_count++;
}

function changeHighlightColor(index, mode) {
    var highlight = $("highlight_"+index);
    if(mode==0) {
        highlight.className = highlight.className.replace("private", "public");
    }else {
        highlight.className = highlight.className.replace("public", "private");
    }
}


function initCEditor(index) {
    $("cContent_"+index).disabled = false;
    $("cContent_"+index).value = "";
    $("cEditorBottom_"+index).style.display = "";
    initCEditorMode(index, DEFAULT_C_MODE);
}   

function initSEditor(index) {
    $("sContent_"+index).disabled = false;
    $("sContent_"+index).value = "";
    $("sEditorBottom_"+index).style.display = "";
    var indexA = index.split("_");
    var a = _bookmarks[indexA[0]].annotations[indexA[1]];
    if(a.s_count!=0) {
        initSEditorMode(index, a['mode'], true);
    }else {
        initSEditorMode(index, DEFAULT_S_MODE);
    }
}

function displayCContent(content) {
    return content.replace(/\r\n|\n|\r/g,"<br/>").replace(/<script/i, "&lt;script").replace(/<\/script/i, "&lt;/script");
}

function postCommentComplete(request, index, content) {
    if(request.status == "200") {
        var respInfos = eval("("+request.responseText+")");
        respInfos.content = displayCContent(content);
        // create new comment
        // depend on your view
        var newComment = createNewComment(respInfos, index);
        if(newComment) {
            var comments = $('comments_'+index);
            comments.appendChild(newComment);
            if(comments.style.display=="none") comments.style.display = "";
            switchCEditor(index);
            renderCount();
        }else {
            switchCEditorToEdit(index);
            showNoticer($("cEditorNoticer_"+index), WORD_4);
        }
    }else {
        switchCEditorToEdit(index);
        showNoticer($("cEditorNoticer_"+index), WORD_4);
    }
}  
function createNewComment(respInfos, index) {  
    try{
        //spanOptions.innerHTML = "<span id='removeComment_"+cIndex+"' onclick=\"doRemoveComment('"+cIndex+"')\">Remove</span>";
        var cIndex = index+"_"+_bookmarks[index].comments.length;
        var li = document.createElement("li");
        li.className = "cItem";
        li.id = "comment_"+cIndex;
        var div = document.createElement("div");
        div.className = "cContent";
        div.innerHTML = respInfos.content;
        var span = document.createElement("span");
        var spanOption = document.createElement("span");
        spanOption.className = "commentOption";
        spanOption.innerHTML = "<span id='removeComment_"+cIndex+"' onclick=\"doRemoveComment('"+cIndex+"')\">Remove</span>";
        span.appendChild(spanOption);
        span.className = "tail";
        span.innerHTML += "posted by ";
        var a = document.createElement("a");
        a.href = GROUP_HOST + "/" + respInfos.g_name + "/bookmark/" + respInfos.user_name;
        a.title = "View " + respInfos.user_real_name + "'s bookmarks in " + respInfos.display_name;
        a.innerHTML = respInfos.user_real_name;
        span.appendChild(a);
        span.innerHTML += " " + respInfos.created_at;
        li.appendChild(div);
        li.appendChild(span);
        
        // make json comment
        var comment = new Comment();
        comment.id = respInfos.id;
        comment.mode = respInfos.mode;
        comment.u_name = respInfos.u_name;
        addCommentToJson(comment, index);
        return li;
    }catch(e) {
        alert(e);
        return null;
    }
}    

// add json comment to client model
function addCommentToJson(comment, index) {
    _bookmarks[index].comments.push(comment);
    _bookmarks[index].c_count++;
}

function addStickyNotes(index) {   
    switchSEditor(index);
}
function cancelSEditor() {
    switchSEditor(this.index);
}
function switchSEditor(index) {
    var sticky = $("sticky_"+index);
    var sEditor = $("sEditor_"+index);
    if($("sEditor_"+index).innerHTML == "") {
        $("sEditor_"+index).appendChild(createSEditor(index));
        initSEditorMode(index, DEFAULT_S_MODE);
    }
    if(sEditor.style.display=="") {
        sEditor.style.display = "none";
        var indexA = index.split("_");
        if(_bookmarks[indexA[0]].annotations[indexA[1]].s_count==0) {
            sticky.style.display = "none";
        }
    }else {
    
        initSEditor(index);
        sEditor.style.display = "";
        sticky.style.display = "";
    }
//new Effect[Element.visible(sEditor) ? 
//          'BlindUp' : 'BlindDown'](sEditor, {duration: 0.25});
}

function createSEditor(index) {
    var form = document.createElement("form");
    form.id = "sEditForm_"+index;
    form.method = "post";
    form.onsubmit = postStickyNote;
    var noticer = document.createElement("div");
    noticer.id = "sEditorNoticer_"+index;
    noticer.className = "cEditTop";
    noticer.style.display = "none";
    form.appendChild(noticer);
    var txtA = document.createElement("textarea");
    txtA.className = "inputTxt";
    txtA.name = "comment_content";
    txtA.id = "sContent_"+index;
    form.appendChild(txtA);
    var bottom = document.createElement("div");
    bottom.className = "cEditorBottom";
    bottom.id = "sEditorBottom_"+index;
    var cancelBtn = document.createElement("input");
    cancelBtn.type = "button";
    cancelBtn.value = "Cancel";
    cancelBtn.className = "cancelBtn";
    cancelBtn.index = index;
    cancelBtn.onclick = cancelSEditor;
    bottom.appendChild(cancelBtn);
    
    var submitBtn = document.createElement("input");
    submitBtn.type = "submit";
    submitBtn.value = "Post";
    submitBtn.className = "postBtn"
    bottom.appendChild(submitBtn);
    
    /*var selectItem = document.createElement("select");
    selectItem.id = "sModeSelector_"+index;
    selectItem.onchange = changeSMode;
    selectItem.index = index;
    selectItem.name = "sMode"; 
    selectItem.className = "sModeSelector";
    var option = document.createElement("option");
    option.value = "0";
    option.innerHTML = "Public";
    selectItem.appendChild(option);
    option = document.createElement("option");
    option.value = "2";
    option.innerHTML = "* Private";
    selectItem.appendChild(option);
    bottom.appendChild(selectItem);
     */
    
    form.appendChild(bottom);
    return form
} 

function initSEditorMode(index, mode, disabled) {   
    /*var selectItem = $("sModeSelector_"+index);
    var noticer = $("sEditorNoticer_"+index);
    if(mode=="0") {
    selectItem.value = "0";
    showNoticer(noticer, WORD_8);
    }else {   
    selectItem.value = "2";
    hideNoticer(noticer);
    }
    selectItem.disabled = disabled;*/ 
    var noticer = $("sEditorNoticer_"+index);
    showNoticer(noticer, WORD_104);
} 

function changeSMode() {       
    doSMode(this.index, $F("sModeSelector_"+this.index));
}  

function doSMode(index, mode) {
    if(mode=="0") {
        showNoticer($("sEditorNoticer_"+index), WORD_8);
    }else {
        hideNoticer($("sEditorNoticer_"+index));
    }
}  

function doRemoveComment(index) {  
    if(!confirm(ALE_21)) return false;
    var indexA = index.split("_");
    var id = _bookmarks[indexA[0]].comments[indexA[1]].id;
    try{
        var url = '/site/delete_page_comment';
        new Ajax.Request(url,
        {
            method:"post",
            asynchronous:true,
            evalScripts:true,
            onLoading:function(request){
                doRemoveCommentLoading(request, index)
            },
            onComplete:function(request){
                doRemoveCommentComplete(request, index)
            },
            parameters:{
                p_c_id:id,
                g_l_id:_bookmarks[indexA[0]].g_l_id,
                user_id:_bookmarks[indexA[0]].comments[indexA[1]].user_id
            }
        }
        );
        return false;
    }catch(e) {
        alert(e);
        return false;
    }
} 
function doRemoveCommentLoading(request, index) { 
    $("comment_"+index).style.backgroundColor = "#eee";
    var remover = $("removeComment_"+index);
    remover.innerHTML = WORD_3;
    remover.onclick = null;
}   
function doRemoveCommentComplete(request, index) { 
    if(request.status=="200") {
        var indexA = index.split("_");
        delete(_bookmarks[indexA[0]].comments[indexA[1]]);
        _bookmarks[indexA[0]].c_count--;
        Element.remove("comment_"+index);
        renderCount();
    }else {
}
}      

function removeStickyNote() {
    doRemoveStickyNote(this.index);
}
function doRemoveStickyNote(index) { 
    if(!confirm(ALE_23)) return false;
    try{
        var indexA = index.split("_");
        var id = _bookmarks[indexA[0]].annotations[indexA[1]].stickyNotes[indexA[2]].id;
        var url = '/site/delete_sticky_note';
        new Ajax.Request(url,
        {
            method:"post",
            asynchronous:true,
            evalScripts:true,
            onLoading:function(request){
                doRemoveStickyNoteLoading(request, index)
            },
            onComplete:function(request){
                doRemoveStickyNoteComplete(request, index)
            },
            parameters:{
                i_c_id:id,
                g_l_id:_bookmarks[indexA[0]].g_l_id,
                user_id:_bookmarks[indexA[0]].annotations[indexA[1]].stickyNotes[indexA[2]].user_id
            }
        }
        );
        return false;
    }catch(e) {
        alert(e);
        return false;
    }
} 
function doRemoveStickyNoteLoading(request, index) { 
    $("sticky_"+index).style.backgroundColor = "#eee";
    var remover = $("removeStickyNote_"+index);
    remover.innerHTML = WORD_3;
    remover.onclick = null;
}   
function doRemoveStickyNoteComplete(request, index) { 
    if(request.status=="200") {
        var indexA = index.split("_");
        delete(_bookmarks[indexA[0]].annotations[indexA[1]].stickyNotes[indexA[2]]);
        _bookmarks[indexA[0]].annotations[indexA[1]].s_count--;
        if(_bookmarks[indexA[0]].annotations[indexA[1]].s_count<=0) {
            $("sticky_"+indexA[0]+"_"+indexA[1]).style.display = "none";
            changeHighlightColor(indexA[0]+"_"+indexA[1], 2);
        }
        Element.remove("sticky_"+index);
        renderCount();
    }else {
}
}

function countDetails(index) {        
    var bookmark = _bookmarks[index];
    if(bookmark.c_count!=0 || bookmark.annotations.length!=0) {
        bookmark.hasDetails = false;
    }else {
        bookmark.hasDetails = true;
    }
}

function switchExpandOrCollapseAll() {
    if(_GLOBAL_VAR['expand']) {
        expandOrCollapseAll(false);
        _GLOBAL_VAR['expand'] = false;
        colorListItem(0);
        var i = 0;
        var s = $("EOCSwitcher_"+i);
        while(s) {
            s.innerHTML = WORD_12;
            i++;
            s = $("EOCSwitcher_"+i);
        }
    }else {
        expandOrCollapseAll(true);
        _GLOBAL_VAR['expand'] = true;
        colorListItem(1);
        var i = 0;
        var s = $("EOCSwitcher_"+i);
        while(s) {
            s.innerHTML = WORD_13;
            i++;
            s = $("EOCSwitcher_"+i);
        }
    }
}

function expandOrCollapseAll(expand) {
    if(expand) {
        for(var index=0; index<_bookmarks.length; index++) {
            if(!_bookmarks[index].hasDetails) continue;
            var details = $("bookmarkDetails_"+index);
            var eoc = $("eoc_"+index);
            details.style.display = "";
            eoc.innerHTML = eoc.innerHTML.replace(DIS_7, DIS_6);
            _bookmarks[index].expand = true;
        }
        _GLOBAL_VAR['expand'] = true;
        var i = 0;
        var s = $("EOCSwitcher_"+i);
        while(s) {
            s.innerHTML = DIS_9;
            i++;
            s = $("EOCSwitcher_"+i);
        }
        setDefaultEC('14');
    }else {
        for(var index=0; index<_bookmarks.length; index++) {
            if(!_bookmarks[index].hasDetails) continue;
            var details = $("bookmarkDetails_"+index);
            var eoc = $("eoc_"+index);
            details.style.display = "none";
            eoc.innerHTML = eoc.innerHTML.replace(DIS_6, DIS_7);
            _bookmarks[index].expand = false;
        }
        _GLOBAL_VAR['expand'] = false;
        var i = 0;
        var s = $("EOCSwitcher_"+i);
        while(s) {
            s.innerHTML = DIS_8;
            i++;
            s = $("EOCSwitcher_"+i);
        }
        setDefaultEC('13');
    }
}

function setDefaultEC(cmd) {
    var cusData = loadCusData();
    if(cmd=='13') {
        cusData['default_ec'] = "1";
    }else {
        cusData['default_ec'] = "0";
    }
    cusData.store();
    //markDefaultECAction(cusData['default_ec']);
    resetMoreAction();
}
function loadCusData() {
    var domain = getCookieDomain();
    var cusData = new Cookie(document, "g_cus_data", 240, '/', domain);
    cusData.load();
    return cusData;
}
function changeListCount(count) {
    var cusData = loadCusData();
    cusData['count'] = count;
    cusData.store();
    self.location.reload();
}

function checkEOCStatus() {
    var expand = false;
    var collapse = false
    for(var i=0; i<_bookmarks.length; i++) {
        if(_bookmarks[i].expand) {
            expand = true;
        }else {
            collapse = true;
        }
    }
    if(expand && !collapse) {
        _GLOBAL_VAR['expand'] = true;
        var i = 0;
        var s = $("EOCSwitcher_"+i);
        while(s) {
            s.innerHTML = WORD_13;
            i++;
            s = $("EOCSwitcher_"+i);
        }
        colorListItem(1);
    }else if(!expand && collapse) {
        _GLOBAL_VAR['expand'] = false;
        var i = 0;
        var s = $("EOCSwitcher_"+i);
        while(s) {
            s.innerHTML = WORD_12;
            i++;
            s = $("EOCSwitcher_"+i);
        }
        colorListItem(0);
    }
}

function initExpandOrCollapseAll() {
    var expand = _GLOBAL_VAR['expand'];
    expandOrCollapseAll(expand);
}

function initExpandOrCollapseItem() {
    for(var i=0; i<_bookmarks.length; i++) {
        var item = $("eoc_"+i);
        item.index = i;
        item.onclick = expandOrCollapse;
        var details_count = _bookmarks[i].details_count();
        if(details_count>0) {
            _bookmarks[i].hasDetails = true;
            item.innerHTML = "<span id='dCount_"+i+"'>"+details_count+"</span>"+DIS_7;
            item.style.display = "";
        }else {
            _bookmarks[i].hasDetails = false;
        }
    }
}

function initSidebarAvatar() {
    displayAvatar(130, [$("avatar")])
}

function getBatchActions() {
    var batchActions = [];
    //for(var i=0; i<_moreActionSelectCount; i++) {
    var range = document;
    var options = range.getElementsByTagName("option");
    var names = "";
    for(var j=0; j<options.length; j++) {
        var name = options[j].getAttribute("name");
        if(name=="batchAction") {
            batchActions.push(options[j]);
        }
    }
    //}
    return batchActions;
}

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 initMoreAction() {
    var i=0;
    while($("moreAction_"+i)) {
        var action = $("moreAction_"+i);
        action.disabled = false;
        action.value = "-1";
        action.onchange = doAction;
        i++;
    }
    switchBatchAction();
}

function importContact(){
    var w = window.open(RESOURCE_HOST+"/contact_mana?from=plusman&referInfo="+GROUP_HOST+"/group_mana/import_contacts", null, "width=460,height=620, left=0, top=0, status=no,resizable=no");
}
function switchPreview(index) {
    var pBox = $("b_preview_box_"+index);
    if(pBox) {
        if(pBox.style.display=="none") {
            pBox.style.display = "";
        }else {
            pBox.style.display = "none";
        }
    }else {
        createPreviewBox(index);
    }
}

function closePreview() {
    hidePreiview(this.index);
}
function newWindowPreview() {
    hidePreiview(this.index);
    return true;
}
function hidePreiview(index) {
    var pBox = $("b_preview_box_"+index);
    pBox.style.display = "none";
}

function createPreviewBox(index) {
    var bBox = $("bookmarkItem_"+index);
    var pBox = document.createElement("div");
    pBox.className = "previewBox";
    pBox.id = "b_preview_box_"+index;
    var pBar = document.createElement("div");
    pBar.className= "previewBar";
    var pCloser = document.createElement("a");
    pCloser.innerHTML = "Close";
    pCloser.className = "pCloser";
    pCloser.href = "javascript:void(0)";
    pCloser.index = index;
    pCloser.onclick = closePreview;
    var pNewWindow = document.createElement("a");
    pNewWindow.innerHTML = "New window";
    pNewWindow.className = "pNewWindow";
    pNewWindow.href = _bookmarks[index].url;
    pNewWindow.index = index;
    pNewWindow.target = "_blank";
    //pNewWindow.onclick = newWindowPreview;
    var pURL = document.createElement("a");
    pURL.id = "pURL_"+index;
    pURL.href = _bookmarks[index].url;
    pURL.target = "_blank";
    pURL.innerHTML = _bookmarks[index].url;
    pURL.onclick = function(){
        return true;
    }
    pBar.appendChild(pCloser);
    pBar.appendChild(pNewWindow);
    pBar.appendChild(pURL);
    pBox.appendChild(pBar);
    var previewInner = document.createElement("div");
    previewInner.className = "previewInner";
    var preview = document.createElement("iframe");
    preview.className = "previewIFrame";
    preview.id = "b_preview_"+index;
    preview.setAttribute("frameBorder", "0");
    previewInner.appendChild(preview)
    pBox.appendChild(previewInner);
    bBox.appendChild(pBox);
    preview.setAttribute("src", _bookmarks[index].url);
}

function copyThis(){
    var url = encodeURIComponent(_bookmarks[this.index].url);
    var title = encodeURIComponent(_bookmarks[this.index].title);
    var tags = encodeURIComponent(_bookmarks[this.index].t_name);
    var referInfo = encodeURIComponent(self.location);
    var url= BOOKMARK_HOST + "/post/index?url="+url+"&title="+title+"&tags="+tags+"&referInfo="+referInfo;
    self.location = url;
}

function quickCopy(){
    try{
        var index = this.index;
        var url =_bookmarks[index].url;
        var title = _bookmarks[index].title;
        var tags = _bookmarks[index].t_name;
        alert("url= "+ url +", title= "+ title + ", tags= " + tags);
        showCentralNoticer(WORD_3);
        var postURL = BOOKMARK_HOST + "/post";
        new Ajax.Request(postURL,
        {
            asynchronous:true,
            evalScripts:false,
            onComplete:function(request){
                alert(request.status);
                hideCentralNoticer();
                if(request.status=="200"){
                    var quickCopy = $(_floatOn+"_menu_item_"+index+"_3");
                    quickCopy.style.display = "none";
                }else {
                    alert(request.status);
                }
            },
            parameters:"url="+url+"&title="+title+"&tags="+tags
        });
        return false;
    }catch(e){
        alert(e);
        return false;
    }
}

/*===========================================
 * Save Item
 * args:
 * index - item index
 * type - 'bookmark', 'list'
 * saveType - 'create', 'edit'
 *
 *===========================================*/

function saveItem(args) {
    var pw;
    if(args.type=='bookmark') {
        _GLOBAL_VAR["saveBType"] = args.saveType;
        var index = args.index;
        var root = "leftColumn";
        var b = $("bookmarkItem_"+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");
    }else if(args.type=='list') {
        var root = "column";
        pw = new PopWindow({
            optEnabled: true,
            left:160,
            top:20,
            width:500,
            title:"Save List",
            root:root
        });
    }
    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);
    // 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' />"));
    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;
    if(args.type=='bookmark') {
        var index = args.index;
        title = _GLOBAL_VAR['bookmarks'][index].title;
        tags = _GLOBAL_VAR['bookmarks'][index].tags.split(",");
        desc = _GLOBAL_VAR['bookmarks'][index].desc;
    }else if(args.type=='list') {
        title = _GLOBAL_VAR['list'].title;
        tags = _GLOBAL_VAR['list'].tags.split(",");
        desc = _GLOBAL_VAR['list'].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 refreshBookmark(index) {
    $("titleLink_"+index).update(_GLOBAL_VAR['bookmarks'][index].title);
    var tagsEl = $("tags_"+index).update("");
    var tags = _GLOBAL_VAR['bookmarks'][index].t_name.split(",");
    for(var i=0; i<tags.length; i++) {
        var a = document.createElement("a");
        if(tags[i].indexOf(" ")!=-1) {
            a.href="/user/"+_GLOBAL_VAR['username']+"/"+encodeURIComponent("\""+tags[i]+"\"");
        }else {
            a.href="/user/"+_GLOBAL_VAR['username']+"/"+encodeURIComponent(tags[i]);
        }
        a.innerHTML = tags[i];
        tagsEl.appendChild(a);
        if(i<tags.length-1) {
            tagsEl.innerHTML += ", "
        }
    }
    var desc = _GLOBAL_VAR['bookmarks'][index].description;
    if(!desc.blank()) {
        $("descContent_"+index).update(desc);
        $("desc_"+index).show();
    }else {
        $("desc_"+index).hide();
    }
    // refresh lists
    renderBelongTo(index);
    // refresh groups
    renderSharedTo(index);
    
}

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 mode;
      
    if(args.type=='bookmark') {
        itemURL = _GLOBAL_VAR['bookmarks'][index].url;
        if(_GLOBAL_VAR["saveBType"]=="edit") {
            mode = _GLOBAL_VAR['bookmarks'][index].mode;
        }else {
            mode = 0;
        }
    } else if(args.type=='list') {
        itemURL = self.location.href;
        mode=0;
    }
      
    mode = 0;
    var json = {
        "title" : titleTxt.value,
        "desc" : descTxt.value,
        "tags" : tagsTxt.value,
        "url" : itemURL,
        "mode" : mode
    };
    
    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"] = _GLOBAL_VAR['bookmarks'][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") {
                        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;
}
