
/* 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";
var _GLOBAL_VAR = new Object();
/*------------------------------------------------------*/


function init() {
  for(var i=0; i<window.onloadListeners.length;i++) {
    var func = window.onloadListeners[i];
    func.call();
  }
}

window.onloadListeners = [];
window.addOnLoadListener = function(listener) {
  window.onloadListeners[window.onloadListeners.length] = listener;
}

/* 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 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";
  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);
  }
  var width = document.body.offsetWidth;
  var height = document.body.offsetHeight;
  noticerBox.style.display = "block";
  noticerBox.style.left = width/2 - (noticerBox.offsetWidth/2) + "px";
  noticerContent.innerHTML = content;
  noticerBox.style.top = "160px";
  if(noticerBox.offsetHeight<100) {
    noticerBox.style.height = "100px";
  }
}
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";
  //setTimeout("new Effect.Fade('"+noticerID+"_box')",delay)
}

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.]+)(\/[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));
 }
 };

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, "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 */

function markUserStatus() {
    var usernameEls = document.getElementsByClassName('dUserName');
    var usernames = [];
    usernameEls.each(function(u) {
        Try.these(
            function() {usernames.push(u.name.toLowerCase());},
            function() {usernames.push(u.title.toLowerCase());}
        );
    });
    var url="/show/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
			    }); 
    //console.log(userNames);
}

function checkUserStatusCompleted(request, usernameEls) {
    if(request.status=="200") {
        var status = request.responseText.evalJSON();
        usernameEls.each(function(u) {
            var username = '';
            Try.these(
                function() {username = u.name.toLowerCase();},
                function() {username = u.title.toLowerCase();}               
            );
            var s = status[username];
            doMarkUserStatus(u, username, s);
        });
    }
}

function doMarkUserStatus(el, username, status) {
    try{
    if(status==1) {
        el.style.background = "url(/images/v3/online_status.gif) no-repeat scroll left -27px";
    }else {
        el.style.background = "url(/images/v3/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
 *
 *
 *------------------------------------------------------*/
_GLOBAL_VAR['u_tagCloud'];

function TagCloud(prefix, oriTags, viewAs, sortBy) {
  this.relTag;
  this.username;
  this.tags;
  this.step;
  this.tags1 = oriTags;
  this.tags2 = new Array();
  for(var i=0; i<oriTags.length; i++) {
    this.tags2.push(oriTags[i]);
  }
  this.calcTagCloudClass = tagCloudItemClass;
  this.sortByType = sortBy?sortBy:"1";
  this.viewAsType = viewAs?viewAs:"0";
  this.prefix = prefix;
  this.cloudBox = prefix+"_cloudBox";
  this.viewerBox = prefix+"_viewerBox";
  this.sorterBox = prefix+"_sorterBox";
  this.viewAs = TagCloud_viewAs;
  this.sortBy = TagCloud_sortBy;
  this.renderSorter = TagCloud_renderSorter;
  this.renderViewer = TagCloud_renderViewer;
  this.calcStep = TagCloud_calcStep;
  this.init_u = TagCloud_init_u;
  this.cloudType;
}

/* calculate tag step */
function TagCloud_calcStep(tags, minCount, maxCount) {
  var step = 1;
  var minCount = minCount ? minCount : 1000000;
  var maxCount = maxCount ? maxCount : 0;
  for(var i=0; i< tags.length; i++) {
    var tag = tags[i];
    if(tag.count > maxCount) {
      maxCount = tag.count;
    }
    if(tag.count < minCount) {
      minCount = tag.count;
    }
    step = (maxCount-minCount)/6;
  }
  step = parseInt(step) == 0 ? 1 : parseInt(step);
  return step;
}

/* type: 0-alpha, 1-freq */
function TagCloud_sortBy(type) {
  if(type=="0") {
    this.tags = this.tags1;
  }else {
    this.tags = this.tags2;
    this.tags.sort(function(a, b){
    var count_1 = b.count;
    if(b.tName=="no_tag") count_1 = 0;
    var count_2 = a.count;
    if(a.tName=="no_tag") count_2 = 0;
    return count_1-count_2});
  }
  var cusData = loadCusData();
  cusData['tag_cloud_options'] = type.toString()+this.viewAsType;
  cusData.store();
  this.sortByType = type;
  this.viewAs(this.viewAsType);
}

/* type: 0-cloud, 1-list */
function TagCloud_viewAs(type) {
  var type = type?type:this.viewAsType;
  var box = $(this.cloudBox);
  var content = "";
    if(type=="0") {
      for(var i=0; i<this.tags.length; i++) {
        var tag = this.tags[i];
		var count = tag.count;
		if(tag.tName=="no_tag") count = 0;
        if(tag.tName.indexOf(" ")!=-1) {
          content += "<li><a class='"+this.calcTagCloudClass(count, this.step)+"' href=\"/user/"+this.username+"/"+encodeURIComponent("\""+tag.tName+"\"")+"?tab="+_GLOBAL_VAR['tag_cloud_tab']+"\">"+tag.tName.escapeHTML()+"</a>, </li> ";
        }else {
          content += "<li><a class='"+this.calcTagCloudClass(count, this.step)+"' href=\"/user/"+this.username+"/"+encodeURIComponent(tag.tName)+"?tab="+_GLOBAL_VAR['tag_cloud_tab']+"\">"+tag.tName.escapeHTML()+"</a>, </li> ";
        }
      }
    }else {
      content += "<table class='TabTagList'>";
      for(var i=0; i<this.tags.length; i++) {
        var tag = this.tags[i];
        if(tag.tName.indexOf(" ")!=-1) {
          content += "<tr><td class='TdLeft'>"+tag.count+"</td><td><a href=\"/user/"+this.username+"/"+encodeURIComponent("\""+tag.tName+"\"")+"?tab="+_GLOBAL_VAR['tag_cloud_tab']+"\">"+tag.tName.escapeHTML()+"</a></td></tr>";
        }else {
          content += "<tr><td class='TdLeft'>"+tag.count+"</td><td><a href=\"/user/"+this.username+"/"+encodeURIComponent(tag.tName)+"?tab="+_GLOBAL_VAR['tag_cloud_tab']+"\">"+tag.tName.escapeHTML()+"</a></td></tr>";
        }
      }
      content += "</table>";
    }
    box.innerHTML = content;
    this.viewAsType = type;
    this.renderSorter();
    this.renderViewer(); 
  var cusData = loadCusData();
  cusData['tag_cloud_options'] = this.sortByType+type.toString();
  cusData.store();
}

function TagCloud_renderViewer() {
  var box = $(this.viewerBox);
  if(this.viewAsType=="0") {
    box.innerHTML = "View as: <strong>cloud</strong> | <a href=\"javascript:eval(_GLOBAL_VAR['"+this.prefix+"'+'_tagCloud']).viewAs('1')\">list</a>\n";
  }else {
    box.innerHTML = "View as: <a href=\"javascript:eval(_GLOBAL_VAR['"+this.prefix+"'+'_tagCloud']).viewAs('0')\">cloud</a> | <strong>list</strong>\n";
  }
}
function TagCloud_renderSorter() {
  var box = $(this.sorterBox);
  if(this.sortByType=="0") {
    box.innerHTML = "Sort by: <strong>alpha</strong> | <a href=\"javascript:eval(_GLOBAL_VAR['"+this.prefix+"'+'_tagCloud']).sortBy('1')\">freq</a>\n";
  }else {
    box.innerHTML = "Sort by: <a href=\"javascript:eval(_GLOBAL_VAR['"+this.prefix+"'+'_tagCloud']).sortBy('0')\">alpha</a> | <strong>freq</strong>\n";
  }
}

function TagCloud_init_u(username) {
  this.tags = this.tags1;
  this.step = this.calcStep(this.tags);
  this.username = username?username:"";
  this.cloudType = 'u';
  this.viewAs();
}

function tagCloudItemClass(count, step) {
    var level = Math.floor(parseInt(count)/step);
    level = level > 5 ? 5 : level;
    var klass = "";
    switch(level) {
        case 0: {
            klass = "notPopular";
        }break;
        case 1: {
            klass = "notVeryPopular";
        }break;
        case 2: {
            klass = "somewhatPopular";
        }break;
        case 3: {
            klass = "popular";
        }break;
        case 4: {
            klass = "veryPopular";
        }break;
        case 5: {
            klass = "ultraPopular";
        }break;
    }
    return klass;
}
/*----------------------------------------------------------*/


/* 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 Successfully";
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 successfully!";
var ALE_14 = "Real Name can't be empty.";
var ALE_15 = "Save general informations successfully!";
var ALE_16 = "Change password successfully!";
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 = "Delete bookmark?";
var ALE_26 = "Delete bookmark(s)?";
var ALE_27 = "Share to Group\"?\" successfully!";
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 successfully!";
var ALE_35 = "Added to List failed!";
var ALE_36 = "No list selected";
var ALE_37 = "Share to Group \"?\" successfully!";
var ALE_38 = "Remove this friend?";
var ALE_39 = "Remove this contact from the list?";
var ALE_40 = "Delete the post?"

/* 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 Successfully!';
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() {}



