/*    HTTP Host:  static.ak.fbcdn.net                                          */
/*    Generated:  January 17th 2010 2:16:38 AM PST                             */
/*      Machine:  10.16.139.104                                                */
/*       Source:  Backing Store                                                */
/*     Location:  js/9yfwom953xssgkcg.pkg.js h:ltpkarzh                        */
/*       Locale:  nu_ll                                                        */
/*         Path:  js/9yfwom953xssgkcg.pkg.js                                   */

if (window.CavalryLogger) { CavalryLogger.start_js(["js\/9yfwom953xssgkcg.pkg.js"]); }


var ChatUserInfos={};

function ChatTabActions(container){this._container=container;this._actions={};this._actionOrder=[];this._visibilityChanged=false;this._anyVisible=false;this.actionClass='action';}
copy_properties(ChatTabActions.prototype,{anyVisible:function(){return this._anyVisible;},appendAction:function(name,create_element,action){this._addAction(name,create_element,action);this._actionOrder.push(name);return this;},prependAction:function(name,create_element,action){this._addAction(name,create_element,action);this._actionOrder.unshift(name);return this;},setVisible:function(name,visible){var action=this._actions[name];if(action.visible!=visible){action.visible=visible;this._visibilityChanged=true;}
return this;},refresh:function(){if(this._visibilityChanged){this._render();this._visibilityChanged=false;return true;}
return false;},_render:function(){DOM.empty(this._container);var actions=this._actions;var actionOrder=this._actionOrder;this._anyVisible=false;var elements=[];for(var i=0;i<actionOrder.length;++i){var action=actions[actionOrder[i]];if(action.visible){if(this._anyVisible){elements.push($N('span',{className:'divider'},'|'));}
elements.push(action.create_element());this._anyVisible=true;}}
DOM.appendContent(this._container,elements);this._container.style.display=this._anyVisible?'block':'none';},_addAction:function(name,create_element,action){if(typeof create_element=='string'){var text=create_element;create_element=function(){return $N('span',{className:this.actionClass},text);}.bind(this);}
this._actions[name]={create_element:function(){var element=create_element();Event.listen(element,'click',action);return element;},visible:false};this._visibilityChanged=true;}});

function rand32(){return Math.floor(Math.random()*4294967295);}
function verifyNumber(num){if(typeof num=='undefined'||isNaN(num)||num==Number.POSITIVE_INFINITY||num==Number.NEGATIVE_INFINITY){num=0;}
return num;}

var Sound=(function(){var _initialized=false;var _swf_id='so_sound_player';return{init:function(){if(_initialized){return;}
_initialized=true;var holder=document.createElement('div');holder.id='sound_player_holder';document.body.appendChild(holder);try{var player=new SWFObject('/swf/SoundPlayer.swf',_swf_id,'1px','1px',['9.0.159.0','10.0.22.87'],'#ffffff');player.addParam('allowscriptaccess','always');player.addParam('wmode','transparent');player.addVariable('swf_id',_swf_id);player.fallback_html=' ';player.write(holder.id);window[_swf_id]=player;}catch(swfex){}},play:function(path){Sound.init();var uri=URI(path);if(!uri.getDomain()){path=URI(env_get('static_base')).setPath(uri.getPath()).toString();}
var player=document[_swf_id]||window[_swf_id];var embed;if(/\.mp3$/.test(path)){if(player){if(!player.playSound&&player.length){player=player[0];}
if(player.playSound){player.playSound(path);return;}}}
embed=ge('sound');if(!embed){embed=document.createElement('span');embed.setAttribute('id','sound');DOM.getRootElement().appendChild(embed);}
embed.innerHTML='<embed src="'+path+'" autostart="true" loop="false" '+'hidden="true" />';}}})();

function html_wordwrap(str,wrap_limit,txt_fn){if(typeof wrap_limit=='undefined'){wrap_limit=60;}
if(typeof txt_fn!='function'){txt_fn=htmlize;}
var regex=new RegExp("\\S{"+(wrap_limit+1)+"}",'g');var start=0;var str_remaining=str;var ret_arr=[];var matches=str.match(regex);if(matches){for(var i=0;i<matches.length;i++){var match=matches[i];var match_index=start+str_remaining.indexOf(match);var chunk=str.substring(start,match_index);if(chunk){ret_arr.push(txt_fn(chunk));}
ret_arr.push(txt_fn(match)+'<wbr/>');start=match_index+match.length;str_remaining=str.substring(start);}}
if(str_remaining){ret_arr.push(txt_fn(str_remaining));}
return ret_arr.join('');}
function text_get_hyperlinks(str){if(typeof(str)!='string'){return[];}
var links=str.match(/(?:(?:ht|f)tps?):\/\/[^\s"',]*[^\s"'.,?!]/ig);if(links&&links.length){var delims={'>':'<',')':'(',']':'['};var leading_delim,link,pos=0,link_offset,prefix,revised_link,regex;for(var i=0;i<links.length;i++){link=links[i];leading_delim=delims[link[link.length-1]];if(leading_delim){link_offset=str.indexOf(link);prefix=str.substr(pos,link_offset);if(prefix.indexOf(leading_delim)!=-1){links[i]=link.substr(0,link.length-1);}
pos=link_offset+link.length;}
prev_link=link;}}
return links;}
function html_hyperlink(str,txt_fn,url_fn,reroute){var accepted_delims={'<':'>','*':'*','{':'}','[':']',"'":"'",'"':'"','#':'#','+':'+','-':'-','(':')'};if(typeof(str)=='undefined'||!str.toString){return'';}
if(typeof txt_fn!='function'){txt_fn=htmlize;}
if(typeof url_fn!='function'){url_fn=htmlize;}
var str=str.toString();var http_matches=text_get_hyperlinks(str);var start=0;var str_remaining=str;var ret_arr=[];var str_remaining=str;if(http_matches){var post_form_elem=reroute?ge('post_form_id'):null;var post_form_id=post_form_elem?post_form_elem.value:'';for(var i=0;i<http_matches.length;i++){var http_url=http_matches[i];var http_index=start+str_remaining.indexOf(http_url);var str_len=http_url.length;var non_url=str.substring(start,http_index);if(non_url){ret_arr.push(txt_fn(non_url));}
var trailing='';if(http_index>0){var delim=str[http_index-1];if(typeof accepted_delims[delim]!='undefined'){var end_delim=accepted_delims[delim];var end_delim_index=http_url.indexOf(end_delim);if(end_delim_index!=-1){trailing=txt_fn(http_url.substring(end_delim_index));http_url=http_url.substring(0,end_delim_index);}}}
var http_str=url_fn(http_url);if(reroute){var http_url_quote_escape="http://www.facebook.com/l.php?u="+
URI.encodeComponent(http_url)+'&h='+post_form_id;}else{var http_url_quote_escape=http_url.replace(/"/g,'%22');}
ret_arr.push('<a href="'+http_url_quote_escape+'" target="_blank" rel="nofollow">'+
http_str+'</a>'+trailing);start=http_index+str_len;str_remaining=str.substring(start);}}
if(str_remaining){ret_arr.push(txt_fn(str_remaining));}
return ret_arr.join('');}
function nl2br(text){if(typeof(text)=='undefined'||!text.toString){return'';}
return text.toString().replace(/\n/g,'<br />');}
function is_email(email){return/^([\w!.%+\-])+@([\w\-])+(?:\.[\w\-]+)+$/.test(email);}

var Emote={_initialized:false,_imageBase:null,_emoteMap:null,_emoteOrderMap:null,_imageURLs:null,_regex:null,_mapOverlay:null,initImageURL:function(imageURL){Emote._imageURL=imageURL;},initExtraEmoticons:function(mapOverlay){Emote._mapOverlay=mapOverlay;},_init:function(){var staticBase=env_get('static_base');Emote._imageBase=staticBase+'images/emote/';Emote._blankImgSrc=staticBase+'images/blank.gif';var emoteOrder=['smile','frown','tongue','grin','gasp','wink','glasses','sunglasses','grumpy','unsure','cry','devil','angel','kiss','heart','kiki','squint','confused','upset','pacman','colonthree'];Emote._emoteMap={':-)':['\\:\\-\\)','smile'],':)':['\\:\\)','smile'],':]':['\\:\\]','smile'],'=)':['=\\)','smile'],':-(':['\\:\\-\\(','frown'],':(':['\\:\\(','frown'],':[':['\\:\\[','frown'],'=(':['=\\(','frown'],':-P':['\\:\\-P','tongue'],':P':['\\:P','tongue'],':-p':['\\:\\-p','tongue'],':p':['\\:p','tongue'],'=P':['=P','tongue'],':-D':['\\:\\-D','grin'],':D':['\\:D','grin'],'=D':['=D','grin'],':-O':['\\:\\-O','gasp'],':O':['\\:O','gasp'],':-o':['\\:\\-o','gasp'],':o':['\\:o','gasp'],';-)':['\\;\\-\\)','wink'],';)':['\\;\\)','wink'],'8-)':['8\\-\\)','glasses'],'8)':['8\\)','glasses'],'B-)':['B\\-\\)','glasses'],'B)':['B\\)','glasses'],'8-|':['8\\-\\|','sunglasses'],'8|':['8\\|','sunglasses'],'B-|':['B\\-\\|','sunglasses'],'B|':['B\\|','sunglasses'],'>:(':['>\\:\\(','grumpy'],'>:-(':['>\\:\\-\\(','grumpy'],':/':['\\:/','unsure'],':-/':['\\:\\-/','unsure'],':\\':['\\:\\\\','unsure'],':-\\':['\\:\\-\\\\','unsure'],":'(":["\\:'\\(",'cry'],'3:)':['3\\:\\)','devil'],'3:-)':['3\\:\\-\\)','devil'],'O:)':['O\\:\\)','angel'],'O:-)':['O\\:\\-\\)','angel'],':-*':['\\:\\-\\*','kiss'],':*':['\\:\\*','kiss'],'<3':['<3','heart'],'^_^':['\\^_\\^','kiki'],'-_-':['\\-_\\-','squint'],'o.O':['o\\.O','confused'],'O.o':['O\\.o','confused'],'>:O':['>\\:O','upset'],'>:-O':['>\\:\\-O','upset'],'>:o':['>\\:o','upset'],'>:-o':['>\\:\\-o','upset'],':v':['\\:v','pacman'],':|]':['\\:\\|\\]','robot'],':3':['\\:3','colonthree'],'<(")':['<\\(\\"\\)','penguin'],':putnam:':['\\:putnam\\:','putnam'],'(^^^)':['\\(\\^\\^\\^\\)','shark']};if(Emote._mapOverlay){copy_properties(Emote._emoteMap,Emote._mapOverlay);}
var regexArr=[];for(var match in Emote._emoteMap){regexArr.push(Emote._emoteMap[match][0]);}
var regexStr='(?:^|\\s|\'|"|\\.)('+regexArr.join('|')+')(?:\\s|\'|"|\\.|,|!|\\?|<br>|$)';Emote._regex=new RegExp(regexStr);Emote._emoteOrderMap={};for(var i=0;i<emoteOrder.length;i++){Emote._emoteOrderMap[emoteOrder[i]]=i;}
Emote._initialized=true;},htmlEmote:function(str,txtFn){if(typeof txtFn!='function'){txtFn=htmlize;}
if(!Emote._initialized){Emote._init();}
var start=0;var strRemaining=str;var retArr=[];while(true){var matchObj=Emote._regex.exec(strRemaining);if(!matchObj||!matchObj.length){break;}
var match=matchObj[1];var matchKey=Emote._emoteMap[match][1];var matchIndex=strRemaining.indexOf(match);var chunk=strRemaining.substring(0,matchIndex);if(chunk){retArr.push(txtFn(chunk));}
retArr.push('<span class="emote_text">');retArr.push(match);retArr.push('</span><img class="emote_img" ');var matchOrder;if(typeof(matchOrder=Emote._emoteOrderMap[matchKey])=='undefined'){retArr.push('src="');retArr.push(Emote._imageBase);retArr.push(matchKey);retArr.push('.gif" ');}else{var matchPos=((matchOrder*-16)-590);retArr.push('src="');retArr.push(Emote._blankImgSrc);retArr.push('" style="background:url(');retArr.push(Emote._imageURL);retArr.push(') ');retArr.push(matchPos);retArr.push('px -84px no-repeat" ');}
retArr.push('alt="');retArr.push(match);retArr.push('" />');strRemaining=strRemaining.substring(matchIndex+match.length);}
if(strRemaining){retArr.push(txtFn(strRemaining));}
return retArr.join('');}};

function CookieManager(version,small_presence){this.version=version;this.cookieName='presence';this.smallPresence=small_presence;this.storers={};}
CookieManager.prototype={register:function(subname,fn){this.storers[subname]=fn;},store:function(){var cookie=this._getCookie();if(cookie&&cookie.v&&this.version<cookie.v){presence.versionShutdown();return;}
var data={'v':this.version,'time':parseInt(presence.getTime()*0.001)};for(var subname in this.storers){data[subname]=this.storers[subname]();}
var serialized=JSON.encode(data);if(this.smallPresence){serialized=serialized.replace(/"([a-zA-Z0-9_]+?)":/g,'$1:');serialized='b'+Base64.encode(serialized);}
setCookie(this.cookieName,serialized,null);},_getCookie:function(){try{var data=getCookie(this.cookieName);if(data&&data.length>1&&data.charAt(0)=='b'){data=Base64.decode(data.substring(1));}
if(this.smallPresence){data=data.replace(/([a-zA-Z0-9_]+?):/g,'"$1":');}
return data?JSON.decode(data):null;}catch(e){return null;}},getSubCookie:function(subname){var cookie=this._getCookie();if(!cookie){return null;}
return cookie[subname];}};

var ChannelRebuildReasons={Unknown:0,AsyncError:1,TooLong:2,Refresh:3,RefreshDelay:4,UIRestart:5,NeedSeq:6,PrevFailed:7,IFrameLoadGiveUp:8,IFrameLoadRetry:9,IFrameLoadRetryWorked:10,PageTransitionRetry:11};function ChannelManager(user,retryInterval,channelConfig,noSubdomain,loginErrorGk){this.user=user;this.iframeCheckTime=16000;this.iframeCheckRetryTime=16000;this.iframeLoadMaxRetries=1;this.retryInterval=retryInterval;this.channelConfig=channelConfig;this._init(noSubdomain);this.loginErrorGk=loginErrorGk;}
function handleChanneliFrameMessageEvent(event){event=event||window.event;var domain=(event.domain||event.origin);if(domain.substring(domain.length-13)!='.facebook.com'&&domain.substring(domain.length-15)!='://facebook.com'&&domain!='facebook.com'){return;}
handleChanneliFrameMessage(event.data);}
function handleChanneliFrameMessage(iframeMsgStr){if(iframeMsgStr&&iframeMsgStr.charAt(0)=='{'){channelManager.handleiFrameMessage(eval('('+iframeMsgStr+')'));}}
ChannelManager.prototype={_init:function(noSubdomain){this.channels={};this.iframeHost=this.iframePort=null;this.isActionRequest=true;this.isReady=false;this.isRebuilding=false;this.iframeIsLoaded=false;this.iframeEverLoaded=false;this.iframeCheckFailedCount=0;this.permaShutdown=false;this.shouldClearSubdomain=false;this.subframe=ge('channel_iframe');this.postMessage=null;var channelData=presenceCookieManager.getSubCookie('ch');if(noSubdomain){this.iframeSubdomain=null;}else{this.iframeSubdomain=0;if(channelData&&channelData.sub){for(var i=0;i<channelData.sub.length;i++){if(!channelData.sub[i]){this.iframeSubdomain=i;break;}}
if(i==channelData.sub.length){this.iframeSubdomain=channelData.sub.length;}}}
var safari=ua.safari();this.pollForMessages=(safari>523&&safari<525);this.useRandomSubdomain=!!ua.ie();if(window.postMessage){if(window.addEventListener){window.addEventListener('message',handleChanneliFrameMessageEvent,false);}else{window.onmessage=handleChanneliFrameMessageEvent;}}else if(document.postMessage){document.addEventListener('message',handleChanneliFrameMessageEvent,false);}else{Util.log('channel: no postMessage listener');}
presenceCookieManager.register('ch',this._getCookieInfo.bind(this));if(ua.firefox()){onbeforeunloadRegister(this._onUnload.bind(this));}else{onunloadRegister(this._onUnload.bind(this));}},sendiFrameMessage:function(msg){if(!this.postMessage){return;}
var msgStr=JSON.encode(msg);try{this.postMessage(msgStr,"*");}catch(e){presence.error('channel: error sending message "'+msgStr+'" to iframe: '+e.toString());}},handleiFrameMessage:function(iframeMsg){if(iframeMsg.type=='init'){this.iframeLoaded();}else if(iframeMsg.type=='channelMsg'){this.handleChannelMsg(iframeMsg.channel,iframeMsg.seq,iframeMsg.msg);}},_onUnload:function(){this.shouldClearSubdomain=true;presence.doSync(true);},addChannel:function(channel,seq,msgHandler,startHandler,shutdownHandler,restartHandler){this.channels[channel]={'currentSeq':seq,'nextSeq':0,'msgHandler':msgHandler,'startHandler':startHandler,'shutdownHandler':shutdownHandler,'restartHandler':restartHandler};},isLowestSubdomain:function(){var channelData=presenceCookieManager.getSubCookie('ch');if(!channelData||!channelData.sub){return true;}
for(var i=0;i<channelData.sub.length;i++){if(channelData.sub[i]){return(i==this.iframeSubdomain);}}},_getCookieInfo:function(){var data={};if(this.iframeHost&&this.iframePort){data.h=this.iframeHost;data.p=this.iframePort;if(null!==this.iframeSubdomain){var channelData=presenceCookieManager.getSubCookie('ch');var subdomains=(channelData&&channelData.sub)?channelData.sub:[];var oldLength=subdomains.length;if(this.shouldClearSubdomain){subdomains[this.iframeSubdomain]=0;}else{subdomains[this.iframeSubdomain]=1;for(var i=oldLength;i<=this.iframeSubdomain;i++){if(!subdomains[i]){subdomains[i]=0;}}}
data.sub=subdomains;}
for(var channel in this.channels){data[channel]=this.channels[channel].currentSeq;}}
data.ri=this.retryInterval;return data;},stop:function(){this.stopped=true;this.setReady(false);},setReady:function(isReady){this.isReady=isReady;var msg={'type':'isReady','isReady':isReady,'isActionRequest':this.isActionRequest};if(isReady&&this.isActionRequest){this.isActionRequest=false;}
if(isReady){msg['channels']=this.channels;}
this.sendiFrameMessage(msg);},setActionRequest:function(isActionRequest){this.sendiFrameMessage({'type':'isActionRequest','isActionRequest':isActionRequest});},iframeLoad:function(path,host,port,isReady){this.isReady=isReady;this.iframeIsLoaded=false;this.iframePath=path;this.iframeHost=host;this.iframePort=port;var subdomain;if(null===this.iframeSubdomain){subdomain='';}else{subdomain=this.iframeSubdomain;if(this.useRandomSubdomain){subdomain+=''+rand32();}
subdomain+='.';}
var url='http://'+subdomain+this.iframeHost+'.facebook.com:'+this.iframePort+this.iframePath;setTimeout(this._iframeCheck.bind(this),this.iframeCheckTime);if(this.subframe.contentDocument){try{this.subframe.contentDocument.location.replace(url);}catch(e){presence.error('channel: error setting location: '+e.toString());}}else if(this.subframe.contentWindow){this.subframe.src=url;}else if(this.subframe.document){this.subframe.src=url;}else{presence.error('channel: error setting subframe url');}
presence.debug('channel: done with iframeLoad, subframe sent to '+url);},iframeLoaded:function(){if(!this.iframeIsLoaded){this.iframeIsLoaded=true;if(window.postMessage){if('object'==typeof window.postMessage){var target=this.subframe.contentWindow;this.postMessage=function(message,origin){target.postMessage(message,origin);};}else{this.postMessage=bind(this.subframe.contentWindow,this.subframe.contentWindow.postMessage);}}else if(document.postMessage){this.postMessage=bind(this.subframe.contentDocument,this.subframe.contentDocument.postMessage);}else{this.postMessage=bind(this.subframe.contentWindow,this.subframe.contentWindow.handleChannelParentMessage);}
this.setReady(this.isReady);if(this.pollForMessages){this.msgCheckInterval=setInterval(this.handleChannelMsgCheck.bind(this),100);}
if(this.iframeCheckFailedCount){for(var c in this.channels){this.channels[c].restartHandler(false);}
this._sendDummyReconnect(ChannelRebuildReasons.IFrameLoadRetryWorked);}else{for(var c in this.channels){this.channels[c].startHandler();}}
this.iframeCheckFailedCount=0;this.iframeEverLoaded=true;}},_iframeCheck:function(){if(!this.iframeIsLoaded){presence.error("channel: uplink iframe never loaded; shutting down");this.iframeCheckFailedCount++;this.iframeHost=this.iframePort=0;presenceCookieManager.store();if(this.iframeCheckFailedCount<=this.iframeLoadMaxRetries){this.iframeCheckTime=this.iframeCheckRetryTime;this.iframePath=null;this.rebuild(ChannelRebuildReasons.IFrameLoadRetry);}else{for(var c in this.channels){this.channels[c].shutdownHandler();}
this._sendDummyReconnect(ChannelRebuildReasons.IFrameLoadGiveUp);}}else{this.retryInterval=0;presence.debug('channel: uplink iframe loaded fine');}},_sendDummyReconnect:function(reason){var areq=new AsyncRequest().setURI('/ajax/presence/reconnect.php').setData({reason:reason,iframe_loaded:this.iframeEverLoaded}).setOption('suppressErrorHandlerWarning',true).setMethod('GET').setReadOnly(true)
areq.specifiesWriteRequiredParams()&&areq.send();},_rebuildResponse:function(response){var rebuildInfo=response.getPayload();var channel=rebuildInfo.user_channel;presence.debug('got rebuild response with channel '+channel+', seq '+rebuildInfo.seq+', host '+rebuildInfo.host+', port '+rebuildInfo.port);this.channels[channel].currentSeq=rebuildInfo.seq;this.channels[channel].nextSeq=0;this.isRebuilding=false;if(rebuildInfo.path!=this.iframePath||rebuildInfo.host!=this.iframeHost||rebuildInfo.port!=this.iframePort){this.iframeLoad(rebuildInfo.path,rebuildInfo.host,rebuildInfo.port,true);}else{this.setReady(true);}
presenceCookieManager.store();presenceUpdater.pauseUpdate();if(typeof chatOptions!='undefined'){chatOptions.setVisibility(rebuildInfo.visibility);}
for(var c in this.channels){this.channels[c].restartHandler(true);}
presenceUpdater.resumeUpdate(['buddy_list']);},_retryRebuild:function(reason,forceMaxRetryInterval){if(forceMaxRetryInterval){this.retryInterval=this.channelConfig.MAX_RETRY_INTERVAL;}else if(this.retryInterval==0){this.retryInterval=this.channelConfig.MIN_RETRY_INTERVAL;}else{this.retryInterval*=2;if(this.retryInterval>=this.channelConfig.MAX_RETRY_INTERVAL){this.retryInterval=this.channelConfig.MAX_RETRY_INTERVAL;}}
var randInterval=this.retryInterval*(0.75+Math.random()*0.5);presence.warn('manager trying again in '+(randInterval*0.001)+' secs');setTimeout(this._rebuildSend.bind(this,reason),this.retryInterval);},_rebuildError:function(reason,response){for(var c in this.channels){this.channels[c].shutdownHandler(true);}
presence.error('got rebuild error: '+response.getErrorDescription());if(presence.checkMaintenanceError(response)){presence.warn('manager not trying again');}else if(presence.checkLoginError(response)){if(presence.inPopoutWindow||this.loginErrorGk){this._retryRebuild(ChannelRebuildReasons.PrevFailed,true);}else{presence.warn('manager not trying again');}}else{this._retryRebuild(ChannelRebuildReasons.PrevFailed,false);}},_rebuildTransportError:function(reason,response){for(var c in this.channels){this.channels[c].shutdownHandler(true);}
presence.error('got rebuild transport error: '+response.getErrorDescription());this._retryRebuild(reason,false);},_rebuildSend:function(reason){if(typeof reason!='number'){reason=ChannelRebuildReasons.Unknown;}
presence.debug('channel: sending rebuild');var areq=new AsyncRequest().setURI('/ajax/presence/reconnect.php').setData({reason:reason,iframe_loaded:this.iframeEverLoaded}).setHandler(this._rebuildResponse.bind(this)).setErrorHandler(this._rebuildError.bind(this,reason)).setTransportErrorHandler(this._rebuildTransportError.bind(this,reason)).setOption('suppressErrorAlerts',true).setMethod('GET').setReadOnly(true);return areq.specifiesWriteRequiredParams()&&areq.send();},rebuild:function(reason){if(this.stopped){return;}
if(this.isRebuilding){presence.debug('channel: rebuild called, but already rebuilding');return;}
this.setReady(false);this.isRebuilding=true;presence.debug('channel: rebuilding');if(reason==ChannelRebuildReasons.RefreshDelay){this.retryInterval=this.channelConfig.MAX_RETRY_INTERVAL;}
setTimeout(this._rebuildSend.bind(this,reason),this.retryInterval);},handleChannelMsgCheck:function(){if(this.pendingMsg){this._handleChannelMsg(this.pendingMsg.channel,this.pendingMsg.seq,this.pendingMsg.msg);this.pendingMsg=null;}},handleChannelMsg:function(channel,seq,msg){if(this.pollForMessages){this.pendingMsg={channel:channel,seq:seq,msg:msg};}else{this._handleChannelMsg(channel,seq,msg);}},_handleChannelMsg:function(channel,seq,msg){if(msg.type=='shutdown'||msg.type=='permaShutdown'){if(!window.loaded||this.permaShutdown){return;}
if(msg.type=='permaShutdown'){presence.warn('channel: got permaShutdown for all channels');this.permaShutdown=true;}else{presence.warn('channel: got shutdown for all channels');this.rebuild(msg.reason);}
for(var c in this.channels){this.channels[c].shutdownHandler(true);}}else{this.channels[channel].currentSeq++;var nextSeq;if((nextSeq=this.channels[channel].nextSeq)&&seq<nextSeq){presence.warn('ignoring a duplicate message ('+seq+')<('+nextSeq+') on '+channel);return;}
this.channels[channel].nextSeq=parseInt(seq)+1;presence.pauseSync();try{this.channels[channel].msgHandler(channel,msg);}catch(e){presence.error('error in channel handlers: '+e.toString()+', msg: '+msg);}
presence.resumeSync();}}};

function LiveMessageReceiver(eventName){this.eventName=eventName;this.subs=null;this.handler=bagofholding;this.shutdownHandler=null;this.restartHandler=null;this.registered=false;this.appId=1;}
LiveMessageReceiver.prototype.setAppId=function(appId){this.appId=appId;return this;}
LiveMessageReceiver.prototype.setHandler=function(handler){this.handler=handler;this._dirty();return this;}
LiveMessageReceiver.prototype.setRestartHandler=function(restartHandler){this.restartHandler=restartHandler.shield();this._dirty();return this;}
LiveMessageReceiver.prototype.setShutdownHandler=function(shutdownHandler){this.shutdownHandler=shutdownHandler.shield();this._dirty();return this;}
LiveMessageReceiver.prototype._dirty=function(){if(this.registered){this.unregister();this.register();}}
LiveMessageReceiver.prototype.register=function(){var wrapper=function(type,message){return this.handler(message);}.bind(this);var type=PresenceMessage.getAppMessageType(this.appId,this.eventName);this.subs={};this.subs['main']=Arbiter.subscribe(type,wrapper);if(this.shutdownHandler){this.subs['shut']=Arbiter.subscribe(PresenceMessage.SHUTDOWN,this.shutdownHandler);}
if(this.restartHandler){this.subs['restart']=Arbiter.subscribe(PresenceMessage.RESTARTED,this.restartHandler);}
this.registered=true;return this;}
LiveMessageReceiver.prototype.unregister=function(){if(!this.subs){return this;}
for(var k in this.subs){if(this.subs[k]){Arbiter.unsubscribe(this.subs[k]);}}
this.subs=null;this.registered=false;return this;}
LiveMessageReceiver.route=function(message){var informHandler=function(response){var type=PresenceMessage.getAppMessageType(message.app_id,message.event_name);Arbiter.inform(type,response,Arbiter.BEHAVIOR_PERSISTENT);};if(message.hasCapture){new AsyncRequest().setHandler(function(r){informHandler(r.getPayload())}).handleResponse(message.response);}else{informHandler(message.response);}}

function Presence(user,name,firstName,serverTime,popoutType,sitevars){this.user=user;this.name=name;this.firstName=firstName;this.sitevars=sitevars;this.popoutURL=env_get('www_base')+'presence/popout.php';var viewportDimensions=Vector2.getViewportDimensions();this.maxTabOffset=37;var divs=['fb_menubar','intern_bookmark_frame'];var div;for(var ii=0;ii<divs.length;ii++){if(div=ge(divs[ii])){this.maxTabOffset+=Vector2.getElementDimensions(div).y;}}
this.maxTabHeight=viewportDimensions.y-this.maxTabOffset;this.updateServerTime(serverTime);this.pageLoadTime=this.getTime();this._init(popoutType);}
Presence.prototype={minWidth:100,minHeight:100,defWidth:600,defHeight:500,defX:30,defY:30,cookiePollTime:2000,popoutHeartbeatTime:1000,popoutHeartbeatAllowance:4000,popoutHeartbeatFirstAllowance:15000,resizeStopTime:500,shutdownDelay:5000,restartDelay:3000,POPOUT_TYPE_CHAT:1,POPOUT_TYPE_VIDEOCHAT:2,_init:function(popoutType){this.stateStorers=[];this.stateLoaders=[];this.windowID=rand32()+1;this.contentPaddings={'buddy_list':77,'presence_notifications':23,'presence_applications':73};this.contentResized={};this.holder=$('presence');this.holderUI=$('presence_ui');this.bar=$('presence_bar');this.popoutSidebar=ge('presence_popout_sidebar');this.popoutWidth=this.defWidth;this.popoutHeight=this.defHeight;this.cookiePoller=null;this.heartbeat=null;this.resizeTimeout=null;this.lastResized=0;this.stateUpdateTime=0;this.loaded=false;this.isShutdown=false;this.isShuttingDown=false;this.isRestarting=false;this.isPermaShutdown=false;this.shutdownTime=0;this.popoutClicked=false;this.popinClicked=false;this.justPoppedOut=false;this.syncPaused=0;this.disableUnfocus=null;this.tempTabCloseHandler=null;this.inPopoutWindow=popoutType==this.POPOUT_TYPE_CHAT;this.inVideoChat=popoutType==this.POPOUT_TYPE_VIDEOCHAT;this.inVideoChatWith=null;this.poppedOut=this.inPopoutWindow;presenceCookieManager.register('state',this._getCookieData.bind(this));if(this.inPopoutWindow){Util.fallbackErrorHandler=null;if(!this.inVideoChat){this.bar.style.marginRight='200px';}
if(!this.inVideoChat){onbeforeunloadRegister(this.popin.bind(this,false));onunloadRegister(this.popin.bind(this,false));}}
Event.listen(window,'resize',this._windowOnResize.bind(this));Event.listen(window,'keypress',this._documentKeyPress.bind(this));Event.listen(document,'click',this._documentOnClick.bind(this));if(DOMScroll.usingScrollWrapper()){DOMScroll.registerScrollChangeHandler(this._handleScrollChange.bind(this));}
Arbiter.subscribe(Arbiter.PAGE_TRANSITION,this.checkRebuild.bind(this));var safari=ua.safari();this.isSafari2=(safari&&safari<500);this.isOpera=(ua.opera()>0);var ff=ua.firefox();this.isFF2=(ff&&ff<3);this.isWindows=ua.windows();this.load();this._windowOnResize.bind(this).defer();if(this.inPopoutWindow){setTimeout(this._windowOnResize.bind(this),3000);}},updateServerTime:function(serverTime){this.timeSkew=(new Date()).getTime()-serverTime;},getTime:function(){return(new Date()).getTime()-this.timeSkew;},debug:function(msg){},warn:function(msg){Util.warn('chirp: '+msg);},error:function(msg){Util.error('chirp: '+msg);},inVideoCallTo:function(to){this.inVideoChatWith=to;},load:function(){var presenceState=presenceCookieManager.getSubCookie('state');if(!presenceState){this.debug('presence: got null state cookie, loading with current state');this._load(this._getCookieData());return;}
try{this._load(presenceState);}catch(e){this.error('presence: got load exception: '+e.toString());this._load(this._getCookieData());}},_load:function(presenceState){this.syncPaused++;this.stateUpdateTime=verifyNumber(presenceState.ut);this.popoutTime=verifyNumber(presenceState.pt);this.popoutWidth=verifyNumber(presenceState.w);this.popoutHeight=verifyNumber(presenceState.h);if(!this.popoutWidth){this.popoutWidth=this.defWidth;}
if(!this.popoutWidth){this.popoutWidth=this.defHeight;}
this.popoutWidth=Math.max(this.popoutWidth,this.minWidth);this.popoutHeight=Math.max(this.popoutHeight,this.minHeight);this.poppedOut=!!presenceState.p;if(this.poppedOut){if(this.inPopoutWindow){if(!this.heartbeat&&!this.inVideoChat){this.heartbeat=setInterval(this._popoutHeartbeat.bind(this),this.popoutHeartbeatTime);}}else{CSS.addClass(this.holder,'popped_out');}}else if(!this.inVideoChat){if(this.inPopoutWindow){if(!this.loaded){this.poppedOut=true;this.doSync();}else{if(!this.popinClicked){window.close();}else{}}}else{this.justPoppedOut=true;}
CSS.removeClass(this.holder,'popped_out');}
if(!this.inPopoutWindow&&!this.cookiePoller){this.cookiePoller=setInterval(this._pollCookie.bind(this),this.cookiePollTime);}
this.virtPopoutWidth=this.popoutWidth;this.virtPopoutHeight=this.popoutHeight;this.state=presenceState;for(var i=0;i<this.stateLoaders.length;i++){this.stateLoaders[i](presenceState);}
this._handleResize.bind(this,0,0).defer();setTimeout(this._handleResize.bind(this,0,0),100);this.syncPaused--;this.loaded=true;},_pollCookie:function(){var presenceState=presenceCookieManager.getSubCookie('state');if(!presenceState){return;}
var myPopoutTime=this.popoutTime;if(presenceState.ut>this.stateUpdateTime){this.load(presenceState);return;}
if(this.poppedOut&&!this.inPopoutWindow){var cookiePopoutTime=verifyNumber(presenceState.pt);var diff=(new Date()).getTime()-cookiePopoutTime;var diffAllowance=this.popoutHeartbeatTime+this.popoutHeartbeatAllowance;if(this.justPoppedOut){if(cookiePopoutTime==myPopoutTime){diffAllowance+=this.popoutHeartbeatFirstAllowance;}else{this.justPoppedOut=false;}}
this.popoutTime=cookiePopoutTime;if(diff>diffAllowance){this.poppedOut=false;this.doSync();}}},_popoutHeartbeat:function(){this._pollCookie();if(this.poppedOut){presenceCookieManager.store();}},_getCookieData:function(){var presenceState={p:this.poppedOut?1:0,w:this.popoutWidth,h:this.popoutHeight,ut:this.stateUpdateTime,pt:this.inPopoutWindow?(new Date()).getTime():this.popoutTime};for(var i=0;i<this.stateStorers.length;i++){presenceState=this.stateStorers[i](presenceState);}
this.state=presenceState;return this.state;},doSync:function(immediate){if(this.syncPaused){return;}
if(immediate)
this._doSync();else{this._doSync.bind(this).defer();}},_doSync:function(){this.stateUpdateTime=(new Date()).getTime();presenceCookieManager.store();this._load(this.state);},pauseSync:function(){this.syncPaused++;},resumeSync:function(){this.syncPaused--;this.doSync();},handleMsg:function(channel,obj){this._handleMsg.bind(this,channel,obj).defer();},_handleMsg:function(channel,obj){if(typeof obj=='string'){if(obj=='shutdown'){this.connectionShutdown();}else if(obj=='restart'){if(this.isShutdown){this.restart();}}
return;}
if(this.isShutdown){return false;}
if(!obj.type){return;}
if(obj.type=='app_msg'){if(obj.event_name=='beep_event'){Bootloader.loadComponents('beeper',function(){Beeper.ensureInitialized();LiveMessageReceiver.route(obj);});}else{LiveMessageReceiver.route(obj);}}
Arbiter.inform(PresenceMessage.getArbiterMessageType(obj.type),{sender:this,channel:channel,obj:obj});},popout:function(){if(this.inVideoChat){return;}
if(this.inPopoutWindow||this.poppedOut){this.popin(true);return;}
if(this.popoutClicked){return;}
this.popoutClicked=true;var width=this.popoutWidth;var height=this.popoutHeight;if(this.isSafari2){width=this.minWidth;height=this.minHeight;}
var w=window.open(this.popoutURL,"fbChatWindow","status=0,toolbar=0,location=0,menubar=0,"+"directories=0,resizable=1,scrollbars=0,"+"width="+width+",height="+height+","+"left="+this.defX+",top="+this.defY);if(width!=this.popoutWidth||height!=this.popoutHeight){w.resizeBy(this.popoutWidth-width,this.popoutHeight-height);}
CSS.removeClass(this.holder,'popped_out');this.poppedOut=true;this.justPoppedOut=true;this.popoutTime=(new Date()).getTime();this.doSync();this.popoutClicked=false;},popin:function(shouldClose){if(this.inVideoChat){return;}
if(typeof shouldClose=='undefined'){shouldClose=true;}
if(this.inPopoutWindow){if(this.popinClicked){return;}
this.popinClicked=true;}
this.poppedOut=false;this.doSync();if(this.inPopoutWindow&&shouldClose){window.close();}},_windowOnResize:function(){this.contentResized={};var viewportDimensions=Vector2.getViewportDimensions();this._handleResize(viewportDimensions.x-this.virtPopoutWidth,viewportDimensions.y-this.virtPopoutHeight);if(this.inPopoutWindow){clearTimeout(this.resizeTimeout);this.lastResized=(new Date()).getTime();this.resizeTimeout=setTimeout(function(){this.resizeTimeout=null;if((new Date()).getTime()>=this.lastResized+this.resizeStopTime){this._stopResize();}}.bind(this),this.resizeStopTime);if(viewportDimensions.x<this.popoutWidth||viewportDimensions.y<this.popoutHeight){try{window.resizeTo(this.popoutWidth,this.popoutHeight);this._stopResize();}catch(e){}}}else{this._updateMaxTabHeight();}},_updateMaxTabHeight:function(){this.maxTabHeight=Vector2.getViewportDimensions().y-this.maxTabOffset;if(DOMScroll.usingScrollWrapper()&&DOMScroll.getScrollState().x){this.maxTabHeight-=DOMScroll.getScrollbarSize();}
if(window.buddyList&&buddyList.buddyListOpen){buddyList.resizeTab();}else if(this.focusedWrapper&&this.focusedContent){this.tabContentResize(this.focusedWrapper,this.focusedContent);}},_handleScrollChange:function(type,message){if(!DOMScroll.usingScrollWrapper()){return;}
var scrollbarSize=DOMScroll.getScrollbarSize();var holderBottom=this.getHolderBottomPosition();var holderUIRight=15+(message.is_scrolled.y?scrollbarSize:0);CSS.setStyle(this.holder,'bottom',holderBottom+'px');CSS.setStyle(this.holderUI,'marginRight',holderUIRight+'px');if(typeof chatDisplay!='undefined'){for(var id in chatDisplay.tabs){chatDisplay.tabs[id].adjustWrapperBottom();}}
this._updateMaxTabHeight();},getHolderBottomPosition:function(){var holderBottom=0;if(DOMScroll.getScrollState().x){var scrollbarSize=DOMScroll.getScrollbarSize();holderBottom=scrollbarSize+(ua.osx()?1:0);}
if(presence.isIE6){holderBottom--;}
return holderBottom;},_handleResize:function(dx,dy){var delay=this.loaded?100:10;if(this.handleResizeTimer){clearTimeout(this.handleResizeTimer);}
this.handleResizeTimer=setTimeout(function(){this.virtPopoutWidth+=dx;this.virtPopoutHeight+=dy;this.popoutWidth=Math.max(this.virtPopoutWidth,this.minWidth);this.popoutHeight=Math.max(this.virtPopoutHeight,this.minHeight);Arbiter.inform(PresenceMessage.WINDOW_RESIZED,{sender:this});},delay);},_stopResize:function(){if(this.virtPopoutWidth!=this.popoutWidth||this.virtPopoutHeight!=this.popoutHeight){this.virtPopoutWidth=this.popoutWidth;this.virtPopoutHeight=this.popoutHeight;this.doSync();}},_documentKeyPress:function(e){e=$E(e);var keycode=e?e.keyCode:-1;if(keycode==KEYS.ESC){Event.kill(e);}},_documentOnClick:function(event){if(DOM.contains(this.holder,event.getTarget())||!DOM.contains(document,event.getTarget())){return;}
if((typeof buddyList!='undefined')&&buddyList.buddyListOpen){if(typeof buddyListDisplay!='undefined'&&buddyListDisplay.isFlyoutOpen()){buddyListDisplay.closeOpenFlyout();return;}
if(!buddyList.isSticky()){buddyList.closeTab();}}else{this.closeTab();}},_unfocus:function(){if(this.focusedWrapper){hide(this.focusedWrapper);}
if(this.focusedTab){CSS.removeClass(ge(this.focusedTab),'focused');if(this.tempTabCloseHandler){this.tempTabCloseHandler();this.tempTabCloseHandler=null;}}
this.wasFocusedTab=this.focusedTab;this.focusedTab=this.focusedWrapper=null;return this.wasFocusedTab;},unfocus:function(){var wasFocusedTab=this._unfocus();if(wasFocusedTab){this.disableUnfocus=wasFocusedTab;setTimeout(function(){this.disableUnfocus=null;}.bind(this),50);}},toggleTab:function(wrapperID,tabID,scrollContentID){var wrapper=ge(wrapperID);var tab=ge(tabID);if(!wrapper||!tab||tabID==this.disableUnfocus){return;}
if(wrapper.style.display=='none'){this.openTab(wrapperID,tabID,scrollContentID);}else{this.closeTab();}},closeTab:function(){var tab=this.focusedTab;if(!tab){return;}
var wasFocusedTab=this.wasFocusedTab;this.unfocus();CSS.removeClass(tab,'focused');CSS.removeClass(this.holder,'tab_open');Arbiter.inform(PresenceMessage.TAB_CLOSED,{sender:this,tabID:tab});if(tab!=wasFocusedTab&&wasFocusedTab=='buddy_list_tab'){buddyList.openTab();}},openTabDelayed:function(wrapperID,tabID,scrollContentID){this.openTab.bind(this,wrapperID,tabID,scrollContentID).defer();},openTab:function(wrapperID,tabID,scrollContentID){if(this.focusedTab==tabID){return;}
this._unfocus();this.focusedWrapper=wrapperID;this.focusedContent=scrollContentID;this.focusedTab=tabID;this.disableUnfocus=this.focusedTab;setTimeout(function(){this.disableUnfocus=null;}.bind(this),50);if(scrollContentID&&!this.contentResized[scrollContentID]){ge(wrapperID).style.visibility='hidden';show(wrapperID);this.tabContentResize(wrapperID,scrollContentID);ge(wrapperID).style.visibility='';}else{show(wrapperID);}
CSS.addClass(ge(tabID),'focused');CSS.addClass(this.holder,'tab_open');Arbiter.inform(PresenceMessage.TAB_OPENED,{sender:this,tabID:tabID});},contentChanged:function(contentID){delete this.contentResized[contentID];},tabContentResize:function(wrapperID,contentID,forceLockHeight){if(this.poppedOut||this.inVideoChat){return;}
var content=ge(contentID);var wrapper=ge(wrapperID);if(!content||!wrapper){return;}
var contentWrapper=content.parentNode;if(this.focusedWrapper==wrapperID){this.contentResized[contentID]=true;}
if(!this.contentPaddings[wrapperID]){var dimWrapper=Vector2.getHiddenElementDimensions(wrapper);var dimContentWrapper=Vector2.getHiddenElementDimensions(contentWrapper);this.contentPaddings[wrapperID]=dimWrapper.y-dimContentWrapper.y;}
if(ua.ie()<8){contentWrapper.style.height='auto';dimContent=Vector2.getHiddenElementDimensions(contentWrapper);}else{dimContent=Vector2.getHiddenElementDimensions(content);}
var maxContentHeight=this.maxTabHeight-this.contentPaddings[wrapperID];if(dimContent.y&&dimContent.y<maxContentHeight){CSS.removeClass(contentWrapper,'scroll');contentWrapper.style.height=forceLockHeight?(dimContent.y+'px'):'auto';}else{CSS.addClass(contentWrapper,'scroll');contentWrapper.style.height=maxContentHeight+'px';}},pauseOffClick:function(tabID){this.disableUnfocus=tabID;},resumeOffClick:function(){this.disableUnfocus=null;},renderLink:function(href,text,extra){return'<a href="'+href+'"'+
(this.inPopoutWindow||this.inVideoChat?' target="_blank"':'')+
(extra?extra:'')+'>'+text+'</a>';},checkRebuild:function(){if(this.isShutdown&&!this.isPermaShutdown){channelManager.rebuild(ChannelRebuildReasons.PageTransitionRetry);}},getErrorDescription:function(asyncResponse){var error=asyncResponse.getError();var desc=asyncResponse.getErrorDescription();if(!desc){desc=_tx("\u767c\u751f\u932f\u8aa4\u3002");}
if(error==kError_Async_NotLoggedIn){desc=_tx("Your session has timed out. Please log in.");}
return desc;},showAsyncError:function(asyncResponse,title){if(typeof title=='undefined'||!title){var chat=_tx("\u804a\u5929\u5ba4");title=_tx("Facebook \u804a\u5929\u5ba4\u932f\u8aa4\u8a0a\u606f");}
var desc=this.getErrorDescription(asyncResponse);new ErrorDialog().showError(title,desc);},showTransportError:function(asyncResponse,title){if(typeof title=='undefined'||!title){var chat=_tx("\u804a\u5929\u5ba4");title=_tx("Facebook \u804a\u5929\u5ba4\u932f\u8aa4\u8a0a\u606f");}
var desc=_tx("\u76ee\u524d\u7121\u6cd5\u9023\u7dda\u5230 Facebook {Chat}\u3002",{'Chat':_tx("\u804a\u5929\u5ba4")});new ErrorDialog().showError(title,desc);this.warn("presence: got async transport error: "+asyncResponse.getErrorDescription());},checkLoginError:function(asyncResponse){var error=asyncResponse.getError();if(error==kError_Async_NotLoggedIn||error==kError_Async_LoginChanged||error==kError_Async_CSRFCheckFailed||error==kError_Login_GenericError){this.loginShutdown();return true;}
return false;},checkMaintenanceError:function(asyncResponse){if(asyncResponse.getError()==1356007){this.maintenanceShutdown();return true;}
return false;},permaShutdown:function(){this.isPermaShutdown=true;this.shutdown();},loginShutdown:function(){var reason=_tx("Your session has timed out. Please log in.");this.shutdown(false,reason);},connectionShutdown:function(shouldDelay){var reason=_tx("\u76ee\u524d\u7121\u6cd5\u9023\u7dda\u5230 Facebook {Chat}\u3002",{'Chat':_tx("\u804a\u5929\u5ba4")});this.shutdown(shouldDelay,reason);},maintenanceShutdown:function(){var reason=_tx("Facebook {Chat} \u73fe\u5728\u7dad\u8b77\u4e2d\uff0c\u7121\u6cd5\u4f7f\u7528\u3002",{'Chat':_tx("\u804a\u5929\u5ba4")});this.shutdown(false,reason);channelManager.stop();},versionShutdown:function(){var reason=_tx("\u8acb\u91cd\u65b0\u6574\u7406 (refresh) \u7db2\u9801\uff0c\u4ee5\u53d6\u5f97\u6700\u65b0\u7248\u7684 Facebook {Chat}\u3002",{'Chat':_tx("\u804a\u5929\u5ba4")});this.shutdown(false,reason);channelManager.stop();},shutdown:function(shouldDelay,reason){this.isRestarting=false;this.isShuttingDown=true;var now=(new Date()).getTime();this.shutdownTime=now;if(!shouldDelay){this._shutdown(reason,0);}else{setTimeout(this._shutdown.bind(this,reason,now),this.shutdownDelay);}},_shutdown:function(reason,shutdownTime){if(!this.isShuttingDown&&shutdownTime==this.shutdownTime){return;}
if(shutdownTime&&this.isShutdown){return;}
if(typeof reason!='string'||!reason){reason=_tx("Facebook {Chat} \u73fe\u6709\u6280\u8853\u6027\u554f\u984c\uff0c\u8acb\u898b\u8ad2\u3002",{'Chat':_tx("\u804a\u5929\u5ba4")});}
if(!this.inPopoutWindow){CSS.addClass(this.holder,'presence_error');set_inner_html($('presence_error_reason'),reason);}else{if(this.shutdownErrorDialog){this.shutdownErrorDialog.hide();}
this.shutdownErrorDialog=new ErrorDialog().setTitle(_tx("Facebook \u804a\u5929\u5ba4\u932f\u8aa4\u8a0a\u606f")).setBody(reason).show();}
if(this.isShutdown){return;}
this.warn("presence: shutting down");this.isShutdown=true;Arbiter.inform(PresenceMessage.SHUTDOWN,{sender:this});},restart:function(shouldDelay){this.isShuttingDown=false;this.isRestarting=true;if(!shouldDelay){this._restart(0);}else{setTimeout(this._restart.bind(this,this.shutdownTime),this.restartDelay);}},_restart:function(shutdownTime){if(!this.isRestarting||(shutdownTime&&shutdownTime!=this.shutdownTime)){return;}
this.debug("presence: restarting");this.isShutdown=false;this.load();Arbiter.inform(PresenceMessage.RESTARTED,{sender:this});if(!this.inPopoutWindow){CSS.removeClass(this.holder,'presence_error');}else{if(this.shutdownErrorDialog){this.shutdownErrorDialog.hide();}}},start:function(){Arbiter.inform(PresenceMessage.STARTED,{sender:this});},registerStateStorer:function(fn){this.stateStorers.push(fn);},registerStateLoader:function(fn){this.stateLoaders.push(fn);},registerTempTabCloseHandler:function(handler){this.tempTabCloseHandler=handler;}};function getFirstName(name){var words=name.split(" ");var fname=words[0];var flen=fname.length;if(typeof words[1]!='undefined'&&(flen==1||(flen==2&&fname.indexOf('.')!=-1)||(flen==3&&fname.toLowerCase()=='the'))){fname+=' '+words[1];}
return fname;}

function ChatTab(chatDisplay,id,name,firstName,numMissed,missedTime){this.chatDisplay=chatDisplay;this.id=id;this.name=name;this.messageTypes={'msg':{visible:true,user:true,preserveHistory:false},'online':{visible:true,user:false,preserveHistory:true}};this.arbiter=new Arbiter();Arbiter.inform(ChatTab.GLOBALMESSAGETYPE.NEWTAB,{tab:this});this.tabRef='chatDisplay.tabs['+this.id+']';this.firstName=firstName;this.tabDisabled=false;this.numMissed=numMissed;this.missedTime=missedTime;this.focused=false;this.lastLogItem=null;this.historyLoaded=false;this.pendingSentMsgs=[];this.failedSentMsgs=[];this.sendingDisplayMsgID=null;this.historyRequestID=0;this.bounceAnimation=null;this.convTextProcessor=this._processConvText.bind(this);this.convTextEmoteProcessor=this._processConvTextEmote.bind(this);this.minTextHeight=presence.inPopoutWindow?this.minTextHeightPopout:this.minTextHeightPopin;this.typingState=this.INACTIVE;this.typingRemoteState=this.INACTIVE;this.typingLastKeystrokeAt=null;this.typingNotifyTimer=null;this.typingCheckTimer=null;this.lastMessageAt=null;this.lastMessageHadOfflineResponse=false;this._buildUI();this.addPopoutChat(id);this.loadData();this.handleVisibility(true);Sound.init();if(presence.inVideoChat){this.videochat_swf=ge(CallCenter.call(this.id)._callSWFID());}}
copy_properties(ChatTab,{GLOBALMESSAGETYPE:{NEWTAB:'chattabs/newtab'},TABMESSAGETYPE:{HISTORYBEGIN:'chattabs/historybegin',HISTORYITER:'chattabs/historyiter',HISTORYEND:'chattabs/historyend',CREATETAB:'chattabs/createtab',RECEIVEMSG:'chattabs/receivemsg',DISPLAYCHAT:'chattabs/displaychat',USERINFOUPDATED:'chattabs/userinfoupdated'}});copy_properties(ChatTab.prototype,{pendingToLogCompareWindow:60000,sendingCheckDelay:55000,sendingDisplayDelay:4000,convWrapLimit:30,handleWidth:136,popinWidth:226,popinHeight:250,popoutWidthOffset:180,flPopoutWidthOffset:200,minTextHeightPopin:13,minTextHeightPopout:26,maxTextHeight:77,msgBunchTime:60000,maxHandleLen:16,maxTitleLen:20,bounceDuration:50,bounceOrgPosition:-3,typingNotifyDelay:1000,typingKeystrokeExpiry:7000,INACTIVE:0,TYPING:1,isTabVisible:function(){return this.focused&&(presence.inPopoutWindow||!presence.poppedOut)&&(this.chatInfo.clientWidth>20);},start:function(){this._popSendQueue();},restart:function(){this.getHistory(true);this.handleResize.bind(this).defer();},loadData:function(){if(ChatUserInfos[this.id]){this.updateUserInfo();this.arbiter.inform(ChatTab.TABMESSAGETYPE.USERINFOUPDATED,{userInfo:ChatUserInfos[this.id]});}else{this.chatDisplay.loadInitialUserInfo(this.id,this.name,this.firstName);}
if(this.chatDisplay.histories[this.id]){this._setHistory(this.chatDisplay.histories[this.id]);}},_onHistoryInitialHandler:function(requestID,response){if(requestID!=this.historyRequestID){presence.debug("tabs: got old history async, ignoring");return false;}},_onHistoryResponse:function(fromRestart,response){var historyPayload=response.getPayload();var userInfo=historyPayload.userInfo;var logItems=historyPayload.history;ChatUserInfos[this.id]=userInfo;buddyList.updateItemDisplay(this.id);this.updateUserInfo();this.arbiter.inform(ChatTab.TABMESSAGETYPE.USERINFOUPDATED,{userInfo:userInfo});if(historyPayload.fls){buddyList.setFlids(this.id,historyPayload.fls);}
if(historyPayload.overlay){buddyList.addOverlayInfo(historyPayload.overlay);}
if(!logItems){this._showHistoryError();return;}
var poppedSendQueue=false;if(this.pendingSentMsgs.length>0&&logItems.length>0){var pendingSendMsg=this.pendingSentMsgs[0];for(var i=logItems.length-1;i>=0;i--){var logItem=logItems[i];if(logItem.to==this.id){var timeDiff=Math.abs(pendingSendMsg.time-logItem.time);if(timeDiff<this.pendingToLogCompareWindow&&pendingSendMsg.text==logItem.msg.text){this._setMsgInfoMarkup(pendingSendMsg.msgID,'');this.pendingSentMsgs.shift();this._popSendQueue();this.poppedSendQueue=true;break;}}}
var lastLogTime=logItems[logItems.length-1].time;for(var i=0;i<this.pendingSentMsgs.length;i++){var pendingSendMsg=this.pendingSentMsgs[i];if(pendingSendMsg.time<lastLogTime){pendingSendMsg.time=(++lastLogTime);}}}
var pendingLogMsgs=this.chatDisplay.histories[this.id];if(pendingLogMsgs){if(logItems.length>0){var lastLogItem=logItems[logItems.length-1];var lastTime=lastLogItem.time;for(var i=0;i<pendingLogMsgs.length;i++){var logItem=pendingLogMsgs[i];if(logItem.time>lastTime){logItems.push(logItem);}}}else{logItems=pendingLogMsgs;}}
this._setHistory(logItems);this.chatDisplay.histories[this.id]=logItems;if(fromRestart){if(!poppedSendQueue){this._popSendQueue();}}},_onHistoryError:function(response){this._showHistoryError();},_showHistoryError:function(){show(this.chatHistoryError);this.scrollToBottom();},getHistory:function(fromRestart){var requestID=++(this.historyRequestID);new AsyncRequest().setInitialHandler(this._onHistoryInitialHandler.bind(this,requestID)).setHandler(this._onHistoryResponse.bind(this,fromRestart)).setErrorHandler(this._onHistoryError.bind(this)).setTransportErrorHandler(this._onHistoryError.bind(this)).setMethod('GET').setReadOnly(true).setOption('suppressErrorAlerts',true).setData({'id':this.id}).setURI('/ajax/chat/history.php').send();},_setHistory:function(logItems){this.lastLogItem=null;var markup='';var sentIndex=0;var sentMsgs=[];Array.prototype.push.apply(sentMsgs,this.failedSentMsgs);Array.prototype.push.apply(sentMsgs,this.pendingSentMsgs);var prevItemTime=0;var anyVisibleMessages=false;this.arbiter.inform(ChatTab.TABMESSAGETYPE.HISTORYBEGIN);for(var i=0;i<logItems.length;i++){var logItem=logItems[i];if(typeof this.messageTypes[logItem.type]==undefined){continue;}
if(!this.messageTypes[logItem.type].preserveHistory){anyVisibleMessages=true;}
for(;sentIndex<sentMsgs.length;sentIndex++){var sentMsg=sentMsgs[sentIndex];if(!this.messageTypes[sentMsg.type].preserveHistory){anyVisibleMessages=true;}
if(sentMsg.time>prevItemTime&&sentMsg.time<=logItem.time){if(this.messageTypes[sentMsg.type].visible){markup+=this._renderMsg(presence.user,this.id,sentMsg.time,sentMsg,sentMsg.msgID,sentMsg.isError,sentMsg.infoMarkup);}}else{break;}}
if(logItem.type=='msg'){markup+=this._renderMsg(logItem.from,logItem.to,logItem.time,logItem.msg);}else if(logItem.type=='online'){markup+=this._renderVisibilityChange(logItem.time,logItem.text);}else{this.arbiter.inform(ChatTab.TABMESSAGETYPE.HISTORYITER,{item:logItem});}
this.lastLogItem=logItem;prevItemTime=logItem.time;}
this.arbiter.inform(ChatTab.TABMESSAGETYPE.HISTORYEND);for(;sentIndex<sentMsgs.length;sentIndex++){var sentMsg=sentMsgs[sentIndex];if(this.messageTypes[sentMsg.type].visible){markup+=this._renderMsg(presence.user,this.id,sentMsg.time,sentMsg,sentMsg.msgID,sentMsg.isError,sentMsg.infoMarkup);this.lastLogItem={'type':sentMsg.type,'from':presence.user,'to':this.id,'time':sentMsg.time,'msg':sentMsg};}}
hide(this.chatHistoryError);this.chatConvContent.innerHTML=markup;this.scrollToBottom();if(this.actions.setVisible('clearHistory',anyVisibleMessages).refresh()){this.handleResize();}
this.historyLoaded=true;},_onClearHistoryError:function(response){var chat=_tx("\u804a\u5929\u5ba4");presence.showAsyncError(response,_tx("\u7121\u6cd5\u6e05\u9664{Chat}\u8a18\u9304",{'Chat':chat}));CSS.removeClass(this.tabHandle,'history_clearing');},_onClearHistoryResponse:function(response){CSS.removeClass(this.tabHandle,'history_clearing');var newHistory=[];for(var i=0;i<this.chatDisplay.histories[this.id].length;i++){var item=this.chatDisplay.histories[this.id][i];if(typeof this.messageTypes[item.type]=='undefined'||this.messageTypes[item.type].preserveHistory){newHistory.push(item);}}
this._setHistory(this.chatDisplay.histories[this.id]=newHistory);},clearHistory:function(){CSS.addClass(this.tabHandle,'history_clearing');new AsyncRequest().setHandler(this._onClearHistoryResponse.bind(this)).setErrorHandler(this._onClearHistoryError.bind(this)).setTransportErrorHandler(this._onClearHistoryError.bind(this)).setData({'clear_history_id':this.id}).setURI(this.chatDisplay.settingsURL).send();},_isCurrentPendingSend:function(msgID){return(this.pendingSentMsgs.length>0&&msgID==this.pendingSentMsgs[0].msgID);},_onSendInitialHandler:function(response){this.lastMessageHadOfflineResponse=false;},_onSendResponse:function(msgID,response){var payload=response.getPayload();if(this._isCurrentPendingSend(msgID)){var pendingMsg=this.pendingSentMsgs[0];pendingMsg.asyncSuccess=true;}
if(payload&&payload.warning){var warningMarkup=this._renderMsgWarningMarkup(payload.warning.title+'<br />'+payload.warning.body);this._setMsgInfoMarkup(msgID,warningMarkup,'msg_warning');}},_onSendTransportError:function(msgID,response){if(!this._isCurrentPendingSend(msgID)){return;}},_onSendError:function(msgID,response){if(!this._isCurrentPendingSend(msgID)){return;}
var payload=response.getPayload();var error=response.getError();var desc=presence.getErrorDescription(response);if(error==kError_Chat_SendOtherNotAvailable){this.lastMessageHadOfflineResponse=true;buddyList.setUnavailable(this.id);for(var i=0;i<this.pendingSentMsgs.length;i++){var msg=this.pendingSentMsgs[i];var msgElement=ge('msg_'+this.id+'_'+msg.msgID);if(msgElement){var onclick;if(window.GigaboxxLinkHandler){onclick=sprintf('onclick="GigaboxxLinkHandler.showDialog(%s);'+'return false;"',JSON.encode({id:this.id,message:msg.text}));}else{onclick=sprintf('onclick="message_dialog.show(%d,%e,%e);'+'return false;"',this.id,'',msg.text);}
var link=presence.renderLink(this.chatDisplay.messageURL+'&id='+this.id,_tx("\u4ee5\u8a0a\u606f\u65b9\u5f0f\u50b3\u9001"),onclick);var markup=_tx("{message} ({=send as a message})",{'message':this._renderMsgHtmlize(msg),'=send as a message':link});set_inner_html(msgElement,markup);}}}
else if(error==kError_Chat_NotAvailable){this.lastMessageHadOfflineResponse=true;chatOptions.setVisibility(false);presence.doSync();}
else if(error==kError_Chat_TooManyMessages){desc=payload.error.title;new ErrorDialog().showError(payload.error.title,payload.error.body);}
else{new ErrorDialog().showError(response.errorSummary,response.errorDescription);}
this._sendErrorAll(desc);},_renderMsgWarningMarkup:function(desc){return'<p class="chat_notice chat_msg_warning">'+
desc+'</p>';},_renderMsgErrorMarkup:function(desc){return'<p class="chat_notice chat_msg_not_sent">'+
desc+'</p>';},_sendErrorAll:function(desc){var errorMarkup=this._renderMsgErrorMarkup(desc);var isFirst=true;while(this.pendingSentMsgs.length){var pendingMsg=this.pendingSentMsgs.shift();pendingMsg.isError=true;if(isFirst){pendingMsg.infoMarkup=errorMarkup;}
this._setMsgInfoMarkup(pendingMsg.msgID,errorMarkup,'msg_error');this.failedSentMsgs.push(pendingMsg);isFirst=false;errorMarkup='';}},_sendError:function(msgID,desc){var errorMarkup=this._renderMsgErrorMarkup(desc);var pendingMsg=this.pendingSentMsgs.shift();pendingMsg.isError=true;pendingMsg.infoMarkup=errorMarkup;this._setMsgInfoMarkup(msgID,errorMarkup,'msg_error');this.failedSentMsgs.push(pendingMsg);this._popSendQueue();this._bumpSendingMessageDisplay(msgID);},_createMessage:function(text,type){var msgID=rand32()+1;var time=presence.getTime();if(this.lastLogItem&&time<this.lastLogItem.time){time=this.lastLogItem.time+1;}
var pendingMsg={text:text,msgID:msgID,type:type,time:time,asyncSuccess:false,isError:false,errorMarkup:''};return pendingMsg;},_flushSmallQueue:function(){if(this.pendingSentMsgs.length==1){this._sendMessage(this.pendingSentMsgs[0],!channelManager.iframeEverLoaded);}},_updateChatActivity:function(pendingMsg,msg){this.lastLogItem={'type':pendingMsg.type,'from':presence.user,'to':this.id,'time':pendingMsg.time,'msg':msg};this.chatDisplay.chatActivityTime=(new Date()).getTime();presence.doSync();},sendInput:function(){var text=this.chatInput.value;if(!text||!text.match(/[^\s]/)){return;}
if(this.actions.setVisible('clearHistory',true).refresh()){this.handleResize();}
this.chatInput.value='';var pendingMsg=this._createMessage(text,'msg');this.pendingSentMsgs.push(pendingMsg);this._flushSmallQueue();var msg={'text':text};var sendMarkup=this._renderMsg(presence.user,this.id,pendingMsg.time,msg,pendingMsg.msgID);this._addConvMarkup(sendMarkup);this._updateChatActivity(pendingMsg,msg);this._resetTypingState();},notifyTypingState:function(state){if(state!=this.typingRemoteState){this.typingRemoteState=state;presence.debug('tabs: notifyTyping('+state+')');if(!channelManager.iframeEverLoaded){return;}
var data={'typ':state,'to':this.id};new AsyncRequest().setHandler(bagofholding).setErrorHandler(bagofholding).setTransportErrorHandler(bagofholding).setData(data).setURI('/ajax/chat/typ.php').send();}},_sendMessage:function(pendingMsg,timeoutOnly){pendingMsg.time=presence.getTime();if(this.lastLogItem&&pendingMsg.time<this.lastLogItem.time){pendingMsg.time=this.lastLogItem.time+1;}
clearTimeout(this.sendingDisplayTimeout);clearTimeout(this.checkMessageSentTimeout);this.sendingDisplayTimeout=setTimeout(this._checkMessageSentShort.bind(this,pendingMsg.msgID),this.sendingDisplayDelay);this.checkMessageSentTimeout=setTimeout(this._checkMessageSentLong.bind(this,pendingMsg.msgID),this.sendingCheckDelay);if(timeoutOnly){return;}
var msgID=pendingMsg.msgID;var history=this.chatDisplay.histories[this.id];var lastConvoTime=null;if(history){for(var i=history.length-1;i>0;i--){if(history[i].type=='msg'){lastConvoTime=history[i].time;break;}}}
var sendData={msg_id:msgID,client_time:pendingMsg.time,to:this.id,num_tabs:this.chatDisplay.numTabs,pvs_time:lastConvoTime};if(pendingMsg.type=='video'){sendData.action=pendingMsg.action;sendData.uid=pendingMsg.uid;var endpoint='/ajax/chat/video.php';}else{sendData.msg_text=pendingMsg.text;var endpoint='/ajax/chat/send.php';}
new AsyncRequest().setInitialHandler(this._onSendInitialHandler.bind(this)).setHandler(this._onSendResponse.bind(this,msgID)).setErrorHandler(this._onSendError.bind(this,msgID)).setTransportErrorHandler(this._onSendTransportError.bind(this,msgID)).setData(sendData).setURI(endpoint).send();},_popSendQueue:function(){if(this.pendingSentMsgs.length==0){return;}
var pendingMsg=this.pendingSentMsgs[0];this._sendMessage(pendingMsg);},_checkMessageSentShort:function(msgID){if(this._isCurrentPendingSend(msgID)){this._setSendingDisplay(this.pendingSentMsgs[0]);}},_checkMessageSentLong:function(msgID){if(this._isCurrentPendingSend(msgID)){if(this.pendingSentMsgs[0].asyncSuccess){this._sendErrorAll(_tx("\u76ee\u524d\u7121\u6cd5\u9023\u7dda\u5230 Facebook {Chat}\u3002",{'Chat':_tx("\u804a\u5929\u5ba4")}));}else if(channelManager.iframeIsLoaded){presence.error('tabs: send took too long; resending and invalidating old one');this._sendMessage(this.pendingSentMsgs[0]);}else{presence.error("tabs: send took too long, but iframe isn't yet loaded.  will check again later.");setTimeout(this._checkMessageSentLong.bind(this,this.pendingSentMsgs[0].msgID),this.sendingCheckDelay);}}},_bumpSendingMessageDisplay:function(msgID){if(msgID==this.sendingDisplayMsgID){this._setMsgInfoMarkup(msgID,'');if(this.pendingSentMsgs.length>0){this._setSendingDisplay(this.pendingSentMsgs[0]);}}},_setSendingDisplay:function(pendingMsg){this.sendingDisplayMsgID=pendingMsg.msgID;pendingMsg.infoMarkup='<p class="chat_notice sending">'+
_tx("\u50b3\u9001\uff1a")+'</p>';this._setMsgInfoMarkup(pendingMsg.msgID,pendingMsg.infoMarkup);},_setMsgInfoMarkup:function(pendingMsgID,markup,msgClass){var msgElement=ge('msg_'+this.id+'_'+pendingMsgID);if(!msgElement){return;}
var infoElement=ge('pending_'+this.id+'_'+pendingMsgID);if(infoElement){infoElement.innerHTML=markup;}
if(msgClass){CSS.addClass(msgElement,msgClass);}
this.scrollToBottom();},updateUserInfo:function(){this.chatInfoPic.src=ChatUserInfos[this.id].thumbSrc;CSS.removeClass(this.chatInfo,'hidden');},tabHitAreaOnClick:function(){if(this.suppressHeaderCollapse){return;}
if(!presence.inVideoChat){if(presence.inPopoutWindow){this.chatDisplay.focusTab(this.id,this.name,this.firstName);}else{this.chatDisplay.toggleTab(this.id,this.name,this.firstName);}}
this.chatDisplay.doStopBlinking();},showChat:function(){if(presence.inVideoChat){animation(this.chatWrapper).to('right','0').duration(300).ease(animation.ease.end).go();animation(this.videochat_swf).to('marginRight','226px').duration(300).ease(animation.ease.end).go();this.arbiter.inform(ChatTab.TABMESSAGETYPE.DISPLAYCHAT,{visible:true});}},tabXOnClick:function(e){if(presence.inVideoChat){animation(this.chatWrapper).to('right','-228px').duration(300).ease(animation.ease.end).go();animation(this.videochat_swf).to('marginRight','0').duration(300).ease(animation.ease.end).go();this.arbiter.inform(ChatTab.TABMESSAGETYPE.DISPLAYCHAT,{visible:false});}else{this.chatDisplay.closeTab(this.id);this.chatDisplay.doStopBlinking();}
$E(e).kill();},headerLinkMouseOver:function(){CSS.addClass(this.chatHeader,'suppress_hover');this.suppressHeaderCollapse=true;},headerLinkMouseOut:function(){CSS.removeClass(this.chatHeader,'suppress_hover');this.suppressHeaderCollapse=false;},chatConvOnMouseDown:function(event){event=$E(event);if(event.button!=0){return;}
this.chatDisplay.doStopBlinking();},chatConvOnMouseUp:function(){if(DOM.getSelectionSupported()&&(DOM.getSelection()=='')){this.focusChatInput();}},focusChatInput:function(){if(!this.tabDisabled&&this.isTabVisible()){this.chatInput.focus();}},_buildUI:function(){var tabCountID='missed_count_'+this.id;var chatWindowWrapperID='chat_window_wrapper_'+this.id;var chatConvID='chat_conv_'+this.id;var chatHistoryErrorID='chat_history_error_'+this.id;var chatHeaderID='chat_header_'+this.id;var chatInfoID='chat_info_'+this.id;var chatInfoPicID='chat_info_pic_'+this.id;var chatConvContentID='chat_conv_content_'+this.id;var chatInputID='chat_input_'+this.id;var chatShadowInputID='chat_shadow_input_'+this.id;var chatToolboxID='chat_toolbox_'+this.id;var chat=_tx("\u804a\u5929\u5ba4");var handleName=htmlize(this.trimName(this.maxHandleLen));var titleName=htmlize(this.trimName(this.maxTitleLen));var chatHeaderLinkMouseOver=' onmouseover="'+this.tabRef+'.headerLinkMouseOver();" onmouseout="'+this.tabRef+'.headerLinkMouseOut();"';var profileURL=this.chatDisplay.profileURL+'?id='+this.id;var chatHeaderPicLink=presence.renderLink(profileURL,'<img class="chat_info_pic" id="'+chatInfoPicID+'" title="View Profile" style="display:block;">',chatHeaderLinkMouseOver);var chatHeaderNameLink=presence.renderLink(profileURL,titleName,chatHeaderLinkMouseOver);var tabMarkupArr=['<div class="tab_button_div" ','onmouseover="CSS.addClass(this, \'hover\')" ','onmouseout="CSS.removeClass(this, \'hover\')">','<div title="',_tx("\u986f\u793a\u6216\u96b1\u85cf{Chat}\u8996\u7a97",{'Chat':chat}),'" ','class="tab_hit_area" ','onclick="',this.tabRef,'.tabHitAreaOnClick()">','<div class="tab_name">','<span>',handleName,'</span>','<img src="http://static.ak.fbcdn.net/images/spacer.gif"','class="tab_availability" alt="',handleName,'"/>','</div>','</div>','<div class="tab_count" id="',tabCountID,'"></div>','<div title="',_tx("\u95dc\u9589{Chat}\u8996\u7a97",{'Chat':chat}),'" ','class="tab_x" ','onclick="',this.tabRef,'.tabXOnClick(event)" ','onmouseover="CSS.addClass(this, \'hover\')" ','onmouseout="CSS.removeClass(this, \'hover\')">','</div>','<div class="chat_window_wrapper" id="',chatWindowWrapperID,'">','<div class="chat_window">','<div class="chat_header" id="',chatHeaderID,'" onclick="',this.tabRef,'.tabHitAreaOnClick()">','<div class="header_buttons">','<a title="',_tx("\u95dc\u9589{Chat}\u8996\u7a97",{'Chat':chat}),'" ','class="close" ','onmouseover="CSS.addClass($(\'',chatHeaderID,'\'), \'suppress_hover\')" ','onmouseout="CSS.removeClass($(\'',chatHeaderID,'\'), \'suppress_hover\')" ','onclick="',this.tabRef,'.tabXOnClick(event)">','</a>','<a title="',_tx("\u96b1\u85cf{Chat}\u8996\u7a97",{'Chat':chat}),'" ','class="minimize">','</a>','</div>',chatHeaderPicLink,'<div class="chat_header_name">',chatHeaderNameLink,'</div>','</div>','<div class="chat_info" id="',chatInfoID,'">','&nbsp;','</div>','<div id="',chatToolboxID,'" class="toolbox">','<div class="chat_actions"></div>','</div>','<div class="chat_conv" id="',chatConvID,'" ','onmousedown="',this.tabRef,'.chatConvOnMouseDown(event)" ','onmouseup="',this.tabRef,'.chatConvOnMouseUp()">','<div class="chat_notice" id="',chatHistoryErrorID,'" style="display:none">',_tx("\u7121\u6cd5\u627e\u56de\u5c0d\u8a71\u8a18\u9304"),'</div>','<div class="chat_conv_content" id="',chatConvContentID,'"></div>','</div>','<div class="chat_input_div">','<textarea class="chat_shadow_input" id="',chatShadowInputID,'"></textarea>','<div class="chat_input_icon"></div>','<textarea class="chat_input" id="',chatInputID,'" ','onclick="chatDisplay.doStopBlinking()" ','onkeydown="return ',this.tabRef,'.inputKeyDown(event)" ','onkeypress="return ',this.tabRef,'.inputKeyPress(event)" ','></textarea>','<div class="chat_input_border"></div>','</div>','</div>','</div>','</div>'];this.tabHandle=document.createElement('div');var chatTabBar=ge('chat_tab_bar');var otherTab=null;for(var id in this.chatDisplay.tabs){otherTab=this.chatDisplay.tabs[id];}
if(otherTab){chatTabBar.insertBefore(this.tabHandle,otherTab.tabHandle);}else{chatTabBar.appendChild(this.tabHandle);}
this.tabHandle.id='tab_handle_'+this.id;CSS.setClass(this.tabHandle,'tab_handle');this.tabHandle.style.width=this.handleWidth+'px';this.tabHandle.style.display='block';this.tabHandle.innerHTML=tabMarkupArr.join('');this.tabCount=ge(tabCountID);this.chatWrapper=ge(chatWindowWrapperID);this.chatConv=ge(chatConvID);this.chatHistoryError=ge(chatHistoryErrorID);this.chatHeader=ge(chatHeaderID);this.chatInfo=ge(chatInfoID);this.chatInfoPic=ge(chatInfoPicID);this.chatConvContent=ge(chatConvContentID);this.chatInput=ge(chatInputID);this.chatShadowInput=ge(chatShadowInputID);this.toolbox=ge(chatToolboxID);var chatActions=DOM.find(this.toolbox,'div.chat_actions');this.actions=new ChatTabActions(chatActions);this.actions.appendAction('clearHistory',_tx("\u522a\u9664{Chat}\u5c0d\u8a71\u8a18\u9304",{'Chat':chat}),this.clearHistory.bind(this));this.arbiter.inform(ChatTab.TABMESSAGETYPE.CREATETAB,{toolbox:this.toolbox});this.actions.refresh();this.popoutChatTabs=presence.inPopoutWindow?ge('open_chats'):null;this.adjustWrapperBottom();this._updateNumMissedDisplay();},adjustWrapperBottom:function(){if(presence.isFF2){var holderBottom=presence.getHolderBottomPosition();CSS.setStyle(this.chatWrapper,'bottom',(holderBottom+24)+'px');}},show:function(){this.tabHandle.style.display='block';},hide:function(){this.tabHandle.style.display='none';},inputKeyDown:function(event){event=$E(event);this.chatDisplay.doStopBlinking();if(this.chatDisplay.gatedFeatures.typ_send){this._updateTyping.bind(this).defer();}
if(event.keyCode==KEYS.RETURN&&!event.shiftKey){if(this.chatInput.value){this.sendInput();}}
if(event.keyCode==KEYS.DELETE||event.keyCode==KEYS.BACKSPACE){this.handleResize.bind(this).defer();}},inputKeyPress:function(event){event=$E(event);this.handleResize.bind(this).defer();if(event.keyCode==KEYS.RETURN&&!event.shiftKey){event.returnValue=false;return false;}},_updateTyping:function(){var state=this.typingState;if(this.chatInput.value.length==0){if(state==this.INACTIVE){}else{this._typingTransition(this.INACTIVE);}}
else if(state==this.TYPING){this._recordKeystroke();}
else if(state==this.INACTIVE){this._typingTransition(this.TYPING);this._recordKeystroke();}},_recordKeystroke:function(){this.typingLastKeystrokeAt=new Date();if(!this.typingCheckTimer){this.typingCheckTimer=setTimeout(this._checkTyping.bind(this),this.typingKeystrokeExpiry);}},_checkTyping:function(){var expiresAt=this.typingLastKeystrokeAt.valueOf()+this.typingKeystrokeExpiry;var now=new Date().valueOf();if(now>expiresAt){this._typingTransition(this.INACTIVE);}else{clearTimeout(this.typingCheckTimer);this.typingCheckTimer=setTimeout(this._checkTyping.bind(this),expiresAt-now+10);}},_typingTransition:function(newState){clearTimeout(this.typingCheckTimer);this.typingCheckTimer=null;typingLastKeystrokeAt=null;presence.debug('typing:'+this.typingState+' -> '+newState);this.typingState=newState;clearTimeout(this.typingNotifyTimer);this.typingNotifyTimer=setTimeout(this.notifyTypingState.bind(this,newState),this.typingNotifyDelay);},_resetTypingState:function(){presence.debug('typing: ** RESET **');this.typingState=this.INACTIVE;this.typingRemoteState=this.INACTIVE;this.typingLastKeystrokeAt=null;clearTimeout(this.typingNotifyTimer);this.typingNotifyTimer=null;clearTimeout(this.typingCheckTimer);this.typingCheckTimer=null;},trimName:function(maxLength){var name=this.name;if(name.length>maxLength){name=name.substring(0,maxLength-2)+'...';}
return name;},handleVisibility:function(onload){var justCameOnline=chatOptions.visibility;if(chatOptions.visibility){this._enableTab(true,false,justCameOnline,onload);}else{this._disableTab(true,justCameOnline,onload);}
this.handleBuddyAvailability(!onload&&justCameOnline,onload);},handleBuddyAvailability:function(justCameOnline,onload){if(!chatOptions.visibility){return;}
var availability=buddyList.getAvailability(this.id);if(availability){this._enableTab(false,availability.i,justCameOnline,onload);}else{this._disableTab(false,justCameOnline,onload);}},_enableTab:function(isYou,isIdle,justCameOnline,onload){onload=onload||false;var wasDisabled=this.tabDisabled;this.tabDisabled=false;if(presence.inPopoutWindow){CSS.removeClass(this.popoutTab,'disabled');CSS.conditionClass(this.popoutTab,'idle',isIdle);}
CSS.removeClass(this.tabHandle,'disabled');CSS.conditionClass(this.tabHandle,'idle',isIdle);if((isYou&&!onload)||(!isYou&&wasDisabled&&!justCameOnline)){this._newVisibilityChange(isYou,onload,true);}},_disableTab:function(isYou,justCameOnline,onload){onload=onload||false;var wasDisabled=this.tabDisabled;this.tabDisabled=true;if(presence.inPopoutWindow){CSS.addClass(this.popoutTab,'disabled');CSS.removeClass(this.popoutTab,'idle');}
CSS.addClass(this.tabHandle,'disabled');CSS.removeClass(this.tabHandle,'idle');if((isYou||onload||!wasDisabled)&&!this.lastMessageHadOfflineResponse&&!justCameOnline){this._newVisibilityChange(isYou,onload,false);}},handleResize:function(){var newConvWidth;var newTextWidth;var newNotAvailWidth;var newTabHeight;var heightExtra=31;var toolboxChildren=this.toolbox.childNodes;for(var i=0;i<toolboxChildren.length;++i){var child=toolboxChildren[i];if(shown(child)){heightExtra+=Vector2.getElementDimensions(child).y;}}
if(presence.inVideoChat||presence.inPopoutWindow){var chatInfoMinHeight=33;heightExtra+=Vector2.getElementDimensions(this.chatInfo).y-chatInfoMinHeight;}
if(presence.inVideoChat){var videoChatWidth=226;newConvWidth=videoChatWidth;newTextWidth=videoChatWidth-28;newNotAvailWidth=videoChatWidth-16;newTabHeight=presence.popoutHeight-77;}else if(presence.inPopoutWindow){var popoutWidth=(presence.popoutWidth>330)?presence.popoutWidth:330;newConvWidth=popoutWidth-this.flPopoutWidthOffset;newTextWidth=popoutWidth-this.flPopoutWidthOffset-28;newNotAvailWidth=popoutWidth-this.flPopoutWidthOffset-16;newTabHeight=presence.popoutHeight-77;}else{newConvWidth=this.popinWidth;newTextWidth=this.popinWidth-28;newNotAvailWidth=this.popinWidth-8;newTabHeight=this.popinHeight;}
this.chatShadowInput.style.width=this.chatInput.style.width=newTextWidth+'px';this.chatShadowInput.value=this.chatInput.value;var textHeight=this.chatShadowInput.scrollHeight;if(!textHeight||presence.isOpera){textHeight=this.minTextHeight;if(this.chatInput.value){var re=new RegExp('([\n]|[^\n]{'+parseInt(newTextWidth/8)+'})','g');var matches=this.chatInput.value.match(re);if(matches){textHeight=(matches.length+1)*this.minTextHeight;}}
if(presence.isSafari2){textHeight+=8;}}
if(ua.ie()){textHeight-=6;}
if(textHeight>this.maxTextHeight){textHeight=this.maxTextHeight;}else if(textHeight<this.minTextHeight){textHeight=this.minTextHeight;}
if(presence.isSafari2){heightExtra-=7;}else if(ua.ie()<7){if(this.tabDisabled){heightExtra+=4;}}
if(!presence.inPopoutWindow||ua.ie()){this.chatHeader.style.width=newConvWidth+'px';this.chatInfo.style.width=(newConvWidth-55)+'px';this.chatConv.style.width=newConvWidth+'px';}
this.chatInput.style.height=textHeight+'px';this.chatConv.style.height=Math.max(0,(newTabHeight-heightExtra-textHeight))+'px';this.scrollToBottom();},isUserScrolled:function(){return(this.chatConv.scrollHeight>this.chatConv.scrollTop+this.chatConv.clientHeight);},scrollToBottom:function(){this.chatConv.scrollTop=this.chatConv.scrollHeight;},unfocus:function(){this.focused=false;CSS.removeClass(this.tabHandle,'focused');},focus:function(hidden,chatDisplayLoaded){if(this.focused){return;}
CSS.addClass(this.tabHandle,'focused');this.focused=true;if(!hidden){this._onFocusUIActions();setTimeout(this._onFocusUIActions.bind(this),100);}
if(!this.historyLoaded){this.getHistory(false);}
this._updateNumMissed(0);this._stopBounce();},_onFocusUIActions:function(){this.handleResize();if(ua.ie()<7&&presence.inPopoutWindow){this.chatWrapper.style.top='67px';}
this.focusChatInput();},_startBounce:function(){if(presence.isFF2&&presence.isWindows){return;}
this.bounceAnimation=animation(this.tabCount).to('top',-11).duration(this.bounceDuration+40).checkpoint().to('top',this.bounceOrgPosition).duration(this.bounceDuration).checkpoint().to('top',-11).duration(this.bounceDuration+40).checkpoint().to('top',this.bounceOrgPosition).duration(this.bounceDuration).checkpoint().to('top',-7).duration(this.bounceDuration).checkpoint().to('top',-5).duration(this.bounceDuration).checkpoint().to('top',this.bounceOrgPosition).duration(this.bounceDuration).checkpoint().go();},_stopBounce:function(){if(this.bounceAnimation){this.bounceAnimation.stop();this.bounceAnimation=null;}},close:function(){this.tabHandle.parentNode.removeChild(this.tabHandle);this.closePopoutChat();},addPopoutChat:function(id){if(this.popoutChatTabs){this.popoutTab=document.createElement('div');this.popoutTab.id='popout_tab_'+this.id;this.popoutTab.className='popout_tab_button'
+(this.chatDisplay.gatedFeatures.typ_show?'':' vanilla')
+((id==this.chatDisplay.focused)?' highlight':'');var popoutCountID='popout_missed_'+this.id;this.popoutTab.innerHTML='<div class="popout_tab_hit_area" onclick="'+this.tabRef+'.tabHitAreaOnClick();">'+'<div id="'+popoutCountID+'" class="popout_tab_count"></div>'+'<div class="popout_tab_name">'+this.name+'</div>'+'</div>'+'<div class="popout_tab_x" onclick="'+this.tabRef+'.tabXOnClick(event)"></div>';this.popoutChatTabs.appendChild(this.popoutTab);this.popoutTabCount=ge(popoutCountID);show(ge('popout_chat_tabs'));}},closePopoutChat:function(){if(this.popoutChatTabs){this.popoutChatTabs.removeChild(this.popoutTab);if(this.popoutChatTabs.childNodes.length<=0){hide(ge('popout_chat_tabs'));}}},selectPopoutChat:function(){CSS.addClass(this.popoutTab,'highlight');},deselectPopoutChat:function(){CSS.removeClass(this.popoutTab,'highlight');},_newVisibilityChange:function(isYou,onload,online){var time=presence.getTime();var text;if(isYou){if(online){text=_tx("\u4f60\u6b63\u5728\u7dda\u4e0a\u3002",{'name':this.firstName});}else{text=_tx("\u4f60\u6c92\u6709\u4e0a\u7dda\u3002",{'name':this.firstName});}}else{if(online){text=_tx("{name}\u5728\u7dda\u4e0a\u3002",{'name':this.firstName});}else{text=_tx("{name}\u5df2\u96e2\u7dda",{'name':this.firstName});}}
var item={'type':'online','time':time,'text':text};var history=this.chatDisplay.getHistory(this.id,true);history.push(item);var markup=this._renderVisibilityChange(time,text);this._addConvMarkup(markup);this.lastLogItem=item;},newTyping:function(msgItem){var from=msgItem.from;var to=msgItem.to;var typ=msgItem.st;if(!this.chatDisplay.gatedFeatures.typ_show){return;}
else if((new Date()-this.lastMessageAt)<this.typingNotifyDelay){return;}
presence.debug('typing from '+from+': '+typ);var show_typing=(typ==this.TYPING)&&(this.numMissed==0);if(to!=this.id){if(presence.inPopoutWindow){CSS.conditionClass(this.popoutTab,'typing',show_typing);}
CSS.conditionClass(this.tabHandle,'typing',show_typing);buddyList.setAvailable(this.id);}},_isChatMessage:function(message){return
typeof this.messageTypes[message.type]!='undefined'&&this.messageTypes[message.type].user;},newMsg:function(msgItem){var from=msgItem.from;var to=msgItem.to;var type=msgItem.type;var msg=msgItem.msg;var time=msg.time;var clientTime=msg.clientTime;var msgID=msg.msgID;var shouldRender=true;this.lastMessageAt=new Date();var history=this.chatDisplay.getHistory(this.id,true);var lastMsg=null;for(var i=history.length-1;i>=0;i--){if(this._isChatMessage(history[i])){lastMsg=history[i];break;}}
if(lastMsg&&time<=lastMsg.time){var found=false;for(var i=0;i<history.length;i++){if(this._isChatMessage(history[i])&&time==history[i].time){found=true;break;}}
if(found){presence.warn('tabs: already had this msg');return;}
for(var i=history.length-1;i>=0;i--){var historyItem=history[i];if(this._isChatMessage(historyItem)&&(historyItem.to!=to||(!historyItem.msg.clientTime||historyItem.msg.clientTime<clientTime))){break;}}
presence.warn('tabs: merging new msg due to out-of-order server timestamp');if(i==history.length-1){this.chatDisplay.histories[this.id].push(msgItem);}else{history.splice(i+1,0,msgItem);this._setHistory(history);shouldRender=false;}}else{this.chatDisplay.histories[this.id].push(msgItem);}
if(to!=this.id){if(this.chatDisplay.gatedFeatures.sound&&this.chatDisplay.isSoundWindow&&chatOptions.getSetting('sound')){Sound.play('/sound/pop.mp3');}
buddyList.setAvailable(this.id);if(!this.focused){this._updateNumMissed(this.numMissed+1,time);this._startBounce();}
if(presence.inPopoutWindow){CSS.removeClass(this.popoutTab,'typing');}
CSS.removeClass(this.tabHandle,'typing');}else{this._updateNumMissed(0,time);for(var i=0;i<this.pendingSentMsgs.length;i++){if(msgID==this.pendingSentMsgs[i].msgID){var pendingMsg=this.pendingSentMsgs.splice(i,1);this._bumpSendingMessageDisplay(msgID);this._popSendQueue();shouldRender=false;break;}}}
this.arbiter.inform(ChatTab.TABMESSAGETYPE.RECEIVEMSG,{type:type,msgItem:msgItem});shouldRender=this.messageTypes[type].visible&&shouldRender;if(shouldRender){var msgMarkup=this._renderMsg(from,to,time,msg);this._addConvMarkup(msgMarkup);if(this.actions.setVisible('clearHistory',true).refresh()){this.handleResize();}
this.lastLogItem=msgItem;}},getInputElemId:function(){return'chat_input_'+this.id;},_updateNumMissed:function(numMissed,time){if(numMissed==this.numMissed||(time&&time<=this.missedTime)){return;}
if(numMissed>99){numMissed=99;}
this.numMissed=numMissed;this.missedTime=time;this._updateNumMissedDisplay();},_updateNumMissedDisplay:function(){this.tabCount.innerHTML=this.numMissed;if(this.numMissed>0){if(this.popoutTabCount){this.popoutTabCount.style.display='block';this.popoutTabCount.innerHTML=this.numMissed;}else{chatTabSlider.updateMissedCount();}
CSS.addClass(this.tabHandle,'highlight');this.tabCount.style.display='block';}else{if(this.popoutTabCount){this.popoutTabCount.style.display='none';}else{chatTabSlider.updateMissedCount();}
CSS.removeClass(this.tabHandle,'highlight');this.tabCount.style.display='none';}},_addConvMarkup:function(markup){var isUserScrolled=this.isUserScrolled();this.chatConvContent.innerHTML+=markup;if(!isUserScrolled){this.scrollToBottom();}},_renderDateBreak:function(time){var newDate=new Date();newDate.setTime(time);var shouldRender=false;var lastDate=new Date();if(this.lastLogItem){lastDate.setTime(this.lastLogItem.time);}
if(newDate.getDate()!=lastDate.getDate()||newDate.getMonth()!=lastDate.getMonth()){shouldRender=true;}
var markup='';if(shouldRender){var classname='date_divider';if(!this.lastLogItem){classname+=' first';}
markup='<div class="'+classname+'">'+
renderDate(newDate,!presence.inPopoutWindow)+'</div>';}
return markup;},_renderVisibilityChange:function(time,visibilityMarkup){var markup=this._renderDateBreak(time);markup+='<div class="visibility_change">'+'<span class="time_stamp">'+
chatDisplay.renderServerTime(time)+'</span>'+
visibilityMarkup+'</div>';return markup;},_renderMsg:function(from,to,time,msg,pendingMsgID,isError,errorMarkup){var fromSelf=from!=this.id;var fromToSelf=fromSelf&&from==to;var msgClass=fromSelf&&!fromToSelf?'self':'other';var markup=this._renderDateBreak(time);if(!markup&&this.lastLogItem&&this.lastLogItem.type=='msg'&&this.lastLogItem.from==from&&time-this.lastLogItem.time<this.msgBunchTime){}else{var userInfo=ChatUserInfos[from];var pic=userInfo&&presence.inPopoutWindow?'<img src="'+userInfo.thumbSrc+'" class="pic" />':'';var name=fromSelf?htmlize(presence.firstName):presence.renderLink(this.chatDisplay.profileURL+'?id='+this.id,htmlize(this.firstName));var timeStr=chatDisplay.renderServerTime(time);markup+='<h5 class="'+msgClass+'">'+
pic+' <span class="time_stamp ts_'+msgClass+'">'+timeStr+'</span>'+
name+'</h5>';}
if(pendingMsgID||errorMarkup){var pendingElementID=pendingMsgID?' id="pending_'+this.id+'_'+pendingMsgID+'"':'';markup+='<div'+pendingElementID+' class="pic_padding">'+
(errorMarkup?errorMarkup:'')+'</div>';}
var msgElementID=pendingMsgID?' id="msg_'+this.id+'_'+pendingMsgID+'"':'';msgClasses='p_'+msgClass+' pic_padding'+
(isError?' msg_error':'');markup+='<p'+msgElementID+' class="'+msgClasses+'">'+
this._renderMsgHtmlize(msg)+'</p>';return markup;},_renderMsgHtmlize:function(msg){return html_hyperlink(msg.text||'',this._processStyledText.bind(this,this.convTextEmoteProcessor),this.convTextProcessor,true);},_processStyledText:function(textProcessor,str){return textProcessor(str).replace(/\b_([^_\*]+)_\b/g,'<u>$1</u>').replace(/(\s|^)\*([^_\*]+)\*(?=$|\s)/g,'$1<b>$2</b>');},_processConvText:function(str){return html_wordwrap(str,this.convWrapLimit);},_processConvTextEmote:function(str){return Emote.htmlEmote(str,this.convTextProcessor);}});function renderDate(date,showRelative){if(showRelative){var today=new Date();today.setHours(0);today.setMinutes(0);today.setSeconds(0);today.setMilliseconds(0);var dayMilliseconds=24*60*60*1000;var diff=today.getTime()-date.getTime();if(diff<=0){return _tx("\u4eca\u5929");}else if(diff<dayMilliseconds){return _tx("\u6628\u5929");}}
var month='';switch(date.getMonth()){case 0:month=_tx("1 \u6708");break;case 1:month=_tx("2 \u6708");break;case 2:month=_tx("3 \u6708");break;case 3:month=_tx("4 \u6708");break;case 4:month=_tx("5 \u6708");break;case 5:month=_tx("6 \u6708");break;case 6:month=_tx("7 \u6708");break;case 7:month=_tx("8 \u6708");break;case 8:month=_tx("9 \u6708");break;case 9:month=_tx("10 \u6708");break;case 10:month=_tx("11 \u6708");break;case 11:month=_tx("12 \u6708");break;}
return _tx("{month} {date}",{'month':month,'date':date.getDate()});}

function ChatDisplay(histories,everSentMessage,activeChats,focusedChat,gatedFeatures){this.histories=histories;this.everSentMessage=everSentMessage;this.user=presence.user;var wwwBase=env_get('www_base');this.profileURL=wwwBase+'profile.php';this.messageURL=wwwBase+'inbox/?compose';this.settingsURL='/ajax/chat/settings.php';this.gatedFeatures=gatedFeatures;this.useUICookieCache=gatedFeatures['ui_cookie_cache'];this.renderServerTime=this.gatedFeatures['24h_times']?this._renderServerTime24hr:this._renderServerTime12hr;this._init(activeChats,focusedChat);}
ChatDisplay.prototype={blinkTime:1500,initialBlinkDelay:3000,_init:function(activeChats,focusedChat){this.loaded=false;this.tabs={};this.numTabs=0;this.lastFocused=null;this.newMsgNames=[];this.newMsgNamesIndex=0;this.blinkingTimer=null;this.isSoundWindow=false;this.windowIsFocused=true;this.chatActivityTime=0;if(this.useUICookieCache){this.uiChangeTime=0;this.uiCookieCacheTime=(Env['rep_lag']+presence.sitevars.CHAT_UI_COOKIE_CACHE_WINDOW)*1000;}
this.favIcon=null;this.altFavIcon=null;this.initialFocusedChat=focusedChat;this.initialActiveChats=activeChats;presence.registerStateStorer(this._store.bind(this));presence.registerStateLoader(this._load.bind(this));var handledMsgTypes=['unfocus_chat','focus_chat','close_chat','msg','video','typ'].map(PresenceMessage.getArbiterMessageType);Arbiter.subscribe(handledMsgTypes,this._handlePresenceMessage.bind(this));Arbiter.subscribe(PresenceMessage.STARTED,this.start.bind(this));Arbiter.subscribe(PresenceMessage.SHUTDOWN,this.shutdown.bind(this));Arbiter.subscribe(PresenceMessage.RESTARTED,this.restart.bind(this));Arbiter.subscribe(ChatOptions.VISIBILITY_CHANGED,this.handleVisibility.bind(this));Arbiter.subscribe(ChatBuddyList.AVAILABILITY_CHANGED,this._onBuddyAvailability.bind(this));Arbiter.subscribe(PresenceMessage.WINDOW_RESIZED,this.handleResize.bind(this));Event.listen(window,'focus',this.onWindowFocus.bind(this));Event.listen(window,'blur',this.onWindowBlur.bind(this));},onWindowFocus:function(){this.isWindowFocused=true;this.doStopBlinking();},onWindowBlur:function(){this.isWindowFocused=false;},start:function(){for(var id in this.tabs){this.tabs[id].start();}},shutdown:function(){this._stopBlinking();},restart:function(){for(var id in this.tabs){this.tabs[id].restart();}},loadInitialUserInfo:function(id,name,firstName){if(ChatUserInfos[id]){return;}
ChatUserInfos[id]={'name':name,'firstName':firstName,'thumbSrc':''};},_loadInitialTabs:function(activeChats,focusedChat){var firstTab=null;for(var id in activeChats){if(presence.inVideoChat&&id!=presence.inVideoChatWith){continue;}
if(!firstTab){firstTab=id;}
if(this.tabs[id]){continue;}
var tabInfo=activeChats[id];var name,firstName;if(ChatUserInfos[id]){name=ChatUserInfos[id].name;firstName=ChatUserInfos[id].firstName;}else{name=tabInfo.n;if(!name){Util.warn('chat display: trying to load chat tab '+id+', but don\'t have the name');continue;}
firstName=tabInfo.fn?tabInfo.fn:getFirstName(name);}
var numMissed=tabInfo.m||0;var missedTime=tabInfo.t||0;this.tabs[id]=new ChatTab(this,id,name,firstName,numMissed,missedTime);this.numTabs++;}
if(presence.inVideoChat&&!firstTab){focusedChat=presence.inVideoChatWith;}else if(presence.inPopoutWindow&&!focusedChat){focusedChat=firstTab;}
if(focusedChat&&(focusedChat!=this.focused)){this._focusTab(focusedChat);}},load:function(){this._load(presence.state);},_load:function(presenceState){var loadedFromCache=false;if(presenceState){this.isSoundWindow=channelManager.isLowestSubdomain();if(this.blinkingTimer&&presenceState.sb){this._stopBlinking();}
this.chatActivityTime=verifyNumber(presenceState.ct)*1000;if(this.useUICookieCache){var now=presence.getTime();this.uiChangeTime=Math.max(this.uiChangeTime,verifyNumber(presenceState.uct)*1000);if(!this.loaded){if(now-this.uiChangeTime<this.uiCookieCacheTime){if(now-presenceState.ut>60*60*1000){for(var id in presenceState.t){presenceState.t[id].m=0;}}
presence.debug('chatDisplay: loading tabs from cookie cache');this._loadInitialTabs.bind(this,presenceState.t,presenceState.f).defer();loadedFromCache=true;}}}}
if(!this.loaded&&!loadedFromCache){presence.debug('chatDisplay: loading tabs from server state');this._loadInitialTabs.bind(this,this.initialActiveChats,this.initialFocusedChat).defer();this.initialFocusedChat=this.initialActiveChats=false;}
this.loaded=true;},_store:function(presenceState){presenceState.ct=Math.floor(this.chatActivityTime*0.001);presenceState.sb=(this.blinkingTimer==null)?1:0;if(this.useUICookieCache){presenceState.t={};presenceState.f=null;presenceState.uct=0;var now=presence.getTime();if(now-this.uiChangeTime<this.uiCookieCacheTime){for(var id in this.tabs){var tab=this.tabs[id];presenceState.t[id]={n:tab.name,m:tab.numMissed};if(tab.firstName!=getFirstName(tab.name)){presenceState.t[id].fn=tab.firstName;}}
presenceState.f=this.focused;presenceState.uct=Math.floor(this.uiChangeTime*0.001);}}
return presenceState;},handleResize:function(){if(!this.focused){return;}
var tab=this.tabs[this.focused];tab.handleResize();},_sendTabStateChange:function(data){data['window_id']=presence.windowID;new AsyncRequest().setURI(this.settingsURL).setData(data).setHandler(this._onCheckTabStateChangeResponse.bind(this)).setErrorHandler(bagofholding).setTransportErrorHandler(bagofholding).send();},_onCheckTabStateChangeResponse:function(response){var payload=response.getPayload();if(payload.overlay){buddyList.addOverlayInfo(payload.overlay);}},reloadTabs:function(){for(var id in this.tabs){this.tabs[id].loadData();}},_closeTab:function(id){if(!this.tabs[id]){return;}
if(this.focused==id){if(presence.inPopoutWindow){var toFocus=null;var breakNext=false;for(var otherId in this.tabs){if(otherId!=id){toFocus=otherId;if(breakNext){break;}}else if(toFocus){break;}else{breakNext=true;}}
if(toFocus){var tabToFocus=this.tabs[toFocus];this._focusTab(toFocus);}else{this.focused=null;}}else{this.focused=null;}}
this.tabs[id].close();delete this.tabs[id];this.numTabs--;chatTabSlider.close(id);},uiChanged:function(){if(this.useUICookieCache){this.uiChangeTime=presence.getTime();presence.doSync();}},closeTab:function(id){this._closeTab(id);this._sendTabStateChange({'close_chat':id});this.uiChanged();},showVideoChatTab:function(){if(presence.inVideoChat){this.tabs[this.focused].showChat();}},_unfocus:function(){if(!this.focused){return false;}
if(presence.inPopoutWindow){this.tabs[this.focused].deselectPopoutChat();}
this.tabs[this.focused].unfocus();this.focused=null;return true;},unfocus:function(){var changed=this._unfocus();if(changed){this._sendTabStateChange({'unfocus_chat':1});this.uiChanged();}
this.lastFocused=null;},unfocusNoSync:function(){this._unfocus();},refocus:function(){if(!this.lastFocused||!this.tabs[this.lastFocused]){return null;}
this._focusTab(this.lastFocused);},_focusTab:function(id,name,firstName){if(id==this.focused||presence.inVideoChat&&id!=presence.inVideoChatWith){return;}
if(!this.tabs[id]){if(typeof name=='undefined'){if(!ChatUserInfos[id]||!ChatUserInfos[id].name){presence.warn("chat: couldn't create tab "+id+" since no name is specified");return;}
name=ChatUserInfos[id].name;firstName=ChatUserInfos[id].firstName;}
this.tabs[id]=new ChatTab(this,id,name,firstName,0);this.numTabs++;chatTabSlider.addTab(id);}
chatTabSlider.gotoTab(id);if(this.focused){this.tabs[this.focused].unfocus();if(presence.inPopoutWindow){this.tabs[this.focused].deselectPopoutChat();}}
this.focused=id;this.lastFocused=id;if(this.focused){var loaded=this.loaded;(function(){var hidden=!presence.inPopoutWindow&&presence.poppedOut;if(this.tabs[this.focused]){this.tabs[this.focused].focus(hidden,loaded);}
if(presence.inPopoutWindow){this.tabs[id].selectPopoutChat();}}).bind(this).defer();}},focusTab:function(id,name,firstName){presence.pauseSync();this._focusTab(id,name,firstName);this._sendTabStateChange({'focus_chat':id});this.uiChanged();this.chatActivityTime=(new Date()).getTime();this.doStopBlinking();presence.resumeSync();},toggleTab:function(id,name,firstName){if(this.focused==id){this.unfocus();}else{this.focusTab(id,name,firstName);}},doBlink:function(){if(!this.favIcon){var links=document.getElementsByTagName('link');for(var i=0;i<links.length;i++){if(links[i].rel=='shortcut icon'){this.favIcon=links[i];this.altFavIcon=document.createElement('link');this.altFavIcon.rel='shortcut icon';this.realTitle=document.title;break;}}}
if(this.favIcon.parentNode){if(this.newMsgNames&&this.newMsgNames.length>0){if(this.newMsgNamesIndex>=this.newMsgNames.length){this.newMsgNamesIndex=0;}
var name=this.newMsgNames[this.newMsgNamesIndex++];document.title=_tx("{name}\u9001\u4f86\u65b0\u8a0a\u606f\uff01",{'name':name});}else{document.title=_tx("\u65b0\u8a0a\u606f\uff01");}
var p=this.favIcon.parentNode;p.removeChild(this.favIcon);p.appendChild(this.altFavIcon);}else{document.title=this.realTitle;var p=this.altFavIcon.parentNode;p.removeChild(this.altFavIcon);p.appendChild(this.favIcon);}},doStopBlinking:function(force){if(this.blinkingTimer||force){this._stopBlinking();presence.doSync();}},_stopBlinking:function(){if(this.blinkingTimer){if(this.favIcon&&!this.favIcon.parentNode){this.doBlink();}
clearInterval(this.blinkingTimer);this.blinkingTimer=null;this.newMsgNames=[];this.newMsgNamesIndex=0;}},_onBuddyAvailability:function(type,data){this.handleBuddyAvailability(data.justCameOnline);},handleBuddyAvailability:function(justCameOnline){for(var id in this.tabs){this.tabs[id].handleBuddyAvailability(justCameOnline);}},_handlePresenceMessage:function(type,data){var obj=data.obj;if(obj.window_id==presence.windowID){return;}
if(obj.from){if(obj.from==this.user){var id=obj.to;}else{var id=obj.from;}
var tab=this.tabs[id];}
switch(obj.type){case'unfocus_chat':if(!presence.inVideoChat){this._unfocus();}
break;case'focus_chat':if(!presence.inVideoChat){this._focusTab(obj.id);}
break;case'close_chat':if(!presence.inVideoChat){this._closeTab(obj.id);}
break;case'msg':case'video':if(this.inVideoChat&&(obj.from==presence.inVideoChatWith||obj.to==presence.inVideoChatWith)){break;}
if(obj.from==this.user){var name=obj.to_name;var firstName=obj.to_first_name?obj.to_first_name:getFirstName(name);}else{var name=obj.from_name;var firstName=obj.from_first_name?obj.from_first_name:getFirstName(name);}
this.loadInitialUserInfo(id,name,firstName);var fromMe=(obj.from==this.user);buddyList.setAvailable(id,fromMe);if(!tab){tab=this.tabs[id]=new ChatTab(this,id,name,firstName,0);this.numTabs++;chatTabSlider.addTab(id);if(!this.focused){this.focusTab(id);}else{tab.getHistory();}}
if(presence.inPopoutWindow||!presence.poppedOut){if(fromMe){this.doStopBlinking(true);}else if(this.isWindowFocused){setTimeout(this.doStopBlinking.bind(this,true),500);}else if(!presence.isOpera){this.newMsgNames.push(tab.firstName);if(!this.blinkingTimer){this.blinkingTimer=setTimeout(function(){this.blinkingTimer=setInterval(this.doBlink.bind(this),this.blinkTime);}.bind(this),this.initialBlinkDelay);}}}
obj.time=obj.msg.time;tab.newMsg(obj);break;case'typ':if(tab){tab.newTyping(obj);}else{presence.debug('typing message ignored');}
break;default:break;}},handleVisibility:function(){for(var id in this.tabs){this.tabs[id].handleVisibility();}},getHistory:function(id,create){create=create||false;if(!this.histories[id]&&create){this.histories[id]=[];}
return this.histories[id];},_renderServerTime12hr:function(serverTimeMS){var time=new Date();time.setTime(serverTimeMS+presence.timeSkew);var hours=time.getHours();var ampm='am';if(hours>=12){ampm='pm';hours-=12;}
if(hours==0){hours=12;}
var minutes=time.getMinutes();if(minutes<10){minutes='0'+minutes;}
var timeStr=hours+':'+minutes+ampm;return timeStr;},_renderServerTime24hr:function(serverTimeMS){var time=new Date();time.setTime(serverTimeMS+presence.timeSkew);var hours=time.getHours();if(hours<10){hours='0'+hours;}
var minutes=time.getMinutes();if(minutes<10){minutes='0'+minutes;}
var timeStr=hours+':'+minutes;return timeStr;}};function chat_simple_popout(){window.open(presence.popoutURL,"fbChatWindow","status=0,toolbar=0,location=0,menubar=0,"+"directories=0,resizable=1,scrollbars=0,"+"width="+Presence.prototype.defWidth+",height="+Presence.prototype.defHeight+",left="+Presence.prototype.defX+",top="+Presence.prototype.defY);}

function ChatBuddyListTypeahead(obj,inputDiv,flid,excludedIds){this.curStr='';this.clearDiv=null;this.focused=false;this.selected=null;this.selectedIndex=0;this.selectableCount=0;this.minBuddyCount=buddyList.flMode?20:10;this.flid=flid;this.excludedIds=excludedIds;this.id=ChatBuddyListTypeahead.numTypeaheads++;this.obj=obj;this.obj.typeahead=this;this.placeholderText=obj.value;this.inputDiv=inputDiv;this.shouldShowClear=!presence.isSafari2;if(!this.shouldShowClear){obj.onmousedown=this._onmousedown.bind(this);}
addEventBase(this.obj,'focus',this._onfocus.bind(this));addEventBase(this.obj,'blur',this._onblur.bind(this));addEventBase(this.obj,'keyup',function(e){e=$E(e);var keycode=e?e.keyCode:-1;this._onkeyup.bind(this,keycode).defer();}.bind(this));this.captureSubmit();this.buildIndex();Arbiter.subscribe(ChatBuddyList.AVAILABILITY_CHANGED,this.buildIndex.bind(this));}
ChatBuddyListTypeahead.numTypeaheads=0;ChatBuddyListTypeahead.mixin({buildIndex:function(){this.availableListIDs=buddyList.getSortedListUI(this.flid);this.firstLetterIndex={};for(var i=0;i<this.availableListIDs.length;i++){var id=this.availableListIDs[i];var name=typeahead_source.tokenize(ChatUserInfos[id].name);for(var token=0;token<name.length;token++){if(!this.firstLetterIndex[name[token][0]]){this.firstLetterIndex[name[token][0]]={};}
this.firstLetterIndex[name[token][0]][id]=true;}}
this._refreshAvailableList();if(buddyList.availableCount<this.minBuddyCount){hide(this.inputDiv);this.resetSearch(true);}else{show(this.inputDiv);this.search.bind(this,true).defer();}},_onfocus:function(e){this.focused=true;this.captureSubmit();},_onblur:function(e){this.focused=false;if(this.curStr==''){this.hideClear();}},_getAvailableListIDs:function(){if(!this.availableIDs){this._refreshAvailableList();}
return this.availableIDs;},_refreshAvailableList:function(){var ids=this.availableListIDs;if(this.excludedIds){ids=ids.filter((function(id){return this.excludedIds[id]!=1;}).bind(this));}
this.availableIDs=ids;},_onmousedown:function(){setTimeout(function(){this._onkeyup(0);}.bind(this),100);},_onkeyup:function(keycode){switch(keycode){case KEYS.ESC:if(''==this.curStr){buddyList.closeTab();}else{this.resetSearch(true);}
break;case undefined:case KEYS.LEFT:case KEYS.RIGHT:return false;break;case KEYS.UP:this.upArrowPress();break;case KEYS.DOWN:this.downArrowPress();break;case KEYS.RETURN:this.select();break;case KEYS.BACKSPACE:case 0:default:if(this.search()){this.resetSearch(true);}
break;}},focusInput:function(){if(buddyList.availableCount&&buddyList.availableCount>this.minBuddyCount){this.obj.focus();}
this.resetSearch();},captureSubmit:function(){if((!this.capturedForm||this.capturedSubstitute!=this.capturedForm.onsubmit)&&this.obj.form){this.capturedForm=this.obj.form;this.captured_event=this.obj.form.onsubmit;this.capturedSubstitute=this.obj.form.onsubmit=function(){return false;}.bind(this.obj.form);}},resetSearch:function(clear){if(!this.obj){return false;}
if(!this.obj.value||clear){this.curStr='';this.obj.value='';this.hideClear();}
this.selected=null;this.selectedIndex=-1;this.showAll();this.hideClear();buddyList.unfreezeTabSize();},search:function(force){var value=this.obj.value;if(value==this.placeholderText){return true;}
var str=typeahead_source.flatten_string(value);if(!force&&str==this.curStr){return false;}
this.curStr=str;var tokenizedStr=typeahead_source.tokenize(str).sort(typeahead_source._sort);if(!tokenizedStr[0]){return true;}
var quickIndex=this.firstLetterIndex[tokenizedStr[0][0]];buddyList.freezeTabSize();this.showClear();buddyList.suppressNonFriendInfoInBuddyList(this.flid);this.getMatchingFriends(quickIndex,tokenizedStr);this.selected=null;this.selectMatchingFriends();return false;},getMatchingFriends:function(quickIndex,tokenizedStr){var matches=0;var firstMatch;var availableListIDs=this._getAvailableListIDs();for(var i=0;i<availableListIDs.length;i++){var id=availableListIDs[i];var fullName=ChatUserInfos[id].name;if(quickIndex!=undefined&&quickIndex[id]&&typeahead_source.check_match(tokenizedStr,fullName)){var name=typeahead_source.highlight_found(fullName,this.curStr);buddyList.getBuddyItemName(id,this.flid).setContent(HTML(name));buddyList.showBuddyItem(id,false,this.flid);matches++;if(!firstMatch){firstMatch=id;}}else{CSS.removeClass(buddyList.getBuddyItem(id,this.flid),'selected');buddyList.hideBuddy(id,this.flid);}}
if(matches>0){buddyList.hideEmptySearch(this.flid);if(matches==1||(tokenizedStr.length==1&&tokenizedStr[0].length==1)){this.selected=firstMatch;this.selectedIndex=0;CSS.addClass(buddyList.getBuddyItem(firstMatch,this.flid),'selected');}}else{buddyList.showEmptySearch(this.flid);}},selectMatchingFriends:function(){this.selectableCount=0;var availableListIDs=this._getAvailableListIDs();for(var i=0;i<availableListIDs.length;i++){var id=availableListIDs[i];var buddy=buddyList.getBuddyItem(id,this.flid);if(buddy&&CSS.getStyle(buddy,'display')!='none'){if(this.selectedIndex==this.selectableCount){this.selected=id;CSS.addClass(buddy,'selected');Vector2.scrollIntoView(buddy);}else{CSS.removeClass(buddy,'selected');}
this.selectableCount++;}}},downArrowPress:function(){this.selectedIndex++;var max=this.selectableCount-1;if(this.selectedIndex>max){this.resetSearch();}
this.selectMatchingFriends();},upArrowPress:function(){this.selectedIndex--;if(this.selectedIndex<0){this.selectedIndex=0;}
this.selectMatchingFriends();},showAll:function(){this.obj.value='';buddyList.hideEmptySearch(this.flid);var availableListIDs=this._getAvailableListIDs();for(var i=0;i<availableListIDs.length;i++){var id=availableListIDs[i];var buddy=buddyList.getBuddyItem(id,this.flid);if(buddy){buddyList.updateBuddyItemName(id,this.flid);CSS.removeClass(buddyList.getBuddyItem(id,this.flid),'selected');buddyList.showBuddyItem(id,true,this.flid);}}
buddyList.unsuppressNonFriendInfoInBuddyList(this.flid);},showClear:function(){if(this.clearDiv==null&&this.shouldShowClear){this.clearDiv=document.createElement('div');this.clearDiv.setAttribute('id','clear_search'+this.id);DOM.setContent(this.clearDiv,HTML('<a href="#" class="hide"></a>'));var link=DOM.find(this.clearDiv,'a');link.listen('click',(function(){this.resetSearch(true);return false;}).bind(this));this.inputDiv.appendChild(this.clearDiv);}},hideClear:function(){if(ge('clear_search'+this.id)){this.clearDiv=null;this.inputDiv.removeChild(ge('clear_search'+this.id));}},select:function(){if(this.selected!=null){CSS.removeClass(buddyList.getBuddyItemName(this.selected,this.flid),'selected');buddyList.itemOnClick(this.selected,this.flid);this.resetSearch(true);}}});

function PresenceUpdater(){this.timerGranularity=presence.sitevars.UPDATE_GRANULARITY?presence.sitevars.UPDATE_GRANULARITY*1000:60000;this._init();}
PresenceUpdater.prototype={_init:function(){this.handlers=[];this.updatePaused=0;this.updateNumber=0;this._runTimer();bind(Arbiter,Arbiter.inform,PresenceMessage.PRESENCE_UPDATER_READY,true,Arbiter.BEHAVIOR_STATE).defer();},register:function(asyncParam,checkCB,responseCB,errorCB,transportErrorCB){this.handlers.push({'asyncParam':asyncParam,'checkCB':checkCB,'responseCB':responseCB,'errorCB':errorCB,'transportErrorCB':transportErrorCB});},_runTimer:function(){clearTimeout(this.timer);this.timer=setTimeout(this.checkForUpdate.bind(this,false,[],false),this.timerGranularity);},forceUpdate:function(handlers){if(this.updatePaused){return;}
if(handlers!==undefined&&handlers.length>0){this.checkForUpdate(false,handlers,false);}else{this.checkForUpdate(true,[],false);}},pauseUpdate:function(){this.updatePaused++;},resumeUpdate:function(handlers){this.updatePaused--;this.forceUpdate(handlers);},checkForUpdate:function(forceAll,forceHandlers,bypassTimer){if(!bypassTimer){clearTimeout(this.timer);}
if(presence.isShutdown){if(!bypassTimer){this._runTimer();}
return;}
var time=presence.getTime();var asyncHandlers=[];var asyncData={user:presence.user};for(var i=0;i<this.handlers.length;i++){var handlerInfo=this.handlers[i];var forceUpdate=forceAll||(forceHandlers.indexOf(handlerInfo.asyncParam)!=-1);var shouldUpdate=handlerInfo.checkCB(time,asyncData,forceUpdate);if(shouldUpdate){asyncData[handlerInfo.asyncParam]=1;asyncHandlers.push(handlerInfo);}}
if(asyncHandlers.length>0){this._sendUpdate(asyncData,asyncHandlers,bypassTimer);}else{if(!bypassTimer){this._runTimer();}}},runHandler:function(asyncHandler){this.checkForUpdate(false,[asyncHandler],true);},_initialHandler:function(updateNumber,response){if(updateNumber!=this.updateNumber){return false;}},_onResponse:function(asyncHandlers,bypassTimer,response){var updateInfo=response.getPayload();presence.updateServerTime(updateInfo.time);var updateTime=presence.getTime();for(var i=0;i<asyncHandlers.length;i++){var handler=asyncHandlers[i];var paramResult=updateInfo[handler.asyncParam];if(typeof paramResult=='undefined'||!paramResult){handler.errorCB(response);}else{handler.responseCB(paramResult,updateTime);}}
presenceCookieManager.store();if(!bypassTimer){this._runTimer();}},_onError:function(asyncHandlers,response){for(var i=0;i<asyncHandlers.length;i++){asyncHandlers[i].errorCB(response);}
this._runTimer();},_onTransportError:function(asyncHandlers,response){for(var i=0;i<asyncHandlers.length;i++){asyncHandlers[i].transportErrorCB(response);}
this._runTimer();},_sendUpdate:function(asyncData,asyncHandlers,bypassTimer){this.updateNumber++;var uri=asyncData['notifications']?'/ajax/presence/update.php':'/ajax/chat/buddy_list.php';var request_data=URI.getRequestURI().getQueryData();var query_data={};for(key in request_data){if(key.indexOf('buddy')==0){query_data[key]=request_data[key];}}
if(query_data){uri=new URI(uri).setQueryData(query_data);}
this.async=new AsyncRequest().setInitialHandler(this._initialHandler.bind(this,this.updateNumber)).setHandler(this._onResponse.bind(this,asyncHandlers,bypassTimer)).setErrorHandler(this._onError.bind(this,asyncHandlers)).setTransportErrorHandler(this._onTransportError.bind(this,asyncHandlers)).setOption('suppressErrorAlerts',true).setData(asyncData).setURI(uri).send();}};

function ChatBuddyList(){this.user=presence.user;this.shouldRender=true;this.haveFullList=false;this.errorMode=false;this.shouldShowLoading=false;this.availableCount=0;this.availableList={};this.sortedList=[];this.listChanged=false;this.updateTime=0;this.flMode=false;this.flData={};this.otherFriendsFlid='-1';this.botsFlid='-2';this.stopUpdates=false;this.flSortableGroup=null;this.reorderingLists=false;this.sortables={};this.flOpts={};this.externalFlids=[];this.updateOverlay={};this.visibilityRatio={};this.justCameOnline=false;this.maxNameLen=20;this.backgroundColor=presence.inPopoutWindow?'#f7f7f7':'#fff';}
copy_properties(ChatBuddyList,{OVERLAY_ONLINE:0,OVERLAY_IDLE:1,OVERLAY_OFFLINE:-1,DEFAULT_OPTS:{fullDisplay:true,excludeIds:{}},BUDDY_LIST_INITIALIZED:'buddylist/initialized',BUDDY_CLICKED:'buddylist/buddy_clicked',AVAILABILITY_CHANGED:'buddylist/availability-changed',UPDATER_NAME:'buddy_list'});ChatBuddyList.prototype={maxItemsToAnimate:10,highlightColor:'#fffbe2',expandAnimDuration:400,compactItemHeight:18,fullItemHeight:26,initError:function(){this.errorMode=true;this._init();},initNoRender:function(availableCount,availableList,updateTime,listChanged,flMode,flData,updateOverlay){this.shouldRender=false;this.shouldShowLoading=true;this.availableCount=availableCount;this.availableList=availableList;this.updateTime=updateTime;this.listChanged=listChanged;this.updateOverlay=updateOverlay;this.flMode=flMode;this.flData=flData;this._init();if(presence.inPopoutWindow){this._forceUpdate.bind(this,false).defer();}},initFullList:function(availableList,updateTime,listChanged,flMode,flData,updateOverlay){this.availableList=availableList;this.updateTime=updateTime;this.listChanged=listChanged;this.haveFullList=true;this.flMode=flMode;this.flData=flData;this.updateOverlay=updateOverlay;this.availableCount=count(this.availableList);this._init();},_init:function(){this.loaded=false;this.poppedOut=presence.poppedOut;this.buddyListOpen=false;this.updateDiff=0;this.rendered=false;this.showingError=false;this.numRequestFailures=0;for(var id in this.availableList){this.availableList[id].i=this.availableList[id].i?1:0;}
this.tabID='buddy_list_tab';this.wrapperID='buddy_list';this.contentID='buddy_list_content';this.tabDiv=ge(this.tabID);this.wrapperDiv=ge(this.wrapperID);this.contentDiv=ge(this.contentID);this.buddyListError=ge('buddy_list_error');this.buddyCountSpan=ge('buddy_count');presenceUpdater.register(ChatBuddyList.UPDATER_NAME,this._checkUpdater.bind(this),this._onUpdaterResponse.bind(this),this._onUpdaterError.bind(this),this._onUpdaterError.bind(this));presenceCookieManager.register('bl',this._getCookieData.bind(this));presence.registerStateStorer(this._storeState.bind(this));presence.registerStateLoader(this._loadState.bind(this));Arbiter.subscribe(PresenceMessage.getArbiterMessageType('fl_settings'),this._handleFLMessage.bind(this));Arbiter.subscribe(ChatOptions.VISIBILITY_CHANGED,this._handleVisibility.bind(this));this.setCompactDisplay(chatOptions.getSetting('compact_buddylist'));this._loadState(presence.state);this._postInit.bind(this).defer();Arbiter.subscribe(Arbiter.LIST_EDITOR_LISTS_CHANGED,this._flManagerHandler.bind(this));},_postInit:function(){if(presence.inPopoutWindow){this._firstRender();}
if(chatOptions.visibility){this._updateCount();}
this.updateDiff=this._computeUpdateTimeDiff();this._mergeOverlay();Arbiter.inform(ChatBuddyList.BUDDY_LIST_INITIALIZED,{},Arbiter.BEHAVIOR_PERSISTENT);},_storeState:function(presenceState){presenceState.blo=this.buddyListOpen?1:0;presenceState.bvt=parseInt(this.buddyViewTime*0.001);return presenceState;},_loadState:function(presenceState){this.buddyViewTime=verifyNumber(presenceState.bvt)*1000;var openBuddyList=!!presenceState.blo;if(!presence.poppedOut&&this.poppedOut){this._showLoading();this._forceUpdate(false);}
this.poppedOut=presence.poppedOut;var fn=null;if(!this.poppedOut){if(openBuddyList){fn=this.openTab.bind(this);}else{fn=this.closeTab.bind(this);}}
if(fn){if(this.loaded){fn();}else{fn.defer();}}
this.loaded=true;},setCompactDisplay:function(isCompact){this.isCompactDisplay=isCompact;if(this.isCompactDisplay){this.itemHeight=this.compactItemHeight;}else{this.itemHeight=this.fullItemHeight;}
if(this.rendered){this._render();}},_handleVisibility:function(){if(chatOptions.visibility){this._showLoading();this._show();this._forceUpdate(true);this.justCameOnline=true;}else{this._hide();}},_handleFLMessage:function(type,data){var obj=data.obj;this.setVisibilityRatio({});if(!this._flChanged(obj.fl_mode,obj.fl_data)){return;}
this._onFlChange(obj.fl_mode,obj.fl_data);},_flChanged:function(newFlMode,newFlData){return(newFlMode!=this.flMode||!are_equal(newFlData,this.flData));},_massageNowAvailableList:function(nowAvailableList,newFlMode,newFlData){for(var id in nowAvailableList){var buddyInfo=nowAvailableList[id];if(newFlMode!=this.flMode){if(newFlMode){delete buddyInfo.fl;}else{buddyInfo['fl']=[this.otherFriendsFlid];}}else{var flids=buddyInfo.fl||[];for(var i=0;i<flids.length;i++){var flid=flids[i];if(typeof this.flData[flid]=='undefined'){buddyInfo.fl.remove(flid);}}
if(buddyInfo.fl&&buddyInfo.fl.length==0){buddyInfo.fl=[this.otherFriendsFlid];}}
nowAvailableList[id]=buddyInfo;}
return nowAvailableList;},_onFlChange:function(newFlMode,newFlData){if(!this.rendered){this.flMode=newFlMode;this.flData=newFlData;return;}
var toAddFlids=[];var toRemoveFlids=[];var onlineFlids=[];var offlineFlids=[];if(this.flMode&&this.flMode==newFlMode){var groupedList=this._groupAvailableListByFl(true);for(var flid in newFlData){if(typeof this.flData[flid]=='undefined'){if(newFlData[flid].h){continue;}
toAddFlids.push(flid);onlineFlids.push(flid);}else{if(this.flData[flid].h!=newFlData[flid].h){if(newFlData[flid].h){toRemoveFlids.push(flid);}else{toAddFlids.push(flid);if(newFlData[flid].o){onlineFlids.push(flid);}}}
else if(this.flData[flid].o!=newFlData[flid].o){if(newFlData[flid].o){onlineFlids.push(flid);}else{offlineFlids.push(flid);}}}}
for(var flid in this.flData){if(typeof newFlData[flid]=='undefined'){toRemoveFlids.push(flid);}}
this.flMode=newFlMode;if(toRemoveFlids.length!=0){this._removeFlidsFromBuddyList(toRemoveFlids,groupedList);}
if(offlineFlids.length!=0){this._goOfflineToLists(offlineFlids,true);}
this.flData=newFlData;if(toAddFlids.length!=0){this._addFlidsToDOM(toAddFlids,groupedList);}
if(onlineFlids.length!=0){this._goOnlineToLists(onlineFlids,true);}}else if(this.flMode&&this.flMode!=newFlMode){var groupedList=this._groupAvailableListByFl(true);toRemoveFlids=keys(this.flData);this.flMode=newFlMode;this.flData=newFlData;this._addFlidsToDOM([null]);this._removeFlidsFromBuddyList(toRemoveFlids,groupedList);this._forceUpdate(false);}else{for(var flid in newFlData){if(newFlData[flid].h){continue;}
toAddFlids.push(flid);if(newFlData[flid].o){onlineFlids.push(flid);}}
this.flMode=newFlMode;this.flData=newFlData;this._removeFlidsFromDOM([null]);if(toAddFlids.length>0){this._addFlidsToDOM(toAddFlids);}
if(onlineFlids.length>0){this._goOnlineToLists.bind(this,onlineFlids,true).defer();}}},_addFlidsToDOM:function(flids,groupedList){groupedList=groupedList||this._groupAvailableListByFl(true);var allFlids=this._getRenderedFriendLists();var firstFlid=allFlids[0];var parentOfThemAll=$('buddy_list_parent');for(var i=0;i<flids.length;i++){var flid=flids[i];if(this.flMode&&flid){var elem=DOM.create('li',{'id':this._getFriendListId(flid),'className':this._getFriendListItemClasses(flid,groupedList)});DOM.setContent(elem,HTML(this._renderFriendListHeader(flid)));DOM.appendContent(elem,HTML(this._renderFriendListContent(flid,[])));if(firstFlid==flid){parentOfThemAll.prependContent(elem);}else{var prevIndex=allFlids.indexOf(flid);var prevFlid=allFlids[prevIndex-1];DOM.insertAfter(ge(this._getFriendListId(prevFlid)),elem);}
this._addFlSortable(flid);this._initFlidSortable(flid,[]);}else{parentOfThemAll.prependContent(HTML(this._renderFriendListContent(null,[])));}}
this._addFriendListListeners(flids);},_removeFlidsFromDOM:function(flids){for(var i=0;i<flids.length;i++){var flid=flids[i];if(flid){if(ge(this._getFriendListId(flid))){DOM.remove($(this._getFriendListId(flid)));this._removeFlSortable(flid);this._destroyFlidSortable(flid);}}else{DOM.remove($(this._getAvailableMarkerId(flid)));DOM.remove($(this._getIdleMarkerId(flid)));}}},loadTypeahead:function(){this.typeahead=new ChatBuddyListTypeahead($("buddy_list_typeahead_input"),$("buddy_list_typeahead"));},getContentWrapper:function(){return this.contentDiv.parentNode;},resizeTab:function(force){if(this.resizeFrozen){if(force){this.resizeFrozen=false;}else{return;}}
presence.tabContentResize(this.wrapperID,this.contentID);},freezeTabSize:function(forceLockHeight){if(this.resizeFrozen||this.showingError){return;}
this.resizeFrozen=true;if(forceLockHeight===undefined){forceLockHeight=true;}
presence.tabContentResize(this.wrapperID,this.contentID,forceLockHeight);},unfreezeTabSize:function(){if(!this.resizeFrozen){return;}
this.resizeFrozen=false;this.resizeTab();presence.contentChanged(this.contentID);},_hide:function(){if(presence.inPopoutWindow){CSS.addClass(presence.popoutSidebar,'buddy_list_hidden');}else{CSS.addClass(presence.holder,'buddy_list_hidden');this.closeTab();DOM.setContent(this.buddyCountSpan,_tx("Chat (Offline)"));}},_show:function(){if(presence.inPopoutWindow){CSS.removeClass(presence.popoutSidebar,'buddy_list_hidden');}else{CSS.removeClass(presence.holder,'buddy_list_hidden');this.openTab();this._updateCount();}},toggleTab:function(){if(!this.buddyListOpen){this.openTab(true);}else{this.closeTab();}},_goOnline:function(){chatOptions.sendVisibility(true);},openTab:function(focusTypeahead){if(this.buddyListOpen){return;}
if(CSS.hasClass(presence.holder,'buddy_list_hidden')){this._goOnline();return;}
if(!this.rendered){var availableList=this.availableList;this.availableList={};this.shouldShowLoading=true;this._firstRender();presence.openTab(this.wrapperID,this.tabID);this.availableList=availableList;if(this.haveFullList){this._render.bind(this).defer();setTimeout(this._availableListChanged.bind(this,true),10);}}else{presence.openTab(this.wrapperID,this.tabID,this.contentID);}
this.buddyListOpen=true;setTimeout(this._openTabPostProcess.bind(this,focusTypeahead),50);},_openTabPostProcess:function(focusTypeahead){this.buddyViewTime=(new Date()).getTime();var sinceLastUpdate=(presence.getTime()-this.updateTime)*0.001;if(this.showingError||sinceLastUpdate>presence.sitevars.BUDDY_VIEW_FETCH_WINDOW){this._forceUpdate(false);}
presence.doSync();if(focusTypeahead&&this.typeahead){this.typeahead.focusInput();}},closeTab:function(){if(!this.buddyListOpen){return;}
this.buddyListOpen=false;presence.toggleTab(this.wrapperID,this.tabID,this.contentID);if(chatOptions.visibility){setTimeout(this._closeTabPostProcess.bind(this),50);}
buddyListDisplay.closeOpenFlyout();this.exitReorderingFlMode();},_closeTabPostProcess:function(){if(this.typeahead){this.typeahead.resetSearch(true);}
this.buddyViewTime=(new Date()).getTime();presence.doSync();},_mergeOverlay:function(){if(!this.haveFullList){return;}
var time=presence.getTime();var nowAvail={};var wasAvail=[];for(var id in this.updateOverlay){if(time<this.updateOverlay[id].exp){var buddyInfo=this.availableList[id];if(!ChatUserInfos[id]){continue;}
if(this.updateOverlay[id].ol!=ChatBuddyList.OVERLAY_OFFLINE){if(!buddyInfo){buddyInfo={i:0};if(this.flMode){buddyInfo.fl=[this.otherFriendsFlid];}
nowAvail[id]=buddyInfo;}else{}}else{wasAvail.push(id);}}else{delete this.updateOverlay[id];}}
if(!is_empty(nowAvail)||!is_empty(wasAvail)){this._updateAvailableListWithDiff(nowAvail,wasAvail);}},getAvailability:function(id){if(id==this.user){return chatOptions.visibility;}
if(typeof this.availableList[id]!='undefined'){return this.availableList[id];}else{return null;}},setAvailable:function(id,keepIdle){this._manageOverlay(id,ChatBuddyList.OVERLAY_ONLINE);this._addToBuddyList([id],keepIdle);},_addToBuddyList:function(ids,keepIdle){var availDiff={};var wasAvail=[];for(var i=0;i<ids.length;i++){var id=ids[i];var availability=this.getAvailability(id);if(availability&&(availability.i==0||keepIdle)){continue;}
availDiff[id]={i:0};if(this.flMode){if(this.availableList[id]&&this.availableList[id].fl){availDiff[id]['fl']=this.availableList[id].fl;}else{availDiff[id]['fl']=[this.otherFriendsFlid];}}
if(availability&&availability.i==1){wasAvail.push(id);}}
this._updateAvailableListWithDiff(availDiff,wasAvail);},setFlids:function(id,flids){if(!this.getAvailability(id)){return;}
if(this.availableList[id].fl[0]==this.otherFriendsFlid){var nowAvail={};nowAvail[id]=this.availableList[id];nowAvail[id]['fl']=flids;this._updateAvailableListWithDiff(nowAvail,[],this.otherFriendsFlid);}},setUnavailable:function(id){this._manageOverlay(id,ChatBuddyList.OVERLAY_OFFLINE);this._removeFromBuddyList([id]);},_removeFromBuddyList:function(ids,flid){var toRemove=[];for(var i=0;i<ids.length;i++){var id=ids[i];if(!this.getAvailability(id)){continue;}
toRemove.push(id);}
if(toRemove.length>0){this._updateAvailableListWithDiff({},toRemove,flid);}},addOverlayInfo:function(overlay){for(var id in overlay){this._manageOverlay(id,overlay[id].ol);}
this._mergeOverlay();},_manageOverlay:function(id,new_state){var exp=presence.getTime()+60000;this.updateOverlay[id]={'ol':new_state,'exp':exp};if(this.rendered){presenceCookieManager.store();}},hideBuddy:function(id,flid){var flids;if(flid){flids=[flid];}else{flids=this._getUserFlids(id,null,true);}
this._toggleBuddy(id,false,flids);},_toggleBuddy:function(id,show,flids){var newDisplay=show?'block':'none';var listItem,flItem;for(var i=0;i<flids.length;i++){var flid=flids[i];listItem=ge(this._getBuddyListItemId(id,flid));if(listItem){listItem.style.display=newDisplay;}
if(show&&(flItem=ge(this._getFriendListId(flid)))){CSS.removeClass(flItem,'suppress');}}},showBuddyItem:function(id,showAll,flid){showAll=showAll||false;var flids;if(flid){flids=[flid];}else{var flids=this._getUserFlids(id,null,true);if(flids.length>1&&!showAll){var hideFlids=flids.slice(1);this._toggleBuddy(id,false,hideFlids);flids=[flids[0]];}}
this._toggleBuddy(id,true,flids);},getBuddyItem:function(id,flid){flid=this._getUserFlid(id,flid);return ge(this._getBuddyListItemId(id,flid));},getBuddyItemName:function(id,flid){flid=this._getUserFlid(id,flid);return ge(this._getBuddyListItemNameId(id,flid));},updateBuddyItemName:function(id,flid){var userInfo=ChatUserInfos[id];var name=userInfo.name;var nameCapped;if(name.length>this.maxNameLen){nameCapped=name.substring(0,this.maxNameLen-2)+'...';}else{nameCapped=name;}
this.getBuddyItemName(id,flid).innerHTML=nameCapped;},_getUserFlid:function(id,flid){if(flid===null||flid===undefined){var flids=this._getUserFlids(id);flid=flids[0];}
return flid;},showEmptySearch:function(flid){show(this._getEmptySearchId(flid));},hideEmptySearch:function(flid){hide(this._getEmptySearchId(flid));},_getSortedList:function(){if(this.sortedList.length==0&&count(this.availableList)==this.availableCount){this._pruneUsersWithoutDisplayInfo(this.availableList);this.sortedList=this._sort(keys(this.availableList));}
return this.sortedList;},_pruneUsersWithoutDisplayInfo:function(availableList){for(var id in availableList){if(!ChatUserInfos[id]){Util.log("pruned user "+id+" without display info");delete availableList[id];}}},getSortedListUI:function(flid){if(!flid&&this.flMode){var groupedList=this._groupAvailableListByFl(true);var list=[];for(var flid in groupedList){list=list.concat(groupedList[flid]);}
return unique(list);}
return this._getSortedList();},getFriendLists:function(){var res={};copy_properties(res,this.flData);delete res[this.otherFriendsFlid];delete res[this.botsFlid];return res;},_getRenderedFriendLists:function(){var flids=[];for(var flid in this.flData){if(!this.flData[flid].h){flids.push(flid);}}
return flids;},_getFriendListsInChat:function(){var flids=this._getRenderedFriendLists();flids.remove(this.otherFriendsFlid);flids.remove(this.botsFlid);return flids;},suppressNonFriendInfoInBuddyList:function(flid){this._updateNonFriendInfoInBuddyList(flid,true);},unsuppressNonFriendInfoInBuddyList:function(flid){this._updateNonFriendInfoInBuddyList(flid,false);},_updateNonFriendInfoInBuddyList:function(flid,suppress){var flids=flid?[flid]:this._getGlobalFlids(true);var idleMarker,flItem;for(var i=0;i<flids.length;i++){var flid=flids[i];if(idleMarker=ge(this._getIdleMarkerId(flid))){CSS.conditionClass(idleMarker,'suppress',suppress);}
if(flid&&(flItem=ge(this._getFriendListId(flid)))){CSS.conditionClass(flItem,'suppress',suppress);}}},_updateCount:function(){if(this.buddyCountSpan){var countText=_tx("{Chat} {number-available}",{'Chat':_tx("\u804a\u5929\u5ba4"),'number-available':'<span class="buddy_count_num">(<strong>'+this.availableCount+'</strong>)</span>'});this.buddyCountSpan.innerHTML=countText;}},setVisibilityRatio:function(cvr){this.visibilityRatio=cvr;presence.doSync();},_getCookieData:function(){var availableListCache={};for(var id in chatDisplay.tabs){if(this.availableList[id]){availableListCache[id]=this.availableList[id];}}
var buddyState={'ac':this.availableCount,'ut':parseInt(this.updateTime*0.001),'ud':parseInt(this.updateDiff),'lc':this.listChanged?1:0,'cvr':this.visibilityRatio};if(!is_empty(this.updateOverlay)){buddyState.uo=this.updateOverlay;}
if(!is_empty(availableListCache)){buddyState.al=availableListCache;}
return buddyState;},_computeUpdateTimeDiff:function(){if(!chatOptions.visibility||(presence.poppedOut&&!presence.inPopoutWindow)){return Math.round(presence.sitevars.BUDDY_MAX_TIME);}
var newUpdateTime=presence.sitevars.BUDDY_BASE_TIME;var now=presence.getTime();if(!chatDisplay.everSentMessage){newUpdateTime+=presence.sitevars.BUDDY_COST_NEVER_SENT_MESSAGE;}
if(!this.listChanged){newUpdateTime+=presence.sitevars.BUDDY_COST_NO_LIST_CHANGE;}
if(chatTabSlider.numTabs==0){newUpdateTime+=presence.sitevars.BUDDY_COST_NO_CHAT_TABS;}
var chatActivityMins=(now-chatDisplay.chatActivityTime)/60000;if(chatActivityMins>presence.sitevars.BUDDY_MAX_ACTIVITY_MINS){chatActivityMins=presence.sitevars.BUDDY_MAX_ACTIVITY_MINS;}
newUpdateTime+=(presence.sitevars.BUDDY_COST_CHAT_ACTIVITY/presence.sitevars.BUDDY_MAX_ACTIVITY_MINS)*chatActivityMins;if(!presence.poppedOut){var pageLoadMins=(now-presence.pageLoadTime)/60000;if(pageLoadMins<chatActivityMins){if(pageLoadMins>presence.BUDDY_MAX_ACTIVITY_MINS){pageLoadMins=presence.BUDDY_MAX_ACTIVITY_MINS;}
newUpdateTime+=(presence.sitevars.BUDDY_COST_PAGE_ACTIVITY/presence.sitevars.BUDDY_MAX_ACTIVITY_MINS)*pageLoadMins;}
if(!this.buddyListOpen){var buddyViewMins=(now-this.buddyViewTime)/60000;if(buddyViewMins>presence.sitevars.BUDDY_MAX_ACTIVITY_MINS){buddyViewMins=presence.sitevars.BUDDY_MAX_ACTIVITY_MINS;}
newUpdateTime+=(presence.sitevars.BUDDY_COST_VIEW_ACTIVITY/presence.sitevars.BUDDY_MAX_ACTIVITY_MINS)*buddyViewMins;}}
if(!newUpdateTime||newUpdateTime>presence.sitevars.BUDDY_MAX_TIME){newUpdateTime=presence.sitevars.BUDDY_MAX_TIME;}
return Math.round(newUpdateTime);},_checkUpdater:function(time,asyncData,forceUpdate){this.updateDiff=this._computeUpdateTimeDiff();if(forceUpdate||(!this.stopUpdates&&(time-this.updateTime)>this.updateDiff*1000)){asyncData.popped_out=presence.poppedOut;asyncData.available_list=this.haveFullList?this.availableList:{};asyncData.force_render=this.shouldRender;return true;}},_forceUpdate:function(forceAll){this.shouldRender=true;var handlers=forceAll?undefined:[ChatBuddyList.UPDATER_NAME];presenceUpdater.forceUpdate(handlers);},updateUserInfos:function(userInfos){copy_properties(ChatUserInfos,userInfos);},_collapseItem:function(id,buddyInfo,shouldAnimate,flid){if(this.flMode&&flid){var flids=[flid];}else{var flids=this._getUserFlids(id,buddyInfo);}
for(var i=0;i<flids.length;i++){var flid=flids[i];var elem=ge(this._getBuddyListItemId(id,flid));if(elem){elem.id=this._getBuddyListWasItemId(id,flid);if(shouldAnimate){animation(elem).to('height','0px').duration(this.expandAnimDuration).go();}
this._removeSortable(id,flids[i]);}}},_expandItem:function(id,flid,prevElem,isIdle,shouldAnimate,shouldDelayExpand,showHighlight){var elem=ge(this._getBuddyListItemId(id,flid));if(!elem){var elem=document.createElement('li');elem.id=this._getBuddyListItemId(id,flid);}
if(isIdle){CSS.setClass(elem,'idle');}
elem.innerHTML=this._renderItem(id,flid,isIdle);var itemHeight=(this.isCompactDisplay?this.compactItemHeight:this.itemHeight);var opts=this._getFlOpts(flid);if(!opts.fullDisplay){itemHeight=this.compactItemHeight;}
if(!shouldAnimate){elem.style.height=itemHeight+'px';DOM.insertAfter(prevElem,elem);}else{elem.style.height='0px';DOM.insertAfter(prevElem,elem);var anim=animation(elem);if(shouldDelayExpand){anim.duration(this.expandAnimDuration+500).checkpoint();}
anim.from('height','0').to('height',itemHeight+'px').duration(this.expandAnimDuration);if(showHighlight===undefined){showHighlight=!isIdle;}
if(showHighlight){elem.style.backgroundColor=this.highlightColor;anim.checkpoint().duration(3000).checkpoint().to('backgroundColor',this.backgroundColor).duration(500);}
anim.go();}
this._addSortable(id,flid);return elem;},_clearWasAvailableItems:function(wasAvailableIDs,wasAvailableList,flid){if(!this.rendered){return;}
for(var i=0;i<wasAvailableIDs.length;i++){var id=wasAvailableIDs[i];if(wasAvailableList[id]){if(this.flMode&&flid){var flids=[flid];}else{var flids=this._getUserFlids(id,wasAvailableList[id]);}
for(var j=0;j<flids.length;j++){var elem=ge(this._getBuddyListWasItemId(id,flids[j]));if(elem){DOM.remove(elem);delete elem;}}}}
this._showBuddyListEmptyItem();},_showBuddyListEmptyItem:function(){var emptyItem=ge(this._getBuddyListEmptyItemId());if(emptyItem){CSS.conditionClass(emptyItem,'hide_empty_item',this.availableCount!=0);}},_hideBuddyListEmptyItem:function(){var emptyItem=ge(this._getBuddyListEmptyItemId());if(emptyItem){CSS.addClass(emptyItem,'hide_empty_item');}},_updateAvailableListWithDiff:function(nowAvailableList,wasAvailableIDs,flid){if(this.stopUpdates){return;}
var id,isIdle;var shouldDelayExpand=false;var wasAvailableList={};var wasAvailableMultipleLists={};var filterExternalFlids=(flid!=null);this._pruneUsersWithoutDisplayInfo(nowAvailableList);for(var i=0;i<wasAvailableIDs.length;i++){var uid=wasAvailableIDs[i];if(this.availableList[uid]){shouldDelayExpand=true;wasAvailableList[wasAvailableIDs[i]]=this.availableList[uid];if(flid&&this.flMode&&this.availableList[uid].fl.length>1){this.availableList[uid].fl.remove(flid);wasAvailableMultipleLists[uid]=1;continue;}
delete this.availableList[uid];}}
this._hideBuddyListEmptyItem();var nowAvailableIDs=keys(nowAvailableList);var shouldAnimate=!flid&&!this.showingError&&!presence.isSafari2&&(wasAvailableIDs.length+nowAvailableIDs.length<this.maxItemsToAnimate);if(this.rendered){for(var i=0;i<wasAvailableIDs.length;i++){if(wasAvailableList[wasAvailableIDs[i]]){this._collapseItem(wasAvailableIDs[i],wasAvailableList[wasAvailableIDs[i]],shouldAnimate,flid);}}
var clearDelay=shouldAnimate?this.expandAnimDuration:0;setTimeout(this._clearWasAvailableItems.bind(this,wasAvailableIDs,wasAvailableList,flid),clearDelay);}
var availableIDs=this.sortedList;if(this.haveFullList){this.sortedList=[];}
this._sort(nowAvailableIDs,nowAvailableList);var nowAvailableID=nowAvailableIDs.shift();var availableID=availableIDs.shift();var compareFunction=this._compareFunction.bind(this,null);var defaultPrevAvailElemIds={},prevIdleElemIds={},prevAvailElemIds={},hasIdle={},hasNotIdle={};var globalFlids=[];if(this.shouldRender){globalFlids=this._getGlobalFlids();for(var i=0;i<globalFlids.length;i++){var flid=globalFlids[i];defaultPrevAvailElemIds[flid]=prevAvailElemIds[flid]=this._getAvailableMarkerId(flid);prevIdleElemIds[flid]=this._getIdleMarkerId(flid);hasIdle[flid]=hasNotIdle[flid]=false;}}
var noResize=false;var flidTracking=function(id,flid,isIdle){var itemID=this._getBuddyListItemId(id,flid);if(isIdle){prevIdleElemIds[flid]=itemID;}else{prevAvailElemIds[flid]=itemID;}
hasIdle[flid]=hasIdle[flid]||isIdle;hasNotIdle[flid]=hasNotIdle[flid]||!isIdle;};var flidTrackingFunc=flidTracking.bind(this);while(true){if(availableID&&wasAvailableList[availableID]&&!wasAvailableMultipleLists[availableID]){availableID=availableIDs.shift();continue;}
if(availableID&&nowAvailableID){if(availableID==nowAvailableID){availableID=availableIDs.shift();continue;}
if(compareFunction(availableID,nowAvailableID,this.availableList[availableID].i,nowAvailableList[nowAvailableID].i)<0){id=availableID;}else{id=nowAvailableID;}}else if(availableID){id=availableID;}else if(nowAvailableID){id=nowAvailableID;}else{break;}
if(id==availableID){availableID=availableIDs.shift();isIdle=this.availableList[id].i;if(this.shouldRender){var flids=this._getUserFlids(id);for(var i=0;i<flids.length;i++){flidTrackingFunc(id,flids[i],isIdle);}}}else{nowAvailableID=nowAvailableIDs.shift();if(this.shouldRender&&this.availableList[id]){var toRemoveFlids=this._getUserFlids(id,this.availableList[id],filterExternalFlids);for(var i=0;i<toRemoveFlids.length;i++){var flid=toRemoveFlids[i];var elem=ge(this._getBuddyListItemId(id,flid));if(elem){this._removeSortable(id,flid);DOM.remove(elem);}}}
this.availableList[id]=nowAvailableList[id];if(this.shouldRender){isIdle=nowAvailableList[id].i;var flids=this._getUserFlids(id,null,filterExternalFlids);for(var i=0;i<flids.length;i++){var flid=flids[i];var prevElem=isIdle?ge(prevIdleElemIds[flid]):ge(prevAvailElemIds[flid]);if(!prevElem){prevElem=ge(defaultPrevAvailElemIds[flid]);}
this._expandItem(id,flid,prevElem,isIdle,shouldAnimate,shouldDelayExpand);noResize=true;flidTrackingFunc(id,flid,isIdle);}}}
if(this.haveFullList){this.sortedList.push(id);}}
if(this.shouldRender){for(var i=0;i<globalFlids.length;i++){var flid=globalFlids[i];var idleMarker=ge(this._getIdleMarkerId(flid));if(idleMarker){if(hasIdle[flid]&&hasNotIdle[flid]){CSS.removeClass(idleMarker,'hide_idle_marker');}else{CSS.addClass(idleMarker,'hide_idle_marker');}}}
var delay=0;if(shouldAnimate){var didExpand=noResize;if(didExpand){delay+=this.expandAnimDuration;}
if(shouldDelayExpand){delay+=this.expandAnimDuration;if(didExpand){delay+=500;}}}
setTimeout(this.resizeTab.bind(this),delay);this._resetFlidClasses();}
this._availableListChanged(noResize);},_sort:function(ids,availableList){availableList=availableList||this.availableList;var compareFunction=this._compareFunction.bind(this,availableList);ids.sort(compareFunction);return ids;},_compareFunction:function(availableList,id1,id2,id1Idle,id2Idle){if(typeof id1Idle=='undefined'){id1Idle=availableList[id1].i;}
if(typeof id2Idle=='undefined'){id2Idle=availableList[id2].i;}
if(id1Idle^id2Idle){return id1Idle?1:-1;}
var id1Name=ChatUserInfos[id1].name.toLowerCase();var id2Name=ChatUserInfos[id2].name.toLowerCase();return(id1Name<id2Name)?-1:1;},_availableListChanged:function(noResize){if(this.haveFullList){this.availableCount=count(this.availableList);}
for(var id in this.availableList){this.availableList[id].i=this.availableList[id].i?1:0;}
if(this.rendered){presenceCookieManager.store();}
presence.contentChanged(this.contentID);if(!noResize){this.resizeTab();}
this._updateCount();Arbiter.inform(ChatBuddyList.AVAILABILITY_CHANGED,{sender:this,justCameOnline:this.justCameOnline});this.justCameOnline=false;},_onUpdaterResponse:function(buddyListResponse,time){if(this.shouldRender&&!buddyListResponse.forcedRender){return;}
this.updateTime=time;if(!chatOptions.visibility||this.stopUpdates){return;}
var hadFullList=this.haveFullList;var flChanged=this._flChanged(buddyListResponse.flMode,buddyListResponse.flData);var nowAvailableListEmpty=is_empty(buddyListResponse.nowAvailableList);this.numRequestFailures=0;this.errorMode=false;this._hideError();this.listChanged=buddyListResponse.listChanged;this.updateUserInfos(buddyListResponse.userInfos);if((hadFullList&&flChanged)||nowAvailableListEmpty){}else{this.flMode=buddyListResponse.flMode;this.flData=buddyListResponse.flData;}
if(this.shouldRender){this.haveFullList=true;if(!this.rendered){this._firstRender();}}else{this.availableCount=buddyListResponse.availableCount;this._updateCount();}
if(!hadFullList||buddyListResponse.wasAvailableIDs.length||!nowAvailableListEmpty){for(var id in this.updateOverlay){if(time<this.updateOverlay[id].exp){if(hadFullList||!this.availableList[id]){delete buddyListResponse.nowAvailableList[id];}else{buddyListResponse.nowAvailableList[id]=this.availableList[id];}
for(var i=0;i<buddyListResponse.wasAvailableIDs.length;i++){if(id==buddyListResponse.wasAvailableIDs[i]){buddyListResponse.wasAvailableIDs.splice(i,1);break;}}}else{delete this.updateOverlay[id];}}
if(hadFullList){if(flChanged&&!nowAvailableListEmpty){buddyListResponse.nowAvailableList=this._massageNowAvailableList(buddyListResponse.nowAvailableList,buddyListResponse.flMode,buddyListResponse.flData);}
this._updateAvailableListWithDiff(buddyListResponse.nowAvailableList,buddyListResponse.wasAvailableIDs);if(flChanged){this._onFlChange(buddyListResponse.flMode,buddyListResponse.flData);}}else{this.availableList=buddyListResponse.nowAvailableList;this._availableListChanged(true);if(this.shouldRender){this._render();}}}else{this._availableListChanged.bind(this).defer();if(flChanged&&nowAvailableListEmpty){this._onFlChange(buddyListResponse.flMode,buddyListResponse.flData);}}},_onUpdaterError:function(response){this.numRequestFailures++;if(this.numRequestFailures>1){this.updateTime=presence.getTime();this.availableCount=0;this._updateCount();this._updateAvailableListWithDiff({},keys(this.availableList));this._showLoadError();}},itemOnClick:function(id,flid){var elem;if((elem=ge(this._getBuddyListItemId(id,flid)))&&elem.activeDrag){return;}
presence.pauseSync();chatDisplay.focusTab(id);if(!this.isSticky()){this.closeTab();}
if(this.typeahead){this.typeahead.resetSearch(true);}
Arbiter.inform(ChatBuddyList.BUDDY_CLICKED,{flid:flid,id:id});presence.resumeSync();},_renderItem:function(id,flid,isIdle){var userInfo=ChatUserInfos[id];var name=userInfo.name;var picSrc=userInfo.thumbSrc;var nameCapped;if(name.length>this.maxNameLen){nameCapped=name.substring(0,this.maxNameLen-2)+'...';}else{nameCapped=name;}
var anchorTitle='';if(isIdle){anchorTitle=_tx("\u9592\u7f6e");}
if(flid){var onclick=sprintf('buddyList.itemOnClick(%d, \'%s\')',id,flid);}else{var onclick=sprintf('buddyList.itemOnClick(%d)',id);}
var markupArr=['<a href="#" class="clearfix" title="',anchorTitle,'"','onclick="',onclick,';return false;">'];var fullDisplay=!this.isCompactDisplay;var opts=this._getFlOpts(flid);fullDisplay&=opts.fullDisplay;if(fullDisplay){markupArr=markupArr.concat('<img src="',picSrc,'" width="22px" height="22px" />');}
markupArr=markupArr.concat('<div class="friend_status">','<strong id="',this._getBuddyListItemNameId(id,flid),'">',htmlize(nameCapped),'</strong>');markupArr=markupArr.concat('</div>','<div class="available_dot"></div>','</a>');return markupArr.join('');},_groupAvailableListByFl:function(groupSorted,emptyGroups){if(!this.flMode||!this.flData){return null;}
groupSorted=groupSorted||false;emptyGroups=emptyGroups||false;var result={};for(var flid in this.flData){result[flid]=[];}
if(emptyGroups){return result;}
var groupId=function(id){var flids=this.availableList[id].fl;if(flids){for(var j=0;j<flids.length;++j){var flid=flids[j];result[flid].push(id);}}};var groupIdFunc=groupId.bind(this);if(groupSorted){var sortedList=this._getSortedList();for(var i=0;i<sortedList.length;i++){groupIdFunc(sortedList[i]);}}else{for(var id in this.availableList){groupIdFunc(id);}}
return result;},_listNameInUse:function(name){for(var flid in this.flData){if(this.flData[flid].n==name){return true;}}
return false;},keyPressNewListInput:function(e){if(event_get_keypress_keycode(e)==KEYS.RETURN){var e=$E(e);var list_name=e.getTarget().value;if(this._listNameInUse(list_name)){new ErrorDialog().showError(_tx("\u767c\u751f\u932f\u8aa4\u3002"),_tx("\u5169\u500b\u540d\u55ae\u4e0d\u80fd\u540c\u540d\u3002\u8acb\u70ba\u9019\u500b\u540d\u55ae\u9078\u64c7\u5176\u4ed6\u540d\u5b57\u3002"))
return;}
var data={'create':list_name};this._saveBuddyListSetting(data,function(){for(var flid in this.flData){if(this.flData[flid].n==list_name){Vector2.scrollIntoView($(this._getFriendListId(flid)));break;}}}.bind(this));return e.kill();}},handleFlInChat:function(is_visible,flid){buddyListDisplay.closeOpenFlyout();if(is_visible){this._unHideFriendListFromChat(flid);}else{this._hideFriendListFromChat(flid);}},_unHideFriendListFromChat:function(flid){var noLists=this._getFriendListsInChat().length==0;var flids=[flid];var data={'unhide_from_chat':1,'flids':flids};this.flData[flid].h=0;this._saveBuddyListSetting(data,function(){this._showEmptyListMomentarily(flid);Vector2.scrollIntoView($(this._getFriendListId(flid)));}.bind(this));if(noLists){this._onFlChange(true,this.flData);}else{this._addFlidsToDOM(flids);}},_hideFriendListFromChat:function(flid){var lastList=this._getFriendListsInChat().length==1;var flids=[flid];var data={'hide_from_chat':1,'flids':flids};this.flData[flid].h=1;this._saveBuddyListSetting(data);if(lastList){this._onFlChange(false,this.flData);}else{this._removeFlidsFromBuddyList(flids);}},_friendListHandleSwitchThrown:function(flid){var currentlyOnline=this.flData[flid].o;if(currentlyOnline){this._goOfflineToLists([flid]);}else{this._goOnlineToLists([flid]);}},_friendListHandleSwitchMouseDown:function(flid){var evt=Event.listen(document,'mouseup',function(){evt.remove();this._friendListHandleSwitchThrown(flid);}.bind(this));},_friendListHandleMouseOver:function(flid){if(this.reorderingLists){return;}
CSS.addClass($(this._getFriendListId(flid)),'hover');},_friendListHandleMouseOut:function(flid){CSS.removeClass($(this._getFriendListId(flid)),'hover');},_friendListHandleEditLinckClick:function(flid){if(!this.reorderingLists){Dialog.bootstrap(DialogBootstrapEndpoints.LIST_EDITOR,{list_id:flid});}
return false;},_saveBuddyListSetting:function(data,callback){data['user']=this.user;callback=callback||bagofholding;new AsyncRequest().setData(data).setURI('/ajax/chat/buddy_list_settings.php').setHandler(this._onBuddyListSettingSave.bind(this,callback)).setFinallyHandler(function(){buddyListDisplay.closeOpenFlyout();}).send();},_goOnlineToLists:function(flids,readOnly){readOnly=readOnly||false;var data={'online_to_list':1,'flids':flids,'read_only':readOnly};this._handleFlVisibilityChange(flids,1);this._saveBuddyListSetting(data);},_handleFlVisibilityChange:function(flids,online,callback){for(var i=0;i<flids.length;i++){var flid=flids[i]
var flItem=ge(this._getFriendListId(flid));if(!flItem){continue;}
this.flData[flid].o=online;if(online){CSS.addClass(flItem,'online');CSS.removeClass(flItem,'offline');if(flid==this.otherFriendsFlid){this._showEmptyListMomentarily(flid);}}else{CSS.addClass(flItem,'offline');CSS.removeClass(flItem,'online');}
var tooltip=DOM.find(flItem,'div.titletip strong');DOM.setText(tooltip,this._getFriendListTooltipText(flid));callback&&callback(flid);}},_showEmptyListMomentarily:function(flid){this.shownEmptyFlids=this.shownEmptyFlids||{};this.shownEmptyFlids[flid]=1;var flItem=ge(this._getFriendListId(flid));if(flItem){CSS.addClass(flItem,'show_empty_list');}
(function(){delete this.shownEmptyFlids[flid];var flItem=ge(this._getFriendListId(flid));if(flItem){CSS.removeClass(flItem,'show_empty_list');}}).bind(this).defer(8000);},_goOfflineToLists:function(flids,uiOnly){uiOnly=uiOnly||false;var groupedLists=this._groupAvailableListByFl();this._handleFlVisibilityChange(flids,0,function(flid){var idsToRemove=groupedLists[flid];this._removeFromBuddyList(idsToRemove,flid);}.bind(this));if(!uiOnly){var data={'offline_to_list':1,'flids':flids};this._saveBuddyListSetting(data);}},_removeFlidsFromBuddyList:function(flids,groupedList){groupedList=groupedList||this._groupAvailableListByFl(true);if(!groupedList){return;}
var nowAvailList={};for(var i=0;i<flids.length;i++){var flid=flids[i];var ids=groupedList[flid];if(!ids){continue;}
for(var j=0;j<ids.length;j++){var id=ids[j];var buddyInfo={};buddyInfo['i']=this.availableList[id].i;buddyInfo['fl']=this.availableList[id].fl.clone();if(this.flMode){buddyInfo.fl.remove(flid);if(buddyInfo.fl.length==0){buddyInfo.fl.push(this.otherFriendsFlid);}}else{delete buddyInfo.fl;}
nowAvailList[id]=buddyInfo;}}
if(!is_empty(nowAvailList)){this._updateAvailableListWithDiff(nowAvailList,[]);}
this._removeFlidsFromDOM(flids);},_onBuddyListSettingSave:function(callback,asyncResponse){var payload=asyncResponse.getPayload();if(payload){if(payload.availableList){this.updateUserInfos(payload.userInfos);var flid;if(payload.flids&&payload.flids.length==1){flid=payload.flids[0];}
this._updateAvailableListWithDiff(payload.availableList,[],flid);}
if(payload.flData){var flMode;if(typeof payload.flMode!='undefined'){flMode=payload.flMode;}else{flMode=true;}
this._onFlChange(flMode,payload.flData);this._resetFlidClasses();}
callback&&callback();}},_flManagerHandler:function(message,data){},_resetFlidClasses:function(){if(!this.flMode){return;}
var groupedFl=this._groupAvailableListByFl();for(var flid in this.flData){var flItem=ge(this._getFriendListId(flid));if(flItem){CSS.setClass(flItem,this._getFriendListItemClasses(flid,groupedFl));}}},_getFriendListItemClasses:function(flid,groupedFl){var flid_online=this.flData[flid].o;var flid_hidden=this.flData[flid].h;var classes=['friend_list'];if(flid_online){classes.push('online');}else{classes.push('offline');}
if(!flid_hidden&&this.shownEmptyFlids&&this.shownEmptyFlids[flid]){classes.push('show_empty_list');}
if(is_empty(groupedFl[flid])){if(this.availableCount!=0&&(this.flData[flid].c==0||flid==this.otherFriendsFlid)){classes.push('empty_friend_list');}else if(flid_online){classes.push('hide_friend_list');}}
if(flid==this.otherFriendsFlid){classes.push('compact_friend_list');classes.push('other_friends_list');}
if(this.reorderingLists&&(flid==this.otherFriendsFlid||flid==this.botsFlid)){classes.push('suppress');}
return classes.join(' ');},_renderFriendListHeader:function(flid){var fl_name=this.flData[flid].n;var online=this.flData[flid].o;var edit_link='';var sacred=typeof this.flData[flid].s!='undefined';if(!sacred&&flid!=this.otherFriendsFlid){edit_link=_tx("\u7de8\u8f2f");}
var markupArr=['<div class="friendlist_status">','<span class="title"><a href="#">',htmlize(fl_name),'</a></span>','<span class="edit_link">','<a href="#">',edit_link,'</a>','</span>','</div>'];if(!sacred){markupArr.push('<div class="online_status_container"><a class="online_status" ','>','<div class="titletip"><strong>',this._getFriendListTooltipText(flid),'</strong></div>','</a>','</div>');}
return markupArr.join('');},_getFriendListTooltipText:function(flid){return this.flData[flid].o?_tx("\u96e2\u7dda"):_tx("\u4e0a\u7dda");},registerExternalFriendList:function(opts){if(!this.rendered){this._firstRender();}
var flid='xfl_'+this.externalFlids.length;this.externalFlids.push(flid);this.flOpts[flid]=opts;return flid;},_renderFriendListContent:function(flid,ids){var markupArr;var haveFlid=this.flMode&&flid;if(haveFlid){markupArr=['<ul id="',this._getFriendListContainerId(flid),'"','class="friend_list_container">'];}else{markupArr=[];}
markupArr.push('<li id="',this._getAvailableMarkerId(flid),'" class="suppress"></li>');var idleArr=[];var hasIdle=false,hasNotIdle=false;for(var j=0;j<ids.length;j++){var id=ids[j];var idle=this.availableList[id].i;var itemMarkupArr=['<li id="',this._getBuddyListItemId(id,flid),'"',(idle?' class="idle"':''),'>',this._renderItem(id,flid,idle),'</li>'];if(idle){hasIdle=true;idleArr=idleArr.concat(itemMarkupArr);}else{hasNotIdle=true;markupArr=markupArr.concat(itemMarkupArr);}}
var idleMarkerClass=(hasIdle&&hasNotIdle)?'':' hide_idle_marker';markupArr.push('<li id="',this._getIdleMarkerId(flid),'" class="subheader',idleMarkerClass,'"></li>');markupArr=markupArr.concat(idleArr);if(haveFlid){markupArr.push('</ul>');}
return markupArr.join('');},_addFriendListListeners:function(flids){if(!this.flMode){return;}
flids=flids||this._getRenderedFriendLists();for(var i=0;i<flids.length;i++){var flid=flids[i];if(typeof this.flData[flid].s!='undefined'){continue;}
var flItem=$(this._getFriendListId(flid));Event.listen(flItem,'mouseover',this._friendListHandleMouseOver.bind(this,flid));Event.listen(flItem,'mouseout',this._friendListHandleMouseOut.bind(this,flid));var switch_link=DOM.find(flItem,'a.online_status');Event.listen(switch_link,'mousedown',this._friendListHandleSwitchMouseDown.bind(this,flid));if(flid!=this.otherFriendsFlid){var edit_link_area=DOM.find(flItem,'div.friendlist_status');Event.listen(edit_link_area,'click',this._friendListHandleEditLinckClick.bind(this,flid));}}},_renderBuddyContent:function(){var emptyItemClass=(this.availableCount?'hide_empty_item':'');var markupArr=['<div id="buddy_list_all" class="subgroup">',this.renderEmptySearch(),'<ul id="buddy_list_parent" class="list_select">','<li id="',this._getBuddyListEmptyItemId(),'" class="info_text ',emptyItemClass,'">',_tx("\u6c92\u4eba\u5728\u7dda\u4e0a\u3002"),'</li>'];var flids;var groupedLists={};if(this.flMode){flids=keys(this.flData);groupedLists=this._groupAvailableListByFl(true);}else{flids=[null];}
for(var i=0;i<flids.length;++i){var flid=flids[i];var ids=[];if(this.flMode&&flid){if(this.flData[flid].h){continue;}
markupArr.push('<li id="',this._getFriendListId(flid),'"','class="',this._getFriendListItemClasses(flid,groupedLists),'">',this._renderFriendListHeader(flid));ids=groupedLists[flid];}else{ids=this._getSortedList();}
markupArr.push(this._renderFriendListContent(flid,ids));if(this.flMode&&flid){markupArr.push('</li>');}}
markupArr.concat(['</ul>','</div>']);return markupArr.join('');},renderEmptySearch:function(flid){var html='<div id="'+this._getEmptySearchId(flid)+'" class="info_text" style="display:none">'+
_tx("\u5728\u7dda\u4e0a\u627e\u4e0d\u5230\u8a72\u4f4d\u670b\u53cb\u3002")+'</div>';return html;},_render:function(){this._getSortedList();CSS.conditionClass(this.contentDiv,'compact',this.isCompactDisplay);var content=this._renderBuddyContent();if(this.rendered){CSS.addClass(this.contentDiv,'hidden');}
this.contentDiv.innerHTML=content;presence.contentChanged(this.contentID);if(this.rendered){CSS.addClass(this.wrapperDiv,'presence_menu_offscreen');this._hideError();CSS.removeClass(this.contentDiv,'hidden');this.resizeTab();CSS.removeClass(this.wrapperDiv,'presence_menu_offscreen');this._initDragging();this._addFriendListListeners();}
if(this.errorMode){this._showLoadError();}
if(this.shouldShowLoading){this._showLoading();this.shouldShowLoading=false;}},_firstRender:function(){this._render();this.rendered=true;this.loadTypeahead();},updateItemDisplay:function(id){var buddyInfo=this.availableList[id];if(!buddyInfo){return;}
var userFlids=this._getUserFlids(id);for(var i=0;i<userFlids.length;i++){var flid=userFlids[i];var item=ge(this._getBuddyListItemId(id,flid));if(!item){return;}
item.innerHTML=this._renderItem(id,flid,buddyInfo.i);}},_showLoadError:function(){this._showError(_tx("\u7121\u6cd5\u8f09\u5165\u53ef\u4ee5\u804a\u5929\u7684\u670b\u53cb\u3002"));},_showLoading:function(){this._showError(_tx("\u8f09\u5165\u4e2d......"));},_hideError:function(){this.showingError=false;CSS.removeClass(this.wrapperDiv,'error');},_showError:function(error){this.showingError=true;set_inner_html(this.buddyListError,error);CSS.addClass(this.wrapperDiv,'error');},isSticky:function(){return chatOptions.getSetting('sticky_buddylist');},enterReorderingFlMode:function(){if(this.reorderingLists){return;}
this.reorderingLists=true;CSS.addClass(this.wrapperDiv,'reorder_fl');var allFlids=this._getRenderedFriendLists();this.flSortableGroup=new SortableGroup();for(var i=0;i<allFlids.length;i++){var flid=allFlids[i];if(flid==this.otherFriendsFlid||flid==this.botsFlid){CSS.addClass(this._getFriendListId(flid),'suppress');}else{this._addFlSortable(flid);}}
var reorder_alert=$N('div',{id:'reorder_fl_alert'},[$N('span',{className:'helper_text'},_tx("\u62d6\u66f3\u540d\u55ae\u91cd\u65b0\u6392\u5e8f")),$N('input',{type:'button',className:'inputbutton',value:_tx("\u5b8c\u6210\u91cd\u65b0\u6392\u5e8f"),onclick:this.exitReorderingFlMode.bind(this)})]);DOM.insertBefore(reorder_alert,this.contentDiv);this.freezeTabSize(false);},exitReorderingFlMode:function(){if(!this.reorderingLists){return;}
this._reorderFlids();DOM.remove($('reorder_fl_alert'));CSS.removeClass(this.wrapperDiv,'reorder_fl');var allFlids=this._getRenderedFriendLists();for(var i=0;i<allFlids.length;i++){var flid=allFlids[i];if(flid==this.otherFriendsFlid||flid==this.botsFlid){CSS.removeClass(this._getFriendListId(flid),'suppress');}else{this._removeFlSortable(flid);}}
this.reorderingLists=false;this.unfreezeTabSize.bind(this).defer(50);this.flSortableGroup.destroy();this.flSortableGroup=null;},_addFlSortable:function(flid){if(this.flSortableGroup!=null){this.flSortableGroup.addSortable(flid,$(this._getFriendListId(flid)));animation($(this._getFriendListContainerId(flid))).to('height','0px').to('opacity',0).from(1).blind().hide().ease(animation.ease.end).duration(300).go();}},_removeFlSortable:function(flid){if(this.flSortableGroup!=null){this.flSortableGroup.removeSortable(flid);var container;if(container=ge(this._getFriendListContainerId(flid))){animation(container).to('height','auto').from('0px').to('opacity',1).from(0).blind().show().ease(animation.ease.end).duration(300).go();}}},_reorderFlids:function(){var data={'reorder':1,'flids':this.flSortableGroup.getOrder()};this._saveBuddyListSetting(data);},_getDragKey:function(id,flid){return id+'_'+flid;},_initDragging:function(){if(!this.flMode){return;}
var groupedLists=this._groupAvailableListByFl();this.sortables={};var flids=this._getRenderedFriendLists();for(var i=0;i<flids.length;i++){var flid=flids[i];var ids=groupedLists[flid];this._initFlidSortable(flid,ids);}},_initFlidSortable:function(flid,ids){if(!flid||!this.flMode){return;}
if(this.flData[flid].s){return;}
var firstFlid=head(this.sortables);this.sortables[flid]=new SortableGroup();if(firstFlid){firstFlid.link(this.sortables[flid]);}
var emptyMessage=$N('li',{id:this._getEmptyListDropZoneId(flid),className:'list_drop_zone'},$N('span',{className:'list_drop_zone_inner'},_tx("\u62d6\u66f3\u670b\u53cb\u7684\u540d\u5b57\u5230\u6b64\uff0c\u5c31\u53ef\u628a\u4ed6\u52a0\u5230\u9019\u500b\u540d\u55ae\u4e2d\u3002")));var root=$(this._getFriendListContainerId(flid));this.sortables[flid].addEmptyMessage(emptyMessage,root).setBoundingBox(this._getBoundingBox()).setDragOverCallback(this._dragOverHandler.bind(this)).setDropCallback(this._dropHandler.bind(this));for(var j=0;j<ids.length;j++){this._addSortable(ids[j],flid);}},_getBoundingBox:function(){return Rect.newFromVectors(new Vector2(0,0),Vector2.getElementDimensions(this.contentDiv));},_destroyFlidSortable:function(flid){if(!flid||!this.flMode){return;}
if(this.sortables&&this.sortables[flid]){this.sortables[flid].destroy();delete this.sortables[flid];}},_addSortable:function(id,flid){if(!flid||!this.flMode||!this.flData[flid]){return;}
if(this.flData[flid].s){return;}
if(!this.sortables[flid]){return;}
var key=this._getDragKey(id,flid);if(this.sortables[flid].keyExists(key)){return;}
this.sortables[flid].addSortable(key,ge(this._getBuddyListItemId(id,flid)));},_removeSortable:function(id,flid,otherFlid){if(!flid||!this.flMode){return;}
if(this.sortables[flid]){this.sortables[flid].removeSortable(this._getDragKey(id,otherFlid||flid));}},_dragOverHandler:function(draggable,droppable){if(CSS.hasClass(droppable,'list_drop_zone')){var flid=this._extractFlid(droppable.id);var parent=$(this._getFriendListId(flid));CSS.addClass(parent,'drag_over');}},_dropHandler:function(key){var temp=key.split('_');if(temp.length!=2){return;}
var id=temp[0];var oldFlid=temp[1];var draggedItem=$(this._getBuddyListItemId(id,oldFlid));if(!draggedItem){return;}
var newFlid=this._extractFlid(draggedItem.parentNode.id);if(newFlid==oldFlid){this._updateUIAfterDragging(id,oldFlid,oldFlid,draggedItem);}else{if(this.flData[oldFlid].s||this.flData[newFlid].s){this._updateUIAfterDragging(id,oldFlid,oldFlid,draggedItem);return;}
var currentFlids=this.availableList[id].fl;var movingList=false;var removingList=false;var saveData=false;if(newFlid==this.otherFriendsFlid){removingList=true;if(currentFlids.length==1){this.availableList[id].fl=[this.otherFriendsFlid];}else{this.availableList[id].fl.remove(oldFlid);saveData=true;DOM.remove(draggedItem);Vector2.scrollIntoView(this.getBuddyItem(id));}}else if(currentFlids.length==1){this.availableList[id].fl=[newFlid];movingList=oldFlid!=this.otherFriendsFlid;}else{movingList=true;this.availableList[id].fl.push(newFlid);this.availableList[id].fl.remove(oldFlid);}
if(saveData||this._updateUIAfterDragging(id,oldFlid,newFlid,draggedItem)){var data;if(removingList){data={'remove_fl':true,'old_flid':oldFlid,'drag_uid':id};}else if(movingList){data={'move_fl':true,'new_flid':newFlid,'old_flid':oldFlid,'drag_uid':id};}else{data={'add_fl':1,'new_flid':newFlid,'drag_uid':id};}
this._saveBuddyListSetting(data);}}
this._resetFlidClasses();},_updateUIAfterDragging:function(id,oldFlid,newFlid,draggedItem){var groupedLists=this._groupAvailableListByFl(true);var sortedList=groupedLists[newFlid];var index=sortedList.indexOf(id);var prevElem;if(index==-1){return false;}else if(index==0){prevElem=$(this._getAvailableMarkerId(newFlid));}else{prevElem=$(this._getBuddyListItemId(sortedList[index-1],newFlid));}
(function(){var shouldAnimate,showHighlight=false;if(sortedList.length!=1){shouldAnimate=showHight=true;}
var newItem=this._expandItem(id,newFlid,prevElem,this.availableList[id].i,shouldAnimate,false,showHighlight);if(oldFlid!=newFlid){DOM.remove(draggedItem);this._removeSortable(id,newFlid,oldFlid);}
Vector2.scrollIntoView(newItem);}).bind(this).defer(500);return true;},_getGlobalFlids:function(filterExternalFlids){var flids=this.flMode&&this.flData?keys(this.flData):[null];return filterExternalFlids?flids:flids.concat(this.externalFlids);},_getUserFlids:function(id,buddyInfo,filterExternalFlids){buddyInfo=buddyInfo||this.availableList[id];var flids=buddyInfo.fl?buddyInfo.fl:[null];if(!filterExternalFlids){if(!buddyInfo.allFlids){buddyInfo.allFlids=this._addExternalFlids(id,flids);}
flids=buddyInfo.allFlids;}
return flids;},_addExternalFlids:function(id,flids){flids=flids.concat();for(var i=0;i<this.externalFlids.length;i++){var flid=this.externalFlids[i];var opts=this._getFlOpts(flid);if(!opts.excludeIds[id]){flids.push(flid);}}
return flids;},_getFlOpts:function(flid){return this.flOpts[flid]||ChatBuddyList.DEFAULT_OPTS;},_getAvailableMarkerId:function(flid){return this._encodeFlid('buddy_list_avail_marker',flid);},_getIdleMarkerId:function(flid){return this._encodeFlid('buddy_list_idle_marker',flid);},_getEmptyListDropZoneId:function(flid){return this._encodeFlid('buddy_list_drop_zone',flid);},_getBuddyListItemId:function(id,flid){return this._encodeFlid('buddy_list_item_'+id,flid);},_getBuddyListItemNameId:function(id,flid){return this._encodeFlid('buddy_list_item_name_'+id,flid);},_getBuddyListWasItemId:function(id,flid){return this._encodeFlid('buddy_list_was_item_'+id,flid);},_getEmptySearchId:function(flid){return this._encodeFlid('buddy_list_empty_search',flid);},_getBuddyListEmptyItemId:function(){return'buddy_list_empty_item';},_encodeFlid:function(elemId,flid){return flid?(flid+'_'+elemId):elemId;},_getFriendListId:function(flid){return this._encodeFlid('friend_list_item',flid);},_extractFlid:function(id){return id.split('_').shift();},_getFriendListContainerId:function(flid){return this._encodeFlid('friend_list_container',flid);},debugPrintUpdateOverlay:function(){Util.log("buddyList.updateOverlay =");var uo=this.updateOverlay;for(var id in uo){Util.log(id+": st = "+uo[id].ol+", expires in = "+
(uo[id].exp-presence.getTime()));}}};

function ChatBuddyListDisplay(buddy_list_panel_id){this.openFlyout=null;this.openControl=null;this.panelID=buddy_list_panel_id;if(presence.inPopoutWindow){this._init();}else{this.arbiterInit=Arbiter.subscribe(PresenceMessage.TAB_OPENED,this._onTabOpen.bind(this));}}
ChatBuddyListDisplay.prototype={_onTabOpen:function(type,data){var tab=data.tabID;if(tab&&tab=='buddy_list_tab'){Arbiter.unsubscribe(this.arbiterInit);this._init();}},_init:function(){this.buddyListPanel=$(this.panelID,true);var lists_callback=this._clickControlPanel.bind(this,'buddy_list_panel_lists_control','buddy_list_panel_lists_flyout',this._getListsFlyoutContent.bind(this));Event.listen(DOM.find(this.buddyListPanel,'#buddy_list_panel_lists_control a'),'click',lists_callback);var settings_callback=this._clickControlPanel.bind(this,'buddy_list_panel_settings_control','buddy_list_panel_settings_flyout',this._getChatSettingsNodes.bind(this));Event.listen(DOM.find(this.buddyListPanel,'#buddy_list_panel_settings_control a'),'click',settings_callback);},_clickVisibilityToggle:function(){chatOptions.toggleVisibility();this.closeOpenFlyout();},_clickReorderLists:function(){buddyList.enterReorderingFlMode();this.closeOpenFlyout();},_clickControlPanel:function(controlID,flyoutID,markupFunc){if(this.openFlyout){if(this.openFlyout==flyoutID){this.closeOpenFlyout();}else{this.closeOpenFlyout();this._openFlyout(controlID,flyoutID,markupFunc());}}else{this._openFlyout(controlID,flyoutID,markupFunc());}
return false;},_openFlyout:function(controlID,flyoutID,content){DOM.setContent($(flyoutID),content);CSS.removeClass(flyoutID,'hidden_elem');CSS.addClass(controlID,'flyout_open');if(!presence.poppedOut){var flyoutHeight=Vector2.getElementDimensions($(flyoutID)).y;var contentWrapperHeight=Vector2.getElementDimensions(buddyList.getContentWrapper()).y;if(flyoutHeight>contentWrapperHeight){CSS.addClass(flyoutID,'flyout_reversed');}}
this.openFlyout=flyoutID;this.openControl=controlID;},isFlyoutOpen:function(){return this.openFlyout;},closeOpenFlyout:function(){if(!this.openFlyout){return;}
CSS.addClass(this.openFlyout,'hidden_elem');CSS.removeClass(this.openFlyout,'flyout_reversed');CSS.removeClass(this.openControl,'flyout_open');this.openFlyout=null;this.openControl=null;},_getListsFlyoutContent:function(){var new_list_input=$N('input',{className:'inputtext',type:'text'});new_list_input.listen('keypress',buddyList.keyPressNewListInput.bind(buddyList));new TextInputControl(new_list_input).setPlaceholderText(_tx("\u8f38\u5165\u670b\u53cb\u540d\u55ae\u540d\u7a31"));var new_list=$N('div',{className:'new_list'},[$N('span',{},_tx("\u5efa\u7acb\u65b0\u540d\u55ae\uff1a")),new_list_input]);var instructions=$N('div',{className:'text'},_tx("\u5728\u804a\u5929\u5ba4\u4e2d\u986f\u793a\u9019\u4e9b\u540d\u55ae\uff1a"));var flData=buddyList.getFriendLists();var checklist=new UISelectList();checklist.setCallback(buddyList.handleFlInChat.bind(buddyList));for(var flid in flData){checklist.addItem(flData[flid].n,!flData[flid].h,flid);}
return[instructions,checklist.getElement(),new_list];},_renderListSettingToggle:function(flid,checked,fl_name){return this._renderToggle('list_online_'+flid,checked,fl_name,'list_online_checkbox_'+flid,function(checkbox,evt){buddyList.handleFlInChat(flid,checkbox);});},_renderChatSettingToggle:function(name,value,label){return this._renderToggle('chat_setting_'+name,value,label,'chat_setting_checkbox_'+name,function(checkbox,evt){this.sendSettingChange(name,checkbox.checked);}.bind(this));},_renderToggle:function(div_id,checked,label,checkbox_id,onclick){var checkbox=$N('input',{type:'checkbox',id:checkbox_id,name:checkbox_id});checkbox.checked=checked;checkbox.defaultChecked=checked;checkbox.listen('click',onclick.bind(this,checkbox));var labelElem=$N('label',{},label);labelElem.setAttribute('for',checkbox_id);return $N('div',{className:'chat_setting clearfix',id:div_id},[$N('div',{className:'input_box'},[$N('span',{className:'show_loading'},$N('img',{src:'/images/loaders/indicator_blue_small.gif'})),$N('span',{className:'hide_loading'},checkbox)]),labelElem]);},_getChatSettingsNodes:function(){var nodes=[];if(this.buddyListPanel){var offline_button=$N('a',{className:'go_offline_control'},[$N('div',{className:'menu_icon'}),$N('span',{},_tx("\u5207\u63db\u70ba\u300c\u96e2\u7dda\u300d\u72c0\u614b\u3002"))]);offline_button.listen('click',this._clickVisibilityToggle.bind(this));var options_actions=$N('div',{className:'options_actions'},offline_button);if(buddyList._getFriendListsInChat().length>1){var reorder_button=$N('a',{className:'list_reorder_control'},[$N('div',{className:'menu_icon'}),$N('span',{},_tx("\u540d\u55ae\u6392\u5e8f"))]);reorder_button.listen('click',this._clickReorderLists.bind(this));options_actions.appendChild(reorder_button);}
var popout_button=$N('a',{className:'list_popout_control'},[$N('div',{className:'menu_icon'}),$N('span',{},(presence.poppedOut?_tx("Pop in Chat"):_tx("\u653e\u5927\u804a\u5929\u5ba4\u8996\u7a97")))]);popout_button.listen('click',presence.popout.bind(presence));options_actions.appendChild(popout_button);nodes.push(options_actions);nodes.push($N('hr',{className:'menu_divider'}));}
var list=[{name:'sound',label:_tx("\u7576\u6709\u65b0\u8a0a\u606f\u6642\u64ad\u653e\u97f3\u6548")},{name:'sticky_buddylist',label:_tx("\u7dda\u4e0a\u670b\u53cb\u7684\u8996\u7a97\u7dad\u6301\u958b\u653e\u72c0\u614b")},{name:'compact_buddylist',label:_tx("\u53ea\u986f\u793a\u6b63\u5728\u7dda\u4e0a\u7684\u670b\u53cb\u540d\u5b57")}];for(var i=0;i<list.length;i++){nodes.push(this._renderChatSettingToggle(list[i].name,chatOptions.getSetting(list[i].name),list[i].label));}
return nodes;},_onSettingChangeResponse:function(name,value,response){chatOptions.setSetting(name,value);CSS.removeClass($('chat_setting_'+name),'chat_setting_loading');presence.doSync();},_onSettingChangeError:function(name,response){presence.showAsyncError(response,_tx("\u7121\u6cd5\u8b8a\u66f4\u8a72\u8a2d\u5b9a"));CSS.removeClass($('chat_setting_'+name),'chat_setting_loading');},sendSettingChange:function(name,value){CSS.addClass($('chat_setting_'+name),'chat_setting_loading');var data={};data[name]=value;new AsyncRequest().setHandler(this._onSettingChangeResponse.bind(this,name,value)).setErrorHandler(this._onSettingChangeError.bind(this,name)).setTransportErrorHandler(this._onSettingChangeError.bind(this,name)).setData(data).setURI(chatDisplay.settingsURL).send();}};

function ChatOptions(visibility,settings){this.visibility=visibility;this.settings=settings;this._init();}
copy_properties(ChatOptions,{VISIBILITY_CHANGED:'chat/visibility-changed'});ChatOptions.prototype={_init:function(){presence.registerStateStorer(this._storeState.bind(this));presence.registerStateLoader(this._loadState.bind(this));},_storeState:function(presenceState){presenceState.vis=this.visibility;presenceState.bls=this.getSetting('sticky_buddylist');presenceState.blc=this.getSetting('compact_buddylist');presenceState.snd=this.getSetting('sound');return presenceState;},_loadState:function(presenceState){if(presenceState.vis!=this.visibility){this.setVisibility(presenceState.vis);}
this.setSetting('sticky_buddylist',presenceState.bls);this.setSetting('compact_buddylist',presenceState.blc);this.setSetting('sound',presenceState.snd);},setVisibility:function(visibility){if(visibility==this.visibility){return;}
this.visibility=visibility;if(visibility){channelManager.isActionRequest=true;channelManager.rebuild(ChannelRebuildReasons.UIRestart);}else{channelManager.setReady(false);}
Arbiter.inform(ChatOptions.VISIBILITY_CHANGED,{sender:this});},_onVisibilityResponse:function(newVisibility,response){presence.pauseSync();this.setVisibility(newVisibility);if(!presence.inPopoutWindow&&!newVisibility){chatDisplay.unfocus();}
presence.resumeSync();if(presence.poppedOut){presence.popout();}},_onVisibilityError:function(response){var chat=_tx("\u804a\u5929\u5ba4");presence.showAsyncError(response,_tx("\u7121\u6cd5\u8a2d\u5b9a{Chat}\u72c0\u614b",{'Chat':chat}));},toggleVisibility:function(){this.sendVisibility(!this.visibility);},sendVisibility:function(visibility){if(this.visibility==visibility){return;}
this.visibilityAsync=new AsyncRequest().setHandler(this._onVisibilityResponse.bind(this,visibility)).setErrorHandler(this._onVisibilityError.bind(this)).setTransportErrorHandler(this._onVisibilityError.bind(this)).setData({'visibility':visibility}).setURI(chatDisplay.settingsURL).send();},getSetting:function(name){return this.settings[name];},setSetting:function(name,value){if(this.getSetting(name)==value){return;}
if(name=='compact_buddylist'){buddyList.setCompactDisplay(value);}
this.settings[name]=value;}};

function ChatTabSlider(){this.handleWidth=141;this.animationTime=210;this._init();}
ChatTabSlider.prototype={_init:function(){this.org_s=0;this.numToShow=0;this.numShift=1;this.shiftByNumTabs=false;this.timer=null;this.skipAnimation=false;this.chatWidth=null;this.tabPos={};this.chat=ge('chat');this.chatTabBar=ge('chat_tab_bar');this.nextTab=ge('chat_next_tab');this.prevTab=ge('chat_previous_tab');this.nextCounter=ge('next_count');this.prevCounter=ge('prev_count');this.numNext=0;this.numPrev=0;this.prevTabs={};this.nextTabs={};this.numMissedNextCounter=ge('next_num_missed');this.numMissedPrevCounter=ge('prev_num_missed');presence.registerStateLoader(this._load.bind(this));presence.registerStateStorer(this._store.bind(this));Arbiter.subscribe(PresenceMessage.WINDOW_RESIZED,this._resize.bind(this,false));},load:function(){this._load(presence.state);this._resize(true);},_load:function(presenceState){var s=0;if(presenceState){s=(presenceState.s?presenceState.s:s);}
this._setPos(s);},_store:function(presenceState){presenceState.s=this._s;return presenceState;},_calculate:function(onload){this._setMaxWidth();if(onload)this.maxWidth-=16;if(presence.poppedOut){this.numToShow=chatDisplay.numTabs;}else{this.numToShow=parseInt(this.maxWidth/this.handleWidth);this.numToShow=this.numToShow>0?this.numToShow:1;}
if(this.shiftByNumTabs)this.numShift=this.numToShow;if(this._s!=null)this._setPos(this._s);},_setMaxWidth:function(){var w=DOMScroll.getScrollRoot().offsetWidth;if(ChatTabSlider.presenceWidthTest){var w=$('presence_ui').offsetWidth;}
var divs=['buddy_list_tab','presence_notifications_tab','presence_applications_tab','icon_garden','bookmarkable_app'];for(var i=0;i<divs.length;i++){w-=(ge(divs[i])&&$(divs[i]).clientWidth!=undefined)?ge(divs[i]).clientWidth:0;}
this.maxWidth=(presence.poppedOut?w-254:w-138);},_setPos:function(val){if(val<0){val=0;}
this._s=val;this._e=this._s+this.numToShow;},_doSync:function(){var changed=(this.org_s!=this._s);this.org_s=0;if(changed){presence.doSync();}},_build:function(){if(presence.poppedOut){return;}
var all=(this.numToShow>=chatDisplay.numTabs)?true:false;this.setVisibleTabs(all);if(all){this.resetCounters();}else{this.updateCounters();}
this.updateMissedCount();},_resize:function(onload){this.org_s=this._s;this._calculate(onload);this._build();this._doSync();if(chatDisplay.lastFocused!=null){this.gotoTab(chatDisplay.lastFocused);}},addTab:function(id){this._build();},gotoTab:function(id){if(this.tabPos[id]!=0&&!this.tabPos[id])return;var n=parseInt(this.tabPos[id]);if(!this._inRange(n)){var p=(n-this.numToShow)+1;this._setPos(p);this._build();}},close:function(id){if(this.tabPos[id]!=0&&!this.tabPos[id])return;delete this.tabPos[id];this._setPos(((this.numPrev>0||this.numNext>0)&&this._s>0)?this._s-1:0);this._calculate();this._build();},setVisibleTabs:function(all){var c=0;for(var id in chatDisplay.tabs){this.tabPos[id]=c;if(this._inRange(c,id)||all==true){chatDisplay.tabs[id].show();}else{chatDisplay.tabs[id].hide();}
c++;}},_inRange:function(n,id){var s,e=false;if(n>=this._s){s=true;delete this.prevTabs[id];}else{this.prevTabs[id]=id;}
if(n<this._e){e=true;delete this.nextTabs[id];}else{this.nextTabs[id]=id;}
return(s&&e);},updateMissedCount:function(){var prev=0;var next=0;for(var id in this.prevTabs){prev+=chatDisplay.tabs[id]?chatDisplay.tabs[id].numMissed:0;}
this.numMissedPrevCounter.innerHTML=prev;this.numMissedPrevCounter.style.display=prev>0?'block':'none';for(var id in this.nextTabs){next+=chatDisplay.tabs[id]?chatDisplay.tabs[id].numMissed:0;}
this.numMissedNextCounter.innerHTML=next;this.numMissedNextCounter.style.display=next>0?'block':'none';},updateCounters:function(){this.numNext=chatDisplay.numTabs-this._e;this.numPrev=this._s;if(this.numNext<=0){this.numNext=0;CSS.addClass(this.nextTab,'disabled');}else{CSS.removeClass(this.nextTab,'disabled');}
if(this.numPrev<=0){this.numPrev=0;CSS.addClass(this.prevTab,'disabled');}else{CSS.removeClass(this.prevTab,'disabled');}
if(this.numPrev>0||this.numNext>0){show('chat_next_tab');show('chat_previous_tab');}else{hide('chat_next_tab');hide('chat_previous_tab');}
this.nextCounter.innerHTML=this.numNext;this.prevCounter.innerHTML=this.numPrev;},resetCounters:function(){this._setPos(0);this.updateCounters();},shift:function(num){this.org_s=this._s;chatDisplay.unfocusNoSync();this._shift.bind(this,num).defer();},_shift:function(num){this._setPos(this._s<0?0:this._s+num);this._slide(num);if(this.timer||this.skipAnimation){this._slideReset();this.skipAnimation=true;var t=setTimeout(function(){this.skipAnimation=false;}.bind(this),500);}else{this.timer=setTimeout(function(){this._slideReset();}.bind(this),this.animationTime);}},_slide:function(num){this._slideSetup(false);this.setVisibleTabs(true);this.slideInc=(num*(this.handleWidth));this.leftPos=-(num)*(this.numNext*(this.slideInc));this.chatTabBar.style.left=this.leftPos+'px';animation(this.chatTabBar).by('left',this.slideInc).duration(this.animationTime-10).go();},_slideSetup:function(reset){this.chat.style.position=reset?'':'relative';this.chat.style.overflow=reset?'visible':'hidden';if(!this.chatWidth){this.chatWidth=this.chatTabBar.clientWidth;}
if(reset){this.chatWidth=null;}
this.chat.style.width=reset?'':this.chatWidth+'px';this.chatTabBar.style.width=reset?'':chatDisplay.numTabs*this.handleWidth+'px';this.chatTabBar.style.position=reset?'':'absolute';},_slideReset:function(){clearTimeout(this.timer);this.timer=null;this._slideSetup(true);this._build();if(chatDisplay.lastFocused){if(this._inRange(this.tabPos[chatDisplay.lastFocused])){chatDisplay.refocus();}else{chatDisplay.lastFocused=null;}}
this._doSync();},next:function(){if(this.numNext<=0){return;}
this.shift(this.numShift);},prev:function(){if(this.numPrev<=0){return;}
this.shift(-this.numShift);}};

function search_typeaheadpro(obj,source,properties){this.parent.construct(this,obj,source,properties);this._allowDuplicateFoundCalls=(this.enableSearchResults?this.enableSearchResults:false);this._onunload_registered=false;}
search_typeaheadpro.extend('typeaheadpro');search_typeaheadpro.prototype.auto_select=false;search_typeaheadpro.prototype.less_than_n_chars=false;search_typeaheadpro.prototype.dirty_results=function(){this.parent.dirty_results();if(!this._onunload_registered){this._onunload_registered=true;onunloadRegister(bind(this,function(){this.clear();this.blur();search_friend_source.hasSubmitted=false;search_friend_source.already_logged=false;this._onunload_registered=false;}));}}
search_typeaheadpro.prototype.show=function(){this.dropdown.style.border='0px none';if(this.suggestions.length){CSS.addClass(this.list,'typeahead_list_with_shadow');}else{CSS.removeClass(this.list,'typeahead_list_with_shadow');}
var typeahead_width=this.is_fbx?207:191;if(!this.less_than_n_chars){CSS.addClass(this.dropdown,'typeahead_search');this.parent.show();var anchor_dimensions=Vector2.getElementDimensions(this.anchor);this.dropdown.style.left=(elementX(this.anchor)-(typeahead_width-anchor_dimensions.x)+4)+'px';this.dropdown.style.width=typeahead_width+'px';}else{this.hide();}}
search_typeaheadpro.prototype.select_suggestion=function(index){this.log_data.sm=this.log_data.sm?this.log_data.sm:'mouse';if(this.suggestions&&this.suggestions.length>index){this.log_data.ty=index>=0?this.suggestions[index].ty:'fs';this.log_data.i=index>=0?this.suggestions[index].i:'0';this.log_data.f=this.suggestions.length>0?0:1;}
this.log_data.si=index;search_typeahead_log_data(this);if(this.suggestions&&this.source.history!=undefined&&this.suggestions.length>index&&index>=0){this.suggestions[index].o=-1;this.source.history[this.suggestions[index].i]=-1;}
return this.parent.select_suggestion.call(this,index);}
search_typeaheadpro.prototype.hide=function(){this.parent.hide();}
search_typeaheadpro.prototype.search_cache=function(text){return undefined;}
search_typeaheadpro.prototype.found_suggestions=function(suggestions,text,fake_data){var auto_select=ADVANCED_SEARCH_TYPEAHEAD&&suggestions&&suggestions.length==1;if(auto_select){suggestions.push({t:text,i:text.trim().replace(/ /g,'+'),ty:'search'});}
this.parent.found_suggestions(suggestions,text,fake_data);if(suggestions.length>0&&suggestions[0].ty=='search'){this.parent.set_suggestion(0);}
if(this.suggestion_count>0){CSS.addClass(this.list.firstChild.firstChild,'suggestions_top_border');CSS.removeClass(this.list,'no_border_list');CSS.addClass(this.list.lastChild.lastChild,'suggestions_bottom_border');}else{CSS.addClass(this.list,'no_border_list');}
if(this.enableSearchResults){if(this.loadingResults&&this.suggestion_count<this.max_results){if(this.list.innerHTML.indexOf('typeahead_search_loading')==-1){this.list.innerHTML+='<div class="typeahead_search_loading">'+
_tx("\u6b63\u5728\u641c\u5c0bFacebook\u2026\u2026")+'</div>';}
CSS.addClass(this.dropdown,'typeahead_search_loading');this.showingLoadingIndicator=true;}else{CSS.removeClass(this.dropdown,'typeahead_search_loading');this.showingLoadingIndicator=false;}}
if(auto_select){this.set_suggestion(0);}}
search_typeaheadpro.prototype._onkeydown=function(e){this.last_key=e?event_get_keypress_keycode(e):-1;this.interactive=true;if(this.last_key==KEYS.TAB&&this.suggestions.length>0){var next_tab_index=this.selectedindex+(e.shiftKey?-1:1);if(next_tab_index<-1||next_tab_index>=this.suggestions.length){return true;}
this.log_data.kt+=1;return false;}
this.parent._onkeydown(e);}
search_typeaheadpro.prototype._onkeypress=function(e){this.last_key=e?event_get_keypress_keycode(e):-1;this.interactive=true;if(this.last_key==KEYS.TAB&&this.suggestions.length>0){var next_tab_index=this.selectedindex+(e.shiftKey?-1:1);if(next_tab_index>=-1&&next_tab_index<this.suggestions.length){this.set_suggestion(next_tab_index);this.last_key_suggestion=(new Date()).getTime();return false;}}
return this.parent._onkeypress(e);}
function search_typeahead_onselect(friend){if(friend&&!search_friend_source.hasSubmitted){search_friend_source.hasSubmitted=true;}else{return false;}
var url=friend.u;if(!url){var type_info=search_friend_source.url_templates[friend.ty];if(type_info){var id;if(friend.a&&type_info.alias_url){url=type_info.alias_url;id=friend.a;}else{url=type_info.default_url;id=friend.i;}
url=sprintf(url,escapeURI(id));}}
if(!url){return undefined;}else if(url.indexOf('?')!=-1){goURI(url+'&ref=ts');}else{goURI(url+'?ref=ts');}
bind(this,this.blur).defer();return false;};function search_typeahead_wstest(query){new AsyncSignal('/ajax/search/web.php',{q:query}).send();};function search_typeahead_log_data(source){var log_data=source.udata;for(var key in source.log_data){log_data[key]=source.log_data[key];}
search_typeahead_log(log_data,'onsubmit');}
function search_typeahead_onsubmit(friend){return!search_friend_source.hasSubmitted;}
window.ADVANCED_SEARCH_TYPEAHEAD=false;

function ChatNotifications(count,countNew,updateTime,app_names,latest_notif,latest_read_notif){this.count=count;this.countNew=countNew;this.updateTime=updateTime;this.user=presence.user;this.app_names=app_names;this.merged_alert_ids={};this.merged_mouseover_handler=null;this.latest_notif_time=latest_notif;this.latest_read_notif_time=latest_read_notif;this.wrapperID='presence_notifications';this.contentID='presence_notifications_content';this.navInboxID='nav_inbox';this.itemTag='div';this.itemNewClass='notif_unread';this.timeElement='span.time';this._init();}
copy_properties(ChatNotifications,{showReportDialog:function(applicationName,hideHandler,reportHandler,cancelHandler){if(!Dialog){var handler=this.showReportDialog.bind(this,applicationName,hideHandler,reportHandler,cancelHandler);Bootloader.loadComponent('dialog',handler);return;}
var hide_button={name:'hide',label:_tx("\u96b1\u85cf\u5168\u90e8"),handler:hideHandler};var report_button={name:'report',label:_tx("\u8209\u5831\u5783\u573e\u90f5\u4ef6"),handler:reportHandler};var cancel_button={};copy_properties(cancel_button,Dialog.CANCEL);cancel_button.handler=cancelHandler||bagofholding;new Dialog().setTitle(_tx("\u60a8\u60f3\u4e0d\u60f3\u96b1\u85cf\u4f86\u81ea{application-name}\u7684\u6240\u6709\u901a\u77e5?",{'application-name':applicationName})).setBody(_tx("\u9019\u6703\u96b1\u85cf\u6240\u6709\u4f86\u81ea\u6b64\u61c9\u7528\u7a0b\u5f0f\u7684\u901a\u77e5\u3002")).setButtons([hide_button,report_button,cancel_button]).setModal().show();},markAppNotificationSpam:function(applicationId,platformType,isSpamReport){var params={app_id:applicationId,collapse:1,type:platformType};if(isSpamReport){params.spam=1;}
new AsyncSignal('/ajax/notifications.php',params).send();},UPDATER_NAME:'notifications'});copy_properties(ChatNotifications.prototype,{_init:function(){this.cookieName='notifications_'+this.user;this.markReadAsync=null;this.markupCached=null;this.beepsExpiredToken=null;this.appHideCache=[];this.updateCheckCount=0;this.wrapper=ge(this.wrapperID);this.content=ge(this.contentID);this.navInbox=ge(this.navInboxID);this.countSpan=ge('presence_notifications_count');this._updateCount();Arbiter.subscribe(PresenceMessage.getArbiterMessageType('notification'),this._handleNotificationMsg.bind(this));Arbiter.subscribe(PresenceMessage.getArbiterMessageType('notifications_read'),this._handleNotificationsReadMsg.bind(this));presenceUpdater.register(ChatNotifications.UPDATER_NAME,this._checkUpdater.bind(this),this._onUpdaterResponse.bind(this),this._onUpdaterError.bind(this),this._onUpdaterError.bind(this));},notifyRead:function(alertsRead){var data=null;if(alertsRead){data={alert_ids:alertsRead};}
AsyncRequest.pingURI('/ajax/presence/notifications_read.php',data);},markRead:function(skipAsyncRequest,alertsRead,numUnread){if(this.countNew==0){return;}
this.countNew=numUnread?numUnread:0;this._updateCount();if(!skipAsyncRequest){this.notifyRead(alertsRead);}
var unreads=[];if(alertsRead){for(var i=0;i<alertsRead.length;i++){var element_id=this.itemTag+'#notification_'+alertsRead[i]+'.'
+this.itemNewClass;var match=DOM.scry(this.content,element_id);if(match.length==1){unreads.push(match[0]);}}}else{unreads=DOM.scry(this.content,this.itemTag+'.'+this.itemNewClass);}
for(var i=0;i<unreads.length;i++){animation(unreads[i]).duration(1250).checkpoint().to('backgroundColor','#FFFFFF').duration(2250).ondone(CSS.removeClass.bind(null,unreads[i],this.itemNewClass)).go();}},requiresUpdate:function(time,asyncData,forceUpdate){if(!buddyList._checkUpdater(time,{},forceUpdate)){return false;}
if(asyncData&&undefined!=asyncData[ChatNotifications.UPDATER_NAME]){return asyncData[ChatNotifications.UPDATER_NAME];}
return forceUpdate||((100/(this.updateCheckCount+1))<=presence.sitevars.NOTIFICATIONS_PIGGYBACK_PERCENTAGE);},_checkUpdater:function(time,asyncData,forceUpdate){if(!buddyList._checkUpdater(time,{},forceUpdate)){return false;}
if(this.requiresUpdate(time,{},forceUpdate)){this.updateCheckCount=0;asyncData['notif_latest']=this.latest_notif_time;asyncData['notif_latest_read']=this.latest_read_notif_time;asyncData[ChatNotifications.UPDATER_NAME]=1;return true;}else{this.updateCheckCount++;asyncData[ChatNotifications.UPDATER_NAME]=0;}
return false;},_updateInboxMarkup:function(inboxCount,inboxDropdownMarkup){if(this.navInbox&&inboxCount!=null){CounterDisplay.setCount('messages_unread',inboxCount);}
var inboxDropdownElement=ge('fb_menu_inbox_dropdown');if(inboxDropdownElement&&inboxDropdownMarkup){inboxDropdownElement.setContent(HTML(inboxDropdownMarkup));}},_onUpdaterResponse:function(notificationResponse,time){this._updateInboxMarkup(notificationResponse.inboxCount,notificationResponse.inboxDropdownMarkup);if(!notificationResponse.no_change){if(this.count!=notificationResponse.count){this.count=notificationResponse.count;presence.contentChanged(this.contentID);}
this.countNew=notificationResponse.countNew;this.updateTime=time;this.latest_notif_time=notificationResponse.latest_notif;this.latest_read_notif_time=notificationResponse.latest_read_notif;this._addAppNames(notificationResponse.app_names);var multiple_updates=(null!=this.markupCached);this.markupCached=notificationResponse.markup;if(presence.focusedTab=='presence_notifications_tab'){multiple_updates||presence.registerTempTabCloseHandler(this._updateDisplayDelayed.bind(this));}else{this._updateDisplayDelayed();}
Arbiter.inform(Arbiter.NEW_NOTIFICATIONS,notificationResponse);}},_updateDisplayDelayed:function(){if(typeof Beeper!='undefined'){this.beepsExpiredToken=Arbiter.subscribe(Arbiter.BEEPS_EXPIRED,this._updateDisplay.bind(this));}else{this._updateDisplay();}},_updateDisplay:function(){if(!this.content||!this.markupCached){return;}
set_inner_html(this.content,this.markupCached);for(var i=0;i<this.appHideCache.length;i++){this.hideNotifications(this.appHideCache[i],true);}
this.markupCached=null;this.appHideCache=[];this._updateCount();if(this.beepsExpiredToken){Arbiter.unsubscribe(this.beepsExpiredToken);}},_onUpdaterError:function(response){},_updateCount:function(){if(this.countSpan){this.countSpan.innerHTML=this.countNew?'<strong>'+this.countNew+'</strong>':'';}},hideNotifications:function(app_id,cached){var element_type=this.itemTag+'.notif_';var notifs=DOM.scry(this.content,element_type+app_id);for(var i=0;i<notifs.length;i++){if(cached){hide(notifs[i]);}else{animation(notifs[i]).to('opacity',0).to('height',0).blind().duration(1000).hide().go();}}
this.count-=notifs.length;presence.contentChanged(this.contentID);if(this.count<=0){var nothing_new=ge('presence_no_notifications');nothing_new&&show(nothing_new);}
cached||this.appHideCache.push(app_id);},showHideDialog:function(clickedElement,app_id,platform_type){var hide_handler=function(button_name){this.hideNotifications(app_id);var is_spam_report=('report'==button_name);ChatNotifications.markAppNotificationSpam(app_id,platform_type,is_spam_report);(typeof(toggleType)=='function')&&(typeof(hidden)!='undefined')&&(!hidden[app_id])&&toggleType(app_id,true,null,false,true,presence.user,false,platform_type);};var hide_handler=bind(this,hide_handler,'hide');var report_handler=bind(this,hide_handler,'report');var app_name=this.app_names[app_id];ChatNotifications.showReportDialog(app_name,hide_handler,report_handler);return false;},_addAppNames:function(appNames){appNames&&copy_properties(this.app_names,appNames);},_insertNotification:function(notificationMarkup){DOM.prependContent(this.content,HTML(notificationMarkup));},_mergeNotification:function(notificationId,notificationMarkup,notificationUnread,appNames){this._insertNotification(notificationMarkup);this.count++;if(notificationUnread){this.countNew++;}
this._updateCount();appNames&&this._addAppNames(appNames);if(presence.focusedTab=='presence_notifications_tab'){if(is_empty(this.merged_alert_ids)){this.merged_mouseover_handler=this.content.listen('mouseover',this._markMergedRead.bind(this));}
this.merged_alert_ids[notificationId]=notificationUnread;presence.tabContentResize(this.wrapperID,this.contentID);}
(function(){var notif_element=ge('notification_'+notificationId);if(notif_element){var timestamp=DOM.find(notif_element,this.timeElement);DOM.setContent(timestamp,_tx("10 \u5206\u9418\u5167"));}}).defer(1000*300);},_markMergedRead:function(){this.merged_mouseover_handler.remove();if(!this.merged_alert_ids){return;}
var unread_ids=[];for(var alert_id in this.merged_alert_ids){if(this.merged_alert_ids){unread_ids.push(alert_id);}}
this.merged_alert_ids={};this.markRead(false,unread_ids);},_handleNotificationMsg:function(type,data){var obj=data.obj;if(obj.markup){this._mergeNotification(obj.alert_id,obj.markup,obj.unread,obj.app_names);}else{presenceUpdater.runHandler('notifications');}},_handleNotificationsReadMsg:function(type,data){var obj=data.obj;if(typeof Beeper!='undefined'){Beeper.getInstance().markRead(true,obj.alert_ids);}
this.markRead(true,obj.alert_ids,obj.num_unread);}});

function UserHistory(userid){var current_time=(new Date()).getTime();new AsyncRequest().setMethod('GET').setReadOnly(true).setURI('/ajax/browse_history.php').setData({'u':userid}).setErrorHandler(function(){}).setTransportErrorHandler(function(){}).setHandler(function(response){var dt=(new Date()).getTime()-current_time;userhistory_log_response({'dt':dt});this.entries=response.getPayload().entries;}.bind(this)).send();}
function userhistory_log_response(data){data['evt']='uh';new AsyncSignal('/ajax/typeahead_log.php',data).send();}

if (window.Bootloader) { Bootloader.done(["js\/9yfwom953xssgkcg.pkg.js"]); }