/*1307137655,169776065*/

if (window.CavalryLogger) { CavalryLogger.start_js(["eWxhv"]); }

function ChatTabActions(a){this._container=a;this._actions={};this._actionOrder=[];this._visibilityChanged=false;this._anyVisible=false;this.actionClass='action';}copy_properties(ChatTabActions.prototype,{anyVisible:function(){return this._anyVisible;},appendAction:function(c,b,a){this._addAction(c,b,a);this._actionOrder.push(c);return this;},prependAction:function(c,b,a){this._addAction(c,b,a);this._actionOrder.unshift(c);return this;},removeAction:function(a){delete this._actions[a];return this;},setVisible:function(b,c){var a=this._actions[b];if(a&&a.visible!=c){a.visible=c;this._visibilityChanged=true;}return this;},refresh:function(){if(this._visibilityChanged){this._render();this._visibilityChanged=false;return true;}return false;},_render:function(){DOM.empty(this._container);var c=this._actions;var b=this._actionOrder;this._anyVisible=false;var d=[];for(var e=0;e<b.length;++e){var a=c[b[e]];if(a.visible){if(this._anyVisible)d.push($N('span',{className:'divider'},HTML(' &middot; ')));d.push(a.create_element());this._anyVisible=true;}}DOM.appendContent(this._container,d);this._container.style.display=this._anyVisible?'block':'none';},_addAction:function(c,b,a){if(typeof b=='string'){var d=b;b=function(){return $N('a',{className:this.actionClass,href:'#'},d);}.bind(this);}this._actions[c]={create_element:function(){var e=b();Event.listen(e,'click',a);return e;},visible:false};this._visibilityChanged=true;}});
var ChatUserInfoManager=window.ChatUserInfoManager||(function(){var a=new Arbiter();var b={};var k=[];var f=false;var h=false;function c(){if(!k.length||f)return;f=true;e.defer();}function d(m,l){a.inform('fetch');new AsyncRequest().setURI(m).setData(l).setHandler(function(n){j(n,l.ids);}).setErrorHandler(i).setAllowCrossPageTransition(true).setMethod('GET').setReadOnly(true).send();}function e(){var l=k;k=[];d('/ajax/chat/user_info.php',{ids:l});}function g(){f=false;c();}function j(o,n){var p=n?Object.from(n):{};for(var m in o.payload){var r=o.payload[m];r.type='friend';ChatUserInfos[m]=r;var l=b[m];if(l){delete b[m];l.forEach(function(s){try{s(r);}catch(t){}});}delete p[m];}for(var q in p)delete b[q];g();a.inform('updated');}function i(){g();}return copy_properties(a,{get:function(m,l){l=l||bagofholding;if(ChatUserInfos[m]){l(ChatUserInfos[m]);}else{if(!b[m]){b[m]=[];k.push(m);c();}b[m].push(l);}},fetchAll:function(){if(!h){d('/ajax/chat/user_info_all.php',{viewer:Env.user});h=true;}}});})();
function TypingIndicator(a,b,d,c){this.id=a;this.input=b;this.source=d;this.callback=null;this.ignoreEnter=false;Arbiter.subscribe(PresenceMessage.getArbiterMessageType('typ'),this.onTyping.bind(this));this.currentState=TypingIndicator.INACTIVE;this.remoteState=TypingIndicator.INACTIVE;this.lastKeystrokeAt=null;this.notifyTimer=null;this.checkTimer=null;c=c||{};this.notifyDelay=c.notifyDelay||TypingIndicator.DEFAULT_NOTIFY_DELAY;this.keystrokeExpiry=c.keystrokeExpiry||TypingIndicator.DEFAULT_KEYSTROKE_EXPIRY;Event.listen(b,'keyup',this._update.bind(this));}copy_properties(TypingIndicator,{INACTIVE:0,TYPING:1,DEFAULT_NOTIFY_DELAY:1000,DEFAULT_KEYSTROKE_EXPIRY:7000});copy_properties(TypingIndicator.prototype,{setIgnoreEnter:function(a){this.ignoreEnter=a;},resetState:function(){presence.debug('typing: ** RESET **');this.currentState=TypingIndicator.INACTIVE;this.remoteState=TypingIndicator.INACTIVE;this.lastKeystrokeAt=null;clearTimeout(this.notifyTimer);this.notifyTimer=null;clearTimeout(this.checkTimer);this.checkTimer=null;},_notifyState:function(c){var d=this.id;var a=AvailableList.get(d);if(a&&c!=this.remoteState){this.remoteState=c;presence.debug('typing: notifyState('+c+')');if(!channelManager.iframeEverLoaded)return;var b={typ:c,to:d,source:this.source};new AsyncRequest().setHandler(this._onTypResponse.bind(this,d)).setErrorHandler(bagofholding).setData(b).setURI('/ajax/messaging/typ.php').setAllowCrossPageTransition(true).send();}},_onTypResponse:function(c,b){var a=b.getPayload()||{};if(a.offline)AvailableList.set(c,AvailableList.OFFLINE);},_update:function(event){var a=Event.getKeyCode(event);var b=this.currentState;if(!(this.ignoreEnter&&a===KEYS.RETURN))if(this.input.value.length===0){if(!(b==TypingIndicator.INACTIVE))this._transition(TypingIndicator.INACTIVE);}else if(b==TypingIndicator.TYPING){this._recordKeystroke();}else if(b==TypingIndicator.INACTIVE){this._transition(TypingIndicator.TYPING);this._recordKeystroke();}},_recordKeystroke:function(){this.lastKeystrokeAt=new Date();if(!this.checkTimer)this.checkTimer=this._checkTyping.bind(this).defer(this.keystrokeExpiry);},_checkTyping:function(){var a=this.lastKeystrokeAt.valueOf()+this.keystrokeExpiry;var b=new Date().valueOf();if(b>a){this._transition(TypingIndicator.INACTIVE);}else{clearTimeout(this.checkTimer);this.checkTimer=this._checkTyping.bind(this).defer(a-b+10);}},_transition:function(a){clearTimeout(this.checkTimer);this.checkTimer=null;this.lastKeystrokeAt=null;presence.debug('typing:'+this.currentState+' -> '+a);this.currentState=a;clearTimeout(this.notifyTimer);this.notifyTimer=this._notifyState.bind(this,a).defer(this.notifyDelay);},setCallback:function(a){this.callback=a;},onTyping:function(b,a){this.callback&&this.callback(a.obj);}});
function ChatThreadTab(a,e,f,b,d,c){this.parent.construct(this,a,e,f,b,d,c);}ChatThreadTab.extend('ChatTab');ChatThreadTab.prototype={rendererName:'chat-thread-tab',msgGroupRendererName:'chat-msg-thread-with-tooltip',hasThread:true,getPostType:function(){return 'thread';},handleBuddyAvailability:bagofholding,getAvailability:function(){return AvailableList.ACTIVE;},showSendAsMessageLinks:bagofholding,_messagingMarkThreadAsRead:function(a){Messaging.markAsRead(a);},getConversationURI:bagof(''),getProfileURI:function(){return Messaging.getInboxThreadURI(this.id);},setHasThread:function(a){this.hasThread=a;},getHasThread:function(){return this.hasThread;}};
function ChatGroupTab(a,b,d,f,e,c){this.parent.construct(this,a,b,d,d,e,c);this._facepileHandlers=[];}ChatGroupTab.extend('ChatTab');ChatGroupTab.prototype={_FACEPILE_UPDATE_INTERVAL:60000,rendererName:'chat-group-tab',msgGroupRendererName:'chat-msg-group-with-tooltip',getPostType:function(){return 'group';},focus:function(c,a,b){this.parent.focus(c,a,b);this._setUpdateFacepiles(true);},unfocus:function(){this.parent.unfocus();this._setUpdateFacepiles(false);},close:function(){this.parent.close();this._setUpdateFacepiles(false);this._removeFacepileHandlers();},_facepilesToken:null,_setUpdateFacepiles:function(a){if(a){if(!this._facepilesToken){this._facepilesToken=setInterval(this._sendFacepileRequest.bind(this),this._FACEPILE_UPDATE_INTERVAL);this._sendFacepileRequest();}}else if(this._facepilesToken){clearInterval(this._facepilesToken);this._facepilesToken=null;}},_sendFacepileRequest:function(){new AsyncRequest().setData({type:this.getPostType(),id:this.id}).setURI('/ajax/groups/chat/update_facepiles.php').setHandler(this._renderFacepile.bind(this)).send();},_renderFacepile:function(b){this._removeFacepileHandlers();var a=b.getPayload();if(a.response_html)DOM.setContent(this.chatInfo,HTML(a.response_html));if(a.facepile_click_info)a.facepile_click_info.each(function(d){var c=DOM.scry($(d.id),'a');if(c.length)this._facepileHandlers.push(Event.listen(c[0],"click",function(){chatDisplay.focusTab(d.uid,true,d.name,d.firstName);return false;}));}.bind(this));this.handleResize();},_removeFacepileHandlers:function(){while(this._facepileHandlers.length)this._facepileHandlers.pop().remove();},handleBuddyAvailability:bagofholding,showSendAsMessageLinks:bagofholding,playSound:bagofholding,_buildUI:function(){var b=this.parent._buildUI();var a=XHPTemplate.getNode(b,'reportLink');if(a)CSS.addClass(a,'hidden_elem');this.chatInfo=XHPTemplate.getNode(b,'facepileHolder');},getAvailability:function(){return AvailableList.ACTIVE;},mentionsUser:function(a){if(a.from==presence.user)return false;var b=a.msg.text;if(presence.alias!==""&&b.indexOf(presence.alias)!=-1)return true;if(presence.firstName!==""&&b.toLowerCase().indexOf(presence.firstName.toLowerCase())!=-1)return true;return false;},newMsg:function(a){if(this.mentionsUser(a))this.parent.playSound();this.parent.newMsg(a);},getConversationURI:bagof(''),getProfileURI:function(){return URI(env_get('www_base')).setPath('/home.php').setQueryData({sk:'group_'+this.id});}};
function ChatTab(a,c,e,b,g,d){this.inDock=!presence.inPopoutWindow;this.chatDisplay=a;this.id=c;this.name=e;this.tabRef='chatDisplay.tabs['+this.id+']';this.firstName=b;this.tabDisabled=false;this.numMissed=g||0;this.missedTime=d;this.focused=false;this.lastLogItem=null;this.historyLoaded=false;this.pendingSentMsgs=[];this.failedSentMsgs=[];this.historyRequestID=0;this.bounceAnimation=null;this.pendingNewRecipients=[];this.convTextEmoteProcessor=Emote.htmlEmote;this.minTextHeight=presence.inPopoutWindow?this.minTextHeightPopout:this.minTextHeightPopin;this.lastMessageAt=null;this.lastMessageHadOfflineResponse=false;this._handlers=[];this._subscriptions=[];this._buildUI();this.loadData();this._handleStatusChange();this._textareaListener=null;Arbiter.subscribe(['chat/visibility-changed','buddylist/availability-changed'],this._handleStatusChange.bind(this));if(this.inDock){var f=new NubController();f.init(this.tabHandle);f.subscribe('show',function(){if(this.chatDisplay.focused!=this.id)this.chatDisplay.focusTab(this.id);}.bind(this));f.subscribe('hide',function(){if(this.focused)this.chatDisplay.unfocus();}.bind(this));}this._subscriptions.push(Arbiter.subscribe('overflow-applied-to-body',this.scrollToBottom.bind(this)));this._messagingToken=MessagingEvents.subscribe('read',function(h,i){if(i.chat_ids&&i.chat_ids.contains(this.id)){this._clearMessagingMarkAsRead();if(i.mark_as_read)this._markRead();}}.bind(this));Sound.init();}ChatTab.mixin('Arbiter',{currentMsgGroup:null,rendererName:'chat-tab',msgGroupRendererName:'chat-msg-group',pendingToLogCompareWindow:60000,resendDelay:5000,handleWidth:150,popinWidth:258,popinHeight:250,popoutWidthOffset:180,flPopoutWidthOffset:200,minTextHeightPopin:13,minTextHeightPopout:32,maxTextHeight:77,msgBunchTime:300000,maxHandleLen:16,maxTitleLen:20,bounceDuration:50,isTabVisible:function(){return this.focused&&(presence.inPopoutWindow||!presence.poppedOut);},start:function(){this._popSendQueue();},restart:function(){if(this.focused){this.getHistory(true);}else this.historyLoaded=false;this.handleResize.bind(this).defer();},loadData:function(){if(this.chatDisplay.histories[this.id])this._setHistory(this.chatDisplay.histories[this.id]);},_onHistoryInitialHandler:function(a,b){if(a!=this.historyRequestID){presence.debug("tabs: got old history async, ignoring");return false;}return null;},_onHistoryResponse:function(a,l){var b=l.getPayload();var n=b.userInfo;var h=b.history;Chat.setUserInfo(this.id,n,b.fls);if(!h)return;var k=false;if(this.pendingSentMsgs.length>0&&h.length>0){var j=this.pendingSentMsgs[0];var c;for(c=h.length-1;c>=0;c--){var g=h[c];if(g.to!=this.chatDisplay.user){var m=Math.abs(j.time-g.time);if(m<this.pendingToLogCompareWindow&&j.text==g.msg.text){this._setMsgInfoMarkup(j.msgID,'');this.pendingSentMsgs.shift();this._popSendQueue();this.poppedSendQueue=true;break;}}}var e=h[h.length-1].time;for(c=0;c<this.pendingSentMsgs.length;c++){j=this.pendingSentMsgs[c];if(j.time<e)j.time=(++e);}}var i=this.chatDisplay.histories[this.id];if(i)if(h.length>0){var d=h[h.length-1];var f=d.time;for(var c=0;c<i.length;c++){var g=i[c];if(g.time>f)h.push(g);}}else h=i;this._setHistory(h);this.chatDisplay.histories[this.id]=h;if(a)if(!k)this._popSendQueue();},getHistory:function(a){var b=++(this.historyRequestID);new AsyncRequest().setInitialHandler(this._onHistoryInitialHandler.bind(this,b)).setHandler(this._onHistoryResponse.bind(this,a)).setErrorHandler(bagofholding).setMethod('GET').setReadOnly(true).setOption('suppressErrorAlerts',true).setData({type:this.getPostType(),id:this.id}).setURI('/ajax/chat/history.php').setAllowCrossPageTransition(true).send();},getPostType:function(){return 'friend';},_setHistory:function(e){this.lastLogItem=null;DOM.empty(this.chatConvContent);var g=0;var j=[];Array.prototype.push.apply(j,this.failedSentMsgs);Array.prototype.push.apply(j,this.pendingSentMsgs);var f=0;var a=false;for(var b=0;b<e.length;b++){var c=e[b];var d=this.getMessageTypeInfo(c.type);if(d.unknown)continue;if(!d.preserveHistory)a=true;for(;g<j.length;g++){var h=j[g];var i=this.getMessageTypeInfo(h.type);if(!i.preserveHistory)a=true;if(h.time>f&&h.time<=c.time){if(i.visible)this.renderMsg(presence.user,this.id,h.time,h,h.msgID,h.isError,h.infoMarkup);}else break;}if(d.msg){this.renderMsg(c.from,c.to,c.time,c.msg);}else if(d.videoMsg)this._renderVideoMsg(c.videoMsg,c.params);this.lastLogItem=c;f=c.time;}for(;g<j.length;g++){var h=j[g];if(this.getMessageTypeInfo(h.type).visible){this.renderMsg(presence.user,this.id,h.time,h,h.msgID,h.isError,h.infoMarkup);this.lastLogItem={type:h.type,from:presence.user,to:this.id,time:h.time,msg:h};}}this._toggleClearChatHistory(a);this.scrollToBottom();this.historyLoaded=true;},addParticipants:function(b){for(var a=0;a<b.length;a++)this.pendingNewRecipients.push(b[a]);return this;},clearHistory:function(){new AsyncRequest().setHandler(bagofholding).setErrorHandler(bagofholding).setData({clear_history_id:this.id}).setURI(this.chatDisplay.settingsURL).setAllowCrossPageTransition(true).send();this.failedSentMsgs=[];this.pendingSentMsgs=[];this._setHistory(this.chatDisplay.histories[this.id]=[]);},reportLinkAction:function(){Bootloader.loadComponents('dialog',(function(){var a=URI(this.chatDisplay.reportURL).addQueryData({id:this.id}).addQueryData({src:'top_report_link'});Dialog.bootstrap(a.toString(),null,false);}).bind(this));},_isCurrentPendingSend:function(a){return (this.pendingSentMsgs.length>0&&a==this.pendingSentMsgs[0].msgID);},_onSendServerDialogCancel:function(){if(!this._isCurrentPendingSend(msgID))return;this.failedSentMsgs.push(this.pendingSentMsgs.shift());this._popSendQueue();},_onSendInitialHandler:function(a){this.lastMessageHadOfflineResponse=false;},_onSendResponse:function(a,d){var b=d.getPayload();if(this._isCurrentPendingSend(a)){var c=this.pendingSentMsgs[0];c.asyncSuccess=true;}if(b&&b.warning){var e=this._renderMsgWarning(('title' in b.warning?b.warning.title+'<br />':'')+b.warning.body);this._setMsgInfoMarkup(a,e,'msg_warning');}},_onSendTransportError:function(a,b){if(!this._isCurrentPendingSend(a))return;if(!this.resendTimeout)this.resendTimeout=this._resendMessage.bind(this,a).defer(this.resendDelay);},_onSendError:function(c,e){if(!this._isCurrentPendingSend(c))return;var d=e.getPayload();var b=e.getError();var a=presence.getErrorDescription(e);if(b==1356003||b==1356022){this.showSendAsMessageLinks();}else if(b==1356002){this.lastMessageHadOfflineResponse=true;chatOptions.setVisibility(false);presence.doSync();}else if(b==1356008){a=d.error.title;ErrorDialog.show(d.error.title,d.error.body);}else if(b==1356026){a=d.errorText;(new Function(d.do_onload)).apply();}this._sendErrorAll(a);},showSendAsMessageLinks:function(){this.lastMessageHadOfflineResponse=true;AvailableList.set(this.id,AvailableList.OFFLINE);for(var b=0;b<this.pendingSentMsgs.length;b++){var e=this.pendingSentMsgs[b];var f=ge('msg_'+this.id+'_'+e.msgID);if(f){var a='rel="dialog"';var g=new URI(this.chatDisplay.messageURL).addQueryData({id:this.id,message:e.text}).toString();var c=presence.renderLink(g,_tx("enviar como un mensaje"),a);var d=_tx("{message} ({=send as a message})",{message:this._renderMsgHtmlize(e.text),'=send as a message':c});DOM.setContent(f,HTML(d));}}},_renderMsgWarning:function(b){var a=this.chatDisplay.templates['chat-msg-warning'].render();DOM.setContent(XHPTemplate.getNode(a,'message'),b);return a;},_renderMsgError:function(a){var b=this.chatDisplay.templates['chat-msg-error'].render();DOM.setContent(XHPTemplate.getNode(b,'message'),a);return b;},_sendErrorAll:function(a){var b=this._renderMsgError(a);var c=true;while(this.pendingSentMsgs.length){var d=this.pendingSentMsgs.shift();d.isError=true;if(c)d.infoMarkup=b;this._setMsgInfoMarkup(d.msgID,b,'msg_error');this.failedSentMsgs.push(d);c=false;b='';}},_createMessage:function(e,c){var b=rand32()+1;var f=presence.getTime();var a=new Date().getTime();if(this.lastLogItem&&f<this.lastLogItem.time)f=this.lastLogItem.time+1;var d={text:e,msgID:b,type:c,created:a,time:f,asyncSuccess:false,isError:false,errorMarkup:''};return d;},_flushSmallQueue:function(){if(this.pendingSentMsgs.length==1){var a=this.pendingSentMsgs[0];if(channelManager.iframeEverLoaded){this._sendMessage(a);}else if(!this.resendTimeout)this.resendTimeout=this._resendMessage.bind(this,a.msgID).defer(this.resendDelay);}},_updateChatActivity:function(b,a){this.lastLogItem={type:b.type,from:presence.user,to:this.id,time:b.time,msg:a};this.chatDisplay.chatActivityTime=(new Date()).getTime();presence.doSync();},sendInput:function(){var d=this.chatInput.value;if(!d||!d.match(/[^\s]/))return;this.chatInput.value='';var c=this._createMessage(d,'msg');this.pendingSentMsgs.push(c);this._flushSmallQueue();var b={text:d};var a=this.isUserScrolled();this.renderMsg(presence.user,this.id,c.time,b,c.msgID);this._toggleClearChatHistory(true);!a&&this.scrollToBottom();this._updateChatActivity(c,b);this.typingIndicator&&this.typingIndicator.resetState();},_sendMessage:function(b){b.time=presence.getTime();if(this.lastLogItem&&b.time<this.lastLogItem.time)b.time=this.lastLogItem.time+1;clearTimeout(this.resendTimeout);this.resendTimeout=null;var c=this._getSendData(b);channelManager.expectResponse();Arbiter.inform('chat/message-sent',c);var a=b.msgID;new AsyncRequest().setServerDialogCancelHandler(this._onSendServerDialogCancel.bind(this)).setInitialHandler(this._onSendInitialHandler.bind(this)).setHandler(this._onSendResponse.bind(this,a)).setErrorHandler(this._onSendError.bind(this,a)).setTransportErrorHandler(this._onSendTransportError.bind(this,a)).setData(c).setURI('/ajax/chat/send.php').setAllowCrossPageTransition(true).send();this.pendingNewRecipients=[];},_getSendData:function(e){var c=this.chatDisplay.histories[this.id];var d=null;var a=this.getAvailability();var h=a==AvailableList.OFFLINE;var g=a==AvailableList.IDLE;var f={msg_id:e.msgID,client_time:e.time,to:this.id,num_tabs:this.chatDisplay.numTabs,pvs_time:d,msg_text:e.text,to_offline:h,to_idle:g};if(this.pendingNewRecipients.length>0)f.new_recips=this.pendingNewRecipients;if(h){var b=AvailableList.getDebugInfo(this.id);f.overlay=b.overlay;f.overlayTime=b.overlayTime;f.presence=b.presence;f.presenceTime=presence.getTime();f.clock=(new Date()).getTime();}return f;},_popSendQueue:function(){if(this.pendingSentMsgs.length==0)return;var a=this.pendingSentMsgs[0];if(channelManager.iframeEverLoaded){this._sendMessage(a);}else if(!this.resendTimeout)this.resendTimeout=this._resendMessage.bind(this,a.msgID).defer(this.resendDelay);},_resendMessage:function(a){clearTimeout(this.resendTimeout);this.resendTimeout=null;if(this._isCurrentPendingSend(a))if(channelManager.iframeEverLoaded){this._sendMessage(this.pendingSentMsgs[0]);}else this.resendTimeout=this._resendMessage.bind(this,a).defer(this.resendDelay);},_setMsgInfoMarkup:function(d,c,a){var b=DOM.scry(this.chatConvContent,'#msg_'+this.id+'_'+d)[0];if(!b)return;DOM.insertAfter(b,c);a&&CSS.addClass(b,a);this.scrollToBottom();},tabHitAreaOnClick:function(){if(this.suppressHeaderCollapse)return;if(presence.inPopoutWindow){this.chatDisplay.focusTab(this.id,true,this.name,this.firstName);}else this.chatDisplay.toggleTab(this.id,true,this.name,this.firstName);this.chatDisplay.doStopBlinking();},tabXOnClick:function(a){this.chatDisplay.closeTab(this.id);this.chatDisplay.doStopBlinking();$E(a).kill();return false;},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){if(event.button!=0)return;this.chatDisplay.doStopBlinking();},chatConvOnMouseUp:function(){if(DOM.getSelection()=='')this.focusChatInput(true);},focusChatInput:function(a){if(this.isTabVisible())if(a||this.canStealFocus())this.chatInput.focus();},canStealFocus:function(){if(undefined!=document.activeElement){var a=document.activeElement;if(a){var b='INPUT'==a.nodeName||'TEXTAREA'==a.nodeName||('DIV'==a.nodeName&&a.contentEditable=="true");return !b;}}return false;},showAddTypeahead:function(b){var d='chat_add_'+(b?'canonical':'multichat')+'_';var f=ge(d+'typeahead');var c=XHPTemplate.getNode(this.tabHandle,d+'header');var a=XHPTemplate.getNode(this.tabHandle,d+'link');var e=XHPTemplate.getNode(f,d+'tab_id');CSS.show(f);c.replaceChild(f,a);e.value=this.id;},_buildUI:function(){var k=this.chatDisplay.templates[this.rendererName].render();DOM.setContent(XHPTemplate.getNode(k,'name'),this.name);var m=XHPTemplate.getNode(k,'titlebarLink');m.href=this.getProfileURI();DOM.setContent(m,this.name);var b=XHPTemplate.getNode(k,'chatConv');var f=XHPTemplate.getNode(k,'closeButton');var c=XHPTemplate.getNode(k,'input');this._handlers.push(Event.listen(b,'mousedown',this.chatConvOnMouseDown.bind(this)),Event.listen(b,'mouseup',this.chatConvOnMouseUp.bind(this)),Event.listen(f,'click',this.tabXOnClick.bind(this)),Event.listen(c,'keydown',this.inputKeyDown.bind(this)),Event.listen(c,'click',this.chatDisplay.doStopBlinking.bind(this.chatDisplay)));var i=XHPTemplate.getNode(k,'maximizeButton');if(i)this._handlers.push(Event.listen(i,'click',this.maximizeOnClick.bind(this)));this.tabHandle=k;this.statusEl=XHPTemplate.getNode(k,'status');this.tabCount=XHPTemplate.getNode(k,'numMessages');this.chatWrapper=XHPTemplate.getNode(k,'chatWrapper');Dock.setFlyoutContentHeight(this.chatWrapper,285);this.chatConv=b;this.chatConvContent=XHPTemplate.getNode(k,'conversation');this.chatInput=c;var d=ge('fbDockChatTabs');DOM.prependContent(d,this.tabHandle);if(Chat.isFeatureAvailable('typ'))this.typingIndicator=new TypingIndicator(this.id,c,'chat');this._updateNumMissedDisplay();var n=XHPTemplate.getNode(k,'videoCallLink');if(n){this._handlers.push(Event.listen(n,'click',function(){VideoEvents.inform(VideoEvents.START_CALL_UI,{idTarget:this.id});this.focused&&this.chatDisplay.unfocus();return false;}.bind(this)));this._callIncomingToken=VideoEvents.subscribe(VideoEvents.CALL_INCOMING,function(o,p){if(p.idTarget==this.id&&this.focused)this.chatDisplay.unfocus();}.bind(this));}if(ChatConfig.get('bigbird_ui')){var h=XHPTemplate.getNode(k,'dropdown');if(h){Toggler.createInstance(h).setSticky(false);var g=XHPTemplate.getNode(k,'conversationLink');if(g){g.href=Messaging.getUserThreadURI(this.id);this._handlers.push(Event.listen(g,'click',this.unfocus.bind(this)));}var j=XHPTemplate.getNode(k,'reportSpamLink');if(j)this._handlers.push(Event.listen(j,'click',this.reportLinkAction.bind(this)));var e=XHPTemplate.getNode(k,'clearWindowLink');if(e)this._handlers.push(Event.listen(e,'click',this.clearHistory.bind(this)));}var l=XHPTemplate.getNode(k,'titlebarCloseButton');this._handlers.push(Event.listen(l,'click',this.tabXOnClick.bind(this)));}else{var a=XHPTemplate.getNode(k,'actions');this.actions=new ChatTabActions(a);this.actions.appendAction('clearHistory',_tx("Despejar ventana",{Chat:_tx("Chat")}),this.clearHistory.bind(this));if(!Chat.isFeatureAvailable('report')&&this instanceof ChatTab)this.actions.appendAction('reportLink',_tx("Informar"),this.reportLinkAction.bind(this));this.actions.refresh();}return k;},maximizeOnClick:function(){var a=this.getConversationURI();if(a){goURI(a);this.focused&&this.chatDisplay.unfocus();}return false;},getConversationURI:function(){return Messaging.getUserThreadURI(this.id);},getProfileURI:function(){return URI(env_get('www_base')).setPath('/profile.php').setQueryData({id:this.id});},show:function(){CSS.show(this.tabHandle);},hide:function(){CSS.hide(this.tabHandle);},inputKeyDown:function(event){this.chatDisplay.doStopBlinking();if(!this._textareaListener){var c=DataStore.get(this.chatInput,'DOMControl');this._textareaListener=c.subscribe('resize',this.handleResize.bind(this));}switch(event.keyCode){case KEYS.RETURN:if(!event.shiftKey){this.sendInput();event.prevent();}break;case KEYS.ESC:this.chatDisplay.closeTab(this.id);event.prevent();return false;case KEYS.TAB:if(presence.inPopoutWindow){var b=event.shiftKey;var a=this.chatDisplay.getNextTabId(this.id,b);if(a>0){this.chatDisplay.focusTab(a,true);event.prevent();return false;}}break;}},trimName:function(a){var b=this.name;if(b.length>a)b=b.substring(0,a-2)+'...';return b;},_handleStatusChange:function(){var b=Chat.isOnline();var a=b?this.getAvailability():AvailableList.OFFLINE;var c;if(b){if(!a)if(Chat.isFeatureAvailable('titan')){var d=ChatUserInfos[this.id]||{};switch(d.gender){case GenderConst.FEMALE_SINGULAR:case GenderConst.FEMALE_SINGULAR_GUESS:c=_tx("{name} is offline. Your messages will be sent to her inbox.",{name:this.firstName});break;case GenderConst.MALE_SINGULAR:case GenderConst.MALE_SINGULAR_GUESS:c=_tx("{name} est\u00e1 sin conexi\u00f3n. Los mensajes se enviar\u00e1n a su bandeja de entrada.",{name:this.firstName});break;default:c=_tx("{name} is offline. Your messages will be sent to their inbox.",{name:this.firstName});break;}}else c=_tx("{name} est\u00e1 desconectado\/a.",{name:this.firstName});}else c=_tx("No est\u00e1s conectado.");if(c){DOM.setContent(this.statusEl,c);CSS.show(this.statusEl);this.scrollToBottom();}else CSS.hide(this.statusEl);if(b&&a){this._enableTab(a==AvailableList.IDLE);}else this._disableTab();},_enableTab:function(a){this.tabDisabled=false;if(presence.inPopoutWindow){CSS.removeClass(this.popoutTab,'disabled');CSS.conditionClass(this.popoutTab,'idle',a);}CSS.removeClass(this.tabHandle,'disabled');CSS.conditionClass(this.tabHandle,'idle',a);},_disableTab:function(){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');},handleResize:function(){var a=this.isUserScrolled();Dock._resizeNubFlyout(this.tabHandle,true);!a&&this.scrollToBottom();},isUserScrolled:function(){return (this.chatConv.scrollHeight>this.chatConv.scrollTop+this.chatConv.clientHeight);},scrollToBottom:function(){if(!this.focused)return;this.chatConv.scrollTop=this.chatConv.scrollHeight;},unfocus:function(){if(!this.focused)return;this.focused=false;if(this.inDock){Dock.hide(this.tabHandle);}else CSS.removeClass(this.tabHandle,'focused');this.inform('unfocus');},focus:function(c,a,b){if(this.focused)return;this.focused=true;this._isFragileMode=false;this._markRead();if(this.inDock){Dock.show(this.tabHandle);}else CSS.addClass(this.tabHandle,'focused');if(!c)this._onFocusUIActions(b);if(!this.historyLoaded)this.getHistory(false);this.inform('focus');},_onFocusUIActions:function(a){this.handleResize();this.scrollToBottom();this.focusChatInput(a);},_startBounce:function(){var a=-8;this.bounceAnimation=animation(this.tabCount).to('top',-16).duration(this.bounceDuration+40).checkpoint().to('top',a).duration(this.bounceDuration).checkpoint().to('top',-16).duration(this.bounceDuration+40).checkpoint().to('top',a).duration(this.bounceDuration).checkpoint().to('top',-12).duration(this.bounceDuration).checkpoint().to('top',-10).duration(this.bounceDuration).checkpoint().to('top',a).duration(this.bounceDuration).checkpoint().go();},_stopBounce:function(){if(this.bounceAnimation){this.bounceAnimation.stop();this.bounceAnimation=null;}},close:function(){if(this.inDock)Dock.unregisterNubController(this.tabHandle);while(this._handlers.length)this._handlers.pop().remove();this._subscriptions.each(Arbiter.unsubscribe);MessagingEvents.unsubscribe(this._messagingToken);this._callIncomingToken&&VideoEvents.unsubscribe(this._callIncomingToken);if(this._textareaListener){var a=DataStore.get(this.chatInput,'DOMControl');a.unsubscribe(this._textareaListener);delete this._textareaListener;this._textareaListener=null;}this.tabHandle.parentNode.removeChild(this.tabHandle);},newTyping:function(c){var b=c.from;var e=c.to;var f=c.st;var a=c.fl;if(!Chat.isFeatureAvailable('typ')){return;}else if((new Date()-this.lastMessageAt)<this.typingIndicator.notifyDelay)return;presence.debug('typing from '+b+': '+f);var d=(f==TypingIndicator.TYPING)&&(this.numMissed==0);if(e!=this.id){if(presence.inPopoutWindow)CSS.conditionClass(this.popoutTab,'typing',d);CSS.conditionClass(this.tabHandle,'typing',d);AvailableList.set(this.id,AvailableList.ACTIVE,a);}},_isChatMessage:function(a){return this.getMessageTypeInfo(a.type).user;},newMsg:function(k){var c=k.from;var o=k.to;var p=k.type;var i=k.msg;var n=i.time;var a=i.clientTime;var j=i.msgID;var l=true;this.lastMessageAt=new Date();var d=this.chatDisplay.getHistory(this.id,true);var h=null;for(var f=d.length-1;f>=0;f--)if(this._isChatMessage(d[f])){h=d[f];break;}if(h&&n<=h.time){var b=false;for(var f=0;f<d.length;f++)if(this._isChatMessage(d[f])&&n==d[f].time){b=true;break;}if(b){presence.warn('tabs: already had this msg');return;}for(var f=d.length-1;f>=0;f--){var e=d[f];if(this._isChatMessage(e)&&(e.to!=o||(!e.msg.clientTime||e.msg.clientTime<a)))break;}presence.warn('tabs: merging new msg due to out-of-order server timestamp');if(f==d.length-1){d.push(k);}else{d.splice(f+1,0,k);this._setHistory(d);l=false;}}else this.chatDisplay.histories[this.id].push(k);if(c!=this.chatDisplay.user){var m=this.chatDisplay.isSquelched()||this.chatDisplay.isSquelchedTab(this.id);this._isFragileMode=false;if(m){this._markRead(n);}else{if(this.focused){this._markRead(n);}else this._markUnread(n);this._messagingMarkAsRead();}if(presence.inPopoutWindow)CSS.removeClass(this.popoutTab,'typing');CSS.removeClass(this.tabHandle,'typing');}else{this._markRead();if(this._removeDuplicatePendingMessage(j))l=false;}l=this.getMessageTypeInfo(p).visible&&l;if(l){var g=this.isUserScrolled();this.renderMsg(c,o,n,i);this._toggleClearChatHistory(true);!g&&this.scrollToBottom();this.lastLogItem=k;}},_removeDuplicatePendingMessage:function(b){for(var a=0;a<this.pendingSentMsgs.length;a++)if(b==this.pendingSentMsgs[a].msgID){var c=this.pendingSentMsgs.splice(a,1);this._popSendQueue();this.chatDisplay.reportLatency(new Date().getTime()-c[0].created);return true;}return false;},getInputElem:function(){return this.chatInput;},_messagingMarkAsRead:function(){if(!Chat.isFeatureAvailable('titan'))return;this._clearMessagingMarkAsRead();var a=chatOptions.getSetting('idle_cutoff');if(a&&UserActivity.isActive(a)){this._messagingMarkThreadAsRead(this.id);}else this._pendingMessagingMarkAsRead=UserActivity.subscribe(this._messagingMarkAsRead.bind(this));},_messagingMarkThreadAsRead:function(a){Messaging.markUserThreadAsRead(a);},_clearMessagingMarkAsRead:function(){if(this._pendingMessagingMarkAsRead){UserActivity.unsubscribe(this._pendingMessagingMarkAsRead);delete this._pendingMessagingMarkAsRead;}},_markRead:function(){this._updateNumMissed(0);this._stopBounce();},_markUnread:function(a){this._updateNumMissed(this.numMissed+1,a);this._startBounce();this.playSound();},squelch:function(){this._markRead();},_updateNumMissed:function(a,b){if(a==this.numMissed||(b&&b<=this.missedTime))return;if(a>99)a=99;this.numMissed=a;this.missedTime=b;this._updateNumMissedDisplay();},_updateNumMissedDisplay:function(){DOM.setContent(this.tabCount,this.numMissed);if(this.inDock)window.chatTabSlider&&chatTabSlider.updateMissedCount();CSS.conditionClass(this.tabHandle,'highlight',this.numMissed>0);CSS.conditionShow(this.tabCount,this.numMissed>0);},_checkDateBreak:function(d){var c=new Date();c.setTime(d);var b=new Date();if(this.lastLogItem)b.setTime(this.lastLogItem.time);var a=null;if(!this.lastLogItem||c.getDate()!==b.getDate()||c.getMonth()!==b.getMonth()){a=this.chatDisplay.templates['chat-msg-date-break'].render();DOM.setContent(a,renderDate(c,!presence.inPopoutWindow));DOM.appendContent(this.chatConvContent,a);this.currentMsgGroup=null;}},_renderVideoMsg:function(g,h){if(presence.inPopoutWindow)return;var e=this.chatDisplay.templates['chat-video-msg'].render();var f=XHPTemplate.getNode(e,'message');var k=XHPTemplate.getNode(e,'timestamp');var a=true;var j=h.start_time||presence.getTime();var i=this.chatDisplay.renderServerTime(j);this._checkDateBreak(j);DOM.setContent(k,i);switch(g){case 'missed-call':Bootloader.loadComponents('VideoChatPlugin',function(){if(ChatConfig.get('video.can_call',false)&&VideoChatPlugin.isSupported()){var l=$N('a',{href:'#',className:'callBackLink'},_tx("Volver a llamar"));Event.listen(l,'click',(function(){VideoEvents.inform(VideoEvents.START_CALL_UI,{idTarget:this.id});return false;}).bind(this));DOM.setContent(f,[_tx("Llamada perdida"),HTML(' &middot; '),l]);}DOM.appendContent(this.chatConvContent,e);}.bind(this));a=false;break;case 'connected-call':var d=_tx("Llamada con {firstname}",{firstname:this.firstName});DOM.setContent(f,HTML(d));break;case 'caller-history':var c=_tx("Se ha llamado a {firstname}",{firstname:this.firstName});DOM.setContent(f,HTML(c));break;case 'callee-history':var b=_tx("{firstname} te ha llamado",{firstname:this.firstName});DOM.setContent(f,HTML(b));break;}a&&DOM.appendContent(this.chatConvContent,e);},renderMsg:function(g,v,u,m,p,i,d){this._checkDateBreak(u);var k=this.chatDisplay.templates['chat-msg'].render();k.id='msg_'+this.id+'_'+p;var h=m.text.substr(0,4)=='?OTR';var s=false;CSS.conditionClass(k,'cyphertext',h);if(h){DOM.setContent(k,_tx("[mensaje encriptado]"));}else{var n=[];var o=m.text;var t;var q;var j;if(m.spoof){q=new RegExp('^\\s*<([^<>]+?)>\\s+');j=o.match(q);if(j){o=o.substr(j[0].length);d=this._renderMsgWarning(j[1]);}}if(m.truncated||m.forward||m.attachment){q=new RegExp('(?:\\.{3}\\s+)?'+'(?:<([^<>]+?)>\\s+)?'+'(?:<([^<>]+?)>\\s+)?'+'(\\S+)\\s*$');j=o.match(q);if(j){o=o.substr(0,o.lastIndexOf(j[0]));var t=j[3];if(m.truncated){n.push(HTML('&hellip; '));var l=$N('a',{href:t,className:'more'},_tx("Ver todo"));n.push(l);}if(m.forward){var f=this.chatDisplay.templates['chat-msg-forward'].render();f.href=t;var e=XHPTemplate.getNode(f,'label');DOM.setContent(e,j[1]);n.push($N('div',f));s=true;}if(m.attachment){var b=this.chatDisplay.templates['chat-msg-attachment'].render();b.href=t;var a=XHPTemplate.getNode(b,'label');DOM.setContent(a,j[2]||j[1]);n.push($N('div',b));s=true;}}}if(!s&&URLScraper.match(o))s=true;if(!this.chatDisplay.user||this.chatDisplay.user==g)s=false;n.unshift(HTML(this._renderMsgHtmlize(o)));DOM.setContent(k,n);}var c=this.getCurrentMsgGroup(g,v,u);if(s&&Chat.isFeatureAvailable('report')){CSS.show(XHPTemplate.getNode(c,'reportLinkWithDot'));var r=URI(this.chatDisplay.reportURL).addQueryData({id:g}).addQueryData({src:'timestamp_report_link'});reportLink=XHPTemplate.getNode(c,'reportLink');reportLink.setAttribute('href',r);}this.addMessageToGroup(k,c);d&&this.addMessageToGroup(d,c);},_renderMsgHtmlize:function(a){return html_hyperlink(a||'',this._processStyledText.bind(this,this.convTextEmoteProcessor),null,true);},newVideoMsg:function(f,d){var e=d.time||presence.getTime();var a=this.chatDisplay.getHistory(this.id,true);var c={type:'videochat',videoMsg:f,time:e,params:d};a.push(c);if(f==='missed-call')if(this.focused){this._markRead(e);this._messagingMarkAsRead();}else this._markUnread(e);var b=this.isUserScrolled();this._renderVideoMsg(f,d);this._toggleClearChatHistory(true);!b&&this.scrollToBottom();this.lastLogItem=c;},_processStyledText:function(b,a){return b(a).replace(/\b_([^_\*]+)_\b/g,'<u>$1</u>').replace(/(\s|^)\*([^_\*]+)\*(?=$|\s)/g,'$1<b>$2</b>');},playSound:function(){if(Chat.isFeatureAvailable('sound')&&chatOptions.getSetting('sound'))Sound.play('/sound/pling.mp3',true);},getMessageTypeInfo:function(a){if(a=='videochat'){return {visible:true,user:false,preserveHistory:true,videoMsg:true};}else return {visible:true,user:true,preserveHistory:false,msg:true};},addMessageToGroup:function(b,a){DOM.appendContent(XHPTemplate.getNode(a,'messages'),b);},getCurrentMsgGroup:function(a,i,g){if(!this.currentMsgGroup||!this.lastLogItem||this.lastLogItem.from!=a||(g-this.lastLogItem.time)>this.msgBunchTime){var c=this.chatDisplay.templates[this.msgGroupRendererName].render();var d=XHPTemplate.getNode(c,'profileLink');var e=XHPTemplate.getNode(c,'profilePhoto');var f=function(j){if(CSS.hasClass(d,'profileTooltipLink')){TooltipLink.setTooltipText(d,j);}else if(j){e.setAttribute('title',j);}else e.removeAttribute('title');};var b=a==this.chatDisplay.user;!b&&f('');ChatUserInfoManager.get(a,function(j){e.src=j.thumbSrc;d.setAttribute('href',this.chatDisplay.profileURL+'?id='+a);!b&&f(j.name||this.name);}.bind(this));var h=this.chatDisplay.renderServerTime(g);DOM.setContent(XHPTemplate.getNode(c,'timestamp'),h);DOM.appendContent(this.chatConvContent,c);this.currentMsgGroup=c;}return this.currentMsgGroup;},getAvailability:function(){return AvailableList.get(this.id);},_isFragileMode:false,setFragileMode:function(){this._isFragileMode=true;this._subscriptions.push(Arbiter.subscribe('page_transition',this._removeFragileTab.bind(this)));},_removeFragileTab:function(){if(!this._isFragileMode)return;this.chatDisplay.closeTab(this.id);},_toggleClearChatHistory:function(a){if(this.actions)this.actions.setVisible('clearHistory',a).setVisible('reportLink',a).refresh();}});function renderDate(a,e){if(e){var f=new Date();f.setHours(0);f.setMinutes(0);f.setSeconds(0);f.setMilliseconds(0);var b=24*60*60*1000;var c=f.getTime()-a.getTime();if(c<=0){return _tx("Hoy");}else if(c<b)return _tx("Ayer");}var d='';switch(a.getMonth()){case 0:d=_tx("enero");break;case 1:d=_tx("febrero");break;case 2:d=_tx("marzo");break;case 3:d=_tx("abril");break;case 4:d=_tx("mayo");break;case 5:d=_tx("junio");break;case 6:d=_tx("julio");break;case 7:d=_tx("agosto");break;case 8:d=_tx("septiembre");break;case 9:d=_tx("octubre");break;case 10:d=_tx("noviembre");break;case 11:d=_tx("diciembre");break;}return _tx("{date} de {month}",{month:d,date:a.getDate()});}onloadRegister(function(){if(ua.firefox()){var a=function(){return CSS.getStyle(document.body,'overflowX')+' '+CSS.getStyle(document.body,'overflowY');};var b=a();document.body.addEventListener('DOMAttrModified',function(event){if(event.getTarget()===document.body&&(event.attrName==='class'||event.attrName==='style')){var c=a();if(c!==b){b=c;Arbiter.inform('overflow-applied-to-body');}}},false);}});
function ChatDisplay(f,c,a,d,e,b,g){this.histories=f;this.everSentMessage=c;this.user=presence.user;var h=env_get('www_base');this.profileURL=h+'profile.php';this.messageURL=h+'ajax/messaging/composer.php';this.settingsURL='/ajax/chat/settings.php';this.tabsURL='/ajax/chat/tabs.php';this.reportURL='/ajax/chat/report.php';this.gatedFeatures=e;this.templates=g;this.controllers=copy_properties({friend:'ChatTab',group:'ChatGroupTab',thread:'ChatThreadTab'},b);this.useUICookieCache=e.ui_cookie_cache;this.renderServerTime=this.gatedFeatures['24h_times']?this._renderServerTime24hr:this._renderServerTime12hr;this.jabberSquelchInterval=300000;this._squelchUntil=null;this._squelchedIds={};this._reportedLatencies=0;this._init(a,d);}ChatDisplay.prototype={blinkTime:1500,initialBlinkDelay:3000,maxNumTabs:20,_init:function(a,b){this.loaded=false;this.tabs={};this.tabList=[];this.numTabs=0;this.lastFocused=null;this.newMsgNames=[];this.newMsgNamesIndex=0;this.blinkingTimer=null;this.chatActivityTime=0;if(this.useUICookieCache){this.uiChangeTime=0;this.uiCookieCacheTime=(Env.rep_lag+presence.sitevars.CHAT_UI_COOKIE_CACHE_WINDOW)*1000;}this.initialFocusedChat=b;this.initialActiveChats=a;presence.registerStateStorer(this._store.bind(this));presence.registerStateLoader(this._load.bind(this));var c=['unfocus_chat','focus_chat','close_chat','group_msg','thread_msg','msg','typ','video','chat_event','buddylist_overlay'].map(PresenceMessage.getArbiterMessageType);Arbiter.subscribe(c,this._handlePresenceMessage.bind(this));Arbiter.subscribe(PresenceMessage.STARTED,this.start.bind(this));Arbiter.subscribe(PresenceMessage.SHUTDOWN,this.shutdown.bind(this));Arbiter.subscribe(PresenceMessage.RESTARTED,this.restart.bind(this));Arbiter.subscribe(PresenceMessage.WINDOW_RESIZED,this.handleResize.bind(this));Arbiter.subscribe('channel/invalid_history',this.handleInvalidHistory.bind(this));Event.listen(window,'focus',this.onWindowFocus.bind(this));Event.listen(window,'blur',this.onWindowBlur.bind(this));if(!presence.inPopoutWindow){var d=$('fbDockChatTabs');Toggler.createInstance(d);}},onWindowFocus:function(){this.isWindowFocused=true;this.doStopBlinking();},onWindowBlur:function(){this.isWindowFocused=false;},start:function(){for(var a in this.tabs)this.tabs[a].start();},shutdown:function(){this._stopBlinking();},restart:function(){for(var a in this.tabs)this.tabs[a].restart();},loadInitialUserInfo:function(c,d,a,b,e){if(ChatUserInfos[c])return;ChatUserInfos[c]={name:d,firstName:a,thumbSrc:'',gender:b||GenderConst.UNKNOWN,type:e||'friend'};},_loadInitialTabs:function(a,d){if(!hasArrayNature(a)){var l=[];for(var b in a)l.push(copy_properties(a[b],{i:b}));a=l;}for(var e=0,g=a.length;e<g;e++){var k=a[e];var f=k.i;if(this.tabs[f])continue;var i,c,m;if(f in ChatUserInfos){i=ChatUserInfos[f].name;c=ChatUserInfos[f].firstName;m=ChatUserInfos[f].type;}else{i=k.n;if(!i)continue;c=k.fn||getFirstName(i);m=k.type||'friend';}var j=k.m||0;var h=k.t||0;this.createTab(m,f,i,c,j,h);}if(presence.inPopoutWindow&&!d&&a.length)d=a[0].i;if(d&&(d!=this.focused))this._focusTab(d);window.chatTabSlider&&chatTabSlider.addTab();},load:function(){var a=Arbiter.subscribe('buddylist/initialized',function(){Arbiter.unsubscribe(a);this._load(presence.state);Arbiter.inform('chat-display/loaded',this,Arbiter.BEHAVIOR_PERSISTENT);}.bind(this));},loadTabFragile:function(b,c,a,d){if(presence.isOnline()&&!this.tabs[b]){this._loadInitialTabs([{i:b,n:c,fn:a,type:d}]);this.tabs[b].setFragileMode();window.EagleEye&&EagleEye.log('chat-tab',{id:b});}},_load:function(c){var a=false;if(c){if(this.blinkingTimer&&c.sb)this._stopBlinking();this._squelchUntil=c.sq;this.chatActivityTime=verifyNumber(c.ct)*1000;if(this.useUICookieCache){var b=presence.getTime();this.uiChangeTime=Math.max(this.uiChangeTime,verifyNumber(c.uct)*1000);if(!this.loaded)if(b-this.uiChangeTime<this.uiCookieCacheTime){if(b-c.ut>60*60*1000)c.t.each(function(d){d.m=0;});presence.debug('chatDisplay: loading tabs from cookie cache');this._loadInitialTabs.bind(this,c.t,c.f).defer();a=true;}}}if(!this.loaded&&!a){presence.debug('chatDisplay: loading tabs from server state');this._loadInitialTabs.bind(this,this.initialActiveChats,this.initialFocusedChat).defer();this.initialFocusedChat=this.initialActiveChats=false;}this.loaded=true;},_store:function(d){d.ct=Math.floor(this.chatActivityTime*.001);d.sb=(this.blinkingTimer==null)?1:0;var e=this.getSquelchUntil();if(e!==null)d.sq=e;if(this.useUICookieCache){d.t=[];d.f=null;d.uct=0;var c=presence.getTime();if(c-this.uiChangeTime<this.uiCookieCacheTime){for(var a=0,b=this.tabList.length;a<b;a++){var g=this.tabList[a];var f={i:g.id,n:g.name,m:g.numMissed};if(g.type=='group'||g.firstName!=getFirstName(g.name))f.fn=g.firstName;d.t.push(f);}d.f=this.focused;d.uct=Math.floor(this.uiChangeTime*.001);}}return d;},handleResize:function(){if(!this.focused)return;var a=this.tabs[this.focused];a.handleResize();},handleInvalidHistory:function(){var a=this.focused&&this.tabs[this.focused];if(a)a.getHistory(true);},_sendTabStateChange:function(a){a.window_id=presence.windowID;new AsyncRequest().setURI(this.tabsURL).setData(a).setHandler(this._onCheckTabStateChangeResponse.bind(this,a)).setErrorHandler(bagofholding).setAllowCrossPageTransition(true).send();},_sendDeferredTabStateChange:function(a){clearTimeout(this._deferredTabStateChange);this._deferredTabStateChange=this._sendTabStateChange.bind(this,a).defer();},_onCheckTabStateChangeResponse:function(b,d){var a=(b&&b.focus_chat)||null;var e=a&&AvailableList.get(a);var c=d.getPayload();if(c&&c.overlay){AvailableList.addLegacyOverlay(c.overlay);if(e&&!AvailableList.get(a))presence.error("presence:ol_on_to_off:id="+a);}},reloadTabs:function(){for(var a in this.tabs)this.tabs[a].loadData();},_closeTab:function(a){if(!this.tabs[a])return;var c=this.tabList.indexOf(this.tabs[a]);if(this.focused==a)if(presence.inPopoutWindow){var b=this.tabList.length;var d=this.tabList[((c+(c?-1:1))+b)%b].id;if(d!=a){this.focusTab(d);}else this.focused=null;}else this.focused=null;this.tabs[a].close();this.tabList.splice(c,1);delete this.tabs[a];this.numTabs--;Arbiter.inform('chat/conversation-closed',{id:a});window.chatTabSlider&&chatTabSlider.close();},uiChanged:function(){if(this.useUICookieCache){this.uiChangeTime=presence.getTime();presence.doSync();}},closeTab:function(a){this._closeTab(a);this._sendTabStateChange({close_chat:a});this.uiChanged();},_unfocus:function(b){var a=this.focused;if(!a||(b&&a!=b))return false;this.focused=null;if(presence.inPopoutWindow)this.tabs[a].deselectPopoutChat();this.tabs[a].unfocus();return true;},unfocus:function(a,b){if(this._unfocus(a)&&b!==false){this._sendDeferredTabStateChange({unfocus_chat:1});this.uiChanged();}this.lastFocused=null;},unfocusNoSync:function(){this._unfocus();},refocus:function(){if(!this.lastFocused||!this.tabs[this.lastFocused])return null;this._focusTab(this.lastFocused);},_focusTab:function(d,b,e,a,f){if(d==this.focused)return this.tabs[d];if(!this.tabs[d]){if(typeof e=='undefined')if(ChatUserInfos[d]&&ChatUserInfos[d].name){e=ChatUserInfos[d].name;a=ChatUserInfos[d].firstName;}else{presence.warn("chat:tab creation aborted:couldn't create tab "+d+" since no name is specified");return null;}if(typeof a=='undefined')a=e;if(typeof f=='undefined')if(ChatUserInfos[d]&&ChatUserInfos[d].type){f=ChatUserInfos[d].type;}else f='friend';this.createTab(f,d,e,a);window.chatTabSlider&&chatTabSlider.addTab(d);}window.chatTabSlider&&chatTabSlider.gotoTab(d);if(this.focused){this.tabs[this.focused].unfocus();if(presence.inPopoutWindow)this.tabs[this.focused].deselectPopoutChat();}this.focused=d;this.lastFocused=d;if(this.focused){var c=!presence.inPopoutWindow&&presence.poppedOut;if(this.tabs[this.focused])this.tabs[this.focused].focus(c,this.loaded,b);if(presence.inPopoutWindow)this.tabs[d].selectPopoutChat();}return this.tabs[d];},focusTab:function(c,b,d,a,e){presence.pauseSync();this._focusTab(c,b,d,a,e);this._sendDeferredTabStateChange({focus_chat:c});this.uiChanged();this.chatActivityTime=(new Date()).getTime();this.doStopBlinking();presence.resumeSync();},toggleTab:function(c,b,d,a){if(this.focused==c){this.unfocus();}else this.focusTab(c,b,d,a);},getCurrentTabId:function(){return this.focused;},_getCurrentTab:function(){return this.tabs[this.focused];},getNextTabId:function(a,e){if(!(a in this.tabs))return -1;var c=this.tabList.indexOf(this.tabs[a]);if(!presence.inPopoutWindow)e=!e;var d=a;if(c>=0){if(e){c--;}else c++;var b=this.tabList.length;d=this.tabList[(c+b)%b].id;}return parseInt(d,10);},_handleBlinking:function(a,c){var b=(a==this.user);if(b){this.doStopBlinking(true);}else if(this.isWindowFocused){setTimeout(this.doStopBlinking.bind(this,true),500);}else if(!presence.isOpera){this.newMsgNames.push(c.firstName);if(!this.blinkingTimer)this.blinkingTimer=setTimeout(function(){this.blinkingTimer=setInterval(this._doBlink.bind(this),this.blinkTime);}.bind(this),this.initialBlinkDelay);}},_doBlink:function(){if(this._isBlinking){DocumentTitle.set(DocumentTitle.get());this._isBlinking=false;}else{if(this.newMsgNames&&this.newMsgNames.length>0){if(this.newMsgNamesIndex>=this.newMsgNames.length)this.newMsgNamesIndex=0;var a=this.newMsgNames[this.newMsgNamesIndex++];DocumentTitle.set(_tx("\u00a1{name} te ha enviado un mensaje!",{name:a}),true);}else DocumentTitle.set(_tx("Nuevo mensaje"),true);this._isBlinking=true;}},doStopBlinking:function(a){if(this.blinkingTimer||a){this._stopBlinking();presence.doSync();}},_stopBlinking:function(){if(this.blinkingTimer){if(this._isBlinking)this._doBlink();clearInterval(this.blinkingTimer);this.blinkingTimer=null;this.newMsgNames=[];this.newMsgNamesIndex=0;}},_handlePresenceMessage:function(n,a){if(!Chat.isOnline())return;var h=a.obj;if(h.window_id==presence.windowID)return;var f=null;if(h.from==this.user){f=h.id||h.to;var e=!!h.csid;this.setSquelched(e);if(e)this._closeTab(f);}else f=h.id||h.from;var l=this.tabs[f];var m=(ChatUserInfos[f]&&ChatUserInfos[f].type)||h.tab_type||'friend';var j=this.isSquelched();var k=this.isSquelchedTab(f);switch(h.type){case 'unfocus_chat':this._unfocus();break;case 'focus_chat':this._focusTab(f,undefined,undefined,undefined,m);break;case 'close_chat':this._closeTab(f);break;case 'thread_msg':case 'group_msg':case 'msg':var c=(h.from==this.user);var g,b,d;if(m=='group'||m=='thread'){g=h.to_name;b=g;d=GenderConst.UNKNOWN_PLURAL;}else if(c){g=h.to_name;b=h.to_first_name?h.to_first_name:getFirstName(g);d=h.to_gender;}else{g=h.from_name;b=h.from_first_name?h.from_first_name:getFirstName(g);d=h.from_gender;}this.loadInitialUserInfo(f,g,b,d,m);if(!c&&m=='friend')AvailableList.set(f,AvailableList.ACTIVE,h.fl);if(!j&&!k&&!l){l=this.createTab(m,f,g,b);window.chatTabSlider&&chatTabSlider.addTab(f);if(!this.focused){this._focusTab(f);}else l.getHistory();}if(!j&&!k&&(presence.inPopoutWindow||!presence.poppedOut))this._handleBlinking(h.from,l);if(l){h.time=h.msg.time;l.newMsg(h);}break;case 'typ':if(!j||this.focused==f)l&&l.newTyping(h);break;case 'video':this._newVideoMessage(h);break;case 'chat_event':this._newChatEventMessage(h);break;case 'buddylist_overlay':for(var i in h.overlay)ChatUserInfoManager.get(i,function(){var o={};o[i]=h.overlay[i];AvailableList.addLegacyOverlay(o);});break;default:break;}},_newVideoMessage:function(a){Arbiter.subscribe('video-chat/initialized',function(c,b){var e=a.from;var f=a.message_type;var g=a.parameters;var d=a.fl;b.handleMessage(e,f,g);if(e!=this.user&&f==b.START_SESSION){this.loadInitialUserInfo(e,g.name,g.firstName,g.gender,'friend');AvailableList.set(e,AvailableList.ACTIVE,d);}}.bind(this));},_newChatEventMessage:function(a){if(!presence.inPopoutWindow&&ChatConfig.get('video.can_call',false))this._handleVideoEvent(a.from,a.event_name,a.parameters||{});},_handleVideoEvent:function(b,a,c){var d=this.tabs[b];switch(a){case 'missed-call':ChatUserInfoManager.get(b,function(e){if(!d)d=this.createTab('friend',b,e.name,e.firstName);if(!this.focused)this._focusTab(b);d.newVideoMsg(a,c);}.bind(this));break;case 'connected-call':if(b==this.user)d=this.tabs[c.to];d&&d.newVideoMsg(a,c);break;}},_getBucketDescription:function(d){var a=[500,1000,2000,3000,5000];var b=["half_s","1s","2s","3s","5s"];for(var c=0;c<a.length;c++)if(d<a[c])return b[c];return "over_5s";},reportLatency:function(b){if(this._reportedLatencies<5){var a=this._getBucketDescription(b);presence.warn("presence:latency_"+a+":delay="+b+",sent="+this._reportedLatencies);this._reportedLatencies++;}},_getIDsToNotifyVisibility:function(a){return keys(this.tabs);},getHistory:function(b,a){a=a||false;if(!this.histories[b]&&a)this.histories[b]=[];return this.histories[b];},_renderServerTime12hr:function(d){var e=new Date();e.setTime(d+presence.timeSkew);var b=e.getHours();var a='am';if(b>=12){a='pm';b-=12;}if(b==0)b=12;var c=e.getMinutes();if(c<10)c='0'+c;var f=b+':'+c+a;return f;},_renderServerTime24hr:function(c){var d=new Date();d.setTime(c+presence.timeSkew);var a=d.getHours();if(a<10)a='0'+a;var b=d.getMinutes();if(b<10)b='0'+b;var e=a+':'+b;return e;},setSquelched:function(c){if(c){var a=(new Date()).valueOf();var b=a+this.jabberSquelchInterval;this._squelchUntil=b;presence.doSync();}else if(this._squelchUntil){this._squelchUntil=null;presence.doSync();}},isSquelched:function(){return this.getSquelchUntil()!==null;},setSquelchedTab:function(a,b){if(b){this._squelchedIds[a]=true;this.tabs[a]&&this.tabs[a].squelch();}else delete this._squelchedIds[a];},isSquelchedTab:function(a){return a in this._squelchedIds;},getSquelchUntil:function(){if(this._squelchUntil===null)return null;var a=(new Date()).valueOf();var b=a+(this.jabberSquelchInterval+5000);if(b<this._squelchUntil){this.setSquelched(false);return null;}else if(a<this._squelchUntil){return this._squelchUntil;}else{this.setSquelched(false);return null;}},_enforceTabLimit:function(){var a=0;while(this.numTabs>this.maxNumTabs&&a<this.numTabs-1)if(this.tabList[a].focused||this.tabList[a].numMissed){++a;}else this.closeTab(this.tabList[a].id);},showAddTypeahead:function(a){this._getCurrentTab().showAddTypeahead(a);},_addInitialParticipants:function(){var a=this.tabs[this.lastFocused];var d=ge('chat_add_canonical_typeahead');var b=this._getTypeaheadRecipients(d);var c=XHPTemplate.getNode(d,'chat_add_canonical_tab_id');if(c)b.push(c.value);a.addParticipants(b);},_getTypeaheadRecipients:function(e){var c=DOM.scry(e,'input[type="hidden"]');var d=[];for(var a=0;a<c.length;a++){var b=c[a];if(b.name=='recipients[]')d.push(b.value);}return d;},addMoreParticipants:function(){var a=this.tabs[this.lastFocused];var c=ge('chat_add_multichat_typeahead');var b=this._getTypeaheadRecipients(c);a.addParticipants(b);},getCurrentTabHasThread:function(){var a=this.tabs[this.lastFocused];return a.getHasThread();},createMultichatTab:function(a,c){this.createTab('thread',a,c,c,0,0);this.focusTab(a,true,c,c,'thread');this._addInitialParticipants();var b=this.tabs[this.lastFocused];b.setHasThread(false);},createTab:function(h,c,e,b,f,d){var a=window[this.controllers[h]];var g=new a(this,c,e,b,f,d);this.tabs[c]=g;this.tabList.push(g);this.numTabs++;Arbiter.inform('chat/conversation-opened',{id:c,conversation:g});this._enforceTabLimit();return g;}};
function ChatBuddyList(){this.user=presence.user;this.buddyListID=ChatBuddyList.ID++;this.errorMode=false;this.shouldShowLoading=false;this.sortedList=[];this.flMode=false;this.flData={};this.otherFriendsFlid='-1';this.botsFlid='-2';this.showingErrorMessage=false;this.flSortableGroup=null;this.reorderingLists=false;this.flOpts={};this.externalFlids=[];this.updateOverlay={};}copy_properties(ChatBuddyList,{ID:0,OVERLAY_ONLINE:0,OVERLAY_IDLE:1,OVERLAY_OFFLINE:-1,DEFAULT_OPTS:{fullDisplay:true,excludeIds:{}},MAX_BUDDY_NAME_LENGTH:20});ChatBuddyList.mixin('Arbiter',{_lastRenderRev:null,_lastSortRev:null,_showTime:null,init:function(d,c,b,a){this.root=d;this.flMode=b;this.flData=a;this.shouldShowLoading=c;this._log=EagleEye.createLogger('chat-buddylist',.1);this._init();Arbiter.subscribe(['buddylist/availability-changed','buddylist/updated'],this._render.bind(this));Arbiter.subscribe('buddylist/update-error',this._showLoadError.bind(this));Arbiter.subscribe('buddylist/fl-changed',this._handleFlChange.bind(this));},initError:function(a){this.root=a;this.errorMode=true;this._init();},_init:function(){this.loaded=false;this._isVisible=false;this.updateDiff=0;this.rendered=false;this.showingError=false;this.contentDiv=DOM.find(this.root,'div.content');this.buddyListError=DOM.find(this.root,'div.status');Arbiter.subscribe(PresenceMessage.getArbiterMessageType('fl_settings'),this._handleFLMessage.bind(this));Arbiter.subscribe('chat/connect',this._showLoading.bind(this));this.setCompactDisplay(chatOptions.getSetting('compact_buddylist'));Arbiter.subscribe('chat/option-changed',this._updateSetting.bind(this));Arbiter.inform('buddylist/initialized',this,Arbiter.BEHAVIOR_PERSISTENT);this.inform('initialized',this,Arbiter.BEHAVIOR_PERSISTENT);},setCompactDisplay:function(a){this.isCompactDisplay=a;if(this.isCompactDisplay){this.itemHeight=18;}else this.itemHeight=22;if(this.rendered)this._render();},_handleFLMessage:function(c,a){var b=a.obj;if(b.fl_mode)this._updateNames(b.fl_data);},_updateNames:function(b){for(var a in this.flData)if(typeof b[a]!='undefined'&&b[a].n!=this.flData[a].n){flname=b[a].n;elem=ge(this._getFriendListNameId(a));if(elem)DOM.setContent(elem,flname);}},_flChanged:function(b,a){return (b!=this.flMode||!are_equal(a,this.flData));},_onFlChange:function(d,c){this._dirtyRendering();if(!this.rendered){this.flMode=d;this.flData=c;return;}var g=[];var h=[];var f=[];var e=[];if(this.flMode&&this.flMode==d){var b=this._groupAvailableListByFl(true);for(var a in c)if(typeof this.flData[a]=='undefined'){if(c[a].h)continue;g.push(a);f.push(a);}else if(this.flData[a].h!=c[a].h){if(c[a].h){h.push(a);}else{g.push(a);if(c[a].o)f.push(a);}}else if(this.flData[a].o!=c[a].o)if(c[a].o){f.push(a);}else e.push(a);for(var a in this.flData)if(typeof c[a]=='undefined')h.push(a);this.flMode=d;if(h.length!=0)this._removeFlidsFromBuddyList(h,b);if(e.length!=0)this._goOfflineToLists(e,true);this.flData=c;if(g.length!=0)this._addFlidsToDOM(g,b);if(f.length!=0)this._goOnlineToLists(f,true);}else if(this.flMode&&this.flMode!=d){var b=this._groupAvailableListByFl(true);h=keys(this.flData);this.flMode=d;this.flData=c;this._addFlidsToDOM([null]);this._removeFlidsFromBuddyList(h,b);}else if(!this.flMode&&this.flMode!=d){for(var a in c){if(c[a].h)continue;g.push(a);if(c[a].o)f.push(a);}this.flMode=d;this.flData=c;this._removeFlidsFromDOM([null]);if(g.length>0)this._addFlidsToDOM(g);if(f.length>0)this._goOnlineToLists.bind(this,f,true).defer();}this._render();},_addFlidsToDOM:function(e,f){f=f||this._groupAvailableListByFl(true);var a=this._getRenderedFriendLists();var c=a[0];var h=$('fbChatBuddyListParent');for(var g=0;g<e.length;g++){var d=e[g];if(this.flMode&&d){var b=DOM.create('div',{id:this._getFriendListId(d),className:this._getFriendListItemClasses(d,f)});DOM.setContent(b,HTML(this._renderFriendListHeader(d)));DOM.appendContent(b,HTML(this._renderFriendListContent(d,[])));if(c==d){DOM.prependContent(h,b);}else{var j=a.indexOf(d);var i=a[j-1];DOM.insertAfter(ge(this._getFriendListId(i)),b);}this._addFlSortable(d);}else DOM.prependContent(h,HTML(this._renderFriendListContent(null,[])));}this._addFriendListListeners(e);},_removeFlidsFromDOM:function(b){for(var c=0;c<b.length;c++){var a=b[c];if(a){if(ge(this._getFriendListId(a))){DOM.remove($(this._getFriendListId(a)));this._removeFlSortable(a);}}else{DOM.remove($(this._getAvailableMarkerId(a)));DOM.remove($(this._getIdleMarkerId(a)));}}},contentChanged:function(){this.inform('content-changed');},show:function(){if(this._isVisible)return;this._showTime=this._showTime||new Date();AvailableList.update();this._isVisible=true;if(!this.rendered){this.shouldShowLoading=true;this._firstRender();if(AvailableList.haveFullList)this._render.bind(this).defer();}CSS.show(this.root);},hide:function(){if(!this._isVisible)return;this._showTime=null;this._isVisible=false;this.exitReorderingFlMode();CSS.hide(this.root);},_getUserFlid:function(c,a){if(a===null||a===undefined){var b=this._getUserFlids(c);a=b[0];}return a;},_getSortedList:function(){if(this._lastSortRev!=AvailableList.getRev()){this.sortedList=this._sort(AvailableList.getAvailableIDs());this._lastSortRev=AvailableList.getRev();}return this.sortedList;},getSortedListUI:function(a){if(!a&&this.flMode){var b=this._groupAvailableListByFl(true);var c=[];for(var a in b)c=c.concat(b[a]);var d={};return c.filter(function(e){return !d[e]&&(d[e]=true);});}return this._getSortedList();},getFriendLists:function(){var a={};copy_properties(a,this.flData);delete a[this.otherFriendsFlid];delete a[this.botsFlid];return a;},_getRenderedFriendLists:function(){var b=[];for(var a in this.flData)if(!this.flData[a].h)b.push(a);return b;},_getFriendListsInChat:function(){var a=this._getRenderedFriendLists();a.remove(this.otherFriendsFlid);a.remove(this.botsFlid);return a;},updateUserInfos:function(a){copy_properties(ChatUserInfos,a);},_sort:function(b){var a=this._compareFunction.bind(this);b.sort(a);return b;},_compareFunction:function(a,d,b,e){if(typeof b=='undefined')b=AvailableList.isIdle(a);if(typeof e=='undefined')e=AvailableList.isIdle(d);if(b^e)return b?1:-1;var c=ChatUserInfos[a].name.toLowerCase();var f=ChatUserInfos[d].name.toLowerCase();return (c<f)?-1:1;},itemOnClick:function(c){var b=DataStore.get(c,'id');var a=DataStore.get(c,'flid');presence.pauseSync();chatDisplay.focusTab(b,true);if(!this.isSticky())Chat.closeBuddyList();this.inform('buddylist/buddy-clicked',{flid:a,id:b});presence.resumeSync();},_renderItem:function(c,a,d){var i=ChatUserInfos[c];var f=i.name;var h=i.thumbSrc;var e=['<a',' href="#"',' id="',this._getBuddyListItemId(c,a),'"',' class="clearfix friend',(d?' idle':''),'"',' title="',f,'"',' data-id="',parseInt(c,10),'"',' data-flid="',a,'"','>'];var b=!this.isCompactDisplay;var g=this._getFlOpts(a);b&=g.fullDisplay;if(b)e=e.concat('<img src="',h,'" />');e=e.concat('<span id="',this._getBuddyListItemNameId(c,a),'">',htmlize(f),'</span>','</a>');return e.join('');},_groupAvailableListByFl:function(c,a){if(!this.flMode||!this.flData)return null;c=c||false;a=a||false;var e={};for(var b in this.flData)e[b]=[];if(a)return e;var d=c?this._getSortedList():AvailableList.getAvailableIDs();d.forEach(function(h){var g=FriendLists.get(h);if(g)for(var i=0;i<g.length;++i){var f=g[i];e[f]&&e[f].push(h);}});return e;},_listNameInUse:function(b){for(var a in this.flData)if(this.flData[a].n==b)return true;return false;},createFriendList:function(b){if(this._listNameInUse(b)){ErrorDialog.show(_tx("Se ha producido un error."),_tx("No puedes tener dos listas con el mismo nombre. Crea un nombre distinto para esta lista."));return;}var a={create:b};this._saveBuddyListSetting(a,function(){for(var c in this.flData)if(this.flData[c].n==b){this.scrollIntoView($(this._getFriendListId(c)));Arbiter.inform('friend-list/new',{flid:c,fl_name:b});break;}}.bind(this));},handleFlInChat:function(b,a){if(b){this._unHideFriendListFromChat(a);}else this._hideFriendListFromChat(a);},_unHideFriendListFromChat:function(b){var d=this._getFriendListsInChat().length==0;var c=[b];var a={unhide_from_chat:1,flids:c};this.flData[b].h=0;this._saveBuddyListSetting(a,function(){this._showEmptyListMomentarily(b);this.scrollIntoView($(this._getFriendListId(b)));}.bind(this));if(d){this._onFlChange(true,this.flData);}else this._addFlidsToDOM(c);},_hideFriendListFromChat:function(b){var d=this._getFriendListsInChat().length==1;var c=[b];var a={hide_from_chat:1,flids:c};this.flData[b].h=1;this._saveBuddyListSetting(a);if(d){this._onFlChange(false,this.flData);}else this._removeFlidsFromBuddyList(c);},_friendListHandleSwitchThrown:function(b){var a=this.flData[b].o;if(a){this._goOfflineToLists([b]);}else this._goOnlineToLists([b]);},_friendListHandleSwitchMouseDown:function(b){var a=Event.listen(document,'mouseup',function(){a.remove();this._friendListHandleSwitchThrown(b);}.bind(this));},_friendListHandleMouseOver:function(a){if(this.reorderingLists)return;CSS.addClass($(this._getFriendListId(a)),'hover');},_friendListHandleMouseOut:function(a){CSS.removeClass($(this._getFriendListId(a)),'hover');},_saveBuddyListSetting:function(b,a){b.user=this.user;a=a||bagofholding;new AsyncRequest().setData(b).setURI('/ajax/chat/buddy_list_settings.php').setHandler(this._onBuddyListSettingSave.bind(this,a)).setAllowCrossPageTransition(true).send();},_goOnlineToLists:function(b,d){d=d||false;var a={online_to_list:1,flids:b,read_only:d};var c=chatDisplay._getIDsToNotifyVisibility(true);if(c)a.notify_ids=c;this._handleFlVisibilityChange(b,1);this._saveBuddyListSetting(a);},_handleFlVisibilityChange:function(d,f,a){for(var e=0;e<d.length;e++){var c=d[e];var b=ge(this._getFriendListId(c));if(!b)continue;this.flData[c].o=f;if(f){CSS.addClass(b,'online');CSS.removeClass(b,'offline');if(c==this.otherFriendsFlid)this._showEmptyListMomentarily(c);}else{CSS.addClass(b,'offline');CSS.removeClass(b,'online');}var g=DOM.scry(b,'div.titletip strong')[0];g&&DOM.setContent(g,this._getFriendListTooltipText(c));a&&a(c);}},_showEmptyListMomentarily:function(b){this.shownEmptyFlids=this.shownEmptyFlids||{};this.shownEmptyFlids[b]=1;var a=ge(this._getFriendListId(b));if(a)CSS.addClass(a,'show_empty_list');(function(){delete this.shownEmptyFlids[b];var c=ge(this._getFriendListId(b));if(c)CSS.removeClass(c,'show_empty_list');}).bind(this).defer(8000);},_goOfflineToLists:function(b,e){e=e||false;var c=this._groupAvailableListByFl();this._handleFlVisibilityChange(b,0);if(!e){var a={offline_to_list:1,flids:b};var d=chatDisplay._getIDsToNotifyVisibility(true);if(d)a.notify_ids=d;this._saveBuddyListSetting(a);}},_removeFlidsFromBuddyList:function(a,b){this._removeFlidsFromDOM(a);},_onBuddyListSettingSave:function(b,a){var d=a.getPayload();if(d){d.userInfos&&this.updateUserInfos(d.userInfos);d.availableList&&AvailableList.addLegacyAvailableList(d.availableList);if(d.flData){var c;if(typeof d.flMode!='undefined'){c=d.flMode;}else c=true;this._onFlChange(c,d.flData);this._resetFlidClasses();}b&&b();}},_resetFlidClasses:function(){if(!this.flMode)return;var c=this._groupAvailableListByFl();for(var b in this.flData){var a=ge(this._getFriendListId(b));if(a)CSS.setClass(a,this._getFriendListItemClasses(b,c));}},_getFriendListItemClasses:function(b,e){var d=this.flData[b].o;var c=this.flData[b].h;var a=['friend_list'];if(d){a.push('online');}else a.push('offline');if(!c&&this.shownEmptyFlids&&this.shownEmptyFlids[b])a.push('show_empty_list');if(b==this.otherFriendsFlid){a.push('compact_friend_list');a.push('other_friends_list');}if(this.reorderingLists&&(b==this.otherFriendsFlid||b==this.botsFlid))a.push('suppress');return a.join(' ');},_renderFriendListHeader:function(c){var b=this.flData[c].n;var e=this.flData[c].o;var a='';var f=typeof this.flData[c].s!='undefined';if(!f&&c!=this.otherFriendsFlid)var a='<a href="/friends/ajax/edit_list.php?list_id='+c+'" '+'rel="dialog-post">'+_tx("Editar")+'</a>';var d=['<div class="friendlist_name">','<span class="title"><a href="#" id="'+this._getFriendListNameId(c)+'">',htmlize(b),'</a></span>','<span class="edit_link">',a,'</span>','</div>'];if(!f)d.push('<div class="switch"><a class="online_status" ','>','<div class="titletip"><strong>',this._getFriendListTooltipText(c),'</strong></div>','</a>','</div>');return d.join('');},_getFriendListTooltipText:function(a){return this.flData[a].o?_tx("Desconectar"):_tx("Conectar");},registerExternalFriendList:function(b){if(!this.rendered)this._firstRender();var a='xfl_'+this.externalFlids.length;this.externalFlids.push(a);this.flOpts[a]=b;return a;},_renderFriendListContent:function(a,i){var l;var d=this.flMode&&a;if(d){l=['<div id="',this._getFriendListContainerId(a),'"','class="friend_list_container">'];}else l=[];l.push('<div id="',this._getAvailableMarkerId(a),'" class="suppress"></div>');var g=[];var b=false,c=false;for(var k=0;k<i.length;k++){var e=i[k];var f=this._isIdle(e);var j=[this._renderItem(e,a,f)];if(f){b=true;g=g.concat(j);}else{c=true;l=l.concat(j);}}var h=(b&&c)?'':' hide_idle_marker';l.push('<div id="',this._getIdleMarkerId(a),'" class="subheader',h,'"></div>');l=l.concat(g);if(d)l.push('</div>');return l.join('');},_isIdle:function(a){return AvailableList.isIdle(a);},_addFriendListListeners:function(c){if(!this.flMode)return;c=c||this._getRenderedFriendLists();for(var d=0;d<c.length;d++){var b=c[d];if(typeof this.flData[b].s!='undefined')continue;var a=$(this._getFriendListId(b));Event.listen(a,'mouseover',this._friendListHandleMouseOver.bind(this,b));Event.listen(a,'mouseout',this._friendListHandleMouseOut.bind(this,b));var e=DOM.find(a,'a.online_status');Event.listen(e,'mousedown',this._friendListHandleSwitchMouseDown.bind(this,b));}},_renderBuddyContent:function(){var a=(AvailableList.getCount()?'hide_empty_item':'');var g=['<div class="subgroup">','<div id="fbChatBuddyListParent" class="list_select">','<div id="',this._getBuddyListEmptyItemId(),'" class="info_text ',a,'">',_tx("No hay nadie disponible para charlar."),'</div>'];var c;var d={};if(this.flMode){c=keys(this.flData);d=this._groupAvailableListByFl(true);}else c=[null];for(var e=0;e<c.length;++e){var b=c[e];var f=[];if(this.flMode&&b){if(this.flData[b].h)continue;g.push('<div id="',this._getFriendListId(b),'"','class="',this._getFriendListItemClasses(b,d),'">',this._renderFriendListHeader(b));f=d[b];}else f=this._getSortedList();g.push(this._renderFriendListContent(b,f));if(this.flMode&&b)g.push('</div>');}g.concat(['</div>','</div>']);return g.join('');},_render:function(){if(!this._isVisible||this._lastRenderRev==AvailableList.getRev())return;this._lastRenderRev=AvailableList.getRev();this._getSortedList();CSS.conditionClass(this.contentDiv,'compact',this.isCompactDisplay);DOM.setContent(this.contentDiv,HTML(this._renderBuddyContent()));if(this.rendered){this._hideError();this._addFriendListListeners();}if(this.errorMode)this._showLoadError();if(this.shouldShowLoading){this._showLoading();this.shouldShowLoading=false;}else if(this._showTime){var a=new Date()-this._showTime;this._showTime=null;this._log({buddy_list_open:a});}},_firstRender:function(){this._render();this.rendered=true;Event.listen(this.contentDiv,'click',function(event){var a=Parent.byClass(event.getTarget(),'friend');a&&this.itemOnClick(a);}.bind(this));},updateItemDisplay:function(d){var a=AvailableList.get(d);if(!a)return;var g=this._getUserFlids(d);for(var c=0;c<g.length;c++){var b=g[c];var f=ge(this._getBuddyListItemId(d,b));if(!f)return;var e=a==AvailableList.IDLE;f=HTML(this._renderItem(d,b,e)).getRootNode();}},_showLoadError:function(){this._showError(_tx("No se ha podido cargar la lista de amigos disponibles."));},_showLoading:function(){this._showError(_tx("Cargando..."));},_hideError:function(){this.showingError=false;CSS.removeClass(this.root,'error');this.contentChanged();},_showError:function(a){this._dirtyRendering();this.showingError=true;DOM.setContent(this.buddyListError,HTML(a));CSS.addClass(this.root,'error');this.contentChanged();},isSticky:function(){return chatOptions.getSetting('sticky_buddylist');},enterErrorMode:function(a){this.exitErrorMode();this.exitReorderingFlMode();this.showingErrorMessage=true;var b=$N('div',{id:'error_fl_alert'},[$N('span',{className:'helper_text'},a),$N('input',{type:'button',className:'inputbutton',value:_tx("Aceptar"),onclick:this.exitErrorMode.bind(this)})]);DOM.insertBefore(b,this.contentDiv);},exitErrorMode:function(){if(this.showingErrorMessage){DOM.remove($('error_fl_alert'));this.showingErrorMessage=false;}return false;},enterReorderingFlMode:function(){if(this.reorderingLists)return;Bootloader.loadComponents('sort',function(){this.exitErrorMode();this.reorderingLists=true;CSS.addClass(this.root,'reorder_fl');var a=this._getRenderedFriendLists();this.flSortableGroup=new SortableGroup();for(var c=0;c<a.length;c++){var b=a[c];if(b==this.otherFriendsFlid||b==this.botsFlid){CSS.addClass(this._getFriendListId(b),'suppress');}else this._addFlSortable(b);}var d=$N('div',{id:'reorder_fl_alert'},[$N('span',{className:'helper_text'},_tx("Arrastra las listas para ordenarlas")),$N('input',{type:'button',className:'inputbutton',value:_tx("Finalizar"),onclick:this.exitReorderingFlMode.bind(this)})]);DOM.insertBefore(d,this.contentDiv);this.inform('reorder-mode/enter');this.contentChanged();}.bind(this));},exitReorderingFlMode:function(){if(!this.reorderingLists)return;this._reorderFlids();DOM.remove($('reorder_fl_alert'));CSS.removeClass(this.root,'reorder_fl');var a=this._getRenderedFriendLists();for(var c=0;c<a.length;c++){var b=a[c];if(b==this.otherFriendsFlid||b==this.botsFlid){CSS.removeClass(this._getFriendListId(b),'suppress');}else this._removeFlSortable(b);}this.reorderingLists=false;this.flSortableGroup.destroy();this.flSortableGroup=null;this.inform('reorder-mode/exit');this.contentChanged();},_addFlSortable:function(a){if(this.flSortableGroup!=null)this.flSortableGroup.addSortable(a,$(this._getFriendListId(a)));},_removeFlSortable:function(a){if(this.flSortableGroup!=null)this.flSortableGroup.removeSortable(a);},_reorderFlids:function(){var a={reorder:1,flids:this.flSortableGroup.getOrder()};this._saveBuddyListSetting(a);},_getGlobalFlids:function(a){var b=this.flMode&&this.flData?keys(this.flData):[null];return a?b:b.concat(this.externalFlids);},_getUserFlids:function(d,a,b){var c=(a&&a.fl)?a.fl:FriendLists.get(d);if(!b)c=this._addExternalFlids(d,c);return c;},_addExternalFlids:function(d,b){b=b?$A(b):[];for(var c=0;c<this.externalFlids.length;c++){var a=this.externalFlids[c];var e=this._getFlOpts(a);if(!e.excludeIds[d])b.push(a);}return b;},_getFlOpts:function(a){return this.flOpts[a]||ChatBuddyList.DEFAULT_OPTS;},_getAvailableMarkerId:function(a){return this._encodeFlid('buddy_list_avail_marker',a);},_getIdleMarkerId:function(a){return this._encodeFlid('buddy_list_idle_marker',a);},_getBuddyListItemId:function(b,a){return this._encodeFlid('buddy_list_item_'+b,a);},_getBuddyListItemNameId:function(b,a){return this._encodeFlid('buddy_list_item_name_'+b,a);},_getBuddyListEmptyItemId:function(){return 'buddy_list_empty_item';},_encodeFlid:function(a,b){return (b?(b+'_'+a):a)+'_'+this.buddyListID;},_getFriendListId:function(a){return this._encodeFlid('friend_list_item',a);},_getFriendListNameId:function(a){return this._encodeFlid('friend_list_name',a);},_getFriendListContainerId:function(a){return this._encodeFlid('friend_list_container',a);},debugPrintUpdateOverlay:function(){var b=this.updateOverlay;for(var a in b);},_updateSetting:function(a,b){this._dirtyRendering();switch(b.name){case 'compact_buddylist':this.setCompactDisplay(b.value);break;}this._render();},_dirtyRendering:function(){this._lastRenderRev=null;},_handleFlChange:function(a,c){var d=c.flMode;var b=c.flData;if(this._flChanged(d,b))this._onFlChange(d,b);}});
function BuddyListNub(){this.parent.construct(this);}BuddyListNub.extend('NubController');copy_properties(BuddyListNub,{TYPEAHEAD_MIN_FRIENDS:10,TYPEAHEAD_MIN_FRIENDS_FLMODE:20});BuddyListNub.prototype={init:function(b,a,d){this.parent.init(b);this.root=b;this.buddyList=a;this.typeahead=d;this.button=DOM.find(b,'a.fbNubButton');this.label=DOM.find(b,'span.label');this.throbber=DOM.scry(b,'img.throbber')[0];a.subscribe('content-changed',this.flyoutContentChanged.bind(this));Arbiter.subscribe('buddylist/count-changed',this._updateCount.bind(this));Arbiter.subscribe('chat/connect',this._handleConnect.bind(this));Arbiter.subscribe('chat/visibility-changed',this._handleVisibility.bind(this));var c=Toggler.createInstance(b);c.setSticky(!!chatOptions.getSetting('sticky_buddylist'));Arbiter.subscribe('chat/option-changed',function(e,f){f.name==='sticky_buddylist'&&c.setSticky(!!f.value);});Event.listen(b,'keydown',this._onKeyDown.bind(this));Event.listen(this.button,'click',this.onButtonClick.bind(this));this.typeahead.subscribe(['respond','query','reset'],function(e,f){f&&f.value?this.buddyList.hide():this.buddyList.show();this.flyoutContentChanged();}.bind(this));this.subscribe('show',this.onShow.bind(this));this.subscribe('hide',this.onHide.bind(this));presence.registerStateStorer(this._storeState.bind(this));presence.registerStateLoader(this._loadState.bind(this));this._loadState(presence.state);Selector.subscribe(['open','close'],function(f,e){if(DOM.contains(this.root,e.selector))CSS.conditionClass(this.root,'menuOpened',f==='open');}.bind(this));Arbiter.inform('buddylist-nub/initialized',this,Arbiter.BEHAVIOR_PERSISTENT);},_handleConnect:function(a){this._setLabel(_tx("Chat"),true);},_handleVisibility:function(){var a=Chat.isOnline();if(!a){this._setLabel(_tx("{Chat} (Desconectado)",{Chat:_tx("Chat")}));this.hide();}CSS.conditionClass(presence.holder,'offline',!a);},_loadState:function(b){var a=!!b.blo;if(!presence.poppedOut)if(a){this.show();}else this.hide();},onButtonClick:function(){var a=this.subscribe('show',function(){this.typeahead.getCore().getElement().focus();}.bind(this));this.unsubscribe.bind(this,a).defer();},onHide:function(){this._isOpen=false;this.buddyList.subscribe('initialized',function(){this.buddyList.hide();}.bind(this));this.typeahead.getCore().reset();presence.doSync();},_onKeyDown:function(event){var a=Event.getKeyCode(event);if(a===KEYS.ESC&&!CSS.hasClass(this.root,'menuOpened')){this.hide();return false;}},onShow:function(){this._isOpen=true;Chat.goOnline(function(){this.buddyList.subscribe('initialized',function(){this.buddyList.show();}.bind(this));presence.doSync();}.bind(this));},_setLabel:function(a,c){var b=this.label.cloneNode(true);DOM.setContent(b,a);DOM.replace(this.label,b);this.label=b;this.throbber&&CSS.conditionShow(this.throbber,!!c);},_storeState:function(a){a.blo=this._isOpen?1:0;return a;},_updateCount:function(){if(!Chat.isOnline())return;var a=AvailableList.getCount();var b=_tx("{Chat} {number-available}",{Chat:_tx("Chat"),'number-available':['<span class="count">','(<strong>',a,'</strong>)','</span>'].join('')});this._setLabel(HTML(b));var c=this.buddyList.flMode?BuddyListNub.TYPEAHEAD_MIN_FRIENDS_FLMODE:BuddyListNub.TYPEAHEAD_MIN_FRIENDS;CSS.conditionShow(this.typeahead.getElement(),a>=c);}};
function ChatBuddyListDropdown(){}ChatBuddyListDropdown.prototype={init:function(a){this.root=a;Selector.listen(a,'open',function(){this._resizeAndFlip();var b=Event.listen(window,'resize',this._resizeAndFlip.bind(this));var c=Selector.listen(a,'close',function(){b.remove();Selector.unsubscribe(c);});}.bind(this));},_resizeAndFlip:function(){var a=Vector2.getElementPosition(this.root,'viewport');var g=Vector2.getViewportDimensions();var f=a.y>g.y/2;CSS.conditionClass(this.root,'uiSelectorBottomUp',f);if(!ua.ie()||ua.ie()>7){var b=Selector.getSelectorMenu(this.root);var c=Vector2.getElementPosition(b,'viewport');if(f){availableHeight=a.y;}else availableHeight=g.y-c.y;var d=DOM.find(b,'ul.uiMenuInner');var e=b.scrollHeight-d.scrollHeight;availableHeight-=e;CSS.setStyle(b,'max-height',availableHeight+'px');}}};
function ChatBuddyListFriendListsDropdown(){this.parent.construct(this);}ChatBuddyListFriendListsDropdown.extend('ChatBuddyListDropdown');ChatBuddyListFriendListsDropdown.prototype={init:function(b,c,a){this.parent.init(b);this.template=c;this.form=a;this.menu=DOM.find(b,'div.menu');this.noListsEl=DOM.find(b,'li.noListsAvailable');Arbiter.subscribe('buddylist/initialized',this._initBuddyList.bind(this));},_initBuddyList:function(a,b){this.buddyList=b;Event.listen(this.form,'submit',this._onSubmitForm.bind(this));Selector.listen(this.root,'open',this._onOpen.bind(this));Selector.listen(this.root,'toggle',this._onToggle.bind(this));},_clearFriendLists:function(){var a=Selector.getOptions(this.root);a.forEach(DOM.remove);},_onOpen:function(){var c=this.buddyList.getFriendLists();this._clearFriendLists();if(count(c)>0){CSS.hide(this.noListsEl);var e=[$N('option')];var f=[];for(var b in c){var a=c[b].n;var g=this.template.render();g.setAttribute('data-label',a);var d=DOM.find(g,'span.itemLabel');DOM.setContent(d,a);DOM.insertBefore(g,this.noListsEl);e.push($N('option',{value:b}));c[b].h===0&&f.push(b);}Selector.attachMenu(this.root,this.menu,$N('select',e));f.forEach(function(h){Selector.setSelected(this.root,h,true);}.bind(this));}else CSS.show(this.noListsEl);},_onSubmitForm:function(event){if(!this.nameInput)this.nameInput=DOM.find(this.form,'input.nameInput');var a=this.nameInput.value;this.buddyList.createFriendList(a);this.nameInput.value='';this.nameInput.blur();Selector.toggle(this.root);return event.kill();},_onToggle:function(a){var c=a.option;var b=Selector.getOptionValue(c);var d=Selector.isOptionSelected(c);this.buddyList.handleFlInChat(d,b);Selector.toggle(this.root);}};
function ChatBuddyListOptionsDropdown(){this.parent.construct(this);}ChatBuddyListOptionsDropdown.extend('ChatBuddyListDropdown');ChatBuddyListOptionsDropdown.prototype={init:function(a){this.parent.init(a);Arbiter.subscribe('buddylist/initialized',this._initBuddyList.bind(this));Arbiter.subscribe('chat/option-changed',this._onOptionChanged.bind(this));},_initBuddyList:function(a,b){this.buddyList=b;Selector.listen(this.root,'open',this._onOpen.bind(this));Selector.listen(this.root,'select',this._onSelect.bind(this));Selector.listen(this.root,'toggle',this._onToggle.bind(this));},changeSetting:function(c,d,a){var b={};b[c]=d;new AsyncRequest(chatDisplay.settingsURL).setHandler(this._onChangeSettingResponse.bind(this,c,d)).setErrorHandler(this._onChangeSettingError.bind(this,c,d)).setFinallyHandler(a).setData(b).setAllowCrossPageTransition(true).send();},_onChangeSettingResponse:function(a,c,b){chatOptions.setSetting(a,c);presence.doSync();},_onChangeSettingError:function(a,c,b){Selector.setSelected(this.root,a,!c);Chat.enterErrorMode(_tx("No es posible guardar tu configuraci\u00f3n de {Chat}",{Chat:_tx("Chat")}));},_onOpen:function(){var b=Selector.getOption(this.root,'reorder');var a=this.buddyList._getFriendListsInChat().length;Selector.setOptionEnabled(b,a>1);},_onOptionChanged:function(a,b){var c=b.name;if(c==='sound')Selector.setSelected(this.root,c,b.value);},_onSelect:function(b){var a=Selector.getOptionValue(b.option);switch(a){case 'offline':return this.toggleVisibility();case 'reorder':return this.reorderLists();case 'popin':return this.popin();case 'popout':return this.popout();}},_onToggle:function(a){var b=Selector.getOptionValue(a.option);var c=Selector.isOptionSelected(a.option);CSS.addClass(a.option,'async_saving');this.changeSetting(b,c,function(){CSS.removeClass(a.option,'async_saving');});},popin:function(){presence.popin();Selector.toggle(this.root);return false;},popout:function(){presence.popout();Selector.toggle(this.root);return false;},reorderLists:function(){this.buddyList.enterReorderingFlMode();Selector.toggle(this.root);return false;},toggleVisibility:function(){chatOptions.toggleVisibility();Selector.toggle(this.root);return false;}};
var ChatConfig=window.ChatConfig||(function(){var a={};return {get:function(c,b){return c in a?a[c]:b;},set:function(b){if(arguments.length>1){b={};b[arguments[0]]=arguments[1];}copy_properties(a,b);}};})();
function ChatOptions(b,a){this.visibility=b;this.settings=a;this._init();Arbiter.inform('chat-options/initialized',this,Arbiter.BEHAVIOR_PERSISTENT);}ChatOptions.prototype={_init:function(){presence.registerStateStorer(this._storeState.bind(this));presence.registerStateLoader(this._loadState.bind(this));},_storeState:function(a){a.vis=this.visibility;a.bls=this.getSetting('sticky_buddylist');a.blc=this.getSetting('compact_buddylist');a.snd=this.getSetting('sound');return a;},_loadState:function(a){if(a.vis!=this.visibility)this.setVisibility(a.vis);this.setSetting('sticky_buddylist',a.bls);this.setSetting('compact_buddylist',a.blc);this.setSetting('sound',a.snd);},setVisibility:function(a){if(a==this.visibility)return;this.visibility=a;if(!Chat.isFeatureAvailable('always_connect'))if(a){channelManager.isActionRequest=true;channelManager.rebuild(ChannelRebuildReasons.UIRestart);}else channelManager.setReady(false);Arbiter.inform('chat/visibility-changed',{sender:this});},_onVisibilityResponse:function(a,b){presence.pauseSync();this.setVisibility(a);if(!presence.inPopoutWindow&&!a)chatDisplay.unfocus();presence.resumeSync();if(presence.poppedOut)presence.popout();},_onVisibilityError:function(b){var a=_tx("Chat");Chat.enterErrorMode(_tx("No es posible guardar tu configuraci\u00f3n de {Chat}",{Chat:a}));},toggleVisibility:function(){this.sendVisibility(!this.visibility);},sendVisibility:function(c){if(this.visibility==c)return;var a={visibility:c};var b=chatDisplay._getIDsToNotifyVisibility(c);if(b)a.notify_ids=b;this.visibilityAsync=new AsyncRequest().setHandler(this._onVisibilityResponse.bind(this,c)).setErrorHandler(this._onVisibilityError.bind(this)).setData(a).setURI(chatDisplay.settingsURL).setAllowCrossPageTransition(true).send();Arbiter.inform(c?'chat/connect':'chat/disconnect');},getSetting:function(a){return this.settings[a];},setSetting:function(a,b){if(this.getSetting(a)==b)return;this.settings[a]=b;Arbiter.inform('chat/option-changed',{name:a,value:b});}};
function ChatTabSlider(){this.inDock=!presence.inPopoutWindow;this.handleWidth=ChatConfig.get('bigbird_ui')?264:150;this.animationTime=210;this._init();}ChatTabSlider.prototype={_init:function(){this.org_s=0;this.numToShow=0;this.numShift=1;this.shiftByNumTabs=false;this.timer=null;this.skipAnimation=false;this.chatWidth=null;if(this.inDock){var a=$('fbDockChatTabSlider');this.chat=ge('fbDockChatTabsWrapper');this.chatTabBar=ge('fbDockChatTabs');this.nextTab=DOM.find(a,'div.next');Event.listen(this.nextTab,'click',this.next.bind(this));this.prevTab=DOM.find(a,'div.previous');Event.listen(this.prevTab,'click',this.prev.bind(this));this.nextCounter=DOM.find(this.nextTab,'span.numTabs');this.prevCounter=DOM.find(this.prevTab,'span.numTabs');this.numMissedNextCounter=DOM.find(this.nextTab,'span.numMessages');this.numMissedPrevCounter=DOM.find(this.prevTab,'span.numMessages');Toggler.createInstance(this.chatTabBar);}else{this.chat=ge('chat');this.chatTabBar=ge('chat_tab_bar');this.nextTab=ge('chat_next_tab');this.prevTab=ge('chat_previous_tab');this.nextCounter=ge('next_count');this.prevCounter=ge('prev_count');this.numMissedNextCounter=ge('next_num_missed');this.numMissedPrevCounter=ge('prev_num_missed');}this.numNext=0;this.numPrev=0;this.prevTabs={};this.nextTabs={};presence.registerStateLoader(this._load.bind(this));presence.registerStateStorer(this._store.bind(this));Event.listen(window,'resize',this._resize.bind(this,false));},load:function(){this._load(presence.state);this._resize(true);},_load:function(a){var b=0;if(a)b=(a.s?a.s:b);this._setPos(b);},_store:function(a){a.s=this._s;return a;},_calculate:function(a){this._setMaxWidth();if(a)this.maxWidth-=16;if(presence.poppedOut){this.numToShow=chatDisplay.numTabs;}else{this.numToShow=parseInt(this.maxWidth/this.handleWidth);this.numToShow=this.numToShow>0?this.numToShow:1;}if(this.shiftByNumTabs)this.numShift=this.numToShow;if(this._s!=null)this._setPos(this._s);},_setMaxWidth:function(){if(this.inDock){var d=document.body.clientWidth;var a=Parent.byClass(this.chat,'fbDock').firstChild;for(;a;a=a.nextSibling)d-=a.clientWidth;d+=this.chat.clientWidth;this.maxWidth=d-70;}else{var d=document.body.offsetWidth;if(ChatTabSlider.presenceWidthTest)var d=$('presence_ui').offsetWidth;var b=['buddy_list_tab','presence_notifications_tab'];for(var c=0;c<b.length;c++)d-=(ge(b[c])&&$(b[c]).clientWidth!=undefined)?ge(b[c]).clientWidth:0;this.maxWidth=(presence.poppedOut?d-254:d-138);}},_setPos:function(a){if(a<0)a=0;this._s=a;this._e=this._s+this.numToShow;},_doSync:function(){var a=(this.org_s!=this._s);this.org_s=0;if(a)presence.doSync();},_build:function(){if(presence.poppedOut)return;var a=(this.numToShow>=chatDisplay.numTabs)?true:false;this.setVisibleTabs(a);if(a){this.resetCounters();}else this.updateCounters();this.updateMissedCount();},_resize:function(a){this.org_s=this._s;this._calculate(a);this._build();this._doSync();if(chatDisplay.lastFocused!=null)this.gotoTab(chatDisplay.lastFocused);},addTab:function(a){this._build();},gotoTab:function(a){if(!(a in chatDisplay.tabs))return;var b=chatDisplay.tabList.indexOf(chatDisplay.tabs[a]);if(!this._inRange(b)){var c=(b-this.numToShow)+1;this._setPos(c);this._build();}},close:function(){this._setPos(((this.numPrev>0||this.numNext>0)&&this._s>0)?this._s-1:0);this._calculate();this._build();},setVisibleTabs:function(a){var d=chatDisplay.tabList;for(var b=0,c=d.length;b<c;++b)if(this._inRange(b,d[b].id)||a){d[b].show();}else d[b].hide();},_inRange:function(c,b){var d,a=false;if(c>=this._s){d=true;delete this.prevTabs[b];}else this.prevTabs[b]=b;if(c<this._e){a=true;delete this.nextTabs[b];}else this.nextTabs[b]=b;return (d&&a);},updateMissedCount:function(){var c=0;var b=0;for(var a in this.prevTabs)c+=chatDisplay.tabs[a]?chatDisplay.tabs[a].numMissed:0;this.numMissedPrevCounter.innerHTML=c;CSS.conditionClass(this.numMissedPrevCounter,'hidden_elem',!c);for(var a in this.nextTabs)b+=chatDisplay.tabs[a]?chatDisplay.tabs[a].numMissed:0;this.numMissedNextCounter.innerHTML=b;CSS.conditionClass(this.numMissedNextCounter,'hidden_elem',!b);},updateCounters:function(){this.numNext=chatDisplay.numTabs-this._e;this.numPrev=this._s;if(this.numNext<=0){this.numNext=0;CSS.addClass(this.nextTab,'disabled');}else CSS.removeClass(this.nextTab,'disabled');if(this.numPrev<=0){this.numPrev=0;CSS.addClass(this.prevTab,'disabled');}else CSS.removeClass(this.prevTab,'disabled');if(this.numPrev>0||this.numNext>0){if(this.inDock){CSS.show(this.nextTab);CSS.show(this.prevTab);}else{show('chat_next_tab');show('chat_previous_tab');}}else if(this.inDock){CSS.hide(this.nextTab);CSS.hide(this.prevTab);}else{hide('chat_next_tab');hide('chat_previous_tab');}this.nextCounter.innerHTML=this.numNext;this.prevCounter.innerHTML=this.numPrev;},resetCounters:function(){this._setPos(0);this.updateCounters();},shift:function(a){this.org_s=this._s;chatDisplay.unfocusNoSync();this._shift.bind(this,a).defer();},_shift:function(a){this._setPos(this._s<0?0:this._s+a);this._slide(a);if(this.timer||this.skipAnimation){this._slideReset();this.skipAnimation=true;var b=setTimeout(function(){this.skipAnimation=false;}.bind(this),500);}else this.timer=setTimeout(function(){this._slideReset();}.bind(this),this.animationTime);},_slide:function(a){this._slideSetup(false);this.setVisibleTabs(true);this.slideInc=(a*(this.handleWidth));this.leftPos=-(a)*(this.numNext*(this.slideInc));this.chatTabBar.style.left=this.leftPos+'px';animation(this.chatTabBar).by('left',this.slideInc).duration(this.animationTime-10).go();},_slideSetup:function(a){this.chat.style.position=a?'':'relative';this.chat.style.overflow=a?'visible':'hidden';if(!this.chatWidth)this.chatWidth=this.chatTabBar.clientWidth;if(a)this.chatWidth=null;this.chat.style.width=a?'':this.chatWidth+'px';this.chatTabBar.style.width=a?'':chatDisplay.numTabs*this.handleWidth+'px';this.chatTabBar.style.position=a?'':'absolute';},_slideReset:function(){clearTimeout(this.timer);this.timer=null;this._slideSetup(true);this._build();var a=chatDisplay.lastFocused;if(a){var b=chatDisplay.tabList.indexOf(chatDisplay.tabs[a]);if(this._inRange(b)){chatDisplay.refocus();}else chatDisplay.lastFocused=null;}this._doSync();},next:function(){this.numNext&&this.shift(this.numShift);return false;},prev:function(){this.numPrev&&this.shift(-this.numShift);return false;}};
