/*    HTTP Host:  b.static.ak.fbcdn.net                                        */
/*    Generated:  March 25th 2009 6:05:45 PM PDT                               */
/*      Machine:  10.16.140.101                                                */
/*       Source:  Global Cache                                                 */
/*     Location:  js/2248229svs74swwo.pkg.js h:1evrr12q                        */
/*       Locale:  en_US                                                        */
/*         Path:  js/2248229svs74swwo.pkg.js                                   */


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=Presence.getArbiterMessageType(this.appId,this.eventName);this.subs={};this.subs['main']=Arbiter.subscribe(type,wrapper);if(this.shutdownHandler){this.subs['shut']=Arbiter.subscribe(Presence.ARBITER_SHUTDOWN,this.shutdownHandler);}
if(this.restartHandler){this.subs['restart']=Arbiter.subscribe(Presence.ARBITER_RESTART,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=Presence.getArbiterMessageType(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 CookieManager(version){this.version=version;this.cookieName='presence';this._init();}
CookieManager.prototype={_init:function(){this.storers={};},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);setCookie(this.cookieName,serialized,null);},_getCookie:function(){try{var data=getCookie(this.cookieName);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){this.user=user;this.iframeCheckTime=16000;this.iframeCheckRetryTime=16000;this.iframeLoadMaxRetries=1;this.retryInterval=retryInterval;this.channelConfig=channelConfig;this._init(noSubdomain);}
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 statusControl!='undefined'){statusControl.setVisibility(rebuildInfo.visibility);}
for(var c in this.channels){this.channels[c].restartHandler(true);}
presenceUpdater.resumeUpdate(['buddy_list']);},_retryRebuild:function(reason){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.checkLoginError(response)||presence.checkMaintenanceError(response)){presence.warn('manager not trying again');}else{this._retryRebuild(ChannelRebuildReasons.PrevFailed);}},_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);},_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 Presence(user,name,firstName,serverTime,inPopoutWindow,sitevars,popoutURL){this.user=user;this.name=name;this.firstName=firstName;this.sitevars=sitevars;this.popoutURL=popoutURL;var viewportDimensions=Vector2.getViewportDimensions();this.maxTabOffset=66;if(ge('intern_bookmark_frame')){this.maxTabOffset+=25;}
this.maxTabHeight=viewportDimensions.y-this.maxTabOffset;this.updateServerTime(serverTime);this.pageLoadTime=this.getTime();this._init(inPopoutWindow);}
copy_properties(Presence,{ARBITER_SHUTDOWN:'presence/shutdown',ARBITER_RESTART:'presence/restart',getArbiterMessageType:function(appid,event_name){return'presence/message:'+appid+':'+event_name;}});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,_init:function(inPopoutWindow){this.resizeHandlers=[];this.stateStorers=[];this.stateLoaders=[];this.msgHandlers=[];this.shutdownHandlers=[];this.restartHandlers=[];this.startHandlers=[];this.tabCloseHandlers=[];this.tabOpenHandlers=[];this.windowID=rand32()+1;this.contentPaddings={'buddy_list':54,'presence_notifications':23,'presence_applications':43};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.disableTabAutoClose=0;this.syncPaused=0;this.disableUnfocus=null;this.tempTabCloseHandler=null;this.inPopoutWindow=inPopoutWindow;this.poppedOut=this.inPopoutWindow;presenceCookieManager.register('state',this._getCookieData.bind(this));if(this.inPopoutWindow){Util.fallbackErrorHandler=null;this.bar.style.marginRight='200px';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(window,'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);},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.heartbeat=setInterval(this._popoutHeartbeat.bind(this),this.popoutHeartbeatTime);}}else{CSS.addClass(this.holder,'popped_out');}}else{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=='app_msg'){LiveMessageReceiver.route(obj);}
var handled=false;for(var i=0;i<this.msgHandlers.length;i++){handled=this.msgHandlers[i](channel,obj);if(handled){break;}}},popout:function(){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(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.openingABTestHalfHeight()||(buddyList.openingABTestHeightAdjust()&&!buddyList.isWideViewport()))){this.maxTabHeight*=0.5;}
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){this.virtPopoutWidth+=dx;this.virtPopoutHeight+=dy;this.popoutWidth=Math.max(this.virtPopoutWidth,this.minWidth);this.popoutHeight=Math.max(this.virtPopoutHeight,this.minHeight);for(var i=0;i<this.resizeHandlers.length;i++){this.resizeHandlers[i]();}},_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(){if(this.disableTabAutoClose){return;}
if((typeof buddyList!='undefined')&&buddyList.buddyListOpen){if(!buddyList.isSticky()){buddyList.closeTab();}}else{this.closeTab();}},allowAutoClose:function(){if(this.disableTabAutoClose>0){this.disableTabAutoClose--;}},disallowAutoClose:function(){this.disableTabAutoClose++;},tabHandleMouseOver:function(tab){this.disallowAutoClose();CSS.addClass(tab,'hover');},tabHandleMouseOut:function(tab){this.allowAutoClose();CSS.removeClass(tab,'hover');},tabContentMouseOver:function(){this.disallowAutoClose();},tabContentMouseOut:function(){this.allowAutoClose();},_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');for(var i=0;i<this.tabCloseHandlers.length;i++){this.tabCloseHandlers[i]();}
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');for(var i=0;i<this.tabOpenHandlers.length;i++){this.tabOpenHandlers[i]();}},contentChanged:function(contentID){delete this.contentResized[contentID];},tabContentResize:function(wrapperID,contentID,forceLockHeight){if(this.poppedOut){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?' 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("An error occurred.");}
if(error==kError_Async_NotLoggedIn){desc=_tx("Your session has timed out. Please login.");}
return desc;},showAsyncError:function(asyncResponse,title){if(typeof title=='undefined'||!title){var chat=_tx("Chat");title=_tx("Facebook Chat Error");}
var desc=this.getErrorDescription(asyncResponse);new ErrorDialog().showError(title,desc);},showTransportError:function(asyncResponse,title){if(typeof title=='undefined'||!title){var chat=_tx("Chat");title=_tx("Facebook Chat Error");}
var desc=_tx("Could not connect to Facebook {Chat} at this time.",{'Chat':_tx("Chat")});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 login.");this.shutdown(false,reason);},connectionShutdown:function(shouldDelay){var reason=_tx("Could not connect to Facebook {Chat} at this time.",{'Chat':_tx("Chat")});this.shutdown(shouldDelay,reason);},maintenanceShutdown:function(){var reason=_tx("Facebook {Chat} is down for maintenance at this time.",{'Chat':_tx("Chat")});this.shutdown(false,reason);channelManager.stop();},versionShutdown:function(){var reason=_tx("Please refresh the page to get the latest version of Facebook {Chat}.",{'Chat':_tx("Chat")});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} is experiencing technical problems.",{'Chat':_tx("Chat")});}
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 Chat Error")).setBody(reason).show();}
if(this.isShutdown){return;}
this.warn("presence: shutting down");this.isShutdown=true;Arbiter.inform(Presence.ARBITER_SHUTDOWN,{sender:this});for(var i=0;i<this.shutdownHandlers.length;i++){this.shutdownHandlers[i]();}},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(Presence.ARBITER_RESTART,{sender:this});for(var i=0;i<this.restartHandlers.length;i++){this.restartHandlers[i]();}
if(!this.inPopoutWindow){CSS.removeClass(this.holder,'presence_error');}else{if(this.shutdownErrorDialog){this.shutdownErrorDialog.hide();}}},start:function(){for(var i=0;i<this.startHandlers.length;i++){this.startHandlers[i]();}},registerResizeHandler:function(fn){this.resizeHandlers.push(fn);},registerStateStorer:function(fn){this.stateStorers.push(fn);},registerStateLoader:function(fn){this.stateLoaders.push(fn);},registerMsgHandler:function(fn){this.msgHandlers.push(fn);},registerShutdownHandler:function(fn){this.shutdownHandlers.push(fn);},registerRestartHandler:function(fn){this.restartHandlers.push(fn);},registerStartHandler:function(fn){this.startHandlers.push(fn);},registerTabOpenHandler:function(fn){this.tabOpenHandlers.push(fn);},registerTabCloseHandler:function(fn){this.tabCloseHandlers.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 verifyNumber(num){if(typeof num=='undefined'||isNaN(num)||num==Number.POSITIVE_INFINITY||num==Number.NEGATIVE_INFINITY){num=0;}
return num;}

function Sound(){}
copy_properties(Sound,{play:function(path){uri=URI(path);if(!uri.getDomain()){path=URI(env_get('static_base')).setPath(uri.getPath()).toString();}
var player;var embed;if(/\.mp3$/.test(path)){player=document['so_sound_player']||window['so_sound_player'];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 ChatTab(chatDisplay,id,name,firstName,numMissed,missedTime){this.chatDisplay=chatDisplay;this.id=id;this.name=name;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.statusTextProcessor=this._processStatusText.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);}
ChatTab.prototype={pendingToLogCompareWindow:60000,sendingCheckDelay:55000,sendingDisplayDelay:4000,convWrapLimit:30,statusWrapLimit:22,handleWidth:136,popinWidth:226,popinHeight:250,popoutWidthOffset:182,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(this.chatDisplay.histories[this.id]){this._setHistory(this.chatDisplay.histories[this.id]);}
if(this.chatDisplay.userInfos[this.id]){this.updateUserInfo();}else{this.chatDisplay.loadInitialUserInfo(this.id,this.name,this.firstName);}},_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;this.chatDisplay.userInfos[this.id]=userInfo;buddyList.updateItemDisplay(this.id);this.updateUserInfo();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;for(var i=0;i<logItems.length;i++){var logItem=logItems[i];if(logItem.type!='msg'&&logItem.type!='mf'&&logItem.type!='online'){continue;}
for(;sentIndex<sentMsgs.length;sentIndex++){var sentMsg=sentMsgs[sentIndex];if(sentMsg.time>prevItemTime&&sentMsg.time<=logItem.time){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=='mf'&&statusControl.getSetting('minifeed')){markup+=this._renderMinifeed(logItem.from,logItem.time,logItem.markup);}else if(logItem.type=='online'){markup+=this._renderVisibilityChange(logItem.time,logItem.text);}
this.lastLogItem=logItem;prevItemTime=logItem.time;}
for(;sentIndex<sentMsgs.length;sentIndex++){var sentMsg=sentMsgs[sentIndex];markup+=this._renderMsg(presence.user,this.id,sentMsg.time,sentMsg,sentMsg.msgID,sentMsg.isError,sentMsg.infoMarkup);this.lastLogItem={'type':'msg','from':presence.user,'to':this.id,'time':sentMsg.time,'msg':sentMsg};}
hide(this.chatHistoryError);this.chatConvContent.innerHTML=markup;this.scrollToBottom();this.historyLoaded=true;},_onClearHistoryError:function(response){var chat=_tx("Chat");presence.showAsyncError(response,_tx("Couldn't clear {Chat} history",{'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(item.type!='msg'){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=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("send as a message"),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;statusControl.setVisibility(false);presence.doSync();}
else if(error==kError_Chat_TooManyMessages){desc=payload.error.title;new ErrorDialog().showError(payload.error.title,payload.error.body);}
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);},sendInput:function(){var text=this.chatInput.value;if(!text||!text.match(/[^\s]/)){return;}
this.chatInput.value='';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,time:time,asyncSuccess:false,isError:false,errorMarkup:''};this.pendingSentMsgs.push(pendingMsg);if(this.pendingSentMsgs.length==1){this._sendMessage(pendingMsg,!channelManager.iframeEverLoaded);}
var msg={'text':text};var sendMarkup=this._renderMsg(presence.user,this.id,time,msg,msgID);this._addConvMarkup(sendMarkup);this.lastLogItem={'type':'msg','from':presence.user,'to':this.id,'time':time,'msg':msg};this.chatDisplay.chatActivityTime=(new Date()).getTime();presence.doSync();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_text:pendingMsg.text,msg_id:msgID,client_time:pendingMsg.time,to:this.id,popped_out:presence.poppedOut,num_tabs:this.chatDisplay.numTabs,pvs_time:lastConvoTime};if(buddyList.openingABTestIsActive()){sendData.wide_viewport=buddyList.isWideViewport();}
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('/ajax/chat/send.php').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("Could not connect to Facebook {Chat} at this time.",{'Chat':_tx("Chat")}));}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("Sending:")+'</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(){var userInfo=this.chatDisplay.userInfos[this.id];this.chatInfoPic.src=userInfo.thumbSrc;var statusMarkup='&nbsp;';var dateMarkup='&nbsp;';var status;if(status=userInfo.status){var time=userInfo.statusTimeRel;statusMarkup=html_hyperlink(status,this.statusTextProcessor,this.statusTextProcessor);dateMarkup=time;}
if(ua.ie()<7){dateMarkup+='<br />&nbsp;<br />&nbsp;';}
this.chatInfoStatusTime.innerHTML=dateMarkup;this.chatInfoStatus.innerHTML=statusMarkup;CSS.removeClass(this.chatInfo,'hidden');},updateStatus:function(status,time,timeRel){var userInfo=this.chatDisplay.userInfos[this.id];userInfo.status=status;userInfo.statusTime=time;userInfo.statusTimeRel=timeRel;this.chatDisplay.userInfos[this.id]=userInfo;buddyList.updateItemDisplay(this.id);this.updateUserInfo();},tabHitAreaOnClick:function(){if(this.suppressHeaderCollapse){return;}
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();},tabXOnClick:function(e){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='this_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 chatInfoLinkID='chat_info_link_'+this.id;var chatInfoPicID='chat_info_pic_'+this.id;var chatInfoStatusID='chat_info_status_'+this.id;var chatInfoStatusTimeID='chat_info_status_time_'+this.id;var chatConvContentID='chat_conv_content_'+this.id;var chatInputID='chat_input_'+this.id;var chatShadowInputID='chat_shadow_input_'+this.id;var chat=_tx("Chat");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("Show\/Hide {Chat} Window",{'Chat':chat}),'" ','class="tab_hit_area" ','onclick="',this.tabRef,'.tabHitAreaOnClick()">','<div class="tab_name">',handleName,'</div>','</div>','<div class="tab_count" id="',tabCountID,'"></div>','<div title="',_tx("Close {Chat} Window",{'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("Close {Chat} Window",{'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("Hide {Chat} Window",{'Chat':chat}),'" ','class="minimize">','</a>','</div>',chatHeaderPicLink,'<div class="chat_header_name">',chatHeaderNameLink,'</div>','</div>','<div class="chat_info" id="',chatInfoID,'">','<span class="chat_info_status" id="',chatInfoStatusID,'"></span><wbr />','<span class="chat_info_status_time" id="',chatInfoStatusTimeID,'"></span>','</div>','<div class="chat_conv" id="',chatConvID,'" ','onmousedown="',this.tabRef,'.chatConvOnMouseDown(event)" ','onmouseup="',this.tabRef,'.chatConvOnMouseUp()">','<div class="chat_info_clear_history">','<span onclick="',this.tabRef,'.clearHistory();">',_tx("Clear {Chat} History",{'Chat':chat}),'</span>','</div>','<div class="chat_notice" id="',chatHistoryErrorID,'" style="display:none">',_tx("Couldn't retrieve chat history"),'</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>','</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&&!buddyList.openingABTestFlipped()){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.chatInfoLink=ge(chatInfoLinkID);this.chatInfoPic=ge(chatInfoPicID);this.chatInfoStatus=ge(chatInfoStatusID);this.chatInfoStatusTime=ge(chatInfoStatusTimeID);this.chatConvContent=ge(chatConvContentID);this.chatInput=ge(chatInputID);this.chatShadowInput=ge(chatShadowInputID);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=statusControl.visibility;if(statusControl.visibility){this._enableTab(true,false,justCameOnline,onload);}else{this._disableTab(true,justCameOnline,onload);}
this.handleBuddyAvailability(!onload&&justCameOnline,onload);},handleBuddyAvailability:function(justCameOnline,onload){if(!statusControl.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;if(presence.inPopoutWindow){var popoutWidth=(presence.popoutWidth>330)?presence.popoutWidth:330;newConvWidth=popoutWidth-this.popoutWidthOffset;newTextWidth=popoutWidth-this.popoutWidthOffset-28;newNotAvailWidth=popoutWidth-this.popoutWidthOffset-16;newTabHeight=presence.popoutHeight-82;}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;}}
this.chatHeader.style.width=newConvWidth+'px';this.chatInfo.style.width=(newConvWidth-55)+'px';this.chatInput.style.height=textHeight+'px';this.chatConv.style.width=newConvWidth+'px';this.chatConv.style.height=(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.focusChatInput();this.handleResize();if(ua.ie()<7&&presence.inPopoutWindow){this.chatWrapper.style.top='72px';}},_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_tab_count_'+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("You are online.",{'name':this.firstName});}else{text=_tx("You are not online.",{'name':this.firstName});}}else{if(online){text=_tx("{name} is online.",{'name':this.firstName});}else{text=_tx("{name} is offline.",{'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;},newMinifeed:function(mfItem){if(mfItem.status){this.updateStatus(mfItem.status,mfItem.time,mfItem.statusTimeRel);}
if(this.lastLogItem&&this.lastLogItem.type=='mf'){return;}
var history=this.chatDisplay.getHistory(this.id,true);history.push(mfItem);var markup=this._renderMinifeed(mfItem.from,mfItem.time,mfItem.markup);this._addConvMarkup(markup);this.lastLogItem=mfItem;},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);}},newMsg:function(msgItem){var from=msgItem.from;var to=msgItem.to;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(history[i].type=='msg'){lastMsg=history[i];break;}}
if(lastMsg&&time<=lastMsg.time){var found=false;for(var i=0;i<history.length;i++){if(history[i].type=='msg'&&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(historyItem.type=='msg'&&(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&&statusControl.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;}}}
if(shouldRender){var msgMarkup=this._renderMsg(from,to,time,msg);this._addConvMarkup(msgMarkup);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;},_renderMinifeed:function(from,time,storyMarkup){var markup=this._renderDateBreak(time);markup+='<div class="minifeed">'+
storyMarkup+'</div>';return markup;},_renderMsg:function(from,to,time,msg,pendingMsgID,isError,errorMarkup){if(!CSS.hasClass(this.tabHandle,'history_loaded')){CSS.addClass(this.tabHandle,'history_loaded');}
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 pic=this.chatDisplay.userInfos[from]&&presence.inPopoutWindow?'<img src="'+this.chatDisplay.userInfos[from].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){var textProcessor=statusControl.showEmoticons?this.convTextEmoteProcessor:this.convTextProcessor;return html_hyperlink(msg.text,textProcessor,this.convTextProcessor,true);},_processConvText:function(str){return html_wordwrap(str,this.convWrapLimit);},_processConvTextEmote:function(str){return Emote.htmlEmote(str,this.convTextProcessor);},_processStatusText:function(str){return html_wordwrap(str,this.statusWrapLimit);}};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("Today");}else if(diff<dayMilliseconds){return _tx("Yesterday");}}
var month='';switch(date.getMonth()){case 0:month=_tx("January");break;case 1:month=_tx("February");break;case 2:month=_tx("March");break;case 3:month=_tx("April");break;case 4:month=_tx("May");break;case 5:month=_tx("June");break;case 6:month=_tx("July");break;case 7:month=_tx("August");break;case 8:month=_tx("September");break;case 9:month=_tx("October");break;case 10:month=_tx("November");break;case 11:month=_tx("December");break;}
return _tx("{month} {date}",{'month':month,'date':date.getDate()});}

function ChatDisplay(userInfos,histories,everSentMessage,activeChats,focusedChat,profileURL,messageURL,gatedFeatures){this.userInfos=userInfos;this.histories=histories;this.everSentMessage=everSentMessage;this.user=presence.user;this.profileURL=profileURL;this.messageURL=messageURL;this.settingsURL='/ajax/chat/settings.php';this.gatedFeatures=gatedFeatures;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;this.favIcon=null;this.altFavIcon=null;this._loadInitialTabs.bind(this,activeChats,focusedChat).defer();presence.registerResizeHandler(this.handleResize.bind(this));presence.registerStateStorer(this._store.bind(this));presence.registerStateLoader(this._load.bind(this));presence.registerMsgHandler(this._handleMsg.bind(this));presence.registerStartHandler(this.start.bind(this));presence.registerShutdownHandler(this.shutdown.bind(this));presence.registerRestartHandler(this.restart.bind(this));statusControl.registerVisibilityHandler(this.handleVisibility.bind(this));buddyList.registerAvailabilityHandler(this.handleBuddyAvailability.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(this.userInfos[id]){return;}
this.userInfos[id]={'name':name,'firstName':firstName,'thumbSrc':'','status':'','statusTime':'','statusTimeRel':''};},_loadInitialTabs:function(activeChats,focusedChat){var firstTab=null;for(var id in activeChats){if(!firstTab){firstTab=id;}
var tabInfo=this.userInfos[id];var numMissed=activeChats[id].m||0;var missedTime=activeChats[id].t||0;this.tabs[id]=new ChatTab(this,id,tabInfo.name,tabInfo.firstName,numMissed,missedTime);this.numTabs++;}
if(presence.inPopoutWindow&&!focusedChat){focusedChat=firstTab;}
if(focusedChat){this._focusTab(focusedChat);}},load:function(){this._load(presence.state);},_load:function(presenceState){if(presenceState){var useNumMissed=false;var now=presence.getTime();if(now-presenceState.ut<60*60*1000){useNumMissed=true;}
this.isSoundWindow=channelManager.isLowestSubdomain();if(this.blinkingTimer&&presenceState.sb){this._stopBlinking();}
this.chatActivityTime=verifyNumber(presenceState.ct)*1000;}
this.loaded=true;},_store:function(presenceState){presenceState.ct=parseInt(this.chatActivityTime*0.001);presenceState.sb=(this.blinkingTimer==null)?1:0;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);},closeTab:function(id){this._closeTab(id);this._sendTabStateChange({'close_chat':id});},_unfocus:function(){if(!this.focused){return false;}
if(presence.poppedOut)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.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){return;}
if(!this.tabs[id]){if(typeof name=='undefined'){if(!this.userInfos[id]||!this.userInfos[id].name){presence.warn("chat: couldn't create tab "+id+" since no name is specified");return;}
name=this.userInfos[id].name;firstName=this.userInfos[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.poppedOut)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.poppedOut){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.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("New message from {name}!",{'name':name});}else{document.title=_tx("New message!");}
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;}},handleBuddyAvailability:function(justCameOnline){for(var id in this.tabs){this.tabs[id].handleBuddyAvailability(justCameOnline);}},_handleMsg:function(channel,obj){if(obj.from){if(obj.from==this.user){var id=obj.to;}else{var id=obj.from;}
var tab=this.tabs[id];}
if(obj.window_id==presence.windowID){return false;}
switch(obj.type){case'unfocus_chat':this._unfocus();return true;case'focus_chat':this._focusTab(obj.id);return true;case'close_chat':this._closeTab(obj.id);return true;case'msg':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);return true;case'mf':if(!tab){return false;}
tab.newMinifeed(obj);return true;case'status':if(!tab){return false;}
tab.updateStatus(obj.status,obj.time,obj.statusTimeRel);return true;case'typ':if(tab){tab.newTyping(obj);}else{presence.debug('typing message ignored');}
return true;default:return false;}},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;Util.log(timeStr);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;Util.log(timeStr);return timeStr;}};function chat_simple_popout(popoutURL){window.open(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 search_typeaheadpro(obj,source,properties){this.parent.construct(this,obj,source,properties);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=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(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){url=sprintf(type_info.default_url,escapeURI(friend.i));}}
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 search_friend_source(get_param){this.parent.construct(this,get_param);var current_time=(new Date()).getTime();new AsyncRequest().setMethod('GET').setReadOnly(true).setURI('/ajax/typeahead_search.php?'+get_param).setErrorHandler(function(){}).setTransportErrorHandler(function(){}).setHandler(function(response){var payload=response.getPayload();this.values=payload.entries;this.build_index.bind(this).defer();search_typeahead_log(this.udata,'getdata',current_time);var now_minus_5_min=((new Date()).getTime()/1000)-60*5;if(payload.gen_time<now_minus_5_min){new AsyncRequest().setMethod('GET').setReadOnly(true).setURI('/ajax/recent_pics.php').setData({ref_time:payload.gen_time}).setErrorHandler(function(){}).setTransportErrorHandler(function(){}).setHandler(function(response){this.updated_pics=response.getPayload().updated_pics;}.bind(this)).send();}}.bind(this)).disableNectar().send();}
search_friend_source.extend('static_source');search_friend_source.prototype.text_noinput=search_friend_source.prototype.text_placeholder=search_friend_source.prototype.text_nomatch='';search_friend_source.prototype.cache_results=true;search_friend_source.prototype.updated_pics={};search_friend_source.prototype._allowed_types=null;search_friend_source.url_templates={};search_friend_source.loaded_images={};search_friend_source.TYPES={USER:'u',PAGE:'p',APP:'a',GROUP:'g',EVENT:'e',SEARCH:'search',WEB:'web'};search_friend_source.prototype.build_index=function(){var history=this.history?this.history.entries:undefined;if(history!=undefined){this.values=this.values.each(function(value){value.o=history[value.i]!=undefined?history[value.i]:value.o;return value;});}
this.parent.build_index();}
search_friend_source.image_load=function(image_elm,insertion_time,user_id){var current_time=(new Date()).getTime();search_friend_source.loaded_images[user_id]=true;if((current_time-insertion_time)<100){CSS.setOpacity(image_elm,1);}else{animation(image_elm).to('opacity',1).duration(100).go();}};search_friend_source.prototype.gen_html=function(friend,highlight){var icon_url=friend.it;if(!icon_url&&friend.ty&&search_friend_source.url_templates[friend.ty]){icon_url=search_friend_source.url_templates[friend.ty].icon;}
if(this.updated_pics[friend.i]){icon_url=this.updated_pics[friend.i];}
switch(friend.ty){case search_friend_source.TYPES.USER:if(!icon_url){return['<div>',typeahead_source.highlight_found(friend.t,highlight),'</div><div><small>',friend.n,'</small></div>'].join('');}else{if(!search_friend_source.loaded_images[friend.i]){var insertion_time=(new Date()).getTime();var attrs=sprintf('onload="search_friend_source.image_load(this, %d, %d);" style="opacity:0;filter:alpha(opacity=0);"',insertion_time,friend.i);}
return['<img ',attrs,' alt="" src="',icon_url,'"/>','<div class="with_pic"><span>',typeahead_source.highlight_found(friend.t,highlight),'</span><small>',friend.n,'</small></div>'].join('');}
break;case search_friend_source.TYPES.SEARCH:return['<div class="app"><div class="icon" style="background-image: url(',icon_url,')">&nbsp;</div>','<span>',friend.t,'</span></div>'].join('');break;default:return['<div class="app clearfix"><div class="icon" style="background-image: url(',icon_url,')">&nbsp;</div>','<span>',typeahead_source.highlight_found(friend.t,highlight),'</span></div>'].join('');}};search_friend_source.prototype.allowTypes=function(type_arr){this._allowed_types=type_arr;return this;}
search_friend_source.prototype.search_value=function(text){var results;var enough_tokens=false;var tokens=typeahead_source.tokenize(text);for(var i=0;i<tokens.length;i++){if(tokens[i]!=''){enough_tokens=true;break;}}
if(enough_tokens){this.owner.less_than_n_chars=false;results=this.parent.search_value(text);}else if(this.is_ready){this.owner.less_than_n_chars=true;results=[];}
var non_people_search=(results&&results.length)?false:true;if(results){for(var i=0;i<results.length;i++){if(results[i].ty!=search_friend_source.TYPES.USER){non_people_search=true;break;}}}
if(results&&non_people_search&&enough_tokens&&search_friend_source.WEBSEARCH_USER){results.push({t:_tx("Search Facebook"),ty:search_friend_source.TYPES.SEARCH,i:text});results.push({t:_tx("Search the Web"),ty:search_friend_source.TYPES.WEB,i:text});}
if(this._allowed_types){results=results.filter(function(result){return this._allowed_types.contains(result.ty);}.bind(this));}
return results;};search_friend_source.prototype._sort_text_obj=function(a,b){var history=this.history?this.history.entries:undefined;if(history!=undefined){a.o=history[a.i]||a.o;b.o=history[b.i]||b.o;}
if(a.o!=b.o){return a.o<b.o?-1:1;}else if(a.t==b.t){return 0;}
return a.t<b.t?-1:1};search_friend_source.WEBSEARCH_USER=false;window.ADVANCED_SEARCH_TYPEAHEAD=false;

function ApplicationDock(bookmarks){this.bookmarks={};this.sortedBookmarks=[];this.bookmarkableApp=null;this.undoTimeouts={}
this.menuLoaded=false;this.menuOpen=false;this.menuWrapperID='presence_applications';this.applicationTabID='presence_applications_tab';this.applicationMenuContentID='presence_applications_content';this.menuWrapper=$(this.menuWrapperID);this.applicationTab=$(this.applicationTabID);this.applicationMenuContainer=$(this.applicationMenuContentID);this.iconGardenContainer=$('presence_applications_icon_garden');this.bookmarkableAppWrapper=$('bookmarkable_app');this.bookmarkableAppContainer=$('presence_applications_bookmark_app');this.sortableRoot=null;this.sortableGroup=null;this.extendedSortableGroup=null;this.extendedSortableRoot=null;this.iconGardenSortableGroup=null;this.iconGardenSortableRoot=null;this.currentIconGardenDraggableKey=null;this.recentSortableGroup=null;this.recentSortableRoot=null;this.lastBookmarkedApp=null;this.logTabOpen=false;this.logBMClick=false;this.topBookmark=null;this.recentApps=null;this.sortedRecentApps=null;this.bookmarks=bookmarks
this.suppressReset=false;this.removedBookmarks={};}
copy_properties(ApplicationDock,{NUM_SHOWN:6,BOOKMARKS_CHANGED:'bookmarks_changed',SaveBookmarksSource:{ICON_GARDEN:1,APPLICATION_MENU:2,BOOKMARK_CURRENT_APP:3},ANIM_DURATION:200,UNDO_ANIM_HIDE_DELAY:5000,RECENT_APPS_ANIM_HIDE_DELAY:1000});ApplicationDock.prototype={_init:function(){this.sortedBookmarks=this._getSortedList();this._renderIconGarden();if(!is_empty(this.bookmarkableApp)){this._renderBookmarkableApp();}
this._initIconGardenSortables.bind(this).defer();presence.registerMsgHandler(this._handleMsg.bind(this));},_getSortedList:function(applications){applications=applications||this.bookmarks;var array=keys(applications);array=mapToInt(array);this._sort(array,applications);return array;},_ensureSortedRecentApps:function(){if(!this.sortedRecentApps){this.sortedRecentApps=this._getSortedList(this.recentApps);}},_sort:function(array,applications){var compareFunction=this._sortApps.bind(null,applications);array.sort(compareFunction);},_sortApps:function(applications,id1,id2){return applications[id1].order-applications[id2].order;},_renderApplicationMenu:function(){DOM.setContent(this.applicationMenuContainer,HTML(this._renderAppMenuContent()));},_renderAppMenuContent:function(){var markupArr=[];var bookmarksDividerRendered=false;if(count(this.recentApps)>0){markupArr.push('<div id="application_menu_recent_apps_container">');markupArr.push(this._renderAppMenuDivider(_tx("Recently Used")));markupArr.push('<ul id="application_menu_recent_apps">');this._ensureSortedRecentApps();for(var i=0;i<this.sortedRecentApps.length;i++){var appID=this.sortedRecentApps[i];markupArr.push(this._renderAppMenuItem(appID));}
markupArr.push('</ul>');markupArr.push('</div>');if(this.sortedBookmarks.length){bookmarksDividerRendered=true;markupArr.push(this._renderAppMenuDivider(_tx("Bookmarks")));}}
if(this.sortedBookmarks.length){if(!bookmarksDividerRendered){markupArr.push(this._renderAppMenuDivider(_tx("Bookmarks")));}
markupArr.push('<ul id="application_menu_root">');for(var i=0;i<this.sortedBookmarks.length;i++){var appID=this.sortedBookmarks[i];if(i==ApplicationDock.NUM_SHOWN){markupArr.push('</ul>',this._renderAppMenuDivider(),'<ul id="application_menu_extended_root">');}
markupArr.push(this._renderAppMenuItem(appID,null,true));}
markupArr.push('</ul>');}
return markupArr.join('');},_renderAppMenuItem:function(appID){var removeBookmarkButtonStr='';var undoRemoveStr='';removeBookmarkButtonStr=sprintf('<div class="del_button" id="%s"></div>',this._getAppMenuRemoveItemId(appID));undoRemoveStr=['<div class="app_menu_undo_remove_bookmark" id="',this._getAppMenuUndoRemoveItemId(appID),'"><div class="app_menu_undo_remove_bookmark_link"><a href="#" id="',this._getAppMenuUndoRemoveItemLinkId(appID),'">',_tx("Undo"),'</a></div><div>',_tx("Bookmark removed"),'</div></div>'].join('');return['<li id="',this._getApplicationMenuItemId(appID),'"><div id="',this._getApplicationMenuLinkContainerId(appID),'">',removeBookmarkButtonStr,this._renderApplicationMenuItem(appID),'</div>',undoRemoveStr,'</li>',].join('');},_renderAppMenuDivider:function(dividerText){return['<div class="application_menu_divider">',dividerText||'','</div>'].join('');},_renderApplicationMenuItem:function(appID){var appInfo=this._getAppInfo(appID);var markupArr=['<a id="',this._getApplicationMenuLinkId(appID),'" href="',appInfo['href'],'" class="item">','<div class="item">','<img src="',appInfo['new_icon'],'" />','</div>',htmlize(appInfo['name']),'</a>'];return markupArr.join('');},_getApplicationMenuItemId:function(appID){return'application_menu_'+appID;},_getApplicationMenuLinkContainerId:function(appID){return'application_menu_link_container_'+appID;},_getApplicationMenuLinkId:function(appID){return'application_menu_link_'+appID;},render:function(){this._init();return this;},toggleTab:function(){if(!this.menuOpen){this._openTab();}else{this._closeTab();}},_openTab:function(){if(this.menuOpen){return;}
if(!this.menuLoaded){this._renderApplicationMenu();this._initApplicationMenu.bind(this).defer();this.menuLoaded=true;}
presence.openTab(this.menuWrapperID,this.applicationTabID,this.applicationMenuContentID);this.menuOpen=true;if(this.logTabOpen){AsyncRequest.pingURI('/ajax/abtest_multi_async.php',{test_names:['PLATFORM_APPDOCK_APPBUTTON','APPS_MENU_TEST'],actions:['APPLICATIONS_MENU_OPEN']});}
if(buddyList&&buddyList.openingABTestIsActive()){AsyncRequest.pingURI('/ajax/abtest_async.php',{test_name:'CHAT_BUDDY_LIST_OPENING',action:'OPEN_APP_DOCK'});}},_closeTab:function(){presence.toggleTab(this.menuWrapperID,this.applicationTabID,this.applicationMenuContentID);this.menuOpen=false;},_initApplicationMenu:function(){this.sortableRoot=$('application_menu_root');this.sortableGroup=new SortableGroup();var source=ApplicationDock.SaveBookmarksSource.APPLICATION_MENU;this.sortableGroup.setOrderChangeHandler(this._saveBookmarksOrder.bind(this,source));var sortableGroup=this.sortableGroup;for(var i=0;i<this.sortedBookmarks.length;i++){var appID=this.sortedBookmarks[i];if(i==ApplicationDock.NUM_SHOWN){this._initExtendedApplicationMenuSortables();sortableGroup=this.extendedSortableGroup;}
this._addApplicationMenuSortable(appID,sortableGroup);this._initEventHandlers(appID);}
if(this.recentApps&&count(this.recentApps)>0){this.recentSortableRoot=$('application_menu_recent_apps');this.recentSortableGroup=new SortableGroup();this.recentSortableGroup.setDroppable(false);this.sortableGroup.link(this.recentSortableGroup);for(var appID in this.recentApps){this._addApplicationMenuSortable(appID,this.recentSortableGroup);}}},_initEventHandlers:function(appID){var menuLinkID=this._getApplicationMenuLinkId(appID);$(menuLinkID).listen('click',this._menuClick.bind(this,appID,menuLinkID));var item=$(this._getApplicationMenuItemId(appID));item.listen('mouseover',CSS.addClass.bind(CSS,item,'hover'));item.listen('mouseout',CSS.removeClass.bind(CSS,item,'hover'));this._registerRemoveItemHandler(appID,this._getAppMenuRemoveItemId(appID),false);this._registerRemoveItemHandler(appID,this._getAppMenuUndoRemoveItemLinkId(appID),true);},_registerRemoveItemHandler:function(appID,elemID,setting){$(elemID).listen('click',(function(e){this._setBookmarked(appID,setting);return $E(e).kill();}).bind(this));},_setBookmarked:function(appID,setting){this.suppressReset=true;var sortableGroup;var item=ge(this._getApplicationMenuItemId(appID));if(item.parentNode==this.sortableRoot){sortableGroup=this.sortableGroup;}else{sortableGroup=this.extendedSortableGroup;}
if(setting){this._addApplicationMenuSortable(appID,sortableGroup);var source=ApplicationDock.SaveBookmarksSource.APPLICATION_MENU;this._saveBookmarksOrder.bind(this,source).defer();delete this.removedBookmarks[appID];}else{if(!this.removedBookmarks[appID]){this.removedBookmarks[appID]=this.bookmarks[appID];}
sortableGroup.removeSortable(appID);this._removeBookmark(appID);}
this._animateSetBookmarked(appID,setting);},_removeBookmark:function(appID){new AsyncRequest().setURI('/ajax/edit_app_settings.php').setData({'bookmark':1,'bookmarked':false,'app_id':appID}).setHandler(this._removeBookmarkHandler.bind(this,appID)).send();},_removeBookmarkHandler:function(appID){this.sortedBookmarks.remove(appID);this._resetIconGarden();},_animateSetBookmarked:function(appID,setting){var itemElem=ge(this._getApplicationMenuLinkContainerId(appID));var undoElem=ge(this._getAppMenuUndoRemoveItemId(appID));var hiddenElem,shownElem;if(!setting){hiddenElem=itemElem;shownElem=undoElem;}else{hiddenElem=undoElem;shownElem=itemElem;}
hide(hiddenElem);animation(shownElem).show().from('opacity',0).to('opacity',1).duration(ApplicationDock.ANIM_DURATION).go();if(!setting){this.undoTimeouts[appID]=(function(){var item=ge(this._getApplicationMenuItemId(appID));if(item){animation(item).to('height',0).duration(ApplicationDock.ANIM_DURATION).hide().ondone(this._onsortableLinkJump.bind(this,null)).go();}}).bind(this).defer(ApplicationDock.UNDO_ANIM_HIDE_DELAY);}else{clearTimeout(this.undoTimeouts[appID]);delete this.undoTimeouts[appID];}},_menuClick:function(appID,menuLinkID){if(ApplicationDock.presenceWidthTest){AsyncRequest.pingURI('/ajax/abtest_async.php',{test_name:'APP_DOCK_TEST',action:'USED_APP_MENU'});}
if(buddyList&&buddyList.openingABTestIsActive()){AsyncRequest.pingURI('/ajax/abtest_async.php',{test_name:'CHAT_BUDDY_LIST_OPENING',action:'CLICK_APP_DOCK_ITEM'});}
var appInfo=this._getAppInfo(appID);var logAction=appInfo.logAction;if(logAction){AsyncRequest.pingURI('/ajax/abtest_async.php',{test_name:'APPS_MENU_TEST',action:logAction});}},_getAppInfo:function(appID){return this.bookmarks[appID]||this.recentApps[appID]||this.removedBookmarks[appID];},_initExtendedApplicationMenuSortables:function(){this.extendedSortableGroup=new SortableGroup();this.extendedSortableRoot=$('application_menu_extended_root');this.sortableGroup.link(this.extendedSortableGroup);this.sortableGroup.setLinkJumpHandler(this._onsortableLinkJump.bind(this));var source=ApplicationDock.SaveBookmarksSource.APPLICATION_MENU;this.extendedSortableGroup.setOrderChangeHandler(this._saveBookmarksOrder.bind(this,source));},_addApplicationMenuSortable:function(appID,sortableGroup){var obj=$(this._getApplicationMenuItemId(appID));var handle=$(this._getApplicationMenuLinkId(appID));sortableGroup.addSortable(appID,obj,handle);},_resetApplicationMenu:function(){if(!this.menuLoaded){return;}
this.sortableGroup.destroy();if(this.extendedSortableGroup){this.extendedSortableGroup.destroy();}
if(this.recentSortableGroup){this.recentSortableGroup.destroy();}
this._renderApplicationMenu();this._initApplicationMenu.bind(this).defer();},_onsortableLinkJump:function(key){var order=this.sortableGroup.getOrder(),migrateKey=null;if(order.length>ApplicationDock.NUM_SHOWN){for(var i=order.length-1;i>=0;i--){if(order[i]!=key){migrateKey=order[i];break;}}
DOM.prependContent(this.extendedSortableRoot,$(this._getApplicationMenuItemId(migrateKey)));this.extendedSortableGroup.migrateLinkedSortable(migrateKey);}else if(order.length<ApplicationDock.NUM_SHOWN){order=this.extendedSortableGroup.getOrder();for(var i=0;i<order.length;i++){if(order[i]!=key){migrateKey=order[i];break;}}
DOM.appendContent(this.sortableRoot,$(this._getApplicationMenuItemId(migrateKey)));this.sortableGroup.migrateLinkedSortable(migrateKey);}
var order=this.recentSortableGroup.getOrder();if(order.length<this.sortedRecentApps.length){this.recentAppBookmarked=parseInt(key,10);}else if(this.recentAppBookmarked){delete this.recentAppBookmarked;}},_saveBookmarksOrder:function(source){this._processNewBookmark();var order=this._getOrder(source);new AsyncRequest().setURI('/ajax/edit_app_settings.php').setData({reorder_bookmarks:1,app_ids:order}).setHandler(this._saveBookmarksHandler.bind(this,order,source)).send();},_processNewBookmark:function(){if(this.recentAppBookmarked){var appID=this.recentAppBookmarked;this.sortedRecentApps.remove(appID)
this._initEventHandlers(appID);this.bookmarks[appID]=this.recentApps[appID];delete this.recentApps[appID];delete this.recentAppBookmarked;if(!this.sortedRecentApps.length){(function(){animation($('application_menu_recent_apps_container')).to('height',0).to('opacity',0).duration(ApplicationDock.ANIM_DURATION).hide().go()}).defer(ApplicationDock.RECENT_APPS_ANIM_HIDE_DELAY);}}},_getOrder:function(source){if(source==ApplicationDock.SaveBookmarksSource.APPLICATION_MENU){order=this.sortableGroup.getOrder();}else{order=this.iconGardenSortableGroup.getOrder();if(source==ApplicationDock.SaveBookmarksSource.BOOKMARK_CURRENT_APP){order.push(this._getAppShaftedByBookmarkableApp());}}
if(this.extendedSortableGroup){order=order.concat(this.extendedSortableGroup.getOrder());}else if(!this.menuLoaded&&this.sortedBookmarks.length>ApplicationDock.NUM_SHOWN){order=order.concat(this.sortedBookmarks.slice(ApplicationDock.NUM_SHOWN));}
order=unique(order);return order;},_saveBookmarksHandler:function(appIDs,source){this._updateSortedList(appIDs);switch(source){case ApplicationDock.SaveBookmarksSource.APPLICATION_MENU:this._resetIconGarden();break;case ApplicationDock.SaveBookmarksSource.ICON_GARDEN:case ApplicationDock.SaveBookmarksSource.BOOKMARK_CURRENT_APP:this._resetApplicationMenu();if(this.lastBookmarkedApp){this._openTab();var menuItem=$(this._getApplicationMenuItemId(this.lastBookmarkedApp));var gardenItem=$(this._getApplicationIconGardenItemId(this.lastBookmarkedApp));animation(menuItem).from('backgroundColor','#FFF9B7').to('backgroundColor','#FFFFFF').ease(animation.ease.begin).duration(4000).ondone(CSS.setStyle.bind(this,menuItem,'backgroundColor','')).go();animation(gardenItem).from('backgroundColor','#FFF9B7').to('backgroundColor','#EAEAEA').ease(animation.ease.begin).duration(4000).ondone(CSS.setStyle.bind(this,gardenItem,'backgroundColor','')).go();}
break;}},_updateSortedList:function(appIDs){this.sortedBookmarks=[];for(var i=0;i<appIDs.length;i++){this.sortedBookmarks.push(parseInt(appIDs[i],10));}},_renderIconGarden:function(){DOM.setContent(this.iconGardenContainer,HTML(this._renderIconGardenContent()));},_renderIconGardenContent:function(){var markupArr=['<div id="application_icon_garden_root"',' class="icon_garden_root">'];for(var i=0,length=Math.min(ApplicationDock.NUM_SHOWN,this.sortedBookmarks.length);i<length;i++){var appID=this.sortedBookmarks[i];markupArr.push('<div id="',this._getApplicationIconGardenItemId(appID),'"',' class="icon_garden_elem">',this._renderApplicationIconGardenItem(appID),'</div>');}
markupArr.push('</div>');return markupArr.join('');},_renderApplicationIconGardenItem:function(appID){var appInfo=this._getAppInfo(appID);var markupArr=['<div class="icon_garden_inner">','<a id="',this._getApplicationIconGardenLinkId(appID),'"',' onmouseover="applicationDock.mouseOverIconGarden(',appID,');"',' onmouseout="applicationDock.MouseOutIconGarden(',appID,');"',' href="',appInfo['href'],'">','<img src="',appInfo['new_icon'],'" />','<div class="titletip">','<strong>',htmlize(appInfo['name']),'</strong>','</div>','</a>','</div>'];return markupArr.join('');},mouseOverIconGarden:function(appID){if(shown(this.menuWrapper)){return;}
if(!this.currentIconGardenDraggableKey||this.currentIconGardenDraggableKey!=appID){CSS.addClass(this._getApplicationIconGardenItemId(appID),'hover');}},MouseOutIconGarden:function(appID){CSS.removeClass(this._getApplicationIconGardenItemId(appID),'hover');},_grabCallback:function(appID){this.currentIconGardenDraggableKey=appID;},_dropCallback:function(appID){this.currentIconGardenDraggableKey=null;},_getApplicationIconGardenItemId:function(appID){return'application_icon_garden_'+appID;},_getApplicationIconGardenLinkId:function(appID){return'application_icon_garden_link_'+appID;},_getAppMenuRemoveItemId:function(appID){return'application_remove_item_'+appID;},_getAppMenuUndoRemoveItemId:function(appID){return'application_undo_remove_item_'+appID;},_getAppMenuUndoRemoveItemLinkId:function(appID){return'application_undo_remove_item_link_'+appID;},_initIconGardenSortables:function(){this.iconGardenSortableGroup=new SortableGroup();this.iconGardenSortableRoot=$('application_icon_garden_root');var source=ApplicationDock.SaveBookmarksSource.ICON_GARDEN;this.iconGardenSortableGroup.setOrderChangeHandler(this._saveBookmarksOrder.bind(this,source));for(var i=0,length=Math.min(this.sortedBookmarks.length,ApplicationDock.NUM_SHOWN);i<length;i++){this._addIconGardenSortable(this.sortedBookmarks[i]);}},_addIconGardenSortable:function(appID){var obj=$(this._getApplicationIconGardenItemId(appID));var handle=$(this._getApplicationIconGardenLinkId(appID));this.iconGardenSortableGroup.addSortable(appID,obj,handle).setGrabCallback(this._grabCallback.bind(this)).setDropCallback(this._dropCallback.bind(this));if(ApplicationDock.presenceWidthTest){handle.listen('click',function(){AsyncRequest.pingURI('/ajax/abtest_async.php',{action:'USED_APP_DOCK',test_name:'APP_DOCK_TEST'});});}
if(this.logBMClick||this.logTabOpen){var actions=['APPLICATIONS_GARDEN_CLICK'];var test_names=['PLATFORM_APPDOCK_APPBUTTON','PLATFORM_BOOKMARK_BUTTON_LOCATION','APPS_MENU_TEST'];handle.listen('click',AsyncRequest.pingURI.bind(AsyncRequest,'/ajax/abtest_multi_async.php',{'actions':actions,'test_names':test_names}));}},_resetIconGarden:function(){this.iconGardenSortableGroup.destroy();this._renderIconGarden();this._initIconGardenSortables.bind(this).defer();},_renderBookmarkableApp:function(){DOM.setContent(this.bookmarkableAppContainer,HTML(this._renderBookmarkableAppContent()));var link=DOM.find(this.bookmarkableAppContainer,'a');link.listen('click',this.bookmarkCurrentApp.bind(this,false));if(this.topBookmark&&ge('sidebar_ads')){this.bookmarkTopContainer=$N('div',{'className':'bookmark_top_container'});DOM.setContent(this.bookmarkTopContainer,HTML(this.topBookmark));var bookmarkTop=DOM.find(this.bookmarkTopContainer,'div.bookmark_dummy');DOM.insertBefore(this.bookmarkTopContainer,$('sidebar_ads'));DOM.replace(bookmarkTop,HTML(this._renderBookmarkableAppContent('top')));var link=DOM.find(this.bookmarkTopContainer,'a');link.listen('click',this.bookmarkCurrentApp.bind(this,true));}
CSS.removeClass(this.bookmarkableAppWrapper,'hidden_elem');},_hideBookmarkableApp:function(){CSS.addClass(this.bookmarkableAppWrapper,'hidden_elem');if(this.bookmarkTopContainer){hide(this.bookmarkTopContainer);}},_renderBookmarkableAppContent:function(){var appInfo=values(this.bookmarkableApp)[0];var markupArr=['<a',' onmouseover="applicationDock.mouseOverBookmarkableApp();return false;"',' onmouseout="applicationDock.mouseOutBookmarkableApp();return false;"',' href="#">','<span class="bookmark_app_plus"></span>','<img src="',appInfo['new_icon'],'" />','<span class="bookmark_text">',_tx("Bookmark"),' ',htmlize(appInfo['name']),'</span>','</a>'];return markupArr.join('');},mouseOverBookmarkableApp:function(){CSS.addClass(this.bookmarkableAppWrapper,'hover');},mouseOutBookmarkableApp:function(){CSS.removeClass(this.bookmarkableAppWrapper,'hover');},setBookmarkableApp:function(bookmarkableApp,noRender){this.bookmarkableApp=bookmarkableApp;if(!noRender){if(is_empty(this.bookmarkableApp)){this._hideBookmarkableApp();}else{this._renderBookmarkableApp();}}
return this;},setRecentApps:function(recentApps){this.recentApps=recentApps;return this;},setTopBookmarkWrap:function(topBookmarkWrap){this.topBookmark=topBookmarkWrap;return this;},setADLogging:function(logState){this.logTabOpen=logState;return this;},setBMLogging:function(logState){this.logBMClick=logState;return this;},_getAppShaftedByBookmarkableApp:function(){return this.sortedBookmarks[ApplicationDock.NUM_SHOWN-1];},bookmarkCurrentApp:function(fromTop){var appID=keys(this.bookmarkableApp)[0];var existingApp=this.bookmarks[appID];this.bookmarks[appID]=this.bookmarkableApp[appID];var div=$N('div',{id:this._getApplicationIconGardenItemId(appID),className:'icon_garden_elem'},HTML(this._renderApplicationIconGardenItem(appID)));if(this.sortedBookmarks.length>=ApplicationDock.NUM_SHOWN){this.iconGardenSortableRoot.replaceChild(div,this.iconGardenSortableRoot.lastChild);this.iconGardenSortableGroup.removeSortable(this._getAppShaftedByBookmarkableApp());}else{this.iconGardenSortableRoot.appendChild(div);}
this._addIconGardenSortable.bind(this,appID).defer();this._hideBookmarkableApp();this.lastBookmarkedApp=appID;if(this.logBMClick){var result={test_name:'PLATFORM_BOOKMARK_BUTTON_LOCATION'};result.action=fromTop?'PLATFORM_BOOKMARK_TOP':'PLATFORM_BOOKMARK_BOTTOM';AsyncRequest.pingURI('/ajax/abtest_async.php',result);}
this._saveBookmarksOrder.bind(this,ApplicationDock.SaveBookmarksSource.BOOKMARK_CURRENT_APP).defer();},_handleMsg:function(channel,obj){if(obj.type=='bookmarks'){var newSortedList=this._getSortedList(obj.bookmarks);if(!are_equal(this.sortedBookmarks,newSortedList)){this.bookmarks=obj.bookmarks;this.sortedBookmarks=newSortedList;if(!this.suppressReset){this._resetApplicationMenu();this._resetIconGarden();}
this.suppressReset=false;}
var message={sender:this,applications:this.sortedBookmarks};Arbiter.inform(ApplicationDock.BOOKMARKS_CHANGED,message);return true;}
return false;}}

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();},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';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 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.latest_notif_time=latest_notif;this.latest_read_notif_time=latest_read_notif;this._init();}
copy_properties(ChatNotifications.prototype,{_init:function(){this.cookieName='notifications_'+this.user;this.markReadAsync=null;this.markupCached=null;this.appHideCache=[];this.updateCheckCount=0;this.contentID='presence_notifications_content';this.content=ge(this.contentID);this.countSpan=ge('presence_notifications_count');this.navInbox=ge('nav_inbox');this._updateCount();presence.registerMsgHandler(this._handleMsg.bind(this));presenceUpdater.register('notifications',this._checkUpdater.bind(this),this._onUpdaterResponse.bind(this),this._onUpdaterError.bind(this),this._onUpdaterError.bind(this));presenceCookieManager.register('ntf',this._getCookieData.bind(this));},markRead:function(skip_async_request){if(this.countNew==0){return;}
this.countNew=0;this._updateCount();if(!skip_async_request){AsyncRequest.pingURI('/ajax/presence/notifications_read.php');}
unreads=DOM.scry(this.content,'div.notif_unread');for(var i=0;i<unreads.length;i++){animation(unreads[i]).duration(1250).checkpoint().to('backgroundColor','#FFFFF').duration(2250).ondone(CSS.removeClass.bind(null,unreads[i],'notif_unread')).go();}},_getCookieData:function(){return this.countNew;},_checkUpdater:function(time,asyncData,forceUpdate){if(!buddyList._checkUpdater(time,{},forceUpdate)){return false;}
this.updateCheckCount++;if(forceUpdate||(100/this.updateCheckCount)<=presence.sitevars.NOTIFICATIONS_PIGGYBACK_PERCENTAGE){this.updateCheckCount=0;asyncData['notif_latest']=this.latest_notif_time;asyncData['notif_latest_read']=this.latest_read_notif_time;return true;}
return false;},_onUpdaterResponse:function(notificationResponse,time){var inboxCount=notificationResponse.inboxCount;if(this.navInbox&&inboxCount!=null){if(inboxCount==0){hide('fb_menu_inbox_unread_count_holder');}else{var countElt=$('fb_menu_inbox_unread_count');DOM.setContent(countElt,inboxCount);show('fb_menu_inbox_unread_count_holder');}}
var inboxDropdownMarkup=notificationResponse.inboxDropdownMarkup;var inboxDropdownElement=ge('fb_menu_inbox_dropdown');if(inboxDropdownElement&&inboxDropdownMarkup){inboxDropdownElement.setContent(HTML(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;for(var k in notificationResponse.app_names){this.app_names[k]=notificationResponse.app_names[k];}
var multiple_updates=(null!=this.markupCached);this.markupCached=notificationResponse.markup;if(presence.focusedTab=='presence_notifications_tab'){multiple_updates||presence.registerTempTabCloseHandler(this._updateDisplay.bind(this));}else{this._updateDisplay();}
Arbiter.inform(Arbiter.NEW_NOTIFICATIONS,notificationResponse);}},_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();},_onUpdaterError:function(response){},_updateCount:function(){if(this.countSpan){this.countSpan.innerHTML=this.countNew?'<strong>'+this.countNew+'</strong>':'';}},hideNotifications:function(app_id,cached){var notifs=DOM.scry(this.content,'div.notif_'+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);setTimeout(presence.allowAutoClose.bind(presence),1100);var params={'app_id':app_id,'collapse':1,'type':platform_type};if('report'==button_name){params['spam']=1;}
new AsyncRequest().setURI('/ajax/notifications.php').setData(params).send();(typeof(toggleType)=='function')&&(typeof(hidden)!='undefined')&&(!hidden[app_id])&&toggleType(app_id,true,null,false,true,presence.user,false,platform_type);};var canceler={};copy_properties(canceler,Dialog.CANCEL);canceler.handler=function(){presence.allowAutoClose();};presence.disallowAutoClose();var app_name=this.app_names[app_id];var dialog_handle=new Dialog().setTitle(_tx("Do you want to hide all notifications from {application-name}?",{'application-name':app_name})).setBody(_tx("This will hide all notifications from this application. ")).setButtons([{name:'hide',label:_tx("Hide all"),handler:bind(this,hide_handler,'hide')},{name:'report',label:_tx("Report Spam"),handler:bind(this,hide_handler,'report')},canceler]).setModal().show();return false;},_handleMsg:function(channel,obj){if(obj.type=='notification'){presenceUpdater.runHandler('notifications');return true;}else if(obj.type=='notifications_read'){this.markRead(true);return true;}}});

function ScrollArea(scroll_div_id,content_div_id,down_arrow_id,up_arrow_id){if(this===window){Util.error('You\'re doing this wrong.  This is a class and should be '+'with new ScrollArea(...);');return;}
copy_properties(this,{scroll_div:$(scroll_div_id),content_div:$(content_div_id),down_arrow:$(down_arrow_id),up_arrow:$(up_arrow_id)});copy_properties(this,{auto_move_interval:null,allow_page_scroll:true,max_height:false});this.down_arrow.onmouseout=bind(this,'_endAutoMove',ScrollArea.DOWN);this.down_arrow.onmouseover=bind(this,'_startAutoMove',ScrollArea.HOVER_INTERVAL,ScrollArea.DOWN);this.up_arrow.onmouseout=bind(this,'_endAutoMove',ScrollArea.UP);this.up_arrow.onmouseover=bind(this,'_startAutoMove',ScrollArea.HOVER_INTERVAL,ScrollArea.UP);this.scroll_div.onmouseover=bind(this,'_disallowPageScroll');this.scroll_div.onmouseout=bind(this,'_allowPageScroll');ScrollWheel.addHandler(this._pageScrollResponse.bind(this));ScrollArea.instances.push(this);this.update();}
copy_properties(ScrollArea,{HOVER_INTERVAL:50,MOUSE_WHEEL_MULTIPLE:-8,UP:1,DOWN:2,instances:[],build:function(id,content,max_height){var content_id=id+'_content';var scroll_id=id+'_scroll';var down_id=id+'_down';var up_id=id+'_up';var content_node=$N('div',{'className':'scroll_area_content','id':content_id},content);var down_node=$N('a',{'className':'arrow down_arrow','id':down_id},HTML('<span>&nbsp;</span>'));down_node.listen('click',Event.kill);var up_node=$N('a',{'className':'arrow up_arrow','id':up_id},HTML('<span>&nbsp;</span>'));up_node.listen('click',Event.kill);var scroller_node=$N('div',{'className':'scroll_area_scroll','id':scroll_id});scroller_node.appendChild(content_node);scroller_node.appendChild(down_node);scroller_node.appendChild(up_node);var wrapper_node=$N('div',{'id':id},scroller_node);(function(scroll_id,content_id,down_id,up_id,max_height){new ScrollArea(scroll_id,content_id,down_id,up_id).setMaxHeight(max_height);}).bind(this,scroll_id,content_id,down_id,up_id,max_height).defer();return wrapper_node;},getInnerInstance:function(element){for(var i=0;i<ScrollArea.instances.length;i++){if(DOM.contains(element,ScrollArea.instances[i].scroll_div)){return ScrollArea.instances[i];}}
return false;}});copy_properties(ScrollArea.prototype,{_startAutoMove:function(interval_time,direction){if(direction==ScrollArea.UP){this.up_arrow.addClass('arrow_hover');this.up_arrow.addClass('up_arrow_hover');}else{this.down_arrow.addClass('arrow_hover');this.down_arrow.addClass('down_arrow_hover');}
var move_fn=bind(this,this.moveBy,(direction==ScrollArea.UP)?-11:11);this.auto_move_interval=setInterval(move_fn,interval_time);},_endAutoMove:function(direction){if(direction==ScrollArea.UP){this.up_arrow.removeClass('arrow_hover');this.up_arrow.removeClass('up_arrow_hover');}else{this.down_arrow.removeClass('arrow_hover');this.down_arrow.removeClass('down_arrow_hover')}
clearInterval(this.auto_move_interval);},_disallowPageScroll:function(){this.allow_page_scroll=false;},_allowPageScroll:function(){this.allow_page_scroll=true;},_pageScrollResponse:function(delta){if(!this.allow_page_scroll){var round_fn=delta>0?Math.ceil:Math.floor
this.moveBy(ScrollArea.MOUSE_WHEEL_MULTIPLE*round_fn(delta));}
return this.allow_page_scroll;},_scrollTop:function(){return(-1*parseInt(this.content_div.style.marginTop))||0;},_setScrollTop:function(new_top){new_top=this._enforceRange(new_top);this.content_div.style.marginTop=-new_top+'px';},_isAtTop:function(){return this._scrollTop()==0;},_isAtBottom:function(){var scrollTop=this._scrollTop();return scrollTop==this._enforceRange(scrollTop+1);},_enforceRange:function(test_val){var new_top;var hidden_content_height=Vector2.getElementDimensions(this.content_div).y-
Vector2.getElementDimensions(this.scroll_div).y;if(test_val<0){new_top=0;}else if(test_val>hidden_content_height){new_top=hidden_content_height;}else{new_top=test_val;}
return new_top;},setMaxHeight:function(new_max){this.max_height=new_max;return this;},moveBy:function(distance){var current_top=this._scrollTop();var new_top=current_top+distance;this._setScrollTop(new_top);this.update();return this;},moveTo:function(destination){this._setScrollTop(destination);this.update();return this;},update:function(){var content_size=Vector2.getElementDimensions(this.content_div);var scroll_size=Vector2.getElementDimensions(this.scroll_div);if(content_size.y){if(content_size.y>=this.max_height&&scroll_size.y!=this.max_height){this.scroll_div.style.height=this.max_height+'px';}else if(content_size.y<this.max_height&&scroll_size.y!=content_size.y){this.scroll_div.style.height=content_size.y+'px';}}
this._isAtTop()?CSS.addClass(this.scroll_div,'at_top'):CSS.removeClass(this.scroll_div,'at_top');this._isAtBottom()?CSS.addClass(this.scroll_div,'at_bottom'):CSS.removeClass(this.scroll_div,'at_bottom');return this;}});ScrollWheel=function(){var _listenerAttached=false;var _callbacks=[];var _handle=function(event){var delta=0;event=$E(event);if(event.wheelDelta){delta=event.wheelDelta/120;if(ua.opera()){delta=-delta;}}else if(event.detail){delta=-event.detail/3;}
if(delta){for(var i=0;i<_callbacks.length;i++){if(!_callbacks[i](delta)){Event.kill(event);return;}}}};return{addHandler:function(callback){if(!_listenerAttached){if(window.addEventListener){window.addEventListener('DOMMouseScroll',_handle,false);}
window.onmousewheel=document.onmousewheel=_handle;_listenerAttached=true;}
_callbacks.push(callback);}};}();

function StatusEditor(root,profile_id){this.rootElem=root;this.profile_id=profile_id;this.statusInput=DOM.find(root,'input.status_input');this.placeholder=this.getPlaceholder();this.emptyValue=this.statusInput.value;this.initialValue='';this.location_id=false;this.locationEnabled=false;this._attach();var ix=StatusEditor.instances.push(this)-1;onunloadRegister(function(){delete StatusEditor.instances[ix];});}
StatusEditor.instances=[];StatusEditor.update=function(payload,time,initiator){StatusEditor.instances.forEach(function(editor){if(editor!=initiator){editor._onUpdate(payload,time);}});}
StatusEditor.poll=function(){new AsyncRequest().setURI('/ajax/poll_status.php').setMethod('GET').setReadOnly(true).setOption('bundle',true).setHandler(function(r){var payload=r.getPayload();StatusEditor.update(payload,null);}).send();}
StatusEditor.prototype._onUpdate=bagofholding;StatusEditor.prototype.getPlaceholder=function(){var placeholder=DOM.find(this.rootElem,'input.status_placeholder_input');return placeholder;}
StatusEditor.prototype._attach=function(){this.statusInput.listen('keypress',this.onkeypress.bind(this));this.statusInput.listen('blur',this.onInputBlur.bind(this));this.placeholder.listen('focus',this._onFocused.bind(this));var loc_anchors=DOM.scry(this.rootElem,'a.location_add_button');for(var i=0;i<loc_anchors.length;i++){loc_anchors[i].listen('click',this._onAddLocation.bind(this));show(loc_anchors[i]);}
if(this.locationEnabled){DOM.find(this.rootElem,'a.location_remove_button').listen('click',this._onRemoveLocation.bind(this));}}
StatusEditor.prototype.onkeypress=function(event){switch(event_get_keypress_keycode(event)){case KEYS.ESC:this.statusInput.value=this.emptyValue;this.statusInput.blur();break;case KEYS.RETURN:this.post();return $E(event).kill();}}
StatusEditor.prototype.onInputBlur=function(){var trimmed=trim(this.statusInput.value);if(this.isNonedit(trimmed)){this.reset();}}
StatusEditor.prototype.clear=function(){new AsyncRequest().setURI('/updatestatus.php').setData({'profile_id':this.profile_id,'clear':1}).setHandler(function(){this._onCleared();StatusEditor.update({'markup':''},null,this);}.bind(this)).send();return false;}
StatusEditor.prototype._onCleared=bagofholding;StatusEditor.prototype._onFocused=bagofholding;StatusEditor.prototype._onAddLocation=bagofholding;StatusEditor.prototype._onRemoveLocation=bagofholding;StatusEditor.prototype.setLocationSelector=function(selector){var location_handler=function(loc){if(this.location_id!==false){this.location_id=loc.id;}}.bind(this);this._locationSelector=selector;selector.setLocationHandler(location_handler);this.locationEnabled=true;}
StatusEditor.prototype.startEdit=function(value){this.statusInput.value=value;this.initialValue=value;this.placeholder.focus();}
StatusEditor.prototype.reset=function(){CSS.removeClass(this.rootElem,'placeholder_off');this.placeholder.getControl().setFocused(false);}
StatusEditor.prototype.isNonedit=function(text){return!text||(text==trim(this.emptyValue))||(this.initialValue&&(text==this.initialValue));}
StatusEditor.prototype.post=function(abtest_data,extra_post_params){var text=trim(this.statusInput.value);if(this.isNonedit(text)){return;}
this.statusInput.disabled=true;CSS.addClass(this.rootElem,'disabled');this.statusInput.blur();var data={'profile_id':this.profile_id,'status':text};var page_uri=URI.getRequestURI();if(page_uri.getPath()=='/profile.php'){data['profile']=true;}else if(page_uri.getPath()=='/home.php'||page_uri.getPath()=='/widgets/livefeed.php'){if(window.HomeFeed){var homefeed=HomeFeed.getInstance();if(homefeed){data['home_tab_id']=homefeed.tabId;}}}
if(abtest_data!=undefined&&abtest_data['test_name']&&abtest_data['action']){copy_properties(data,abtest_data);}else{data['test_name']='INLINE_STATUS_EDITOR';data['action']='OTHER_UPDATE';}
if(this.publish_all){data['publish_all']=1;}
if(this.app_id){data['app_id']=this.app_id;}
if(this.location_id){data['location_id']=this.location_id;}
if(extra_post_params){copy_properties(data,extra_post_params);}
new AsyncRequest().setURI('/updatestatus.php').setData(data).setFinallyHandler(function(){this.statusInput.disabled=false;CSS.removeClass(this.rootElem,'disabled');}.bind(this)).setHandler(function(r){this.reset();this.initialValue=this.statusInput.value;var payload=r.getPayload();this._onPosted(payload);StatusEditor.update(payload,null,this);}.bind(this)).send();}
StatusEditor.prototype._onPosted=bagofholding;function HomeStatusEditor(root,profile_id,is_friends){this.parent.construct(this,root,profile_id);if(this.showsStatusBody()){this.statusBody=DOM.find(root,'div.status_body');DOM.find(root,'a.status_clear_link').onclick=this.clear.bind(this);}
this.postButton=DOM.find(root,'input[type="submit"]');this.postButton.listen('click',this.post.shield(this));this.is_friends=is_friends;}
HomeStatusEditor.extend('StatusEditor');HomeStatusEditor.prototype.showsStatusBody=function(){return true;}
HomeStatusEditor.prototype.post=function(){this.statusMessage=this.statusInput.value;var action_message=this.is_friends?'FRIENDS_UPDATE':'HOME_UPDATE';this.parent.post({test_name:'INLINE_STATUS_EDITOR',action:action_message});}
HomeStatusEditor.prototype._onPosted=function(payload){this._onUpdate(payload);}
HomeStatusEditor.prototype._onUpdate=function(payload,time){var status=payload.markup;if(!status){this._onCleared();}
if(this.showsStatusBody()&&status){DOM.find(this.rootElem,'span.status_text').setContent(HTML(status));DOM.find(this.rootElem,'span.status_time').setContent(HTML(time||_tx("a moment ago&nbsp;")));var status_location=DOM.scry(this.rootElem,'span.status_location')[0];if(!payload.location_label){if(status_location){hide(status_location);}}else{if(!status_location){DOM.insertAfter(DOM.find(this.rootElem,'span.status_time'),$N('span',{className:'status_location'},[_tx("near {location}",{location:''}),$N('a',{href:payload.location_href,target:'_blank'},payload.location_label)]));}
show(status_location);}
if(CSS.hasClass(this.statusBody,'status_empty')){CSS.removeClass(this.statusBody,'status_empty');animation(this.statusBody).to('height','auto').from('0px').to('opacity',1).from(0).blind().show().duration(300).ease(animation.ease.end).go();}else{animation(this.statusBody).to('opacity',1).from(0).duration(300).go();}}
var homefeed=window.HomeFeed&&HomeFeed.getInstance();if(homefeed){if(payload.feed){var tabId=homefeed.tabId;if(tabId==payload.feed_tab){var container=document.createElement('div');CSS.setClass(container,'just_updated_status');container.style.display='none';DOM.setContent(container,HTML(payload.feed));var newsfeedWrapper=$('newsfeed_wrapper');var topStories=DOM.scry(newsfeedWrapper,'div.tab_top_stories')[0];newsfeedWrapper.prependContent(container);if(topStories&&topStories.firstChild&&CSS.hasClass(topStories.firstChild,'one_liner_cluster')){animation(topStories.firstChild).to('padding-top','0px').duration(300).go();}
animation(container).to('height','auto').from('0px').to('opacity',1).from(0).blind().show().duration(300).ease(animation.ease.end).go();}}
if(payload.top_status_stories&&homefeed.tabId==HomeFeed.TAB_TOP_STORIES){var newsfeedWrapper=$('newsfeed_wrapper');var topStories=DOM.scry(newsfeedWrapper,'div.tab_top_stories')[0];if(topStories&&topStories.firstChild&&CSS.hasClass(topStories.firstChild,'one_liner_cluster')){var old_status_stories=DOM.scry(topStories.firstChild,'div.status_story_wrapper');old_status_stories.forEach(function(story){story.remove();});DOM.prependContent(topStories.firstChild,HTML(payload.top_status_stories));}}}}
HomeStatusEditor.prototype._onCleared=function(){CSS.addClass(this.statusBody,'status_empty');animation(this.statusBody).to('height','0px').to('opacity',0).from(1).blind().hide().duration(300).ease(animation.ease.end).go();}
HomeStatusEditor.prototype._onAddLocation=function(target){CSS.addClass(this.rootElem,'location_composer_shown');var loc=this._locationSelector.getLocation();if(loc){this.location_id=loc.id;}
return false;}
HomeStatusEditor.prototype._onRemoveLocation=function(target){CSS.removeClass(this.rootElem,'location_composer_shown');this.location_id=null;return false;}
function LiveFeedWidgetStatusEditor(root,profile_id){this.parent.construct(this,root,profile_id);this.publish_line=ge('status_publish_all_line');this.publish_line_hover=false;if(this.publish_line){this.publish_line.listen('mouseover',function(){this.publish_line_hover=true;}.bind(this));this.publish_line.listen('mouseout',function(){this.publish_line_hover=false;}.bind(this));}}
LiveFeedWidgetStatusEditor.extend('HomeStatusEditor');LiveFeedWidgetStatusEditor.prototype.showsStatusBody=function(){return false;}
LiveFeedWidgetStatusEditor.prototype.setApplicationId=function(app_id){this.app_id=app_id;}
LiveFeedWidgetStatusEditor.prototype.setPublishAll=function(status){this.publish_all=status;}
LiveFeedWidgetStatusEditor.prototype._onFocused=function(value){this.parent._onFocused(value);if(this.publish_line){this.publish_line.addClass('show_publish_checkbox');}}
LiveFeedWidgetStatusEditor.prototype.reset=function(value){if(this.publish_line_hover){return;}
this.parent.reset();if(this.publish_line){this.publish_line.removeClass('show_publish_checkbox');}}
LiveFeedWidgetStatusEditor.prototype.post=function(abtest_data){if(ge('status_publish_all')){this.setPublishAll(ge('status_publish_all').checked);}
var homefeed=HomeFeed.getInstance();if(homefeed){homefeed.temporarilySuspendCdn(1);var tabId=homefeed.getTab();if(tabId==HomeFeed.TAB_LIVEWIDGET_EVERYONE&&!this.publish_all){this.showNotification();}}
this.parent.post();}
LiveFeedWidgetStatusEditor.prototype.showNotification=function(){var notificationLine=ge('status_notification_line');if(notificationLine){animation(notificationLine).to('opacity',1).from('opacity',0).show().duration(1000).checkpoint().duration(3000).checkpoint().to('opacity',0).from('opacity',1).duration(1000).hide().go();}}
LiveFeedWidgetStatusEditor.savePublishAllSetting=function(widgetAppId){if(ge('status_publish_all')){var publishAll=ge('status_publish_all').checked;new AsyncSignal('/ajax/live_feed_settings.php',{'publish_all':publishAll,'widget_app_id':widgetAppId}).send();}}
function ChatStatusEditor(root,profile_id,isEmpty){this.parent.construct(this,root,profile_id);this.statusBody=DOM.find(root,'div.chat_status_body');this.isEmpty=isEmpty;};ChatStatusEditor.prototype._attach=function(){this.parent._attach();DOM.find(this.rootElem,'a.status_clear_link').onclick=this.clear.bind(this);var edit_links=DOM.scry(this.rootElem,'a.status_edit_link');for(var i=0;i<edit_links.length;i++){edit_links[i].onclick=this.startEdit.bind(this,this.emptyValue);}}
ChatStatusEditor.prototype.reset=function(){this.parent.reset();CSS.removeClass(this.rootElem,'edit');if(this.isEmpty){CSS.addClass(this.statusBody,'status_empty');}else{CSS.removeClass(this.statusBody,'status_empty');}}
ChatStatusEditor.prototype.post=function(){this.statusMessage=this.statusInput.value;this.parent.post({test_name:'INLINE_STATUS_EDITOR',action:'CHAT_UPDATE'},{'chat':1});}
ChatStatusEditor.prototype._onUpdate=function(payload,time){var status=payload.markup;if(status){this.isEmpty=false;$('chat_su_text').setContent(HTML(status));$('chat_su_time').setContent(HTML(time||_tx("a moment ago&nbsp;")));}else{this.isEmpty=true;$('chat_su_text').setContent('');$('chat_su_time').setContent('');}
this.statusInput.value=this.emptyValue;this.reset();}
ChatStatusEditor.prototype._onCleared=function(){this._onUpdate({markup:''});}
ChatStatusEditor.prototype.startEdit=function(value){CSS.addClass(this.rootElem,'edit');this.parent.startEdit(value);}
ChatStatusEditor.prototype._onPosted=function(payload){this._onUpdate(payload);}
ChatStatusEditor.extend('StatusEditor');

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\/2248229svs74swwo.pkg.js"]); }