/*-------------------------------------------------
 *TopNav funciton 
 * Copyright (c) 2007 Allen Dog & Diigo System.
 *------------------------------------------------*/
var TopNav = Class.create();
TopNav.ShowTimeOut = null;
TopNav.hideTimeOut = null;
TopNav.mouseoverHandler =  function(id){
    TopNav.clearTimeHandler();
    TopNav.showTimeOut = setTimeout(function(){
        TopNav.showContextMenu(id)
    },50);
}
TopNav.mouseoutHandler = function(){
    TopNav.clearTimeHandler();
    TopNav.hideTimeOut = setTimeout(TopNav.hideContextMenu,200);
}
TopNav.clearTimeHandler = function(){
    clearTimeout(TopNav.showTimeOut);
    clearTimeout(TopNav.hideTimeOut)
}
TopNav.showContextMenu = function(id){
    //IE6 select overlap bug
    if(!$("contextMenuHideIframe")){
        TopNav.hideIframe = new Element('iframe', {
            id: "contextMenuHideIframe"
        });
        document.body.appendChild(TopNav.hideIframe);
        TopNav.hideIframe.hide();
    }
    TopNav.hideIframe = $("contextMenuHideIframe");
	
    li = $(id);
    if(TopNav.selected && TopNav.selected != li){
        TopNav.hideContextMenu();
    }
    TopNav.selected = li;
    var toggler = li.down();
    var submenu = toggler.next();
		
    if(!submenu.visible()){
        toggler.addClassName("flyMenu")
        var p = [0,0]
        var p=[toggler.offsetLeft,toggler.offsetTop]
        var left = 0;
        var top = 0;
        var offsetX = 0;
        left = p[0] + offsetX;
        top = p[1]+toggler.getHeight();
        submenu.setStyle({
            display: "block",
            left: left+"px",
            top:top+"px"
        });
        submenu_p = Position.cumulativeOffset(submenu);
        TopNav.hideIframe.setStyle({
            display: "block",
            position:"absolute",
            left: submenu_p[0]+"px",
            top: submenu_p[1]+"px",
            width: submenu.getWidth()+"px",
            height: submenu.getHeight()+"px"
        });
    }
}
TopNav.hideContextMenu = function(){
    if(TopNav.selected){
        var toggler = TopNav.selected.down();
        var submenu = toggler.next();
        if(submenu.visible()){
            TopNav.hideIframe.hide();
            submenu.hide();
            toggler.removeClassName("flyMenu");
        }
        TopNav.selected = null;
    }
}
/*=========================
 * bookmark float menu
 *=========================*/
function hoverMenuBox() {
    this.className += " menuItemHover";
}
function outMenuBox(){
    this.className = this.className.replace("menuItemHover", "");
}
function hoverMenu() {
    this.className += " menuItemOnAction";
}
function outMenu(){
    this.className = this.className.replace("menuItemOnAction", "");
}

/*--------------------------
 * get message count
 *-------------------------*/
function getMessageCount() {
    var url = "/message_mana/get_message_count";
    new Ajax.Request(url,
    {
        asynchronous:true,
        evalScripts:false,
        method:"get",
        onComplete:function(request){
            if(request.status=="200") {
                $("messageCount").innerHTML = "("+request.responseText+")";
            }
        }
    });
    return false;
}
/**
 * Domain crumb
 */
function initDomainCrumb(){
    var tip = 'e.g. www.example.com';
    var p = $('txtDomainCrumb');
    var originalValue = p.value;

    if (/^\s*$/.test(p.value) || p.value == tip) {
        p.addClassName('tip').setValue(tip);
    }
    var submitting = false;
    var focused = false;
    var f = function(e) {
        if (e && e.keyCode == Event.KEY_RETURN) submitting = true;
        p.setStyle({
            width: p.next('div').update(p.value).getWidth() + 35 + 'px'
        });
    };

    p.observe('keypress', f).observe('keyup', f)
    .observe('focus', function() {
        p.addClassName('focused');
        focused = true;
        if (p.value == tip) {
            p.removeClassName('tip').setValue('');
        }
    })
    .observe('blur', function() {
        if (submitting) return false;
        p.removeClassName('focused');
        focused = false;
        if (/^\s*$/.test(p.value)) {
            p.addClassName('tip').setValue(tip);
        }
        f();
    })
    .observe('mouseover', function() {
        p.addClassName('focused');
    })
    .observe('mouseout', function() {
        if (!focused) p.removeClassName('focused');
    });
    f();
}

/*-------------------------------------------------
 * doTopSearch
 *------------------------------------------------*/
function doTopSearch() {
    var form = $("topSearchForm");
    var scope = form.scope.value;
    var what = form.what.value;
    switch(scope) {
        case "diigo": {
            self.location = BOOKMARK_HOST+"/search/fulltext?what="+encodeURIComponent(what);
        }break;
        case "groups": {
            self.location = GROUP_HOST+"/group_mana/search_groups?keywords="+encodeURIComponent(what);
        }break;
        case "people": {
            self.location = BOOKMARK_HOST+"/people/search?query="+encodeURIComponent(what);
        }break;
        case "messages": {
            }break;
        case "web":{
            self.location = "http://www.google.com/search?hl=en&q="+encodeURIComponent(what);
        }break;
    }
} 
 
/*-------------------------------------------------
 * Context Menu
 * Copyright (c) 2007 Allen Dog & Diigo System.
 *  leinte 2007-11-5
 * options:
 *     eventType:
 *                click -- onclick event
 *                mouseover  --  mouseover event
 *     background-color
 *     color:      font color
 *     togglerClass:  class name of toggler
 *------------------------------------------------*/
var ContextMenu = Class.create({
    initialize: function(scope, options) {
        var eventType = options.eventType || "click";
        // IE6 select overlap bug
        if(!ContextMenu.hideIframe && !$("contextMenuHideIframe")) {
            ContextMenu.hideIframe = new Element('iframe', {
                id: "contextMenuHideIframe"
            });
            document.body.appendChild(ContextMenu.hideIframe);
            ContextMenu.hideIframe.hide();
        }

        $(scope).select(".contextMenu").each(function(li){
            var toggler = li.down();
            var submenu = toggler.next();
            if(options.submenuId){
                submenu = $(options.submenuId)
            }
            if(eventType == "click"){
                toggler.onclick = function(){
                    toggler.blur();
                    ContextMenu.clearTimeHandler();
                    if(!submenu.visible()){
                        ContextMenu.showContextMenu(li,options);
                        Event.observe(document,"mousedown",ContextMenu.onclick);
                    }else{
                        ContextMenu.onclick();
                    }
                    return false;
                }
            }else if(eventType == "mouseover"){
                li.onmouseover = function(event){
                    ContextMenu.clearTimeHandler()
                    ContextMenu.showTimeOut = setTimeout(function(){
                        ContextMenu.showContextMenu(li,options)
                    },50)
                }
                li.select(".subMenu")[0].select("a").each(function(aEl){
                    aEl.onmouseover = function(){
                        ContextMenu.clearTimeHandler();
                    }
                    aEl.onmouseout = function(){
                        ContextMenu.clearTimeHandler();
                        ContextMenu.hideTimeOut = setTimeout(ContextMenu.hideContextMenu,500);
                    }
                });
            }
        })
    }
});

ContextMenu.showTimeOut = null;
ContextMenu.hideTimeOut = null;
ContextMenu.selected = null;
ContextMenu.selected_submenu = null;
ContextMenu.options = null;
ContextMenu.onclick = function(event){
    ContextMenu.clearTimeHandler();
    ContextMenu.hideTimeOut = setTimeout(ContextMenu.hideContextMenu,200)
    Event.stopObserving(document,"mousedown",ContextMenu.onclick);
}
ContextMenu.clearTimeHandler = function(){
    if(ContextMenu.showTimeOut){
        clearTimeout(ContextMenu.showTimeOut);
    }
    if(ContextMenu.hideTimeOut){
        clearTimeout(ContextMenu.hideTimeOut)
    }
}
ContextMenu.showContextMenu = function(li,options){
    if(ContextMenu.selected && ContextMenu.selected != li){
        ContextMenu.hideContextMenu();
    }
    ContextMenu.options = options;
    ContextMenu.selected = li;
    var toggler = ContextMenu.selected;
    var submenu = toggler.down().next();
    if(options.submenuId){
        submenu = $(options.submenuId)
    }
    if(!submenu.visible()){
        if(options.togglerClass){
            toggler.addClassName(options.togglerClass)
        }
        ContextMenu.selected_submenu = submenu;
        var p = Position.cumulativeOffset(toggler);
        var left = p[0]
        var top = p[1]+toggler.getHeight();
        var offsetX = options.offsetX || 0;
        var offsetY = options.offsetY || 0;
        if(submenu.getWidth()+p[0]+30>document.body.offsetWidth){
            left = p[0]-(submenu.getWidth()-toggler.getWidth());
        }else {
            left = p[0] + offsetX;
            if(options.align == "right"){
                left = p[0] + toggler.getWidth() - submenu.getWidth();
            }
        }
        document.body.appendChild(submenu);
        if(options.className){
            submenu.addClassName(options.className);
        }
        submenu.setStyle({
            display: "block",
            left: left+"px",
            top:top+"px"
        });
        ContextMenu.hideIframe.setStyle({
            display: "block",
            postion:'absolute',
            border:0,
            frameborder:'no',
            left: left+"px",
            top: top+"px",
            width: submenu.getWidth()+"px",
            height: submenu.getHeight()+"px"
        });
    }
}
ContextMenu.hideContextMenu = function(){
    if(ContextMenu.selected){
        var toggler = ContextMenu.selected.down();
        var submenu = ContextMenu.selected_submenu//toggler.next();
        if(ContextMenu.options.submenuId){
            submenu = $(ContextMenu.options.submenuId)
        }
        if(submenu.visible()){
            ContextMenu.hideIframe.hide();
            submenu.hide();
            if(ContextMenu.options.togglerClass){
                toggler.removeClassName(ContextMenu.options.togglerClass)
            }
            ContextMenu.selected.appendChild(submenu)
        }
        ContextMenu.selected = null;
    }
}

/*====================================
 * domain crumb
 *====================================*/
function initDomainCrumb() {
    var tip = 'e.g. www.example.com';
    var p = $('txtDomainCrumb');
    var originalValue = p.value;

    if (/^\s*$/.test(p.value) || p.value == tip) {
        p.addClassName('tip').setValue(tip);
    }
    var submitting = false;
    var focused = false;
    var f = function(e) {
        if (e && e.keyCode == Event.KEY_RETURN) submitting = true;
        p.setStyle({
            width: p.next('div').update(p.value).getWidth() + 35 + 'px'
        });
    };

    p.observe('keypress', f).observe('keyup', f)
    .observe('focus', function() {
        p.addClassName('focused');
        focused = true;
        if (p.value == tip) {
            p.removeClassName('tip').setValue('');
        }
    })
    .observe('blur', function() {
        if (submitting) return false;
        p.removeClassName('focused');
        focused = false;
        if (/^\s*$/.test(p.value)) {
            p.addClassName('tip').setValue(tip);
        }

        //p.setValue(originalValue);
        f();
    })
    .observe('mouseover', function() {
        p.addClassName('focused');
    })
    .observe('mouseout', function() {
        if (!focused) p.removeClassName('focused');
    });
    f();
}

/*====================================
 * auto complate
 *
 *====================================*/
function AutoComplete(inputID, itemsID, submitID) {
    this.id = itemsID;
    this.inputField = document.getElementById(inputID);
    if(!this.inputField){
        return null;
    }
    this.completeDiv = document.getElementById(itemsID);
    this.submitBtn = document.getElementById(submitID);
    this.itemPrefix = itemsID;
    this.temItemIndex = -1;
    this.items;
    this.filterItems; // item filter handler
    this.init; // init items handler
    this.blurKeyword = blurKeyword;
    this.afterTab = function(){
        return true;
    }; // default no action after hit tab
    this.afterCreated = function(){
        return true
    }; // default no action after afterCreated;
    this.cleanTail = function(str) {
        return  str.replace(/\s*$/,"").replace(/,*$/,"");
    }
    this.findItems = autoCompleteFindItems;
    this.clearItems = autoCompleteClearItems;
    this.afterEnter = this.clearItems; // default no action after hit enter
    this.setOffsets = autoCompleteSetOffsets;
    this.calculateOffset = autoCompleteCalculateOffest;
    this.populateItems = autoCompletePopulateItems;
    this.keydown = autoCompleteKeydown;
    this.inputField.object = this;
    this.disabled = false;
    this.turnOff = function(){
        this.inputField.onkeyup = null;
        this.inputField.onkeydown = null;
        this.disabled = false;
    }
    this.turnOn = function(){
        this.inputField.onkeyup = this.findItems;
        this.inputField.onkeydown = this.keydown;
        this.disabled = true;
    }
    this.inputField.onblur = function() {
        setTimeout(this.object.clearItems.bind(this.object), 200);
        blurKeyword();
        return false;
    }
    this.lockSubmit = function() {
        this.lockedSubmit = true;
        this.submitBtn.disabled = true;
    }
    this.unlockSubmit = function() {
        this.lockedSubmit = false;
        this.submitBtn.disabled = false;
    }
}

function autoCompleteKeydown(e) {
    var object = this.object;
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if (e) keycode = e.which;
    // tab
    if(keycode==9) {
        setCaretPos(object.inputField, 255);
        var nameItem = document.getElementById(object.itemPrefix+"Item_"+(object.temItemIndex+1));
        if(nameItem) {
            nameItem.className = "mouseOver";
            var preItem = document.getElementById(object.itemPrefix+"Item_"+object.temItemIndex);
            if(preItem) preItem.className = "mouseOut";
            object.temItemIndex++;
        }
        return false;
    }else{
        try{
            object.inputField.style.width = getTextSize(object.inputField.value, $("tagsCrumbSizer")) + 30 + "px";
        }catch(e){}
        return true;
    }
}

function autoCompleteClearItems() {
    if(this.lockedSubmit) {
        this.unlockSubmit();
    }
    if(this.completeDiv) {
        this.completeDiv.innerHTML = "";
        this.completeDiv.style.display = "none";
    }
    if(this.actShadow) {
        this.actShadow.style.display = "none";
    }
//    try{
//        this.inputField.style.width = (this.inputField.value, $("tagsCrumbSizer")) + 30 + "px";
//    }catch(e){}
}


function autoCompleteFindItems(e) {
    var object = this.object;
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if (e) keycode = e.which;
    switch(keycode){
        // down
        case 40: {
            setCaretPos(object.inputField, 255);
            var nameItem = document.getElementById(object.itemPrefix+"Item_"+(object.temItemIndex+1));
            if(nameItem) {
                nameItem.className = "mouseOver";
                var preItem = document.getElementById(object.itemPrefix+"Item_"+object.temItemIndex);
                if(preItem) preItem.className = "mouseOut";
                object.temItemIndex++;
            }
        }return false;
        // up
        case 38: {
            setCaretPos(object.inputField, 255);
            nameItem = document.getElementById(object.itemPrefix+"Item_"+(object.temItemIndex-1));
            if(nameItem) {
                nameItem.className = "mouseOver";
                var preItem = document.getElementById(object.itemPrefix+"Item_"+object.temItemIndex);
                if(preItem) preItem.className = "mouseOut";
                object.temItemIndex--;
            }
        }return false;
        // enter
        case 13: {
            if(object.temItemIndex!=-1) {
                object.populateItems(document.getElementById(object.itemPrefix+"Item_"+object.temItemIndex));
            }
            object.afterEnter();
            object.temItemIndex = -1;
            object.submitBtn.click();
        }return false;
        //tab
        case 9:{
            }return false;
    }
    //
    if (object.inputField.value.length > 0) {
        object.filterItems(object.items);
    } else {
        object.clearItems();
    }
}

function autoCompleteSetOffsets() {
    var end = this.inputField.offsetWidth;
    var left = this.calculateOffset(this.inputField, "offsetLeft");
    var top = this.calculateOffset(this.inputField, "offsetTop") + this.inputField.offsetHeight;
    var d = $(this.id);
    d.setStyle({
        left:left+"px",
        top:top+"px",
        zIndex:888
    })
    var w = d.getWidth();
    var h = d.getHeight();
    if(!this.actShadow) {
        this.actShadow = new Element('iframe', {
            id: this.id+"Shadow",
            width:w+"px",
            height:h+"px"
        });
        this.actShadow.setAttribute("frameBorder", "0");
        this.actShadow.setAttribute("marginheight", "0");
        this.actShadow.setAttribute("marginwidth", "0");
        this.actShadow.setAttribute("scrolling", "no");
        document.body.appendChild(this.actShadow);
    }
    this.actShadow.setStyle({
        left:left+"px",
        top:top+"px",
        zIndex:887,
        position: "absolute"
    });
    this.actShadow.style.display = "";
}

function autoCompleteCalculateOffest(field, attr) {
    var offset = 0;
    while(field) {
        offset += field[attr];
        field = field.offsetParent;
    }
    return offset;
}

function autoCompletePopulateItems(row) {
    var na = this.cleanTail(this.inputField.value.replace(/\\n/g, ""));
    if(na.lastIndexOf(" ")!=-1) {
        na = na.substring(0, na.lastIndexOf(" ")+1);
    }else if(na.lastIndexOf(",")!=-1) {
        na = na.substring(0, na.lastIndexOf(",")+1);
    }else {
        na = "";
    }
    this.inputField.value = na+this.items[parseInt(row.name)]+" ";
    this.clearItems();
}


/* global var */
var DEFAULT_C_MODE = "2";
var DEFAULT_S_MODE = "2";
var DURATION_1 = 300000;
var DURATION_2 = 3000;
var DURATION_3 = 10000;
var USER_DEF_AVATAR = "_d_u";
var GROUP_DEF_AVATAR = "_d_g";


/* on document mouse up */
window.onmouseupListeners = [];
window.addOnMouseUpListener = function(listener) {
    window.onmouseupListeners[window.onmouseupListeners.length] = listener;
}

function initOnMouseUp() {
    window.document.onmouseup = function() {
        for(var i=0; i<window.onmouseupListeners.length;i++) {
            var func = window.onmouseupListeners[i];
            func.call();
        }
    }
}
/* on document mouse up */


window.globalObjects = [];
window.registerGlobalObject = function(object) {
    window.globalObjects[object.id] = object;
}

String.prototype.trim = function() {
    return this.replace(/^\s*/,"").replace(/\s*$/,"");
}

String.prototype.replaceAll = function(AFindText,ARepText,i){ 
    raRegExp = new RegExp(AFindText,"g"+i);
    return this.replace(raRegExp,ARepText)
}

Array.prototype.removeItem = function(index) {
    if(index==0) {
        this.shift();
        return this;
    }else if(index>=this.length || index<0) {
        return this;
    }else {
        return this.slice(0, index).concat(this.slice(index+1, this.length));
    }
}

function switchStyle(s) {
    if (!document.getElementsByTagName) return;
    var el = document.getElementsByTagName("link");
    for (var i = 0; i < el.length; i++ ) {
        if (el[i].getAttribute("rel").indexOf("style") != -1 && el[i].getAttribute("title")) {
            el[i].disabled = true;
            if (el[i].getAttribute("title") == s) el[i].disabled = false;
        }
    }
}
//
function switchBox(editor, switcher){
    new Effect[Element.visible(editor) ?
    'BlindUp' : 'BlindDown'](editor, {
        duration: 0.25
    });
    new Effect[Element.visible(switcher) ?
    'BlindUp' : 'BlindDown'](switcher, {
        duration: 0.25
    });
}

function switchBox2(box1, box2){
    new Effect[Element.visible(box1) ?
    'BlindUp' : 'BlindDown'](box1, {
        duration: 0.25
    });
    new Effect[Element.visible(box2) ?
    'BlindUp' : 'BlindDown'](box2, {
        duration: 0.25
    });
}

// 
function encodeAdSyntax() {
    var p_what = "";
    // encode tags
    var p_tags = $F('ad_tags').trim();
    if(p_tags!='') {
        p_tags = "tag:("+p_tags+") ";
        p_what += p_tags;
    }
    // encode title
    var p_url = $F('ad_url').trim();
    if(p_url!='') {
        p_url = "url:("+p_url+") ";
        p_what += p_url;
    }
    // encode title
    var p_title = $F('ad_title').trim();
    if(p_title!='') {
        p_title = "title:("+p_title+") ";
        p_what += p_title;
    }
    // encode text
    var p_text = $F('ad_text').trim();
    if(p_text!='') {
        p_text = "text:("+p_text+") ";
        p_what += p_text;
    }
    // encode comments
    var p_comments = $F('ad_comments').trim();
    if(p_comments!='') {
        p_comments = "c:("+p_comments+") ";
        p_what += p_comments;
    }
    // encode highlights
    var p_highlights = $F('ad_highlights').trim();
    if(p_highlights!='') {
        p_highlights = "h:("+p_highlights+") ";
        p_what += p_highlights;
    }
    // encode anywhere
    var p_anywhere = $F('ad_anywhere').trim();
    if(p_anywhere!='') {
        p_anywhere = p_anywhere+" ";
        p_what += p_anywhere;
    }
  
    // encode anywhere 2
    var p_anywhere_2 = $F('ad_anywhere_2').trim();
    if(p_anywhere_2!='') {
        p_anywhere_2 = "\""+p_anywhere_2+"\" ";
        p_what += p_anywhere_2;
    }
  
    // encode nowhere
    var p_nowhere = $F('ad_nowhere').trim();
    if(p_nowhere!='') {
        p_nowhere = "-("+p_nowhere+")";
        p_what += p_nowhere;
    }
    return p_what;
}

function decodeAdSyntax(whatID) {
    var p_what = $F(whatID).trim();
    // decode tags
    var re = new RegExp(/tags?:\([^\)]*\)/i);
    var t_match_a = p_what.match(re);
    if(t_match_a) {
        var t_match_str = t_match_a[0];
        p_what = p_what.replace(t_match_str,'');
        var p_tags = t_match_str.substring(t_match_str.indexOf(':(')+2, t_match_str.length-1);
        $('ad_tags').value = p_tags.trim();
    }else {
        $('ad_tags').value = "";
    }
  
    // decode title
    var re = new RegExp(/titles?:\([^\)]*\)/i);
    var t_match_a = p_what.match(re);
    if(t_match_a) {
        var t_match_str = t_match_a[0];
        p_what = p_what.replace(t_match_str,'');
        var p_title = t_match_str.substring(t_match_str.indexOf(':(')+2, t_match_str.length-1);
        $('ad_title').value = p_title.trim();
    }else {
        $('ad_title').value = "";
    }
  
    // decode text
    var re = new RegExp(/text?:\([^\)]*\)/i);
    var t_match_a = p_what.match(re);
    if(t_match_a) {
        var t_match_str = t_match_a[0];
        p_what = p_what.replace(t_match_str,'');
        var p_text = t_match_str.substring(t_match_str.indexOf(':(')+2, t_match_str.length-1);
        $('ad_text').value = p_text.trim();
    }else {
        $('ad_text').value = "";
    }
  
    // decode url
    var re = new RegExp(/url:\([^\)]*\)/i);
    var t_match_a = p_what.match(re);
    if(t_match_a) {
        var t_match_str = t_match_a[0];
        p_what = p_what.replace(t_match_str,'');
        var p_url = t_match_str.substring(t_match_str.indexOf(':(')+2, t_match_str.length-1);
        $('ad_url').value = p_url.trim();
    }else {
        $('ad_url').value = "";
    }
  
    // decode comments
    var re = new RegExp(/c:\([^\)]*\)/i);
    var t_match_a = p_what.match(re);
    if(t_match_a) {
        var t_match_str = t_match_a[0];
        p_what = p_what.replace(t_match_str,'');
        var p_comments = t_match_str.substring(t_match_str.indexOf(':(')+2, t_match_str.length-1);
        $('ad_comments').value = p_comments.trim();
    }else {
        $('ad_comments').value = "";
    }
  
    // decode highlights
    var re = new RegExp(/h:\([^\)]*\)/i);
    var t_match_a = p_what.match(re);
    if(t_match_a) {
        var t_match_str = t_match_a[0];
        p_what = p_what.replace(t_match_str,'');
        var p_highlights = t_match_str.substring(t_match_str.indexOf(':(')+2, t_match_str.length-1);
        $('ad_highlights').value = p_highlights.trim();
    }else {
        $('ad_highlights').value = "";
    }
  
    // decode nowhere
    var re = new RegExp(/\-\([^\)]*\)/i);
    var t_match_a = p_what.match(re);
    if(t_match_a) {
        var t_match_str = t_match_a[0];
        p_what = p_what.replace(t_match_str,'');
        var p_nowhere = t_match_str.substring(t_match_str.indexOf('-(')+2, t_match_str.length-1);
        $('ad_nowhere').value = p_nowhere.trim();
    }else {
        $('ad_nowhere').value = "";
    }
  
    // decode phrase
    var re = new RegExp(/\"[^\"]*\"/i);
    var t_match_a = p_what.match(re);
    if(t_match_a) {
        var t_match_str = t_match_a[0];
        p_what = p_what.replace(t_match_str,'');
        var p_anywhere_2 = t_match_str.substring(t_match_str.indexOf('"')+1, t_match_str.length-1);
        $('ad_anywhere_2').value = p_anywhere_2.trim();
    }else {
        $('ad_anywhere_2').value = "";
    }
  
    // decode anywhere
    var t_match_str = p_what.trim();
    $('ad_anywhere').value = t_match_str;

}
/*search box*/

function calculateOffest(field, attr) {
    var offset = 0;
    while(field) {
        offset += field[attr];
        field = field.offsetParent;
    }
    return offset;
} 

function initSideBarBoxSwitchAble() {
    var index = 0;
    var header = $("sideBarBoxTitle_"+index);
    var eocMark = $("eocMark_"+index);
    var content = $("sideBarBoxContent_"+index);
    while(header) {
        header.onclick = switchSideBarBox;
        if(content.style.display=="") {
            eocMark.className += " expand";
        }else {
            eocMark.className += " collapse";
        }
        index++;
        header = $("sideBarBoxTitle_"+index);
        eocMark = $("eocMark_"+index);
        content = $("sideBarBoxContent_"+index);
    }
}

function switchSideBarBox() {
    var index = this.id.split("_")[1];
    var content = $("sideBarBoxContent_"+index);
    new Effect[Element.visible(content) ?
    'BlindUp' : 'BlindDown'](content, {
        duration: 0.25
    });
    var eocMark = $("eocMark_"+index);
    if(content.style.display=="") {
        eocMark.className = eocMark.className.replace("expand", "collapse");
    }else {
        eocMark.className = eocMark.className.replace("collapse", "expand");
    }
}

/* cookie */
function getCookieDomain() {
    return D_DOMAIN;
}
function Cookie(document, name, hours, path, domain, secure) {
    this.$document = document;
    this.$name = name;
    if(hours)
        this.$expiration = new Date((new Date).getTime() + hours*3600000);
    else this.$expiration = null;
    if(path) this.$path = path; else this.$path = null;
    if(domain) this.$domain = domain; else this.$domain = null;
    if(secure) this.$secure = secure; else this.$secure = null;
}

Cookie.prototype.store = function() {
    var cookieval = "";
    for(var prop in this) {
        if((prop.charAt(0) =='$' ) || ((typeof this[prop]) == 'function' ))
            continue;
        if(cookieval != "") cookieval += '|';
        cookieval += prop + ':' + escape(this[prop]);
    }
  
    var cookie = this.$name + '=' + cookieval;
    if(this.$expiration)
        cookie += '; expires=' + this.$expiration.toGMTString();
    if(this.$path) cookie += '; path=' + this.$path;
    if(this.$domain) cookie += '; domain=' + this.$domain;
    if(this.$secure) cookie += '; secure';
    this.$document.cookie = cookie;
}

Cookie.prototype.load = function() {
    var allcookies = this.$document.cookie;
    if(allcookies == '') return false;
  
    var start = allcookies.indexOf(this.$name + '=');
    if(start==-1) return false;
    start += this.$name.length + 1;
    var end = allcookies.indexOf(';', start);
    if(end==-1) end = allcookies.length;
    var cookieval = allcookies.substring(start, end);
  
    var a = cookieval.split('|');
    for(var i=0; i<a.length; i++){
        a[i] = a[i].split(':');
    }
  
    for(var i=0; i<a.length; i++) {
        this[a[i][0]] = unescape(a[i][1]);
    }
  
    return true
}

Cookie.prototype.remove = function() {
    var cookie;
    cookie = this.$name + '=';
    if(this.$path) cookie += '; path=' + this.$path;
    if(this.$domain) cookie += '; domain=' + this.$domain;
    cookie += '; expires=Fri, 02-Jan-1970 00:00:00 GMT';
    this.$document.cookie = cookie;
}
/* cookie */

function report() {
    var w = window.open("/report/index", null, "width=380,height=500, left=0, top=0, status=no,resizable=no");
}

function getInstallURL(aEvent) {

    // The event target might be the link itself or one of its children
    var target = aEvent.target;
    while (target && !target.href)
        target = target.parentNode;

    return target && target.href;
}


function install( aEvent, extName, iconURL, extHash) {
    if (aEvent.altKey || !window.InstallTrigger)
        return true;

    var url = getInstallURL(aEvent);

    if (url) {

        var params = new Array();

        params[extName] = {
            URL: url,
            IconURL: iconURL,
            toString: function () {
                return this.URL;
            }
        };
        // Only add the Hash param if it exists.
        //
        // We optionally add this to params[] because installTrigger
        // will still try to compare a null hash as long as the var is set.
        if (extHash) {
            params[extName].Hash = extHash;
        }

        InstallTrigger.install(params);

        return false;
    }
    return true;
}

function flashNotice(content, noticerID, duration) {
    if(typeof(noticerID)=="undefined") noticerID = "noticeBar";
    if(typeof(duration)=="undefined") duration = 10000;
    var noticer = $(noticerID);
    if(noticer) {
        noticer.style.display = "";
        setTimeout("$('"+noticerID+"').hide()",duration);
        var c = noticer.getElementsByClassName('contentb')[0];
        c.innerHTML = content;
    }
}

function flashNotice2(content, noticerID, className, duration) {
    if(typeof(noticerID)=="undefined") noticerID = "tailNoticer";
    if(typeof(className)=="undefined") className = "tailNoticer";
    if(typeof(duration)=="undefined") duration = DURATION_1;
    var noticer = $(noticerID);
    if(noticer) {
        noticer.style.display = "";
        noticer.innerHTML = content;
        noticer.className = className;
        noticer.onclick = quickFadeFlashNoticer;
        setTimeout("new Effect.Fade('"+noticerID+"')",duration);
    }
}

function hideNotice2(noticerID) {
    if(typeof(noticerID)=="undefined") noticerID = "tailNoticer";
    var noticer = $(noticerID);
    if(noticer) noticer.style.display = "none";
}

function quickFadeFlashNoticer() {
    setTimeout("new Effect.Fade('"+this.id+"')",DURATION_2);
}
function showCentralNoticer(content, noticerID) {
    if(typeof(noticerID)=='undefined') noticerID = "centralNoticer";
    if(typeof(content)=='undefined') content = "Processing...";
    var noticerBox = $(noticerID+"_box");
    var noticerContent = $(noticerID+"_content");
    if(!noticerBox) {
        noticerBox = document.createElement("div");
        noticerBox.className = "centralNoticerBox";
        noticerBox.id = noticerID+"_box";
        noticerContent = document.createElement("div");
        noticerContent.id = noticerID+"_content";
        noticerContent.className = "centralNoticerContent";
        noticerBox.appendChild(noticerContent);
        document.body.appendChild(noticerBox);
    }
    //TODO
    noticerContent.innerHTML = content;
    var width = document.body.offsetWidth;
    var left = width/2 - $(noticerID+"_box").getWidth()/2;
    noticerBox.show();
    noticerBox.setStyle({
        "left":left+"px",
        "top":0
    });
  
}
function updateCentralNoticer(content, noticerID) {
    if(typeof(noticerID)=='undefined') noticerID = "centralNoticer";
    var noticerBox = $(noticerID+"_content");
    noticerBox.innerHTML = content;
}
function hideCentralNoticer(delay) {
    if(typeof(noticerID)=='undefined') noticerID = "centralNoticer";
    if(typeof(delay)=='undefined') delay = 1;
    delay = delay*1000;
    $(noticerID+"_box").style.display="none";
}

function EasySignin(id){
    if(!$(id+"_switcher")) {
        this.valid = false;
        return false;
    }
    this.valid = true;
    this.id = id;
    this.enableEasySignin = function() {
        var switcher = $(this.id+"_switcher");
        switcher.onclick = this.switchEasySignin;
        return false;
    }
  
    this.disableEasySignin = function() {
        var switcher = $(this.id+"_switcher");
        switcher.onclick = null;
        return true;
    }
  
    this.switchEasySignin = function() {
        var id = this.id.split("_")[0];
        var box = $(id+"_box");
        if(box.style.display=="") {
            box.style.display="none";
        }else {
            var switcher = $(id+"_switcher");
            var end = switcher.offsetWidth;
            var left = calculateOffest(switcher, "offsetLeft");
            var top = calculateOffest(switcher, "offsetTop") + switcher.offsetHeight;
            box.style.left = left-30 + "px";
            box.style.top = top + "px";
            box.style.display=""
            $(id+"_username").focus();
        }
        return false;
    }
  
    this.initEasySinginBox = function() {
        var id = this.id;
        var box = document.createElement("div");
        box.style.display = "none";
        box.id = id+"_box";
        box.className = "signinBox";
        var top = document.createElement("div");
        top.className = "top";
        var closer = document.createElement("img");
        closer.id = id+"_closer";
        closer.src="/images/v2/closer.gif";
        closer.onclick = this.switchEasySignin;
        top.appendChild(closer);
        var content = document.createElement("div");
        content.className = id+"_content";
        var form = document.createElement("form");
        form.method = "post";
        form.action = "/user_mana2/login";
        var referInfo = document.createElement("input");
        referInfo.name = "referInfo";
        referInfo.value = self.location;
        referInfo.type = "hidden";
        form.appendChild(referInfo);
        var label = document.createElement("label");
        label.innerHTML = DIS_1;
        var input = document.createElement("input");
        input.type = "text";
        input.id= id+"_username";
        input.name = "username";
        input.className = "inputTxt";
        form.appendChild(label);
        form.appendChild(input);
        label = document.createElement("label");
        label.innerHTML = DIS_2;
        input = document.createElement("input");
        input.type = "password";
        input.id= id+"_password";
        input.name = "password";
        input.className = "inputTxt";
        form.appendChild(label);
        form.appendChild(input);
        input = document.createElement("input");
        input.type = "submit";
        input.value = DIS_3;
        input.id = id+"_submit";
        input.className = "diigoBtn";
        form.appendChild(input);
        content.appendChild(form);
        box.appendChild(top);
        box.appendChild(content);
        var bottom = document.createElement("div");
        bottom.className = "bottom";
        box.appendChild(bottom);
        document.body.appendChild(box);
    }
    return true;
}

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.isUrl2 = /^([a-z]+:\/\/)?([a-z0-9.]+)(:[0-9]+)?(\/[a-z0-9+&@#\/%=~_|!:,.;]*)?(\?[a-z0-9+&@#\/%=~_|!:,.;]*)?$/i;
    this.IsEmail = function (email) {
        re = this.isEmail;
        return (re.test(email.trim()));
    };
    this.IsEmail2 = function (email) {
        re = this.isEmail2;
        return (re.test(email.trim()));
    };
    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.trim()));
    };
    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))
    }
    this.IsUrl2 = function(url){
        re = this.isUrl2;
        return (re.test(url));
    }
};

/*-------------------------------------------
 * float tip
 *------------------------------------------*/
function appendTip(tipperID, content, position, offsetX, offsetY) {
    var tipper = $(tipperID);
    tipper.content = content;
    tipper.tipPosition = position;
    tipper.offsetX = offsetX;
    tipper.offsetY = offsetY;
    tipper.onmouseover = showFloatTip;
    tipper.onmouseout = hideFloatTip;
}

function showFloatTip() {
    var floatTipID = "floatTip";
    var floatTip = getFloatTip(floatTipID);
    floatTip.innerHTML = "<p>"+this.content+"</p>";
    setFloatTipOffsets(this, floatTip, this.tipPosition, this.offsetX, this.offsetY);
    floatTip.style.display = "block";
}
function hideFloatTip() {
    var floatTipID = "floatTip";
    var floatTip = getFloatTip(floatTipID);
    floatTip.style.display = "none";
}
function getFloatTip(floatTipID) {
    var floatTip = $(floatTipID);
    return floatTip ? floatTip : createFloatTip(floatTipID);
}
function createFloatTip(floatTipID) {
    var box = document.createElement("div");
    box.id = floatTipID;
    box.className = box.id;
    box.style.display = "none";
    document.body.appendChild(box);
    return box;
}
function setFloatTipOffsets(tipper, floatTip, position, offsetX, offsetY) {
    var width = tipper.offsetWidth;
    var height = tipper.offsetHeight;
    var margin = 2;
    if(!offsetX){
        var offsetX = 0;
    }
    if(!offsetY){
        var offsetY = 0;
    }
    var left;
    var top;
    switch(position) {
        case "top": {
            left = calculateOffest(tipper, "offsetLeft");
            bottom = calculateOffest(tipper, "offsetTop")+margin;
            floatTip.style.left = left+offsetX + "px";
            floatTip.style.bottom = bottom+offsetY + "px";
        }break;
        case "right": {
            left = calculateOffest(tipper, "offsetLeft")+width+margin;
            top = calculateOffest(tipper, "offsetTop");
            floatTip.style.left = left+offsetX + "px";
            floatTip.style.top = top+offsetY + "px";
        }break;
        case "bottom": {
            left = calculateOffest(tipper, "offsetLeft");
            top = calculateOffest(tipper, "offsetTop")+height+margin;
            floatTip.style.left = left+offsetX + "px";
            floatTip.style.top = top+offsetY + "px";
        }break;
        case "left": {
            right = calculateOffest(tipper, "offsetLeft")+margin;
            top = calculateOffest(tipper, "offsetTop")+height;
            floatTip.style.right = right+offsetX + "px";
            floatTip.style.top = top+offsetY + "px";
        }break;
    }
}
// size: small, medium, big
function loading(loaderID, size) {
    if(typeof(size)=="undefined") size = "small";
    var loader = $(loaderID);
    loader.innerHTML = "<img src=\"/images/v2/loading_"+size+".gif\" alt=\"loading...\" />";
    loader.style.display = "";
}
function loadComplete(loaderID) {
    var loader = $(loaderID);
    loader.innerHTML = "";
    loader.style.display = "none";
}

function authFailed(){
    self.location = "/sign-out";
}

//function getElementsByClassName(oElm, strTagName, strClassName){
//    var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
//    var arrReturnElements = new Array();
//    strClassName = strClassName.replace(/\-/g, "\\-");
//    var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
//    var oElement;
//    for(var i=0; i<arrElements.length; i++){
//        oElement = arrElements[i];      
//        if(oRegExp.test(oElement.className)){
//            arrReturnElements.push(oElement);
//        }   
//    }
//    return (arrReturnElements)
//}

function doSearch(searchType, ad) {
    if(typeof(searchType)=="undefined") searchType="T";
    var reAll = new RegExp(/^all$/i);
    var reMy = new RegExp(/^my$/i);
    var scope = $F("dSearchScope").trim();
    var keyword = $F("dSearchKeyword").trim();
    var url;
    if(searchType=="T") {
        if(scope=="" || scope.match(reAll)) {
            if(keyword==_GLOBAL_VAR['keywordTip']) return false;
            url = "/tag/"+keyword;
        }else if(scope.match(reMy)){
            if(keyword==_GLOBAL_VAR['keywordTip'])
                url = "/user/"+_GLOBAL_VAR['my_name'];
            else
                url = "/user/"+_GLOBAL_VAR['my_name']+"/"+keyword;
        }else {
            if(keyword==_GLOBAL_VAR['keywordTip'])
                url = "/user/"+scope;
            else
                url = "/user/"+scope+"/"+keyword;
        }
    }else if(searchType=="F") {
        if(keyword==_GLOBAL_VAR['keywordTip'])
            url = "/search/ad="+ad+"&who="+scope+"&what=";
        else
            url = "/search/ad="+ad+"&who="+scope+"&what="+keyword;
    }else {
        return false;
    }
    self.location = url;
    return false;
}
function doFSearch(type) {
    if(typeof(type)=="undefined") type="all";
    var ad = 0;
    if(type=="my") {
        $("dSearchScope").value = "My";
    }else if(type=="all") {
        $("dSearchScope").value = "All";
    }else if(type=="ad") {
        ad = 1;
    }
    doSearch("F", ad);
}

function fillScope(scope) {
    $("dSearchScope").value = scope;
    switchScopeList();
  
}
function switchScopeList() {
    var scopeList = $("scopeList");
    if(scopeList.style.display=="none") {
        scopeList.style.display = ""
        setScopeListOffsets(scopeList);
    }else {
        scopeList.style.display = "none";
    }
    return false;
}

function setScopeListOffsets(scopeList) {
    var who = $("dSearchScope");
    var end = who.offsetWidth;
    var left = calculateOffest(who, "offsetLeft");
    var top = calculateOffest(who, "offsetTop") + who.offsetHeight;
    scopeList.style.left = left + "px";
    scopeList.style.top = top + "px";
}
function blurKeyword() {
}
function focusKeyword() {
}

function setCaretPos(ele, pos) {
    if(ele.createTextRange) {
        /* Create a TextRange, set the internal pointer to
a specified position and show the cursor at this
position
*/
        var range = ele.createTextRange();
        range.move("character", pos);
        range.select();
    } else if(ele.selectionStart >= 0) {
        /* Gecko is a little bit shorter on that. Simply
focus the element and set the selection to a
specified position
*/
        ele.focus();
        ele.setSelectionRange(pos, pos);
    }
}

function loadCusData() {
    var domain = getCookieDomain();
    var cusData = new Cookie(document, "g_cus_data", 240, '/', domain);
    cusData.load();
    return cusData;
}

function switchSearchMoreList() {
    var list = $("searchMore");
    if(list.style.display=="none") {
        list.style.display = ""
        setSearchMoreOffsets(list);
    }else {
        list.style.display = "none";
    }
    return false;
}

function setSearchMoreOffsets(list) {
    var switcher = $("searchMoreLink");
    var end = switcher.offsetWidth;
    var left = calculateOffest(switcher, "offsetLeft");
    var top = calculateOffest(switcher, "offsetTop") + switcher.offsetHeight;
    list.style.left = left-75 + "px";
    list.style.top = top+3 + "px";
}

function flagAsSpammer(flagID) {
    var url = "/spam_mana/mark_spammer?spammer_id="+flagID;
    new Ajax.Request(url,
    {
        asynchronous:true,
        evalScripts:false,
        onComplete:function(request){
            if(request.status=="200") {
                var flag = $("spammerFlag_"+flagID);
                flag.innerHTML = "Spammer reported";
                flag.onclick = null;
            }else {
        //alert(request.status);
        }
        }
    });
    return false;
}

/* load user's group */
function cLoadUserGroups() {
    var url = "/group_mana/load_groups?u_name="+_GLOBAL_VAR['username'];
    new Ajax.Request(url,
    {
        asynchronous:true,
        evalScripts:false,
        method: "get",
        onComplete:function(request){
            if(request.status=="200") {
                var groups = request.responseText.evalJSON();
                renderGroupsSidebar(groups);
            }else if(request.status=="400") {
            }else {
        }
        }
    });
}

function renderGroupsSidebar(groups) {
    var groupsUL = $("groupsUL");
    if(!groupsUL) return false;
    if(groups.length>0) {
        for(var i=0; i<_diigo_groups.length; i++) {
            var li = document.createElement("li");
            li.innerHTML = "<a href=\""+GROUP_HOST+"/groups/"+_diigo_groups[i]['g_name']+"\">"+_diigo_groups[i]['display_name']+"</a>";
            li.id = "group_"+i;
            groupsUL.appendChild(li);
        }
        $("groupCount").innerHTML = _diigo_groups.length;
    }else {
        $("groupCount").innerHTML = 0;
    }
}

/* load recommend user */
function cLoadRecommendUsersByUser() {
    var username = _GLOBAL_VAR['username'];
    var url="/recommend/user_by_user?username="+username;
    new Ajax.Request(url,
    {
        asynchronous:true,
        evalScripts:false,
        onComplete:function(request){
            if(request.status=="200") {
                $("recommendUserHolder").innerHTML = request.responseText;
                if($F("rUserCount")>0) $("rUserList").style.display = "";
            }
        }
    });
}
/* load recommend user */

/*-------------------------------------------------
 *  markUserStatus
 *------------------------------------------------*/
function markUserStatus() {
    var usernameEls = $("main").select('.dUserName');
    var usernames = [];
    usernameEls.each(function(u) {
        usernames.push(u.getAttribute("username")||"")
    });
    var url="/site/check_user_status";
    var params = "json_infos="+usernames.toJSON();
    new Ajax.Request(url,
    {
        asynchronous:true,
        evalScripts:false,
        method:'get',
        onComplete:function(request){
            checkUserStatusCompleted(request, usernameEls)
        },
        parameters:params
    });
}

function checkUserStatusCompleted(request, usernameEls) {
    if(request.status=="200") {
        var status = request.responseText.evalJSON();
        usernameEls.each(function(u) {
            var username = u.getAttribute("username") || "";
            var s = status[username];
            doMarkUserStatus(u, username, s);
        });
    }
}
function doMarkUserStatus(el, username, status) {
    try{
        if(status==1) {
            el.style.background = "url(/images/online_status.gif) no-repeat scroll left -25px";
        }else {
            el.style.background = "url(/images/online_status.gif) no-repeat scroll left top";
        }
        el.style.paddingLeft = "11px";
        el.style.width = "37px";
    }catch(e) {}
}


function focusInputTxt(el){
    el.className += ' inputFocus';
}

function blurInputTxt(el){
    el.className = el.className.replace(' inputFocus', '');
}
function getTextSize(text, el){
    el.innerHTML = text.escapeHTML().replace(/ /g, '&nbsp;');
    return el.offsetWidth;
}


/*======================================== 
 * tag cloud
 *
 *========================================*/
function tagsSortBy(sortType) {
    var cusData = loadCusData();
    cusData['tag_cloud_options'] = sortType+_GLOBAL_VAR['userTagsOpt'].viewType;
    cusData.store();
    self.location.reload();
}
function tagsViewAs(viewType) {
    if(viewType=="0") {
        $("userTagsUL").className = "tagCloud";
        $("viewType_0").className = "current";
        $("viewType_1").className = "";
    }else {
        $("userTagsUL").className = "tagList";
        $("viewType_0").className = "";
        $("viewType_1").className = "current";
    }
    _GLOBAL_VAR['userTagsOpt'].viewType = viewType;
    var cusData = loadCusData();
    cusData['tag_cloud_options'] = _GLOBAL_VAR['userTagsOpt'].sortType+viewType;
    cusData.store();
}

//function initTagsCrumb() {
//    _GLOBAL_VAR["tagsCrumbHint"] = "filter by tags, space-separated";
//    var tagsCrumb = $("tagsCrumb");
//    if(!tagsCrumb){
//        return false;
//    }
//    tagsCrumb.innerHTML = "";
//    var popupTag = document.createElement("ul");
//    popupTag.id="popupTag";
//    popupTag.className="autoUL";
//    popupTag.style.display = "none";
//    document.body.appendChild(popupTag);
//    var form = document.createElement("form");
//    form.style.display = "inline";
//    var input = document.createElement("input");
//    var tagsCrumbSizer = document.createElement("div");
//    if(!_GLOBAL_VAR["tagsCrumb"]){
//        _GLOBAL_VAR["tagsCrumb"]="";
//    }
//    input.type = "text";
//    input.value = _GLOBAL_VAR["tagsCrumb"].blank() ? _GLOBAL_VAR["tagsCrumbHint"] : _GLOBAL_VAR["tagsCrumb"];
//    if(input.value==_GLOBAL_VAR["tagsCrumbHint"]){
//        input.className="blurNoTag";
//    }
//    input.onfocus = function(){
//        this.className = "focus";
//        if(this.value==_GLOBAL_VAR["tagsCrumbHint"]){
//            this.value="";
//        }
//        else{
//            this.value = this.value.trim()+" ";
//        }
//    };
//    input.onmouseover = function(){
//        this.className += " mouseover";
//    };
//    input.onmouseout = function(){
//        this.className = this.className.replace(/\s?mouseover/g, "");
//    }
//    input.id = "tagsCrumbInput";
//    input.maxLength = 255;
//    input.setAttribute("autocomplete", "off");
//    var submit = document.createElement("input");
//    submit.type = "submit";
//    submit.style.display = "none";
//    submit.id = "tagCrumbSubmit";
//
//    form.onsubmit = function() {
//        var url = self.location.href;
//        if(url.indexOf("community/site")!=-1) {
//            var u = url.split("?");
//            var p = u[0];
//            var q = u[1] || '';
//            self.location = p.substring(0, p.lastIndexOf("/")+1) + encodeURIComponent($F("tagsCrumbInput").trim()) + (q.blank() ? '' : '?'+q);
//        }else {
//            var t = _GLOBAL_VAR['tag_tail_tab'] || '';
//            if (_GLOBAL_VAR['username']) {
//                self.location = "/user/"+_GLOBAL_VAR['username']+"/"+encodeURIComponent($F("tagsCrumbInput").trim()) + t;
//            }else {
//                self.location = "/tag/"+encodeURIComponent($F("tagsCrumbInput").trim()) + t;
//            }
//        }
//        return false;
//    }
//
//    form.appendChild(input);
//    form.appendChild(submit);
//
//    tagsCrumbSizer.className = "tagsCrumbSizer";
//    tagsCrumbSizer.style.position = "absolute";
//    tagsCrumbSizer.style.visibility = "hidden";
//    tagsCrumbSizer.top = 0;
//    tagsCrumbSizer.right = 0;
//    tagsCrumbSizer.id = "tagsCrumbSizer";
//
//    tagsCrumb.appendChild(tagsCrumbSizer);
//
//    input.style.width = getTextSize(input.value, $("tagsCrumbSizer")) + 30 + "px";
//
//    tagsCrumb.appendChild(form);
//}

function changeMonth(month){     
    var month = $("month").value
    var old_day = $("day").value
    if(month == 0) return;
    var day_max_index = 31;
    switch(month){
        case "1":
        case "3":
        case "5":
        case "7":
        case "8":
        case "10":
        case "12":
            day_max_index = 31
            break;
        case "2":
            day_max_index = 28
            break;
        case "4":
        case "6":
        case "9":
        case "11":
            day_max_index = 30
            break;
    }
    $("day").innerHTML = "";
    var option = document.createElement("option")
    option.value = 0;
    option.innerHTML = "Day:";
    $("day").appendChild(option);
    for(var i = 1;i <= day_max_index;i++){
        var option = document.createElement("option")
        option.value = i;
        option.innerHTML = i;
        $("day").appendChild(option);
    }
    $("day").value = old_day;
}

function appendTip(tipperID, content, position, offsetX, offsetY) {
    var tipper = $(tipperID);
    tipper.content = content;
    tipper.tipPosition = position;
    tipper.offsetX = offsetX;
    tipper.offsetY = offsetY;
    tipper.onmouseover = showFloatTip;
    tipper.onmouseout = hideFloatTip;
}
var BrowserVersion={
    IE:     !!(window.attachEvent && !window.opera),
    Opera:  !!window.opera,
    WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
    Gecko:  navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1,
    MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/),
    getIEVersion: function(){
        var rv = null;
        if (navigator.appName == 'Microsoft Internet Explorer'){
            var ua = navigator.userAgent;
            var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
            if (re.exec(ua) != null)
                rv = parseFloat( RegExp.$1 );
        }
        return rv
    },
    isIE6:  function(){
        var version = BrowserVersion.getIEVersion();
        return version && BrowserVersion.getIEVersion() <= 6
    }
}

///*==================================
// * CONSTANTS
// *
// *==================================*/
//var WORD_1 = "Title can't be empty";
//var WORD_2 = "Tags can't be empty";
//var WORD_3 = "Processing...";
//var WORD_4 = "Process failed! try again later";
//var WORD_5 = "Delete it?";
//var WORD_6 = "Delete it(s)?";
//var WORD_7 = "Batch Share To Done";
//var WORD_8 = "Caution: your inputs can be seen by all Diigo members visiting the web page";
//var WORD_9 = "No Comment No Post!";
//var WORD_10 = "Remove this annotation?";
//var WORD_11 = "Cant' do this";
//var WORD_12 = "Expand All";
//var WORD_13 = "Collapse All";
//var WORD_14 = "Comment";
//var WORD_15 = "Collapse";
//var WORD_16 = "Expand";
//var WORD_17 = "Edit";
//var WORD_18 = "Forward";
//var WORD_19 = "Delete";
//var WORD_20 = "Forward";
//var WORD_21 = "Unread";
//var WORD_22 = "Read";
//var WORD_23 = "Public";
//var WORD_24 = "Private";
//var WORD_25 = "Share to";
//var WORD_26 = "Alert";
//var WORD_27 = "Remove alert";
//var WORD_28 = "alert";
//var WORD_29 = "Add to lists";
//var WORD_30 = "Edit Tags";
//var WORD_31 = "Up";
//var WORD_32 = "Down";
//var WORD_33 = "Top";
//var WORD_34 = "Bottom";
//var WORD_35 = "Remove from list";
//
///* display wording */
//var DIS_1 = "Username / Email";
//var DIS_2 = "Password";
//var DIS_3 = "Sign In";
//var DIS_4 = "Template";
//var DIS_5 = "Choose your favor";
//var DIS_6 = "Collapse";
//var DIS_7 = "Expand";
//var DIS_8 = "Expand All";
//var DIS_9 = "Collapse All";
//var DIS_10 = "Processing...";
//var DIS_11 = "All your del.icio.us tags will be imported in Diigo. In addition, you can set optional tag(s) to your del.icio.us bookmarks."
//var DIS_12 = "Highlight and sticky notes";
//var DIS_13 = "Search Bookmarks...";
//var DIS_14 = "include url and title";
//var DIS_15 = "include url, title and tag";
//var DIS_16 = "include url, title, tag, comments and sticky notes";
//var DIS_17 = "include url, title, tag, comments and sticky notes";
//var DIS_18 = "same as del.icio.us exporting format";
//var DIS_19 = "Title can't be empty.";
//var DIS_20 = "Please select a category.";
//var DIS_21 = "Incorrect url format.";
//
//
///* alert wording */
//var ALE_1 = "Username can't be empty.";
//var ALE_2 = "Password can't be empty.";
//var ALE_3 = "Incorrect username format.";
//var ALE_4 = "Sorry, the username \"?\" is taken.";
//var ALE_5 = "Great, the username \"?\" is available.";
//var ALE_6 = "Incorrect password format.";
//var ALE_7 = "The retyped Password does not match.";
//var ALE_8 = "Incorrect email format.";
//var ALE_9 = "Sorry, the email \"?\" is already in use under another username.";
//var ALE_10 = "Great, the email \"?\" is available.";
//var ALE_11 = "Your input was not correct.";
//var ALE_12 = "You need to accept the Terms and Conditions to complete your registration.";
//var ALE_13 = "Delete picture Done!";
//var ALE_14 = "Real Name can't be empty.";
//var ALE_15 = "Save general informations Done!";
//var ALE_16 = "Change password Done!";
//var ALE_17 = "Incorrect url format.";
//var ALE_18 = "Incorrect title format.";
//var ALE_19 = "Incorrect tags format.";
//var ALE_20 = "No bookmark selected";
//var ALE_21 = "Remove this comment?";
//var ALE_22 = "Remove this annotation?";
//var ALE_23 = "Remove this sticky note?";
//var ALE_24 = "No Comment No Post!";
//var ALE_25 = "Want to delete this item from this group?";
//var ALE_26 = "Delete bookmark(s)?";
//var ALE_27 = "Share to Group\"?\" Done!";
//var ALE_28 = "Share to Group\"?\" failed!";
//var ALE_29 = "Oops, Current export job failed! Please try again later or ?";
//var ALE_30 = "Delete this config?";
//var ALE_31 = "Remove selected contact(s)?";
//var ALE_32 = "Remove selected list(s)?";
//var ALE_33 = "Remove from list?";
//var ALE_34 = "Added to List Done!";
//var ALE_35 = "Added to List failed!";
//var ALE_36 = "No list selected";
//var ALE_37 = "Selected links have been shared to the group \"?\".";
//var ALE_38 = "Remove this friend?";
//var ALE_39 = "Remove this contact from the list?";
//var ALE_40 = "Delete the post?"
//
//var GROUP_ALE_1 = "&nbsp;However, please note discussion threads cannot be shared to another group.";
//var GROUP_ALE_2 = "Email notification for this item enabled.";
//var GROUP_ALE_3 = "Email notification for this item disbled.";
//var GROUP_ALE_4 = "Please note discussion threads cannot be shared to another group.";
//var GROUP_ALE_5 = "Enable email alert";
//var GROUP_ALE_6 = "Disable email alert";
//
///* exception */
//var EXC_1 = "Oops, server busy. Please try again later...";
//var EXC_2 = "Sorry, upload picture failed. [1500]";
//var EXC_3 = "Sorry, save general information failed. [1501]";
//var EXC_4 = "Sorry, change password failed. [1502]";
//var EXC_5 = "Sorry, server error. [1503]";
//var EXC_6 = "Oops, bad request. [1400]";
//
///*------------------------*/
//var BL_1 = 'End Point is Invalid';
//var BL_2 = 'Username Can not be empty';
//var BL_3 = 'Password Can not be empty';
//var BL_4 = 'Post Done!';
//var BL_5 = 'Post Failed!';
//var BL_6 = 'No Blog Selected';
//var BL_7 = 'Url is Invalid';
//var BL_8 = 'Convert to public';
//var BL_9 = 'Delete highlight';
//var BL_10 = "All settings are verified. Check to post";
//var BL_11 = "No password stored. Please enter when ready to post";
//var BL_12 = "Your blog settings cannot be verified. Please check";
//var BL_14 = "Your Blogs Saved with Diigo";
//var BL_15 = "Could not find any API for your blog. Click Back to try another blog, or click next to manually configure your blog.";
//var BL_16 = "Valid";
//var BL_17 = "Checking...";
//var BL_18 = "InValid";
//var BL_19 = "&lt;&lt; Need select a blog before post";
//var BL_20 = "&lt;&lt; Need select a blog first";

/* hack CA */
function _popupControl() {}

/*--------------------------
 * get message count
 *-------------------------*/
function getMessageCount() {
    var url = "/message_mana/get_message_count";
    new Ajax.Request(url,
    {
        asynchronous:true,
        evalScripts:false,
        method:"get",
        onComplete:function(request){
            if(request.status=="200") {
                if($("messageCount") != null) $("messageCount").innerHTML = "("+request.responseText+")";
            }
        }
    });
    return false;
}

function aboutDiigoFourm(){
    var w = window.open(ABOUTDIIGOFORUM, null, "width=700,height=500, left=0, top=0, status=1,scrollbars=1,resizable=1");
}

/*--------------------------
 * Bookmark Thumb Up/Down
 * 2008-01-07 by vincent
 *-------------------------*/
function initBookmarkVote(return_zero_count){
    try{
        var link_ids = [];
        _bookmarks.each(function(item){
            link_ids.push(item.link_id);
        })
        var group_id = _bookmarks[0].group_id;
        var url = '/bookmark_mana/bookmark_vote';
        new Ajax.Request(url,
        {
            onLoading:function(request){
                initBookmarkVoteLoading(request)
            },
            onSuccess:function(request){
                initBookmarkVoteComplete(request,return_zero_count)
            },
            parameters:{
                group_id : group_id,
                link_ids : link_ids.join(",")
            }
        }
        );
        return false;
    }catch(e) {
        alert(e);
    }
}

function initBookmarkVoteLoading(request){
    
}

function initBookmarkVoteComplete(request,return_zero_count){
    var bm_votes = request.responseText.evalJSON();
    bm_votes.each(function (item){
        bm_vote_item = $("bm_vote_"+item.link_id);
        bm_vote_item.link_id = item.link_id;
        bm_vote_item.group_id = item.group_id;
        if(item.vote_type == 0){// haven't voted yet
            bm_vote_item.addClassName("thumbVote thumbUp");
            bm_vote_item.observe("click",bmThumbUp);
            bm_vote_item.title = WORD_118;
        }else{
            bm_vote_item.addClassName("thumbVote thumbUped");
        }
        if(return_zero_count){
            $("bm_vote_"+item.link_id+"_count").update(item.thumb_up_count);
        }else if(!return_zero_count && item.thumb_up_count != 0){
            $("bm_vote_"+item.link_id+"_count").update(item.thumb_up_count);
        }
        bm_vote_item.show();
    })
}

function bmThumbUp(){
    bm_vote_item = $("bm_vote_"+this.link_id);
    new Ajax.Request("/bookmark_mana/bm_thumb_up",
    {
        onLoading:function(request){
            bmThumbUpLoading(request)
        },
        onSuccess:function(request){
            bmThumbUpComplete(request)
        },
        parameters:{
            group_id : this.group_id,
            link_id : this.link_id
        }
    });
}

function bmThumbUpLoading(request){
}

function bmThumbUpComplete(request){
    var bm_vote_stas = request.responseText.evalJSON();
    bm_vote_item = $("bm_vote_"+bm_vote_stas.link_id);
    
    bm_vote_item.toggleClassName("thumbUped").stopObserving('click',bmThumbUp);
    $("bm_vote_"+bm_vote_stas.link_id+"_count").update(bm_vote_stas.thumb_up_count);
    new Effect.Highlight("bm_vote_"+bm_vote_stas.link_id);
}

/*-------------------------------------------------
 * Copy to Clipboard
 * http://webchicanery.com/2006/11/14/clipboard-copy-javascript/
 *------------------------------------------------*/
function _copy(text2copy) {
    if (window.clipboardData) {
        window.clipboardData.setData("Text",text2copy);
    } else {
        var flashcopier = 'flashcopier';
        if(!document.getElementById(flashcopier)) {
            var divholder = document.createElement('div');
            divholder.id = flashcopier;
            document.body.appendChild(divholder);
        }
        document.getElementById(flashcopier).innerHTML = '';
        var divinfo = '<embed src="/_clipboard.swf" FlashVars="clipboard='+escape(text2copy)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
        document.getElementById(flashcopier).innerHTML = divinfo;
    }
}

/*---------------------------------------------------
 * Group bookmarks tag search, auto-suggestion
 * -------------------------------------------------*/
function initTagsCrumb() {
    _GLOBAL_VAR["tagsCrumbHint"] = "filter by tags, space-separated";
    var tagsCrumb = $("tagsCrumb");
    if(!tagsCrumb){
        return false;
    }
    tagsCrumb.innerHTML = "";
    var popupTag = document.createElement("ul");
    popupTag.id="popupTag";
    popupTag.className="autoUL";
    popupTag.style.display = "none";
    document.body.appendChild(popupTag);
    var form = document.createElement("form");
    form.style.display = "inline";
    var input = document.createElement("input");
    var tagsCrumbSizer = document.createElement("div");
    if(!_GLOBAL_VAR["tagsCrumb"]){
        _GLOBAL_VAR["tagsCrumb"]="";
    }
    input.type = "text";
    input.value = _GLOBAL_VAR["tagsCrumb"].blank() ? _GLOBAL_VAR["tagsCrumbHint"] : _GLOBAL_VAR["tagsCrumb"];
    if(input.value==_GLOBAL_VAR["tagsCrumbHint"]){
        input.className="blurNoTag";
    }
    input.onfocus = function(){
        this.className = "focus";
        if(this.value==_GLOBAL_VAR["tagsCrumbHint"]){
            this.value="";
        }
        else{
            this.value = this.value.trim()+" ";
        }
    };
    input.onmouseover = function(){
        this.className += " mouseover";
    };
    input.onmouseout = function(){
        this.className = this.className.replace(/\s?mouseover/g, "");
    }
    input.id = "tagsCrumbInput";
    input.maxLength = 255;
    input.setAttribute("autocomplete", "off");
    var submit = document.createElement("input");
    submit.type = "submit";
    submit.style.display = "none";
    submit.id = "tagCrumbSubmit";
    
    form.onsubmit = function() {
        var t = _GLOBAL_VAR['tag_tail_tab'] || '';
        self.location = GROUP_HOST + "/" +_GLOBAL_VAR['group_name']+"/bookmark/tag/"+encodeURIComponent($F("tagsCrumbInput").trim()) + t;
        return false;
    }
    
    form.appendChild(input);
    form.appendChild(submit);
    
    tagsCrumbSizer.className = "tagsCrumbSizer";
    tagsCrumbSizer.style.position = "absolute";
    tagsCrumbSizer.style.visibility = "hidden";
    tagsCrumbSizer.top = 0;
    tagsCrumbSizer.right = 0;
    tagsCrumbSizer.id = "tagsCrumbSizer";
    
    tagsCrumb.appendChild(tagsCrumbSizer);
    
    input.style.width = getTextSize(input.value, $("tagsCrumbSizer")) + 30 + "px";
    
    tagsCrumb.appendChild(form);
}

/*--------------------------------------------
 * Tag Auto Suggestion
 *-------------------------------------------*/
function filterItemsTags(items) {
    this.temItemIndex = -1;
    this.clearItems();
    var size = items.length;
    this.setOffsets();
    var content = this.inputField.value;
    var na = this.inputField.value; //new String(content);
    if(na.lastIndexOf(" ")!=-1) {
        na = na.substring(na.lastIndexOf(" ")+1, na.length);
    }else if(na.lastIndexOf(",")!=-1) {
        na = na.substring(na.lastIndexOf(",")+1, na.length);
    }
    if(na=="" && content=="") return;
    status = content;
    var j = 0;
    var itemRegExp1 = new RegExp("^("+content+").+","i");
    var itemRegExp2 = new RegExp("^("+na+").+","i");
    var itemRegExp = [itemRegExp1, itemRegExp2];
    var statusContent = []
    for(var i = 0; i < size; i++) {
        var itemTxt = this.items[i].tName;
        for(var k=0; k<itemRegExp.length; k++) {
            if(k==1 && (na=="" || na==content)) break;
            if(itemRegExp[k].test(itemTxt)) {
                this.lockSubmit();
                var row = document.createElement("li");
                row.className = "mouseOut";
                row.id = this.itemPrefix+"Item_"+j;
                row.name = i;
                row.object = this;
                row.onclick = function(){
                    this.object.populateItems(this);
                }
                row.onmouseout = function() {
                    this.className='mouseOut';
                };
                row.onmouseover = function() {
                    this.className='mouseOver';this.object.temItemIndex=parseInt(this.name);
                };
                var _txt = new String(itemTxt);
                if(_txt.indexOf(" ")!=-1) _txt="\""+_txt+"\"";
                row.innerHTML = _txt;
                this.completeDiv.appendChild(row);
                j++;
                break;
            }
        }
    }
    status = statusContent.join(",");
    var _item = document.getElementById(this.itemPrefix+"Item_"+(this.temItemIndex+1));
    if(_item) {
        this.completeDiv.style.display = "";
    //_item.className = "mouseOver";
    //this.temItemIndex++;
    }
}
function autoCompletePopulateTag(row) {
    var na = this.cleanTail(this.inputField.value.replace(/\\n/g, ""));
    if(na.lastIndexOf(" ")!=-1) {
        na = na.substring(0, na.lastIndexOf(" ")+1);
    }else if(na.lastIndexOf(",")!=-1) {
        na = na.substring(0, na.lastIndexOf(",")+1);
    }else {
        na = "";
    }
    var _txt = this.items[parseInt(row.name)].tName;
    if(_txt.indexOf(" ")!=-1) _txt="\""+_txt+"\" ";
    this.inputField.value = na+_txt;
    this.clearItems();
}
function initACTag() {
    var autoCompleteTag = new AutoComplete("tagsCrumbInput","popupTag","tagCrumbSubmit");
    autoCompleteTag.filterItems = filterItemsTags;
    autoCompleteTag.populateItems = autoCompletePopulateTag;
    autoCompleteTag.items = _GLOBAL_VAR['tags'];
    autoCompleteTag.turnOn();
}
function blurKeywordACTag() {
    var tagCrumb = $("tagsCrumbInput");
    tagCrumb.className = tagCrumb.className.replace("focus", "");
    if(tagCrumb.value.blank()) {
        if(_GLOBAL_VAR["tagsCrumb"].blank()){
            tagCrumb.value = _GLOBAL_VAR["tagsCrumbHint"]; tagCrumb.className="blurNoTag";
        }
        else{
            tagCrumb.value=_GLOBAL_VAR["tagsCrumb"]
        }
    }
    //else if(tagCrumb.value.trim()!=_GLOBAL_VAR["tagsCrumb"]){tagCrumb.value = _GLOBAL_VAR["tagsCrumb"];}
    tagCrumb.style.width = getTextSize(tagCrumb.value, $("tagsCrumbSizer")) + 30 + "px";
}

/*
 * calculate body dimension
 * keep the left position between min and max
 * args:
 * left: element's left position
 * width: element's width
 */
function fixLeft(left, width){
    var maxP = Element.getDimensions(document.body);
    if((left+width) >= maxP.width){
        left = maxP.width-width;
    }else if(left<0){
        left = 0;
    }
    return left;
}
/*
 * calculate body dimension
 * keep the top position between min and max
 * args:
 * top: element's top position
 * height: element's height
 */
function fixTop(top, height){
    var maxP = Element.getDimensions(document.body);
    if((top+height) >= maxP.height){
        top = maxP.height-height;
    }else if(top<0){
        top = 0;
    }
    return top;
}