/*    HTTP Host:  static.ak.fbcdn.net                                          */
/*    Generated:  November 6th 2008 4:46:39 PM PST                             */
/*      Machine:  10.16.139.107                                                */
/*       Source:  Local Cache                                                  */
/*     Location:  rsrc:4mpseg0f:en_US:/html/js/9wt8p6oifncwwo8w.pkg.js:141     */
/*       Locale:  en_US                                                        */
/*         Path:  js/9wt8p6oifncwwo8w.pkg.js                                   */


function ComposerAttachment(){this._container=null;}
copy_properties(ComposerAttachment,{newFromURL:function(url,errorCallback){if(!/(?:https?:\/\/)?\w+\.\w+/.test(url)){return false;}
var attachment=new ComposerAttachment();attachment.url=url;new AsyncRequest().setURI('/ajax/inbox/ajax.php').setData({action:'attachment',url:url}).setHandler(attachment._asyncCallback.bind(attachment)).setErrorHandler(errorCallback).send();return attachment;},setupThumbnails:function(imgs,obj){var sandbox=new ImageSandbox();sandbox.onfinish=function(){imgs=sandbox.getImages();for(var i=imgs.length-1;i>=0;i--){if(imgs[i].width&&(imgs[i].height<50||imgs[i].width<50||imgs[i].height/imgs[i].width>3||imgs[i].width/imgs[i].height>3)){imgs.splice(i,1);}}
if(!imgs.length){CSS.removeClass(obj,'loading');CSS.removeClass(obj.parentNode,'has_image');var input=obj;while(input.parentNode&&input.tagName.toLowerCase()!='form'){input=input.parentNode;}
input=input.getElementsByTagName('input');for(var i=0;i<input.length;i++){if(input[i].name.indexOf('[params][images]')!=-1){input[i].parentNode.removeChild(input[i]);}}
return;}
for(var si=0;si<imgs.length-1;si++){for(var sj=imgs.length-1;sj>=si;sj--){if(imgs[si].width*imgs[si].height<imgs[sj].width*imgs[sj].height){temp=imgs[si];imgs[si]=imgs[sj];imgs[sj]=temp;}}}
var input=obj;while(input.parentNode&&input.tagName.toLowerCase()!='form'){input=input.parentNode;}
input=input.getElementsByTagName('input');for(var i=0;i<input.length;i++){if(input[i].name.indexOf('[params][images]')!=-1){input=input[i];break;}}
CSS.removeClass(obj,'loading');new ThumbnailSelector(obj,input,imgs);}.bind(this);sandbox.loadImages(imgs);}});copy_properties(ComposerAttachment.prototype,{containerReady:function(obj,show_loading){this._container=obj;var inputs=obj.getElementsByTagName('input');var html=[''];for(var i=0;i<inputs.length;i++){if(inputs[i].type=='text'||inputs[i].type=='hidden'){html.push('<input type="hidden" name="'+htmlspecialchars(inputs[i].name)+'" value="'+htmlspecialchars(inputs[i].value)+'" />');}}
if(show_loading){html.push('&nbsp;');obj.innerHTML=html.join('');CSS.addClass(obj,'share_attachment_loading');}else{obj.innerHTML+=html.join('');}},_renderInputsRecursive:function(name,params){if(params===null){return'';}
var html=[];if(typeof(params)=='object'){for(var i in params){html.push(this._renderInputsRecursive(name+'['+i+']',params[i]));}}else if(typeof(params)!='function'){html.push('<input type="hidden" name="',name,'" value="',htmlspecialchars(params),'" />');}
return html.join('');},_asyncCallback:function(response){var payload=response.getPayload();var html=[payload.html];html.push(this._renderInputsRecursive('attachment[params]',payload.params));html.push('<input type="hidden" name="attachment[type]" value="',payload.type,'" />');CSS.removeClass(this._container,'share_attachment_loading');set_inner_html(this._container,html.join(''));}});function ThumbnailSelector(obj,input,images){var html=['<div class="thumbnail_stage"><h4>'+_tx("Choose a Thumbnail")+'</h4><div class="selector clearfix"><div class="arrows clearfix">','<span class="left"><a href="#" class="arrow disabled">&nbsp;</a></span>','<span class="right"><a href="#" class="arrow ',images.length>1?'enabled':'disabled','">&nbsp;</a></span>','</div><div class="counter"><span>1 of ',images.length,'</span></div></div>'];for(var k=0;k<images.length;k++){html.push('<div class="thumbnail',k==0?' thumbnail_selected':' thumbnail_unselected','">','<img class="img_loading" src="',images[k].src,'" onload="adjustImage(this);" />','</div>');}
html.push('<label style="white-space:nowrap"><input type="checkbox" onclick="this.parentNode.parentNode.parentNode.thumbnail.use_thumbnail(this.checked)" />'+_tx("No Picture")+'</label></div>');obj.innerHTML=html.join('');this.images=images;this.input=input;input.value=this.images[0].src;this.obj=obj;this.obj.thumbnail=this;this.label=obj.getElementsByTagName('span')[2];this.index=0;var anchors=obj.getElementsByTagName('a');this.left=anchors[0];this.right=anchors[1];this.left.onclick=this.left_arrow_press.bind(this);this.right.onclick=this.right_arrow_press.bind(this);this.left.onselectstart=this.right.onselectstart=function(){return false};this.left.onmousedown=this.right.onmousedown=this._onmousedown;this.left.onmouseout=this.right.onmouseout=this._onmouseout;}
copy_properties(ThumbnailSelector.prototype,{use_thumbnail:function(checkbox){if(!checkbox){this.move_selection(0);CSS.removeClass(this.obj,'thumbnail_dont_use');}else{this.input.value='';CSS.addClass(this.obj,'thumbnail_dont_use');}},_onmousedown:function(){CSS.addClass(this,'active');return false;},_onmouseout:function(){CSS.removeClass(this,'active');},left_arrow_press:function(){CSS.addClass(this.left,'active');this.move_selection(-1);return false;},right_arrow_press:function(){CSS.removeClass(this.right,'active');this.move_selection(1);return false;},move_selection:function(offset){var index=this.index+offset;if(index>=0&&index<this.images.length){var divs=this.obj.getElementsByTagName('div');var j=0;this.index=index;for(var i=0;i<divs.length;i++){var className=divs[i].className;if(!CSS.hasClass(divs[i],'thumbnail ')){continue;}
var selected=j==index;if(className.indexOf(selected?'_unselected':'_selected')!=-1){divs[i].className=className.replace(/thumbnail_(?:un)?selected/,selected?'thumbnail_selected':'thumbnail_unselected');}
j++;}
this.label.innerHTML=_tx("{selected} of {total}",{selected:(index+1),total:j});this.left.className=this.left.className.replace(/[^ ]+abled/,index==0?'disabled':'enabled');this.right.className=this.right.className.replace(/[^ ]+abled/,index==this.images.length-1?'disabled':'enabled');this.input.value=this.images[index].src;}}});function ImageSandbox(){this.obj=document.createElement('div');this.obj.style.left=this.obj.style.top='-100px';this.obj.style.width=this.obj.style.height='1px';this.obj.style.overflow='hidden';this.images=0;this.done=0;DOMScroll.getScrollRoot().appendChild(this.obj);}
copy_properties(ImageSandbox.prototype,{loadImages:function(imgs){this.images=imgs.length;for(var i=0;i<imgs.length;i++){new ImageSandboxLoader(this,imgs[i]);}},onImageLoaded:function(img_loader){this.done++;this._stateChange();},onImageFailed:function(img_loader){img_loader.destroy();this.images--;this._stateChange();},getImages:function(){var imgs=new Array();var collection=this.obj.getElementsByTagName('img');for(var i=0;i<collection.length;i++){imgs.push(collection[i]);}
return imgs;},_stateChange:function(){if(this.done==this.images){if(this.onfinish){this.onfinish();}}}});function ImageSandboxLoader(sandbox,img){this._timeout=4000;this._start=new Date().getTime();this._sandbox=sandbox;if(typeof img!='object'){img={src:img};}
this._obj=document.createElement('img');this._obj.onload=function(){if(this._pollImage)this._pollImage(1);}.bind(this);this._obj.onerror=function(){if(this._pollImage)this._pollImage(2);}.bind(this);copy_properties(this._obj,img);this._sandbox.obj.appendChild(this._obj);if(this._pollImage!==null){this._pollImage();}}
copy_properties(ImageSandboxLoader.prototype,{_pollImage:function(state){if(state==1){this._pollImage=null;this._sandbox.onImageLoaded(this);}else if(state==2){this._pollImage=null;this._sandbox.onImageFailed(this);}else{if(image_has_failed(this._obj)){this._pollImage(2);}else if(image_has_loaded(this._obj)){this._pollImage(1);}else if((this._start+this._timeout)<new Date().getTime()){this._pollImage(2);}else{setTimeout(function(){if(this._pollImage)this._pollImage();}.bind(this),20);}}},destroy:function(){DOM.remove(this._obj);this._obj=null;}});

function fix_attachment_more_menu_alignment(more_link){var attachment_buttons_list=ge('attachment_buttons_list');var total_width=attachment_buttons_list.offsetWidth;if(more_link){var more_offset=Vector2.getElementPosition(more_link).x;var attachments_offset=Vector2.getElementPosition(attachment_buttons_list).x;var offset=more_offset-attachments_offset;var icon_width=more_link.offsetWidth;var space_left=total_width-offset;if(space_left>=icon_width&&space_left<126){var more_menu=ge('wall_more_menu');var right_margin=0;more_menu.style.left='auto';more_menu.style.right=right_margin+'px';}}}
function wall_video_thumb_adjust(play_img_div,thumb_img){if(ua.ie()>=6&&ua.ie()<7){play_img_div.style.marginTop=(-1*thumb_img.height-3)+'px';play_img_div.style.paddingTop=(thumb_img.height-19)+'px';}
play_img_div.style.display='block';}
function attachments(context_id){this.attachment_added=false;this.attachment_oid=null;this.attachment_app_id=null;this.is_share=false;this.attached_share=false;this.scrape_last_count=0;this.dialog=null;this.wall_attachments={};this.last_url_scraped=null;this.context=context_id;this.edit_container_id='attachment_edit_container_'+context_id;this.edit_loading_id='attachment_edit_loading_'+context_id;this.edit_id='attachment_edit_'+context_id;this.view_container_id='attachment_view_container_'+context_id;this.view_wrapper_id='attachment_view_wrapper_'+context_id;this.view_id='attachment_view_'+context_id;this.remove_id='attachment_remove_'+context_id;this.view_loading_id='attachment_view_loading_'+context_id;this.is_active=false;}
attachments.prototype.show_edit_loading=function(){show(this.edit_loading_id);}
attachments.prototype.hide_edit_loading=function(){hide(this.edit_loading_id);}
attachments.prototype.show_attachment_edit=function(title,html,share_type,ajax_params){this.is_active=true;if(this.dialog){return;}
var is_app=(share_type==14);this.is_share=(share_type==100);var wrapper='<div id="'+this.edit_container_id+'">'+'<div id="'+this.edit_loading_id+'">&nbsp;</div>'+'</div>';this.dialog=new pop_dialog('attachment_dialog');this.dialog.is_stackable=true;this.dialog.show_choice(title,wrapper,_tx("Attach"),function(){if(this.is_share){this._share_attach();}else{this._attach(is_app,ajax_params,true);}
this.dialog.hide();this.dialog=null;this.is_active=false;}.bind(this),_tx("Cancel"),function(){this.dialog.fade_out(100);this.remove_attachment_view();this.dialog=null;this.is_active=false;}.bind(this));var container=ge(this.edit_container_id);var div=$N('div',{className:'share_stage attachment_edit',id:this.edit_id,is_app:is_app},HTML(html));container.appendChild(div);if(this.is_share){placeholderSetup('share_link');if(ua.ie()<7){$('share_link').focus();}}
return div;}
attachments.prototype._show_attachment_view=function(html,is_app){var container=ge(this.view_container_id);var div=$N('div',{className:'share_stage attachment_view',id:this.view_id,is_app:is_app},HTML(html));container.appendChild(div);hide('attachment_buttons_list');var wrapper=ge(this.view_wrapper_id);wrapper.style.display='block';this.attachment_added=true;return div;}
attachments.prototype.remove_attachment_view=function(){var container=ge(this.view_container_id);var attachment=ge(this.view_id);if(this.attachment_added&&attachment){this.removed=true;container.removeChild(attachment);hide(this.view_wrapper_id);if(ge('attachment_buttons_list')){show('attachment_buttons_list');}
var attachment_remove=ge(this.remove_id);attachment_remove.className=attachment_remove.className.replace(' edit','');}
this.attachment_added=false;this.attachment_oid=null;this.attachment_app_id=null;this.is_share=false;this.attached_share=false;}
attachments.prototype.get_all_form_elements=function(attachment){var inputs=[];if(attachment){var html_input=attachment.getElementsByTagName('input');for(var i=0;i<html_input.length;i++){inputs.push(html_input[i]);}
var html_select=attachment.getElementsByTagName('select');for(var i=0;i<html_select.length;i++){inputs.push(html_select[i]);}
var html_textarea=attachment.getElementsByTagName('textarea');for(var i=0;i<html_textarea.length;i++){inputs.push(html_textarea[i]);}}
return inputs;}
attachments.prototype._add_attachment_input_data=function(data,attachment){if(!attachment){return false;}
var inputs=this.get_all_form_elements(attachment);if(attachment.is_app){data['attachment']={'app':{},'type':14};for(var i=0;i<inputs.length;i++){if(!(inputs[i].type=="radio"||inputs[i].type=="checkbox")||inputs[i].checked){data['attachment']['app'][inputs[i].name]=inputs[i].value;}}}else{var has_type=false;for(var i=0;i<inputs.length;i++){if(inputs[i].name=='attachment[type]'){has_type=true;}
if(inputs[i].name=='attachment[params][url]'){if(!inputs[i].value||inputs[i].value=='http://'){return false;}}
data[inputs[i].name]=inputs[i].value;}
if(!has_type){return false;}}
data['context']=this.context;return true;}
attachments.prototype._attach=function(is_app,ajax_params,has_form_data){var asyncData={};if(has_form_data){var attachment=ge(this.edit_id);var added=this._add_attachment_input_data(asyncData,attachment);if(!added){return;}}
if(ajax_params){for(var param in ajax_params){asyncData[param]=ajax_params[param];}}
var loading=ge(this.view_loading_id);loading.style.display='block';var view_container=this._show_attachment_view('',is_app);var onDone=function(response){var responseObj=response.getPayload();if(!view_container.removed){hide(this.view_loading_id);set_inner_html(view_container,responseObj['html']);this.attachment_oid=responseObj['oid'];this.attachment_app_id=responseObj['app_id'];}}.bind(this);new AsyncRequest().setHandler(onDone).setURI('/ajax/attachments.php').setErrorHandler(this.remove_attachment_view).setTransportErrorHandler(this.remove_attachment_view).setData(asyncData).send();}
attachments.prototype.add_post_data=function(post_data){if(this.attachment_added){if(this.attached_share){this._add_attachment_input_data(post_data,ge(this.view_id));}else{post_data['attachment']={'oid':this.attachment_oid,'app_id':this.attachment_app_id};}}}
attachments.prototype.prepare_wall_post=function(){var attachment=ge(this.view_id);if(attachment){var inputs=this.get_all_form_elements(attachment);for(var i=0;i<inputs.length;i++){inputs[i].disabled=true;}}}
attachments.prototype.show_full_attachment=function(post_id){if(typeof this.wall_attachments[post_id]!='string'){return;}
hide('attachment_compact_'+post_id);hide('attached_item_info_'+post_id);hide('attachment_compact_td_'+post_id);attachment_div=ge('wall_attachment_'+post_id);set_inner_html(attachment_div,this.wall_attachments[post_id]);}
attachments.prototype.fix_app_inputs_on_send=function(){var attachment=ge(this.view_id);if(!this.attachment_added||!attachment){return;}
if(!this.attached_share){new_inputs=[];new_inputs.push(create_hidden_input('attachment[oid]',this.attachment_oid));new_inputs.push(create_hidden_input('attachment[app_id]',this.attachment_app_id));if(attachment.is_app){new_inputs.push(create_hidden_input('attachment[type]',14));new_inputs.push(create_hidden_input('attachment[app][message_sent]',true));}
for(var i=0,il=new_inputs.length;i<il;i++){attachment.appendChild(new_inputs[i]);}}}
attachments.prototype.share_attach_from_dialog=function(){this._share_attach();generic_dialog.get_dialog(ge(this.edit_container_id)).hide();this.dialog=null;}
attachments.prototype._share_attach=function(){var share_link=ge('share_link');var url=share_link.value;if(url&&url!='http://'){this._share_submit_url(url);}}
attachments.prototype._share_submit_url=function(url){this._show_attachment_view(this.share_html_block,false);var view_container=ge(this.view_container_id);var stage_area=view_container.childNodes[0].childNodes[0].childNodes[0];this._attach_link_url(stage_area,url,true);var attachment_remove=ge(this.remove_id);attachment_remove.className+=' edit';this.attached_share=true;}
attachments.prototype._attach_link_url=function(obj,url,show_loading){var errorCallback=function(resp){this.remove_attachment_view();}.bind(this);var attachment=ComposerAttachment.newFromURL(url,errorCallback);attachment.containerReady(obj,show_loading);}
attachments.prototype._is_fb_code_url=function(url){return url.search('fb:')==0;}
attachments.prototype._detect_url=function(obj,force){var url='';var start_position=-1;var end_position=-1;if(force==true){if(url=obj.value.match(/www\.\S*/i)){start_position=obj.value.indexOf(url[0]);end_position=start_position+url[0].length;url="http://"+url[0];}else{var match='';if(match=obj.value.match(/(http|fb):\/\/\S*/i)){url=match[0];start_position=obj.value.indexOf(match[0]);end_position=start_position+match[0].length;}}}else{if(url=obj.value.match(/www\.\S*[\s|\)|\!]/i)){start_position=obj.value.indexOf(url[0]);end_position=start_position+url[0].length;url="http://"+url[0];}else{var match='';if(match=obj.value.match(/(http|fb):\/\/\S*[\s|\)|\!]/i)){url=match[0];start_position=obj.value.indexOf(match[0]);end_position=start_position+match[0].length;}}}
if(url){url=url.replace(/[\s|\)|\!]/g,'');var last_char=url.charAt(url.length-1);if(last_char.match(/[,|.]/)){url=url.substr(0,url.length-1);}
var cursor_position=DOM.getCaretPosition(obj).start;if(url!=this.last_url_scraped&&cursor_position&&start_position>=0&&end_position>=0&&(cursor_position<start_position||cursor_position>=end_position)){this.last_url_scraped=url;if(this._is_fb_code_url(url)){obj.value=obj.value.substr(0,start_position)+obj.value.substr(end_position);}}else{url='';}}
return url;}
attachments.prototype._auto_scrape_url=function(obj){if(this.attachment_added){return false;}
if(!this.scrape_last_count){this.scrape_last_count=0;}
if((obj.value.length-this.scrape_last_count)>5||(this.scrape_last_count==0&&obj.value.length>1)){var force=true;}
var url=this._detect_url(obj,force);if(url){if(this._is_fb_code_url(url)){var data={'code':url,'context':this.context};this._attach(true,data,false);}else{this._share_submit_url(url);}}
this.scrape_last_count=obj.value.length;return false;}
attachments.prototype.start_textarea_interval=function(obj){this.textarea_obj=obj;this.textarea_interval=setInterval(this._textarea_interval_function.bind(this),50);}
attachments.prototype._textarea_interval_function=function(){if(typeof this!='undefined'&&this.textarea_obj&&(!this.attachment_added&&ge(this.view_wrapper_id))){this._auto_scrape_url(this.textarea_obj);}else{this.stop_textarea_interval();}}
attachments.prototype.stop_textarea_interval=function(){clearInterval(this.textarea_interval);}

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){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){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(document.postMessage){document.addEventListener('message',handleChanneliFrameMessageEvent,false);}else if(window.postMessage){window.addEventListener('message',handleChanneliFrameMessageEvent,false);}
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){this.postMessage=this.subframe.contentWindow.postMessage.bind(this.subframe.contentWindow);}else if(document.postMessage){this.postMessage=window.parent.document.postMessage.bind(window.parent.document);this.postMessage=this.subframe.contentDocument.postMessage.bind(this.subframe.contentDocument);}else{this.postMessage=this.subframe.contentWindow.handleChannelParentMessage.bind(this.subframe.contentWindow);}
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.contentPaddings={'buddy_list':54,'presence_notifications':23,'presence_applications':43};this.contentResized={};this.holder=$('presence');this.holderUI=$('presence_ui');this.barButtons=$('presence_bar_buttons');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=verifyBool(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((typeof buddyList!='undefined')&&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;}}
var wasFocused=this.focusedTab;this.focusedTab=this.focusedWrapper=null;return wasFocused;},unfocus:function(){var wasFocused=this._unfocus();if(wasFocused){this.disableUnfocus=wasFocused;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;}
this.unfocus();CSS.removeClass(tab,'focused');CSS.removeClass(this.holder,'tab_open');for(var i=0;i<this.tabCloseHandlers.length;i++){this.tabCloseHandlers[i]();}},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<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().show_prompt(_tx("Facebook Chat Error"),'<div class="dialog_body">'+
reason+'</div>');}
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 verifyBool(bool){if(typeof bool=='undefined'){bool=false;}
return bool==0?false:true;}

function Sound(){Sound.play('/sound/quack.mp3');}
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');DOMScroll.getScrollRoot().appendChild(embed);}
embed.innerHTML='<embed src="'+path+'" autostart="true" hidden="true" />';}});

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

function ChatTab(chatDisplay,id,name,firstName,numMissed){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.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,maxStatusLen:90,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(false);}else{this.chatDisplay.userInfos[this.id]={'name':this.name,'firstName':this.firstName,'thumbSrc':'','status':''};}},_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(false);if(historyPayload.fls){buddyList.setFlids(this.id,historyPayload.fls);}
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)).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);var pendingMsg=this.pendingSentMsgs[0];var pendingMsgID=pendingMsg.msgID;var msgElement=ge('msg_'+this.id+'_'+pendingMsgID);if(msgElement){var mesg;if(this.pendingSentMsgs.length>1){var texts=[];for(var i=0;i<this.pendingSentMsgs.length;i++){texts.push(this.pendingSentMsgs[i].text);}
mesg=texts.join('\n');desc=_tx("{name} is no longer online. The following were not sent",{'name':this.firstName});}else{mesg=pendingMsg.text;}
var onclick=sprintf('onclick="message_dialog.show(%d, %e, %e); return false;"',this.id,'',mesg);var link=presence.renderLink(this.chatDisplay.messageURL+'&id='+this.id,_tx("send as a message"),onclick);var text=_tx(" ({send-as-a-message})",{'send-as-a-message':link});if(this.pendingSentMsgs.length>1){desc+=text;}else{msgElement.innerHTML+=text;}}}
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};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,pendingMsg.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){if(status.length>this.maxStatusLen){status=status.substring(0,this.maxStatusLen-2)+'...';}
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(true);},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();this.convMouseMoved=false;},chatConvOnMouseMove:function(){this.convMouseMoved=true;},chatConvOnMouseUp:function(){if(!this.convMouseMoved){this.focusChatInput();}
this.convMouseMoved=false;},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()" ','onmousemove="',this.tabRef,'.chatConvOnMouseMove()">','<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){chatTabBar.insertBefore(this.tabHandle,otherTab.tabHandle);}else{chatTabBar.appendChild(this.tabHandle);}
DOM.setID(this.tabHandle,'tab_handle_'+this.id);this.tabHandle.className='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._updateTabCount();},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(this.tabDisabled){heightExtra+=15;}
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._setNumMissed(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){var popoutCountID='popout_tab_count_'+this.id;this.popoutTab=$N('div',{id:'popout_tab_'+this.id,className:('popout_tab_button'
+(this.chatDisplay.gatedFeatures.typ_show?'':' vanilla')
+((id==this.chatDisplay.focused)?' highlight':''))},HTML('<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._setNumMissed(this.numMissed+1);this._startBounce();}
if(presence.inPopoutWindow){CSS.removeClass(this.popoutTab,'typing');}
CSS.removeClass(this.tabHandle,'typing');}else{this._setNumMissed(0);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;}},_setNumMissed:function(numMissed){if(numMissed==this.numMissed){return;}
if(numMissed>99){numMissed=99;}
this.numMissed=numMissed;this._updateTabCount();},_updateTabCount: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">'+
this._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 textProcessor=statusControl.showEmoticons?this.convTextEmoteProcessor:this.convTextProcessor;var htmlizedText=html_hyperlink(msg.text,textProcessor,this.convTextProcessor,true);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=this._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+'">'+
htmlizedText+'</p>';return markup;},_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);},_renderServerTime:function(serverTimeMS){var time=new Date();time.setTime(serverTimeMS+presence.timeSkew);var hours=time.getHours();var ampm='am';if(hours>=12){ampm='pm';}
if(hours==0){hours=12;}else if(hours>12){hours-=12;}
var minutes=time.getMinutes();if(minutes<10){minutes='0'+minutes;}
var timeStr=hours+':'+minutes+ampm;return timeStr;}};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,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._init();}
ChatDisplay.prototype={blinkTime:1500,initialBlinkDelay:3000,_init:function(){this.loaded=false;this.tabs={};this.numTabs=0;this.focused=null;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;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();}},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();}
try{this.chatActivityTime=verifyNumber(presenceState.ct)*1000;var firstTab=null;if(!this.loaded&&ua.ie()<7){presenceState.t={};presenceState.f=null;}
for(var id in presenceState.t){if(!firstTab){firstTab=id;}
if(!this.tabs[id]){var tabInfo=presenceState.t[id];var name=tabInfo.n;var firstName=tabInfo.fn?tabInfo.fn:getFirstName(name);var numMissed=useNumMissed?verifyNumber(tabInfo.m):0;this.tabs[id]=new ChatTab(this,id,name,firstName,numMissed);this.numTabs++;}}
if(!this.loaded&&presence.inPopoutWindow&&!presenceState.f&&firstTab){presenceState.f=firstTab;}
if(presenceState.f!=this.focused){if(presenceState.f){this._focusTab(presenceState.f);if(presence.inPopoutWindow){window.focus();}}else{this._unfocus();}}
for(var id in this.tabs){if(!presenceState.t[id]){this._closeTab(id);}}}catch(e){presence.error('chat: error loading state: '+e.toString());}}
this.loaded=true;},_store:function(presenceState){presenceState.ct=parseInt(this.chatActivityTime*0.001);presenceState.t={};presenceState.f=this.focused;for(var id in this.tabs){var tab=this.tabs[id];presenceState.t[id]={n:tab.name,m:tab.numMissed};if(tab.firstName!=getFirstName(tab.name)){presenceState.t[id].fn=tab.firstName;}}
presenceState.sb=(this.blinkingTimer==null)?1:0;return presenceState;},handleResize:function(){if(!this.focused){return;}
var tab=this.tabs[this.focused];tab.handleResize();},reloadTabs:function(){for(var id in this.tabs){this.tabs[id].loadData();}},_closeTab:function(id){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);presence.doSync();},_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){presence.doSync();}
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 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;this.tabs[this.focused].focus(hidden,loaded);if(presence.poppedOut)this.tabs[id].selectPopoutChat();}).bind(this).defer();}},focusTab:function(id,name,firstName){this._focusTab(id,name,firstName);this.doStopBlinking();this.chatActivityTime=(new Date()).getTime();presence.doSync();},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;}},focusTextBox:function(){if(this.focused&&!(document.getSelection?document.getSelection():document.selection.createRange().text))
{this.tabs[this.focused].textBox.focus();}},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];}
switch(obj.type){case'msg':var fromMe=(obj.from==this.user);buddyList.setAvailable(id,fromMe);if(!tab){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);}
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];}};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);}

var Drag={};Drag.currentDraggable=null;Drag.grab=function(draggable){if(Drag.currentDraggable){Drag._onmouseup();}
draggable.lastDragOver=null;Drag.attachDragEvents();Drag.currentDraggable=draggable;}
Drag.attachDragEvents=function(){document.onselectstart=function(){document.onselectstart=null;return false;}
if(Drag.dragEventsAttached){return;}
Drag.dragEventsAttached=true;Event.listen(document,'mousemove',Drag._onmousemove);Event.listen(document,'mouseup',Drag._onmouseup);}
Drag.droppables={};Drag.addDroppable=function(namespace,droppable){(Drag.droppables[namespace]=Drag.droppables[namespace]||[]).push(droppable);}
Drag.removeDroppable=function(namespace,droppable){Drag.droppables[namespace].filter(function(a){a!=droppable;});}
Drag._onmousemove=function(event){if(!Drag.currentDraggable){return;}
var cursorPosition=Vector2.getEventPosition(event),currentDraggable=Drag.currentDraggable,droppables=Drag.droppables[currentDraggable.namespace];if(currentDraggable.namespace&&currentDraggable.active&&droppables){var zIndexesDict={};droppables.each(function(droppable){zIndexesDict[droppable.zIndex]=droppable.zIndex;});var zIndexes=[];for(var i in zIndexesDict){zIndexes.push(zIndexesDict[i]);}
zIndexes.sort();var lastDragOver=currentDraggable.lastDragOver,currentDragOver=null;for(var z=zIndexes.length;z>=0;z--){if(lastDragOver&&lastDragOver.zIndex==zIndexes[z]&&lastDragOver.pointInside(cursorPosition)){currentDragOver=lastDragOver;break;}else{for(var i=0;i<droppables.length;i++){if(zIndexes[z]!=droppables[i].zIndex){continue;}
if(lastDragOver!=droppables[i]&&currentDraggable.dom!=droppables[i].dom&&droppables[i].pointInside(cursorPosition)){currentDragOver=droppables[i];z=-1;break;}}}}
if(currentDragOver&&currentDragOver!=lastDragOver){currentDragOver.ondragover(currentDraggable);}
if(currentDragOver){currentDragOver.ondragmove(currentDraggable,cursorPosition.sub(Vector2.getElementPosition(currentDragOver.dom)));}
currentDraggable.lastDragOver=currentDragOver;}
Drag.currentDraggable._onmousemove(cursorPosition);}
Drag._onmouseup=function(){document.onselectstart=null;if(Drag.currentDraggable){Drag.currentDraggable._ondrop();Drag.currentDraggable=null;}}
function Draggable(element){if(this==window){if(element instanceof Array){var collection=[];element.each(function(instance){collection.push(new Draggable(instance));});return new Collection(Draggable,collection);}else{return new Draggable(element);}}else{this.data={};this.handles=[];this.dom=element;this.addHandle(this.dom);}}
Draggable.prototype.destroy=function(){this.handles.each(function(handle){this.removeHandle(handle.dom);}.bind(this));this.data=this.dom=null;}
Draggable.prototype._onclick=function(event){if(this.active){return Event.kill(event);}}
Draggable.prototype._ongrab=function(){this.ongrab();if(!this.oldPosition){this.oldPosition=this.dom.style.position;}
this.dom.style.position=this.absolute?'absolute':'relative';}
Draggable.prototype._onmousedown=function(event){var target=$E(event).getTarget();if(is_node(target,['input','select','textarea','object','embed'])){return true;}
var vector=Vector2.getEventPosition(event);this.cursorPositionVector=vector.sub(Vector2.getElementPosition(this.dom));Drag.grab(this,event);if(this.gutter){this.cursorInitialVector=vector;}else{this._setActive(true);this._ongrab();}
return Event.kill(event);}
Draggable.prototype._onmousemove=function(vector){if(!this.active){if(vector.distanceTo(this.cursorInitialVector)>=this.gutter){this._setActive(true);this._ongrab();}}
if(this.active){vector.sub(Vector2.getElementPosition(this.dom).sub(new Vector2(parseInt(this.dom.style.left?this.dom.style.left:CSS.getStyle(this.dom,'left'),10)||0,parseInt(this.dom.style.top?this.dom.style.top:CSS.getStyle(this.dom,'top'),10)||0))).sub(this.cursorPositionVector).setElementPosition(this.dom);this.ondrag(vector);}}
Draggable.prototype._ondrop=function(){if(this.active){(function(){this._setActive(false);}).bind(this).defer();this.ondrop();if(this.lastDragOver){this.lastDragOver.ondrop(this);}}}
Draggable.prototype.resetPosition=function(){this.dom.style.position=this.oldPosition;this.oldPosition=null;this.dom.style.left=null;this.dom.style.top=null;return this;}
Draggable.prototype.setUseAbsolute=function(absolute){this.absolute=absolute;return this;}
Draggable.prototype.ondrag=bagofholding;Draggable.prototype.setDragHandler=function(func){this.ondrag=func;return this;}
Draggable.prototype.ongrab=bagofholding;Draggable.prototype.setGrabHandler=function(func){this.ongrab=func;return this;}
Draggable.prototype.ondrop=bagofholding;Draggable.prototype.setDropHandler=function(func){this.ondrop=func;return this;}
Draggable.prototype.gutter=0;Draggable.prototype.setGutter=function(gutter){this.gutter=gutter;return this;}
Draggable.prototype.setNamespace=function(namespace){this.namespace=namespace;return this;}
Draggable.prototype.handles=null;Draggable.prototype.addHandle=function(handle){if(this.handles.length==1&&this.handles[0]==this.dom){this.removeHandle(this.dom);}
this.handles.push({obj:handle,evt:[Event.listen(handle,'mousedown',this._onmousedown.bind(this)),Event.listen(handle,'click',this._onclick.bind(this)),Event.listen(handle,'drag',Event.kill),Event.listen(handle,'selectstart',Event.kill)]});return this;}
Draggable.prototype.removeHandle=function(handle){this.handles.filter(function(a){if(a.dom!=handle){return true;}else{a.evt.each(function(evt){evt.remove();});return false;}});}
Draggable.prototype.getDOM=function(){return this.dom;}
Draggable.prototype.setKey=function(key,value){this.data[key]=value;return this;}
Draggable.prototype.getKey=function(key){return this.data[key];}
Draggable.prototype._setActive=function(state){this.dom.activeDrag=this.active=state;for(var i=0;i<this.handles.length;i++){this.handles[i].obj.activeDrag=state;}}
function Droppable(element){if(this==window){if(element instanceof Array){var collection=[];element.each(function(instance){collection.push(new Droppable(instance));});return new Collection(Droppable,collection);}else{return new Droppable(element);}}else{this.data={};this.dom=element;this.namespace=null;}}
Droppable.prototype.destroy=function(){if(this.namespace){Drag.removeDroppable(this.namespace,this);}
this.data=this.dom=null;}
Droppable.prototype.setNamespace=function(namespace){if(this.namespace){Drag.removeDroppable(namespace,this);}
Drag.addDroppable(namespace,this);return this;}
Droppable.prototype.zIndex=0;Droppable.prototype.setZIndex=function(index){this.zIndex=index;return this;}
Droppable.prototype.pointInside=function(vector){var position=Vector2.getElementPosition(this.dom);return position.x<=vector.x&&this.dom.offsetWidth+position.x>vector.x&&position.y<=vector.y&&this.dom.offsetHeight+position.y>vector.y;}
Droppable.prototype.ondragover=bagofholding;Droppable.prototype.setDragOverHandler=function(func){this.ondragover=func;return this;}
Droppable.prototype.ondragmove=bagofholding;Droppable.prototype.setDragMoveHandler=function(func){this.ondragmove=func;return this;}
Droppable.prototype.ondrop=bagofholding;Droppable.prototype.setDropHandler=function(func){this.ondrop=func;return this;}
Droppable.prototype.getDOM=Draggable.prototype.getDOM;Droppable.prototype.setKey=Draggable.prototype.setKey;Droppable.prototype.getKey=Draggable.prototype.getKey;

function SortableGroup(){this.namespace='sortable'+(++SortableGroup.instanceCount);this.draggables={};this.droppables={};this.sortables={};this.linkedGroups=[];this.linkedGroups.onlinkjump=bagofholding;this.rootNode=null;}
SortableGroup.instanceCount=0;SortableGroup.prototype.gutter=15;SortableGroup.prototype.addSortable=function(key,obj,handle){if(this.rootNode===null){this.rootNode=obj.parentNode;if(!this.linkedGroups.placeholder){this.linkedGroups.placeholder=this.placeholder=$N(obj.tagName,{className:'dragPlaceholder',style:{padding:'0px'}});}else{this.placeholder=this.linkedGroups.placeholder;}}else if(this.rootNode!=obj.parentNode){throw new Error('All sortables of a collection must share the same parentNode');}
if(key in this.draggables){throw new Error('All sortables must have a unique key');}
this.sortables[key]=obj;this.draggables[key]=(new Draggable(obj)).setNamespace(this.namespace).setGutter(this.gutter).setUseAbsolute(true).setGrabHandler(this.grabHandler.bind(this,key)).setDropHandler(this.dropHandler.bind(this,key)).setKey('key',key);if(handle){this.draggables[key].addHandle(handle);}
this.droppables[key]=(new Droppable(obj)).setNamespace(this.namespace).setDragOverHandler(this._dragOverHandlerShim.bind(null,this,key));return this;}
SortableGroup.prototype.link=function(sortgroup){sortgroup.linkedGroups=this.linkedGroups;if(!this.linkedGroups.length){this.linkedGroups.push(this);}
this.linkedGroups.push(sortgroup);for(var i=0;i<this.linkedGroups.length;i++){if(this.linkedGroups[i].namespace!=this.namespace){this.linkedGroups[i].namespace=this.namespace;for(var j in this.linkedGroups[i].droppables){this.linkedGroups[i].droppables[j].setNamespace(this.namespace);this.linkedGroups[i].draggables[j].setNamespace(this.namespace);}}}
return this;}
SortableGroup.prototype.getOrder=function(){if(!this.rootNode){return[];}
var ret=[],childNodes=this.rootNode.childNodes;for(var i=0;i<childNodes.length;i++){for(var k in this.sortables){if(this.sortables[k]==childNodes[i]){ret.push(k);break;}}}
return ret;}
SortableGroup.prototype.migrateLinkedSortable=function(key){for(var i=0;i<this.linkedGroups.length;i++){if(key in this.linkedGroups[i].draggables){this.sortables[key]=this.linkedGroups[i].sortables[key];this.draggables[key]=this.linkedGroups[i].draggables[key];this.draggables[key].setGrabHandler(this.grabHandler.bind(this,key)).setDropHandler(this.dropHandler.bind(this,key));this.droppables[key]=this.linkedGroups[i].droppables[key];this.droppables[key].setDragOverHandler(this._dragOverHandlerShim.bind(null,this,key));delete this.linkedGroups[i].sortables[key];delete this.linkedGroups[i].draggables[key];delete this.linkedGroups[i].droppables[key];return true;}}
return false;}
SortableGroup.prototype.setLinkJumpHandler=function(func){this.linkedGroups.onlinkjump=func;}
SortableGroup.prototype.onorderchange=bagofholding;SortableGroup.prototype.setOrderChangeHandler=function(func){this.onorderchange=func;}
SortableGroup.prototype.ongrabcallback=bagofholding;SortableGroup.prototype.setGrabCallback=function(func){this.ongrabcallback=func;return this;}
SortableGroup.prototype.grabHandler=function(draggableKey){this.placeholder.className=this.sortables[draggableKey].className;CSS.addClass(this.sortables[draggableKey],'drag');Vector2.getElementDimensions(this.sortables[draggableKey]).setElementDimensions(this.placeholder);this.rootNode.insertBefore(this.placeholder,this.sortables[draggableKey]);this.ongrabcallback(draggableKey);}
SortableGroup.prototype.ondropcallback=bagofholding;SortableGroup.prototype.setDropCallback=function(func){this.ondropcallback=func;return this;}
SortableGroup.prototype.dropHandler=function(draggableKey){CSS.removeClass(this.sortables[draggableKey],'drag');this.draggables[draggableKey].resetPosition();this.rootNode.insertBefore(this.sortables[draggableKey],this.placeholder);this.rootNode.removeChild(this.placeholder);this.ondropcallback(draggableKey);this.onorderchange();}
SortableGroup.prototype._dragOverHandlerShim=function(that,droppableKey,draggable){that.dragOverHandler(droppableKey,draggable.getKey('key'));};SortableGroup.prototype.dragOverHandler=function(droppableKey,draggableKey){var jumped=false;if(!(draggableKey in this.draggables)){if(!this.migrateLinkedSortable(draggableKey)){throw new Error('Draggable dropped onto a foreign droppable!');}
jumped=true;}
var before=true,childNodes=this.rootNode.childNodes,droppable=this.sortables[droppableKey],draggable=this.sortables[draggableKey];for(var i=0;i<childNodes.length;i++){if(childNodes[i]==droppable){break;}else if(childNodes[i]==draggable){before=false;break;}}
if(before){this.rootNode.insertBefore(draggable,droppable);}else{this.rootNode.insertBefore(droppable,draggable);}
this.rootNode.insertBefore(this.placeholder,draggable);if(jumped){this.linkedGroups.onlinkjump.call(this,draggableKey);}}
SortableGroup.prototype.destroy=function(){for(var k in this.droppables){this.droppables[k].destroy();}
for(var k in this.draggables){this.draggables[k].destroy();}
this.droppables=this.draggables=this.rootNode=null;}
SortableGroup.prototype.removeSortable=function(key){this.draggables[key].destroy();this.droppables[key].destroy();delete this.draggables[key];delete this.droppables[key];}

function typeaheadpro(obj,source,properties){if(!typeaheadpro.hacks){typeaheadpro.should_check_missing_events=ua.safari()<500;typeaheadpro.should_simulate_keypress=(ua.ie()<8)||(ua.safari()>500&&ua.safari()<523||ua.safari()>=525);if(typeaheadpro.should_use_iframe==undefined){typeaheadpro.should_use_iframe=typeaheadpro.should_simulate_keypress;}
typeaheadpro.should_use_overflow=ua.opera()<9.5||ua.safari()<500;if(ua.firefox()){this.activate_poll_on_focus_events=true;}
typeaheadpro.hacks=true;}
typeaheadpro.instances=(typeaheadpro.instances||[]);typeaheadpro.instances.push(this);this.instance=typeaheadpro.instances.length-1;copy_properties(this,properties||{});this.obj=obj;this.obj.typeahead=this;this.obj.onfocus=this._onfocus.bind(this);this.obj.onblur=chain(this.obj.onblur,this._onblur.bind(this));this.obj.onchange=this._onchange.bind(this);this.obj.onkeyup=function(event){return this._onkeyup(event||window.event);}.bind(this);this.obj.onkeydown=function(event){return this._onkeydown(event||window.event);}.bind(this);this.obj.onkeypress=function(event){return this._onkeypress(event||window.event);}.bind(this);this.want_icon_list=false;this.showing_icon_list=false;this.stop_suggestion_select=false;if(this.typeahead_icon_class&&this.typeahead_icon_get_return){this.typeahead_icon=document.createElement('div');CSS.addClass(this.typeahead_icon,'typeahead_list_icon');CSS.addClass(this.typeahead_icon,this.typeahead_icon_class);this.typeahead_icon.innerHTML='&nbsp;';this.setup_typeahead_icon();setTimeout(function(){this.focus();}.bind(this),50);this.typeahead_icon.onmousedown=function(event){return this.typeahead_icon_onclick(event||window.event);}.bind(this);}
this.focused=this.focused||this.obj.offsetWidth?true:false;this.anchor=this.setup_anchor();this.dropdown=document.createElement('div');CSS.addClass(this.dropdown,'typeahead_list');if(!this.focused){this.dropdown.style.display='none';}
this.anchor_block=this.anchor_block||this.anchor.tagName.toLowerCase()=='div';DOMScroll.getScrollRoot().appendChild(this.dropdown);this.dropdown.className+=' typeahead_list_absolute';this.dropdown.appendChild(this.list=document.createElement('div'));this.dropdown.onmousedown=function(event){return this.dropdown_onmousedown(event||window.event);}.bind(this);if(typeaheadpro.should_use_iframe&&!typeaheadpro.iframe){typeaheadpro.iframe=document.createElement('iframe');typeaheadpro.iframe.src="/common/blank.html";typeaheadpro.iframe.className='typeahead_iframe';typeaheadpro.iframe.style.display='none';typeaheadpro.iframe.frameBorder=0;DOMScroll.getScrollRoot().appendChild(typeaheadpro.iframe);}
if(typeaheadpro.should_use_iframe&&typeaheadpro.iframe){typeaheadpro.iframe.style.zIndex=parseInt(CSS.getStyle(this.dropdown,'zIndex'))-1;}
this.log_data={'kt':0,'kp':0,'sm':null};this.results_text='';this.last_key_suggestion=0;this.status=typeaheadpro.STATUS_BLOCK_ON_SOURCE_BOOTSTRAP;this.clear_placeholder();if(source){this.set_source(source);}
if(this.source){this.selectedindex=-1;if(this.focused){this._onfocus();this.show();this._onkeyup();this.set_class('');this.capture_submit();}}else{this.hide();}
onunloadRegister(bind(this,'hide'),true);}
typeaheadpro.prototype.enumerate=false;typeaheadpro.prototype.interactive=false;typeaheadpro.prototype.changed=false;typeaheadpro.prototype.render_block_size=50;typeaheadpro.prototype.typeahead_icon_class=false;typeaheadpro.prototype.typeahead_icon_get_return=false;typeaheadpro.prototype.old_value="";typeaheadpro.prototype.poll_handle=null;typeaheadpro.prototype.activate_poll_on_focus_events=false;typeaheadpro.prototype.suggestion_count=0;typeaheadpro.STATUS_IDLE=0;typeaheadpro.STATUS_WAITING_ON_SOURCE=1;typeaheadpro.STATUS_BLOCK_ON_SOURCE_BOOTSTRAP=2;typeaheadpro.prototype.clear_value_on_blur=true;typeaheadpro.prototype.max_results=0;typeaheadpro.prototype.max_display=10;typeaheadpro.prototype.allow_placeholders=false;typeaheadpro.prototype.auto_select=true;typeaheadpro.dirty_instances=function(){if(typeaheadpro.instances){typeaheadpro.instances.forEach(function(instance){instance.update_status(typeaheadpro.STATUS_BLOCK_ON_SOURCE_BOOTSTRAP);if(instance.source){instance.source.is_ready=false;}});}}
typeaheadpro.prototype.set_source=function(source){this.source=source;this.source.set_owner(this);this.status=typeaheadpro.STATUS_IDLE;this.cache={};this.last_search=0;this.suggestions=[];}
typeaheadpro.prototype.setup_anchor=function(){return this.obj;}
typeaheadpro.prototype.destroy=function(){if(this.typeahead_icon){DOM.remove(this.typeahead_icon);this.toggle_icon_list=function(){};}
this.clear_render_timeouts();if(!this.anchor_block&&this.anchor.nextSibling.tagName.toLowerCase()=='br'){DOM.remove(this.anchor.nextSibling);}
if(this.dropdown){DOM.remove(this.dropdown);}
if(this.obj){this.obj.onfocus=this.obj.onblur=this.obj.onkeyup=this.obj.onkeydown=this.obj.onkeypress=this.obj.typeahead=null;DOM.remove(this.obj);}
this.anchor=this.obj=this.dropdown=null;delete typeaheadpro.instances[this.instance];}
typeaheadpro.prototype.check_value=function(){if(this.obj){var new_value=this.obj.value;if(new_value!=this.old_value){this.dirty_results();this.old_value=new_value;}}}
typeaheadpro.prototype._onkeyup=function(e){this.last_key=e?e.keyCode:-1;if(this.key_down==this.last_key){this.key_down=0;}
switch(this.last_key){case 27:this.selectedindex=-1;this._onselect(false);this.hide();break;}}
typeaheadpro.prototype._onkeydown=function(e){this.key_down=this.last_key=e?e.keyCode:-1;this.interactive=true;switch(this.last_key){case 33:case 34:case KEYS.UP:case KEYS.DOWN:this.log_data.kt+=1;if(typeaheadpro.should_simulate_keypress){this._onkeypress({keyCode:this.last_key});}
return false;case KEYS.TAB:this.log_data.kt+=1;this.select_suggestion(this.selectedindex);if(e.shiftKey){this.reverse_focus();}else{this.advance_focus();}
break;case KEYS.RETURN:this.log_data.sm='key_ret';if(this.select_suggestion(this.selectedindex)){this.hide();}
if(typeof(this.submit_keydown_return)!='undefined'){this.submit_keydown_return=this._onsubmit(this.get_current_selection());}
return this.submit_keydown_return;case 229:if(!this.poll_handle){this.poll_handle=setInterval(this.check_value.bind(this),100);}
break;default:this.log_data.kp+=1;setTimeout(bind(this,'check_value'),10);}}
typeaheadpro.prototype._onkeypress=function(e){var multiplier=1;this.last_key=e?event_get_keypress_keycode(e):-1;this.interactive=true;switch(this.last_key){case 33:multiplier=this.max_display;case KEYS.UP:this.set_suggestion(multiplier>1&&this.selectedindex>0&&this.selectedindex<multiplier?0:this.selectedindex-multiplier);this.last_key_suggestion=(new Date()).getTime();return false;case 34:multiplier=this.max_display;case KEYS.DOWN:if(trim(this.get_value())==''&&!this.enumerate){this.enumerate=true;this.results_text=null;this.dirty_results();}else{this.set_suggestion(this.suggestions.length<=this.selectedindex+multiplier?this.suggestions.length-1:this.selectedindex+multiplier);this.last_key_suggestion=(new Date()).getTime();}
return false;case KEYS.RETURN:var ret=null;if(typeof(this.submit_keydown_return)=='undefined'){ret=this.submit_keydown_return=this._onsubmit(this.get_current_selection());}else{ret=this.submit_keydown_return;delete this.submit_keydown_return;}
return ret;default:setTimeout(bind(this,'check_value'),10);break;}
return true;}
typeaheadpro.prototype._onchange=function(){this.changed=true;}
typeaheadpro.prototype._onfound=function(obj){return this.onfound?this.onfound.call(this,obj):true;}
typeaheadpro.prototype._onsubmit=function(obj){if(this.onsubmit){var ret=this.onsubmit.call(this,obj);if(ret&&this.obj.form){if(!this.obj.form.onsubmit||this.obj.form.onsubmit()){this.obj.form.submit();}
return false;}
return ret;}else{this.advance_focus();return false;}}
typeaheadpro.prototype._onselect=function(obj){var call_select_handler=(function(){if(this.onselect){this.onselect.call(this,obj);}}).bind(this);if(obj.no_email){var async=new AsyncRequest().setData({action:'require',require_field:'email',uid:obj.i}).setMethod('GET').setReadOnly(true).setURI('/friends/ajax/external.php');new Dialog().setCloseHandler(function(typeahead){var email=this.getUserData();if(email){call_select_handler();}else{typeahead.set_value('');}}.bind(null,this)).setAsync(async).show();}else{call_select_handler();}}
typeaheadpro.prototype._onfocus=function(){if(!this.poll_handle&&this.activate_poll_on_focus_events){this.poll_handle=setInterval(this.check_value.bind(this),100);}
if(this.source){this.source.bootstrap();}
if(this.last_dropdown_mouse>(new Date()).getTime()-10||this.focused){return;}
if(this.changed){this.dirty_results();}
this.focused=true;this.changed=false;this.clear_placeholder();this.results_text='';this.set_class('');this.show();this.capture_submit();if(this.typeahead_icon){show(this.typeahead_icon);}}
typeaheadpro.prototype._onblur=function(event){if(this.last_dropdown_mouse&&this.last_dropdown_mouse>(new Date()).getTime()-10){Event.kill(event);setTimeout(function(){this.focus();}.bind(this),0);return false;}
if(!this.stop_hiding){if(this.showing_icon_list){this.toggle_icon_list(true);}}else{this.focus();return false;}
this.focused=false;if(this.changed&&!this.interactive){this.dirty_results();this.changed=false;return;}
if(!this.suggestions){this._onselect(false);}else if(this.selectedindex>=0&&this.auto_select){this.select_suggestion(this.selectedindex);}
this.hide();this.update_class();if(this.clear_value_on_blur&&!this.get_value()){var noinput=this.allow_placeholders?this.source.gen_noinput():'';this.set_value(noinput?noinput:'');this.set_class('typeahead_placeholder')}
if(this.poll_handle){clearInterval(this.poll_handle);this.poll_handle=null;}}
typeaheadpro.prototype.typeahead_icon_onclick=function(event){this.stop_hiding=true;this.focus();setTimeout(function(){this.toggle_icon_list();}.bind(this),50);Event.kill(event);return false;}
typeaheadpro.prototype.dropdown_onmousedown=function(event){this.last_dropdown_mouse=(new Date()).getTime();}
typeaheadpro.prototype.setup_typeahead_icon=function(){this.typeahead_parent=document.createElement('div');CSS.addClass(this.typeahead_parent,'typeahead_parent');this.typeahead_parent.appendChild(this.typeahead_icon);this.obj.parentNode.insertBefore(this.typeahead_parent,this.obj);}
typeaheadpro.prototype.mouse_set_suggestion=function(index){if(!this.visible){return;}
if((new Date()).getTime()-this.last_key_suggestion>50){this.set_suggestion(index);}}
typeaheadpro.prototype.capture_submit=function(){if(!typeaheadpro.should_check_missing_events)return;if((!this.captured_form||this.captured_substitute!=this.captured_form.onsubmit)&&this.obj.form){this.captured_form=this.obj.form;this.captured_event=this.obj.form.onsubmit;this.captured_substitute=this.obj.form.onsubmit=function(){return((this.key_down&&this.key_down!=KEYS.RETURN&&this.key_down!=KEYS.TAB)?this.submit_keydown_return:(this.captured_event?this.captured_event.apply(arguments,this.captured_form):true))?true:false;}.bind(this);}}
typeaheadpro.prototype.set_suggestion=function(index){this.stop_suggestion_select=false;if(!this.suggestions||this.suggestions.length<=index){return}
var old_node=this.get_suggestion_node(this.selectedindex);this.selectedindex=(index<=-1)?-1:index;var cur_node=this.get_suggestion_node(this.selectedindex);if(old_node){CSS.removeClass(old_node,'typeahead_selected');CSS.addClass(old_node,'typeahead_not_selected');}
if(cur_node){CSS.removeClass(cur_node,'typeahead_not_selected');CSS.addClass(cur_node,'typeahead_selected');}
this.recalc_scroll();this._onfound(this.get_current_selection());}
typeaheadpro.prototype.get_suggestion_node=function(index){var nodes=this.list.childNodes;return index==-1?null:nodes[Math.floor(index/this.render_block_size)].childNodes[index%this.render_block_size];}
typeaheadpro.prototype.get_current_selection=function(){return this.selectedindex==-1?false:this.suggestions[this.selectedindex];}
typeaheadpro.prototype.update_class=function(){if(this.suggestions&&this.selectedindex!=-1&&typeahead_source.flatten_string(this.get_current_selection().t)==typeahead_source.flatten_string(this.get_value())){this.set_class('typeahead_found');}else{this.set_class('');}}
typeaheadpro.prototype.select_suggestion=function(index){if(!this.stop_suggestion_select&&this.current_selecting!=index){this.current_selecting=index;}
if(!this.suggestions||index==undefined||index===false||this.suggestions.length<=index||index<0){this._onfound(false);this._onselect(false);this.selectedindex=-1;this.set_class('');}else{this.selectedindex=index;var type=this.suggestions[index].ty;if(type!='web'&&type!='search'){this.set_value(this.suggestions[index].t);}
this.set_class('typeahead_found');this._onfound(this.suggestions[this.selectedindex]);this._onselect(this.suggestions[this.selectedindex]);}
if(!this.interactive){this.hide();this.blur();}
this.current_selecting=null;return true;}
typeaheadpro.prototype.is_showing_suggestions=function(){return(this.suggestions)&&(this.suggestions.length>0);}
typeaheadpro.prototype.set_value=function(value){this.obj.value=value;}
typeaheadpro.prototype.get_value=function(){if(this.showing_icon_list&&this.old_typeahead_value!=this.obj.value){this.toggle_icon_list();}
if(this.want_icon_list){return this.typeahead_icon_get_return;}else{if(this.showing_icon_list){this.toggle_icon_list();}}
return this.obj.value;}
typeaheadpro.prototype.found_suggestions=function(suggestions,text,fake_data){if(!suggestions){suggestions=[];}
this.suggestion_count=suggestions.length;if(!fake_data){this.status=typeaheadpro.STATUS_IDLE;this.add_cache(text,suggestions);}
this.clear_render_timeouts();if(this.get_value()==this.results_text){return;}else if(!fake_data){this.results_text=typeahead_source.flatten_string(text);if(this.enumerate&&trim(this.results_text)!=''){this.enumerate=false;}}
var current_selection=-1;if(this.selectedindex!=-1){var selected_id=this.suggestions[this.selectedindex].i;for(var i=0,l=suggestions.length;i<l;i++){if(suggestions[i].i==selected_id){current_selection=i;break;}}}
if(current_selection==-1&&this.auto_select&&suggestions.length){current_selection=0;this._onfound(suggestions[0]);}
this.selectedindex=current_selection;this.suggestions=suggestions;if(!fake_data){this.real_suggestions=suggestions;}
if(suggestions.length){var html=[],blocks=Math.ceil(suggestions.length/this.render_block_size),must_render={},firstblock,samplenode=null;this.list.innerHTML='';for(var i=0;i<blocks;i++){this.list.appendChild(document.createElement('div'));}
if(current_selection>-1){firstblock=Math.floor(current_selection/this.render_block_size);must_render[firstblock]=true;if(current_selection%this.render_block_size>this.render_block_size/2){must_render[firstblock+1]=true;}else if(firstblock!=0){must_render[firstblock-1]=true;}}else{must_render[0]=true;}
for(var node in must_render){this.render_block(node);sample=this.list.childNodes[node].firstChild;}
this.show();if(blocks){var suggestion_height=sample.offsetHeight;this.render_timeouts=[];for(var i=1;i<blocks;i++){if(!must_render[i]){this.list.childNodes[i].style.height=suggestion_height*Math.min(this.render_block_size,suggestions.length-i*this.render_block_size)+'px';this.list.childNodes[i].style.width='1px';this.render_timeouts.push(setTimeout(this.render_block.bind(this,i),700+i*50));}}}}else{this.selectedindex=-1;this.set_message(this.status==typeaheadpro.STATUS_IDLE?this.source.gen_nomatch():this.source.gen_loading());this._onfound(false);}
this.recalc_scroll();if(!fake_data&&this.results_text!=typeahead_source.flatten_string(this.get_value())){this.dirty_results();}}
typeaheadpro.prototype.render_block=function(block,stack){var suggestions=this.suggestions,selectedindex=this.selectedindex,text=this.get_value(),instance=this.instance,html=[],node=this.list.childNodes[block];for(var i=block*this.render_block_size,l=Math.min(suggestions.length,(block+1)*this.render_block_size);i<l;i++){html.push('<div class="');if(selectedindex==i){html.push('typeahead_suggestion typeahead_selected');}else{html.push('typeahead_suggestion typeahead_not_selected');}
html.push('" onmouseover="typeaheadpro.instances[',instance,'].mouse_set_suggestion(',i,')" ','onmousedown="var instance=typeaheadpro.instances[',instance,']; instance.select_suggestion(',i,');instance.hide();Event.kill(event);">',this.source.gen_html(suggestions[i],text),'</div>');}
node.innerHTML=html.join('');CSS.addClass(node,'typeahead_suggestions');}
typeaheadpro.prototype.clear_render_timeouts=function(){if(this.render_timeouts){for(var i=0;i<this.render_timeouts.length;i++){clearTimeout(this.render_timeouts[i]);}
this.render_timeouts=null;}}
typeaheadpro.prototype.recalc_scroll=function(){var cn=this.list.firstChild;if(!cn){return;}
if(cn.childNodes.length>this.max_display){var last_child=cn.childNodes[this.max_display-1];var height=last_child.offsetTop+last_child.offsetHeight;this.dropdown.style.height=height+'px';var selected=this.get_suggestion_node(this.selectedindex);if(selected){var scrollTop=this.dropdown.scrollTop;if(selected.offsetTop<scrollTop){this.dropdown.scrollTop=selected.offsetTop;}else if(selected.offsetTop+selected.offsetHeight>height+scrollTop){this.dropdown.scrollTop=selected.offsetTop+selected.offsetHeight-height;}}
if(!typeaheadpro.should_use_overflow){this.dropdown.style.overflowY='scroll';this.dropdown.style.overflowX='hidden';}}else{this.dropdown.style.height='auto';if(!typeaheadpro.should_use_overflow){this.dropdown.style.overflowY='hidden';}}}
typeaheadpro.prototype.search_cache=function(text){return this.cache[typeahead_source.flatten_string(text)];}
typeaheadpro.prototype.add_cache=function(text,results){if(this.source.cache_results){this.cache[typeahead_source.flatten_string(text)]=results;}}
typeaheadpro.prototype.update_status=function(status){this.status=status;this.dirty_results();}
typeaheadpro.prototype.set_class=function(name){this.obj.className=(this.obj.className.replace(/typeahead_[^\s]+/g,'')+' '+name).replace(/ {2,}/g,' ');}
typeaheadpro.prototype.dirty_results=function(){if(!this.enumerate&&trim(this.get_value())==''){this.list.innerHTML='';this.results_text='';this.set_message(this.source.gen_placeholder());this.suggestions=[];this.selectedindex=-1;return;}else if(this.results_text==typeahead_source.flatten_string(this.get_value())){return;}else if(this.status==typeaheadpro.STATUS_BLOCK_ON_SOURCE_BOOTSTRAP){this.set_message(this.source.gen_loading());return;}
var time=(new Date).getTime();var updated=false;if(this.last_search<=(time-this.source.search_limit)&&this.status==typeaheadpro.STATUS_IDLE){updated=this.perform_search();}else{if(this.status==typeaheadpro.STATUS_IDLE){if(!this.search_timeout){this.search_timeout=setTimeout(function(){this.search_timeout=false;if(this.status==typeaheadpro.STATUS_IDLE){this.dirty_results();}}.bind(this),this.source.search_limit-(time-this.last_search));}}}
if(this.source.allow_fake_results&&this.real_suggestions&&!updated){var ttext=typeahead_source.tokenize(this.get_value()).sort(typeahead_source._sort);var fake_results=[];for(var i=0;i<this.real_suggestions.length;i++){if(typeahead_source.check_match(ttext,this.real_suggestions[i].t+' '+this.real_suggestions[i].n)){fake_results.push(this.real_suggestions[i]);}}
if(fake_results.length){this.found_suggestions(fake_results,this.get_value(),true);}else{this.selectedindex=-1;this.set_message(this.source.gen_loading());}}}
typeaheadpro.prototype.perform_search=function(){if(this.get_value()==this.results_text){return true;}
var results;if((results=this.search_cache(this.get_value()))===undefined&&!(results=this.source.search_value(this.get_value()))){this.status=typeaheadpro.STATUS_WAITING_ON_SOURCE;this.last_search=(new Date).getTime();return false;}
this.found_suggestions(results,this.get_value(),false);return true;}
typeaheadpro.prototype.set_message=function(text){this.clear_render_timeouts();if(text){this.list.innerHTML='<div class="typeahead_message">'+text+'</div>';this.reset_iframe();}else{this.hide();}
this.recalc_scroll();}
typeaheadpro.prototype.reset_iframe=function(){if(!typeaheadpro.should_use_iframe){return}
typeaheadpro.iframe.style.top=this.dropdown.style.top;typeaheadpro.iframe.style.left=this.dropdown.style.left;typeaheadpro.iframe.style.width=this.dropdown.offsetWidth+'px';typeaheadpro.iframe.style.height=this.dropdown.offsetHeight+'px';typeaheadpro.iframe.style.display='';}
typeaheadpro.prototype.advance_focus=function(){return this._move_focus(true);}
typeaheadpro.prototype.reverse_focus=function(){return this._move_focus(false);}
typeaheadpro.prototype._move_focus=function(move_forward){var inputs=this.obj.form?get_all_form_inputs(this.obj.form):get_all_form_inputs();var next_inputs=[];next_inputs._insert=move_forward?next_inputs.push:next_inputs.unshift;var should_insert=!move_forward;for(var i=0;i<inputs.length;i++){if(!move_forward&&inputs[i]==this.obj){should_insert=false;}else if(should_insert&&inputs[i].type!='hidden'&&inputs[i].tabIndex!=-1&&inputs[i].offsetParent){next_inputs._insert(inputs[i]);}else if(inputs[i]==this.obj){should_insert=true;}}
setTimeout(function(){for(var i=0;i<this.length;i++){try{if(this[i].offsetParent){this[i].focus();setTimeout(function(){try{this.focus();}catch(e){}}.bind(this[i]),0);return;}}catch(e){}}}.bind(next_inputs?next_inputs:[]),0);}
typeaheadpro.prototype.clear_placeholder=function(){if(this.obj.className.indexOf('typeahead_placeholder')!=-1){this.set_value('');this.set_class('');}}
typeaheadpro.prototype.clear=function(){this.set_value('');this.set_class('');this.selectedindex=-1;this.enumerate=false;this.dirty_results();}
typeaheadpro.prototype.hide=function(){if(this.stop_hiding){return;}
this.visible=false;this.dropdown.style.display='none';this.clear_render_timeouts();if(typeaheadpro.should_use_iframe){typeaheadpro.iframe.style.display='none';}}
typeaheadpro.prototype.show=function(){this.visible=true;if(this.focused){this.dropdown.style.top=elementY(this.anchor)+this.anchor.offsetHeight+'px';this.dropdown.style.left=elementX(this.anchor)+'px';this.dropdown.style.width=(this.anchor.offsetWidth-2)+'px';this.dropdown.style.display='';if(typeaheadpro.should_use_iframe){typeaheadpro.iframe.style.display='';this.reset_iframe();}}}
typeaheadpro.prototype.toggle_icon_list=function(no_focus){if(this.showing_icon_list){this.showing_icon_list=false;this.source.showing_icon_list=false;if(!no_focus){this.focus();}
CSS.removeClass(this.typeahead_icon,'on_selected');this.want_icon_list=false;this.showing_icon_list=false;this.stop_suggestion_select=true;if(this.obj){this.dirty_results();}}else{this.source.showing_icon_list=true;this.old_typeahead_value=this.obj.value;this.stop_suggestion_select=true;this.want_icon_list=true;this.dirty_results();this.focus();CSS.addClass(this.typeahead_icon,'on_selected');this.show();this.set_suggestion(-1);this.showing_icon_list=true;}
setTimeout(function(){this.stop_hiding=false;}.bind(this),100)}
typeaheadpro.prototype.focus=function(){this.obj.focus();}
typeaheadpro.prototype.blur=function(){if(this.obj){this.obj.blur();}}
typeaheadpro.kill_typeahead=function(obj){if(obj.typeahead){if(!this.anchor_block){obj.parentNode.removeChild(obj.nextSibling);}
obj.parentNode.removeChild(obj.nextSibling);if(obj.typeahead.source){obj.typeahead.source=obj.typeahead.source.owner=null;}
obj.onfocus=obj.onblur=obj.onkeypress=obj.onkeyup=obj.onkeydown=obj.typeahead=null;}}

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';search_typeahead_log_data(this);return this.parent.select_suggestion.call(this,index);}
search_typeaheadpro.prototype.hide=function(){this.parent.hide();}
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[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){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>=this.suggestions.length){next_tab_index=-1;}else if(next_tab_index<-1){next_tab_index=this.suggestions.length-1;}
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,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];}
log_data['si']=source.selectedindex;search_typeahead_log(log_data,'onsubmit');}
function search_typeahead_onsubmit(friend){search_typeahead_log_data(this);return!search_friend_source.hasSubmitted;}
window.ADVANCED_SEARCH_TYPEAHEAD=false;

function typeahead_source(){}
typeahead_source.prototype.cache_results=false;typeahead_source.prototype.enumerable=false;typeahead_source.prototype.allow_fake_results=false;typeahead_source.prototype.search_limit=10;typeahead_source.prototype.bootstrap=bagofholding;typeahead_source.check_match=function(search,value){value=typeahead_source.tokenize(value);for(var i=0,il=search.length;i<il;i++){if(search[i].length){var found=false;for(var j=0,jl=value.length;j<jl;j++){if(value[j].length>=search[i].length&&value[j].substring(0,search[i].length)==search[i]){found=true;value[j]='';break;}}
if(!found){return false;}}}
return true;}
typeahead_source.tokenize=function(text,capture,noflatten){return(noflatten?text:typeahead_source.flatten_string(text)).split(capture?typeahead_source.normalizer_regex_capture:typeahead_source.normalizer_regex);}
typeahead_source.normalizer_regex_str='(?:(?:^| +)["\'.\\-]+ *)|(?: *[\'".\\-]+(?: +|$)|[@_]| +)';typeahead_source.normalizer_regex=new RegExp(typeahead_source.normalizer_regex_str,'g');typeahead_source.normalizer_regex_capture=new RegExp('('+typeahead_source.normalizer_regex_str+')','g');typeahead_source.flatten_string=function(text){if(!typeahead_source.accents){typeahead_source.accents={a:/а|à|á|â|ã|ä|å/g,b:/б/g,c:/ц|ç/g,d:/д|ð/g,e:/э|е|è|é|ê|ë/g,f:/ф/g,g:/г/g,h:/х/g,i:/и|ì|í|î|ï/g,j:/й/g,k:/к/g,l:/л/g,m:/м/g,n:/н|ñ/g,o:/о|ø|ö|õ|ô|ó|ò/g,p:/п/g,r:/р/g,s:/с/g,t:/т/g,u:/у|ю|ü|û|ú|ù/g,v:/в/g,y:/ы|ÿ|ý/g,z:/з/g,ae:/æ/g,oe:/œ/g,ts:/ц/g,ch:/ч/g,sh:/ш/g,ya:/я/g}}
text=text.toLowerCase();for(var i in typeahead_source.accents){text=text.replace(typeahead_source.accents[i],i);}
return text;}
typeahead_source.prototype.set_owner=function(obj){this.owner=obj;if(this.is_ready){this.owner.update_status(typeaheadpro.STATUS_IDLE);}}
typeahead_source.prototype.ready=function(){if(this.owner&&!this.is_ready){this.is_ready=true;this.owner.update_status(typeaheadpro.STATUS_IDLE);}else{this.is_ready=true;}}
typeahead_source.highlight_found=function(result,search){var html=[];resultv=typeahead_source.tokenize(result,true,true);result=typeahead_source.tokenize(result,true);search=typeahead_source.tokenize(search);search.sort(typeahead_source._sort);for(var i=0,il=resultv.length;i<il;i++){var found=false;for(var j=0,jl=search.length;j<jl;j++){if(search[j]&&result[i].lastIndexOf(search[j],0)!=-1){html.push('<em>',htmlspecialchars(resultv[i].substring(0,search[j].length)),'</em>',htmlspecialchars(resultv[i].substring(search[j].length,resultv[i].length)));found=true;break;}}
if(!found){html.push(htmlspecialchars(resultv[i]));}}
return html.join('');}
typeahead_source._sort=function(a,b){return b.length-a.length;}
typeahead_source.prototype.gen_nomatch=function(){return this.text_nomatch!=null?this.text_nomatch:_tx("No matches found");}
typeahead_source.prototype.gen_loading=function(){return this.text_loading!=null?this.text_loading:_tx("Loading...");}
typeahead_source.prototype.gen_placeholder=function(){return this.text_placeholder!=null?this.text_placeholder:_tx("Start typing...");}
typeahead_source.prototype.gen_noinput=function(){return this.text_noinput!=null?this.text_noinput:_tx("Start typing...");}
typeahead_source.prototype.onselect_not_found=function(){if(typeof this.tokenizer._ontokennotfound!='undefined'){this.tokenizer._ontokennotfound(this.obj.value);}
if(typeof this.tokenizer.onselect!='undefined'){return this.tokenizer.onselect();}}

function static_source(){this.values=null;this.index=null;this.index_includes_hints=false;this.exclude_ids={};this.parent.construct(this);}
static_source.extend('typeahead_source');static_source.prototype.enumerable=true;static_source.prototype.build_index=function(){var index=[];var values=this.values;var gen_id=values.length&&typeof values[0].i=='undefined';for(var i=0,il=values.length;i<il;i++){var tokens=typeahead_source.tokenize(values[i].t);for(var j=0,jl=tokens.length;j<jl;j++){index.push({t:tokens[j],o:values[i]});}
if(this.index_includes_hints&&values[i].s){var tokens=typeahead_source.tokenize(values[i].s);for(var j=0,jl=tokens.length;j<jl;j++){index.push({t:tokens[j],o:values[i]});}}
if(gen_id){values[i].i=i;}}
index.sort(function(a,b){return(a.t==b.t)?0:(a.t<b.t?-1:1)});this.index=index;this.ready();}
static_source.prototype._sort_text_obj=function(a,b){if(a.e&&!b.e){return 1;}
if(!a.e&&b.e){return-1;}
if(a.t==b.t){return 0;}
return a.t<b.t?-1:1}
static_source.prototype.search_value=function(text){if(!this.is_ready){return;}
var results;if(text==''){results=this.values;}else{var ttext=typeahead_source.tokenize(text).sort(typeahead_source._sort);var index=this.index;var lo=0;var hi=this.index.length-1;var p=Math.floor(hi/2);while(lo<=hi){if(index[p].t>=ttext[0]){hi=p-1;}else{lo=p+1;}
p=Math.floor(lo+((hi-lo)/2));}
var results=[];var stale_keys={};var check_ignore=typeof _ignoreList!='undefined';for(var i=lo;i<index.length&&index[i].t.lastIndexOf(ttext[0],0)!=-1;i++){var elem_id=index[i].o.flid?index[i].o.flid:index[i].o.i;if(typeof stale_keys[elem_id]!='undefined'){continue;}else{stale_keys[elem_id]=true;}
if((!check_ignore||!_ignoreList[elem_id])&&!this.exclude_ids[elem_id]&&(ttext.length==1||typeahead_source.check_match(ttext,index[i].o.t))){results.push(index[i].o);}}}
results.sort(this._sort_text_obj);if(this.owner.max_results){results=results.slice(0,this.owner.max_results);}
return results;}
static_source.prototype.set_exclude_ids=function(ids){this.exclude_ids=ids;}

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)).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.url_templates={};search_friend_source.loaded_images={};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'u':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':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.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!='u'){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',i:text});results.push({t:_tx("Search the Web"),ty:'web',i:text});}
return results;};search_friend_source.prototype._sort_text_obj=function(a,b){if(a.o!=b.o){return a.o-b.o;}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;

var HistoryManager={_IFRAME_BASE_URI:'http://static.ak.facebook.com/common/history_manager.html',history:null,current:0,fragment:null,_setIframeSrcFragment:function(src){src=src.toString();var index=HistoryManager.history.length-1;HistoryManager.iframe.src=HistoryManager._IFRAME_BASE_URI+'?|index='+index+'#'+src;return HistoryManager;},getIframeSrcFragment:function(){return URI(HistoryManager.iframe.contentWindow.document.location.href).getFragment();},nextframe:function(frame){if(frame!==undefined){HistoryManager.iframeQueue.push(frame);}else{HistoryManager.iframeQueue.splice(0,1);HistoryManager.iframeTimeout=null;HistoryManager.checkURI();}
if(HistoryManager.iframeQueue.length&&!HistoryManager.iframeTimeout){var src=HistoryManager.iframeQueue[0];HistoryManager.iframeTimeout=setTimeout(function(){HistoryManager._setIframeSrcFragment(src);},100,false);}},init:function(){if(HistoryManager._initialized){return HistoryManager;}
var uri=URI();var cur_fragment=uri.getFragment()||'';copy_properties(HistoryManager,{_initialized:true,fragment:cur_fragment,orig_fragment:cur_fragment,history:[uri],callbacks:[],lastChanged:new Date().getTime(),canonical:URI('#'),fragmentTimeout:null,user:0,iframeTimeout:null,iframeQueue:[],enabled:true,debug:bagofholding});if(ua.safari()<500||ua.firefox()<2){HistoryManager.enabled=false;return HistoryManager;}
if(ua.ie()<8){HistoryManager.iframe=document.createElement('iframe');copy_properties(HistoryManager.iframe.style,{width:'1px',height:'1px',left:'-10000px',top:'-10000px',position:'absolute'});onloadRegister(function(){HistoryManager._setIframeSrcFragment(cur_fragment);document.body.insertBefore(HistoryManager.iframe,document.body.firstChild);});}else{setInterval(HistoryManager.checkURI,42,false);}
return HistoryManager;},registerURIHandler:function(callback){HistoryManager.callbacks.push(callback);return HistoryManager;},setCanonicalLocation:function(loc){HistoryManager.canonical=URI(loc);return HistoryManager;},notify:function(uri){if(uri==HistoryManager.orig_fragment){uri=HistoryManager.canonical.getFragment();}
for(var ii=0;ii<HistoryManager.callbacks.length;ii++){try{if(HistoryManager.callbacks[ii](uri)){return true;}}catch(ex){Util.error('Uncaught exception in HistoryManager URI handler callback: %x',ex);}}
return false;},checkURI:function(){if(new Date().getTime()-HistoryManager.lastChanged<400){return;}
if(HistoryManager.iframeQueue.length){return;}
if(ua.safari()&&window.history.length==200){if(!HistoryManager.warned){HistoryManager.warned=true;Util.error('Your history length is over 200 and you are in Safari; things will '+'start behaving oddly now. This is a known bug.');}
return;}
var frag=URI().getFragment();if(ua.ie()<8){frag=HistoryManager.getIframeSrcFragment();}
if(frag!=HistoryManager.fragment){HistoryManager.debug([frag,' vs ',HistoryManager.fragment,'whl: ',window.history.length,'QHL: ',HistoryManager.history.length].join(' '));for(var ii=HistoryManager.history.length-1;ii>=0;--ii){if(HistoryManager.history[ii].getFragment()==frag){break;}}
++HistoryManager.user;if(ii>=0){HistoryManager.go(ii-HistoryManager.current);}else{HistoryManager.go('#'+frag);}
--HistoryManager.user;}
delete frag;},go:function(href,now,replace){HistoryManager.debug('go: '+href);if(now===undefined){now=true;}
if(!HistoryManager.enabled){if(!now){return false;}}
if(typeof(href)=='number'){if(!href){return false;}
var dst=href+HistoryManager.current;var loc=Math.max(0,Math.min(HistoryManager.history.length-1,dst));HistoryManager.current=loc;dst=HistoryManager.history[loc].getFragment()||HistoryManager.orig_fragment;HistoryManager.fragment=dst;HistoryManager.lastChanged=new Date().getTime();if(ua.ie()<8){if(HistoryManager.fragmentTimeout){clearTimeout(HistoryManager.fragmentTimeout);}
HistoryManager._temporary_fragment=dst;HistoryManager.fragmentTimeout=setTimeout(function(){window.location.hash='#'+dst;delete HistoryManager._temporary_fragment;},750,false);if(!HistoryManager.user){HistoryManager.nextframe(dst);}}else if(!HistoryManager.user){go_or_replace(window.location,URI().setFragment(dst),replace);}
if(now){HistoryManager.notify(dst);}
return false;}
href=URI(href);if(href.getDomain()==URI().getDomain()){href=URI('#'+href.getUnqualifiedURI());}
var cur=HistoryManager.history[HistoryManager.current].getFragment();var tgt=href.getFragment();if(tgt==cur||(cur==HistoryManager.orig_fragment&&tgt==HistoryManager.canonical.getFragment())){if(now){HistoryManager.notify(tgt);}
return false;}
if(replace){HistoryManager.current--;}
var wipe=(HistoryManager.history.length-HistoryManager.current)-1;HistoryManager.history.splice(HistoryManager.current+1,wipe);HistoryManager.history.push(URI(href));return HistoryManager.go(1,now,replace);},getCurrentFragment:function(){var cur_fragment=HistoryManager._temporary_fragment!==undefined?HistoryManager._temporary_fragment:URI.getRequestURI(false).getFragment();return cur_fragment==HistoryManager.orig_fragment?HistoryManager.canonical.getFragment():cur_fragment;}};var PageTransitions={_transition_handlers:[],_scroll_positions:{},isInitialized:function(){return!!PageTransitions._initialized;},_init:function(){if(PageTransitions._initialized){return PageTransitions;}
PageTransitions._initialized=true;var req_uri=URI.getRequestURI(false);var canonical_uri=req_uri.getUnqualifiedURI();copy_properties(PageTransitions,{_current_uri:canonical_uri,_most_recent_uri:canonical_uri});var canonical_uri_frag;if(req_uri.getFragment().startsWith('/')){canonical_uri_frag=req_uri.getFragment();}else{canonical_uri_frag=canonical_uri;}
HistoryManager.init().setCanonicalLocation('#'+canonical_uri_frag).registerURIHandler(PageTransitions._historyManagerHandler);LinkController.registerFallbackHandler(PageTransitions._rewriteHref,LinkController.ALL_TARGETS|LinkController.ALL_KEY_MODIFIERS);LinkController.registerFallbackHandler(PageTransitions._onlinkclick);FormController.registerFallbackHandler(PageTransitions._onformsubmit);window.onscroll=chain(window.onscroll,function(){var frag=HistoryManager.getCurrentFragment();if(PageTransitions._current_uri==frag){PageTransitions._scroll_positions[frag]=Vector2.getScrollPosition();}});return PageTransitions;},registerHandler:function(transition_handler){PageTransitions._init();if(PageTransitions._transition_handlers.contains(transition_handler)){Util.warn('Registering a transition handler that\'s already been '
+'registered.  Ur probably doin it wrong.');}
PageTransitions._transition_handlers.push(transition_handler);},getCurrentURI:function(){if(!PageTransitions._current_uri){Util.warn('You\'ve requested the current URI, but there is no "current" '
+'URI.  This is probably because you\'re in the middle of a '
+'page transition.  That\'s an awkward time to ask for the '
+'current URI, and you should probably avoid this situation.  '
+'For now, I\'m just gonna return the most recent page URI, '
+'since that\'s better than returning null.');return new URI(PageTransitions._most_recent_uri);}
return new URI(PageTransitions._current_uri);},_rewriteHref:function(link){var old_href=link.getAttribute('href');var new_href=_computeRelativeURI(PageTransitions._most_recent_uri.getQualifiedURI(),old_href).toString();if(old_href!=new_href){link.setAttribute('href',new_href);}},_onlinkclick:function(link){_BusyUIManager.lookBusy(link);PageTransitions.go(link.getAttribute('href'));return false;},go:function(uri,replace){var qualified_uri=new URI(uri).removeQueryData('quickling').getQualifiedURI();var unqualified_uri=qualified_uri.getUnqualifiedURI();delete PageTransitions._scroll_positions[unqualified_uri];_BusyUIManager.lookBusy();PageTransitions._loadPage(qualified_uri,function(handled){if(handled){HistoryManager.go(qualified_uri.toString(),false,replace);}else{go_or_replace(window.location,qualified_uri,replace);}});},_historyManagerHandler:function(uri_s){if(uri_s.charAt(0)!='/'){return false;}
PageTransitions._loadPage(new URI(uri_s),function(handled){if(!handled){go_or_replace(window.location,uri_s,true);}});return true;},_loadPage:function(uri,ondone){if(uri.getFragment()&&are_equal(URI(uri).setFragment(null).getQualifiedURI(),URI(PageTransitions._current_uri).setFragment(null).getQualifiedURI())){PageTransitions._current_uri=PageTransitions._most_recent_uri=uri;PageTransitions._adjustScrollForCurrentURI();_BusyUIManager.stopLookingBusy();return;}
var scroll_position=PageTransitions._scroll_positions[PageTransitions._current_uri];PageTransitions._current_uri=null;PageTransitions._next_uri=uri;if(scroll_position){DOMScroll.scrollTo(scroll_position,false);}
var handle_transition=function(){var handled=PageTransitions._handleTransition(uri);ondone&&ondone(handled);};var beforeleave_warning=_runHooks('onbeforeleavehooks');if(beforeleave_warning){_BusyUIManager.stopLookingBusy();PageTransitions._warnBeforeLeaving(beforeleave_warning,handle_transition);}else{handle_transition();}},_handleTransition:function(uri){window.onbeforeleavehooks=undefined;_BusyUIManager.lookBusy();for(var i=PageTransitions._transition_handlers.length-1;i>=0;--i){if(PageTransitions._transition_handlers[i](uri)===true){var message={sender:this,uri:uri};Arbiter.inform(Arbiter.PAGE_TRANSITION,message);return true;}else{PageTransitions._transition_handlers.splice(i,1);}}
return false;},transitionComplete:function(){_BusyUIManager.stopLookingBusy();PageTransitions._current_uri=PageTransitions._most_recent_uri=PageTransitions._next_uri;PageTransitions._adjustScrollForCurrentURI();},_warnBeforeLeaving:function(warning_text,continuation){new Dialog().setTitle(_tx("Are you sure you want to navigate away from this page?")).setSummary(_tx("Press {ok} to continue, or {cancel} to stay on the current page.",{ok:_tx("Okay"),cancel:_tx("Cancel")})).setBody(htmlize(warning_text)).setButtons(Dialog.OK_AND_CANCEL).setHandler(continuation).setModal().show();},_adjustScrollForCurrentURI:function(){var current_uri=PageTransitions._current_uri;var scroll_position=PageTransitions._scroll_positions[current_uri];if(scroll_position){DOMScroll.scrollTo(scroll_position,false);return;}
function get_anchor(name){return(name||null)&&($$(sprintf('a[name=%e]',name))[0]||ge(name));}
var anchor=get_anchor(current_uri.getFragment());if(anchor){var anchor_position=Vector2.getElementPosition(anchor);anchor_position.x=0;DOMScroll.scrollTo(anchor_position);}},_onformsubmit:function(form){var old_action=new URI(form.getAttribute('action')||'');var new_action=_computeRelativeURI(PageTransitions._most_recent_uri,old_action);form.setAttribute('action',new_action.toString());var method=form.method?form.method.toUpperCase():'GET';if(method=='GET'){PageTransitions.go(new_action.addQueryData(serialize_form(form)));return false;}else{}}};function _computeRelativeURI(original,delta){var ret=new URI(),delta_=delta;original=new URI(original);delta=new URI(delta);if(!delta.isFacebookURI()){return delta_;}
var source=original;var components=['Protocol','Domain','Port','Path','QueryData','Fragment'];components.forEach(function(component){var combine_paths=component=='Path'&&source===original;if(combine_paths){ret.setPath(_computeRelativePath(original.getPath(),delta.getPath()));}
if(!is_empty(delta['get'+component]())){source=delta;}
if(!combine_paths){ret['set'+component](source['get'+component]());}});return ret;}
function _computeRelativePath(original,delta){if(!delta){return original;}
if(delta.charAt(0)=='/'){return delta;}
var parts=original.split('/').slice(0,-1);if(parts[0]!==''){Util.warn('Original path is not absolute.');}
delta.split('/').forEach(function(part){if(part=='.'){}else if(part=='..'){if(parts.length>1){parts=parts.slice(0,-1);}}else{parts.push(part);}});return parts.join('/');}
function go_or_replace(location_obj,target_url,replace){target_url=target_url.toString();if(replace&&!(ua.ie()<8)){location_obj.replace(target_url);}else if(location_obj.href==target_url){location_obj.reload();}else{location_obj.href=target_url;}}
var _BusyUIManager={_looking_busy:false,_original_cursors:[],lookBusy:function(link_element){if(link_element){_BusyUIManager._giveProgressCursor(link_element);}
if(_BusyUIManager._looking_busy){return;}
_BusyUIManager._looking_busy=true;_BusyUIManager._giveProgressCursor(document.body);},stopLookingBusy:function(){if(!_BusyUIManager._looking_busy){return;}
_BusyUIManager._looking_busy=false;while(_BusyUIManager._original_cursors.length){var element_and_cursor=_BusyUIManager._original_cursors.pop();var element=element_and_cursor[0];var cursor=element_and_cursor[1];if(element.style){element.style.cursor=cursor||'';}}},_giveProgressCursor:function(element){if(!ua.safari()){_BusyUIManager._original_cursors.push([element,element.style.cursor]);element.style.cursor='progress';}}};onloadRegister(HistoryManager.init);

function ApplicationDock(applications,bookmarkableApp){this.applications={};this.sortedList=[];this.bookmarkableApp=bookmarkableApp||null;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._init(applications);}
copy_properties(ApplicationDock,{NUM_SHOWN:6,BOOKMARKS_CHANGED:'bookmarks_changed',SaveBookmarksSource:{ICON_GARDEN:1,APPLICATION_MENU:2,BOOKMARK_CURRENT_APP:3}});ApplicationDock.prototype={_init:function(applications){this.applications=applications;this.sortedList=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.applications;var array=keys(applications);array=mapToInt(array);this._sort(array,applications);return array;},_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=['<ul id="application_menu_root">'];var secondaryUl=false;for(var i=0;i<this.sortedList.length;i++){var appID=this.sortedList[i];if(i==ApplicationDock.NUM_SHOWN){secondaryUl=true;markupArr.push(this._renderAppMenuContentHelper());}
markupArr.push('<li id="',this._getApplicationMenuItemId(appID),'"',' class="clearfix">',this._renderApplicationMenuItem(appID),'</li>');}
if(!secondaryUl){markupArr.push(this._renderAppMenuContentHelper());}
markupArr.push('</ul>');return markupArr.join('');},_renderAppMenuContentHelper:function(){return['</ul>','<div class="divider"></div>','<ul id="application_menu_extended_root">'].join('');},_renderApplicationMenuItem:function(appID){var appInfo=this.applications[appID];var markupArr=['<a id="',this._getApplicationMenuLinkId(appID),'" href="',appInfo['href'],'">','<div>','<img src="',appInfo['new_icon'],'" />','</div>',htmlize(appInfo['name']),'</a>'];return markupArr.join('');},_getApplicationMenuItemId:function(appID){return'application_menu_'+appID;},_getApplicationMenuLinkId:function(appID){return'application_menu_link_'+appID;},toggleTab:function(){if(!this.menuOpen){this._openTab();}else{this._closeTab();}},_openTab:function(){if(this.menuOpen){return;}
if(!this.menuLoaded){this._renderApplicationMenu();this._initApplicationMenuSortables.bind(this).defer();this.menuLoaded=true;}
presence.openTab(this.menuWrapperID,this.applicationTabID,this.applicationMenuContentID);this.menuOpen=true;},_closeTab:function(){presence.toggleTab(this.menuWrapperID,this.applicationTabID,this.applicationMenuContentID);this.menuOpen=false;},_initApplicationMenuSortables: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.sortedList.length;i++){var appID=this.sortedList[i];if(i==ApplicationDock.NUM_SHOWN){this._initExtendedApplicationMenuSortables();sortableGroup=this.extendedSortableGroup;}
this._addApplicationMenuSortable(appID,sortableGroup);if(ApplicationDock.presenceWidthTest){$(this._getApplicationMenuLinkId(appID)).listen('click',function(){AsyncRequest.pingURI('/ajax/abtest_async.php',{action:'USED_APP_MENU',test_name:'APP_DOCK_TEST'});});}}},_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();}
this._renderApplicationMenu();this._initApplicationMenuSortables.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);}},_saveBookmarksOrder:function(source){var order;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.sortedList.length>ApplicationDock.NUM_SHOWN){order=order.concat(this.sortedList.slice(ApplicationDock.NUM_SHOWN));}
order=unique(order);new AsyncRequest().setURI('/ajax/edit_app_settings.php').setData({reorder_bookmarks:1,app_ids:order}).setHandler(this._saveBookmarksHandler.bind(this,order,source)).send();},_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();break;}},_updateSortedList:function(appIDs){this.sortedList=[];for(var i=0;i<appIDs.length;i++){this.sortedList.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.sortedList.length);i<length;i++){var appID=this.sortedList[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.applications[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;},_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.sortedList.length,ApplicationDock.NUM_SHOWN);i<length;i++){this._addIconGardenSortable(this.sortedList[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'});});}},_resetIconGarden:function(){this.iconGardenSortableGroup.destroy();this._renderIconGarden();this._initIconGardenSortables.bind(this).defer();},_renderBookmarkableApp:function(){DOM.setContent(this.bookmarkableAppContainer,HTML(this._renderBookmarkableAppContent()));CSS.removeClass(this.bookmarkableAppWrapper,'hidden_elem');},_hideBookmarkableApp:function(){CSS.addClass(this.bookmarkableAppWrapper,'hidden_elem');},_renderBookmarkableAppContent:function(){var appInfo=values(this.bookmarkableApp)[0];var markupArr=['<a',' onclick="applicationDock.bookmarkCurrentApp(); return false;"',' 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"),'</span>','</a>'];return markupArr.join('');},mouseOverBookmarkableApp:function(){CSS.addClass(this.bookmarkableAppWrapper,'hover');},mouseOutBookmarkableApp:function(){CSS.removeClass(this.bookmarkableAppWrapper,'hover');},setBookmarkableApp:function(bookmarkableApp){this.bookmarkableApp=bookmarkableApp;if(is_empty(this.bookmarkableApp)){this._hideBookmarkableApp();}else{this._renderBookmarkableApp();}},_getAppShaftedByBookmarkableApp:function(){return this.sortedList[ApplicationDock.NUM_SHOWN-1];},bookmarkCurrentApp:function(){var appID=keys(this.bookmarkableApp)[0];var existingApp=this.applications[appID];this.applications[appID]=this.bookmarkableApp[appID];var div=$N('div',{id:this._getApplicationIconGardenItemId(appID),className:'icon_garden_elem'},HTML(this._renderApplicationIconGardenItem(appID)));if(this.sortedList.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._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.sortedList,newSortedList)){this.applications=obj.bookmarks;this.sortedList=newSortedList;this._resetApplicationMenu();this._resetIconGarden();}
var message={sender:this,applications:this.sortedList};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();}}},_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 search_selector_onfound(result){var n;if(!(n=ge('n'))){return;}
n.value=result?result.i:-1;}
function search_result_selector_onsubmit(result){$('search').init.value=$('filter_init').value;$('search').sf.value=$('filter_sf').value;$('search').submit();this.hide();this.advance_focus();}
function search_logged_ajax(data){new AsyncSignal('/ajax/search_log.php',data).send();}
function search_log_2nd_action(data){new AsyncRequest().setURI('/ajax/search_log_2nd_action.php').setMethod('POST').setContextData('clicktype',data).setHandler(function(){}).send();}
function search_typeahead_log(data,evt,timestart){if(!data){return;}
var moddata=data;if(evt){moddata.evt=evt;}
moddata.t=(new Date()).getTime();if(timestart){moddata.dt=moddata.t-timestart;}
new AsyncSignal('/ajax/typeahead_log.php',moddata).send();}

function StatusEditor(root){this.rootElem=root;this.statusInput=DOM.find(root,'input.status_input');this.placeholder=this.getPlaceholder();this.emptyValue=this.statusInput.value;this.initialValue='';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.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));}
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({'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.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){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={'status':text};var page_uri=URI.getRequestURI();if(page_uri.getPath()=='/profile.php'){data['profile']=true;}else if(page_uri.getPath()=='/home.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';}
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){this.parent.construct(this,root);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));}
HomeStatusEditor.extend('StatusEditor');HomeStatusEditor.prototype._onPosted=function(payload){this._onUpdate(payload);}
HomeStatusEditor.prototype._onUpdate=function(payload,time){var status=payload.markup;if(!status){this._onCleared();return;}
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;")));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();}
if(payload.feed&&window.HomeFeed){var homefeed=HomeFeed.getInstance();if(homefeed){var tabId=homefeed.tabId;if(tabId==payload.feed_tab){var container=document.createElement('div');container.className='just_updated_status';container.style.display='none';DOM.setContent(container,HTML(payload.feed));$('newsfeed_wrapper').prependContent(container);animation(container).to('height','auto').from('0px').to('opacity',1).from(0).blind().show().duration(300).ease(animation.ease.end).go();}}}}
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();}
function ChatStatusEditor(root,isEmpty){this.parent.construct(this,root);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._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');

if(typeof deconcept=="undefined")var deconcept={};if(typeof deconcept.util=="undefined")deconcept.util={};if(typeof deconcept.SWFObjectUtil=="undefined")deconcept.SWFObjectUtil={};deconcept.SWFObject=function(swf,id,w,h,ver,c,quality,xiRedirectUrl,redirectUrl,detectKey){if(!document.getElementById){return;}
this.DETECT_KEY=detectKey?detectKey:'detectflash';this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params={};this.variables={};this.attributes=[];this.fallback_html='';this.fallback_js_fcn=function(){};if(swf){this.setAttribute('swf',swf);}
if(id){this.setAttribute('id',id);}
if(w){this.setAttribute('width',w);}
if(h){this.setAttribute('height',h);}
if(ver){this.setAttribute('version',new deconcept.PlayerVersion(ver.toString().split(".")));}
this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);}
window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}
if(c){this.addParam('bgcolor',c);}
var q=quality?quality:'high';this.addParam('quality',q);this.setAttribute('useExpressInstall',false);this.setAttribute('doExpressInstall',false);var xir=(xiRedirectUrl)?xiRedirectUrl:window.location;this.setAttribute('xiRedirectUrl',xir);this.setAttribute('redirectUrl','');if(redirectUrl){this.setAttribute('redirectUrl',redirectUrl);}}
deconcept.SWFObject.prototype={useExpressInstall:function(path){this.xiSWFPath=!path?"/swf/expressinstall.swf":path;this.setAttribute('useExpressInstall',true);},setAttribute:function(name,value){this.attributes[name]=value;},getAttribute:function(name){return this.attributes[name]||"";},addParam:function(name,value){this.params[name]=value;},getParams:function(){return this.params;},addVariable:function(name,value){this.variables[name]=value;},getVariable:function(name){return this.variables[name]||"";},getVariables:function(){return this.variables;},getVariablePairs:function(){var variablePairs=[];var key;var variables=this.getVariables();for(key in variables){variablePairs[variablePairs.length]=key+"="+variables[key];}
return variablePairs;},getSWFHTML:function(){var swfNode="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute('swf',this.xiSWFPath);}
swfNode='<embed type="application/x-shockwave-flash" src="'+htmlspecialchars(this.getAttribute('swf'))+'" width="'+htmlspecialchars(this.getAttribute('width'))+'" height="'+htmlspecialchars(this.getAttribute('height'))+'" style="'+htmlspecialchars(this.getAttribute('style')||"")+'"';swfNode+=' id="'+htmlspecialchars(this.getAttribute('id'))+'" name="'+htmlspecialchars(this.getAttribute('id'))+'" ';var params=this.getParams();for(var key in params){swfNode+=htmlspecialchars(key)+'="'+htmlspecialchars(params[key])+'" ';}
var pairs=this.getVariablePairs().join("&");if(pairs.length>0){swfNode+='flashvars="'+pairs+'"';}
swfNode+='/>';}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute('swf',this.xiSWFPath);}
swfNode='<object id="'+this.getAttribute('id')+'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+this.getAttribute('width')+'" height="'+this.getAttribute('height')+'" style="'+(this.getAttribute('style')||"")+'">';swfNode+='<param name="movie" value="'+this.getAttribute('swf')+'" />';var params=this.getParams();for(var key in params){swfNode+='<param name="'+key+'" value="'+params[key]+'" />';}
var pairs=this.getVariablePairs().join("&");if(pairs.length>0){swfNode+='<param name="flashvars" value="'+pairs+'" />';}
swfNode+="</object>";}
return swfNode;},write:function(elementId){if(this.getAttribute('useExpressInstall')){var expressInstallReqVer=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(expressInstallReqVer)&&!this.installedVer.versionIsValid(this.getAttribute('version'))){this.setAttribute('doExpressInstall',true);this.addVariable("MMredirectURL",escape(this.getAttribute('xiRedirectUrl')));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}
var n=(typeof elementId=='string')?document.getElementById(elementId):elementId;if(this.skipDetect||this.getAttribute('doExpressInstall')||this.installedVer.versionIsValid(this.getAttribute('version'))){n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute('redirectUrl')!=""){document.location.replace(this.getAttribute('redirectUrl'));}
need_version=this.getAttribute('version').major+'.'+this.getAttribute('version').minor+'.'+this.getAttribute('version').rev;have_version=this.installedVer.major+'.'+this.installedVer.minor+'.'+this.installedVer.rev;this.fallback_js_fcn(have_version,need_version);n.innerHTML=this.fallback_html;}
return false;}}
deconcept.SWFObjectUtil.getPlayerVersion=function(){var PlayerVersion=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){for(k=0;k<navigator.plugins.length;k++){try{x=navigator.plugins[k];if(x.name=='Shockwave Flash'){PlayerVersion_tmp=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));if(typeof PlayerVersion=='undefined'||PlayerVersion_tmp.major>PlayerVersion.major||(PlayerVersion_tmp.major==PlayerVersion.major&&(PlayerVersion_tmp.minor>PlayerVersion.minor||(PlayerVersion_tmp.minor==PlayerVersion.minor&&PlayerVersion_tmp.rev>PlayerVersion.rev)))){PlayerVersion=PlayerVersion_tmp;}}}catch(honk){}}}else if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var counter=3;while(axo){try{counter++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+counter);PlayerVersion=new deconcept.PlayerVersion([counter,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");PlayerVersion=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(PlayerVersion.major==6){return PlayerVersion;}}
try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}
if(axo!=null){PlayerVersion=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}
return PlayerVersion;}
deconcept.PlayerVersion=function(arrVersion){this.major=arrVersion[0]!=null?parseInt(arrVersion[0]):0;this.minor=arrVersion[1]!=null?parseInt(arrVersion[1]):0;this.rev=arrVersion[2]!=null?parseInt(arrVersion[2]):0;}
deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major)return false;if(this.major>fv.major)return true;if(this.minor<fv.minor)return false;if(this.minor>fv.minor)return true;if(this.rev<fv.rev)return false;return true;}
deconcept.util={getRequestParameter:function(param){var q=document.location.search||document.location.hash;if(param==null){return q;}
if(q){var pairs=q.substring(1).split("&");for(var i=0;i<pairs.length;i++){if(pairs[i].substring(0,pairs[i].indexOf("="))==param){return pairs[i].substring((pairs[i].indexOf("=")+1));}}}
return"";}}
deconcept.SWFObjectUtil.cleanupSWFs=function(){var objects=document.getElementsByTagName("OBJECT");for(var i=objects.length-1;i>=0;i--){objects[i].style.display='none';for(var x in objects[i]){if(typeof objects[i][x]=='function'){objects[i][x]=function(){};}}}}
if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];}}
var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;var flash_update_dialog_shown=false;function spawn_flash_update_dialog(have_version,need_version){if(flash_update_dialog_shown){return;}
flash_update_dialog_shown=true;new AsyncRequest().setURI('/ajax/flash_update_dialog.php').setData({have_version:have_version,need_version:need_version}).setHandler(function(response){message_data=response.getPayload();new Dialog().setClassName('errorDialog').setTitle(message_data.title).setBody(message_data.body).setButtons([Dialog.CLOSE]).show();}).send();}
function setFlashFallback(id,required_version){var fallback=ge(id);var version=deconcept.SWFObjectUtil.getPlayerVersion();if(fallback&&version['major']>0){var current_version=version['major']+'.'+version['minor']+'.'+version['rev'];fallback.innerHTML=_tx("Flash {required-version} is required to view this content. Your current version is {current-version}. Please download the latest Flash Player.",{'required-version':required_version,'current-version':current_version});}}
function getFlashPlayer(){goURI('http://adobe.com/go/getflashplayer');return false;}

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