/*    HTTP Host:  static.ak.fbcdn.net                                          */
/*    Generated:  May 10th 2009 6:33:12 PM PDT                                 */
/*      Machine:  10.16.139.103                                                */
/*       Source:  Local Cache                                                  */
/*     Location:  rsrc:2cgqopc3:en_US:/html/js/60ykwiekb0kk80os.pkg.js:141     */
/*       Locale:  en_US                                                        */
/*         Path:  js/60ykwiekb0kk80os.pkg.js                                   */


var onloadRegister=window.onloadRegister||function(h){onloadhooks.push(h);};var onloadhooks=window.onloadhooks||[];var onafterloadRegister=window.onafterloadRegister||function(h){onafterloadhooks.push(h);};var onafterloadhooks=window.onafterloadhooks||[];function wait_for_load(element,e,f){f=bind(element,f,e);if(window.loaded){return f();}
switch((e||event).type){case'load':case'focus':onloadRegister(f);return;case'click':if(element.original_cursor===undefined){element.original_cursor=element.style.cursor;}
if(document.body.original_cursor===undefined){document.body.original_cursor=document.body.style.cursor;}
element.style.cursor=document.body.style.cursor='progress';onafterloadRegister(function(){element.style.cursor=element.original_cursor;document.body.style.cursor=document.body.original_cursor;element.original_cursor=document.body.original_cursor=undefined;if(element.tagName.toLowerCase()=='a'){var original_event=window.event;window.event=e;var ret_value=element.onclick.call(element,e);window.event=original_event;if(ret_value!==false&&element.href){window.location.href=element.href;}}else if(element.click){element.click();}});break;}
return false;};function bind(obj,method){var args=[];for(var ii=2;ii<arguments.length;ii++){args.push(arguments[ii]);}
var fn=function(){var _obj=obj||(this==window?false:this);var _args=args.slice();for(var jj=0;jj<arguments.length;jj++){_args.push(arguments[jj]);}
if(typeof(method)=="string"){if(_obj[method]){return _obj[method].apply(_obj,_args);}}else{return method.apply(_obj,_args);}};if(typeof method=='string'){fn.name=method;}else if(method&&method.name){fn.name=method.name;}
fn.toString=function(){return bind._toString(obj,args,method);};return fn;};var curry=bind(null,bind,null);bind._toString=bind._toString||function(obj,args,method){return(typeof method=='string')?('late bind<'+method+'>'):('bound<'+method.toString()+'>');};function goURI(uri,force_reload){uri=uri.toString();if(!force_reload&&window.PageTransitions&&PageTransitions.isInitialized()){PageTransitions.go(uri);}else if(window.location.href==uri){window.location.reload();}else{window.location.href=uri;}}
var PrimordialBootloader=window.PrimordialBootloader||{loaded:[],done:function(names){PrimordialBootloader.loaded.push(names);}};var Bootloader=window.Bootloader||{done:PrimordialBootloader.done};function loadExternalJavascript(urls,callback,body){if(urls instanceof Array){var url=urls.shift(0);loadExternalJavascript(url,function(){if(urls.length){loadExternalJavascript(urls,callback,body);}else{callback&&callback();}},body);}else{var node=body?document.body:document.getElementsByTagName('head')[0];var script=document.createElement('script');script.type='text/javascript';script.src=urls;if(callback){script.onerror=script.onload=callback;script.onreadystatechange=function(){if(this.readyState=="complete"||this.readyState=="loaded"){callback();}}}
node.appendChild(script);return script;}}
window.loadFirebugConsole&&window.loadFirebugConsole();

function hasArrayNature(obj){if(!obj){return false;}
if(typeof obj!='object'){return false;}
if(obj instanceof Array){return true;}
if(!('length'in obj)){return false;}
if('callee'in obj){return true;}
if('push'in obj&&'pop'in obj){return true;}
return false;}
function copy_properties(u,v){if(!u||!v){throw new TypeError("Can not copy between types "+typeof(u)+" and "+typeof(v)+".");}
for(var k in v){u[k]=v[k];}
if(v.hasOwnProperty&&v.hasOwnProperty('toString')&&(typeof v.toString!='undefined')&&(u.toString!==v.toString)){u.toString=v.toString;}
return u;}
function arrayize(obj){if(!hasArrayNature(obj)){return[obj];}
return obj;}
function is_empty(obj){if(obj instanceof Array){return obj.length==0;}else if(obj instanceof Object){for(var i in obj){return false;}
return true;}else{return!obj;}}
var Bootloader={configurePage:function(reverse_map){var links=document.getElementsByTagName('link');this._cssLinks=[];for(var ii=0;ii<links.length;++ii){if(links[ii].rel!='stylesheet'){continue;}
for(var k in reverse_map){if(links[ii].href.indexOf(k)!==-1){var name=reverse_map[k][0],permanent=reverse_map[k][1];this._cssLinkMap[name]=this._cssLinks.length;if(permanent){this._permanent[name]=true;}
delete reverse_map[k];break;}}
this._cssLinks.push(links[ii]);}},loadComponents:function(components,callback){components=arrayize(components);var required_resources=[];for(var ii=0;ii<components.length;++ii){var component_resource_list=this._componentMap[components[ii]];if(!component_resource_list){throw new Error("Can not bootload `"+components[ii]+"'.");}
for(var jj=0;jj<component_resource_list.length;++jj){required_resources.push(component_resource_list[jj]);}}
this.loadResources(required_resources,callback);},loadResources:function(resources,callback,replace,append){resources=arrayize(resources);if(replace){var map={};for(var ii=0;ii<resources.length;++ii){map[resources[ii].name]=true;}
for(var k in this._requested){if(!(k in this._permanent)&&!(k in map)){this._unloadResource(k);}}}
var request_index=append&&this._pending.length?this._pending.length-1:this._pending.length;var will_request=[];var pending_request=false;for(var ii=0;ii<resources.length;++ii){var rsrc=resources[ii];if(rsrc.permanent){this._permanent[rsrc.name]=true;}
if(this._loaded[rsrc.name]){continue;}
if(callback){if(!this._pending[request_index]){this._pending[request_index]={names:{},callback:callback};}
this._pending[request_index].names[rsrc.name]=true;pending_request=true;}
if(!this._requested[rsrc.name]){this.requested(rsrc.name);will_request.push(rsrc);}}
for(var ii=0;ii<will_request.length;++ii){this.requestResource(will_request[ii].type,will_request[ii].src,will_request[ii].name);}
if(!pending_request&&callback){this._invoke(callback);}},requestResource:function(type,source,name){var h=this._getHardpoint();switch(type){case'js':var script=document.createElement('script');script.src=source;script.type='text/javascript';h.appendChild(script);break;case'css':var link=null;for(var jj=0;jj<this._cssLinks.length;++jj){if(this._cssLinks[jj]._unused){link=this._cssLinks[jj];if(name){this._cssLinkMap[name]=jj;}
break;}}
if(!link){var link=document.createElement('link');link.rel="stylesheet";link.type="text/css";link.media="all";link.href=source;this._cssLinks.push(link);h.appendChild(link);}else{link.href=source;}
link._unused=false;var id=Bootloader._getDivIdForCSSComponent(name);var div=document.getElementById(id);if(!div){div=document.createElement('div');div.id=id;document.body.appendChild(div);setTimeout(Bootloader._pollCSS.bind(Bootloader,name,Bootloader._CSS_POLL_EXPIRATION),Bootloader._CSS_POLL_INTERVAL,false);}
break;default:throw new TypeError("Bad resource type `"+type+"'.");}},_getDivIdForCSSComponent:function(name){return'bootloader_'+name.replace(/[^a-z0-9]/ig,'_');},_pollCSS:function(name,remaining){var id=Bootloader._getDivIdForCSSComponent(name);var div=document.getElementById(id);if(!div){return;}
var expected='42';var computedStyle;var done=div.offsetHeight==expected||div.currentStyle&&div.currentStyle['height']==expected+'px'||window.getComputedStyle&&(computedStyle=document.defaultView.getComputedStyle(div,null))&&computedStyle.getPropertyValue('height')==expected+'px';if(done||remaining<=0){Bootloader.done([name]);div.parentNode.removeChild(div);if(!done&&window.Util){Util.error('Bootloading css file/package %s times out.',name);}}else{setTimeout(Bootloader._pollCSS.bind(Bootloader,name,remaining-Bootloader._CSS_POLL_INTERVAL),Bootloader._CSS_POLL_INTERVAL,false);}},done:function(names){var preloaded=PrimordialBootloader.loaded;PrimordialBootloader.loaded=[];for(var ii=0;ii<preloaded.length;++ii){Bootloader.done(preloaded[ii]);}
this.requested(names);for(var ii=0;ii<names.length;++ii){var loaded_resource=names[ii];this._loaded[loaded_resource]=true;for(var jj=0;jj<this._pending.length;++jj){var required_resources=this._pending[jj].names;delete required_resources[loaded_resource];if(is_empty(required_resources)){var callback=this._pending[jj].callback;this._pending.splice(jj,1);--jj;if(callback){this._invoke(callback);}}}}
if(window.Arbiter){var message={sender:this};Arbiter.inform(Arbiter.BOOTLOAD,message,Arbiter.BEHAVIOR_EVENT);}},requested:function(resources){resources=arrayize(resources);for(var ii=0;ii<resources.length;++ii){this._requested[resources[ii]]=true;}},enableBootload:function(map){copy_properties(this._componentMap,map);},_unloadResource:function(name){if(this._cssLinks&&(name in this._cssLinkMap)){var link_id=this._cssLinkMap[name];var link=this._cssLinks[link_id];link.href=Bootloader._UNUSED_CSS_URL;link._unused=true;delete this._cssLinkMap[name];delete this._requested[name];delete this._loaded[name];}},_invoke:function(callback){setTimeout(callback,0);},_getHardpoint:function(){if(!this._hardpoint){var n,heads=document.getElementsByTagName('head');if(heads.length){n=heads[0];}else{n=document.body;}
this._hardpoint=n;}
return this._hardpoint;},initialResourcesReady:function(){return this._initialResourcesReady;},loadInitialResources:function(resources){this._initialResourcesReady=false;this.loadResources(resources,bind(this,function(){this._initialResourcesReady=true;window.onResourceReady&&window.onResourceReady();},false,true));},_initialResourcesReady:true,_requested:{},_permanent:{},_loaded:{},_pending:[],_componentMap:{},_cssLinkMap:{},_cssLinks:[],_hardpoint:null,_CSS_POLL_EXPIRATION:5000,_CSS_POLL_INTERVAL:20,_UNUSED_CSS_URL:'javascript:void(0)'};

function Arbiter(){copy_properties(this,{_listeners:[],_events:{}});copy_properties(this,Arbiter);}
copy_properties(Arbiter,{SUBSCRIBE_NEW:'new',SUBSCRIBE_ALL:'all',BEHAVIOR_EVENT:'event',BEHAVIOR_PERSISTENT:'persistent',BEHAVIOR_STATE:'state',ALL:'all',LIVEMESSAGE:'livemessage',BOOTLOAD:'bootload',PAGE_TRANSITION:'pagetransitions/transition',CONTEXT_CHANGE:'ui/context-change',PROFILE_PUBLISHER:'profile/publisher',REPLAYABLE_AJAX:'ajax/replayable',PAGECACHE_INVALIDATE:'pagecache/invalidate',NEW_NOTIFICATIONS:'chat/new_notifications',BEEPS_EXPIRED:'beeper/beeps_expired',USER_ACTIVITY:'useractivity/activity',subscribe:function(types,callback,subscription_policy){var a=Arbiter._getInstance(this);types=types||Arbiter.ALL;a._listeners.push({callback:callback,types:types});subscription_policy=subscription_policy||Arbiter.SUBSCRIBE_ALL;if(subscription_policy==Arbiter.SUBSCRIBE_ALL){if(!(types instanceof Array)){types=[types];}
var e;var type;var ret;for(var idx=0;idx<types.length;idx++){type=types[idx];if(typeof type!="string"){throw new TypeError("Event types must be strings.");}
if(type in a._events){for(var ii=0;ii<a._events[type].length;ii++){e=a._events[type][ii];if(Arbiter._checkType(e[0],types)){ret=callback.apply(null,e);if(ret===false){a._events[type].splice(ii,1);ii--;}}}}}}else if(subscription_policy!=Arbiter.SUBSCRIBE_NEW){throw new TypeError("Bad subscription policy.");}
return{arbiterID:a._listeners.length-1};},unsubscribe:function(token){if(!('arbiterID'in token)){throw new TypeError("Not an arbiter token.");}
delete Arbiter._getInstance(this)._listeners[token.arbiterID];},inform:function(type,data,behavior){var a=Arbiter._getInstance(this);var e=[type,data];var idx=null;behavior=behavior||Arbiter.BEHAVIOR_EVENT;if(behavior==Arbiter.BEHAVIOR_PERSISTENT){idx=a._events.length;if(!(type in a._events)){a._events[type]=[];}
a._events[type].push(e);a._events[type]._stateful=false;}else if(behavior==Arbiter.BEHAVIOR_STATE){idx=0;a._events[type]=[e];a._events[type]._stateful=true;}else if(type in a._events){a._events[type]._stateful=false;}
var res;for(var ii=0;ii<a._listeners.length;ii++){if(a._listeners[ii]){if(Arbiter._checkType(e[0],a._listeners[ii].types)){res=a._listeners[ii].callback.apply(null,e);if(res===false){if(idx!==null){a._events[type].splice(idx,1);}
break;}}}}},query:function(type){var a=Arbiter._getInstance(this);if(!(type in a._events)){return null;}
if(!a._events[type]._stateful){throw new Error("Querying state of an unstateful event.");}
if(a._events[type].length){return a._events[type][0];}
return null;},_instance:null,_getInstance:function(self){if(self instanceof Arbiter){return self;}
if(!Arbiter._instance){Arbiter._instance=new Arbiter();}
return Arbiter._instance;},_checkType:function(event_type,callback_type){if(callback_type==Arbiter.ALL){return true;}
if(event_type==callback_type){return true;}
if(callback_type.length){for(var ii=0;ii<callback_type.length;ii++){if(callback_type[ii]==event_type){return true;}}}
return false;}});

Function.prototype.extend=function(superclass){if(typeof superclass!='string'){throw new TypeError('You must extend() with the name of a class, not the function object. '+'This generally means you need to replace "Dog.extend(Animal);" with '+'"Dog.extend(\'Animal\');".');}
if(!Metaprototype._arbiterHandle){Metaprototype._arbiterHandle=Arbiter.subscribe(Arbiter.BOOTLOAD,Metaprototype._onbootload.bind(Metaprototype));}
Metaprototype._queue(this,superclass);}
function Metaprototype(){}
copy_properties(Metaprototype,{_pending:[],_queue:function(subclass,superclass){this._pending.push({subclass:subclass,superclass:superclass});var src=this._pending;var dst=[];for(var ii=0;ii<src.length;++ii){var node=src[ii];for(var jj=0;jj<dst.length;++jj){if(window[dst[jj].superclass]==node.subclass){dst.splice(jj,0,node);break;}}
if(jj==dst.length){dst.push(node);}}
this._pending=dst;},_onbootload:function(type,data){this._update();},_update:function(){for(var ii=0;ii<this._pending.length;++ii){var node=this._pending[ii];var super_object=window[node.superclass];if(!super_object){continue;}
for(var jj=0;jj<this._pending.length;++jj){if(this._pending[jj].subclass==super_object){break;}}
if(jj==this._pending.length){this._pending.splice(ii,1);--ii;this._apply(node.subclass,super_object);}}},_apply:function(subclass,superclass){var superprototype=__metaprototype(superclass,0);var subprototype=__metaprototype(subclass,superprototype.prototype.__level+1);subprototype.parent=superprototype;}});function __metaprototype(obj,level){if(obj.__metaprototype){return obj.__metaprototype;}
var metaprototype=new Function();metaprototype.construct=__metaprototype_construct;metaprototype.prototype.construct=__metaprototype_wrap(obj,level,true);metaprototype.prototype.__level=level;metaprototype.base=obj;obj.prototype.parent=metaprototype;obj.__metaprototype=metaprototype;return metaprototype;}
function __metaprototype_construct(instance){__metaprototype_init(instance.parent);var parents=[];var obj=instance;while(obj.parent){parents.push(new_obj=new obj.parent());new_obj.__instance=instance;obj=obj.parent;}
instance.parent=parents[1];parents.reverse();parents.pop();instance.__parents=parents;instance.__instance=instance;return instance.parent.construct.apply(instance.parent,arguments);}
function __metaprototype_init(metaprototype){if(metaprototype.initialized)return;var base=metaprototype.base.prototype;if(metaprototype.parent){__metaprototype_init(metaprototype.parent);var parent_prototype=metaprototype.parent.prototype;for(i in parent_prototype){if(i!='__level'&&i!='construct'&&base[i]===undefined){base[i]=metaprototype.prototype[i]=parent_prototype[i]}}}
metaprototype.initialized=true;var level=metaprototype.prototype.__level;for(i in base){if(i!='parent'){base[i]=metaprototype.prototype[i]=__metaprototype_wrap(base[i],level);}}}
function __metaprototype_wrap(method,level,shift){if(typeof method!='function'||method.__prototyped){return method;}
var func=function(){var instance=this.__instance;if(instance){var old_parent=instance.parent;instance.parent=level?instance.__parents[level-1]:null;if(shift){var args=[];for(var i=1;i<arguments.length;i++){args.push(arguments[i]);}
var ret=method.apply(instance,args);}else{var ret=method.apply(instance,arguments);}
instance.parent=old_parent;return ret;}else{return method.apply(this,arguments);}}
func.__prototyped=true;return func;}
Function.prototype.mixin=function(){var args=$A(arguments);args.unshift(this.prototype);Function.mixin.apply(null,args);}
Function.mixin=function(){args=$A(arguments);var object=args.shift();for(var i=0;i<args.length;i++){mixin=args[i];if((typeof mixin=='string'&&typeof Mixins[mixin]!='object')&&typeof mixin!='object'&&typeof mixin!='function'){throw new TypeError('mixin was called with an invalid argument. mixin '+'may be called with a variable number of '+'arguments, but each must either be an object or '+'the name of a mixin in "Mixins"');}
mixin=Mixins[mixin]||mixin;copy_properties(object,mixin);}}
Function.prototype.bind=function(context){var argv=[arguments[0],this];var argc=arguments.length;for(var ii=1;ii<argc;ii++){argv.push(arguments[ii]);}
return bind.apply(null,argv);}
Function.prototype.curry=Function.prototype.bind.bind(null,null);Function.prototype.shield=function(context){if(typeof this!='function'){throw new TypeException();}
var bound=this.bind.apply(this,to_array(arguments));return function(){return bound();}};Function.prototype.defer=function(msec){if(typeof this!='function'){throw new TypeError();}
msec=msec||0;return setTimeout(this,msec);};Function.prototype.deferUntil=function(callback,timeout){if(typeof this!='function'){throw new TypeError();}
if(timeout&&typeof timeout!='number'){throw new TypeError();}
if(callback()){this();return;}
var orig=this,interval=null,start_time=(new Date()).getTime();var fn=function(){if(callback()||timeout&&((new Date()).getTime()-start_time)>=timeout){orig();interval&&clearInterval(interval);}};interval=setInterval(fn,50);return interval;};Function.prototype.recur=function(msec){if(typeof this!='function'){throw new TypeError();}
return setInterval(this,msec);};Function.prototype.occur=function(){if(typeof this!='function'){throw new TypeError();}
return this.apply(this,arguments);};Function.prototype.memoize=function(){if(typeof this!='function'){throw new TypeError();}
var cache={};var functor=this;return function(){var key=JSON.encode(arguments);if(!(key in cache)){cache[key]=functor.apply(this,arguments);}
return cache[key];};};Function.prototype.toString=(function(native_fn){return function(full){var raw_output=native_fn.call(this);if(full){return raw_output;}
var lines=raw_output.split('\n'),max_lines=5;if(lines.length>max_lines){lines.splice(3,lines.length-max_lines,'    ...');}
return lines.join('\n');};})(Function.prototype.toString);function bagofholding(){return undefined;}
function abstractMethod(){throw new Error('You must implement this function in your base class.');}
function identity(input){return input;}
function truth(){return true;}
function fireonce(fn){var fired=false;return function(){if(!fired){fired=true;return fn();}}}
function call_or_eval(obj,func,args_map){if(!func){return undefined;}
args_map=args_map||{};if(typeof(func)=='string'){var params=keys(args_map).join(', ');func=eval('({f: function('+params+') { '+func+'}})').f;}
if(typeof(func)!='function'){Util.error('handler was neither a function nor a string of JS code');return undefined;}
return func.apply(obj,values(args_map));}

var Mixins={Arbiter:{_getArbiterInstance:function(){if(!this._arbiter){this._arbiter=new Arbiter();}
return this._arbiter;},subscribe:function(types,callback,subscription_policy){this._getArbiterInstance().subscribe(types,callback,subscription_policy);},inform:function(type,data,behavior){this._getArbiterInstance().inform(type,data,behavior);},unsubscribe:function(token){this._getArbiterInstance().unsubscribe(token);}}};

function object(o){var F=new Function();F.prototype=o;return new F();}
function is_scalar(v){switch(typeof(v)){case'string':case'number':case'null':case'boolean':return true;}
return false;}
function keys(obj){if(hasArrayNature(obj)){throw new TypeError('keys() was passed an array.');}
var keys=[];for(var i in obj){keys.push(i);}
return keys;}
function values(obj){if(hasArrayNature(obj)){throw new TypeError('values() was passed an array; use to_array().');}
var values=[];for(var i in obj){values.push(obj[i]);}
return values;}
function count(obj){if(hasArrayNature(obj)){throw new TypeError('count() was passed an array.');}
var count=0;for(var i in obj){count++;}
return count;}
function are_equal(a,b){return JSON.encode(a)==JSON.encode(b);}
function merge(){var ret={};for(var i=0;i<arguments.length;i++){copy_properties(ret,arguments[i]);}
return ret;}
function obj_filter_keys(obj,keys){var ret={};for(var ii=0;ii<keys.length;ii++){var key=keys[ii];if(key in obj){ret[key]=obj[key];}}
return ret;}
function obj_intersect_keys(){var ret={};var _obj=arguments[0];oloop:for(var j in _obj){if(!_obj.hasOwnProperty(j)){continue;}
iloop:for(var ii=1;ii<arguments.length;ii++){var obj=arguments[ii];for(var k in obj){if(k===j){if(arguments.length-1===ii){ret[j]=_obj[j];}
continue iloop;}}
continue oloop;}}
return ret;}
function head(obj){for(var i in obj){return obj[i];}
return null;}
Object.from=function(keys,values){if(!hasArrayNature(keys)){throw new TypeError('Must pass an array of keys.');}
var object={};var is_array=hasArrayNature(values);if(typeof values=='undefined'){values=true;}
for(var i=keys.length;i--;){object[keys[i]]=is_array?values[i]:values;}
return object;};function coalesce(){for(var i=0;i<arguments.length;++i){if(arguments[i]!=null){return arguments[i];}}
return null;}

function to_array(obj){var ret=[];for(var i=0,l=obj.length;i<l;++i){ret.push(obj[i]);}
return ret;}
var $A=to_array;Array.prototype.alloc=function(length){return length?new Array(length):[];}
Array.prototype.map=function(callback,thisObject){if(this==window){throw new TypeError();}
if(typeof(callback)!=="function"){throw new TypeError();}
var ii;var len=this.length;var r=this.alloc(len);for(ii=0;ii<len;++ii){if(ii in this){r[ii]=callback.call(thisObject,this[ii],ii,this);}}
return r;};Array.prototype.forEach=function(callback,thisObject){this.map(callback,thisObject);return this;};Array.prototype.each=function(callback,thisObject){return this.forEach.apply(this,arguments);}
Array.prototype.filter=function(callback,thisObject){callback=callback||identity;if(this==window){throw new TypeError();}
if(typeof(callback)!=="function"){throw new TypeError();}
var ii,val,len=this.length,r=this.alloc();for(ii=0;ii<len;++ii){if(ii in this){val=this[ii];if(callback.call(thisObject,val,ii,this)){r.push(val);}}}
return r;};Array.prototype.every=function(callback,thisObject){return(this.filter(callback,thisObject).length==this.length);}
Array.prototype.some=function(callback,thisObject){return(this.filter(callback,thisObject).length>0);}
Array.prototype.pull=function(callback){if(this==window){throw new TypeError();}
if(typeof(callback)=='string'){var grip_key=callback;callback=function(){return this[grip_key]};}
if(typeof(callback)!=='function'){throw new TypeError();}
var args=Array.prototype.slice.call(arguments,1);var len=this.length;var r=this.alloc(len);for(ii=0;ii<len;++ii){if(ii in this){r[ii]=callback.apply(this[ii],args);}}
return r;}
Array.prototype.pullEach=function(callback){this.pull.apply(this,arguments);return this;}
Array.prototype.filterEach=function(callback){var map=this.pull.apply(this,arguments);var len=this.length;var r=this.alloc();for(var ii=0;ii<len;++ii){if(ii in this){r.push(this[ii]);}}
return r;}
Array.prototype.reduce=null;Array.prototype.reduceRight=null;Array.prototype.sort=(function(sort){return function(callback){return(this==window)?null:(callback?sort.call(this,function(a,b){return callback(a,b)}):sort.call(this));}})(Array.prototype.sort);Array.prototype.reverse=(function(reverse){return function(){return(this==window)?null:reverse.call(this);}})(Array.prototype.reverse);Array.prototype.concat=(function(concat){return function(){return(this==window)?null:concat.apply(this,arguments);}})(Array.prototype.concat);Array.prototype.slice=(function(slice){return function(){return(this==window)?null:slice.apply(this,arguments);}})(Array.prototype.slice);Array.prototype.clone=Array.prototype.slice;if(Array.prototype.indexOf){Array.prototype.indexOf=(function(indexOf){return function(val,index){return(this==window)?null:indexOf.apply(this,arguments);}})(Array.prototype.indexOf);}else{Array.prototype.indexOf=function(val,index){if(this==window){throw new TypeError();}
var len=this.length;var from=Number(index)||0;from=(from<0)?Math.ceil(from):Math.floor(from);if(from<0){from+=len;}
for(;from<len;from++){if(from in this&&this[from]===val){return from;}}
return-1;};}
Array.prototype.contains=function(val){return this.indexOf(val)!=-1;};Array.prototype.remove=function(val){var index=this.indexOf(val);if(index!=-1){this.splice(index,1);}}
function mapToInt(array){return array.map(function(val,i){return parseInt(val,10);});}
function unique(array){var obj={};var res=[];for(var i=0;i<array.length;i++){var val=array[i];if(!obj[val]){res.push(val);}
obj[val]=1;}
return res;}
function array_set_add(elements,item){if(!elements.contains(item)){elements.push(item);}
return elements;}

var ua={ie:function(){return ua._populate()||this._ie;},firefox:function(){return ua._populate()||this._firefox;},opera:function(){return ua._populate()||this._opera;},safari:function(){return ua._populate()||this._safari;},safariPreWebkit:function(){return ua._populate()||this._safari<500;},windows:function(){return ua._populate()||this._windows;},osx:function(){return ua._populate()||this._osx;},linux:function(){return ua._populate()||this._linux;},_populated:false,_populate:function(){if(ua._populated){return;}
ua._populated=true;var agent=/(?:MSIE.(\d+\.\d+))|(?:(?:Firefox|GranParadiso|Iceweasel).(\d+\.\d+))|(?:Opera.(\d+\.\d+))|(?:AppleWebKit.(\d+(?:\.\d+)?))/.exec(navigator.userAgent);var os=/(Mac OS X)|(Windows;)|(Linux)/.exec(navigator.userAgent);if(agent){ua._ie=agent[1]?parseFloat(agent[1]):NaN;if(ua._ie>=8&&!window.HTMLCollection){ua._ie=7;}
ua._firefox=agent[2]?parseFloat(agent[2]):NaN;ua._opera=agent[3]?parseFloat(agent[3]):NaN;ua._safari=agent[4]?parseFloat(agent[4]):NaN;}else{ua._ie=ua._firefox=ua._opera=ua._safari=NaN;}
if(os){ua._osx=!!os[1];ua._windows=!!os[2];ua._linux=!!os[3];}else{ua._osx=ua._windows=ua._linux=false;}}};

DOMStorage={_storage:{},_elements:{},_tokenCounter:1,_NOT_IN_DOM_CONST:1,_getElementStorage:function(elem){var token;token=(elem.__FB_TOKEN||(elem.__FB_TOKEN=[DOMStorage._tokenCounter++]))[0];DOMStorage._elements[token]=elem;return DOMStorage._storage[token]||(DOMStorage._storage[token]={});},_shouldDeleteData:function(element){if(!element.nodeName){return false;}
try{if(null!=element.offsetParent){return false;}}catch(ex){}
if(document.documentElement.contains){return!document.documentElement.contains(element);}else{return(document.documentElement.compareDocumentPosition(element)&DOMStorage._NOT_IN_DOM_CONST);}},setData:function(element,key,value){var element_store=DOMStorage._getElementStorage(element);element_store[key]=value;return element;},getData:function(element,key,default_value){var element_store=DOMStorage._getElementStorage(element);var value=element_store[key];if((undefined===value)&&(typeof element.getAttribute=='function')){var attr_val=element.getAttribute('data-'+key);value=(null===attr_val)?undefined:attr_val;}
if((default_value!==undefined)&&(value===undefined)){value=element_store[key]=default_value;}
return value;},removeData:function(element,key){var element_store=DOMStorage._getElementStorage(element);delete element_store[key];return element;},cleanup:function(){var elem_token,elem;for(elem_token in DOMStorage._elements){elem=DOMStorage._elements[elem_token];if(DOMStorage._shouldDeleteData(elem)){delete DOMStorage._storage[elem_token];delete DOMStorage._elements[elem_token];}}}};

function chain(u,v){var fn,calls=[];for(var ii=0;ii<arguments.length;ii++){calls.push(arguments[ii]);}
fn=function(event){event=event||window.event;for(var ii=0;ii<calls.length;ii++){if(calls[ii]&&calls[ii].apply(this,arguments)===false){return false;}else if(event&&event.cancelBubble){return true;}}
return true;};fn.toString=function(){return chain._toString(calls);};return fn;}
chain._toString=chain._toString||function(calls){var ret='chained fns',call=calls.filter();for(var i=0;i<calls.length;i++){ret+='\n'+calls[i].toString();}
return ret;};function addEventBase(obj,type,fn,name_hash)
{if(obj.addEventListener){obj.addEventListener(type,fn,false);}
else if(obj.attachEvent)
{var fn_name=type+fn+name_hash;obj["e"+fn_name]=fn;obj[fn_name]=function(){obj["e"+fn_name](window.event);}
obj.attachEvent("on"+type,obj[fn_name]);}
return fn;}
function removeEventBase(obj,type,fn,name_hash)
{if(obj.removeEventListener){obj.removeEventListener(type,fn,false);}
else if(obj.detachEvent)
{var fn_name=type+fn+name_hash;if(obj[fn_name]){obj.detachEvent("on"+type,obj[fn_name]);obj[fn_name]=null;obj["e"+fn_name]=null;}}}
window.Event=window.Event||function(){};Event.prototype=Event.prototype||{};Event.prototype._inherits_from_prototype=true;function $E(e){e=e||window.event;e=e||{};if(!e._inherits_from_prototype){for(var k in Event.prototype){try{e[k]=Event.prototype[k];}catch(ignored){}}}
return e;}
Event.prototype.kill=function(){this.stop();this.prevent();return false;}
Event.prototype.prevent=function(){this.returnValue=false;this.preventDefault&&this.preventDefault();}
Event.prototype.stop=function(){this.cancelBubble=true;this.stopPropagation&&this.stopPropagation();}
Event.stop=function(e){return $E(e).stop();}
Event.kill=function(e){return $E(e).kill();}
Event.prevent=function(e){return $E(e).prevent();}
Event._DOMSTORAGE_KEY='Event.listeners';Event.Priority={URGENT:-20,TRADITIONAL:-10,NORMAL:0,LINK_CONTROLLER:100};Event.listen=function(element,event_name,handler,priority){if(typeof element=='string'){element=$(element,true);}
if(typeof priority=='undefined'){priority=Event.Priority.NORMAL;}
var handlers=DOMStorage.getData(element,Event._DOMSTORAGE_KEY,{});event_name=Event._normalizeName(event_name);Event._attachHandler(element,event_name);var type_handlers=handlers[event_name];if(!(priority in type_handlers)){type_handlers[priority]=[];}
var id=type_handlers[priority].length;var ref=new EventHandlerRef(handler,type_handlers[priority],id);type_handlers[priority].push(ref);return ref;};Event._normalizeName=function(event_name){event_name=event_name.toLowerCase();if(event_name.match(/^on/)){throw new TypeError("Bad event name `"+event_name+"': use `click', not `onclick'.");}
return event_name;};Event._attachHandler=function(element,event_name){var full_event_name='on'+event_name;var handlers=DOMStorage.getData(element,Event._DOMSTORAGE_KEY);if(event_name in handlers){if(element[full_event_name]!==Event._listenHandler){throw new Error("`"+full_event_name+"' listen handler gone!");}
return;}
handlers[event_name]={};var old_handler=element[full_event_name];element[full_event_name]=Event._listenHandler;if(old_handler){Event.listen(element,event_name,old_handler,Event.Priority.TRADITIONAL);}};Event._listenHandler=function(event){event=$E(event);var type=event.type;if(!DOMStorage.getData(this,Event._DOMSTORAGE_KEY)){throw new Error("Bad _listenHandler() context.");}
var type_handlers=DOMStorage.getData(this,Event._DOMSTORAGE_KEY)[type];if(!type_handlers){throw new Error("No registered handlers for `"+type+"'.");}
var priorities=Event._getOrderedPriorities();for(var pri_idx=0;pri_idx<priorities.length;pri_idx++){var priority=priorities[pri_idx];if(priority in type_handlers){var handlers=type_handlers[priority];for(var idx=0;idx<handlers.length;idx++){if(!handlers[idx]){continue;}
var result=handlers[idx].fire(this,event);if(result===false){return event.kill();}else if(event.returnValue===false){return false;}else if(event.cancelBubble){return event.stop();}}}}};Event._listenHandler.toString=function _toString(){return'Use Util.listeners() to see the list of listeners on an element.';};Event._getOrderedPriorities=function(){if(!Event._listenHandler._orderedPriorities){var ordered=values(Event.Priority);ordered.sort(function(a,b){return a-b;});Event._listenHandler._orderedPriorities=ordered;}
return Event._listenHandler._orderedPriorities;}
function EventHandlerRef(handler,container,index){this._handler=handler;this._container=container;this._index=index;}
copy_properties(EventHandlerRef.prototype,{remove:function(){delete this._handler;delete this._container[this._index];},fire:function(element,event){return this._handler.call(element,event);}});Event.prototype.getTarget=function(){var target=this.target||this.srcElement;if(target){return $(target);}
return null;}
Event.prototype.getModifiers=function(){var m={control:!!this.ctrlKey,shift:!!this.shiftKey,alt:!!this.altKey,meta:!!this.metaKey};m.access=ua.osx()?m.control:m.alt;m.any=m.control||m.shift||m.alt||m.meta;return m;}
function event_get_keypress_keycode(event){event=$E(event);if(!event){return false;}
switch(event.keyCode){case 63232:return 38;case 63233:return 40;case 63234:return 37;case 63235:return 39;case 63272:case 63273:case 63275:return null;case 63276:return 33;case 63277:return 34;}
if(event.shiftKey){switch(event.keyCode){case 33:case 34:case 37:case 38:case 39:case 40:return null;}}
return event.keyCode;}

function Stack(){this.stack=[];try{var metaStack=[];try{({}).llama();}catch(e){if(e.stack){var regex=/^[^@]*?@(.+?):([0-9]+)$/mg;for(line=regex.exec(e.stack);line;line=regex.exec()){metaStack.push([line[1],line[2]]);}}}
var frame=arguments.callee,stale=[];for(var frame=arguments.callee,i=0;frame;frame=frame.caller,++i){i&&this.stack.push({func:frame,args:frame.arguments,file:metaStack[i]?metaStack[i][0]:null,line:metaStack[i]?metaStack[i][1]:null,toString:Stack.frameToString});if(stale.indexOf(frame)>=0){break;}
stale.push(frame);}}catch(e){}}
Stack.prototype.shift=function(n){this.stack.splice(0,n);return this;}
Stack.recursion={toString:bind(Stack,'frameToString')};Stack.functionGetName=function(fn,default_name){return(fn&&fn.name)||(/^function *([^(]*)\(/.exec(fn)||[]).pop()||(default_name===undefined?'(no name)':default_name);}
Stack.frameSrcToString=function(file,line){if(!file){return'?';}else if(file.indexOf('TabConsole.getInstance().onresult')>0){return'IceSpider';}else if(file.indexOf('with (__scope__.vars)')>0){return'FireBug';}else{return file+(line?':'+line:'');}}
Stack.frameToString=function(){if(this==Stack.recursion){return'* * recursion * *';}
var str=Stack.argToString(this.func)+'(';for(var i=0;i<this.args.length;i++){str+=(i?', ':'')+Stack.argToString(this.args[i]);}
return str+') @ '+Stack.frameSrcToString(this.file,this.line);}
Stack.argToString=function(arg){if(arg instanceof Function){return Stack.functionGetName(arg);}if(arg instanceof Array){return'Array';}else if(arg instanceof Object){return'Object';}else if(typeof arg=='string'){return'"'+arg.replace(/("|\\)/g,'\\$1')+'"';}else{return arg+'';}}
Stack.prototype.toString=function(){if(!this.stack.length){return'No stack trace available.';}
var str='';for(var i=0;i<this.stack.length;i++){str+=(i?'\n':'')+'#'+i+' '+this.stack[i];}
return str;}

String.prototype.trim=function(){if(this==window){return null;}
return this.replace(/^\s*|\s*$/g,'');}
function trim(text){try{return String(text.toString()).trim();}catch(ignored){return'';}}
String.prototype.startsWith=function(substr){if(this==window){return null;}
return this.substring(0,substr.length)==substr;};String.prototype.endsWith=function(substr){if(this==window){return null;}
return this.length>=substr.length&&this.substring(this.length-substr.length)==substr;};String.prototype.split=(function(split){return function(separator,limit){var flags="";if(separator===null||limit===null){return[];}else if(typeof separator=='string'){return split.call(this,separator,limit);}else if(separator===undefined){return[this.toString()];}else if(separator instanceof RegExp){if(!separator._2||!separator._1){flags=separator.toString().replace(/^[\S\s]+\//,"");if(!separator._1){if(!separator.global){separator._1=new RegExp(separator.source,"g"+flags);}else{separator._1=1;}}}
separator1=separator._1===1?separator:separator._1;var separator2=(separator._2?separator._2:separator._2=new RegExp("^"+separator1.source+"$",flags));if(limit===undefined||limit<0){limit=false;}else{limit=Math.floor(limit);if(!limit)return[];}
var match,output=[],lastLastIndex=0,i=0;while((limit?i++<=limit:true)&&(match=separator1.exec(this))){if((match[0].length===0)&&(separator1.lastIndex>match.index)){separator1.lastIndex--;}
if(separator1.lastIndex>lastLastIndex){if(match.length>1){match[0].replace(separator2,function(){for(var j=1;j<arguments.length-2;j++){if(arguments[j]===undefined)match[j]=undefined;}});}
output=output.concat(this.substring(lastLastIndex,match.index),(match.index===this.length?[]:match.slice(1)));lastLastIndex=separator1.lastIndex;}
if(match[0].length===0){separator1.lastIndex++;}}
return(lastLastIndex===this.length)?(separator1.test("")?output:output.concat("")):(limit?output:output.concat(this.substring(lastLastIndex)));}else{return split.call(this,separator,limit);}}})(String.prototype.split);

function escapeURI(u)
{if(encodeURIComponent){return encodeURIComponent(u);}
if(escape){return escape(u);}}
function htmlspecialchars(text){if(typeof(text)=='undefined'||text===null||!text.toString){return'';}
if(text===false){return'0';}else if(text===true){return'1';}
return text.toString().replace(/&/g,'&amp;').replace(/"/g,'&quot;').replace(/'/g,'&#039;').replace(/</g,'&lt;').replace(/>/g,'&gt;');}
function htmlize(text){return htmlspecialchars(text).replace(/\n/g,'<br />');}
function escape_js_quotes(text){if(typeof(text)=='undefined'||!text.toString){return'';}
return text.toString().replace(/\\/g,'\\\\').replace(/\n/g,'\\n').replace(/\r/g,'\\r').replace(/"/g,'\\x22').replace(/'/g,'\\\'').replace(/</g,'\\x3c').replace(/>/g,'\\x3e').replace(/&/g,'\\x26');}

function sprintf(){if(arguments.length==0){Util.warn('sprintf() was called with no arguments; it should be called with at '+'least one argument.');return'';}
var args=['This is an argument vector.'];for(var ii=arguments.length-1;ii>0;ii--){if(typeof(arguments[ii])=="undefined"){Util.log('You passed an undefined argument (argument '+ii+') to sprintf(). '+'Pattern was: `'+(arguments[0])+'\'.','error');args.push('');}else if(arguments[ii]===null){args.push('');}else if(arguments[ii]===true){args.push('true');}else if(arguments[ii]===false){args.push('false');}else{if(!arguments[ii].toString){Util.log('Argument '+(ii+1)+' to sprintf() does not have a toString() '+'method. The pattern was: `'+(arguments[0])+'\'.','error');return'';}
args.push(arguments[ii]);}}
var pattern=arguments[0];pattern=pattern.toString().split('%');var patlen=pattern.length;var result=pattern[0];for(var ii=1;ii<patlen;ii++){if(args.length==0){Util.log('Not enough arguments were provide to sprintf(). The pattern was: '+'`'+(arguments[0])+'\'.','error');return'';}
if(!pattern[ii].length){result+="%";continue;}
var p=0;var m=0;var r='';var padChar=' ';var padSize=null;var maxSize=null;var rawPad='';var pos=0;if(m=pattern[ii].match(/^('.)?(?:(-?\d+\.)?(-?\d+)?)/)){if(m[2]!==undefined&&m[2].length){padSize=parseInt(rawPad=m[2]);}
if(m[3]!==undefined&&m[3].length){if(padSize!==null){maxSize=parseInt(m[3]);}else{padSize=parseInt(rawPad=m[3]);}}
pos=m[0].length;if(m[1]!==undefined&&m[1].length){padChar=m[1].charAt(1);}else{if(rawPad.charAt(0)==0){padChar='0';}}}
switch(pattern[ii].charAt(pos)){case's':case'#':raw=htmlspecialchars(args.pop().toString());break;case'h':raw=args.pop().toString();break;case'd':raw=parseInt(args.pop()).toString();break;case'f':raw=parseFloat(args.pop()).toString();break;case'q':raw="`"+htmlspecialchars(args.pop().toString())+"'";break;case'e':raw="'"+escape_js_quotes(args.pop().toString())+"'";break;case'L':var list=args.pop();for(var ii=0;ii<list.length;ii++){list[ii]="`"+htmlspecialchars(args.pop().toString())+"'";}
if(list.length>1){list[list.length-1]='and '+list[list.length-1];}
raw=list.join(', ');break;case'x':var x=args.pop();var line=null;var src=null;try{if(typeof(x['line'])!='undefined'){line=x.line;}else if(typeof(x['lineNumber'])!='undefined'){line=x.lineNumber;}
if(typeof(x['sourceURL'])!='undefined'){src=x['sourceURL'];}else if(typeof(x['fileName'])!='undefined'){src=x['fileName'];}}catch(exception){}
var s='[An Exception]';try{s=x.message||x.toString();}catch(exception){}
raw=s+' [at '+Stack.frameSrcToString(src,line)+']';break;default:raw="%"+pattern[ii].charAt(pos+1);break;}
if(padSize!==null){if(raw.length<Math.abs(padSize)){var padding='';var padlen=(Math.abs(padSize)-raw.length);for(var ll=0;ll<padlen;ll++){padding+=padChar;}
if(padSize<0){raw+=padding;}else{raw=padding+raw;}}}
if(maxSize!==null){if(raw.length>maxSize){raw=raw.substr(0,maxSize);}}
result+=raw+pattern[ii].substring(pos+1);}
if(args.length>1){Util.log('Too many arguments ('+(args.length-1)+' extras) were passed to '+'sprintf(). Pattern was: `'+(arguments[0])+'\'.','error');}
return result;}

function env_get(k){return typeof(window['Env'])!='undefined'&&Env[k];}
function muffinize(str){var muffin_top='a';var muffin_bottom='d';var muffin=[muffin_top,muffin_bottom].join('');return str.replace(/muffin/g,muffin);}
var Util={_suppress:false,fallbackErrorHandler:function(msg){aiert(msg);},isDevelopmentEnvironment:function(){return env_get('dev');},warn:function(){Util.log(sprintf.apply(null,arguments),'warn');},error:function(){Util.log(sprintf.apply(null,arguments),'error');},info:function(){Util.log(sprintf.apply(null,arguments),'info');},group:function(){Util.log(sprintf.apply(null,arguments),'group');},groupEnd:function(){Util.log(sprintf.apply(null,arguments),'groupEnd');},log:function(msg,type){if(Util._suppress){return;}
if(Util.isDevelopmentEnvironment()){type=type||'log';if(typeof(console)!='undefined'&&console[type]){console[type](msg);}else if(typeof(window.TabConsole)!='undefined'){var con=TabConsole.getInstance();if(con){con.log(HTML(msg),type);}}else if(Util.fallbackErrorHandler){Util.fallbackErrorHandler(msg);}}else{if(type=='error'){if((typeof(window['Env'])!='undefined')&&(Env.rlog)&&(typeof(window['debug_rlog'])=='function')){msg+='\n\n'+Util.stack();debug_rlog(msg);}}}},setSuppressed:function(suppress){Util._suppress=suppress;},stack:function(){return(new Stack()).toString();},trace:function(){Util.log(Util.stack());},keyForValue:function(obj,val){for(var i in obj){if(obj[i]==val){return i;}}},listeners:function(element,type){if(type.indexOf('on')!==0){type='on'+type;}
var none_found='Sorry, no listeners were found';if(!element[type]){return none_found;}else if(typeof element[type]=='string'){return element[type]||none_found;}else if(element[type]!==Event._listenHandler){return element[type].toString()||none_found;}else{var all_handlers=DOMStorage.getData(element,Event._DOMSTORAGE_KEY),type_handlers=(all_handlers&&all_handlers[type.substring(2)])||{},output=[],priorities=Event._getOrderedPriorities(),found=false;for(var ii=0;ii<priorities.length;ii++){var pri_val=priorities[ii];if(pri_val in type_handlers){var pri_name=Util.keyForValue(Event.Priority,pri_val);if(found){output.push('\n');}
output.push('*** '+pri_name+' Listeners ***');var handlers=type_handlers[pri_val];for(var idx=0;idx<handlers.length;idx++){if(handlers[idx]){found=true;output.push('    '+handlers[idx]._handler.toString().replace(/\n/g,'\n    '));}}}}
return found?output.join('\n'):none_found;}}};chain._toString=function(calls){var indent='\n |  ',first_indent=' |--',last_indent='\n    ',filtered_fns=calls.filter(),output=['Chained Functions ('+filtered_fns.length+')'+indent];for(var ii=0;ii<filtered_fns.length;ii++){var last=(ii==filtered_fns.length-1),ind=last?last_indent:indent;output.push(filtered_fns[ii]?first_indent
+filtered_fns[ii].toString().replace(/\n/g,ind)
+(!last?indent:''):'');}
return output.join('\n');};bind._toString=function(obj,args,method){if(typeof method!='string'&&typeof method!='function'){return'';}
var env=Stack.functionGetName(obj&&obj.constructor,'UnknownType'),late=(typeof method=='string'),b_type=late?'Late Binding Function':'Bound Function',m_name=(late&&method)||(method.toString==Function.prototype.toString&&Stack.functionGetName(method,false))||Util.keyForValue(obj,method)||method.toString().replace(/\n/g,'\n           '),arg_list;if(late){arg_list=args.map(Stack.argToString).join(', ');}else{var fn_str=Function.prototype.toString.call(method);fn_str=fn_str.substr(fn_str.indexOf('(')+1);fn_str=fn_str.substr(0,fn_str.indexOf(')'));arg_list=fn_str.split(',').pull(''.trim).concat(args.slice(method.length).map(function(elm,i){return'undeclared_'+(i+1);})).filter().map(function(param,i){return args[i]===undefined?'<'+param+'>':param+' = '+Stack.argToString(args[i]);}).join(', ')||'no arguments';}
return b_type
+'\n  scope  : '+env
+'\n  params : '+arg_list
+'\n  method : '+m_name;};

window.onloadRegister=function(handler){window.loaded?_runHook(handler):_addHook('onloadhooks',handler);};function onafterloadRegister(handler){window.afterloaded?setTimeout(function(){_runHook(handler);},0):_addHook('onafterloadhooks',handler);}
function onpagecacheRegister(handler,id){id=(id===undefined?'':String(id));window.Quickling&&Quickling.registerPageCacheHook(handler,id);}
function _include_quickling_events_default(){return!window.loading_page_chrome;}
function onbeforeunloadRegister(handler,include_quickling_events){if(include_quickling_events===undefined){include_quickling_events=_include_quickling_events_default();}
if(include_quickling_events){_addHook('onbeforeleavehooks',handler);}else{_addHook('onbeforeunloadhooks',handler);}}
function onunloadRegister(handler,include_quickling_events){if(include_quickling_events===undefined){include_quickling_events=_include_quickling_events_default();}
if(include_quickling_events){_addHook('onleavehooks',handler);}else{_addHook('onunloadhooks',handler);}}
function _readyToLoad(){return!window.bootloader_pending&&(!window.Bootloader||Bootloader.initialResourcesReady())&&window.loading_begun;}
function onResourceReady(){if(_readyToLoad()){_onloadHook();if(window.afterloading_begun){_onafterloadHook();}}}
function _onloadHook(){window.loading_begun=true;if(_readyToLoad()){!window.loaded&&window.Env&&(Env.t_willonloadhooks=(new Date()).getTime());_runHooks('onloadhooks');!window.loaded&&window.Env&&(Env.t_doneonloadhooks=(new Date()).getTime());window.loaded=true;if(window.logOnloadData){aggregate_js_onload('onloadRegister');}}}
function _onafterloadHook(){window.afterloading_begun=true;if(_readyToLoad()){_runHooks('onafterloadhooks');window.afterloaded=true;if(window.logOnloadData){aggregate_js_onload('onafterloadRegister');}}}
function _runHook(handler){try{handler();}catch(ex){Util.error('Uncaught exception in hook (run after page load): %x',ex);}}
function _runHooks(hooks){var isbeforeunload=hooks=='onbeforeleavehooks'||hooks=='onbeforeunloadhooks';var warn=null;if(window.logOnloadData){var startTime=new Date().getTime();window.totalHookTime=window.totalHookTime||{};}
do{var h=window[hooks];if(!isbeforeunload){window[hooks]=null;}
if(!h){break;}
for(var ii=0;ii<h.length;ii++){try{if(isbeforeunload){warn=warn||h[ii]();}else{h[ii]();}}catch(ex){Util.error('Uncaught exception in hook (%q) %q: %x',hooks,h[ii],ex);}}
if(isbeforeunload){break;}}while(window[hooks]);if(window.logOnloadData){var endTime=new Date().getTime();window.totalHookTime[hooks]=endTime-startTime;}
if(isbeforeunload&&warn){return warn;}}
function _addHook(hooks,handler){(window[hooks]?window[hooks]:(window[hooks]=[])).push(handler);}
function removeHook(hooks){window[hooks]=[];}
function _bootstrapEventHandlers(){if(document.addEventListener){if(ua.safari()){var timeout=setInterval(function(){if(/loaded|complete/.test(document.readyState)){(window.Env&&(Env.t_domcontent=(new Date()).getTime()));_onloadHook();clearTimeout(timeout);}},3);}else{document.addEventListener("DOMContentLoaded",function(){(window.Env&&(Env.t_domcontent=(new Date()).getTime()));_onloadHook();},true);}}else{var src='javascript:void(0)';if(window.location.protocol=='https:'){src='//:';}
document.write('<script onreadystatechange="if (this.readyState==\'complete\') {'+'(window.Env&&(Env.t_domcontent=(new Date()).getTime()));'+'this.parentNode.removeChild(this);_onloadHook();}" defer="defer" '+'src="'+src+'"><\/script\>');}
window.onload=chain(window.onload,function(){(window.Env&&(Env.t_layout=(new Date()).getTime()));var force_layout=document&&document.body&&document.body.offsetWidth;(window.Env&&(Env.t_onload=(new Date()).getTime()));_onloadHook();_onafterloadHook();});window.onbeforeunload=function(){var warn=_runHooks('onbeforeleavehooks')||_runHooks('onbeforeunloadhooks');if(!warn){window.loaded=false;window.afterloaded=false;}
return warn;};window.onunload=chain(window.onunload,function(){_runHooks('onleavehooks');_runHooks('onunloadhooks');});}
function keep_window_set_as_loaded(){if(window.loaded==false){window.loaded=true;_runHooks('onloadhooks');}
if(window.afterloaded==false){window.afterloaded=true;_runHooks('onafterloadhooks');}}
function log_js_onload(onloadHook,total_time,task_name){window.logOnloadData=window.logOnloadData||{};window.logOnloadData[onloadHook]=window.logOnloadData[onloadHook]||{};var logOnloadData=window.logOnloadData[onloadHook];if(logOnloadData[task_name]){logOnloadData[task_name].count++;logOnloadData[task_name].total_time+=total_time;}else{logOnloadData[task_name]={};logOnloadData[task_name]={count:1,total_time:total_time};}}
function aggregate_js_onload(onloadHook){var logOnloadData=window.logOnloadData[onloadHook];var array=[];var total_time=0;for(var task_name in logOnloadData){total_time+=logOnloadData[task_name].total_time;array.push(sprintf("%' 4.4d",logOnloadData[task_name].total_time)+'ms : '+
sprintf("%' 2.2d",logOnloadData[task_name].count)+' calls : '+
task_name.replace('Task_','(Task) '));}
if(!array.length){return;}
array.sort().reverse();var key;if(onloadHook=='onloadRegister'){key='onloadhooks';}else{key='onafterloadhooks';}
Util.group(onloadHook+' took a total of '+total_time+' ms with '+
window.totalHookTime[key]+' ms spent in _runHooks');array.each(function(item){Util.info(item);});Util.groupEnd(onloadHook);window.logOnloadData[onloadHook]={};}

window.aiert=(function(a){var aiert=function _aiert(m){if(window.last_alert){(window.alerts=window.alerts||[]).push((new Date()).getTime()-window.last_alert);window.alerts.splice(0,window.alerts.length-3);if(window.alerts.length==3&&window.alerts[0]+window.alerts[1]+window.alerts[2]<200){if(!confirm(m+'\n\nThis page may be caught in an infinite loop. Press "Cancel" to abort, or "Ok" to continue.')){window.aiert=bagofholding;}
window.last_alert=(new Date()).getTime();return;}}
a(m);window.last_alert=(new Date()).getTime();}
return aiert;})(window.alert);window.alert=function _alert(m){if(m!==undefined){(new Image()).src='/ajax/typeahead_callback.php?l='+escapeURI(document.location)+'&m='+
escapeURI(m)+(typeof Env!='undefined'?'&t='+Math.round(((new Date()).getTime()-Env.start)/100):'')+'&d='+escapeURI((typeof fbpd!='undefined')?JSON.encode(fbpd):'')+'&s='+escapeURI(typeof Util!='undefined'?Util.stack():'')+'&ai='+escapeURI(window.aiert)+'&al='+escapeURI(window.alert);return window.aiert(m);}}

function _fbt(text){return fbt(arguments);}
function fbt(text){if(arguments.length==1){return text;}
var name_map=new Object();var match;var arg_index=1;var fbt_reg=/(?:[^\{]|^)(\{\w\})(?!\})/g;while((match=fbt_reg.exec(text))!=null){var token=match[1].slice(1,-1);while(!(token in name_map)){if(arg_index<arguments.length){var arg=arguments[arg_index++];var t_arg=typeof arg;if(arg==null){Util.error('fbt: null value for arg for text: %s',text);}else if(arg instanceof Array||t_arg=="array"){Util.error(sprintf('fbt: cannot use Array type as arg in js fbt. '+'Use Object instead. text: %s',text));}else if(t_arg=='number'||t_arg=='string'){name_map[token]=arg;}else if(t_arg=='object'){copy_properties(name_map,arg);}else{Util.error(sprintf('fbt: cannot use %s type as arg in fbt: %s',t_arg,text));}}else{Util.error('fbt: Too few arguments for text: %s',text);break;}}}
if(arg_index<arguments.length&&typeof arguments[arg_index++]=="string"&&arg_index<arguments.length){Util.error('fbt: Too many arguments.');}
return fbt_replace_braces(text,name_map);}
function fbts(project,text){return fbt.apply(this,to_array(arguments).slice(1));}
function fbt_replace_braces(text,args){if(args){if(typeof args!='object'){Util.error('intl.js: the 2nd argument must be a keyed array (not a string) for tx('+text+', ...)');}else{for(var key in args){var reg=new RegExp("([^\\{]|^)\\{"+key+"\\}(?!\\})",'g');text=text.replace(reg,'$1'+args[key]);}}}
return text.replace(/\{\{/g,'{').replace(/\}\}/g,'}');}
function tx(str,args){if(typeof _string_table=='undefined'){return;}
str=_string_table[str];return _tx(str,args);}
function intl_ends_in_punct(str){if(typeof str!='string'){return false;}
return str.match(new RegExp(intl_ends_in_punct.punct_char_class+'['+')"'+"'"+'\u00BB'+'\u0F3B'+'\u0F3D'+'\u2019'+'\u201D'+'\u203A'+'\u3009'+'\u300B'+'\u300D'+'\u300F'+'\u3011'+'\u3015'+'\u3017'+'\u3019'+'\u301B'+'\u301E'+'\u301F'+'\uFD3F'+'\uFF07'+'\uFF09'+'\uFF3D'+'\s'+']*$'));}
intl_ends_in_punct.punct_char_class='['+'.!?'+'\u3002'+'\uFF01'+'\uFF1F'+'\u0964'+'\u2026'+'\u0EAF'+'\u1801'+'\u0E2F'+'\uFF0E'+']';function intl_phonological_rules(str){var rules=window.intl_locale_rewrites;var regexp;if(rules){var pats=[];var reps=[];for(var p in rules['patterns']){var pat=p;var rep=rules['patterns'][p];for(var m in rules['meta']){regexp=new RegExp(m.slice(1,-1),'g');pat=pat.replace(regexp,rules['meta'][m]);rep=rep.replace(regexp,rules['meta'][m]);}
regexp=new RegExp("\\+",'g');pats[pats.length]=pat.replace(regexp,'\x01');reps[reps.length]=rep.replace(regexp,'\x01');}
for(var ii=0;ii<pats.length;ii++){regexp=new RegExp(pats[ii].slice(1,-1),'g');str=str.replace(regexp,reps[ii]);}}
regexp=new RegExp('\x01','g');str=str.replace(regexp,'');return str;}
function _tx(str,args){if(args){if(typeof args!='object'){Util.error('intl.js: the 2nd argument must be a keyed array (not a string) for tx('+str+', ...)');}else{var regexp;for(var key in args){if(intl_ends_in_punct(args[key])){regexp=new RegExp('\{'+key+'\}'+
intl_ends_in_punct.punct_char_class+'*','g');}else{regexp=new RegExp('\{'+key+'\}','g');}
str=str.replace(regexp,'\x01'+args[key]+'\x01');}
str=intl_phonological_rules(str);}}
return str;}

0;

function RoundedImage(imgSrc){this.imgSrc=imgSrc;this.imgAlt="";this.thesize=RoundedImage.SIZE_DEFAULT;this.background=RoundedImage.BACKGROUND_DEFAULT;}
RoundedImage.SIZE_LARGE='UIRoundedImage_LARGE';RoundedImage.SIZE_SMALL='UIRoundedImage_SMALL';RoundedImage.SIZE_TINY='UIRoundedImage_TINY';RoundedImage.SIZE_DEFAULT=RoundedImage.SIZE_LARGE;RoundedImage.BACKGROUND_NONE='UIRoundedImage_NONE';RoundedImage.BACKGROUND_WHITE='UIRoundedImage_WHITE';RoundedImage.BACKGROUND_GIRLIE='UIRoundedImage_GIRLIE';RoundedImage.BACKGROUND_DARK='UIRoundedImage_DARK';RoundedImage.BACKGROUND_MEDIA='UIRoundedImage_MEDIA';RoundedImage.BACKGROUND_DEFAULT=RoundedImage.BACKGROUND_WHITE;copy_properties(RoundedImage.prototype,{setAlt:function(name){this.imgAlt=name;},setSize:function(size){this.thesize=size;},setBackground:function(bg_const){if(this.corners){CSS.setClass(this.corners,'UIRoundedImage_Corners '+bg_const);}else{this.background=bg_const;}},render:function(){if(this.root){return;}
var controllerClassName='UIRoundedImage'
+' '+this.thesize
+' '+this.background;this.root=$N("span",{className:controllerClassName});var pic=new Image();pic.alt=this.imgAlt;pic.src=this.imgSrc;CSS.setClass(pic,'UIRoundedImage_Image');this.root.appendChild(pic);this.corners=$N("span",{className:'UIRoundedImage_Corners'},$N("span",{className:'UIRoundedImage_CornersSprite'},$N("span",{className:'invisible_png'})));this.root.appendChild(this.corners);return this.root;}});

function Scroller(canvas){this.canvas=canvas;this.scrollZone=50;this.velocity=100;this.coefficient=1;}
Scroller.findScrollParent=function(el){var sty;el=el.parentNode;while(el){if(el.scrollHeight!=el.offsetTop){sty=CSS.getStyle(el,'overflowY');if(sty=='scroll'||sty=='auto'){return el;}}
el=el.parentNode;}
return document.body;}
Scroller.prototype.activate=function(){this.activate=bagofholding;this.event=$(document).listen('mousemove',this._onmousemove.bind(this));this.interval=this._intervalHandler.bind(this).recur(50);this.cursor=null;}
Scroller.prototype.deactivate=function(){delete this.activate;this.event&&this.event.remove();this.event=null;clearInterval(this.interval);}
Scroller.prototype._onmousemove=function(event){this.cursor=new Vector2.getEventPosition(event);}
Scroller.prototype._intervalHandler=function(){if(!this.cursor){return;}
var viewport=this.canvas==document.body?Rect.getViewportBounds():Rect(this.canvas);var rect=new Rect(this.cursor.y-viewport.t,viewport.r-this.cursor.x,viewport.b-this.cursor.y,this.cursor.x-viewport.l);var scrollBy=new Vector2(0,0);if(rect.t<rect.b&&rect.t<this.scrollZone){scrollBy.y=-this.scrollZone+rect.t;}else if(rect.b<this.scrollZone){scrollBy.y=this.scrollZone-rect.b;}
scrollBy.y=this._doMath(scrollBy.y);if(rect.l<rect.r&&rect.l<this.scrollZone){scrollBy.x=-this.scrollZone+rect.l;}else if(rect.r<this.scrollZone){scrollBy.x=this.scrollZone-rect.r;}
scrollBy.x=this._doMath(scrollBy.x);if(scrollBy.x||scrollBy.y){scrollBy.scrollElementBy(this.canvas);if(document.body==this.canvas){this.cursor=this.cursor.add(scrollBy);}
Arbiter.inform('scroller/scroll',this.cursor);}}
Scroller.prototype._doMath=function(diff){return Math.floor(Math.pow((diff>=0?Math.min(diff,this.scrollZone):Math.max(diff,-this.scrollZone))/this.scrollZone*this.velocity,this.coefficient));}

function List(length){if(arguments.length>1){for(var ii=0;ii<arguments.length;ii++){this.push(arguments[ii]);}}else{this.resize(length||0);}}
List.prototype.length=0;List.prototype.size=function(){return this.length;}
List.prototype.resize=function(new_size){this.length=new_size;return this;}
List.prototype.alloc=function(n){return new List(n);}
List.prototype.toString=function(){return'['+this.join(', ')+']';}
List.prototype.push=Array.prototype.push;List.prototype.pop=Array.prototype.pop;List.prototype.join=Array.prototype.join;List.prototype.map=Array.prototype.map;List.prototype.forEach=Array.prototype.forEach;List.prototype.each=Array.prototype.each;List.prototype.filter=Array.prototype.filter;List.prototype.every=Array.prototype.every;List.prototype.some=Array.prototype.some;List.prototype.pull=Array.prototype.pull;List.prototype.pullEach=Array.prototype.pullEach;List.prototype.pullFilter=Array.prototype.pullFilter;List.prototype.splice=Array.prototype.splice;

function Augment(name,generator){this.name=name;this.generator=generator;this.properties=null;}
copy_properties(Augment.prototype,{augmentObject:function(target){if(!target){return target;}
try{if(!target.__augment){target.__augment={};}
if(!target.__augment[this.name]){target.__augment[this.name]=true;copy_properties(target,this.getProperties());}}catch(e){}
return target;},getProperties:function(){if(!this.properties){this.properties=this.generator();}
return this.properties;}});

function HTML(content){if(this===window){if(content instanceof HTML){return content;}
return new HTML(content);}
this._content=content;this._defer=false;this._extra_action='';this._nodes=null;this._inline_js=bagofholding;this._has_option_elements=false;return this;}
copy_properties(HTML.prototype,{toString:function(){var str=this._content;if(this._extra_action){str+='<script type="text/javascript">'+this._extra_action
+'</scr'+'ipt>';}
return str;},setAction:function(js){this._extra_action=js;return this;},getAction:function(){this._fillCache();var fn=function(){this._inline_js();eval_global(this._extra_action);}.bind(this);if(this.getDeferred()){return fn.defer.bind(fn);}else{return fn;}},setDeferred:function(defer){this._defer=!!defer;return this;},getDeferred:function(){return this._defer;},getContent:function(){return this._content;},getNodes:function(){this._fillCache();return this._nodes;},getRootNode:function(){return this.getNodes()[0];},hasOptionElements:function(){this._fillCache();return this._has_option_elements;},_fillCache:function(){if(null!==this._nodes){return;}
var html=this._content;if(!html){this._nodes=[];return;}
html=html.replace(/(<(\w+)[^>]*?)\/>/g,function(all,front,tag){return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?all:front+'></'+tag+'>';});var tags=html.trim().toLowerCase(),wrapper_elem=document.createElement('div'),dummy_span=false;var wrap=(!tags.indexOf('<opt')&&[1,'<select multiple="multiple" class="__WRAPPER">','</select>'])||(!tags.indexOf('<leg')&&[1,'<fieldset class="__WRAPPER">','</fieldset>'])||(tags.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,'<table class="__WRAPPER">','</table>'])||(!tags.indexOf('<tr')&&[2,'<table><tbody class="__WRAPPER">','</tbody></table>'])||((!tags.indexOf('<td')||!tags.indexOf('<th'))&&[3,'<table><tbody><tr class="__WRAPPER">','</tr></tbody></table>'])||(!tags.indexOf('<col')&&[2,'<table><tbody></tbody><colgroup class="__WRAPPER">','</colgroup></table>'])||null;if(null===wrap){wrapper_elem.className='__WRAPPER';if(ua.ie()){wrap=[0,'<span style="display:none">&nbsp;</span>',''];dummy_span=true;}else{wrap=[0,'',''];}}
wrapper_elem.innerHTML=wrap[1]+html+wrap[2];;while(wrap[0]--){wrapper_elem=wrapper_elem.lastChild;}
if(dummy_span){wrapper_elem.removeChild(wrapper_elem.firstChild);}
if(wrapper_elem.className!='__WRAPPER'){Util.warn('HTML._fillCache: HTML markup is not well formed.');}
if(0!=wrapper_elem.getElementsByTagName('option').length){this._has_option_elements=true;}
if(ua.ie()){var tbody;if(!tags.indexOf('<table')&&-1==tags.indexOf('<tbody')){tbody=wrapper_elem.firstChild&&wrapper_elem.firstChild.childNodes;}else if(wrap[1]=='<table>'&&-1==tags.indexOf('<tbody')){tbody=wrapper_elem.childNodes;}else{tbody=[];}
for(var ii=tbody.length-1;ii>=0;--ii){if(tbody[ii].nodeName&&tbody[ii].nodeName.toLowerCase()=='tbody'&&tbody[ii].childNodes.length==0){tbody[ii].parentNode.removeChild(tbody[ii]);}}}
var scripts=wrapper_elem.getElementsByTagName('script');var callbacks=[];for(var i=0;i<scripts.length;i++){if(scripts[i].src){callbacks.push(Bootloader.requestResource.bind(Bootloader,'js',scripts[i].src));}else{callbacks.push(eval_global.bind(null,scripts[i].innerHTML));}}
for(var i=scripts.length-1;i>=0;i--){scripts[i].parentNode.removeChild(scripts[i]);}
var extracted_js=function(){for(var ii=0;ii<callbacks.length;ii++){callbacks[ii]();}};this._nodes=to_array(wrapper_elem.childNodes);this._inline_js=extracted_js;}});

function show(){for(var i=0;i<arguments.length;i++){var element=ge(arguments[i]);if(element&&element.style)element.style.display='';}
return false;}
function hide(){for(var i=0;i<arguments.length;i++){var element=ge(arguments[i]);if(element&&element.style)element.style.display='none';}
return false;}
function shown(el){el=ge(el);return(el.style.display!='none'&&!(el.style.display==''&&el.offsetWidth==0));}
function toggle(){for(var i=0;i<arguments.length;i++){var element=$(arguments[i]);element.style.display=CSS.getStyle(element,"display")=='block'?'none':'block';}
return false;}
function toggleDisplayNone(){for(var i=0;i<arguments.length;i++){var element=$(arguments[i]);if(shown(element)){hide(element);}else{show(element);}}
return false;}
function set_inner_html(obj,html,defer_js_execution){DOM.setContent(obj,HTML(html).setDeferred(!!defer_js_execution));}
function eval_global(js){if('string'!=typeof(js)){throw new Error('JS sent to eval_global is not a string.  Only strings '+'are permitted.');}else if(''==js){return;}
var obj=document.createElement('script');obj.type='text/javascript';try{obj.appendChild(document.createTextNode(js));}catch(e){obj.text=js;}
document.body.appendChild(obj);}
function expandCollapseInplace(topElemId,bottomElemId){topElem=ge(topElemId);bottomElem=ge(bottomElemId);if(!topElem||!bottomElem){return false;}
topElemHeight=topElem.clientHeight;if(shown(bottomElemId)){bottomElemHeight=bottomElem.clientHeight;newHeight=topElemHeight+bottomElemHeight;topElem.style.height=newHeight+'px';CSS.addClass(bottomElem,'hidden_elem');}else{CSS.removeClass(bottomElem,'hidden_elem');bottomElemHeight=bottomElem.clientHeight;newHeight=topElemHeight-bottomElemHeight;topElem.style.height=newHeight+'px';}
return true;}

var DOM={tryElement:function(id,no_augment){if(typeof(id)=='undefined'){Util.error('Tried to get "undefined" element!');return null;}
var obj;var aug=no_augment?identity:DOM._getNodeAugment();if(typeof(id)=='string'){if(id=='book'){Util.error('FB95: Trying to get #book element from JS. #book no'+'longer exists.');}
obj=document.getElementById(id);if(!(ua.ie()>=7&&ua.ie()<8)){return aug(obj);}
if(!obj){return null;}else if(typeof(obj.id)=='string'&&obj.id==id){return aug(obj);}else{var candidates=document.getElementsByName(id);if(!candidates||!candidates.length){return null;}
var maybe=[];for(var ii=0;ii<candidates.length;ii++){var c=candidates[ii];if(!c.id&&id){continue;}
if(typeof(c.id)=='string'&&c.id!=id){continue;}
maybe.push(candidates[ii]);}
if(!maybe.length){return null;}
return aug(maybe[0]);}}
return aug(id);},getElement:function(id,no_augment){var el=DOM.tryElement.apply(null,$A(arguments),no_augment);if(!el){Util.warn('Tried to get element %q, but it is not present in the page. (Use '+'ge() to test for the presence of an element.)',arguments[0]);}
return el;},find:function(element,selector_str){var elements=DOM.scry(element,selector_str);if(1!=elements.length){Util.error('DOM.find located %d elements that matched the selector `%s\''+'.  Please only use find when you are sure that 1 element '+'should match (like $).  Otherwise, please use DOM.scry.',elements.length,selector_str);return null;}
return elements[0];},scry:function(element,selector_str,no_augment){var selectors=selector_str.split(' ');var candidates=[element||document];for(var i=0;i<selectors.length;i++){if(candidates.length==0){break;}
if(selectors[i]==''){continue;}
var selector=selectors[i];var new_candidates=[];selector=selector.replace(/\./g,' .');selector=selector.replace(/\#/g,' #');selector=selector.replace(/\[/g,' [');var sub_selectors=selector.split(' ');var tag=sub_selectors[0]||'*';var id_selector=sub_selectors[1]&&sub_selectors[1].charAt(0)=='#';if(i==0&&tag=='*'&&Util.isDevelopmentEnvironment()&&!id_selector){Util.error('DOM.scry was called without a tag in the selector. You '+'should probably use DOM.scry like `%s` instead of `%s`.','div'+selector_str,selector_str);}
if(id_selector){var elem=ge(sub_selectors[1].slice(1),true);if(elem&&('*'==tag||elem.tagName.toLowerCase()==tag)){for(var iter=0;iter<candidates.length;iter++){if(document==candidates[iter]||DOM.contains(candidates[iter],elem)){new_candidates=[elem];break;}}}}else{var tag_candidates=[];var candidate_l=candidates.length;for(var ii=0;ii<candidate_l;ii++){var elements=candidates[ii].getElementsByTagName(tag);var elements_l=elements.length;for(var jj=0;jj<elements_l;jj++){tag_candidates.push(elements[jj]);}}
var is_class;var class_regexp;for(var sub_iter=1;sub_iter<sub_selectors.length;sub_iter++){var sub_selector=sub_selectors[sub_iter];if(sub_selector.charAt(0)=='.'){is_class=true;class_regexp=new RegExp('\\b'+sub_selector.substring(1)+'\\b');}else{is_class=false;}
for(var ii=0;ii<tag_candidates.length;ii++){var tag_candidate=tag_candidates[ii];if(!tag_candidate){continue;}
if(is_class){if(!class_regexp.test(tag_candidate.className)){delete tag_candidates[ii];}
continue;}else{var class_selector=sub_selector.slice(1,sub_selector.length-1);if(class_selector.indexOf('=')==-1){if(tag_candidate.getAttribute(class_selector)===null){delete tag_candidates[ii];continue;}}else{var parts=class_selector.split('=');var attr=parts[0];var value=parts[1];value=value.slice(1,value.length-1);if(tag_candidate.getAttribute(attr)!=value){delete tag_candidates[ii];continue;}}}}}
for(var ii=0;ii<tag_candidates.length;ii++){if(tag_candidates[ii]){new_candidates.push(tag_candidates[ii]);}}}
candidates=new_candidates;}
var list=null;if(!no_augment){var augment=DOM._getNodeAugment();for(var ii=0;ii<candidates.length;ii++){augment(candidates[ii]);}
list=new NodeList();list.push.apply(list,$A(candidates));}else{list=candidates;}
return list;},getBoxWidth:function(obj){var pL=parseInt(CSS.getStyle(obj,'paddingLeft'),10),pR=parseInt(CSS.getStyle(obj,'paddingRight'),10),bL=parseInt(CSS.getStyle(obj,'borderLeftWidth'),10),bR=parseInt(CSS.getStyle(obj,'borderRightWidth'),10);return obj.offsetWidth-(pL?pL:0)-(pR?pR:0)-(bL?bL:0)-
(bR?bR:0);},getBoxHeight:function(obj){var pT=parseInt(CSS.getStyle(obj,'paddingTop'),10),pB=parseInt(CSS.getStyle(obj,'paddingBottom'),10),bT=parseInt(CSS.getStyle(obj,'borderTopWidth'),10),bW=parseInt(CSS.getStyle(obj,'borderBottomWidth'),10);return obj.offsetHeight-(pT?pT:0)-(pB?pB:0)-(bT?bT:0)-
(bW?bW:0);},setText:function(el,text){if(DOM.isNode(el,DOM.NODE_TYPES.TEXT)){el.data=text;}else{DOM.empty(el);el.appendChild(document.createTextNode(text));}},getText:(function(){var div=document.createElement('div'),prop=div.innerText==null?'textContent':'innerText';return function(el){if(!el){return'';}else if(DOM.isNode(el,DOM.NODE_TYPES.TEXT)){return el.data;}else{return el[prop];}};})(),_getSelectionPrivate:function(onlyTestForSupport){var result=onlyTestForSupport?false:'';if(document.selection&&document.selection.createRange&&document.selection.createRange.text){result=onlyTestForSupport?true:document.selection.createRange().text;}
else if(document.getSelection){result=onlyTestForSupport?true:document.getSelection();}
else if(window.getSelection){result=onlyTestForSupport?true:window.getSelection();}
return result;},getSelectionSupported:function(){return DOM._getSelectionPrivate(true);},getSelection:function(){return DOM._getSelectionPrivate(false);},create:function(element,attributes,children,no_augment){element=document.createElement(element);if(attributes){attributes=copy_properties({},attributes);if(attributes.style){copy_properties(element.style,attributes.style);delete attributes.style;}
for(var k in attributes){if(k.toLowerCase().indexOf('on')==0){Event.listen(element,k.substr(2),attributes[k]);delete attributes[k];}}
copy_properties(element,attributes);}
if(children!=undefined){DOM.setContent(element,children);}
var aug=no_augment?identity:DOM._getNodeAugment();return aug(element);},setID:function(element,id){element.id=id;},prependContent:function(parent,content){if(!DOM.isNode(parent)){throw new Error('DOM.prependContent: reference element is not a node');}
var append_fn=function(fragment){if(parent.firstChild){parent.insertBefore(fragment,parent.firstChild);}else{parent.appendChild(fragment);}};return DOM._addContent(content,append_fn,parent);},insertAfter:function(reference_element,content){if(!DOM.isNode(reference_element)||!reference_element.parentNode){throw new Error('DOM.insertAfter: reference element is not a node');}
var append_fn=function(fragment){if(reference_element.nextSibling){reference_element.parentNode.insertBefore(fragment,reference_element.nextSibling);}else{reference_element.parentNode.appendChild(fragment);}};return DOM._addContent(content,append_fn,reference_element.parentNode);},insertBefore:function(content,reference_element){if(!DOM.isNode(reference_element)||!reference_element.parentNode){throw new Error('DOM.insertBefore: reference element is not a node or '+'does not have a parent.');}
var append_fn=function(fragment){reference_element.parentNode.insertBefore(fragment,reference_element);};return DOM._addContent(content,append_fn,reference_element.parentNode);},setContent:function(el,content){if(!DOM.isNode(el)){throw new Error('DOM.setContent: reference element is not a node');}
DOM.empty(el);return DOM.appendContent(el,content,el);},appendContent:function(reference_element,content){if(!DOM.isNode(reference_element)){throw new Error('DOM.appendContent: reference element is not a node');}
var append_fn=function(fragment){reference_element.appendChild(fragment);};return DOM._addContent(content,append_fn,reference_element);},replace:function(reference_element,content){if(!DOM.isNode(reference_element)||!reference_element.parentNode){throw new Error('DOM.replace: reference element must be a node with a'+' parent');}
var append_fn=function(fragment){reference_element.parentNode.replaceChild(fragment,reference_element);};DOM._addContent(content,append_fn,reference_element.parentNode);},_gettingCaretPosition:false,getCaretPosition:function(element){element=$(element);if(!DOM.isNode(element,['input','textarea'])){return{start:undefined,end:undefined};}
if(!document.selection){return{start:element.selectionStart,end:element.selectionEnd};}
if(DOM.isNode(element,'input')){var range=document.selection.createRange();return{start:-range.moveStart('character',-element.value.length),end:-range.moveEnd('character',-element.value.length)};}else{if(!DOM._gettingCaretPosition){DOM._gettingCaretPosition=true;element.focus();DOM._gettingCaretPosition=false;}
var range=document.selection.createRange();var range2=range.duplicate();range2.moveToElementText(element);range2.setEndPoint('StartToEnd',range);var end=element.value.length-range2.text.length;range2.setEndPoint('StartToStart',range);return{start:element.value.length-range2.text.length,end:end};}},setCaretPosition:function(obj,start,end){obj=$(obj);if(document.selection){if(obj.tagName=='TEXTAREA'){var i=obj.value.indexOf("\r",0);while(i!=-1&&i<end){end--;if(i<start){start--;}
i=obj.value.indexOf("\r",i+1);}}
var range=obj.createTextRange();range.collapse(true);range.moveStart('character',start);if(end!=undefined){range.moveEnd('character',end-start);}
range.select();}else{obj.selectionStart=start;var sel_end=end==undefined?start:end;obj.selectionEnd=Math.min(sel_end,obj.value.length);obj.focus();}},remove:function(element){element=$(element,true);if(element.parentNode){element.parentNode.removeChild(element);if(ua.ie()<8){try{element.outerHTML='';}catch(ignored){}}}},empty:function(element){element=$(element,true);while(element.firstChild){DOM.remove(element.firstChild);}},contains:function(outer_obj,inner_obj){outer_obj=ge(outer_obj,true);inner_obj=ge(inner_obj,true);if(!outer_obj||!inner_obj){return false;}else if(outer_obj===inner_obj){return true;}else if(DOM.isNode(outer_obj,'#text')){return false;}else if(DOM.isNode(inner_obj,'#text')){return DOM.contains(outer_obj,inner_obj.parentNode);}else if(outer_obj.contains){return outer_obj.contains(inner_obj);}else if(outer_obj.compareDocumentPosition){return!!(outer_obj.compareDocumentPosition(inner_obj)&16);}else{return false;}},getRootElement:function(){var elem=null;if(window.Quickling&&Quickling.isActive()){elem=ge('content');}
return elem||DOMScroll.getScrollRoot();},isNode:function(o,of_type){if(typeof(Node)=='undefined'){Node=null;}
try{if(!o||!((Node!=undefined&&o instanceof Node)||o.nodeName)){return false;}}catch(ignored){return false;}
if(typeof(of_type)!=='undefined'){of_type=arrayize(of_type).map(function(i){return(i+'').toUpperCase();});var name,type;try{name=new String(o.nodeName).toUpperCase();type=o.nodeType;}catch(ignored){return false;}
for(var ii=0;ii<of_type.length;ii++){try{if(name==of_type[ii]||type==of_type[ii]){return true;}}catch(ignored){}}
return false;}
return true;},NODE_TYPES:{ELEMENT:1,ATTRIBUTE:2,TEXT:3,CDATA_SECTION:4,ENTITY_REFERENCE:5,ENTITY:6,PROCESSING_INSTRUCTION:7,COMMENT:8,DOCUMENT:9,DOCUMENT_TYPE:10,DOCUMENT_FRAGMENT:11,NOTATION_NODE:12},_addContent:function(content,append_fn,target_element){var item,elements=[],callbacks=[];var fragment=document.createDocumentFragment();if(!(content instanceof Array)){content=[content];}
for(var ii=0;ii<content.length;ii++){item=content[ii];if(item instanceof HTML){callbacks.push(item.getAction());var new_nodes=item.getNodes(),cloned_item;for(var jj=0;jj<new_nodes.length;jj++){cloned_item=(ua.safari()||(ua.ie()&&item.hasOptionElements()))?new_nodes[jj]:new_nodes[jj].cloneNode(true);elements.push(cloned_item);fragment.appendChild(cloned_item);}}else if(is_scalar(item)){var text=document.createTextNode(item);elements.push(text);fragment.appendChild(text);}else if(DOM.isNode(item)){elements.push(item);fragment.appendChild(item);}else if(item instanceof Array){Util.error('DOM._addContent: Nested arrays not supported');}else if(item!==null){Util.error('DOM._addContent: No way to set content %q.',item);}}
append_fn(fragment);for(var ii=0;ii<callbacks.length;ii++){callbacks[ii]();}
if(0<elements.length&&DOM.contains(document.documentElement,target_element)){Arbiter.inform('DOM.contentJustAdded',elements);Arbiter.inform.bind(Arbiter,'DOM.contentAdded',elements).defer();}
return elements;},_nodeAugment:null,_getNodeAugment:function(){if(!DOM._nodeAugment){var aug=new Augment('NodeAugment',function(){var bind1st=function(fn){return function(){return fn.apply(null,[this].concat($A(arguments)));};};return{toString:function(){return'[Node]';},setContent:bind1st(DOM.setContent),prependContent:bind1st(DOM.prependContent),appendContent:bind1st(DOM.appendContent),replace:bind1st(DOM.replace),remove:bind1st(DOM.remove),empty:bind1st(DOM.empty),scry:bind1st(DOM.scry),find:bind1st(DOM.find),listen:bind1st(Event.listen),addClass:bind1st(CSS.addClass),removeClass:bind1st(CSS.removeClass),hasClass:bind1st(CSS.hasClass),toggleClass:bind1st(CSS.toggleClass),getStyle:bind1st(CSS.getStyle),setStyle:bind1st(CSS.setStyle)};});DOM._nodeAugment=aug.augmentObject.bind(aug);}
return DOM._nodeAugment;}};function NodeList(length){if(!NodeList._augmented){var augment=NodeList._getAugment();augment.augmentObject(NodeList.prototype);NodeList._augmented=true;}
List.call(this,length);}
NodeList.prototype=new List();copy_properties(NodeList.prototype,{toString:function(){return'[NodeList]';}});copy_properties(NodeList,{_augmented:false,_getAugment:function(){return new Augment('NodeListAugment',function(){var binditerator=function(iterator,fn){return function(){var args=$A(arguments);return this[iterator](function(value,idx,list){return fn.apply(null,[value].concat(args));});};};var selfreduce=function(fn){return function(){fn.apply(this,$A(arguments));return this;};};var mergereduce=function(type,fn){return function(){var unmerged=fn.apply(this,$A(arguments));var result=new type();for(var ii=0;ii<unmerged.length;ii++){result.push.apply(result,$A(unmerged[ii]));}
return result;};};return{scry:mergereduce(NodeList,binditerator('map',DOM.scry)),addClass:selfreduce(binditerator('map',CSS.addClass)),removeClass:selfreduce(binditerator('map',CSS.removeClass)),hasClass:binditerator('every',CSS.hasClass),toggleClass:selfreduce(binditerator('map',CSS.toggleClass)),getStyle:binditerator('map',CSS.getStyle),setStyle:selfreduce(binditerator('map',CSS.setStyle))};});}});function $N(element,attributes,content){if(typeof attributes!='object'||DOM.isNode(attributes)||attributes instanceof Array||attributes instanceof HTML){content=attributes;attributes=null;}
return DOM.create(element,attributes,content);}
var ge=DOM.tryElement;var $$=function _$$(rules){if(Util.isDevelopmentEnvironment()&&rules&&!(/^[a-zA-Z1-6]+$/).test(rules)&&-1==rules.indexOf('#')){Util.warn('$$() has been called with `%s\' as a selector. You should not use only '+'class or attribute selectors from the document element, because these '+'can not be efficiently queried. Call DOM.find() or DOM.scry() with a '+'root element, or look at DOM.scry() for more information.',rules);}
return DOM.scry.apply(null,[document].concat($A(arguments)));};var $=DOM.getElement;

var DOMScroll={_scrollWrapper:0,usingScrollWrapper:function(){return env_get('use_scroll_wrapper');},getScrollWrapper:function(){if(DOMScroll._scrollWrapper===0){DOMScroll._scrollWrapper=DOMScroll.usingScrollWrapper()?ge('scroll_wrapper'):null;}
return DOMScroll._scrollWrapper;},getScrollRoot:function(){return DOMScroll.getScrollWrapper()||document.body;},SCROLL_CHANGE:'scroll_change',_hasScrollListeners:false,_isScrolled:null,registerScrollChangeHandler:function(cb){Arbiter.subscribe(DOMScroll.SCROLL_CHANGE,cb);if(!DOMScroll._hasScrollListeners){DOMScroll._hasScrollListeners=true;Event.listen(window,'resize',DOMScroll.updateScrollState);}},updateScrollState:function(){if(DOMScroll.usingScrollWrapper()){var wrapper=DOMScroll.getScrollWrapper();var offset_dim=Vector2.getElementDimensions(wrapper);var client_dim=Vector2.getElementDimensions(wrapper,true);var is_scrolled_x=(offset_dim.y>client_dim.y);var is_scrolled_y=(offset_dim.x>client_dim.x);}else{var viewport_dim=Vector2.getViewportDimensions();var document_dim=Vector2.getDocumentDimensions();var is_scrolled_x=(document_dim.x>viewport_dim.x);var is_scrolled_y=(document_dim.y>viewport_dim.y);}
is_scrolled_x+=0;is_scrolled_y+=0;var changed=(DOMScroll._isScrolled===null)||(is_scrolled_x!=DOMScroll._isScrolled.x)||(is_scrolled_y!=DOMScroll._isScrolled.y);if(changed){DOMScroll._isScrolled=new Vector2(is_scrolled_x,is_scrolled_y);var message={sender:DOMScroll,is_scrolled:DOMScroll.getScrollState()};Arbiter.inform(DOMScroll.SCROLL_CHANGE,message,Arbiter.BEHAVIOR_STATE);}},getScrollState:function(){if(DOMScroll._isScrolled===null){DOMScroll.updateScrollState();}
return DOMScroll._isScrolled;},_scrollbarSize:null,_initScrollbarSize:function(){var inner=$N('p');inner.style.width='100%';inner.style.height='200px';var outer=$N('div');outer.style.position='absolute';outer.style.top='0px';outer.style.left='0px';outer.style.visibility='hidden';outer.style.width='200px';outer.style.height='150px';outer.style.overflow='hidden';outer.appendChild(inner);document.body.appendChild(outer);var w1=inner.offsetWidth;outer.style.overflow='scroll';var w2=inner.offsetWidth;if(w1==w2){w2=outer.clientWidth;}
document.body.removeChild(outer);DOMScroll._scrollbarSize=w1-w2;if(DOMScroll._scrollbarSize<5){DOMScroll._scrollbarSize=15;}},getScrollbarSize:function(){if(DOMScroll._scrollbarSize===null){DOMScroll._initScrollbarSize();}
return DOMScroll._scrollbarSize;},scrollTo:function(v,use_animation,center){use_animation=use_animation||use_animation===undefined;if(!(v instanceof Vector2)){var x=Vector2.getScrollPosition().x;var y=Vector2.getElementPosition($(v)).y;y=y-Math.min(0,Math.max(Vector2.getViewportDimensions().y/3,100));v=new Vector2(x,y,'document');}
if(center){v.y-=Vector2.getViewportDimensions().y/2;}
v=v.convertTo('document');var wrapper=DOMScroll.getScrollWrapper();if(use_animation&&window.animation){var root=wrapper||document.body;animation(root).to('scrollTop',v.y).to('scrollLeft',v.x).ease(animation.ease.end).duration(750).go();}else if(wrapper){wrapper.scrollTop=v.y;wrapper.scrollLeft=v.x;}else if(window.scrollTo){window.scrollTo(v.x,v.y);}}};

function Vector2(x,y,domain){copy_properties(this,{x:parseFloat(x),y:parseFloat(y),domain:domain||'pure'});};copy_properties(Vector2.prototype,{toString:function(){return'('+this.x+', '+this.y+')';},add:function(vx,vy){if(arguments.length==1){if(vx.domain!='pure'){vx=vx.convertTo(this.domain);}
return this.add(vx.x,vx.y);}
var dx=parseFloat(vx);var dy=parseFloat(vy);return new Vector2(this.x+dx,this.y+dy,this.domain);},mul:function(sx,sy){if(typeof(sy)=="undefined"){sy=sx;}
return new Vector2(this.x*sx,this.y*sy,this.domain);},sub:function(vx,vy){if(arguments.length==1){return this.add(vx.mul(-1));}else{return this.add(-vx,-vy);}},distanceTo:function(v){return this.sub(v).magnitude();},magnitude:function(){return Math.sqrt((this.x*this.x)+(this.y*this.y));},convertTo:function(newDomain){if(newDomain!='pure'&&newDomain!='viewport'&&newDomain!='document'){Util.error('Domain %q is not valid; legitimate coordinate domains are %q, %q, '+'%q.',newDomain,'pure','viewport','document');return new Vector2(0,0);}
if(newDomain==this.domain){return new Vector2(this.x,this.y,this.domain);}
if(newDomain=='pure'){return new Vector2(this.x,this.y);}
if(this.domain=='pure'){Util.error('Unable to covert a pure vector to %q coordinates; a pure vector is '+'abstract and does not exist in any document coordinate system. If '+'you need to hack around this, create the vector explicitly in some '+'document coordinate domain, by passing a third argument to the '+'constructor. But you probably don\'t, and are just using the class '+'wrong. Stop doing that.',newDomain);return new Vector2(0,0);}
var o=Vector2.getScrollPosition('document');var x=this.x,y=this.y;if(this.domain=='document'){x-=o.x;y-=o.y;}else{x+=o.x;y+=o.y;}
return new Vector2(x,y,newDomain);},setElementPosition:function(el){var p=this.convertTo('document');el.style.left=parseInt(p.x)+'px';el.style.top=parseInt(p.y)+'px';return this;},setElementDimensions:function(el){return this.setElementWidth(el).setElementHeight(el);},setElementWidth:function(el){el.style.width=parseInt(this.x,10)+'px';return this;},setElementHeight:function(el){el.style.height=parseInt(this.y,10)+'px';return this;},scrollElementBy:function(el){if(el==document.body){el=DOMScroll.getScrollRoot();}
if(el==document.body){window.scrollBy(this.x,this.y);}else{el.scrollLeft+=this.x;el.scrollTop+=this.y;}
return this;}});copy_properties(Vector2,{compass:{east:'e',west:'w',north:'n',south:'s',center:'center',northeast:'ne',northwest:'nw',southeast:'se',southwest:'sw'},getEventPosition:function(e,domain){domain=domain||'document';e=$E(e);var x=e.pageX||(e.clientX+
(document.documentElement.scrollLeft||document.body.scrollLeft));var y=e.pageY||(e.clientY+
(document.documentElement.scrollTop||document.body.scrollTop));var v=new Vector2(x,y,'document');if(DOMScroll.getScrollWrapper()){v=v.add(Vector2.getScrollPosition());}
return v.convertTo(domain);},getScrollPosition:function(domain){domain=domain||'document';var wrapper=DOMScroll.getScrollWrapper();if(wrapper){var x=wrapper.scrollLeft;var y=wrapper.scrollTop;}else{var x=document.body.scrollLeft||document.documentElement.scrollLeft;var y=document.body.scrollTop||document.documentElement.scrollTop;}
return(new Vector2(x,y,'document').convertTo(domain));},getElementPosition:function(el,domain){domain=domain||'document';if(!el){return;}
if(ua.safari()<500&&el.tagName=='TR'){el=el.firstChild;}
var left=el.offsetLeft;var top=el.offsetTop;var op=el.offsetParent;var root=DOMScroll.getScrollWrapper()||document.body;var fixed=false;while(el.parentNode&&root!=el.parentNode&&document.body!=el.parentNode){el=el.parentNode;if(!isNaN(el.scrollTop)){if(!(ua.opera()<9.50)||!operaIgnoreScroll[window.getComputedStyle(el,'').getPropertyValue('display')]){top-=el.scrollTop;left-=el.scrollLeft;}}
if(op==el){if(ua.safari()<500&&el.tagName=='TR'){top+=el.firstChild.offsetTop;left+=el.firstChild.offsetLeft;}else{top+=el.offsetTop;left+=el.offsetLeft;}
op=el.offsetParent;}
if(op&&CSS.getStyle(op,'position')=='fixed'){fixed=true;top+=op.offsetTop;left+=op.offsetLeft;break;}}
if(fixed){var scrollPosition=Vector2.getScrollPosition('document');left+=scrollPosition.x;top+=scrollPosition.y;}
return(new Vector2(left,top,'document').convertTo(domain));},getElementDimensions:function(el,useClient){if(ua.safariPreWebkit()&&el.nodeName=='TR'){var tds=el.getElementsByTagName('td');var dimensions=Vector2.getElementCompassPoint(tds[tds.length-1],Vector2.compass.southeast,useClient).sub(Vector2.getElementPosition(tds[0],'document',useClient));return dimensions;}
var x=(useClient?el.clientWidth:el.offsetWidth)||0;var y=(useClient?el.clientHeight:el.offsetHeight)||0;return new Vector2(x,y);},getHiddenElementDimensions:function(el){var element=$(el);var els=element.style;var originalVisibility=els.visibility;var originalPosition=els.position;var originalDisplay=els.display;if(originalDisplay=='none'){els.visibility='hidden';els.position='absolute';els.display='block';}
var originalDimensions=Vector2.getElementDimensions(element);els.display=originalDisplay;els.position=originalPosition;els.visibility=originalVisibility;return originalDimensions;},getElementCompassPoint:function(el,which,useClient){which=which||Vector2.compass.southeast;var p=Vector2.getElementPosition(el);var d=Vector2.getElementDimensions(el,useClient);var c=Vector2.compass;switch(which){case c.east:return p.add(d.x,d.y*.5);case c.west:return p.add(0,d.y*.5);case c.north:return p.add(d.x*.5,0);case c.south:return p.add(d.x*.5,d.y);case c.center:return p.add(d.mul(.5));case c.northwest:return p;case c.northeast:return p.add(d.x,0);case c.southwest:return p.add(0,d.y);case c.southeast:return p.add(d);}
Util.error('Unknown compass point %s.',which);return p;},getViewportDimensions:function(){var x=(window&&window.innerWidth)||(document&&document.documentElement&&document.documentElement.clientWidth)||(document&&document.body&&document.body.clientWidth)||0;var y=(window&&window.innerHeight)||(document&&document.documentElement&&document.documentElement.clientHeight)||(document&&document.body&&document.body.clientHeight)||0;return new Vector2(x,y,'viewport');},getDocumentDimensions:function(){var wrapper=DOMScroll.getScrollWrapper();var x=(wrapper&&wrapper.scrollWidth)||(document&&document.documentElement&&document.documentElement.scrollWidth)||(document&&document.body&&document.body.scrollWidth)||0;var y=(wrapper&&wrapper.scrollHeight)||(document&&document.documentElement&&document.documentElement.scrollHeight)||(document&&document.body&&document.body.scrollHeight)||0;return new Vector2(x,y,'document');},scrollIntoView:function(el){var offsetParent=el.offsetParent;var rect=Rect(el);var position=rect.boundWithin(Rect(offsetParent)).getPositionVector();rect.getPositionVector().sub(position).scrollElementBy(offsetParent);}});var mouseX=function(e){return Vector2.getEventPosition(e).x;}
var mouseY=function(e){return Vector2.getEventPosition(e).y;}
var pageScrollX=function(){return Vector2.getScrollPosition().x;}
var pageScrollY=function(){return Vector2.getScrollPosition().y;}
var getViewportWidth=function(){return Vector2.getViewportDimensions().x;}
var getViewportHeight=function(){return Vector2.getViewportDimensions().y;}
var operaIgnoreScroll={'table':true,'inline-table':true,'inline':true};function elementX(obj){return Vector2.getElementPosition(obj,'document').x;}
function elementY(obj){return Vector2.getElementPosition(obj,'document').y;}

function Rect(t,r,b,l,domain){if(this===window){if(t instanceof Rect){return t;}
return Rect.getElementBounds($(t));}
copy_properties(this,{t:t,r:r,b:b,l:l,domain:domain||'pure'});};copy_properties(Rect.prototype,{w:function(){return this.r-this.l;},h:function(){return this.b-this.t;},area:function(){return this.w()*this.h();},toString:function(){return'(('+this.l+', '+this.t+'), ('+this.r+', '+this.b+'))';},intersects:function(v){v=Rect(v).convertTo(this.domain);var u=this;if(u.l>v.r||v.l>u.r||u.t>v.b||v.t>u.b){return false;}
return true;},clipTo:function(clipRect){clipRect=clipRect.convertTo(this.domain);if(!this.intersects(clipRect)){return null;}
return new Rect(Math.max(this.t,clipRect.t),Math.min(this.r,clipRect.r),Math.min(this.b,clipRect.b),Math.max(this.l,clipRect.l),this.domain);},contains:function(v){v=Rect(v).convertTo(this.domain);var u=this;if(v instanceof Vector2){return(u.l<=v.x&&u.r>=v.x&&u.t<=v.y&&u.b>=v.y);}else{return(u.l<=v.l&&u.r>=u.r&&u.t<=v.t&&u.b>=v.b);}},canContain:function(v){v=Rect(v).convertTo(this.domain);return(v.h()<=this.h())&&(v.w()<=this.w());},forceBelow:function(v,min){min=min||0;v=Rect(v).convertTo(this.domain);if(v.b>this.t){return this.add(0,(v.b-this.t)+min);}
return this;},add:function(vx,vy){if(arguments.length==1){if(vx.domain!='pure'){vx=vx.convertTo(this.domain);}
return this.add(vx.x,vx.y);}
var dx=parseFloat(vx);var dy=parseFloat(vy);return new Rect(this.t+dy,this.r+dx,this.b+dy,this.l+dx,this.domain);},sub:function(vx,vy){if(arguments.length==1){return this.add(vx.mul(-1));}else{return this.add(-vx,-vy);}},expand:function(x,y){return new Rect(this.t,this.r+x,this.b+y,this.l,this.domain);},scale:function(x,y){y=y||x;return new Rect(this.t,this.l+(this.w()*x),this.t+(this.h()*y),this.l,this.domain);},setDimensions:function(x,y){return new Rect(this.t,this.l+x,this.t+y,this.l,this.domain);},setPosition:function(x,y){return new Rect(x,this.w(),this.h(),y,this.domain);},boundWithin:function(v){var x=0,y=0;if(this.l<v.l){x=v.l-this.l;}else if(this.r>v.r){x=v.r-this.r;}
if(this.t<v.t){y=v.t-this.t;}else if(this.b>v.b){y=v.b-this.b;}
return this.add(x,y);},setElementBounds:function(el){this.getPositionVector().setElementPosition(el);this.getDimensionVector().setElementDimensions(el);return this;},getPositionVector:function(){return new Vector2(this.l,this.t,this.domain);},getDimensionVector:function(){return new Vector2(this.w(),this.h(),'pure');},convertTo:function(newDomain){if(this.domain==newDomain){return this;}
if(newDomain=='pure'){return new Rect(this.t,this.r,this.b,this.l,'pure');}
if(this.domain=='pure'){Util.error('Unable to convert a pure rect to %q coordinates.',newDomain);return new Rect(0,0,0,0);}
var p=new Vector2(this.l,this.t,this.domain).convertTo(newDomain);return new Rect(p.y,p.x+this.w(),p.y+this.h(),p.x,newDomain);},constrict:function(x,y){if(typeof(y)=='undefined'){y=x;}
x=x||0;return new Rect(this.t+y,this.r-x,this.b-y,this.l+x,this.domain);},expandX:function(){return new Rect(this.t,Number.POSITIVE_INFINITY,this.b,Number.NEGATIVE_INFINITY);},expandY:function(){return new Rect(number.NEGATIVE_INFINITY,this.r,Number.POSITIVE_INFINITY,this.l);},drawBox:function(color){var d=$N('div',{style:{position:'absolute',border:'2px solid '+(color||'red'),zIndex:'10000'}});this.setElementBounds(d);document.body.appendChild(d);}});copy_properties(Rect,{newFromVectors:function(pos,dim){return new Rect(pos.y,pos.x+dim.x,pos.y+dim.y,pos.x,pos.domain);},getElementBounds:function(el){return Rect.newFromVectors(Vector2.getElementPosition(el),Vector2.getElementDimensions(el));},getViewportBounds:function(){return Rect.newFromVectors(Vector2.getScrollPosition(),Vector2.getViewportDimensions());},getDocumentBounds:function(){return Rect.newFromVectors(new Vector2(0,0,'document'),Vector2.getDocumentDimensions());}});

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;Arbiter.subscribe('scroller/scroll',Drag._onmousemove);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]=Drag.droppables[namespace].filter(function(a){return a!=droppable;});}
Drag._onmousemove=function(event,cursor){if(!Drag.currentDraggable){return;}
var cursorPosition=cursor||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.dom!=null&&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(e){document.onselectstart=null;if(Drag.currentDraggable){Drag.currentDraggable._ondrop();Drag.currentDraggable=null;}}
function Draggable(element){if(!element){throw new Error('Element should be a DOM node');}
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.boundingBox=null;this.addHandle(this.dom);}}
Draggable.prototype.destroy=function(){this.handles.each(function(handle){this.removeHandle(handle.obj);}.bind(this));this.data=this.dom=null;}
Draggable.prototype._onclick=function(event){if(this.active){return Event.kill(event);}}
Draggable.prototype._ongrab=function(vector){this.ongrab();if(!this.scroller){this.scroller=new Scroller(Scroller.findScrollParent(this.dom));}
this.scroller.activate();if(this.active){if(!this.oldPosition){this.oldPosition=this.dom.style.position;}
this.dom.style.position=this.absolute?'absolute':'relative';vector.sub(this.cursorPositionVector).setElementPosition(this.dom);}}
Draggable.prototype._onmousedown=function(event){var target=$E(event).getTarget();if(DOM.isNode(target,['input','select','textarea','object','embed'])){return true;}
var vector=Vector2.getEventPosition(event);this.draggableInitialVector=Vector2.getElementPosition(this.dom);this.cursorPositionVector=vector.sub(this.draggableInitialVector);Drag.grab(this,event);if(this.gutter){this.cursorInitialVector=vector;}else{this._setActive(true);this._ongrab(vector);}
return Event.kill(event);}
Draggable.prototype._onmousemove=function(vector){if(!this.active){if(vector.distanceTo(this.cursorInitialVector)>=this.gutter){this._setActive(true);this._ongrab(vector);}}
if(this.active){var sub_vector=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));var vector2=vector.sub(sub_vector).sub(this.cursorPositionVector);if(this.boundingBox){var box=Rect.newFromVectors(vector2,Vector2.getElementDimensions(this.dom));box=box.boundWithin(this.boundingBox);vector2=box.getPositionVector(box);if(this.boundingBox.w()==0){var final_vector=new Vector2(this.draggableInitialVector.x,vector2.y,'document');}else if(this.boundingBox.h()==0){var final_vector=new Vector2(vector2.x,this.draggableInitialVector.y,'document');}else{var final_vector=vector2;}}else{var final_vector=vector2;}
final_vector.setElementPosition(this.dom);this.ondrag(vector);}}
Draggable.prototype._ondrop=function(){this.scroller&&this.scroller.deactivate();if(this.active){(function(){this._setActive(false);}).bind(this).defer();this.ondrop();if(this.lastDragOver){this.lastDragOver.ondrop(this);}}}
Draggable.prototype.killDrag=function(){this._setActive(false);Drag._onmouseup();}
Draggable.prototype.setBoundingBox=function(bounding_box){this.boundingBox=bounding_box;return 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].obj==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=this.handles.filter(function(a){if(a.obj!=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(!element){throw new Error('Element should be a DOM node');}
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);}
this.namespace=namespace;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;

var CSS={hasClass:function(element,className){element=$(element);if(element&&className&&element.className){return new RegExp('(?: |^)'+trim(className)+'(?: |$)').test(element.className);}
return false;},addClass:function(element,className){element=$(element);if(element&&className){if(!CSS.hasClass(element,className)){className=trim(className);if(element.className){element.className+=' '+className;}else{element.className=className;}}}
return this;},removeClass:function(element,className){element=$(element);if(element&&className&&element.className){className=trim(className);element.className=element.className.split(' ').filter(function(ii){if(ii!=className){return true;}}).join(' ');}
return this;},conditionClass:function(element,className,shouldShow){element=$(element);if(shouldShow){CSS.addClass(element,className);}else{CSS.removeClass(element,className);}},chooseClass:function(element,expression,trueClass,falseClass){CSS.conditionClass(element,trueClass,expression);CSS.conditionClass(element,falseClass,!expression);},setClass:function(element,className){element=$(element,true);element.className=className;return this;},toggleClass:function(element,className){element=$(element);if(CSS.hasClass(element,className)){return CSS.removeClass(element,className);}else{return CSS.addClass(element,className);}},setStyle:function(element,name,value){element.style[name]=value;return element;},getStyle:function(element,property){element=$(element);function hyphenate(property){return property.replace(/[A-Z]/g,function(match){return'-'+match.toLowerCase();});}
if(window.getComputedStyle){return window.getComputedStyle(element,null).getPropertyValue(hyphenate(property));}
if(document.defaultView&&document.defaultView.getComputedStyle){var computedStyle=document.defaultView.getComputedStyle(element,null);if(computedStyle)
return computedStyle.getPropertyValue(hyphenate(property));if(property=="display")
return"none";Util.error("Can't retrieve requested style %q due to a bug in Safari",property);}
if(element.currentStyle){return element.currentStyle[property];}
return element.style[property];},setOpacity:function(element,opacity){element=$(element);var opaque=(opacity==1);try{element.style.opacity=(opaque?'':''+opacity);}catch(ignored){}
try{element.style.filter=(opaque?'':'alpha(opacity='+(opacity*100)+')');}catch(ignored){}},getOpacity:function(element){element=$(element);var opacity=CSS.getStyle(element,'filter');var val=null;if(opacity&&(val=/(\d+(?:\.\d+)?)/.exec(opacity))){return parseFloat(val.pop())/100;}else if(opacity=CSS.getStyle(element,'opacity')){return parseFloat(opacity);}else{return 1.0;}},Cursor:{kGrabbable:'grabbable',kGrabbing:'grabbing',kEditable:'editable',set:function(element,name){element=$(element);element=element||document.body;switch(name){case CSS.Cursor.kEditable:name='text';break;case CSS.Cursor.kGrabbable:if(ua.firefox()){name='-moz-grab';}else{name='move';}
break;case CSS.Cursor.kGrabbing:if(ua.firefox()){name='-moz-grabbing';}else{name='move';}
break;}
element.style.cursor=name;}}};

function UINav(controller,item_data,data){this.controller=controller;this.data=data;copy_properties(this,{controller:controller,data:data,items:[],selectedItem:null,selectedClass:this.selectedClass||''});this.initializeItems(item_data);}
UINav.instances={};UINav.prototype.getItemContainers=abstractMethod;UINav.prototype.getItemLinks=abstractMethod;UINav.prototype.getItems=function(){return this.items;}
UINav.prototype.initializeItems=function(item_data){var containers=this.getItemContainers();var links=this.getItemLinks();for(var i=0;i<containers.length;i++){var item={'container':containers[i],'link':links[i],'data':(item_data[i]||{})};this.items.push(item);if(CSS.hasClass(item.container,this.selectedClass)){this.selectedItem=item;}
item.addClickHandler=this.addClickHandler.bind(this,item);item.addClickHandler(this.selectItem.bind(this,item));}}
UINav.prototype.selectItem=function(item){if(item==this.selectedItem){return;}
if(this.selectedItem){CSS.removeClass(this.selectedItem.container,this.selectedClass);}
if(item){CSS.addClass(item.container,this.selectedClass);}
this.selectedItem=item;}
UINav.prototype.deselectAll=function(){if(this.selectedItem){CSS.removeClass(this.selectedItem.container,this.selectedClass);}
this.selectedItem=null;}
UINav.prototype.getSelectedItem=function(){return this.selectedItem;}
UINav.prototype.addClickHandler=function(item,handler){if(typeof item=='function'){handler=item;this.getItems().each(function(handler,item){this.addClickHandler(item,handler);}.bind(this,handler));return true;}else{return Event.listen(item.link,'click',handler);}}
function UINavGeneric(controller,item_data,data){this.parent.construct(this,controller,item_data,data);}
UINavGeneric.extend('UINav');UINavGeneric.prototype.getItemContainers=function(){if(!this.containers){this.containers=DOM.scry(this.controller,'li');}
return this.containers;}
UINavGeneric.prototype.getItemLinks=function(){if(!this.containerLinks){this.containerLinks=DOM.scry(this.controller,'li a');}
return this.containerLinks;}
function UITabStructure(controller,item_data,data){this.selectedClass='UITabStructure_TabSelected';this.parent.construct(this,controller,item_data,data);}
UITabStructure.extend('UINavGeneric');UITabStructure.prototype.getItemContainers=function(){if(!this.tab_containers){this.tab_containers=[];var li_elements=DOM.scry(this.controller,'li');for(var i=0;i<li_elements.length;i++){this.tab_containers.push(li_elements[i].childNodes[0]);}}
return this.tab_containers;}
function UISourceList(controller,item_data,data){this.selectedClass='UISourceList_ItemSelected';this.parent.construct(this,controller,item_data,data);}
UISourceList.extend('UINavGeneric');function UIFilterList(controller,item_data,data){this.selectedClass='UIObject_SelectedItem';this._itemsContainer=DOM.scry(controller,'div.UIFilterList_List')[0];this.parent.construct(this,controller,item_data,data);this._editIconHandler=bagofholding;var items=this.getItems();for(var i=0;i<items.length;i++){var link=items[i].link;if(CSS.hasClass(link,'UIFilterList_HasEditIcon')){var edit_icon=DOM.find(link,'span.UIFilterList_EditIcon');if(edit_icon){edit_icon.listen('mouseover',function(icon){CSS.addClass(icon,'UIFilterList_EditIconHover');}.bind(null,edit_icon));edit_icon.listen('mouseout',function(icon){CSS.removeClass(icon,'UIFilterList_EditIconHover');}.bind(null,edit_icon));edit_icon.listen('click',function(data){this._editIconHandler(data);return false;}.bind(this,items[i]['data']));}}}}
UIFilterList.extend('UINav');UIFilterList.prototype.getItemContainers=function(){if(!this.containers){this.containers=DOM.scry(this.controller,'div.UIFilterList_Item');}
return this.containers;}
UIFilterList.prototype.getItemLinks=function(){if(!this.containerLinks){this.containerLinks=DOM.scry(this.controller,'div.UIFilterList_Item a');}
return this.containerLinks;}
UIFilterList.prototype.setEditIconHandler=function(handler){this._editIconHandler=handler;return this;}
UIFilterList.prototype.setLoading=function(loading){CSS.conditionClass(this.controller,'UIFilterList_Loading',loading);}
UIFilterList.prototype.setCreateLinkHandler=function(handler){var elem=DOM.find(this.controller,'a.UIFilterList_Create');elem.listen('click',handler);}
UIFilterList.prototype.addItem=function(title,href,pos,icon,data){if(!pos){pos=0;}
var items=this.getItems();data=data?data:{};var main_div=$N('div',{className:'UIFilterList_Item'});var link=$N('a',{className:'UIFilterList_ItemLink',href:href});if(icon){main_div.addClass('UIFilterList_HasIcon');var icon_span=$N('span',{className:'UIFilterList_Icon'});icon_span.setStyle('backgroundImage','url('+icon+')');link.appendContent(icon_span);}
link.appendContent($N('span',{className:'UIFilterList_Title'},title));var loading=$N('span',{className:'UIFilterList_LoadingIndicator'});var right=$N('span',{className:'UIFilterList_ItemRight'});main_div.setContent([link,loading,right]);if(pos==0&&items[0]){main_div.addClass('UIFilterList_FirstItem');items[0].container.removeClass('UIFilterList_FirstItem');}
if(pos==(items.length)){main_div.addClass('UIFilterList_LastItem');if(items.length>0){items[items.length-1].container.removeClass('UIFilterList_LastItem');}}
var item={container:main_div,link:link,data:data};if(items.length>0){if(this.getItems()[pos]){DOM.insertBefore(main_div,items[pos].container);}else{pos=pos-1;DOM.insertAfter(items[pos].container,main_div);}}else{this._itemsContainer.appendContent(main_div);CSS.removeClass(this.controller,'UIFilterList_HasBlankState');}
this.getItems().splice(pos,0,item);this.getItemContainers().splice(pos,0,item.container);this.getItemLinks().splice(pos,0,item.link);return item;}
UIFilterList.prototype.setItemTitle=function(item,title){var title_span=DOM.find(item.link,'span.UIFilterList_Title');title_span.setContent(title);}
UIFilterList.prototype.removeItem=function(item){var items=this.getItems();var item_index=null;for(var i=0;i<items.length;i++){if(items[i]==item){item_index=i;break;}}
if(item_index!=null){if(this.selectedItem==item){this.selectItem(null);}
this.getItemContainers().splice(item_index,1);this.getItemLinks().splice(item_index,1);this.getItems().splice(item_index,1);DOM.remove(item.container);}
if(items.length==0){CSS.addClass(this.controller,'UIFilterList_HasBlankState');}}

function UIMutableFilterList(controller,item_data,num_visible,data){this.showLink=controller.find('a.UIMutableFilterList_Show');this.hideLink=controller.find('a.UIMutableFilterList_Hide');this.hiddenContainer=controller.find('div.UIMutableFilterList_HiddenSection');this.showLink.listen('click',this.showBottom.bind(this));this.hideLink.listen('click',this.hideBottom.bind(this));this.emptyMsg=controller.find('div.UIMutableFilterList_EmptyMsg');this.orderMsg=controller.find('div.UIMutableFilterList_OrderMsg');this.bottomShown=this.showLink.hasClass('hidden_elem');this.numVisible=num_visible;return this.parent.construct(this,controller,item_data,data);}
UIMutableFilterList.extend('UIFilterList');UIMutableFilterList.prototype.setOrderChangedHandler=function(handler){this.orderChangedHandler=handler;return this;}
UIMutableFilterList.prototype.getOrderedItems=function(){var ordered={};ordered.shown=[];ordered.hidden=[];var top_order=this.topGroup.getOrder();for(var i=0;i<top_order.length;i++){if(this.getItems()[top_order[i]]){ordered.shown.push(this.getItems()[top_order[i]].data);}}
var bottom_order=this.bottomGroup.getOrder();for(var i=0;i<bottom_order.length;i++){if(this.getItems()[bottom_order[i]]){ordered.hidden.push(this.getItems()[bottom_order[i]].data);}}
return ordered;}
UIMutableFilterList.prototype.initializeItems=function(item_data){var LIMIT_TO_SHOW_MORE_SECTION=3;var ongrabcallback=function(i){if(CSS.hasClass(this.showLink,'hidden_elem')&&CSS.hasClass(this.hideLink,'hidden_elem')&&this.getItemContainers().length>LIMIT_TO_SHOW_MORE_SECTION){this.showBottom();CSS.addClass(this.orderMsg,'hidden_elem');}
CSS.setOpacity(this.getItemContainers()[i],0.5);Vector2.getElementDimensions(this.getItemContainers()[i]).sub(4,0).setElementWidth(this.getItemContainers()[i]);}.bind(this);var ondropcallback=function(i){if(!CSS.hasClass(this.emptyMsg,'hidden_elem')){this.hideBottom();CSS.addClass(this.showLink,'hidden_elem');}
CSS.setOpacity(this.getItemContainers()[i],1);this.fixItemClasses();this.setBoundingBox(this.getCurrentBoundingBox());}.bind(this);this.topGroup=new SortableGroup();this.topGroup.setGrabCallback(ongrabcallback);this.topGroup.setDropCallback(ondropcallback);this.topGroup.setOrderChangeHandler(this.orderChanged.bind(this));this.bottomGroup=new SortableGroup();this.bottomGroup.setGrabCallback(ongrabcallback);this.bottomGroup.setDropCallback(ondropcallback);this.bottomGroup.setOrderChangeHandler(this.orderChanged.bind(this));this.topGroup.link(this.bottomGroup);var items=this.getItemContainers();var link_items=this.getItemLinks();for(var i=0;i<items.length;i++){if(i<this.numVisible){this.topGroup.addSortable(i,items[i]);this.topGroup.draggables[i].addHandle(link_items[i]);this.topGroup.draggables[i].addHandle(items[i]);}else{this.bottomGroup.addSortable(i,items[i]);this.bottomGroup.draggables[i].addHandle(link_items[i]);this.bottomGroup.draggables[i].addHandle(items[i]);}}
var root=this.hiddenContainer.find('div.UIFilterList_List');this.bottomGroup.addEmptyMessage(this.emptyMsg,root);this.bottomGroup.setLinkJumpHandler(function(){if(root.childNodes.length>1){CSS.addClass(this.emptyMsg,'hidden_elem');}else{CSS.removeClass(this.emptyMsg,'hidden_elem');CSS.addClass(this.orderMsg,'hidden_elem');}}.bind(this));this.topGroup.setNeverEmpty(true);this.orderChangedHandler=bagofholding;this.setBoundingBox(this.getCurrentBoundingBox());return this.parent.initializeItems(item_data);}
UIMutableFilterList.prototype.orderChanged=function(){this.orderChangedHandler(this.getOrderedItems());}
UIMutableFilterList.prototype.fixItemClasses=function(){var top_length=this.topGroup.getOrder().length;var items=this.controller.scry('div.UIFilterList_Item');for(var i=0;i<items.length;i++){if(i<top_length){var first=(i==0);var last=(i==top_length-1);}else{var first=(i==top_length);var last=(i==items.length-1);}
CSS.removeClass(items[i],'UIFilterList_FirstItem');CSS.removeClass(items[i],'UIFilterList_LastItem');if(first){CSS.addClass(items[i],'UIFilterList_FirstItem');}
if(last){CSS.addClass(items[i],'UIFilterList_LastItem');}}}
UIMutableFilterList.prototype.setBoundingBox=function(bounding_box){this.bottomGroup.setBoundingBox(bounding_box);this.topGroup.setBoundingBox(bounding_box);}
UIMutableFilterList.prototype.getCurrentBoundingBox=function(){var items=this.controller.scry('div.UIFilterList_Item');var top_item_pos=Vector2.getElementCompassPoint(items[0],Vector2.compass.north);var bounding_top=top_item_pos.y;var bounding_left=0;if(this.bottomShown){var last_item=items.length-1;}else{var last_item=this.topGroup.getOrder().length-1;}
var bottom_item_pos=Vector2.getElementCompassPoint(items[last_item],Vector2.compass.south);var bounding_right=0;var bounding_bottom=bottom_item_pos.y;return new Rect(bounding_top,bounding_right,bounding_bottom,bounding_left,'document');}
UIMutableFilterList.prototype.showBottom=function(){this.hiddenContainer.setStyle('height','0px');this.hiddenContainer.removeClass('hidden_elem');animation(this.hiddenContainer).to('height','auto').from('opacity',0).to('opacity',1).ease(animation.ease.both).duration(200).ondone(function(){this.bottomShown=true;this.setBoundingBox(this.getCurrentBoundingBox());}.bind(this)).go();this.showLink.addClass('hidden_elem');this.hideLink.removeClass('hidden_elem');return false;}
UIMutableFilterList.prototype.hideBottom=function(){animation(this.hiddenContainer).to('height','0px').from('opacity',1).to('opacity',0).ease(animation.ease.both).duration(200).ondone(function(){this.bottomShown=false;this.setBoundingBox(this.getCurrentBoundingBox());this.hiddenContainer.addClass('hidden_elem');}.bind(this)).go();this.showLink.removeClass('hidden_elem');this.hideLink.addClass('hidden_elem');return false;}

function AsyncSignal(uri,data){this.data=data||{};this.uri=uri;this.handler=null;}
AsyncSignal.prototype.setHandler=function(h){this.handler=h;return this;}
AsyncSignal.prototype.send=function(){var h=this.handler,d=this.data,u=this.uri,s=[],i=new Image(),a=document.getElementById('post_form_id');d.asyncSignal=Math.floor(Math.random()*10000)+1;if(a){d.post_form_id=a.value;}
for(var k in d){s.push(encodeURIComponent(k)+'='+encodeURIComponent(d[k]));}
if(u.indexOf('?')==-1){u+='?';}
u+=s.join('&');if(h){i.onload=i.onerror=(function(i,h){return function(){h((i.height==1));}})(i,h);}
i.src=u;return this;}

function URI(uri){if(uri===window){Util.error('what the hell are you doing');return;}
if(this===window){return new URI(uri||window.location.href);}
this.parse(uri||'');}
copy_properties(URI,{getRequestURI:function(respect_page_transitions,suppress_warning){respect_page_transitions=respect_page_transitions===undefined||respect_page_transitions;if(respect_page_transitions&&window.PageTransitions&&PageTransitions.isInitialized()){return PageTransitions.getCurrentURI(!!suppress_warning).getQualifiedURI();}else{return new URI(window.location.href);}},getMostRecentURI:function(){if(window.PageTransitions&&PageTransitions.isInitialized()){return PageTransitions.getMostRecentURI().getQualifiedURI();}else{return new URI(window.location.href);}},expression:/(((\w+):\/\/)([^\/:]*)(:(\d+))?)?([^#?]*)(\?([^#]*))?(#(.*))?/,arrayQueryExpression:/^(\w+)((?:\[\w*\])+)=?(.*)/,explodeQuery:function(q){if(!q){return{};}
var result={};q=q.replace(/%5B/ig,'[').replace(/%5D/ig,']');q=q.split('&');for(var ii=0,length=q.length;ii<length;ii++){var match=q[ii].match(URI.arrayQueryExpression);if(!match){var term=q[ii].split('=');result[URI.decodeComponent(term[0])]=term[1]===undefined?null:URI.decodeComponent(term[1]);}else{var indices=match[2].split(/\]\[|\[|\]/).slice(0,-1);var name=match[1];var value=URI.decodeComponent(match[3]||'');indices[0]=name;var resultNode=result;for(var i=0;i<indices.length-1;i++){if(indices[i]){if(resultNode[indices[i]]===undefined){if(indices[i+1]&&!indices[i+1].match(/\d+$/)){resultNode[indices[i]]={};}else{resultNode[indices[i]]=[];}}
resultNode=resultNode[indices[i]];}else{if(indices[i+1]&&!indices[i+1].match(/\d+$/)){resultNode.push({});}else{resultNode.push([]);}
resultNode=resultNode[resultNode.length-1];}}
if(resultNode instanceof Array&&indices[indices.length-1]==''){resultNode.push(value);}else{resultNode[indices[indices.length-1]]=value;}}}
return result;},implodeQuery:function(obj,name,encode){name=name||'';if(encode===undefined){encode=true;}
var r=[];if(obj===null||obj===undefined){r.push(encode?URI.encodeComponent(name):name);}else if(obj instanceof Array){for(var ii=0;ii<obj.length;++ii){try{if(obj[ii]!==undefined){r.push(URI.implodeQuery(obj[ii],name?(name+'['+ii+']'):ii));}}catch(ignored){}}}else if(typeof(obj)=='object'){if(DOM.isNode(obj)){r.push('{node}');}else{for(var k in obj){try{if(obj[k]!==undefined){r.push(URI.implodeQuery(obj[k],name?(name+'['+k+']'):k));}}catch(ignored){}}}}else{if(encode){r.push(URI.encodeComponent(name)+'='+URI.encodeComponent(obj));}else{r.push(name+'='+obj);}}
return r.join('&');},encodeComponent:function(raw){var parts=String(raw).split(/([\[\]])/);for(var i=0,length=parts.length;i<length;i+=2){parts[i]=window.encodeURIComponent(parts[i]);}
return parts.join('');},decodeComponent:function(encoded_s){return window.decodeURIComponent(encoded_s.replace(/\+/g,' '));}});copy_properties(URI.prototype,{parse:function(uri){var m=uri.toString().match(URI.expression);copy_properties(this,{protocol:m[3]||'',domain:m[4]||'',port:m[6]||'',path:m[7]||'',query_s:m[9]||'',fragment:m[11]||''});return this;},setProtocol:function(p){this.protocol=p;return this;},getProtocol:function(){return this.protocol;},setQueryData:function(o){this.query_s=URI.implodeQuery(o);return this;},addQueryData:function(o){return this.setQueryData(copy_properties(this.getQueryData(),o));},removeQueryData:function(keys){if(!(keys instanceof Array)){keys=[keys];}
var query=this.getQueryData();for(var i=0,length=keys.length;i<length;++i){delete query[keys[i]];}
return this.setQueryData(query);},getQueryData:function(){return URI.explodeQuery(this.query_s);},setFragment:function(f){this.fragment=f;return this;},getFragment:function(){return this.fragment;},setDomain:function(d){this.domain=d;return this;},getDomain:function(){return this.domain;},setPort:function(p){this.port=p;return this;},getPort:function(){return this.port;},setPath:function(p){this.path=p;return this;},getPath:function(){return this.path.replace(/^\/+/,'/');},toString:function(){var r='';this.protocol&&(r+=this.protocol+'://');this.domain&&(r+=this.domain);this.port&&(r+=':'+this.port);if(this.domain&&!this.path){r+='/';}
this.path&&(r+=this.path);this.query_s&&(r+='?'+this.query_s);this.fragment&&(r+='#'+this.fragment);return r;},valueOf:function(){return this.toString();},isFacebookURI:function(){if(!URI._facebookURIRegex){URI._facebookURIRegex=new RegExp('(^|\.)facebook\.('+env_get('tlds').join('|')+')([^.]*)$','i');}
return!this.domain||URI._facebookURIRegex.test(this.domain);},isQuicklingEnabled:function(){return window.Quickling&&Quickling.isActive()&&Quickling.isPageActive(this);},getRegisteredDomain:function(){if(!this.domain){return'';}
if(!this.isFacebookURI()){return null;}
var parts=this.domain.split('.');var index=parts.indexOf('facebook');return parts.slice(index).join('.');},getTld:function(true_tld){if(!this.domain){return'';}
var parts=this.domain.split('.');var tld=parts[parts.length-1];if(true_tld){return tld;}
var launched_tlds=env_get('tlds');if(launched_tlds.indexOf(tld)==-1){for(var i=0;i<launched_tlds.length;++i){var launched_tld=launched_tlds[i];if(new RegExp(launched_tld+'$').test(this.domain)){tld=launched_tld;break;}}}
return tld;},getUnqualifiedURI:function(){return new URI(this).setProtocol(null).setDomain(null).setPort(null);},getQualifiedURI:function(){var uri=new URI(this);if(!uri.getDomain()){var current=URI();uri.setProtocol(current.getProtocol()).setDomain(current.getDomain()).setPort(current.getPort());}
return uri;},isSameOrigin:function(asThisURI){var uri=asThisURI||window.location.href;if(!(uri instanceof URI)){uri=new URI(uri.toString());}
if(this.getProtocol()&&this.getProtocol()!=uri.getProtocol()){return false;}
if(this.getDomain()&&this.getDomain()!=uri.getDomain()){return false;}
return true;},coerceToSameOrigin:function(targetURI){var uri=targetURI||window.location.href;if(!(uri instanceof URI)){uri=new URI(uri.toString());}
if(this.isSameOrigin(uri)){return true;}
if(this.getProtocol()!=uri.getProtocol()){return false;}
var dst=uri.getDomain().split('.');var src=this.getDomain().split('.');var dst_part;if(uri.isFacebookURI()){while((dst_part=dst.pop())&&dst_part==src.pop()){if(dst_part=='facebook'){this.setDomain(uri.getDomain());return true;}}}
return false;},go:function(){goURI(this);},setSubdomain:function(subdomain){var uri=new URI(this).getQualifiedURI();var domains=uri.getDomain().split('.');if(domains.length<=2){domains.unshift(subdomain);}else{domains[0]=subdomain;}
return uri.setDomain(domains.join('.'));},getSubdomain:function(){if(!this.getDomain()){return'';}
var domains=this.getDomain().split('.');if(domains.length<=2){return'';}else{return domains[0];}}});

function _ElementController(tag_name,event_name){copy_properties(this,{_controlled_tag_name:tag_name,_controlled_event_name:event_name,_handlers:[],_fallback_handlers:[]});var controller=this;this._onevent=function(e){return controller._handle.bind(controller)(this,$E(e));};}
copy_properties(_ElementController.prototype,{ALL:1,ALL_TARGETS:2,ALL_KEY_MODIFIERS:4,_ALL_UNUSED_1:8,_ALL_UNUSED_2:16,registerHandler:function(callback,filters,prepend){this._registerHandler(this._handlers,callback,filters,prepend);},registerFallbackHandler:function(callback,filters,prepend){this._registerHandler(this._fallback_handlers,callback,filters,prepend);},bindAll:function(root_element){if(!root_element||root_element.nodeType!=DOM.NODE_TYPES.ELEMENT){return;}
var tabconsole=ge('tabconsole');if(tabconsole){if((root_element.id&&root_element.id.substring(0,8)=='cacheobs')||DOM.contains(tabconsole,root_element)){return;}}
var should_insert=ua.firefox()&&!DOM.contains(document.documentElement,root_element);if(should_insert){var invisible_div=ge('an_invisible_div');if(!invisible_div){invisible_div=DOM.create('div',{id:'an_invisible_div'});invisible_div.style.display='none';DOMScroll.getScrollRoot().appendChild(invisible_div);}
invisible_div.appendChild(root_element);}
var element,event_name=this._controlled_event_name.substring(2),onevent=this._onevent,elements=root_element.getElementsByTagName(this._controlled_tag_name);try{for(var i=elements.length-1;i>=0;--i){element=elements[i];Event.listen(element,event_name,onevent,Event.Priority.LINK_CONTROLLER);}
if(DOM.isNode(root_element,this._controlled_tag_name)){Event.listen(root_element,event_name,onevent,Event.Priority.LINK_CONTROLLER);}}catch(ex){Util.error('Uncaught exception while reading %s handler for element with contents %h: %s',event_name,element.innerHTML,ex);}
if(should_insert){invisible_div.removeChild(root_element);}},_handle:function(element,event){var handlers=this.getHandlers();for(var i=0;i<handlers.length;++i){var callback=handlers[i].callback;var filters=handlers[i].filters;try{if(this._filter(filters,element,event)){var abort=callback(element,event);if(abort===false){return Event.kill(event);}}}catch(exception){Util.error('Uncaught exception in %s handler: %x',this._controlled_event_name,exception);}}},getHandlers:function(){return this._handlers.concat(this._fallback_handlers);},_init:function(){if(this._initialized){return;}
this._initialized=true;onloadRegister(function(){this.bindAll(document.body);Arbiter.subscribe('DOM.contentAdded',function(type,data){for(var ii=0;ii<data.length;ii++){this.bindAll(data[ii]);}}.bind(this),Arbiter.SUBSCRIBE_NEW);}.bind(this));},_registerHandler:function(handler_array,callback,filters,prepend){this._init();var args={callback:callback,filters:filters||0};if(prepend){handler_array.unshift(args);}else{handler_array.push(args);}},_filter:function(filters,element,event){if(filters&this.ALL){return true;}
if(!(filters&this.ALL_TARGETS)){if(element.target){return false;}}
if(!(filters&this.ALL_KEY_MODIFIERS)){if(event&&$E(event).getModifiers().any){return false;}}
return true;}});var LinkController=new _ElementController('a','onclick');copy_properties(LinkController,{ALL_PROTOCOLS:LinkController._ALL_UNUSED_1,ALL_BUTTONS:LinkController._ALL_UNUSED_2,_filter:function(filters,element,event){if(!_ElementController.prototype._filter.apply(this,arguments)){return false;}
var href=element.getAttribute('href');if(!href||href=='#'){return false;}
if(!(filters&this.ALL_PROTOCOLS)){if(!LinkController.usesWebProtocol(element)){return false;}}
if(!(filters&this.ALL_BUTTONS)){if(ua.safari()>=525&&event&&event.which!=1){return false;}}
return true;},getProtocol:function(link){var href,protocol;return(href=link.getAttribute('href'))&&(protocol=href.match(/^(\w+):/))&&protocol[1].toLowerCase();},usesWebProtocol:function(link){var protocol=LinkController.getProtocol(link);return!protocol||protocol=='http'||protocol=='https';}});var FormController=new _ElementController('form','onsubmit');

function Nectar(){}
copy_properties(Nectar,{linkHandler:function(ret_val,link){var nctr_params=Nectar.getNectarParams();nctr_params['ia']=true;nctr_params['url']=link.href;var uri='/ajax/nectar.php'+'?'
+URI.implodeQuery({'nctr':nctr_params})+'&';new AsyncSignal(uri,{}).send();return ret_val;},getNectarParams:function(){var nctr_params={};var impid=env_get('nctrlid');if(impid){nctr_params['id']=impid;}
var navimpid=env_get('nctrlnid');if(navimpid){nctr_params['nid']=navimpid;}
if(impid||navimpid){nctr_params['ct']=(new Date()).getTime();}
return nctr_params;}});if(URI().getSubdomain()!='apps'){onafterloadRegister(function(){LinkController.registerFallbackHandler(bind(null,Nectar.linkHandler,true),LinkController.ALL_TARGETS|LinkController.ALL_KEY_MODIFIERS);});}

function AsyncRequest(uri){var dispatchResponse=bind(this,function(asyncResponse){if(!this._asyncResponse){this._asyncResponse=asyncResponse;}
try{this.clearStatusIndicator();if(this.initialHandler(asyncResponse)!==false){if(this.handler){try{this.handler(asyncResponse);}catch(exception){this.finallyHandler(asyncResponse);throw exception;}}
this.finallyHandler(asyncResponse);if(asyncResponse.instrument){Env.t_domcontent=(new Date()).getTime();Env.t_layout=Env.t_domcontent;var force_layout=document&&DOMScroll.getScrollRoot()&&DOMScroll.getScrollRoot().offsetWidth;Env.t_onload=(new Date()).getTime();Env.t_willonloadhooks=Env.t_onload;}
var onload=asyncResponse.onload;if(onload){for(var ii=0;ii<onload.length;ii++){try{eval('(function() {'+onload[ii]+'})();');}catch(exception){Util.error('An onload hook in response to a request to to URI %q threw an '+'exception: %x. (This is not a problem with AsyncRequest, it is '+'a problem with the registered hook.)',this.getURI(),exception);}}}
if(asyncResponse.instrument){Env.t_doneonloadhooks=(new Date()).getTime();}
var onafterload=asyncResponse.onafterload;if(onafterload){for(var ii=0;ii<onafterload.length;ii++){try{eval('(function() {'+onafterload[ii]+'})();');}catch(exception){Util.error('An onafterload hook in response to a request to to URI %q threw an '+'exception: %x. (This is not a problem with AsyncRequest, it is '+'a problem with the registered hook.)',this.getURI(),exception);}}}
var invalidate_cache=asyncResponse.invalidate_cache;if(invalidate_cache&&invalidate_cache.length){Arbiter.inform(Arbiter.PAGECACHE_INVALIDATE,invalidate_cache);}}
if(asyncResponse.cacheObservation&&typeof(TabConsoleCacheobserver)!='undefined'&&TabConsoleCacheobserver.instance){TabConsoleCacheobserver.getInstance().addAsyncObservation(asyncResponse.cacheObservation);}}catch(exception){Util.error('The user supplied handler function for an AsyncRequest to URI %q '+'threw an exception: %x. (This is not a problem with AsyncRequest, it '+'is a problem with the callback, which failed to catch the exception.)',this.getURI(),exception);}});var replayResponse=bind(this,function(){if(!this._asyncResponse){Util.warn('Unable to replay AsyncResponse for an AsyncRequest to '+this.getURI());return;}
Util.log('replaying the response for '+this.getURI());this._asyncResponse.setReplay(true);dispatchResponse(this._asyncResponse);});var dispatchErrorResponse=bind(this,function(asyncResponse,isTransport){try{this.clearStatusIndicator();var async_error=asyncResponse.getError();if(async_error==kError_Async_InternalCaptchaRequired){this._captchaHtml=asyncResponse.getPayload().captcha_html;this._displayCaptcha();}else if(async_error==kError_Async_ConfirmationRequired){var payload=asyncResponse.getPayload();this.requireConfirmation(payload.confirmation_message,payload.confirmation_title,payload.confirmation_button);this._displayConfirmation();}else if(this.initialHandler(asyncResponse)!==false){try{if(isTransport){this.transportErrorHandler(asyncResponse);}else{this.errorHandler(asyncResponse);}}catch(exception){this.finallyHandler(asyncResponse);throw exception;}
this.finallyHandler(asyncResponse);}}catch(exception){Util.error('Async error handler threw an exception for URI %q, when processing a '+'%d error: %x.',this.getURI(),asyncResponse.getError(),exception);}});var _interpretTransportResponse=bind(this,function(){if(this.getOption('suppressEvaluation')){var r=new AsyncResponse();r.payload=this.transport;return{asyncResponse:r};}
var shield="for (;;);";var shieldlen=shield.length;if(this.transport.responseText.length<=shieldlen){var kind=this.transport.responseText.length?('a '+this.transport.responseText.length+' byte'):'an empty';return{transportError:sprintf('An error occurred when making an AsyncRequest to %q. '+'The server returned '+kind+' response.',this.getURI())};}
var text=this.transport.responseText;var offset=0;while(text.charAt(offset)==" "||text.charAt(offset)=="\n"){offset++;}
if(offset&&text.substring(offset,offset+shieldlen)==shield){Util.error('Response for request to endpoint %q seems to be valid, but was '+'preceeded by whitespace. (This probably means that someone '+'committed whitespace in a header file.)',this.getURI());}
var safeResponse=text.substring(offset+shieldlen);var response;try{eval('response = ('+safeResponse+')');}catch(exception){return{transportError:sprintf('Evaluation failed for <a href="javascript:aiert(%e);">'+'response from %q</a>: %x.',this.transport.responseText,this.getURI(),exception)};}
return interpretResponse(response);});var interpretResponse=bind(this,function(response){if(response.redirect){return{redirect:response.redirect};}
var r=new AsyncResponse();if(typeof(response.payload)=='undefined'||typeof(response.error)=='undefined'||typeof(response.errorDescription)=='undefined'||typeof(response.errorSummary)=='undefined'||typeof(response.errorIsWarning)=='undefined'){Util.warn('AsyncRequest to endpoint %q returned a JSON response, but it '+'is not properly formatted. The endpoint needs to provide a '+'response including both error and payload information; use '+'the AsyncResponse PHP class to do this easily.',this.getURI());r.payload=response;}else{copy_properties(r,response);}
return{asyncResponse:r};});var invokeResponseHandler=bind(this,function(interp){if(typeof(interp.redirect)!='undefined'){(function(){this.setURI(interp.redirect).send();}).bind(this).defer();return;}
if(this.handler||this.errorHandler||this.transportErrorHandler){if(typeof(interp.transportError)!='undefined'){var r=new AsyncResponse();var errorDescription=Util.isDevelopmentEnvironment()?interp.transportError:_tx("Something went wrong. We're working on getting this fixed as soon as we can. You may be able to try again.");copy_properties(r,{error:1000,errorSummary:_tx("Oops"),errorDescription:errorDescription});if(this.transportErrorHandler){dispatchErrorResponse(r,true);}else{Util.error('Something bad happened; provide a transport error handler for '+'complete details.');}
return;}
var r=interp.asyncResponse;document.cookie="cvr_tx=;"
+" expires=Mon, 26 Jul 1997 05:00:00 GMT;"
+" path=/;"
+" domain=.facebook.com";if(r.instrument){if(window.___t_measuring){r.instrument=false;}else{window.___t_arrival=(new Date()).getTime();window.___t_measuring=true;window.Env=window.Env||{};Env.start=(new Date()).getTime();cavalry_measure=[];}}
if(r.instrument){___tcss=0;___thtml=0;___tjs=(new Date()).getTime()-Env.start;}
if(r.getError()&&!r.getErrorIsWarning()){var fn=dispatchErrorResponse;}else{var fn=dispatchResponse;}
fn=fn.shield(null,r);fn=fn.defer.bind(fn);if(r.bootload){var is_transitional=false;if(this.preBootloadHandler){is_transitional=this.preBootloadHandler(r);}
Bootloader.loadResources(r.bootload,fn,is_transitional);}else{fn();}}});var invokeErrorHandler=bind(this,function(explicitError){try{if(!window.loaded){return;}}catch(ex){return;}
var r=new AsyncResponse();var err;try{err=explicitError||this.transport.status||1001;}catch(ex){err=1001;}
try{if(this.responseText==''){err=1002;}}catch(ignore){}
if(this.transportErrorHandler){var desc=sprintf('Transport error (#%d) while retrieving data from endpoint %q: %s',err,this.getURI(),AsyncRequest.getHTTPErrorDescription(err));if(!this.getOption('suppressErrorAlerts')){Util.error(desc);}
copy_properties(r,{error:err,errorSummary:AsyncRequest.getHTTPErrorSummary(err),errorDescription:desc});dispatchErrorResponse(r,true);}else{Util.error('Async request to %q failed with a %d error, but there was no error '+'handler available to deal with it.',this.getURI(),err);}});var handleResponse=function(response){var asyncResponse=this.interpretResponse(response);this.invokeResponseHandler(asyncResponse);}
var onStateChange=function(){try{if(this.transport.readyState==4){if(this.transport.status>=200&&this.transport.status<300){invokeResponseHandler(_interpretTransportResponse());}else{if(ua.safari()&&(typeof(this.transport.status)=='undefined')){invokeErrorHandler(1002);}else{invokeErrorHandler();}}
if(this.getOption('asynchronous')!==false){delete this.transport;}}}catch(exception){try{if(!window.loaded){return;}}catch(ex){return;}
delete this.transport;if(this.remainingRetries){--this.remainingRetries;this.send(true);}else{if(!this.getOption('suppressErrorAlerts')){Util.error('AsyncRequest exception when attempting to handle a state change: %x.',exception);}
invokeErrorHandler(1001);}}};copy_properties(this,{onstatechange:onStateChange,replayResponse:replayResponse,invokeResponseHandler:invokeResponseHandler,interpretResponse:interpretResponse,handleResponse:handleResponse,transport:null,method:'POST',uri:'',initialHandler:bagofholding,handler:null,errorHandler:null,transportErrorHandler:null,finallyHandler:bagofholding,statusElement:null,logNectar:true,data:{},context:{},readOnly:false,writeRequiredParams:['post_form_id'],remainingRetries:0,option:{asynchronous:true,suppressErrorHandlerWarning:false,suppressEvaluation:false,suppressErrorAlerts:false,retries:1,jsonp:false,bundle:false,useIframeTransport:false},_captchaHtml:'',_confirmationMessage:'',_confirmationTitle:'',_confirmationButton:'',_confirmationCallback:bagofholding,_requiresConfirmation:false,_replayable:undefined,_replayKey:''});if(typeof ErrorDialog!="undefined"){this.errorHandler=ErrorDialog.showAsyncError;this.transportErrorHandler=ErrorDialog.showAsyncError;}
if(uri!=undefined){this.setURI(uri);}
return this;}
copy_properties(AsyncRequest,{getHTTPErrorSummary:function(errCode){return AsyncRequest._getHTTPError(errCode).summary;},getHTTPErrorDescription:function(errCode){return AsyncRequest._getHTTPError(errCode).description;},pingURI:function(uri,data,synchronous){data=data||{};return new AsyncRequest().setURI(uri).setData(data).setOption('asynchronous',!synchronous).setOption('suppressErrorHandlerWarning',true).setErrorHandler(bagofholding).setTransportErrorHandler(bagofholding).send();},receiveJSONPResponse:function(path,data){if(this._JSONPReceivers[path]){for(var ii=0;ii<this._JSONPReceivers[path].length;ii++){var request=this._JSONPReceivers[path][ii];if(request.transportIframe){(function(x){DOMScroll.getScrollRoot().removeChild(x);}).bind(null,request.transportIframe).defer();}
request.invokeResponseHandler(request.interpretResponse(data));}
delete this._JSONPReceivers[path];}},_hasBundledRequest:function(){return!is_empty(AsyncRequest._allBundledRequests);},stashBundledRequest:function(){var ret=AsyncRequest._allBundledRequests;AsyncRequest._allBundledRequests={};return ret;},setBundledRequestProperties:function(properties){if(properties.stashedRequests){copy_properties(AsyncRequest._allBundledRequests,properties.stashedRequests);}
if(!AsyncRequest._hasBundledRequest()){var callback=properties.callback;callback&&callback();}else{copy_properties(AsyncRequest._bundledRequestProperties,properties);if(properties.start_immediately){AsyncRequest._sendBundledRequests();}}},_bundleRequest:function(request){if(request.getOption('jsonp')||request.getOption('useIframeTransport')){Util.error('You cannot bundle AsyncRequest that uses jsonp or iframe transport.');request.setOption('bundle',false);return false;}else if(!request.uri.isFacebookURI()){Util.error('You can not bundle AsyncRequest sent to non-facebook URIs');request.setOption('bundle',false);return false;}else if(!request.getOption('asynchronous')){Util.error('We cannot bundle synchronous AsyncRequests');request.setOption('bundle',false);return false;}
var path=request.uri.getPath();if(path in AsyncRequest._allBundledRequests){Util.warn('Bundling multiple AsyncRequests to the same endpoint is not '+'supported. They will still be sent seqentially. Only the last '+'AsyncRequest to a unique endpoint is included in the bundle.');var old_request=AsyncRequest._allBundledRequests[path];old_request.setOption('bundle',false).send();}
if(is_empty(AsyncRequest._allBundledRequests)){AsyncRequest._bundleTimer=setTimeout(function(){AsyncRequest._sendBundledRequests();},0);}
AsyncRequest._allBundledRequests[path]=request;return true;},_sendBundledRequests:function(){clearTimeout(AsyncRequest._bundleTimer);AsyncRequest._bundleTimer=null;var bundled_requests=AsyncRequest._allBundledRequests;AsyncRequest._allBundledRequests={};var property={};copy_properties(property,AsyncRequest._bundledRequestProperties);AsyncRequest._bundledRequestProperties={};var on_done=function(){property.callback&&property.callback();};if(is_empty(bundled_requests)){on_done();return;}
var data={};for(var path in bundled_requests){var request=bundled_requests[path];data[path]=URI.implodeQuery(request.data);}
var query_data={data:data}
if(property.extra_data){copy_properties(query_data,property.extra_data);}
new AsyncRequest().setURI('/ajax/proxy.php').setData(query_data).setMethod('POST').setInitialHandler(property.onInitialResponse||truth).setHandler(function(r){var payload=r.getPayload();var responses=payload.responses;for(var path in bundled_requests){var request=bundled_requests[path];if(path in responses){var asyncResponse=request.interpretResponse(responses[path]);request.invokeResponseHandler(asyncResponse);}else{var response={transportError:sprintf('An error occurred when making an AsyncRequest to %q '+' in a bundled request.',path)};request.invokeResponseHandler(response);}}}).setTransportErrorHandler(function(response){var paths=[];var interp={transportError:response.errorDescription};for(var path in bundled_requests){paths.push(path);var request=bundled_requests[path];request.invokeResponseHandler(interp);}
Util.error('Transport error occured for bundled requests to '+
paths.join(', '));}).setFinallyHandler(function(r){on_done();}).send()},_getHTTPError:function(errCode){var e=AsyncRequest._HTTPErrors[errCode]||AsyncRequest._HTTPErrors[errCode-(errCode%100)]||{summary:'HTTP Error',description:'Unknown HTTP error #'+errCode};return e;},_HTTPErrors:{400:{summary:'Bad Request',description:'Bad HTTP request.'},401:{summary:'Unauthorized',description:'Not authorized.'},403:{summary:'Forbidden',description:'Access forbidden.'},404:{summary:'Not Found',description:'Web address does not exist.'},1000:{summary:'Bad Response',description:'Invalid response.'},1001:{summary:'No Network',description:'A network error occurred. Check that you are connected to the '+'internet.'},1002:{summary:'No Data',description:'The server did not return a response.'},1003:{summary:'Eval Error',description:'Exception thrown during JSON evaluation.'}},_JSONPReceivers:[],_allBundledRequests:{},_bundledRequestProperties:{},_bundleTimer:null});copy_properties(AsyncRequest.prototype,{setMethod:function(m){this.method=m.toString().toUpperCase();return this;},getMethod:function(){return this.method;},setData:function(obj){this.data=obj;return this;},getData:function(){return this.data;},setContextData:function(key,value,enabled){enabled=enabled===undefined?true:enabled;if(enabled){this.context['_log_'+key]=value;}
return this;},setURI:function(uri){var uri_obj=URI(uri);if(this.getOption('useIframeTransport')&&!uri_obj.isFacebookURI()){Util.error('IframeTransport requests should only be used when going between '+'different Facebook subdomains.  This probably won\'t do what you want '+'if you\'re going to a non-Facebook URI.  Check out JSONP for that, '+'but that\'s also a bad idea to use.');return this;}
if(!this.getOption('jsonp')&&!this.getOption('useIframeTransport')&&!uri_obj.isSameOrigin()){Util.error('Asynchronous requests must specify relative URIs (like %q); this '+'ensures they conform to the Same Origin Policy (see %q). The '+'provided absolute URI (%q) is invalid, use a relative URI instead. '+'If you need to dispatch cross-domain requests, you can use JSONP, '+'but consider this decision carefully because there are tradeoffs and '+'JSONP is completely insecure.','/path/to/endpoint.php','http://www.mozilla.org/projects/security/components/same-origin.html',uri_obj.toString());return this;}
this.uri=uri_obj;return this;},getURI:function(){return this.uri.toString();},setInitialHandler:function(fn){this.initialHandler=fn;return this;},setHandler:function(fn){if(typeof(fn)!='function'){Util.error('AsyncRequest response handlers must be functions. Pass a function, '+'or use bind() to build one.');}else{this.handler=fn;}
return this;},getHandler:function(){return this.handler;},setErrorHandler:function(fn){if(typeof(fn)!='function'){Util.error('AsyncRequest error handlers must be functions. Pass a function, or '+'use bind() to build one.');}else{this.errorHandler=fn;}
return this;},setTransportErrorHandler:function(fn){this.transportErrorHandler=fn;return this;},getErrorHandler:function(){return this.errorHandler;},getTransportErrorHandler:function(){return this.transportErrorHandler;},setFinallyHandler:function(fn){this.finallyHandler=fn;return this;},setPreBootloadHandler:function(fn){this.preBootloadHandler=fn;return this;},disableNectar:function(){this.logNectar=false;return this;},setReadOnly:function(readOnly){if(typeof(readOnly)!='boolean'){Util.error('AsyncRequest readOnly value must be a boolean.');}else{this.readOnly=readOnly;}
return this;},setFBMLForm:function(){this.writeRequiredParams=["fb_sig"];return this;},getReadOnly:function(){return this.readOnly;},setStatusElement:function(element){this.statusElement=element;return this;},getStatusElement:function(){return this.statusElement;},clearStatusIndicator:function(){if(this.getStatusElement()){CSS.removeClass($(this.getStatusElement()),'async_saving');}},addStatusIndicator:function(){if(this.getStatusElement()){CSS.addClass($(this.getStatusElement()),'async_saving');}},specifiesWriteRequiredParams:function(){return this.writeRequiredParams.every(function(param){this.data[param]=this.data[param]||Env[param]||(ge(param)||{}).value;if(this.data[param]!==undefined){return true;}},this);},setReplayable:function(replayable,key){this._replayable=replayable;this._replayKey=key||'';return this;},setOption:function(opt,v){if(typeof(this.option[opt])!='undefined'){this.option[opt]=v;}else{Util.warn('AsyncRequest option %q does not exist; request to set it was ignored.',opt);}
return this;},getOption:function(opt){if(typeof(this.option[opt])=='undefined'){Util.warn('AsyncRequest option %q does not exist, get request failed.',opt);}
return this.option[opt];},abort:function(){if(this.transport){var old_handler=this.getTransportErrorHandler();this.setTransportErrorHandler(bagofholding);this.transport.abort();this.setTransportErrorHandler(old_handler);}},addNectarParams:function(){var nctr_params;if(!this.logNectar){nctr_params={};nctr_params['n']=true;}else{nctr_params=Nectar.getNectarParams();var nctr_ia=this.data['_log_nectar_isaction'];if(nctr_ia!==undefined){nctr_params['ia']=nctr_ia;delete this.data['_log_nectar_isaction'];}}
this.data['nctr']=nctr_params;},send:function(isRetry){isRetry=isRetry||false;if(this.requiresConfirmation()){this._displayConfirmation();return true;}
if(!this.uri){Util.error('Attempt to dispatch an AsyncRequest without an endpoint URI! This is '+'all sorts of silly and impossible, so the request failed.');return false;}
if(!this.errorHandler&&!this.getOption('suppressErrorHandlerWarning')){Util.warn('Dispatching an AsyncRequest that does not have an error handler. '+'You SHOULD supply one, or use AsyncRequest.pingURI(). If this '+'omission is intentional and well-considered, set the %q option to '+'suppress this warning.','suppressErrorHandlerWarning');}
if(this.getOption('jsonp')&&this.method!='GET'){this.setMethod('GET');}
if(this.getOption('useIframeTransport')&&this.method!='GET'){Util.warn('Iframe transport currently works only with GET.');this.setMethod('GET');}
if(!this.getReadOnly()){if(!this.specifiesWriteRequiredParams()){Util.error('You are making a POST request to %s without one or more of the '+'required parameters: %s. Requests which modify data and do not '+'verify the request origin through parameter validation are '+'vulnerable to CSRF attacks. You should either specify values for '+'these parameters explicitly by using setData(), put them in the '+'page as inputs, or mark this request as safe and idempotent by '+'using setReadOnly(). Consult the setReadOnly() documentation for '+'more information.',this.uri.toString(),this.writeRequiredParams.join(','));return false;}
if(this.method!='POST'){Util.error('You are making a GET request which modifies data; this violates '+'the HTTP spec and is generally a bad idea. Either change this '+'request to use POST or use setReadOnly() to mark the request as '+'idempotent and appropriate for HTTP GET. Consult the setReadOnly() '+'documentation for more information.');return false;}}
if(this.method=='POST'){this.data.fb_dtsg=Env.fb_dtsg;}
if((!this.getReadOnly()&&this._replayable!==false)||this._replayable){Arbiter.inform(Arbiter.REPLAYABLE_AJAX,this);}
if(!is_empty(this.context)){copy_properties(this.data,this.context);this.data['ajax_log']=1;}
if(!this.getReadOnly()&&this.method=='POST'&&this.data['post_form_id_source']===undefined){this.data['post_form_id_source']='AsyncRequest';}
if(this.getOption('bundle')&&env_get('ajax_bundle')&&AsyncRequest._bundleRequest(this)){return true;}
this.addNectarParams();var uri_str,query;if(this.method=='GET'){uri_str=this.uri.addQueryData(this.data).toString();query='';}else{uri_str=this.uri.toString();query=URI.implodeQuery(this.data);}
if(this.getOption('jsonp')||this.getOption('useIframeTransport')){var path=this.uri.getPath();if(!AsyncRequest._JSONPReceivers[path]){AsyncRequest._JSONPReceivers[path]=[];}
AsyncRequest._JSONPReceivers[path].push(this);if(this.getOption('jsonp')){(function(){DOMScroll.getScrollRoot().appendChild($N('script',{src:uri_str,type:"text/javascript"}))}).bind(this).defer();}else{var style={position:'absolute',top:'-1000px',left:'-1000px',width:'80px',height:'80px'};this.transportIframe=$N('iframe',{src:uri_str,style:style});DOMScroll.getScrollRoot().appendChild(this.transportIframe);}
return true;}
if(this.transport){Util.error('You must wait for an AsyncRequest to complete before sending another '+'request with the same object. To send two simultaneous requests, '+'create a second AsyncRequest object.');return false;}
var transport=null;try{transport=new XMLHttpRequest();}catch(ignored){};if(!transport){try{transport=new ActiveXObject("Msxml2.XMLHTTP");}catch(ignored){};}
if(!transport){try{transport=new ActiveXObject("Microsoft.XMLHTTP");}catch(ignored){};}
if(!transport){Util.error('Unable to build XMLHTTPRequest transport.');return false;}
transport.onreadystatechange=bind(this,'onstatechange');if(!isRetry){this.remainingRetries=0;if(this.getReadOnly()){this.remainingRetries=this.getOption('retries');}}
this.transport=transport;try{this.transport.open(this.method,uri_str,this.getOption('asynchronous'));}catch(ex){Util.error('Exception when opening Async transport to %q: %x',uri,ex);return false;}
var svn_rev=env_get('svn_rev');if(svn_rev){this.transport.setRequestHeader('X-SVN-Rev',String(svn_rev));}
if(this.method=='POST'){this.transport.setRequestHeader('Content-Type','application/x-www-form-urlencoded');}
this.addStatusIndicator();this.transport.send(query);return true;},_displayCaptcha:function(){Dialog.createCaptchaDialog(this._captchaHtml,this.finallyHandler).setHandler(this._displayCaptchaDialogHandler.bind(this)).show();},_displayCaptchaDialogHandler:function(){var captcha_data=serialize_form($('captcha'));copy_properties(this.data,captcha_data);this.send();},requireConfirmation:function(message,title,button,callback){this._confirmationMessage=message;this._confirmationTitle=title;this._confirmationButton=button;this._confirmationCallback=callback||bagofholding;this._requiresConfirmation=true;return this;},requiresConfirmation:function(){if(this._requiresConfirmation){if(this.data.confirmed){this._requriesConfirmation=false;}}
return this._requiresConfirmation;},_displayConfirmation:function(){var message=this._confirmationMessage||_tx("Are you sure you want to perform this action?");var html='<div class="confirmation_message">'
+HTML(message)
+'</div>';var title=this._confirmationTitle||_tx("Confirmation Required");var button=this._confirmationButton||Dialog.CONFIRM;Dialog.createConfirmationDialog(html,title,button,this.finallyHandler.bind(this)).setHandler(this._displayConfirmationHandler.bind(this)).setCancelHandler(this._confirmationCallback.curry(false)).show();},_displayConfirmationHandler:function(){this.data.confirmed=1;this._requiresConfirmation=false;this._confirmationCallback(true);this.send();}});function AsyncResponse(payload){copy_properties(this,{error:0,errorSummary:null,errorDescription:null,onload:null,replay:false,payload:payload||null});return this;}
copy_properties(AsyncResponse.prototype,{getPayload:function(){return this.payload;},getError:function(){return this.error;},getErrorSummary:function(){return this.errorSummary;},getErrorDescription:function(){return this.errorDescription;},getErrorIsWarning:function(){return this.errorIsWarning;},setReplay:function(replay){replay=(replay===undefined?true:replay);this.replay=!!replay;return this;},isReplay:function(){return this.replay;}});

function intl_set_xmode(xmode){(new AsyncRequest()).setURI('/ajax/intl/save_xmode.php').setData({xmode:xmode}).setHandler(function(){document.location.reload();}).send();}
function intl_set_cmode(cmode){(new AsyncRequest()).setURI('/ajax/intl/save_xmode.php').setData({cmode:cmode}).setHandler(function(){document.location.reload();}).send();}
function intl_set_vmode(vmode){(new AsyncRequest()).setURI('/ajax/intl/save_xmode.php').setData({vmode:vmode}).setHandler(function(){document.location.reload();}).send();}
function intl_set_amode(amode){(new AsyncRequest()).setURI('/ajax/intl/save_xmode.php').setData({amode:amode,app:false}).setHandler(function(){document.location.reload();}).send();}
function intl_set_pmode(pmode){CSS.toggleClass($('translations_nub'),'pnub');if(pmode==0){CSS.addClass($('progress_check'),'progress_hidden');CSS.removeClass($('progress_check'),'progress_shown');}else{CSS.addClass($('progress_check'),'progress_shown');CSS.removeClass($('progress_check'),'progress_hidden');}
(new AsyncRequest()).setURI('/ajax/intl/save_xmode.php').setData({pmode:pmode}).setHandler(function(){}).send();}
function intl_set_locale(obj,source,locale){if(!locale){var locale=obj.options[obj.selectedIndex].value;}
new AsyncRequest().setURI('/ajax/intl/beta_locale_check.php').setData({locale:locale}).setHandler(function(response){data=response.getPayload();if(data.rtl_unsupported){if(data.app_is_installed){new Dialog().setTitle('Limited Support For This Language').setBody('Although you can browse Facebook using this language, translation for this language '+'is only supported for Safari 3, Firefox 3 and Opera browsers for now. Please switch to one of those '+'browsers to translate Facebook to help us launch this language sooner! ').setButtons([Dialog.OK]).setHandler(intl_save_locale.bind(null,locale,true,null,source)).show();}}else if(data.locale_is_beta){if(data.app_is_installed){intl_save_locale(locale,true,null,source);}else{var async=new AsyncRequest().setURI('/ajax/intl/beta_locale_dialog.php?locale='+locale);new Dialog().setAsync(async).show();}}else{intl_save_locale(locale,true,null,source);}}).send();}
function intl_save_locale(locale,reload,location,source){new AsyncRequest().setURI('/ajax/intl/save_locale.php').setData({locale:locale,source:source}).setHandler(function(response){if(reload){document.location.reload();}else{document.location=location;}}).send();}
function intl_toggle_beta_locale_install(obj){if(obj.checked){show($('beta_locale_install'));}else{hide($('beta_locale_install'));}}
function intl_set_cookie_locale(locale,uri){var old_locale=getCookie('locale');new AsyncRequest().setURI('/ajax/intl/save_locale_cookie_logging.php').setData({new_locale:locale,old_locale:old_locale,source:'LOGGED_OUT'}).setReadOnly(true).send();setCookie('locale',locale,7*24*3600000);if(URI.getRequestURI().getTld()!='com'){transferCookieToComTld('locale',function(success){if(success){clearCookie('locale');}
goURI(uri);});}else{goURI(uri);}}
function intl_disable_rooster_save(obj){var save=document.getElementById('install_translation_app');save.disabled=!obj.checked;var container=document.getElementById('install_container');if(obj.checked){container.style.display='block';}else{container.style.display='none';}}
function intl_confirm_rooster_and_install_app(uid,divid){document.location='add.php?api_key=efa7a7045708fcadede8d705e39b1642';}
function intl_locale_is_rtl(){var body=DOM.find(document,'body');return('rtl'==CSS.getStyle(body,'direction'));}
function intl_is_left_click(e){if(e.which==null){if(e.button<2)return true;}else{if(e.which<2)return true;}
return false;}
function intl_left_click_cancelBubble(e){if(intl_is_left_click(e)){e.cancelBubble=true;}}

function animation(obj){if(obj==undefined){Util.error("Creating animation on non-existant object");return;}
if(this==window){return new animation(obj);}else{this.obj=obj;this._reset_state();this.queue=[];this.last_attr=null;}}
animation.resolution=20;animation.offset=0;animation.prototype._reset_state=function(){this.state={attrs:{},duration:500}}
animation.prototype.stop=function(){this._reset_state();this.queue=[];return this;}
animation.prototype._build_container=function(){if(this.container_div){this._refresh_container();return;}
if(this.obj.firstChild&&this.obj.firstChild.__animation_refs){this.container_div=this.obj.firstChild;this.container_div.__animation_refs++;this._refresh_container();return;}
var container=document.createElement('div');container.style.padding='0px';container.style.margin='0px';container.style.border='0px';container.__animation_refs=1;var children=this.obj.childNodes;while(children.length){container.appendChild(children[0]);}
this.obj.appendChild(container);this.obj.style.overflow='hidden';this.container_div=container;this._refresh_container();}
animation.prototype._refresh_container=function(){this.container_div.style.height='auto';this.container_div.style.width='auto';this.container_div.style.height=this.container_div.offsetHeight+'px';this.container_div.style.width=this.container_div.offsetWidth+'px';}
animation.prototype._destroy_container=function(){if(!this.container_div){return;}
if(!--this.container_div.__animation_refs){var children=this.container_div.childNodes;while(children.length){this.obj.appendChild(children[0]);}
this.obj.removeChild(this.container_div);}
this.container_div=null;}
animation.ATTR_TO=1;animation.ATTR_BY=2;animation.ATTR_FROM=3;animation.prototype._attr=function(attr,value,mode){attr=attr.replace(/-[a-z]/gi,function(l){return l.substring(1).toUpperCase();});var auto=false;switch(attr){case'background':this._attr('backgroundColor',value,mode);return this;case'margin':value=animation.parse_group(value);this._attr('marginBottom',value[0],mode);this._attr('marginLeft',value[1],mode);this._attr('marginRight',value[2],mode);this._attr('marginTop',value[3],mode);return this;case'padding':value=animation.parse_group(value);this._attr('paddingBottom',value[0],mode);this._attr('paddingLeft',value[1],mode);this._attr('paddingRight',value[2],mode);this._attr('paddingTop',value[3],mode);return this;case'backgroundColor':case'borderColor':case'color':value=animation.parse_color(value);break;case'opacity':value=parseFloat(value,10);break;case'height':case'width':if(value=='auto'){auto=true;}else{value=parseInt(value,10);}
break;case'borderWidth':case'lineHeight':case'fontSize':case'marginBottom':case'marginLeft':case'marginRight':case'marginTop':case'paddingBottom':case'paddingLeft':case'paddingRight':case'paddingTop':case'bottom':case'left':case'right':case'top':case'scrollTop':case'scrollLeft':value=parseInt(value,10);break;default:throw new Error(attr+' is not a supported attribute!');}
if(this.state.attrs[attr]===undefined){this.state.attrs[attr]={};}
if(auto){this.state.attrs[attr].auto=true;}
switch(mode){case animation.ATTR_FROM:this.state.attrs[attr].start=value;break;case animation.ATTR_BY:this.state.attrs[attr].by=true;case animation.ATTR_TO:this.state.attrs[attr].value=value;break;}}
animation.prototype.to=function(attr,value){if(value===undefined){this._attr(this.last_attr,attr,animation.ATTR_TO);}else{this._attr(attr,value,animation.ATTR_TO);this.last_attr=attr;}
return this;}
animation.prototype.by=function(attr,value){if(value===undefined){this._attr(this.last_attr,attr,animation.ATTR_BY);}else{this._attr(attr,value,animation.ATTR_BY);this.last_attr=attr;}
return this;}
animation.prototype.from=function(attr,value){if(value===undefined){this._attr(this.last_attr,attr,animation.ATTR_FROM);}else{this._attr(attr,value,animation.ATTR_FROM);this.last_attr=attr;}
return this;}
animation.prototype.duration=function(duration){this.state.duration=duration?duration:0;return this;}
animation.prototype.checkpoint=function(distance,callback){if(distance===undefined){distance=1;}
this.state.checkpoint=distance;this.queue.push(this.state);this._reset_state();this.state.checkpointcb=callback;return this;}
animation.prototype.blind=function(){this.state.blind=true;return this;}
animation.prototype.hide=function(){this.state.hide=true;return this;}
animation.prototype.show=function(){this.state.show=true;return this;}
animation.prototype.ease=function(ease){this.state.ease=ease;return this;}
animation.prototype.go=function(){var time=(new Date()).getTime();this.queue.push(this.state);for(var i=0;i<this.queue.length;i++){this.queue[i].start=time-animation.offset;if(this.queue[i].checkpoint){time+=this.queue[i].checkpoint*this.queue[i].duration;}}
animation.push(this);return this;}
animation.prototype._frame=function(time){var done=true;var still_needs_container=false;var whacky_firefox=false;for(var i=0;i<this.queue.length;i++){var cur=this.queue[i];if(cur.start>time){done=false;continue;}
if(cur.checkpointcb){this._callback(cur.checkpointcb,time-cur.start);cur.checkpointcb=null;}
if(cur.started===undefined){if(cur.show){this.obj.style.display='block';}
for(var a in cur.attrs){if(cur.attrs[a].start!==undefined){continue;}
switch(a){case'backgroundColor':case'borderColor':case'color':var val=animation.parse_color(CSS.getStyle(this.obj,a=='borderColor'?'borderLeftColor':a));if(cur.attrs[a].by){cur.attrs[a].value[0]=Math.min(255,Math.max(0,cur.attrs[a].value[0]+val[0]));cur.attrs[a].value[1]=Math.min(255,Math.max(0,cur.attrs[a].value[1]+val[1]));cur.attrs[a].value[2]=Math.min(255,Math.max(0,cur.attrs[a].value[2]+val[2]));}
break;case'opacity':var val=CSS.getOpacity(this.obj);if(cur.attrs[a].by){cur.attrs[a].value=Math.min(1,Math.max(0,cur.attrs[a].value+val));}
break;case'height':var val=DOM.getBoxHeight(this.obj);if(cur.attrs[a].by){cur.attrs[a].value+=val;}
break;case'width':var val=DOM.getBoxWidth(this.obj);if(cur.attrs[a].by){cur.attrs[a].value+=val;}
break;case'scrollLeft':case'scrollTop':var val=(this.obj==document.body)?(document.documentElement[a]||document.body[a]):this.obj[a];if(cur.attrs[a].by){cur.attrs[a].value+=val;}
cur['last'+a]=val;break;default:var val=parseInt(CSS.getStyle(this.obj,a),10)||0;if(cur.attrs[a].by){cur.attrs[a].value+=val;}
break;}
cur.attrs[a].start=val;}
if((cur.attrs.height&&cur.attrs.height.auto)||(cur.attrs.width&&cur.attrs.width.auto)){if(ua.firefox()<3){whacky_firefox=true;}
this._destroy_container();for(var a in{height:1,width:1,fontSize:1,borderLeftWidth:1,borderRightWidth:1,borderTopWidth:1,borderBottomWidth:1,paddingLeft:1,paddingRight:1,paddingTop:1,paddingBottom:1}){if(cur.attrs[a]){this.obj.style[a]=cur.attrs[a].value+(typeof cur.attrs[a].value=='number'?'px':'');}}
if(cur.attrs.height&&cur.attrs.height.auto){cur.attrs.height.value=DOM.getBoxHeight(this.obj);}
if(cur.attrs.width&&cur.attrs.width.auto){cur.attrs.width.value=DOM.getBoxWidth(this.obj);}}
cur.started=true;if(cur.blind){this._build_container();}}
var p=(time-cur.start)/cur.duration;if(p>=1){p=1;if(cur.hide){this.obj.style.display='none';}}else{done=false;}
var pc=cur.ease?cur.ease(p):p;if(!still_needs_container&&p!=1&&cur.blind){still_needs_container=true;}
if(whacky_firefox&&this.obj.parentNode){var parentNode=this.obj.parentNode;var nextChild=this.obj.nextSibling;parentNode.removeChild(this.obj);}
for(var a in cur.attrs){switch(a){case'backgroundColor':case'borderColor':case'color':this.obj.style[a]='rgb('+
animation.calc_tween(pc,cur.attrs[a].start[0],cur.attrs[a].value[0],true)+','+
animation.calc_tween(pc,cur.attrs[a].start[1],cur.attrs[a].value[1],true)+','+
animation.calc_tween(pc,cur.attrs[a].start[2],cur.attrs[a].value[2],true)+')';break;case'opacity':CSS.setOpacity(this.obj,animation.calc_tween(pc,cur.attrs[a].start,cur.attrs[a].value));break;case'height':case'width':this.obj.style[a]=pc==1&&cur.attrs[a].auto?'auto':animation.calc_tween(pc,cur.attrs[a].start,cur.attrs[a].value,true)+'px';break;case'scrollLeft':case'scrollTop':var is_body=this.obj==document.body;var val=(is_body)?(document.documentElement[a]||document.body[a]):this.obj[a];if(cur['last'+a]!=val){delete cur.attrs[a];}else{var diff=animation.calc_tween(pc,cur.attrs[a].start,cur.attrs[a].value,true)-val;if(DOMScroll.usingScrollWrapper()||!is_body){this.obj[a]=diff+val;}else{if(a=='scrollLeft'){window.scrollBy(diff,0);}else{window.scrollBy(0,diff);}}
cur['last'+a]=diff+val;}
break;default:this.obj.style[a]=animation.calc_tween(pc,cur.attrs[a].start,cur.attrs[a].value,true)+'px';break;}}
if(p==1){this.queue.splice(i--,1);this._callback(cur.ondone,time-cur.start-cur.duration);}}
if(whacky_firefox){parentNode[nextChild?'insertBefore':'appendChild'](this.obj,nextChild);}
if(!still_needs_container&&this.container_div){this._destroy_container();}
return!done;}
animation.prototype.ondone=function(fn){this.state.ondone=fn;return this;}
animation.prototype._callback=function(callback,offset){if(callback){animation.offset=offset;callback.call(this);animation.offset=0;}}
animation.calc_tween=function(p,v1,v2,whole){return(whole?parseInt:parseFloat)((v2-v1)*p+v1,10);}
animation.parse_color=function(color){var hex=/^#([a-f0-9]{1,2})([a-f0-9]{1,2})([a-f0-9]{1,2})$/i.exec(color);if(hex){return[parseInt(hex[1].length==1?hex[1]+hex[1]:hex[1],16),parseInt(hex[2].length==1?hex[2]+hex[2]:hex[2],16),parseInt(hex[3].length==1?hex[3]+hex[3]:hex[3],16)];}else{var rgb=/^rgba? *\(([0-9]+), *([0-9]+), *([0-9]+)(?:, *([0-9]+))?\)$/.exec(color);if(rgb){if(rgb[4]==='0'){return[255,255,255];}else{return[parseInt(rgb[1],10),parseInt(rgb[2],10),parseInt(rgb[3],10)];}}else if(color=='transparent'){return[255,255,255];}else{throw'Named color attributes are not supported.';}}}
animation.parse_group=function(value){var value=trim(value).split(/ +/);if(value.length==4){return value;}else if(value.length==3){return[value[0],value[1],value[2],value[1]];}else if(value.length==2){return[value[0],value[1],value[0],value[1]];}else{return[value[0],value[0],value[0],value[0]];}}
animation.push=function(instance){if(!animation.active){animation.active=[];}
animation.active.push(instance);if(!animation.timeout){animation.timeout=setInterval(animation.animate.bind(animation),animation.resolution,false);}
animation.animate(true);}
animation.animate=function(last){var time=(new Date()).getTime();for(var i=last===true?animation.active.length-1:0;i<animation.active.length;i++){try{if(!animation.active[i]._frame(time)){animation.active.splice(i--,1);}}catch(e){animation.active.splice(i--,1);}}
if(animation.active.length==0){clearInterval(animation.timeout);animation.timeout=null;}}
animation.ease={}
animation.ease.begin=function(p){return Math.sin(Math.PI/2*(p-1))+1;}
animation.ease.end=function(p){return Math.sin(0.5*Math.PI*p);}
animation.ease.both=function(p){return 0.5*Math.sin(Math.PI*(p-0.5))+0.5;}

function getRadioFormValue(obj){for(i=0;i<obj.length;i++){if(obj[i].checked){return obj[i].value;}}
return null;}
function getElementsByTagNames(list,obj){if(!obj)var obj=document;var tagNames=list.split(',');var resultArray=new Array();for(var i=0;i<tagNames.length;i++){var tags=obj.getElementsByTagName(tagNames[i]);for(var j=0;j<tags.length;j++){resultArray.push(tags[j]);}}
var testNode=resultArray[0];if(!testNode)return[];if(testNode.sourceIndex){resultArray.sort(function(a,b){return a.sourceIndex-b.sourceIndex;});}
else if(testNode.compareDocumentPosition){resultArray.sort(function(a,b){return 3-(a.compareDocumentPosition(b)&6);});}
return resultArray;}
function get_all_form_inputs(root_element){if(!root_element){root_element=document;}
return getElementsByTagNames('input,select,textarea,button',root_element);}
function get_form_select_value(select){return select.options[select.selectedIndex].value;}
function set_form_select_value(select,value){for(var i=0;i<select.options.length;++i){if(select.options[i].value==value){select.selectedIndex=i;break;}}}
function get_form_attr(form,attr){var val=form[attr];if(typeof val=='object'&&val.tagName=='INPUT'){var pn=val.parentNode,ns=val.nextSibling,node=val;pn.removeChild(node);val=form[attr];ns?pn.insertBefore(node,ns):pn.appendChild(node);}
return val;}
function serialize_form_helper(data,name,value){var match=/([^\]]+)\[([^\]]*)\](.*)/.exec(name);if(match){data[match[1]]=data[match[1]]||{};if(match[2]==''){var i=0;while(data[match[1]][i]!=undefined){i++;}}else{i=match[2];}
if(match[3]==''){data[match[1]][i]=value;}else{serialize_form_helper(data[match[1]],i.concat(match[3]),value);}}else{data[name]=value;}}
function serialize_form_fix(data){var keys=[];for(var i in data){if(data instanceof Object){data[i]=serialize_form_fix(data[i]);}
keys.push(i);}
var j=0,is_array=true;keys.sort().each(function(i){if(i!=j++){is_array=false;}});if(is_array){var ret={};keys.each(function(i){ret[i]=data[i];});return ret;}else{return data;}}
function serialize_form(obj){var data={};var elements=obj.tagName=='FORM'?obj.elements:get_all_form_inputs(obj);for(var i=elements.length-1;i>=0;i--){if(elements[i].name&&!elements[i].disabled){if(!elements[i].type||((elements[i].type=='radio'||elements[i].type=='checkbox')&&elements[i].checked)||elements[i].type=='text'||elements[i].type=='password'||elements[i].type=='hidden'||elements[i].tagName=='TEXTAREA'||elements[i].tagName=='SELECT'){serialize_form_helper(data,elements[i].name,elements[i].value);}}}
return serialize_form_fix(data);}
function do_post(uri){var pieces=/(^([^?])+)\??(.*)$/.exec(uri.toString());var form=document.createElement('form');form.action=pieces[1];form.method='post';form.style.display='none';var sparam=/([\w]+)(?:=([^&]+)|&|$)/g;var param=null;if(ge('post_form_id')){pieces[3]+='&post_form_id='+$('post_form_id').value;}
while(param=sparam.exec(pieces[3])){var input=document.createElement('input');input.type='hidden';input.name=decodeURIComponent(param[1]);input.value=decodeURIComponent(param[2]);form.appendChild(input);}
DOM.getRootElement().appendChild(form);form.submit();return false;}
function dynamic_post(uri,params,target){var form=document.createElement('form');form.action=uri.toString();form.method='POST';form.style.display='none';if(target){form.target=target;}
if(ge('post_form_id')){params['post_form_id']=$('post_form_id').value;}
params['post_form_id_source']='dynamic_post';params['next']=htmlspecialchars(document.location.href);create_hidden_inputs(params,form);DOM.getRootElement().appendChild(form);form.submit();return false;}
function create_hidden_inputs(params,form,inputs,overwrite){inputs=inputs||{};var input;var query=URI.implodeQuery(params,'',false);var query_data=query.split('&');for(var i=0;i<query_data.length;i++){if(query_data[i]){var temp=query_data[i].split('=');var n=temp[0];var v=temp[1];if(n===undefined||v===undefined){continue;}
v=URI.decodeComponent(v);if(inputs[n]&&overwrite){inputs[n].value=v;}else{input=$N('input',{type:'hidden',name:n,value:v});inputs[n]=input;form.appendChild(input);}}}
return inputs;}

function generic_dialog(className,modal){this.className=className;this.content=null;this.obj=null;this.popup=null;this.overlay=null;this.modal=null;this.modal_settings={},this.iframe=null;this.hidden_objects=[];if(modal==true){this.modal=true;}
this.auto_focus=true;}
generic_dialog.dialog_stack=null;generic_dialog.prototype.setClassName=function(className){if(this.obj){CSS.addClass(this.obj,className);}
this.className=className;};generic_dialog.hide_all=function(){if(generic_dialog.dialog_stack!==null){var stack=generic_dialog.dialog_stack.clone();generic_dialog.dialog_stack=null;for(var i=stack.length-1;i>=0;i--){stack[i].hide();}}};generic_dialog.prototype.should_hide_objects=!ua.windows();generic_dialog.prototype.should_use_iframe=ua.ie()<7||(ua.osx()&&ua.firefox());generic_dialog.prototype.set_auto_focus=function(auto_focus){this.auto_focus=auto_focus;}
generic_dialog.prototype.show_dialog=function(html){if(generic_dialog.dialog_stack===null){onunloadRegister(generic_dialog.hide_all,true);}
if(!this.obj){this.build_dialog();}
set_inner_html(this.content,html,true);var imgs=this.content.getElementsByTagName('img');for(var i=0;i<imgs.length;i++){imgs[i].onload=chain(imgs[i].onload,this.hide_objects.bind(this));}
this.show();if(this.auto_focus){this.focus_first_textbox_or_button.bind(this).defer();}
this.on_show_callback&&this.on_show_callback();return this;}
generic_dialog.prototype.set_callback=function(callback){this.on_show_callback=callback;return this;}
generic_dialog.prototype.focus_first_textbox_or_button=function(){var selectors=['input[type="text"]','textarea','input[type="password"]','input[type="button"]','input[type="submit"]'];var nodes=[];for(var ii=0;ii<selectors.length&&nodes.length==0;ii++){nodes=DOM.scry(this.content,selectors[ii]);}
if(nodes.length>0){var node=nodes[0];try{if(elementY(node)>0&&elementX(node)>0){node.focus();}}catch(e){};}
return true;}
generic_dialog.prototype.set_top=function(top){return this;}
generic_dialog.prototype.set_modal_setting=function(key,val){this.modal_settings[key]=val;return this;}
generic_dialog.prototype.get_modal_setting=function(key){return this.modal_settings[key];}
generic_dialog.prototype.make_modal=function(dark){if(dark){this.set_modal_setting(dark,true);}
if(this.modal){return;}
this.modal=true;if(ua.ie()==7){this.build_iframe();}
this.build_overlay();this.reset_iframe();}
generic_dialog.prototype.show_loading=function(loading_html){if(!loading_html){loading_html=_tx("Loading...");}
return this.show_dialog('<div class="dialog_loading">'+loading_html+'</div>');}
generic_dialog.prototype.show_ajax_dialog_custom_loader=function(html,src,post_vars,use_async_response){if(html){this.show_loading(html);}
var handler=function(use_async_response,response){var html=use_async_response?response.getPayload():response.getPayload().responseText;this.show_dialog(html);}.bind(this,use_async_response);var error_handler=function(response){ErrorDialog.showAsyncError(response);this.hide(false);}.bind(this);var async=new AsyncRequest().setOption('suppressEvaluation',!use_async_response).setURI(src).setData(post_vars||{}).setHandler(handler).setErrorHandler(error_handler).setTransportErrorHandler(error_handler);if(!post_vars){async.setMethod('GET').setReadOnly(true);}
async.send();return this;}
generic_dialog.prototype.show_ajax_dialog=function(src,post_vars,use_async_response){post_vars=post_vars||false;var load=_tx("Loading...");return this.show_ajax_dialog_custom_loader(load,src,post_vars,use_async_response);}
generic_dialog.prototype.show_prompt=function(title,content){return this.show_dialog('<h2 class="dialog_title"><span>'+title+'</span></h2><div class="dialog_content">'+content+'</div>');}
generic_dialog.prototype.show_message=function(title,content,button){if(button==null){button=_tx("Okay");}
return this.show_choice(title,content,button,function(){generic_dialog.get_dialog(this).fade_out(100)});}
generic_dialog.prototype.show_choice=function(title,content,button1,button1js,button2,button2js,buttons_msg,button3,button3js){var buttons='<div class="dialog_buttons" id="dialog_buttons">';if(typeof(buttons_msg)!='undefined'){buttons+='<div class="dialog_buttons_msg">';buttons+=buttons_msg;buttons+='</div>';}
buttons+='<input class="inputsubmit" type="button" value="'+button1+'" id="dialog_button1" />';if(button2){var button2_class='inputsubmit';if(button2==_tx("Cancel")){button2_class+=' inputaux';}
buttons+='<input class="'+button2_class+'" type="button" value="'+button2+'" id="dialog_button2" />';}
if(button3){var button3_class='inputsubmit';if(button3==_tx("Cancel")){button3_class+=' inputaux';}
buttons+='<input class="'+button3_class+'" type="button" value="'+button3+'" id="dialog_button3" />';}
this.show_prompt(title,this.content_to_markup(content)+buttons);var inputs=this.obj.getElementsByTagName('input');if(button3){button1obj=inputs[inputs.length-3];button2obj=inputs[inputs.length-2];button3obj=inputs[inputs.length-1];}else if(button2){button1obj=inputs[inputs.length-2];button2obj=inputs[inputs.length-1];}else{button1obj=inputs[inputs.length-1];}
if(button1js&&button1){if(typeof button1js=='string'){eval('button1js = function() {'+button1js+'}');}
button1obj.onclick=button1js;}
if(button2js&&button2){if(typeof button2js=='string'){eval('button2js = function() {'+button2js+'}');}
button2obj.onclick=button2js;}
if(button3js&&button3){if(typeof button3js=='string'){eval('button3js = function() {'+button3js+'}');}
button3obj.onclick=button3js;}
if(!this.modal){document.onkeyup=function(e){var keycode=(e&&e.which)?e.which:event.keyCode;var btn2_exists=(typeof button2obj!='undefined');var btn3_exists=(typeof button3obj!='undefined');var is_webkit=ua.safari();if(is_webkit&&keycode==13){button1obj.click();}
if(keycode==27){if(btn3_exists){button3obj.click();}else if(btn2_exists){button2obj.click();}else{button1obj.click();}}
document.onkeyup=function(){}}
this.button_to_focus=button1obj;button1obj.offsetWidth&&button1obj.focus();}
return this;}
generic_dialog.prototype.content_to_markup=function(content){return(typeof content=='string')?'<div class="dialog_body">'+content+'</div>':'<div class="dialog_summary">'+content.summary+'</div><div class="dialog_body">'+content.body+'</div>';}
generic_dialog.prototype.hide=function(temporary){if(this.obj){this.obj.style.display='none';}
if(this.iframe){this.iframe.style.display='none';}
if(this.overlay){this.overlay.style.display='none';}
if(this.timeout){clearTimeout(this.timeout);this.timeout=null;return;}
if(this.hidden_objects.length){for(var i=0,il=this.hidden_objects.length;i<il;i++){this.hidden_objects[i].style.visibility='';}
this.hidden_objects=[];}
clearInterval(this.active_hiding);if(!temporary){if(generic_dialog.dialog_stack){var stack=generic_dialog.dialog_stack;for(var i=stack.length-1;i>=0;i--){if(stack[i]==this){stack.splice(i,1);}}
if(stack.length){stack[stack.length-1].show();}}
if(this.obj){this.obj.parentNode.removeChild(this.obj);this.obj=null;}
if(this.close_handler){this.close_handler();}}
return this;}
generic_dialog.prototype.fade_out=function(interval,timeout,callback){if(!this.popup){return this;}
try{animation(this.obj).duration(timeout||0).checkpoint().to('opacity',0).hide().duration(interval||350).ondone(function(){callback&&callback();this.hide();}.bind(this)).go();}catch(e){this.hide();}
return this;}
generic_dialog.prototype.show=function(){if(this.obj&&this.obj.style.display){this.obj.style.visibility='hidden';this.obj.style.display='';this.reset_dialog();this.obj.style.visibility='';this.obj.dialog=this;}else{this.reset_dialog();}
this.hide_objects();clearInterval(this.active_hiding);this.active_hiding=setInterval(this.active_resize.bind(this),500);var stack=generic_dialog.dialog_stack?generic_dialog.dialog_stack:generic_dialog.dialog_stack=[];if(stack.length){var current_dialog=stack[stack.length-1];if(current_dialog!=this&&!current_dialog.is_stackable){current_dialog.hide();}}
for(var i=stack.length-1;i>=0;i--){if(stack[i]==this){stack.splice(i,1);}else{stack[i].hide(true);}}
stack.push(this);return this;}
generic_dialog.prototype.active_resize=function(){if(this.last_offset_height!=this.content.offsetHeight){this.hide_objects();this.last_offset_height=this.content.offsetHeight;}}
generic_dialog.prototype.hide_objects=function(){var hide=[],objects=[];var ad_locs=['',0,1,2,4,5,9,3];for(var i=0;i<ad_locs.length;i++){var ad_div=ge('ad_'+ad_locs[i]);if(ad_div!=null){hide.push(ad_div);}}
var rect={x:elementX(this.content),y:elementY(this.content),w:this.content.offsetWidth,h:this.content.offsetHeight};if(this.should_hide_objects){var iframes=document.getElementsByTagName('iframe');for(var i=0;i<iframes.length;i++){if(iframes[i].className.indexOf('share_hide_on_dialog')!=-1){objects.push(iframes[i]);}}}
var swfs=getElementsByTagNames('embed,object',document.body);for(var i=0;i<swfs.length;i++){if((swfs[i].getAttribute('wmode')||'').toLowerCase()!='transparent'||this.should_hide_objects){objects.push(swfs[i]);}}
for(var i=0;i<objects.length;i++){var node=objects[i].offsetHeight?objects[i]:objects[i].parentNode;swf_rect={x:elementX(node),y:elementY(node),w:node.offsetWidth,h:node.offsetHeight};if(!DOM.contains(this.content,objects[i])&&rect.y+rect.h>swf_rect.y&&swf_rect.y+swf_rect.h>rect.y&&rect.x+rect.w>swf_rect.x&&swf_rect.x+swf_rect.w>rect.w&&this.hidden_objects.indexOf(node)==-1){hide.push(node);}}
for(var i=0;i<hide.length;i++){this.hidden_objects.push(hide[i]);hide[i].style.visibility='hidden';}}
generic_dialog.prototype.build_dialog=function(){if(!this.obj){this.obj=document.createElement('div');}
CSS.setClass(this.obj,'generic_dialog'+(this.className?' '+this.className:''));this.obj.style.display='none';onloadRegister(function(){DOM.getRootElement().appendChild(this.obj);}.bind(this));if(this.should_use_iframe||(this.modal&&ua.ie()==7)){this.build_iframe();}
if(!this.popup){this.popup=document.createElement('div');CSS.setClass(this.popup,'generic_dialog_popup');}
this.popup.style.left=this.popup.style.top='';this.obj.appendChild(this.popup);if(this.modal){this.build_overlay();}}
generic_dialog.prototype.build_iframe=function(){if(!this.iframe&&!(this.iframe=ge('generic_dialog_iframe'))){this.iframe=document.createElement('iframe');this.iframe.id='generic_dialog_iframe';this.iframe.src="/common/blank.html";}
this.iframe.frameBorder='0';onloadRegister(function(){DOM.getRootElement().appendChild(this.iframe);}.bind(this));}
generic_dialog.prototype.build_overlay=function(){this.overlay=document.createElement('div');this.overlay.id='generic_dialog_overlay';if(this.get_modal_setting('dark')){CSS.addClass(this.overlay,'dark_dialog_overlay');}
this.overlay.style.height=Vector2.getDocumentDimensions().y+'px';onloadRegister(function(){DOM.getRootElement().appendChild(this.overlay);}.bind(this));}
generic_dialog.prototype.reset_dialog=function(){if(!this.popup){return;}
onloadRegister(function(){this.reset_dialog_obj();this.reset_iframe();}.bind(this));}
generic_dialog.prototype.reset_iframe=function(){if(!this.should_use_iframe&&!(this.modal&&ua.ie()==7)){return;}
if(this.modal){this.iframe.style.left='0px';this.iframe.style.top='0px';this.iframe.style.width='100%';var documentHeight=Vector2.getDocumentDimensions().y;if(documentHeight>10000){documentHeight=10000;}
this.iframe.style.height=documentHeight+'px';}else{this.iframe.style.left=elementX(this.frame)+'px';this.iframe.style.top=elementY(this.frame)+'px';this.iframe.style.width=this.frame.offsetWidth+'px';this.iframe.style.height=this.frame.offsetHeight+'px';}
this.iframe.style.display='';}
generic_dialog.prototype.reset_dialog_obj=function(){}
generic_dialog.get_dialog=function(obj){while(!obj.dialog&&obj.parentNode){obj=obj.parentNode;}
return obj.dialog?obj.dialog:false;}
function pop_dialog(className,callback_function,modal){this.top=125;this.parent.construct(this,className,modal);this.on_show_callback=callback_function;}
pop_dialog.extend('generic_dialog');pop_dialog.prototype.do_expand_animation=false;pop_dialog.prototype.kill_expand_animation=true;pop_dialog.prototype.show_ajax_dialog=function(src,post_vars,title,use_async_response){post_vars=post_vars||false;if(this.do_expand_animation&&!this.kill_expand_animation){var load=null;this.show_loading_title(title);}else{var load=_tx("Loading...");}
return this.show_ajax_dialog_custom_loader(load,src,post_vars,use_async_response);}
pop_dialog.prototype.show_message=function(title,content,button){if(this.do_expand_animation&&!this.kill_expand_animation){this.show_loading_title(title);}else{this.show_loading();}
return this.parent.show_message(title,content,button);}
pop_dialog.prototype.show_dialog=function(html,prevent_expand_animation){var new_dialog=this.parent.show_dialog(html);if(this.do_expand_animation&&!prevent_expand_animation&&!this.kill_expand_animation){function check_done_loading_title(callback,i){var i=(i?i:0);if(this.done_loading_title!=true&&i<10){i++;setTimeout(check_done_loading_title.bind(this,callback,i),50);}else{callback&&callback();}}
function check_for_complete_images(content,callback,attempt){var complete_images=0;var images=content.getElementsByTagName('img');var safari2=ua.safari()<3;for(var i=0;i<images.length;i++){var imageobj=images[i];if(image_has_loaded(imageobj)){complete_images++;}}
if(complete_images!=images.length){if(attempt<20){attempt++;setTimeout(function(){check_for_complete_images(content,callback,attempt);},100);}else{callback();}}else{callback();}}
var divs=this.content.getElementsByTagName('div');for(var i=0;i<divs.length;i++){if(divs[i].className=='dialog_content'){expand_animation_div=divs[i];break;}}
var container_div=document.createElement('div');container_div.style.padding='0px';container_div.style.margin='0px';container_div.style.overflow='visible';expand_animation_div.parentNode.insertBefore(container_div,expand_animation_div);container_div.appendChild(expand_animation_div);expand_animation_div.style.overflow='hidden';check_for_complete_images(expand_animation_div,function(){check_done_loading_title.bind(this,function(){this.content.getElementsByTagName('h2')[0].className='';animation(expand_animation_div).to('height','auto').from(0).from('opacity',0).to(1).ease(animation.ease.both).show().duration(200).ondone(function(){container_div.parentNode.insertBefore(expand_animation_div,container_div);container_div.parentNode.removeChild(container_div);if(!this.button_to_focus){var inputs=this.obj.getElementsByTagName('input');for(var i=0;i<inputs.length;i++){if(inputs[i].type=='button'&&inputs[i].id=='dialog_button1'){this.button_to_focus=inputs[i];break;}}}
if(this.button_to_focus){setTimeout(function(){this.button_to_focus.focus();}.bind(this),50);}
expand_animation_div.style.overflow='visible';this.do_expand_animation=false;this.show();}.bind(this,{expand_animation_div:expand_animation_div,container_div:container_div})).go();}.bind(this))();}.bind(this,{expand_animation_div:expand_animation_div}),0);}
return new_dialog;}
pop_dialog.prototype.build_dialog=function(){this.parent.build_dialog();CSS.addClass(this.obj,'pop_dialog');if(intl_locale_is_rtl()){CSS.addClass(this.obj,'pop_dialog_rtl');}
set_inner_html(this.popup,'<table id="pop_dialog_table" class="pop_dialog_table">'+'<tr><td class="pop_topleft"></td><td class="pop_border pop_top"></td><td class="pop_topright"></td></tr>'+'<tr><td class="pop_border pop_side"></td><td class="pop_content" id="pop_content"></td><td class="pop_border pop_side"></td></tr>'+'<tr><td class="pop_bottomleft"></td><td class="pop_border pop_bottom"></td><td class="pop_bottomright"></td></tr>'+'</table>');this.frame=this.popup.getElementsByTagName('tbody')[0];this.content=this.popup.getElementsByTagName('td')[4];}
pop_dialog.prototype.reset_dialog_obj=function(){this.popup.style.top=Vector2.getScrollPosition().y+this.top+'px';}
pop_dialog.prototype.set_top=function(top){this.top=top;}
pop_dialog.prototype.show_prompt=function(title,content){if(!this.do_expand_animation||this.kill_expand_animation){return this.show_dialog('<h2 class="dialog_title"><span>'+title+'</span></h2><div class="dialog_content">'+content+'</div>');}
return this.show_dialog('<h2 class="dialog_loading"><span>'+title+'</span></h2><div class="dialog_content" style="display:none;">'+content+'</div>');}
pop_dialog.prototype.show_loading_title=function(title){if(!this.kill_expand_animation){this.do_expand_animation=true;this.show_dialog('<h2 class="dialog_loading"><span>'+title+'</span></h2>',true);setTimeout(function(){this.done_loading_title=true;}.bind(this),200);}else{this.show_loading();}}
pop_dialog.prototype.get_popup_dialog=function(){return DOM.find(this.popup,"table.pop_dialog_table");}
function contextual_dialog(className){this.parent.construct(this,className);}
contextual_dialog.extend('generic_dialog');contextual_dialog.prototype.set_context=function(obj){this.context=obj;return this;}
contextual_dialog.prototype.set_modal=function(mod){this.modal=mod;return this;}
contextual_dialog.prototype.build_dialog=function(){this.parent.build_dialog();this.obj.className+=' contextual_dialog';this.popup.innerHTML='<div class="contextual_arrow"><span>^_^keke1</span></div><div class="contextual_dialog_content"></div>';this.arrow=this.popup.getElementsByTagName('div')[0];this.content=this.frame=this.popup.getElementsByTagName('div')[1];}
contextual_dialog.prototype.reset_dialog_obj=function(){var x=elementX(this.context);var documentOffsetWidth=DOMScroll.getScrollRoot().offsetWidth;var center=(documentOffsetWidth-this.popup.offsetWidth)/2;if(x<documentOffsetWidth/2){this.arrow.className='contextual_arrow_rev';var left=Math.min(center,x+this.context.offsetWidth-this.arrow_padding_x);var arrow=x-left+this.context.offsetWidth+this.arrow_padding_x;}else{this.arrow.className='contextual_arrow';var left=Math.max(center,x-this.popup.offsetWidth+this.arrow_padding_x);var arrow=x-left-this.arrow_padding_x-this.arrow_width;}
if(isNaN(left)){left=0;}
if(isNaN(arrow)){arrow=0;}
this.popup.style.top=(elementY(this.context)+this.context.offsetHeight-this.arrow.offsetHeight+this.arrow_padding_y)+'px';this.popup.style.left=left+'px';this.arrow.style.backgroundPosition=arrow+'px';}
contextual_dialog.prototype._remove_resize_events=function(){if(this._scroll_events){for(var i=0;i<this._scroll_events.length;i++){removeEventBase(this._scroll_events[i].obj,this._scroll_events[i].event,this._scroll_events[i].func);}}
this._scroll_events=[];}
contextual_dialog.prototype.show=function(){this._remove_resize_events();var obj=this.context;while(obj){if(obj.id!='content'&&(obj.scrollHeight&&obj.offsetHeight&&obj.scrollHeight!=obj.offsetHeight)||(obj.scrollWidth&&obj.offsetWidth&&obj.scrollWidth!=obj.offsetWidth)){var evt={obj:obj,event:'scroll',func:this.reset_dialog_obj.bind(this)};addEventBase(evt.obj,evt.event,evt.func);}
obj=obj.parentNode;}
var evt={obj:window,event:'resize',func:this.reset_dialog_obj.bind(this)};addEventBase(evt.obj,evt.event,evt.func);this.parent.show();}
contextual_dialog.prototype.hide=function(temp){this._remove_resize_events();this.parent.hide(temp);}
contextual_dialog.prototype.arrow_padding_x=5;contextual_dialog.prototype.arrow_padding_y=10;contextual_dialog.prototype.arrow_width=13;contextual_dialog.hide_all=function(callback){if(generic_dialog.dialog_stack){for(var i=0;i<generic_dialog.dialog_stack.length;i++){if(generic_dialog.dialog_stack[i].context&&generic_dialog.dialog_stack[i].arrow){generic_dialog.dialog_stack[i].hide();}}}
callback&&callback();}

function Dialog(model){Dialog._setup();this._pd=new pop_dialog();this._pd._dialog_object=this;this._show_loading=true;this._onload_handlers=[];if(model){this._setFromModel(model);}}
copy_properties(Dialog,{OK:{name:'ok',label:_tx("Okay")},CANCEL:{name:'cancel',label:_tx("Cancel"),className:'inputaux'},CLOSE:{name:'close',label:_tx("Close")},SAVE:{name:'save',label:_tx("Save")},SUBMIT:{name:'submit',label:_tx("Submit")},CONFIRM:{name:'confirm',label:_tx("Confirm")},DELETE:{name:'delete',label:_tx("Delete")}});copy_properties(Dialog,{OK_AND_CANCEL:[Dialog.OK,Dialog.CANCEL],_STANDARD_BUTTONS:[Dialog.OK,Dialog.CANCEL,Dialog.CLOSE,Dialog.SAVE,Dialog.SUBMIT,Dialog.CONFIRM,Dialog.DELETE],newButton:function(name,label,className,handler){var button={name:name,label:label}
if(className){button.className=className;}
if(handler){button.handler=handler;}
return button;},getCurrent:function(){var stack=generic_dialog.dialog_stack;if(!stack||stack.length==0){return null;}
return stack[stack.length-1]._dialog_object||null;},createCaptchaDialog:function(captchaHtml,closeHandler){var dialog=new Dialog().setClassName('captcha_dialog').setTitle(_tx("Security Check")).setBody(captchaHtml).setButtons([Dialog.SUBMIT,Dialog.CANCEL]).setCloseHandler(closeHandler).setModal().onloadRegister(create_captcha);return dialog;},createConfirmationDialog:function(confirmationHtml,title,button,closeHandler){var dialog=new Dialog().setClassName('confirm_dialog').setTitle(title).setBody(confirmationHtml).setButtons([button,Dialog.CANCEL]).setCloseHandler(closeHandler).setModal();return dialog;},showFormAjax:function(title,uri,button_label,reload_page_on_success){var dialog=new Dialog().setTitle(title);var form_id='dialog_ajax_form__'+gen_unique();var buttons=[Dialog.newButton(button_label.toLowerCase(),button_label),Dialog.CANCEL];dialog.setShowLoading(true).show();var preSubmitErrorHandler=function(response){if(response.getError()!=true){dialog.hide();ErrorDialog.showAsyncError(response);}else{dialog.setBody(response.getPayload()).setButtons(Dialog.OK).clearHandler().show();}};var preSubmitHandler=function(response){var contents='<form id="'+
form_id+'" onsubmit="return false;">'+
response.getPayload()+'</form>';dialog.setBody(contents).setButtons(buttons).setHandler(submitHandler).show();};var submitHandler=function(){new AsyncRequest().setURI(uri).setData(serialize_form(ge(form_id))).setHandler(postSubmitHandler).setErrorHandler(postSubmitErrorHandler).send();};var postSubmitHandler=function(response){dialog.setBody(response.getPayload()).setButtons([Dialog.OK]).show();if(reload_page_on_success){window.location.reload();}else{dialog.setAutohide(750);}};var postSubmitErrorHandler=function(response){if(response.getError()==kError_Global_ValidationError){preSubmitHandler(response);}else if(response.getError()!=true){ErrorDialog.showAsyncError(response);}else{preSubmitErrorHandler(response);}};new AsyncRequest().setURI(uri).setReadOnly(true).setHandler(preSubmitHandler).setErrorHandler(preSubmitErrorHandler).send();},_basicMutator:function(private_key){return function(value){this[private_key]=value;this._dirty();return this;};},_findButton:function(buttons,name){for(var i=0;i<buttons.length;++i){if(buttons[i].name==name){return buttons[i];}}
return null;},_setup:function(){if(Dialog._is_set_up){return;}
Dialog._is_set_up=true;var filter=function(event,type){return type=='onkeyup'&&KeyEventController.filterEventModifiers(event,type);};KeyEventController.registerKey('ESCAPE',Dialog._handleEscapeKey,filter);},_handleEscapeKey:function(event,type){var dialog=Dialog.getCurrent();if(!dialog){return true;}
var buttons=dialog._buttons;if(!buttons){return true;}
var cancel_button=Dialog._findButton(buttons,'cancel');if(cancel_button){var button_to_simulate=cancel_button;}else if(buttons.length==1){var button_to_simulate=buttons[0];}else{return true;}
dialog.handleButton(button_to_simulate);return false;}});copy_properties(Dialog.prototype,{show:function(){this._showing=true;this._dirty();return this;},hide:function(){this._showing=false;if(this._autohide_timeout){clearTimeout(this._autohide_timeout);this._autohide_timeout=null;}
if(!generic_dialog.dialog_stack||generic_dialog.dialog_stack.length==1){this._pd.fade_out(250);}else{this._pd.hide();}
return this;},getRoot:function(){return this._pd.obj;},setShowing:function(){this.show();return this;},setHiding:function(){this.hide();return this;},setTitle:Dialog._basicMutator('_title'),setBody:Dialog._basicMutator('_body'),setExtraData:Dialog._basicMutator('_extra_data'),setShowLoading:Dialog._basicMutator('_show_loading'),setFullBleed:Dialog._basicMutator('_full_bleed'),setImmediateRendering:Dialog._basicMutator('_immediate_rendering'),setUserData:Dialog._basicMutator('_user_data'),getUserData:function(){return this._user_data;},setAutohide:function(autohide){if(autohide){if(this._showing){this._autohide_timeout=setTimeout(bind(this,'hide'),autohide);}else{this._autohide=autohide;}}else{this._autohide=null;if(this._autohide_timeout){clearTimeout(this._autohide_timeout);this._autohide_timeout=null;}}
return this;},setSummary:Dialog._basicMutator('_summary'),setButtons:function(buttons){if(!(buttons instanceof Array)){buttons=[buttons];}
for(var i=0;i<buttons.length;++i){if(typeof(buttons[i])=='string'){var button=Dialog._findButton(Dialog._STANDARD_BUTTONS,buttons[i]);if(!button){Util.error('Unknown button: '+buttons[i]);}
buttons[i]=button;}}
this._buttons=buttons;this._dirty();return this;},setButtonsMessage:Dialog._basicMutator('_buttons_message'),setStackable:Dialog._basicMutator('_is_stackable'),setHandler:function(handler){this._handler=handler;return this;},setCancelHandler:function(cancelHandler){this._cancelHandler=cancelHandler;return this;},clearHandler:function(){return this.setHandler(null);},setPostURI:function(post_uri,asynchronous){if(asynchronous===undefined){asynchronous=true;}
if(asynchronous){this.setHandler(this._submitForm.bind(this,'POST',post_uri));}else{this.setHandler(function(){dynamic_post(post_uri,this.getFormData());this.hide();}.bind(this));}
return this;},setGetURI:function(get_uri){this.setHandler(this._submitForm.bind(this,'GET',get_uri));return this;},setModal:function(modal){if(modal===undefined){modal=true;}
if(this._showing&&this._modal&&!modal){Util.error("At the moment we don't support un-modal-ing a modal dialog");}
this._modal=modal;return this;},setDarkModal:function(dark){if(dark===undefined){dark=true;}
if(dark){this.setModal();}
this._pd.set_modal_setting('dark',dark);return this;},setContentWidth:function(width,fixed){this._content_width=width;if(fixed){this._resize(fixed);}else{this._dirty();}
return this;},setTitleLoading:function(loading){if(loading===undefined){loading=true;}
var header=DOM.find(this._pd.popup,'h2.dialog_title');CSS.conditionClass(header,'loading',loading);return this;},setClassName:Dialog._basicMutator('_class_name'),setCloseHandler:function(close_handler){this._close_handler=call_or_eval.bind(null,this,close_handler);this._pd.close_handler=this._close_handler;return this;},setFooter:Dialog._basicMutator('_footer'),setAutoFocus:Dialog._basicMutator('_auto_focus'),onloadRegister:function(handler){this._onload_handlers.push(handler.bind(this));return this;},setAsync:function(async_request){var handler=function(response){if(this._async_request!=async_request){return;}
this._async_request=null;var payload=response.getPayload();if(typeof(payload)=='string'){this.setBody(payload);}else{this._setFromModel(payload);}
this._update(true);}.bind(this);var hide=bind(this,'hide');async_request.setHandler(chain(async_request.getHandler(),handler)).setErrorHandler(chain(hide,async_request.getErrorHandler())).setTransportErrorHandler(chain(hide,async_request.getTransportErrorHandler())).send();this._async_request=async_request;this._dirty();return this;},_dirty:function(){if(!this._is_dirty){this._is_dirty=true;if(this._immediate_rendering){this._update();}else{bind(this,'_update').defer();}}},_update:function(even_if_not_dirty){if(!this._is_dirty&&even_if_not_dirty!==true){return;}
this._is_dirty=false;if(!this._showing){return;}
if(this._autohide&&!this._async_request&&!this._autohide_timeout){this._autohide_timeout=setTimeout(bind(this,'hide'),this._autohide);}
if(this._class_name){this._pd.setClassName(this._class_name);}
if(this._full_bleed){this._pd.setClassName('full_bleed');}
this._pd.set_auto_focus(this._auto_focus===undefined||this._auto_focus);if(!this._async_request||!this._show_loading){var html=[];if(this._title){html.push('<h2 class="dialog_title"><span>'+this._title+'</span></h2>');}
html.push('<div class="dialog_content">');if(this._summary){html.push('<div class="dialog_summary">');html.push(this._summary);html.push('</div>');}
html.push('<div class="dialog_body">');html.push(this._body);html.push('</div>');if((this._buttons&&this._buttons.length>0)||this._buttons_message){html.push('<div class="dialog_buttons">');if(this._buttons_message){html.push('<div class="dialog_buttons_msg">');html.push(this._buttons_message);html.push('</div>');}
if(this._buttons){this._buttons.forEach(function(button){html.push('<input class="inputsubmit '+(button.className||'')+'"'
+' type="button"'
+(button.name?(' name="'+button.name+'"'):'')
+' value="'+htmlspecialchars(button.label)+'"'
+' onclick="Dialog.getCurrent().handleButton(this.name);" />');},this);}
html.push('</div>');}
if(this._footer){html.push('<div class="dialog_footer">');html.push(this._footer);html.push('</div>');}
html.push('</div>');this._pd.show_dialog(html.join(''));for(var i=0;i<this._onload_handlers.length;++i){try{this._onload_handlers[i]();}catch(ex){Util.error('Uncaught exception in dialog onload hook: %x',ex);}}
this._onload_handlers=[];}else{var title=this._title||_tx("Loading...");this._pd.show_loading_title(title);}
if(this._modal){this._pd.make_modal();}
if(this._content_width){this._resize();}
this._pd.is_stackable=this._is_stackable;this._pd.close_handler=this._close_handler;},handleButton:function(button){if(typeof(button)=='string'){button=Dialog._findButton(this._buttons,button);}
if(!button){Util.error('Huh?  How did this button get here?');return;}
var value=call_or_eval(button,button.handler);if(value===false){return;}
if(button==Dialog.CANCEL){call_or_eval(this,this._cancelHandler);}else{if(call_or_eval(this,this._handler,{button:button})===false){return;}}
this.hide();},getButtonElement:function(button){if(typeof(button)=='string'){button=Dialog._findButton(this._buttons,button);}
if(!button||!button.name){return null;}
var inputs=DOM.scry(this._pd.popup,'input');var name_filter=function(elem){return elem.name==button.name;};return inputs.filter(name_filter)[0]||null;},_submitForm:function(method,uri,button){var data=this.getFormData();data[button.name]=button.label;if(this._extra_data){copy_properties(data,this._extra_data);}
var async_request=new AsyncRequest().setURI(uri).setData(data).setMethod(method).setReadOnly(method=='GET');this.setAsync(async_request);return false;},getFormData:function(){var dialog_content_divs=DOM.scry(this._pd.content,'div.dialog_content');if(dialog_content_divs.length!=1){Util.error(dialog_content_divs.length
+" dialog_content divs in this dialog?  Weird.");}
return serialize_form(dialog_content_divs[0]);},_setFromModel:function(model){for(var propertyName in model){var mutator=this['set'+propertyName.substr(0,1).toUpperCase()
+propertyName.substr(1)];if(!mutator){Util.error("Unknown Dialog property: "+propertyName);}
mutator.call(this,model[propertyName]);}},_resize:function(fixed){var popup=this._pd.get_popup_dialog();var offsetLeft=popup.offsetLeft;popup.style.width=(this._content_width+42)+'px';if(fixed){popup.style.marginLeft=offsetLeft+'px';}}});function ErrorDialog(){this.parent.construct(this);this.setClassName('errorDialog').setModal(true);this.setStackable(true);return this;}
ErrorDialog.extend('Dialog');copy_properties(ErrorDialog,{showAsyncError:function(response){try{return(new ErrorDialog()).showError(response.getErrorSummary(),response.getErrorDescription());}catch(ex){aiert(response);}}});copy_properties(ErrorDialog.prototype,{showError:function(title,message){return this.setTitle(title).setBody(message).setButtons([Dialog.OK]).show();}});function ConnectDialog(profile_id,source,ondone_func,ondone_data,ondone_reload,ref,pymk_score,pymk_source,pymk_page){this.parent.construct(this);this.setClassName('UIConnect_Dialog');this.setStackable(true);this.setAsync(new AsyncRequest().setURI('/ajax/profile/connect.php').setData({'dialog':1,'profile_id':profile_id,'source':source}).setContextData('clicktype','Add a Friend',ref=='profile_others'));this.ondone_func=ondone_func;this.ondone_data=ondone_data;this.ondone_reload=ondone_reload;this.pymk_score=pymk_score;this.pymk_source=pymk_source;this.pymk_page=pymk_page;ConnectDialog.setInstance(this);onunloadRegister(ConnectDialog.deleteInstance);return this;}
ConnectDialog.extend('Dialog');ConnectDialog.deleteInstance=function(){delete ConnectDialog.instance;}
ConnectDialog.setInstance=function(instance){ConnectDialog.instance=instance;}
ConnectDialog.getInstance=function(){return ConnectDialog.instance;}

if(!this.JSON){this.JSON=function(){function f(n){return n<10?'0'+n:n;}
Date.prototype.toJSON=function(){return this.getUTCFullYear()+'-'+
f(this.getUTCMonth()+1)+'-'+
f(this.getUTCDate())+'T'+
f(this.getUTCHours())+':'+
f(this.getUTCMinutes())+':'+
f(this.getUTCSeconds())+'Z';};var m={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};function stringify(value,whitelist){var a,i,k,l,v;switch(typeof value){case'string':return(new RegExp('[\x00-\x1f\\\\"]')).test(value)?'"'+value.replace(/[\x00-\x1f\\"]/g,function(a){var c=m[a];if(c){return c;}
c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+
(c%16).toString(16);})+'"':'"'+value+'"';case'number':return isFinite(value)?String(value):'null';case'boolean':return String(value);case'null':return'null';case'object':if(DOM.isNode(value)){return null;}
if(!value){return'null';}
if(typeof value.toJSON==='function'){return stringify(value.toJSON());}
a=[];if(typeof value.length==='number'&&!(propertyIsEnumerable(value,'length'))){l=value.length;for(i=0;i<l;i+=1){a.push(stringify(value[i],whitelist)||'null');}
return'['+a.join(',')+']';}
if(whitelist){l=whitelist.length;for(i=0;i<l;i+=1){k=whitelist[i];if(typeof k==='string'){v=stringify(value[k],whitelist);if(v){a.push(stringify(k)+':'+v);}}}}else{for(k in value){if(typeof k==='string'){v=stringify(value[k],whitelist);if(v){a.push(stringify(k)+':'+v);}}}}
return'{'+a.join(',')+'}';}}
return{stringify:stringify,parse:function(text,filter){var j;function walk(k,v){var i,n;if(v&&typeof v==='object'){for(i in v){if(Object.prototype.hasOwnProperty.apply(v,[i])){n=walk(i,v[i]);if(n!==undefined){v[i]=n;}}}}
return filter(k,v);}
if(text&&/^[\],:{}\s]*$/.test(text.replace(/\\./g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(:?[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof filter==='function'?walk('',j):j;}
throw new SyntaxError('decodeJSON');}};}();}
this.JSON.encode=this.JSON.stringify;this.JSON.decode=this.JSON.parse;function propertyIsEnumerable(o,p){if(o.propertyIsEnumerable){return o.propertyIsEnumerable(p);}
for(var prop in o){if(prop==p)return true;}
return false;}

function setCookie(cookieName,cookieValue,nMilliSecs,path){if(nMilliSecs){var thisMoment=new Date();var expire=new Date();expire.setTime(thisMoment.getTime()+nMilliSecs);}
document.cookie=cookieName+"="+encodeURIComponent(cookieValue)+"; "+
(nMilliSecs?"expires="+expire.toGMTString()+"; ":"")+"path="+(path||'/')+"; domain=."+
window.location.hostname.replace(/^.*(facebook\..*)$/i,'$1');}
function clearCookie(cookieName){document.cookie=cookieName+"=; expires=Mon, 26 Jul 1997 05:00:00 GMT; "+"path=/; domain=."+
window.location.hostname.replace(/^.*(facebook\..*)$/i,'$1');}
function getCookie(name){var nameEQ=name+"=";var ca=document.cookie.split(';');for(i=0;i<ca.length;i++){var c=ca[i];while(c.charAt(0)==' ')c=c.substring(1,c.length);if(c.indexOf(nameEQ)==0){return decodeURIComponent(c.substring(nameEQ.length,c.length))}}
return null;}
function transferCookieToComTld(cookieName,handler){handler=handler||bagofholding;var cookieNames;if(cookieName instanceof Array){cookieNames=cookieName;}else{cookieNames=[cookieName];}
var data={};for(var i=0;i<cookieNames.length;i++){var value=getCookie(cookieNames[i]);if(value){data[cookieNames[i]]=value;}}
var domain=window.location.hostname.replace(/facebook.*/,'facebook.com');var uri='http://'+domain+'/common/cookie_transfer.php';new AsyncSignal(uri,data).setHandler(handler).send();}

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];}};

function rand32(){return Math.floor(Math.random()*4294967295);}

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);}}

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

function Presence(user,name,firstName,serverTime,popoutType,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+=Vector2.getElementDimensions($('intern_bookmark_frame')).y;}
this.maxTabHeight=viewportDimensions.y-this.maxTabOffset;this.updateServerTime(serverTime);this.pageLoadTime=this.getTime();this._init(popoutType);}
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,POPOUT_TYPE_CHAT:1,POPOUT_TYPE_VIDEOCHAT:2,_init:function(popoutType){this.resizeHandlers=[];this.stateStorers=[];this.stateLoaders=[];this.msgHandlers=[];this.shutdownHandlers=[];this.restartHandlers=[];this.startHandlers=[];this.tabCloseHandlers=[];this.tabOpenHandlers=[];this.windowID=rand32()+1;this.contentPaddings={'buddy_list':54,'presence_notifications':23,'presence_applications':43};if(this.sitevars.FL_LIVE){this.contentPaddings['buddy_list']=77;}
this.contentResized={};this.holder=$('presence');this.holderUI=$('presence_ui');this.bar=$('presence_bar');this.popoutSidebar=ge('presence_popout_sidebar');this.popoutWidth=this.defWidth;this.popoutHeight=this.defHeight;this.cookiePoller=null;this.heartbeat=null;this.resizeTimeout=null;this.lastResized=0;this.stateUpdateTime=0;this.loaded=false;this.isShutdown=false;this.isShuttingDown=false;this.isRestarting=false;this.isPermaShutdown=false;this.shutdownTime=0;this.popoutClicked=false;this.popinClicked=false;this.justPoppedOut=false;this.disableTabAutoClose=0;this.syncPaused=0;this.disableUnfocus=null;this.tempTabCloseHandler=null;this.inPopoutWindow=popoutType==this.POPOUT_TYPE_CHAT;this.inVideoChat=popoutType==this.POPOUT_TYPE_VIDEOCHAT;this.inVideoChatWith=null;this.poppedOut=this.inPopoutWindow;presenceCookieManager.register('state',this._getCookieData.bind(this));if(this.inPopoutWindow){Util.fallbackErrorHandler=null;if(!this.inVideoChat){this.bar.style.marginRight='200px';}
if(!this.inVideoChat){onbeforeunloadRegister(this.popin.bind(this,false));onunloadRegister(this.popin.bind(this,false));}}
Event.listen(window,'resize',this._windowOnResize.bind(this));Event.listen(window,'keypress',this._documentKeyPress.bind(this));Event.listen(document,'click',this._documentOnClick.bind(this));if(DOMScroll.usingScrollWrapper()){DOMScroll.registerScrollChangeHandler(this._handleScrollChange.bind(this));}
Arbiter.subscribe(Arbiter.PAGE_TRANSITION,this.checkRebuild.bind(this));var safari=ua.safari();this.isSafari2=(safari&&safari<500);this.isOpera=(ua.opera()>0);var ff=ua.firefox();this.isFF2=(ff&&ff<3);this.isWindows=ua.windows();this.load();this._windowOnResize.bind(this).defer();if(this.inPopoutWindow){setTimeout(this._windowOnResize.bind(this),3000);}},updateServerTime:function(serverTime){this.timeSkew=(new Date()).getTime()-serverTime;},getTime:function(){return(new Date()).getTime()-this.timeSkew;},debug:function(msg){},warn:function(msg){Util.warn('chirp: '+msg);},error:function(msg){Util.error('chirp: '+msg);},inVideoCallTo:function(to){this.inVideoChatWith=to;},load:function(){var presenceState=presenceCookieManager.getSubCookie('state');if(!presenceState){this.debug('presence: got null state cookie, loading with current state');this._load(this._getCookieData());return;}
try{this._load(presenceState);}catch(e){this.error('presence: got load exception: '+e.toString());this._load(this._getCookieData());}},_load:function(presenceState){this.syncPaused++;this.stateUpdateTime=verifyNumber(presenceState.ut);this.popoutTime=verifyNumber(presenceState.pt);this.popoutWidth=verifyNumber(presenceState.w);this.popoutHeight=verifyNumber(presenceState.h);if(!this.popoutWidth){this.popoutWidth=this.defWidth;}
if(!this.popoutWidth){this.popoutWidth=this.defHeight;}
this.popoutWidth=Math.max(this.popoutWidth,this.minWidth);this.popoutHeight=Math.max(this.popoutHeight,this.minHeight);this.poppedOut=!!presenceState.p;if(this.poppedOut){if(this.inPopoutWindow){if(!this.heartbeat&&!this.inVideoChat){this.heartbeat=setInterval(this._popoutHeartbeat.bind(this),this.popoutHeartbeatTime);}}else{CSS.addClass(this.holder,'popped_out');}}else if(!this.inVideoChat){if(this.inPopoutWindow){if(!this.loaded){this.poppedOut=true;this.doSync();}else{if(!this.popinClicked){window.close();}else{}}}else{this.justPoppedOut=true;}
CSS.removeClass(this.holder,'popped_out');}
if(!this.inPopoutWindow&&!this.cookiePoller){this.cookiePoller=setInterval(this._pollCookie.bind(this),this.cookiePollTime);}
this.virtPopoutWidth=this.popoutWidth;this.virtPopoutHeight=this.popoutHeight;this.state=presenceState;for(var i=0;i<this.stateLoaders.length;i++){this.stateLoaders[i](presenceState);}
this._handleResize.bind(this,0,0).defer();setTimeout(this._handleResize.bind(this,0,0),100);this.syncPaused--;this.loaded=true;},_pollCookie:function(){var presenceState=presenceCookieManager.getSubCookie('state');if(!presenceState){return;}
var myPopoutTime=this.popoutTime;if(presenceState.ut>this.stateUpdateTime){this.load(presenceState);return;}
if(this.poppedOut&&!this.inPopoutWindow){var cookiePopoutTime=verifyNumber(presenceState.pt);var diff=(new Date()).getTime()-cookiePopoutTime;var diffAllowance=this.popoutHeartbeatTime+this.popoutHeartbeatAllowance;if(this.justPoppedOut){if(cookiePopoutTime==myPopoutTime){diffAllowance+=this.popoutHeartbeatFirstAllowance;}else{this.justPoppedOut=false;}}
this.popoutTime=cookiePopoutTime;if(diff>diffAllowance){this.poppedOut=false;this.doSync();}}},_popoutHeartbeat:function(){this._pollCookie();if(this.poppedOut){presenceCookieManager.store();}},_getCookieData:function(){var presenceState={p:this.poppedOut?1:0,w:this.popoutWidth,h:this.popoutHeight,ut:this.stateUpdateTime,pt:this.inPopoutWindow?(new Date()).getTime():this.popoutTime};for(var i=0;i<this.stateStorers.length;i++){presenceState=this.stateStorers[i](presenceState);}
this.state=presenceState;return this.state;},doSync:function(immediate){if(this.syncPaused){return;}
if(immediate)
this._doSync();else{this._doSync.bind(this).defer();}},_doSync:function(){this.stateUpdateTime=(new Date()).getTime();presenceCookieManager.store();this._load(this.state);},pauseSync:function(){this.syncPaused++;},resumeSync:function(){this.syncPaused--;this.doSync();},handleMsg:function(channel,obj){this._handleMsg.bind(this,channel,obj).defer();},_handleMsg:function(channel,obj){if(typeof obj=='string'){if(obj=='shutdown'){this.connectionShutdown();}else if(obj=='restart'){if(this.isShutdown){this.restart();}}
return;}
if(this.isShutdown){return false;}
if(obj.type=='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.inVideoChat){return;}
if(this.inPopoutWindow||this.poppedOut){this.popin(true);return;}
if(this.popoutClicked){return;}
this.popoutClicked=true;var width=this.popoutWidth;var height=this.popoutHeight;if(this.isSafari2){width=this.minWidth;height=this.minHeight;}
var w=window.open(this.popoutURL,"fbChatWindow","status=0,toolbar=0,location=0,menubar=0,"+"directories=0,resizable=1,scrollbars=0,"+"width="+width+",height="+height+","+"left="+this.defX+",top="+this.defY);if(width!=this.popoutWidth||height!=this.popoutHeight){w.resizeBy(this.popoutWidth-width,this.popoutHeight-height);}
CSS.removeClass(this.holder,'popped_out');this.poppedOut=true;this.justPoppedOut=true;this.popoutTime=(new Date()).getTime();this.doSync();this.popoutClicked=false;},popin:function(shouldClose){if(this.inVideoChat){return;}
if(typeof shouldClose=='undefined'){shouldClose=true;}
if(this.inPopoutWindow){if(this.popinClicked){return;}
this.popinClicked=true;}
this.poppedOut=false;this.doSync();if(this.inPopoutWindow&&shouldClose){window.close();}},_windowOnResize:function(){this.contentResized={};var viewportDimensions=Vector2.getViewportDimensions();this._handleResize(viewportDimensions.x-this.virtPopoutWidth,viewportDimensions.y-this.virtPopoutHeight);if(this.inPopoutWindow){clearTimeout(this.resizeTimeout);this.lastResized=(new Date()).getTime();this.resizeTimeout=setTimeout(function(){this.resizeTimeout=null;if((new Date()).getTime()>=this.lastResized+this.resizeStopTime){this._stopResize();}}.bind(this),this.resizeStopTime);if(viewportDimensions.x<this.popoutWidth||viewportDimensions.y<this.popoutHeight){try{window.resizeTo(this.popoutWidth,this.popoutHeight);this._stopResize();}catch(e){}}}else{this._updateMaxTabHeight();}},_updateMaxTabHeight:function(){this.maxTabHeight=Vector2.getViewportDimensions().y-this.maxTabOffset;if(DOMScroll.usingScrollWrapper()&&DOMScroll.getScrollState().x){this.maxTabHeight-=DOMScroll.getScrollbarSize();}
if(window.buddyList&&buddyList.buddyListOpen){buddyList.resizeTab();}else if(this.focusedWrapper&&this.focusedContent){this.tabContentResize(this.focusedWrapper,this.focusedContent);}},_handleScrollChange:function(type,message){if(!DOMScroll.usingScrollWrapper()){return;}
var scrollbarSize=DOMScroll.getScrollbarSize();var holderBottom=this.getHolderBottomPosition();var holderUIRight=15+(message.is_scrolled.y?scrollbarSize:0);CSS.setStyle(this.holder,'bottom',holderBottom+'px');CSS.setStyle(this.holderUI,'marginRight',holderUIRight+'px');if(typeof chatDisplay!='undefined'){for(var id in chatDisplay.tabs){chatDisplay.tabs[id].adjustWrapperBottom();}}
this._updateMaxTabHeight();},getHolderBottomPosition:function(){var holderBottom=0;if(DOMScroll.getScrollState().x){var scrollbarSize=DOMScroll.getScrollbarSize();holderBottom=scrollbarSize+(ua.osx()?1:0);}
if(presence.isIE6){holderBottom--;}
return holderBottom;},_handleResize:function(dx,dy){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(typeof buddyListDisplay!='undefined'&&buddyListDisplay.isFlyoutOpen()){buddyListDisplay.closeOpenFlyout();return;}
if(!buddyList.isSticky()){buddyList.closeTab();}}else{this.closeTab();}},allowAutoClose:function(){if(this.disableTabAutoClose>0){this.disableTabAutoClose--;}},disallowAutoClose:function(){this.disableTabAutoClose++;},tabHandleMouseOver:function(tab){this.disallowAutoClose();CSS.addClass(tab,'hover');},tabHandleMouseOut:function(tab){this.allowAutoClose();CSS.removeClass(tab,'hover');},tabContentMouseOver:function(){this.disallowAutoClose();},tabContentMouseOut:function(){this.allowAutoClose();},_unfocus:function(){if(this.focusedWrapper){hide(this.focusedWrapper);}
if(this.focusedTab){CSS.removeClass(ge(this.focusedTab),'focused');if(this.tempTabCloseHandler){this.tempTabCloseHandler();this.tempTabCloseHandler=null;}}
this.wasFocusedTab=this.focusedTab;this.focusedTab=this.focusedWrapper=null;return this.wasFocusedTab;},unfocus:function(){var wasFocusedTab=this._unfocus();if(wasFocusedTab){this.disableUnfocus=wasFocusedTab;setTimeout(function(){this.disableUnfocus=null;}.bind(this),50);}},toggleTab:function(wrapperID,tabID,scrollContentID){var wrapper=ge(wrapperID);var tab=ge(tabID);if(!wrapper||!tab||tabID==this.disableUnfocus){return;}
if(wrapper.style.display=='none'){this.openTab(wrapperID,tabID,scrollContentID);}else{this.closeTab();}},closeTab:function(){var tab=this.focusedTab;if(!tab){return;}
var wasFocusedTab=this.wasFocusedTab;this.unfocus();CSS.removeClass(tab,'focused');CSS.removeClass(this.holder,'tab_open');for(var i=0;i<this.tabCloseHandlers.length;i++){this.tabCloseHandlers[i](tab);}
if(tab!=wasFocusedTab&&wasFocusedTab=='buddy_list_tab'){buddyList.openTab();}},openTabDelayed:function(wrapperID,tabID,scrollContentID){this.openTab.bind(this,wrapperID,tabID,scrollContentID).defer();},openTab:function(wrapperID,tabID,scrollContentID){if(this.focusedTab==tabID){return;}
this._unfocus();this.focusedWrapper=wrapperID;this.focusedContent=scrollContentID;this.focusedTab=tabID;this.disableUnfocus=this.focusedTab;setTimeout(function(){this.disableUnfocus=null;}.bind(this),50);if(scrollContentID&&!this.contentResized[scrollContentID]){ge(wrapperID).style.visibility='hidden';show(wrapperID);this.tabContentResize(wrapperID,scrollContentID);ge(wrapperID).style.visibility='';}else{show(wrapperID);}
CSS.addClass(ge(tabID),'focused');CSS.addClass(this.holder,'tab_open');for(var i=0;i<this.tabOpenHandlers.length;i++){this.tabOpenHandlers[i](tabID);}},contentChanged:function(contentID){delete this.contentResized[contentID];},tabContentResize:function(wrapperID,contentID,forceLockHeight){if(this.poppedOut||this.inVideoChat){return;}
var content=ge(contentID);var wrapper=ge(wrapperID);if(!content||!wrapper){return;}
var contentWrapper=content.parentNode;if(this.focusedWrapper==wrapperID){this.contentResized[contentID]=true;}
if(!this.contentPaddings[wrapperID]){var dimWrapper=Vector2.getHiddenElementDimensions(wrapper);var dimContentWrapper=Vector2.getHiddenElementDimensions(contentWrapper);this.contentPaddings[wrapperID]=dimWrapper.y-dimContentWrapper.y;}
if(ua.ie()<8){contentWrapper.style.height='auto';dimContent=Vector2.getHiddenElementDimensions(contentWrapper);}else{dimContent=Vector2.getHiddenElementDimensions(content);}
var maxContentHeight=this.maxTabHeight-this.contentPaddings[wrapperID];if(dimContent.y&&dimContent.y<maxContentHeight){CSS.removeClass(contentWrapper,'scroll');contentWrapper.style.height=forceLockHeight?(dimContent.y+'px'):'auto';}else{CSS.addClass(contentWrapper,'scroll');contentWrapper.style.height=maxContentHeight+'px';}},pauseOffClick:function(tabID){this.disableUnfocus=tabID;},resumeOffClick:function(){this.disableUnfocus=null;},renderLink:function(href,text,extra){return'<a href="'+href+'"'+
(this.inPopoutWindow||this.inVideoChat?' target="_blank"':'')+
(extra?extra:'')+'>'+text+'</a>';},checkRebuild:function(){if(this.isShutdown&&!this.isPermaShutdown){channelManager.rebuild(ChannelRebuildReasons.PageTransitionRetry);}},getErrorDescription:function(asyncResponse){var error=asyncResponse.getError();var desc=asyncResponse.getErrorDescription();if(!desc){desc=_tx("An error occurred.");}
if(error==kError_Async_NotLoggedIn){desc=_tx("Your session has timed out. Please login.");}
return desc;},showAsyncError:function(asyncResponse,title){if(typeof title=='undefined'||!title){var chat=_tx("Chat");title=_tx("Facebook Chat Error");}
var desc=this.getErrorDescription(asyncResponse);new ErrorDialog().showError(title,desc);},showTransportError:function(asyncResponse,title){if(typeof title=='undefined'||!title){var chat=_tx("Chat");title=_tx("Facebook Chat Error");}
var desc=_tx("Could not connect to Facebook {Chat} at this time.",{'Chat':_tx("Chat")});new ErrorDialog().showError(title,desc);this.warn("presence: got async transport error: "+asyncResponse.getErrorDescription());},checkLoginError:function(asyncResponse){var error=asyncResponse.getError();if(error==kError_Async_NotLoggedIn||error==kError_Async_LoginChanged||error==kError_Async_CSRFCheckFailed||error==kError_Login_GenericError){this.loginShutdown();return true;}
return false;},checkMaintenanceError:function(asyncResponse){if(asyncResponse.getError()==1356007){this.maintenanceShutdown();return true;}
return false;},permaShutdown:function(){this.isPermaShutdown=true;this.shutdown();},loginShutdown:function(){var reason=_tx("Your session has timed out. Please login.");this.shutdown(false,reason);},connectionShutdown:function(shouldDelay){var reason=_tx("Could not connect to Facebook {Chat} at this time.",{'Chat':_tx("Chat")});this.shutdown(shouldDelay,reason);},maintenanceShutdown:function(){var reason=_tx("Facebook {Chat} is down for maintenance at this time.",{'Chat':_tx("Chat")});this.shutdown(false,reason);channelManager.stop();},versionShutdown:function(){var reason=_tx("Please refresh the page to get the latest version of Facebook {Chat}.",{'Chat':_tx("Chat")});this.shutdown(false,reason);channelManager.stop();},shutdown:function(shouldDelay,reason){this.isRestarting=false;this.isShuttingDown=true;var now=(new Date()).getTime();this.shutdownTime=now;if(!shouldDelay){this._shutdown(reason,0);}else{setTimeout(this._shutdown.bind(this,reason,now),this.shutdownDelay);}},_shutdown:function(reason,shutdownTime){if(!this.isShuttingDown&&shutdownTime==this.shutdownTime){return;}
if(shutdownTime&&this.isShutdown){return;}
if(typeof reason!='string'||!reason){reason=_tx("Facebook {Chat} is experiencing technical problems.",{'Chat':_tx("Chat")});}
if(!this.inPopoutWindow){CSS.addClass(this.holder,'presence_error');set_inner_html($('presence_error_reason'),reason);}else{if(this.shutdownErrorDialog){this.shutdownErrorDialog.hide();}
this.shutdownErrorDialog=new ErrorDialog().setTitle(_tx("Facebook Chat Error")).setBody(reason).show();}
if(this.isShutdown){return;}
this.warn("presence: shutting down");this.isShutdown=true;Arbiter.inform(Presence.ARBITER_SHUTDOWN,{sender:this});for(var i=0;i<this.shutdownHandlers.length;i++){this.shutdownHandlers[i]();}},restart:function(shouldDelay){this.isShuttingDown=false;this.isRestarting=true;if(!shouldDelay){this._restart(0);}else{setTimeout(this._restart.bind(this,this.shutdownTime),this.restartDelay);}},_restart:function(shutdownTime){if(!this.isRestarting||(shutdownTime&&shutdownTime!=this.shutdownTime)){return;}
this.debug("presence: restarting");this.isShutdown=false;this.load();Arbiter.inform(Presence.ARBITER_RESTART,{sender:this});for(var i=0;i<this.restartHandlers.length;i++){this.restartHandlers[i]();}
if(!this.inPopoutWindow){CSS.removeClass(this.holder,'presence_error');}else{if(this.shutdownErrorDialog){this.shutdownErrorDialog.hide();}}},start:function(){for(var i=0;i<this.startHandlers.length;i++){this.startHandlers[i]();}},registerResizeHandler:function(fn){this.resizeHandlers.push(fn);},registerStateStorer:function(fn){this.stateStorers.push(fn);},registerStateLoader:function(fn){this.stateLoaders.push(fn);},registerMsgHandler:function(fn){this.msgHandlers.push(fn);},registerShutdownHandler:function(fn){this.shutdownHandlers.push(fn);},registerRestartHandler:function(fn){this.restartHandlers.push(fn);},registerStartHandler:function(fn){this.startHandlers.push(fn);},registerTabOpenHandler:function(fn){this.tabOpenHandlers.push(fn);},registerTabCloseHandler:function(fn){this.tabCloseHandlers.push(fn);},registerTempTabCloseHandler:function(handler){this.tempTabCloseHandler=handler;}};function getFirstName(name){var words=name.split(" ");var fname=words[0];var flen=fname.length;if(typeof words[1]!='undefined'&&(flen==1||(flen==2&&fname.indexOf('.')!=-1)||(flen==3&&fname.toLowerCase()=='the'))){fname+=' '+words[1];}
return fname;}
function verifyNumber(num){if(typeof num=='undefined'||isNaN(num)||num==Number.POSITIVE_INFINITY||num==Number.NEGATIVE_INFINITY){num=0;}
return num;}

function 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';var request_data=URI.getRequestURI().getQueryData();var query_data={};for(key in request_data){if(key.indexOf('buddy')==0){query_data[key]=request_data[key];}}
if(query_data){uri=new URI(uri).setQueryData(query_data);}
this.async=new AsyncRequest().setInitialHandler(this._initialHandler.bind(this,this.updateNumber)).setHandler(this._onResponse.bind(this,asyncHandlers,bypassTimer)).setErrorHandler(this._onError.bind(this,asyncHandlers)).setTransportErrorHandler(this._onTransportError.bind(this,asyncHandlers)).setOption('suppressErrorAlerts',true).setData(asyncData).setURI(uri).send();}};

function 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,{showReportDialog:function(applicationName,hideHandler,reportHandler,cancelHandler){var hide_button={name:'hide',label:_tx("Hide all"),handler:hideHandler};var report_button={name:'report',label:_tx("Report Spam"),handler:reportHandler};var cancel_button={};copy_properties(cancel_button,Dialog.CANCEL);cancel_button.handler=cancelHandler;new Dialog().setTitle(_tx("Do you want to hide all notifications from {application-name}?",{'application-name':applicationName})).setBody(_tx("This will hide all notifications from this application. ")).setButtons([hide_button,report_button,cancel_button]).setModal().show();},markAppNotificationSpam:function(applicationId,platformType,isSpamReport){var params={app_id:applicationId,collapse:1,type:platformType};if(isSpamReport){params.spam=1;}
new AsyncSignal('/ajax/notifications.php',params).send();},UPDATER_NAME:'notifications'});copy_properties(ChatNotifications.prototype,{_init:function(){this.cookieName='notifications_'+this.user;this.markReadAsync=null;this.markupCached=null;this.beepsExpiredToken=null;this.appHideCache=[];this.updateCheckCount=0;this.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(ChatNotifications.UPDATER_NAME,this._checkUpdater.bind(this),this._onUpdaterResponse.bind(this),this._onUpdaterError.bind(this),this._onUpdaterError.bind(this));presenceCookieManager.register('ntf',this._getCookieData.bind(this));},notifyRead:function(alertsRead){var data=null;if(alertsRead){data={alert_ids:alertsRead};}
AsyncRequest.pingURI('/ajax/presence/notifications_read.php',data);},markRead:function(skipAsyncRequest,alertsRead,numUnread){if(this.countNew==0){return;}
this.countNew=numUnread?numUnread:0;this._updateCount();if(!skipAsyncRequest){this.notifyRead(alertsRead);}
var unreads=[];if(alertsRead){for(var i=0;i<alertsRead.length;i++){var element_id='div#notification_'+alertsRead[i]+'.notif_unread';var match=DOM.scry(this.content,element_id);if(match.length==1){unreads.push(match[0]);}}}else{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;},requiresUpdate:function(time,asyncData,forceUpdate){if(!buddyList._checkUpdater(time,{},forceUpdate)){return false;}
if(asyncData&&undefined!=asyncData[ChatNotifications.UPDATER_NAME]){return asyncData[ChatNotifications.UPDATER_NAME];}
return forceUpdate||((100/(this.updateCheckCount+1))<=presence.sitevars.NOTIFICATIONS_PIGGYBACK_PERCENTAGE);},_checkUpdater:function(time,asyncData,forceUpdate){if(!buddyList._checkUpdater(time,{},forceUpdate)){return false;}
if(this.requiresUpdate(time,{},forceUpdate)){this.updateCheckCount=0;asyncData['notif_latest']=this.latest_notif_time;asyncData['notif_latest_read']=this.latest_read_notif_time;asyncData[ChatNotifications.UPDATER_NAME]=1;return true;}else{this.updateCheckCount++;asyncData[ChatNotifications.UPDATER_NAME]=0;}
return false;},_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._updateDisplayDelayed.bind(this));}else{this._updateDisplayDelayed();}
Arbiter.inform(Arbiter.NEW_NOTIFICATIONS,notificationResponse);}},_updateDisplayDelayed:function(){if(typeof Beeper!='undefined'){this.beepsExpiredToken=Arbiter.subscribe(Arbiter.BEEPS_EXPIRED,this._updateDisplay.bind(this));}else{this._updateDisplay();}},_updateDisplay:function(){if(!this.content||!this.markupCached){return;}
set_inner_html(this.content,this.markupCached);for(var i=0;i<this.appHideCache.length;i++){this.hideNotifications(this.appHideCache[i],true);}
this.markupCached=null;this.appHideCache=[];this._updateCount();if(this.beepsExpiredToken){Arbiter.unsubscribe(this.beepsExpiredToken);}},_onUpdaterError:function(response){},_updateCount:function(){if(this.countSpan){this.countSpan.innerHTML=this.countNew?'<strong>'+this.countNew+'</strong>':'';}},hideNotifications:function(app_id,cached){var 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 is_spam_report=('report'==button_name);ChatNotifications.markAppNotificationSpam(app_id,platform_type,is_spam_report);(typeof(toggleType)=='function')&&(typeof(hidden)!='undefined')&&(!hidden[app_id])&&toggleType(app_id,true,null,false,true,presence.user,false,platform_type);};var hide_handler=bind(this,hide_handler,'hide');var report_handler=bind(this,hide_handler,'report');var cancel_handler=function(){presence.allowAutoClose();};var app_name=this.app_names[app_id];ChatNotifications.showReportDialog(app_name,hide_handler,report_handler,cancel_handler);presence.disallowAutoClose();return false;},_handleMsg:function(channel,obj){if(obj.type=='notification'){presenceUpdater.runHandler('notifications');return true;}else if(obj.type=='notifications_read'){if(typeof Beeper!='undefined'){Beeper.getInstance().markRead(true,obj.alert_ids);}
this.markRead(true,obj.alert_ids,obj.num_unread);return true;}}});

function UserActivity(){}
copy_properties(UserActivity,{_initialized:false,_listeners:[],initialize:function(){var activityFn=function(event){Arbiter.inform(Arbiter.USER_ACTIVITY,event);};UserActivity._listeners.push(Event.listen(document.body,'mouseover',activityFn));var key_context=window;if(ua.ie()){key_context=document.body;}
UserActivity._listeners.push(Event.listen(key_context,'keydown',activityFn));UserActivity._listeners.push(Event.listen(document.body,'click',activityFn));UserActivity._initialized=true;},subscribe:function(callback){if(!UserActivity._initialized){UserActivity.initialize();}
return Arbiter.subscribe(Arbiter.USER_ACTIVITY,callback,Arbiter.SUBSCRIBE_NEW);}});onloadRegister(UserActivity.initialize);

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+'#'+encodeURIComponent(src);return HistoryManager;},getIframeSrcFragment:function(){return decodeURIComponent(URI(HistoryManager.iframe.contentWindow.document.location.href).getFragment());},nextframe:function(frame,replace){if(replace){HistoryManager._setIframeSrcFragment(frame);return;}
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);}},isInitialized:function(){return!!HistoryManager._initialized;},init:function(){if(URI.getRequestURI(false).getProtocol().toLowerCase()=='https'){return;}
if(!env_get('ALLOW_TRANSITION_IN_IFRAME')&&window!=window.top){return;}
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:'0',height:'0',frameborder:'0',left:'0',top:'0',position:'absolute'});onloadRegister(function(){HistoryManager._setIframeSrcFragment(cur_fragment);document.body.insertBefore(HistoryManager.iframe,document.body.firstChild);});}else{setInterval(HistoryManager.checkURI,42,false);}
HistoryManager._updateRefererURI(URI.getRequestURI(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;},_updateRefererURI:function(uri){uri=uri.toString();if(uri.charAt(0)!='/'&&uri.indexOf('//')==-1){return;}
setCookie('x-referer',URI(uri).getQualifiedURI().setFragment('').toString());},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,replace);}}else if(!HistoryManager.user){go_or_replace(window.location,window.location.href.split('#')[0]+'#'+dst,replace);}
if(now){HistoryManager.notify(dst);}
HistoryManager._updateRefererURI(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);}
HistoryManager._updateRefererURI(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(URI.getRequestURI(false).getProtocol().toLowerCase()=='https'){return;}
if(!env_get('ALLOW_TRANSITION_IN_IFRAME')&&window!=window.top){return;}
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,_next_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,prepend){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.');}
if(prepend){PageTransitions._transition_handlers.unshift(transition_handler);}else{PageTransitions._transition_handlers.push(transition_handler);}},getCurrentURI:function(suppress_warning){if(!PageTransitions._current_uri&&!suppress_warning){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);},getMostRecentURI:function(){return new URI(PageTransitions._most_recent_uri);},getNextURI:function(){return new URI(PageTransitions._next_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;},_rewriteSubDomain:function(uri){uri=URI(uri);var domain=uri.getDomain();if(domain.indexOf('apps.')===0){var cur_domain=URI.getRequestURI().getDomain();uri.addQueryData({_fb_qsub:domain}).setDomain(cur_domain);}
return uri;},_revertSubDomain:function(uri){uri=URI(uri);var query_data=uri.getQueryData();if('_fb_qsub'in query_data){var old_domain=query_data._fb_qsub;uri.removeQueryData('_fb_qsub').setDomain(old_domain).setProtocol(URI().getProtocol());}
return uri;},go:function(uri,replace){var qualified_uri=new URI(uri).removeQueryData('quickling').getQualifiedURI();qualified_uri=PageTransitions._rewriteSubDomain(qualified_uri);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{qualified_uri=PageTransitions._revertSubDomain(qualified_uri);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){uri_s=PageTransitions._revertSubDomain(uri_s);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.restoreScrollPosition();_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.restoreScrollPosition();},_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();},restoreScrollPosition: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){var uri=new URI(target_url);if(location_obj.pathname=='/'&&uri.getPath()!='/'&&uri.isQuicklingEnabled()){var query_data=location_obj.search?{}:{q:''};uri=new URI().setPath('/').setQueryData(query_data).setFragment(uri.getUnqualifiedURI()).toString();}
target_url=uri.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';}}};

function UIIntentionalStream(root,newest,oldest,hiddenCount,hiddenIDCount,storyCount,hasAdditionalStories){if(!root){throw new Error('UIIntentionalStream instantiated with no root.');}
copy_properties(this,{id:root.id,root:root,newest:newest,oldest:oldest,hiddenCount:hiddenCount,hiddenIDCount:hiddenIDCount,storyCount:storyCount,hasAdditionalStories:hasAdditionalStories,isAutoRefreshing:false,storyInterval:null,lastRefresh:new Date().getTime(),presenceCheckCounter:0,storyQueue:[],storyQueueCount:0,showNewStories:root.find('div.UIIntentionalStream_ShowNewStories'),showNewStoriesMsg:root.find('a.UIIntentionalStream_ShowNewStories_Msg'),pageloadTime:new Date().getTime(),heavyRefreshCount:0,pushRefreshCount:0,pollRefreshCount:0,scrollLoadIsDone:false,loader:root.find('img.UIIntentionalStream_Loader'),error:root.find('div.UIIntentionalStream_Error'),pager:root.find('div.UIIntentionalStream_Pager'),showMore:root.find('div.UIIntentionalStream_ShowMore'),hiddenInfo:root.find('div.UIIntentionalStream_HiddenInfo'),streamContent:root.find('div.UIIntentionalStream_Content'),requestNum:0,firstStory:null,forceRefresh:false});this.setAutoRefreshConfig({});onunloadRegister(this.unload.bind(this));this.userActivity();this.updateFirstStory();this.updatePager();UIIntentionalStream.instance=this;CSS.removeClass(this.pager,'hidden_elem');UserActivity.subscribe(this.userActivity.bind(this));}
UIIntentionalStream.prototype.unload=function(){if(this.logDetail&&this.allowAutoRefresh){var open_time=new Date().getTime()-this.pageloadTime;scribe_log('nile_refresh_detail','unload_stat '+open_time+' '+this.heavyRefreshCount+' '+this.pushRefreshCount+' '+this.pollRefreshCount);}
this.enableAutoRefresh(false);UIIntentionalStream.instance=null;this.clearScrollLoader();}
UIIntentionalStream.handleNewStoryMessage=function(channel,obj){if(obj.type=='feedpub'){var stream=UIIntentionalStream.instance;if(stream&&!stream.queueIsFull()){stream.pushRefreshCount++;stream.updateStream();}
return true;}
return false;}
UIIntentionalStream.callOnInstance=function(fn_name){return function(){if(UIIntentionalStream.instance){var fn=UIIntentionalStream.instance[fn_name];return fn.apply(UIIntentionalStream.instance,arguments);}else{return null;}}}
UIIntentionalStream.prototype.presenceStreamCheck=function(time,asyncData,forceUpdate){if(!this.allowAutoRefresh||!this.presenceLoopPerPoll){return false;}
if(!presenceNotifications.requiresUpdate(time,asyncData,forceUpdate)){return false;}
++this.presenceCheckCounter;if(this.presenceCheckCounter>=this.presenceLoopPerPoll){var extraData=this.getCurrentParams();extraData.newest=this.newest;extraData.last_refresh=this.getMSSinceLastRefresh();asyncData['stream_query']=extraData;this.presenceCheckCounter=0;return true;}
return false;}
UIIntentionalStream.prototype._getUpdateInsertType=function(){if(this.isDarkRefresh){return UIIntentionalStream.REFRESH_DARK;}else if(this.queueNewStories){return UIIntentionalStream.REFRESH_QUEUE;}else{return UIIntentionalStream.REFRESH_PREPEND;}}
UIIntentionalStream.prototype.presenceStreamResponse=function(payload,time){this.lastRefresh=new Date().getTime();this.heavyRefreshCount++;this.handleResponsePayload(0,this._getUpdateInsertType(),payload,true);}
UIIntentionalStream.prototype.setStoryInterval=function(rate){this.storyInterval=rate;return this;}
UIIntentionalStream.prototype.setAutoRefreshConfig=function(config){config=config||{};var long_time=24*60*60*1000;this.allowAutoRefresh=coalesce(config.allow_auto_refresh,false);this.inactiveThreshold=coalesce(config.inactive_threshold,0);this.activeRefreshTime=coalesce(config.fast_refresh_rate,long_time);this.inactiveRefreshTime=coalesce(config.slow_refresh_rate,long_time);this.allowPolling=coalesce(config.allow_polling,false);this.refreshFactor=coalesce(config.refresh_factor,10);this.queueNewStories=coalesce(config.queue_new_stories,true);this.isDarkRefresh=coalesce(config.dark,false);this.presenceLoopPerPoll=coalesce(config.presence_loop_per_poll,0);this.maxQueueSize=coalesce(config.max_queue_size,0);this.minRefreshInterval=coalesce(config.min_refresh_interval,60*1000);this.logDetail=coalesce(config.log_detail,false)
return this;}
UIIntentionalStream.prototype.queueIsFull=function(){return(this.maxQueueSize&&this.storyQueueCount>=this.maxQueueSize);}
UIIntentionalStream.prototype.shouldAutoRefresh=function(){return this.isAutoRefreshing&&this.allowAutoRefresh;}
UIIntentionalStream.prototype.userActivity=function(){var wasInactive=this.isInactive();this.lastActivity=(new Date().getTime());if(wasInactive&&this.allowAutoRefresh){this.updateStream();this.schedulePoll(this.getRefreshInterval());}
return true;}
UIIntentionalStream.prototype.getMSSinceLastActivity=function(){return(new Date().getTime())-this.lastActivity;}
UIIntentionalStream.prototype.getMSSinceLastRefresh=function(){return(new Date().getTime())-this.lastRefresh;}
UIIntentionalStream.prototype.isInactive=function(){return this.getMSSinceLastActivity()>this.inactiveThreshold;}
UIIntentionalStream.prototype.getRefreshInterval=function(){if(this.isInactive()){return this.inactiveRefreshTime;}else{if(this.storyInterval!=null){var interval=this.storyInterval*this.refreshFactor;return Math.max(interval,this.activeRefreshTime);}else{return this.activeRefreshTime;}}}
UIIntentionalStream.prototype.enableAutoRefresh=function(enabled,immediate){this.isAutoRefreshing=enabled;if(enabled){var delay=immediate?0:this.getRefreshInterval();this.schedulePoll(delay);}else{this.cancelUpdate();}}
UIIntentionalStream.prototype.cancelUpdate=function(){if(this.updateTask){clearTimeout(this.updateTask);this.updateTask=null;}}
UIIntentionalStream.prototype.schedulePoll=function(delay){this.cancelUpdate();if(this.allowPolling){this.updateTask=setTimeout(this.runUpdatePoll.bind(this),delay);}}
UIIntentionalStream.prototype.runUpdatePoll=function(){this.updateTask=null;if(!this.shouldAutoRefresh()){return;}
if(!(this.queueIsFull()||this.getMSSinceLastRefresh()<this.minRefreshInterval)){this.pollRefreshCount++;this.updateStream();}
this.schedulePoll(this.getRefreshInterval());}
UIIntentionalStream.prototype.updateStream=function(flush_on_complete){if(!this.allowAutoRefresh){return;}
this.loadNewer({showLoader:false,ignoreSelf:true,flushOnComplete:flush_on_complete,insertType:this._getUpdateInsertType()});}
UIIntentionalStream.prototype.clearScrollLoader=function(){if(this.currentScrollListener){this.currentScrollListener.remove();this.currentScrollListener=null;}
this.scrollLoadIsDone=true;}
UIIntentionalStream._getScrollTarget=function(){if(DOMScroll.usingScrollWrapper()){return DOMScroll.getScrollRoot();}else{return window;}}
UIIntentionalStream.prototype.loadMoreOnScroll=function(loadMoreStoryID,count){if(this.scrollLoadIsDone){return;}
var viewport_bottom=Vector2.getViewportDimensions().y;var content_bottom=Vector2.getElementPosition(this.streamContent).y+
Vector2.getElementDimensions(this.streamContent).y;if(content_bottom<viewport_bottom){this.loadOlder({count:count,showLoader:false});this.scrollLoadIsDone=true;return;}
var targetY=Vector2.getElementPosition($(loadMoreStoryID)).y;var scrollTarget=UIIntentionalStream._getScrollTarget();var ref=Event.listen(scrollTarget,'scroll',function(){var y=Vector2.getScrollPosition().y;if(y>targetY){this.clearScrollLoader();this.loadOlder({count:count,showLoader:false});}
return true;}.bind(this));this.currentScrollListener=ref;}
UIIntentionalStream.prototype.updatePageCache=function(){this.loadNewer({bundleAsync:true,showLoader:false});}
UIIntentionalStream.prototype.getID=function(){return this.id;}
UIIntentionalStream.prototype.showPositioned=function(element,type,kwargs){if(type==UIIntentionalStream.REFRESH_APPEND){this.root.appendContent(element);}else if(type==UIIntentionalStream.REFRESH_PREPEND){this.root.prependContent(element);}else if(type==UIIntentionalStream.REFRESH_EXPAND){DOM.insertAfter($(kwargs.expandStoryID),element);}
element.setStyle('display','block');if(element.src){element.src=element.src;}}
UIIntentionalStream.showHidden=function(){var req=URI.getRequestURI();req.addQueryData({'show_hidden':true});goURI(req);DOMScroll.scrollTo($('home_stream'),false);return false;}
UIIntentionalStream.prototype.showHiddenPeople=function(filterKey){this.forceRefresh=false;if(filterKey==undefined){filterKey=this.getCurrentFilterKey();}
var async=new AsyncRequest().setMethod('GET').setReadOnly(true).setURI('/ajax/feed/hidden_people_settings.php').setData({filter_key:filterKey});new Dialog().setAsync(async).setCloseHandler(function(){if(this.forceRefresh){var data=this.getCurrentParams();this.refresh(UIIntentionalStream.REFRESH_TRANSITION,data);DOMScroll.scrollTo($('home_stream'),false);}}.bind(this)).show();return false;}
UIIntentionalStream.prototype.setAutoUpdate=function(checkbox,checkedValue,uncheckedValue){this.forceRefresh=true;var value;if(checkbox.checked){value=checkedValue;}else{value=uncheckedValue;}
new AsyncRequest().setURI('/ajax/feed/filter_action.php').setData({filter_key:this.getCurrentFilterKey(),action:'auto_update',value:value}).send();}
UIIntentionalStream.prototype.getCurrentFilterKey=function(){var params=this.getCurrentParams();if(params){return params.filter;}
return null;}
UIIntentionalStream.prototype.addToNewsFeed=function(data){this.forceRefresh=true;new AsyncRequest().setURI('/ajax/feed/filter_action.php').setData({filter_key:this.getCurrentFilterKey(),action:data.action,value:data.id}).setHandler(function(payload){ObjectBrowserController.getController(data.element).removeItem(data.id);}).send();}
UIIntentionalStream.prototype.loadOlder=function(kwargs){kwargs=kwargs||{};if(!this.oldest){return;}
var params=this.getCurrentParams();params.oldest=this.oldest;if(kwargs.count){params.delay_load_count=kwargs.count;}
this.refresh(UIIntentionalStream.REFRESH_APPEND,params,kwargs);return this;}
UIIntentionalStream.prototype.loadNewer=function(kwargs){if(!this.newest){return;}
kwargs=kwargs||{};var extraData=this.getCurrentParams();extraData.newest=this.newest;if(kwargs.ignoreSelf){extraData.ignore_self=true;}
var type=coalesce(kwargs.insertType,UIIntentionalStream.REFRESH_PREPEND);this.lastRefresh=new Date().getTime();this.refresh(type,extraData,kwargs);return this;}
UIIntentionalStream.prototype.getCurrentParams=function(){var params={};var qdata=URI.getRequestURI(true,true).getQueryData();var valid_param=this.getValidParams();if(valid_param){valid_param.forEach(function(i){params[i]=qdata[i];});}else{params=qdata;}
params.hidden_count=this.hiddenCount||0;return params;}
UIIntentionalStream.prototype.refresh=function(type,data,kwargs){kwargs=kwargs||{};var requestNum=++this.requestNum;var bundleAsync=coalesce(kwargs.bundleAsync,false);var showLoader=coalesce(kwargs.showLoader,true);var handler=function(response){UIIntentionalStream.instance.handleResponse(requestNum,type,response,kwargs);};var errHandler=function(response){UIIntentionalStream.instance.handleError(requestNum,type,response);};var finallyHandler=function(response){UIIntentionalStream.instance.handleFinally(type,response);};if(!data.request_type){data.request_type='none';}
var is_replayable=true;if(data.newest){is_replayable=false;}
new AsyncRequest().setURI(this.getEndpoint()).setReadOnly(true).setOption('retries',0).setMethod('GET').setData(data).setOption('bundle',bundleAsync).setReplayable(is_replayable).setHandler(handler).setErrorHandler(errHandler).setTransportErrorHandler(errHandler).setFinallyHandler(finallyHandler).send();if(type==UIIntentionalStream.REFRESH_TRANSITION){DOM.empty(this.streamContent);this.storyCount=0;this.hasAdditionalStories=true;hide(this.pager);this.clearQueue();this.clearScrollLoader();this.oldest=this.newest=null;}
if(showLoader){this.showPositioned(this.loader,type,kwargs);}}
UIIntentionalStream.prototype.updateFirstStory=function(content){content=$(content||this.streamContent);var story=content.scry(UIIntentionalStream.FIRST_STORY_SELECTOR)[0];if(this.firstStory){CSS.removeClass(this.firstStory,UIIntentionalStream.FIRST_STORY_CLASS);}
if(story){CSS.addClass(story,UIIntentionalStream.FIRST_STORY_CLASS);}
this.firstStory=story;}
UIIntentionalStream.prototype.addContent=function(content,delay){CSS.addClass(content,UIIntentionalStream.FIRST_STORY_CLASS);this.addContentPrepend($N('div',{className:'UIStream'},content),delay);}
UIIntentionalStream.prototype.addContentPrepend=function(content,delay){this.updateFirstStory(content);if(ua.ie()<=7){CSS.setStyle(content,'display','none');this.streamContent.prependContent(content);setTimeout(function(){CSS.setStyle(content,'display','');},delay);}else{CSS.setStyle(content,'overflow','hidden');CSS.setStyle(content,'height','0px');CSS.setOpacity(content,'0');this.streamContent.prependContent(content);var anim=animation(content).to('height','auto').to('opacity','1').duration(UIIntentionalStream.ANIMATION_DURATION);if(delay){setTimeout(anim.go.bind(anim),delay);}else{anim.go();}}}
UIIntentionalStream.prototype.addContentAppend=function(content){this.streamContent.appendContent(content);this.clearFirst(content);}
UIIntentionalStream.prototype.unfollow=function(data){var asyncData={value:data.id,action:'unfollow',filter_key:this.getCurrentFilterKey()};var asyncHandler=function(){var count=UIIntentionalStream.forEachStory(data.id,hide);this.hiddenCount+=count;this.hiddenIDCount++;this.updatePager();}.bind(this);new AsyncRequest().setURI('/ajax/feed/filter_action.php').setData(asyncData).setReplayable(true).setHandler(asyncHandler).send();var selected_story=$(data.storyID);var msg_div=$N('div',{className:'unfollow_message'});var undo_link=$N('a',{className:'unfollow_undo','href':'#'},HTML(_tx("Undo")));var show_hidden_link=$N('a',{onclick:this.showHiddenPeople.shield(this)},HTML(_tx("Edit Options")));undo_link.listen('click',this.undoUnfollow.bind(this,data,msg_div));var unfollow_msg;if(!data.isApp){unfollow_msg=_tx("<strong>{name} has been hidden from your News Feed.<\/strong><br>In the future, you won't see posts from {first_name}.  ",{'name':data.name,'first_name':data.firstName});}else{unfollow_msg=_tx("<strong>{application} has been hidden from your News Feed.<\/strong><br>In the future, you won't see posts from {application}.  ",{'application':data.name});}
msg_content=[undo_link,HTML(unfollow_msg),' (',show_hidden_link,')'];msg_div.setContent($N('p',msg_content));hide(msg_div);DOM.insertBefore(msg_div,selected_story);var count=UIIntentionalStream.forEachStory(data.id,hide);CSS.setOpacity(msg_div,'0');show(msg_div);if(count>1){DOMScroll.scrollTo(msg_div,false,true);}
animation(msg_div).to('opacity','1').duration(UIIntentionalStream.ANIMATION_DURATION).ondone(function(){setTimeout(function(){animation(msg_div).to('opacity','0').checkpoint().ease(animation.ease.both).to('height','0').to('padding','0').blind().duration(UIIntentionalStream.ANIMATION_DURATION).ondone(function(){if(msg_div.parentNode){msg_div.remove();}}).go();},10*1000);}).go();return false;}
UIIntentionalStream.forEachStory=function(id,fn){var stories=UIIntentionalStream.getStoriesByAssoc(id);stories.forEach(fn);return stories.length;}
UIIntentionalStream.prototype.undoUnfollow=function(data,msg_div){var asyncData={value:data.id,action:'undo_unfollow',filter_key:this.getCurrentFilterKey()};var asyncHandler=function(){var count=UIIntentionalStream.forEachStory(data.id,show);this.hiddenCount-=count;this.hiddenIDCount--;this.updatePager();}.bind(this);new AsyncRequest().setURI('/ajax/feed/filter_action.php').setData(asyncData).setReplayable(true).setHandler(asyncHandler).send();var count=UIIntentionalStream.forEachStory(data.id,show);if(count>1){DOMScroll.scrollTo(msg_div,false,true);}
msg_div.remove();return false;}
UIIntentionalStream.prototype.updatePager=function(){var show_hidden_link=null;var edit_prefs_link=null;if(this.hiddenCount>0){var story_count_text;if(this.hiddenCount==1){story_count_text=_tx("1 Hidden Post");}else{story_count_text=_tx("{count} Hidden Posts",{'count':this.hiddenCount});}
show_hidden_link=$N('a',{href:'#'},_tx("Show {count-stories}",{'count-stories':story_count_text}));Event.listen(show_hidden_link,'click',UIIntentionalStream.showHidden);}
if(this.hiddenIDCount>0){edit_prefs_link=$N('a',{href:'#'},_tx("Edit Options"));Event.listen(edit_prefs_link,'click',this.showHiddenPeople.shield(this));}
var bottom_info='';if(show_hidden_link&&edit_prefs_link){bottom_info=[show_hidden_link,HTML(' &#183; '),edit_prefs_link];}else if(show_hidden_link){bottom_info=[show_hidden_link];}else if(edit_prefs_link){bottom_info=[edit_prefs_link];}
if(!this.storyCount||!this.hasAdditionalStories){hide(this.showMore);}else{show(this.showMore);}
if(!this.storyCount){if(this.hiddenIDCount){show(this.pager);}else{hide(this.pager);}}else{show(this.pager);}
DOM.setContent(this.hiddenInfo,bottom_info);}
UIIntentionalStream.getStoriesByAssoc=function(assoc){return DOM.scry(UIIntentionalStream.instance.root,'div.aid_'+assoc);}
UIIntentionalStream.prototype.handleResponse=function(requestNum,type,response,kwargs){return this.handleResponsePayload(requestNum,type,response.getPayload(),response.isReplay(),kwargs);}
UIIntentionalStream.prototype.handleResponsePayload=function(requestNum,type,payload,ignore_request_num,kwargs){kwargs=kwargs||{};if(is_empty(payload)){return;}
if(payload.autoRefreshConfig){this.setAutoRefreshConfig(payload.autoRefreshConfig);}
hide(this.loader);hide(this.error);if(!ignore_request_num&&requestNum!=this.requestNum){return;}
this.hiddenCount=payload.hiddenCount;this.hiddenIDCount=payload.hiddenIDCount;this.storyCount+=payload.storyCount;if('newestStoryTime'in payload&&payload.newestStoryTime>this.newest){this.newest=payload.newestStoryTime;}
if('oldestStoryTime'in payload&&(!this.oldest||payload.oldestStoryTime<this.oldest)){this.oldest=payload.oldestStoryTime;}
if('hasAdditionalStories'in payload){this.hasAdditionalStories=payload.hasAdditionalStories;}else if(type==UIIntentionalStream.REFRESH_APPEND&&payload.storyCount==0){this.hasAdditionalStories=false;}
this.updatePager();if(payload.html){var content=HTML(payload.html).getRootNode();switch(type){case UIIntentionalStream.REFRESH_QUEUE:this.queueStories(content,payload.storyCount);break;case UIIntentionalStream.REFRESH_PREPEND:this.addContentPrepend(content);break;case UIIntentionalStream.REFRESH_APPEND:this.addContentAppend(content);this.clearScrollLoader();break;case UIIntentionalStream.REFRESH_TRANSITION:this.streamContent.setContent(content);this.updateFirstStory();break;case UIIntentionalStream.REFRESH_DARK:break;case UIIntentionalStream.REFRESH_EXPAND:CSS.setStyle(content,'overflow','hidden');CSS.setOpacity(content,'0');DOM.insertAfter($(kwargs.expandStoryID),content);animation(content).to('opacity','1').duration(UIIntentionalStream.ANIMATION_DURATION).go();break;}}
if(kwargs.flushOnComplete){this._flushQueue();}}
UIIntentionalStream.prototype.clearQueue=function(delay){delay=delay||0;this.storyQueue=[];this.storyQueueCount=0;if(delay){setTimeout(function(){animation(this.showNewStories).to('opacity','0').checkpoint().to('height','0').hide().duration(150).go();}.bind(this),delay);}else{hide(this.showNewStories);}}
UIIntentionalStream.prototype.flushQueue=function(){if(this.getMSSinceLastRefresh()<this.minRefreshInterval){this._flushQueue();}else{this.updateStream(true);}}
UIIntentionalStream.prototype._flushQueue=function(){var stories=[];var newStories=$N('div',{className:'UIStream'});this.storyQueue.forEach(function(stream,i){if(i!=0){this.clearFirst(stream);}
newStories.appendContent($A(stream.childNodes));stream.remove();}.bind(this));this.addContentPrepend(newStories);this.clearQueue(UIIntentionalStream.ANIMATION_DURATION);}
UIIntentionalStream.prototype.clearFirst=function(content){var first=DOM.scry(content,UIIntentionalStream.FIRST_STORY_SELECTOR)[0];if(first){CSS.removeClass(first,UIIntentionalStream.FIRST_STORY_CLASS);}}
UIIntentionalStream.prototype.queueStories=function(content,numStories){var showMessage=(this.storyQueueCount==0);hide(content);this.streamContent.prependContent(content);this.storyQueue=[content].concat(this.storyQueue);var countString='';if(numStories){this.storyQueueCount+=numStories;countString=this.storyQueueCount;}
var msg;if(this.storyQueueCount==1){msg=_tx("SHOW 1 NEW POST");}else{msg=_tx("SHOW {count} NEW POSTS",{count:countString});}
this.showNewStoriesMsg.setContent(HTML(msg));if(showMessage){CSS.setStyle(this.showNewStories,'height','0');CSS.setStyle(this.showNewStories,'display','block');animation(this.showNewStories).to('height','auto').to('opacity','1').go();}}
UIIntentionalStream.prototype.handleError=function(requestNum,type,response){if(!response.isReplay()&&requestNum!=this.requestNum){return;}
hide(this.loader);var error=response.getError();if(error==kError_Async_NotLoggedIn){var title=_tx("Feed Error");var msg=_tx("Your session has timed out. Please {login}.",{'login':'<a href="/login.php">'+_tx("log in")+'</a>'});new ErrorDialog().showError(title,msg);}
if(type!=UIIntentionalStream.REFRESH_PREPEND){this.showPositioned(this.error,type);}}
UIIntentionalStream.prototype.handleFinally=function(type){if(type==UIIntentionalStream.REFRESH_TRANSITION){PageTransitions.transitionComplete();}}
UIIntentionalStream.prototype.getValidParams=function(){return UIIntentionalStream.VALID_PARAMS;}
UIIntentionalStream.prototype.getEndpoint=function(){return UIIntentionalStream.ENDPOINT;}
copy_properties(UIIntentionalStream,{ANIMATION_DURATION:300,REFRESH_TRANSITION:1,REFRESH_PREPEND:2,REFRESH_APPEND:3,REFRESH_QUEUE:4,REFRESH_DARK:5,REFRESH_EXPAND:6,FIRST_STORY_CLASS:'UIIntentionalStory_First',FIRST_STORY_SELECTOR:'div.UIIntentionalStory_First',PAGER_SELETOR:'div.UIIntentionalStream_Pager',PAGER_INNER_SELETOR:'div.UIIntentionalStream_PagerInner',VALID_PARAMS:['filter','show_hidden'],ENDPOINT:'/ajax/intent.php',_presenceInit:false});UIIntentionalStream.presenceRegister=function(){if(UIIntentionalStream._presenceInit){return true;}
var checkCB=UIIntentionalStream.callOnInstance('presenceStreamCheck');var responseCB=UIIntentionalStream.callOnInstance('presenceStreamResponse');presenceUpdater.register('stream_update',checkCB,responseCB,bagofholding,bagofholding);presence.registerMsgHandler(UIIntentionalStream.handleNewStoryMessage);UIIntentionalStream._presenceInit=true;};

var FriendListManagerBootstrap={FRIEND_LISTS_CHANGED:'flm_friend_lists_changed',bootstrap:function(selectedList,showCreate){var data={};if(selectedList){data['selected_list']=selectedList;}else if(showCreate){data['show_create']=1;}
var async=new AsyncRequest().setMethod('GET').setReadOnly(true).setURI('/ajax/friend_lists/manager.php').setData(data);new Dialog().setAsync(async).setButtons(Dialog.OK).setModal().show();return false;}}

function UIHomeFilter(root,assoc_id,item_data,num_visible,data,stream,composer){this.parent.construct(this,root,item_data,num_visible,data);copy_properties(this,{root:root,stream:stream,composer:composer,assoc_id:assoc_id});UIHomeFilter.activate(this,this.stream.getID());var clickHandler=function(){UIHomeFilter.active[this.stream.getID()].each(function(filter){if(this!==filter){filter.deselectAll();}}.bind(this));}.bind(this);this.addClickHandler(clickHandler);this.setOrderChangedHandler(UIHomeFilter.filterOrderChanged.bind(this));var transitionHandler=UIHomeFilter.handlePageTransition.bind(this);PageTransitions.registerHandler(transitionHandler);Arbiter.subscribe(FriendListManagerBootstrap.FRIEND_LISTS_CHANGED,this._listsChanged.bind(this),Arbiter.SUBSCRIBE_NEW);}
UIHomeFilter.extend('UIMutableFilterList');UIHomeFilter.prototype={_listsChanged:function(message,data){if(message==FriendListManagerBootstrap.FRIEND_LISTS_CHANGED){if(data.latest_list){var data={new_key:'fl'+'_'+data.latest_list,id:this.assoc_id};new AsyncRequest().setURI('/ajax/filterlist.php').setData(data).setHandler(function(new_key){goURI(URI('/home.php').addQueryData({filter:new_key}),true);}.bind(null,data.new_key)).send();}else{goURI(URI('/home.php'),true);}}}};UIHomeFilter.handlePageTransition=function(uri){var extraData=uri.getQueryData();if(extraData.disable_nile||extraData.ref||!(uri.getPath()=='/nile.php'||uri.getPath()=='/home.php')){return false;}
var filter=extraData.filter;if(this.composer){var app_id=0;if(filter&&filter.startsWith('app_')){app_id=parseInt(filter.substr(4),10);}
this.composer.loadAttachment(app_id);}
this.stream.refresh(UIIntentionalStream.REFRESH_TRANSITION,extraData);return true;};UIHomeFilter.activate=function(filter,streamID){if(!UIHomeFilter.active[streamID]){UIHomeFilter.active[streamID]=[];}
UIHomeFilter.active[streamID].push(filter);};UIHomeFilter.active={};UIHomeFilter.filterOrderChanged=function(ordered){var shown=[];var hidden=[];for(var i=0;i<ordered.shown.length;i++){shown.push(ordered.shown[i]['filter']);}
for(var i=0;i<ordered.hidden.length;i++){hidden.push(ordered.hidden[i]['filter']);}
var postData={};postData.order=[];postData.visible=shown.length;postData.id=this.assoc_id;postData.order=shown.concat(hidden);new AsyncRequest().setURI('/ajax/filterlist.php').setData(postData).setHandler(bagofholding).send();};

function ads_fetch_admarket_ad(page,location,adnetwork_id,handler,error_handler){var data={'page':page,'location':location,'adnetwork_id':adnetwork_id};var r=new AsyncRequest().setURI(muffinize('/muffins/ajax/fetch_admarket_muffin.php')).setData(data).setHandler(handler).setErrorHandler(error_handler).send();}

function ads_refresh(tab,page,onResponse,onError){if(window.ads_refreshing){return;}
var possible=['sidebar_ads','fadbar','home_sponsor','home_sponsor_nile'];var locations=[];for(var i=0;i<possible.length;i++){if(ge(possible[i])){locations.push(possible[i]);}}
if(locations.length==0){return;}
var data={'page':page,'tab':tab,'locations':locations};var _onResponse=function(response){window.ads_refreshing=false;var divs=response.getPayload();for(var id in divs){if(ge(id)&&divs[id].length>0){$(id).setContent(HTML(HTML(divs[id]).getRootNode().innerHTML));}}
if(onResponse){onResponse(response);}}
var _onError=function(response){window.ads_refreshing=false;if(onError){onError(response);}}
new AsyncRequest().setURI('/ajax/location_refresh.php').setData(data).setOption('bundle',true).setHandler(_onResponse).setErrorHandler(_onError).send();window.ads_refreshing=true;}
function social_ads_pagecache_log_imps(){var ads=DOM.scry(document,'div.pagecache_social_ad');for(var i=0;i<ads.length;i++){var data={'meta':DOMStorage.getData(ads[i],'link_data')};new AsyncRequest().setURI('/ajax/social_ad_impression.php').setOption('bundle',true).setData(data).send();}}

function AdsFeedback(container){this.ad_container=container;this.feedback_div=DOM.find(this.ad_container,'div.ads_feedback');this.thumbs_up=DOM.find(this.ad_container,'a.thumbs_up');this.thumbs_dn=DOM.find(this.ad_container,'a.thumbs_dn');this.disable_if_dn=true;var next_ad_buttons=DOM.scry(this.ad_container,'a.next_ad');if(next_ad_buttons){this.next_ad_button=next_ad_buttons[0];}
this.usage_data=[];this.click_usage_data=[];this.enc_log_data='';this.cancel_btn={name:'cancel',label:_tx("Cancel"),className:'inputaux'};this.buttons=[Dialog.OK,this.cancel_btn];this.thumbs_up.listen('click',this._thumbs_up.bind(this));this.thumbs_dn.listen('click',this._thumbs_dn.bind(this));if(this.next_ad_button){this.next_ad_button.listen('click',this._cycle_muffin.bind(this));}}
copy_properties(AdsFeedback,{K_THUMBS_UP:1,K_THUMBS_DN:0,K_THUMBS_UP_FEEDBACK:1});copy_properties(AdsFeedback.prototype,{_thumbs_dn:function(){this.isPositive=false;this.click_usage_data=this.usage_data.clone();this.click_usage_data.push(AdsFeedback.K_THUMBS_DN);var async=new AsyncRequest().setMethod('GET').setReadOnly(true).setURI(muffinize('/muffins/ajax/feedback.php'));new Dialog().setAsync(async).setButtons(this.buttons).setHandler(this._form_handler.bind(this)).show();return false;},_thumbs_up:function(){this.isPositive=true;this.click_usage_data=this.usage_data.clone();this.click_usage_data.push(AdsFeedback.K_THUMBS_UP,AdsFeedback.K_THUMBS_UP_FEEDBACK,'');hide(this.thumbs_up);hide(this.thumbs_dn);this._log();return false;},_log:function(){var serialized_usage_data=this.click_usage_data.join('|');if(serialized_usage_data){var params='type=usage'+'&params[]='+escapeURI('ads_feedback')+'&params[]='+escapeURI(serialized_usage_data)+'&';new AsyncSignal(muffinize('/muffins/ajax/tracking_log.php?'+params)).send();}
if(this.enc_log_data){var adscribe_params='type=event'+'&params[]='+escapeURI('ads_feedback')+'&params[]='+escapeURI(this.enc_log_data)+'&params[]='+escapeURI(this.isPositive)+'&';new AsyncSignal(muffinize('/muffins/ajax/tracking_log.php?'+adscribe_params)).send();}},_form_handler:function(r){if(r==this.cancel_btn){var reason_value=0;var other_text='';}else if(r==Dialog.OK){var reason_select=$('ads_feedback_select');var reason_value=get_form_select_value(reason_select);var other_text=$('ads_feedback_form_other_text').value;if(!this.isPositive){this._cycle_muffin();if(this.disable_if_dn){this._disable_ad();}}
hide(this.thumbs_up);hide(this.thumbs_dn);}
this.click_usage_data.push(reason_value,other_text);this._log();},_disable_ad:function(){if(this.enc_log_data){var params='ld='+escapeURI(this.enc_log_data)+'&';new AsyncSignal(muffinize('/muffins/ajax/disable_muffin.php?'+params)).send();}},set_usage_data:function(usage_data){this.usage_data=usage_data;return this;},set_log_data:function(enc_log_data){this.enc_log_data=enc_log_data;return this;},_cycle_muffin:abstractMethod});function AdspaceAdsFeedback(container_id){var container=$(container_id);this.parent.construct(this,container);return this;}
AdspaceAdsFeedback.extend('AdsFeedback');copy_properties(AdspaceAdsFeedback.prototype,{_cycle_muffin:function(){var onResponse=function(asyncResponse){var payload=asyncResponse.getPayload();if(payload.html){DOM.replace(this.ad_container,HTML(payload['html']));}else{hide(this.feedback_div);}}.bind(this);var onError=function(asyncResponse){hide(this.feedback_div);}.bind(this);var page=URI.getRequestURI().getPath();ads_fetch_admarket_ad(page,null,null,onResponse,onError);return false;}});function EmuAdsFeedback(container_id){var container=$(container_id);this.parent.construct(this,container);this.disable_if_dn=true;return this;}
EmuAdsFeedback.extend('AdsFeedback');copy_properties(EmuAdsFeedback.prototype,{_cycle_muffin:function(){var onResponse=null;var onError=function(asyncResponse){hide(DOM.find(this.ad_container,'div.ads_feedback'));}.bind(this);var page=URI.getRequestURI().getPath();ads_refresh(null,page,onResponse,onError);return false;}});function AdnetAdspaceAdsFeedback(container_id,ad_location,adnetwork_id){var container=$(container_id);this.parent.construct(this,container);this.ad_location=ad_location;this.adnetwork_id=adnetwork_id;if(window.top.document.domain==window.document.domain){this.dialog_parent=window.top;}else{this.dialog_parent=window;}
this.buttons=this.dialog_parent.Dialog.OK_AND_CANCEL;return this;}
AdnetAdspaceAdsFeedback.extend('AdsFeedback');copy_properties(AdnetAdspaceAdsFeedback.prototype,{_thumbs_dn:function(){this.isPositive=false;this.click_usage_data=this.usage_data.clone();this.click_usage_data.push(AdsFeedback.K_THUMBS_DN);var async=new AsyncRequest().setMethod('GET').setReadOnly(true).setURI(muffinize('/muffins/ajax/feedback.php'));new this.dialog_parent.Dialog().setAsync(async).setButtons(this.buttons).setHandler(this._form_handler.bind(this)).show();return false;},_form_handler:function(r){if(r==this.dialog_parent.Dialog.OK){var reason_select=this.dialog_parent.DOM.getElement('ads_feedback_select');var reason_value=get_form_select_value(reason_select);var other_text=this.dialog_parent.DOM.getElement('ads_feedback_form_other_text').value;if(!this.isPositive){this._disable_ad();this._cycle_muffin();}
hide(this.thumbs_up);hide(this.thumbs_dn);this.click_usage_data.push(reason_value,other_text);this._log();}},_cycle_muffin:function(){var onResponse=function(asyncResponse){var payload=asyncResponse.getPayload();if(payload.html){DOM.replace(this.ad_container,HTML(payload['html']));}else{hide(this.feedback_div);}}.bind(this);var onError=function(asyncResponse){hide(this.feedback_div);}.bind(this);var page=URI.getRequestURI().getPath();ads_fetch_admarket_ad(page,this.ad_location,this.adnetwork_id,onResponse,onError);return false;}});function ads_feedback_select_onchange(){var select_elem=$('ads_feedback_select');var selected_index=select_elem.selectedIndex;if(selected_index==select_elem.options.length-1){show($('ads_feedback_form_other_text'));}else{hide($('ads_feedback_form_other_text'));}}

function DOMControl(root){copy_properties(this,{root:root&&$(root),updating:false});if(root){root.getControl=identity.bind(null,this);}}
copy_properties(DOMControl.prototype,{getRoot:function(){return this.root;},beginUpdate:function(){if(this.updating){return false;}
this.updating=true;return true;},endUpdate:function(){this.updating=false;},update:function(e){if(!this.beginUpdate()){return this;}
this.onupdate(e);this.endUpdate();}});

function TextInputControl(textinput){this.parent.construct(this,textinput);copy_properties(this,{placeholderText:null,maxLength:this.getRoot().maxLength||null,radio:null,focused:false,interval:null,nativePlaceholder:false});var r=this.getRoot();if((String(r.type).toLowerCase()=='search')&&ua.safari()){this.nativePlaceholder=true;this.setPlaceholderText(r.getAttribute('placeholder'));}
addEventBase(r,'focus',this.onfocus.bind(this));addEventBase(r,'blur',this.onblur.bind(this));var up=this.update.bind(this);Event.listen(r,'keydown',up);Event.listen(r,'keyup',up);Event.listen(r,'keypress',up);this.setFocused(false);}
TextInputControl.extend('DOMControl');copy_properties(TextInputControl.prototype,{associateWithRadioButton:function(element){this.radio=element&&$(element);return this;},setMaxLength:function(maxlength){this.maxLength=maxlength;this.getRoot().maxLength=this.maxLength||null;return this;},getValue:function(){if(!this.focused&&this.getRoot().value==this.placeholderText){return null;}
return this.getRoot().value;},isEmpty:function(){var v=this.getValue();return(v===null||v=='');},setValue:function(value){this.getRoot().value=value;this.update();return this;},clear:function(){return this.setValue('');},isFocused:function(){return this.focused;},setFocused:function(focused){var empty=this.isEmpty();this.focused=focused;if(this.placeholderText&&!this.nativePlaceholder){var r=this.getRoot();var v=r.value;if(this.focused){CSS.removeClass(r,'DOMControl_placeholder');if(empty){this.clear();}}else if(empty){CSS.addClass(r,'DOMControl_placeholder');this.setValue(this.placeholderText);}}
this.update();return this;},setPlaceholderText:function(text){this.placeholderText=text;if(this.nativePlaceholder){this.getRoot().setAttribute('placeholder',text);}
return this.setFocused(this.isFocused());},getPlaceholderText:function(){return this.placeholderText;},onupdate:function(){if(this.radio){if(this.focused){this.radio.checked=true;}}
var root=this.getRoot();if(this.maxLength>0){if(root.value.length>this.maxLength){var value=root.value;var remove_length=value.length-this.maxLength;var pos_pair=DOM.getCaretPosition(root);var remove_behind_pos=pos_pair.end||value.length;root.value=value.substring(0,remove_behind_pos-remove_length)+
value.substring(remove_behind_pos);if(typeof pos_pair.start!='undefined'){DOM.setCaretPosition(root,pos_pair.start,Math.max(pos_pair.start,pos_pair.end-remove_length));}}}
this.setFocused(this.focused);},onfocus:function(){this.setFocused(true);if(this.interval){clearInterval(this.interval);}
this.interval=setInterval(this.update.bind(this),150);return this;},onblur:function(){this.setFocused(false);if(this.interval){this.interval=clearInterval(this.interval);}
return this;}});function placeholderSetup(id){if(!ge(id)){Util.warn('Setting up a placeholder for an element which does not exist: %q.',id);return;}
if(!$(id).getAttribute('placeholder')){Util.warn('Setting up a placeholder for an element with no placeholder text: %q.',id);return;}
return new TextInputControl($(id)).setPlaceholderText($(id).getAttribute('placeholder'));}

function TextAreaControl(textarea){copy_properties(this,{autogrow:false,shadow:null,originalHeight:null,metricsValue:null});this.parent.construct(this,textarea);};TextAreaControl.extend('TextInputControl');copy_properties(TextAreaControl.prototype,{setAutogrow:function(autogrow){this.autogrow=autogrow;this.refreshShadow();CSS.addClass(this.getRoot(),'DOMControl_autogrow');return this;},onupdate:function(){this.parent.onupdate();var r=this.getRoot();if(this.autogrow&&r.value!=this.metricsValue){this.metricsValue=r.value;if(CSS.getStyle(r,'fontSize')==""){return false;}
copy_properties(this.shadow.style,{fontSize:parseInt(CSS.getStyle(r,'fontSize'),10)+'px',fontFamily:CSS.getStyle(r,'fontFamily'),width:(Vector2.getElementDimensions(r).x-8)+'px'});DOM.setContent(this.shadow,HTML(htmlize(r.value)));if(this.isEmpty()&&this.originalHeight){r.style.height=this.originalHeight+'px';}else{r.style.height=Math.max(this.originalHeight,Vector2.getElementDimensions(this.shadow).y+15)+'px';}}},refreshShadow:function(){if(this.autogrow){this.shadow=$N('div',{className:'DOMControl_shadow'});DOM.getRootElement().appendChild(this.shadow);var r=this.getRoot();this.originalHeight=parseInt(CSS.getStyle(r,'height'))||Vector2.getElementDimensions(this.getRoot()).y;}else{if(this.shadow){DOM.remove(this.shadow);}
this.shadow=null;}}});function autogrow_textarea(element){element=$(element);if(!element._hascontrol){element._hascontrol=true;new TextAreaControl(element).setAutogrow(true);}}

function gen_unique(){return++gen_unique._counter;}
gen_unique._counter=0;function create_hidden_input(name,value){return $N('input',{name:name,id:name,value:value,type:'hidden'});}
var KEYS={BACKSPACE:8,TAB:9,RETURN:13,ESC:27,SPACE:32,LEFT:37,UP:38,RIGHT:39,DOWN:40,DELETE:46};var KeyCodes={Up:63232,Down:63233,Left:63234,Right:63235};function getTableRowShownDisplayProperty(){if(ua.ie()<8){return'inline';}else{return'table-row';}}
function showTableRow()
{for(var i=0;i<arguments.length;i++){var element=ge(arguments[i]);if(element&&element.style)element.style.display=getTableRowShownDisplayProperty();}
return false;}
function getParentRow(el){el=ge(el);while(el.tagName&&el.tagName!="TR"){el=el.parentNode;}
return el;}
function adjustImage(obj){var block=obj.parentNode;while(CSS.getStyle(block,'display')!='block'&&block.parentNode){block=block.parentNode;}
var width=block.offsetWidth;if(obj.offsetWidth>width){try{if(ua.ie()<8){var img_div=document.createElement('div');img_div.style.filter='progid:DXImageTransform.Microsoft.AlphaImageLoader(src="'+obj.src.replace('"','%22')+'", sizingMethod="scale")';img_div.style.width=width+'px';img_div.style.height=Math.floor(((width/obj.offsetWidth)*obj.offsetHeight))+'px';if(obj.parentNode.tagName=='A'){img_div.style.cursor='pointer';}
obj.parentNode.insertBefore(img_div,obj);obj.parentNode.removeChild(obj);}else{throw 1;}}catch(e){obj.style.width=width+'px';}}
CSS.removeClass(obj,'img_loading');}
function imageConstrainSize(src,maxX,maxY,placeholderid){var image=new Image();image.onload=function(){if(image.width>0&&image.height>0){var width=image.width;var height=image.height;if(width>maxX||height>maxY){var desired_ratio=maxY/maxX;var actual_ratio=height/width;if(actual_ratio>desired_ratio){width=width*(maxY/height);height=maxY;}else{height=height*(maxX/width);width=maxX;}}
var placeholder=ge(placeholderid);if(placeholder){var newimage=document.createElement('img');newimage.src=src;newimage.width=width;newimage.height=height;placeholder.parentNode.insertBefore(newimage,placeholder);placeholder.parentNode.removeChild(placeholder);}}}
image.src=src;}
function require_password_confirmation(onsuccess,oncancel){if((!getCookie('sid')||getCookie('sid')=='0')||getCookie('pk')){onsuccess();return;}
require_password_confirmation.onsuccess=onsuccess;require_password_confirmation.oncancel=oncancel;(new pop_dialog()).show_ajax_dialog('/ajax/password_check_dialog.php');}
function search_validate(search_input_id){var search_input=$(search_input_id);if(search_input.value!=""&&search_input.value!=search_input.getAttribute('placeholder')){return true;}else{search_input.focus();return false;}}
function abTest(data,inline)
{AsyncRequest.pingURI('/ajax/abtest.php',{data:data,"post_form_id":null},true);if(!inline){return true;}}
function ac(metadata)
{new AsyncSignal('/ajax/ac.php',{'meta':metadata}).send();return true;}
function alc(metadata)
{AsyncRequest.pingURI('/ajax/alc.php',{'meta':metadata},true);return true;}
function scribe_log(category,message){AsyncRequest.pingURI('/ajax/scribe_log.php',{'category':category,'message':message,'post_form_id':null},true);}
function image_has_loaded(obj){try{if((obj.mimeType!=null&&obj.complete&&obj.mimeType!='')||(obj.naturalHeight!=null&&obj.complete&&obj.naturalHeight!=0)){return true;}else if(ua.safari()<3){var new_image=new Image();new_image.src=obj.src;if(new_image.complete==true){return true;}
delete new_image;}}catch(exception){return true;}}
function image_has_failed(obj){if((obj.complete==null&&obj.width==20&&obj.height==20)||(obj.mimeType!=null&&obj.complete&&obj.mimeType=='')||(obj.naturalHeight!=null&&obj.complete&&obj.naturalHeight==0)){return true;}}
function show_search_profile(user_id){var async=new AsyncRequest().setURI('/ajax/search_profile.php').setData({id:user_id}).setMethod('GET').setReadOnly(true);new Dialog().setAsync(async).setButtons(Dialog.CLOSE).setContentWidth(490).show();}
function _search_profile_link_handler(link){var uri=new URI(link.href);if(uri.getPath()=='/s.php'){var query=uri.getQueryData();if(query.k==100000080){show_search_profile(query.id);return false;}}}
onloadRegister(function(){LinkController.registerHandler(_search_profile_link_handler);});function warn_if_unsaved(form_id){var form=ge(form_id);if(!form){Util.error("warn_if_unsaved couldn't find form in order to save its "
+"original state.  This is probably because you called "
+"render_start_form_with_unsaved_warning to render a form, "
+"but then didn't echo it into page.  To get around this, you "
+"can call render_start_form, and then call warn_if_unsaved "
+"yourself once you've caused the form to appear.");return;}
if(!_unsaved_forms_to_check_for){_unsaved_forms_to_check_for={};LinkController.registerHandler(_check_for_unsaved_forms);}
form.original_state=serialize_form(form);_unsaved_forms_to_check_for[form_id]=true;}
function _check_for_unsaved_forms(link){for(var form_id in _unsaved_forms_to_check_for){var form=ge(form_id);if(form&&form.original_state&&!are_equal(form.original_state,serialize_form(form))){var href=link.href;var submit=_find_first_submit_button(form);var buttons=[];if(submit){buttons.push({name:'save',label:_tx("Save"),handler:function(){submit.click();}});}
buttons.push({name:'dont_save',label:_tx("Don't Save"),className:'inputaux',handler:function(){window.location.href=href;}});buttons.push(Dialog.CANCEL);new Dialog().setTitle(_tx("Unsaved Changes")).setBody(_tx("Some of your changes have not been saved.  Would you like to save your changes now?")).setButtons(buttons).setModal().show();return false;}}}
function _find_first_submit_button(root_element){var inputs=root_element.getElementsByTagName('input');for(var i=0;i<inputs.length;++i){if(inputs[i].type.toUpperCase()=='SUBMIT'){return inputs[i];}}
return null;}
_unsaved_forms_to_check_for=undefined;function textLimit(ta,count){var text=ge(ta);if(text.value.length>count){text.value=text.value.substring(0,count);if(arguments.length>2){$(arguments[2]).style.display='block';}}}
function textLimitStrict(text_id,limit,message_id,count_id,submit_id){var text=ge(text_id);if(text){var len=text.value.length;var diff=len-limit;if(diff>0){if(diff>25000){text.value=text.value.substring(0,limit+25000);diff=25000;}
$(message_id).style.display='block';$(count_id).innerHTML=diff;$(submit_id).disabled=true;}else if(len==0){$(message_id).style.display='none';$(submit_id).disabled=true;$(count_id).innerHTML=1;}else{if($(count_id).innerHTML!=0){$(count_id).innerHTML=0;$(message_id).style.display='none';$(submit_id).disabled=false;}}}}
function city_selector_onfound(input,obj){input.value=obj?obj.i:-1;}
function city_selector_onselect(success){if(window[success]){window[success]();}}
onloadRegister(function(){var secrets=[38,38,40,40,37,39,37,39,66,65,13],ii=0;function fn(evt){var kk=evt?evt.keyCode:event.keyCode;if(ii==-1){return;}else if(secrets[ii]==kk){++ii;if(ii==secrets.length){new AsyncRequest('/ajax/lensflare.php').setReadOnly(true).setMethod('GET').send();ii=-1;}}else if(ii){ii=0;}}
addEventBase(document,'keydown',fn);});_bootstrapEventHandlers();if(navigator&&navigator.userAgent&&document.domain.toLowerCase().match(/(^|\.)facebook\..*/)&&!(parseInt((/Gecko\/([0-9]+)/.exec(navigator.userAgent)||[]).pop())<=20060508)){document.domain=window.location.hostname.replace(/^.*(facebook\..*)$/i,'$1');}

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 name="no_picture" 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){CSS.setClass(divs[i],className.replace(/thumbnail_(?:un)?selected/,selected?'thumbnail_selected':'thumbnail_unselected'));}
j++;}
this.label.innerHTML=_tx("{selected} of {total}",{selected:(index+1),total:j});CSS.setClass(this.left,this.left.className.replace(/[^ ]+abled/,index==0?'disabled':'enabled'));CSS.setClass(this.right,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;DOM.getRootElement().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 UrlDetector(element){this.element=element;this.suppress_detection=bagofholding;this.detection_interval=null;this.last_url_scraped=null;this.last_char_count=0;Event.listen(element,'focus',this.startDetectionInterval.bind(this));Event.listen(element,'blur',this.stopDetectionInterval.bind(this));};UrlDetector.mixin('Arbiter',{getText:function(){return this.element.value;},setText:function(text){this.element.value=text;},setSuppressDetectionCheck:function(fn){this.suppress_detection=fn;},startDetectionInterval:function(){if(!this.suppress_detection()){this.detection_interval=setInterval(this.detectionIntervalFire.bind(this),50);}},stopDetectionInterval:function(){clearInterval(this.detection_interval);},detectionIntervalFire:function(){if(this.suppress_detection()){return;}
var char_count=this.getText().length;if((char_count-this.last_char_count)>5||(this.last_char_count==0&&char_count>1)){var pasted_text=true;}
this.last_char_count=char_count;var url=this.detectUrl(pasted_text);if(url){this.inform('urlDetected',url);}},detectUrl:function(pasted_text){var url='';var start_position=-1;var end_position=-1;var text=this.getText();if(pasted_text){if(url=text.match(/www\.\S*/i)){start_position=text.indexOf(url[0]);end_position=start_position+url[0].length;url="http://"+url[0];}else{var match='';if(match=text.match(/(http|fb):\/\/\S*/i)){url=match[0];start_position=text.indexOf(match[0]);end_position=start_position+match[0].length;}}}else{if(url=text.match(/www\.\S*[\s|\)|\!]/i)){start_position=text.indexOf(url[0]);end_position=start_position+url[0].length;url="http://"+url[0];}else{var match='';if(match=text.match(/(http|fb):\/\/\S*[\s|\)|\!]/i)){url=match[0];start_position=text.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(this.element).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.isFbCodeUrl(url)){this.setText(text.substr(0,start_position)+text.substr(end_position));}}else{url='';}}
return url;},isFbCodeUrl:function(url){return url.search('fb:')==0;}});

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 Dialog().setImmediateRendering(true).setClassName('attachment_dialog').setTitle(title).setBody(wrapper).setStackable(true).setButtons([Dialog.newButton('attach',_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)),Dialog.newButton('cancel',_tx("Cancel"),'inputaux',function(){this.dialog.hide();this.remove_attachment_view();this.dialog=null;this.is_active=false;}.bind(this))]).show();var container=ge(this.edit_container_id);var div=document.createElement('div');div.className='share_stage';CSS.addClass(div,'attachment_edit');div.id=this.edit_id;div.is_app=is_app;container.appendChild(div);set_inner_html(div,html);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=document.createElement('div');div.className='share_stage';CSS.addClass(div,'attachment_view');div.id=this.view_id;div.is_app=is_app;container.appendChild(div);set_inner_html(div,html);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);CSS.setClass(attachment_remove,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();Dialog.getCurrent().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._auto_attach_link=function(event,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);}}
attachments.prototype.register_url_detection=function(textarea_id){var detector=new UrlDetector($(textarea_id));detector.subscribe('urlDetected',this._auto_attach_link.bind(this));detector.setSuppressDetectionCheck(function(){return this.attachment_added;}.bind(this));}

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";CSS.setClass(typeaheadpro.iframe,'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,'ty':0,'f':1};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(this._onunload.bind(this),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=null;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){e=$E(e);this.last_key=e?e.keyCode:-1;if(this.key_down==this.last_key){this.key_down=0;}
var return_val=true;switch(this.last_key){case KEYS.ESC:this.selectedindex=-1;this._onselect(false);this.hide();e.stop();return_val=false;break;}
return return_val;}
typeaheadpro.prototype._onkeydown=function(e){e=$E(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){e=$E(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._onunload=function(){if(typeaheadpro.instances[this.instance]){this.hide();}}
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;}
var suggestion_found=true;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('');suggestion_found=false;}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;if(!suggestion_found&&this.ignore_invalid_suggestion){return false;}
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;DOM.empty(this.list);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.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');}
if(i>0&&suggestions[i-1].o<0&&suggestions[i].o>=0){html.push(' typeahead_delimiter');}
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('');node.style.height='auto';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){CSS.setClass(this.obj,(this.obj.className.replace(/typeahead_[^\s]+/g,'')+' '+name).replace(/ {2,}/g,' '));}
typeaheadpro.prototype.dirty_results=function(){if(!this.enumerate&&trim(this.get_value())==''){DOM.empty(this.list);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);this.blur();this.hide();}
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 typeahead_tagger(element,source,options){this.element=$(element);options=copy_properties({delimiter:'@',anchor_block:true,max_display:4,max_results:4,submit_keydown_return:false,auto_select:false},options||{});this.selected=null;source=new search_friend_source(source,true);source.allowTypes([search_friend_source.TYPES.USER,search_friend_source.TYPES.PAGE,search_friend_source.TYPES.APP,search_friend_source.TYPES.GROUP,search_friend_source.TYPES.EVENT]);this.parent.construct(this,element,source,options);CSS.addClass(this.list,'typeahead_tagger');CSS.addClass(this.dropdown,'typeahead_search');this.initializeBuffer();this.initializeEvents();this.hide();}
typeahead_tagger.extend('typeaheadpro');copy_properties(typeahead_tagger.prototype,{set_class:bagofholding,set_value:bagofholding,update_class:bagofholding,clear_placeholder:bagofholding,initializeBuffer:function(){var buffer=$N('input',{type:'text',className:'tagger_buffer'});DOM.appendContent(document.body,buffer);Event.listen(buffer,'blur',this.deselectToken.bind(this));Event.listen(buffer,'keydown',function(event){if(!this.token){return;}
var token=this.token,code=event_get_keypress_keycode(event);if(code==KEYS.BACKSPACE||code==KEYS.DELETE){return this.removeToken(token);}
if(code==KEYS.LEFT||code==KEYS.UP){var prev=token.previousSibling;if(!prev||!this.isText(prev)){prev=document.createTextNode('');DOM.insertBefore(prev,token);}
this.focusNode(prev,prev.length);}
else if(code==KEYS.RIGHT||code==KEYS.DOWN){var next=token.nextSibling;if(!next||!this.isText(next)){next=document.createTextNode('');DOM.insertAfter(token,next);}
this.focusNode(next,0);}
event.kill();}.bind(this));this.buffer=buffer;},initializeEvents:function(){this.shouldClean=!ua.safari();if(!this.shouldClean){return;}
if(document.selection){Event.listen(this.element,'paste',function(){setTimeout(this.cleanup.bind(this),100);}.bind(this));Event.listen(document,'selectionchange',function(){var node=Text.getFocusNode();if(this.isToken(node)){this.selectToken(node);}}.bind(this));}else{var timer,element=this.element;var nodeCount=element.childNodes.length;var charCount=DOM.getText(element).length;var check=function(){if(!this.shouldClean){this.shouldClean=true;return;}
if(Math.abs(nodeCount-element.childNodes.length)>2||Math.abs(charCount-DOM.getText(element).length)>5){this.cleanup();}
this.focusInput();}.bind(this);addEventBase(element,'DOMCharacterDataModified',function(){charCount=DOM.getText(element).length;nodeCount=element.childNodes.length;});addEventBase(element,'DOMNodeInserted',function(){clearTimeout(timer);timer=setTimeout(check,25);});}},show:function(){this.parent.show();this.dropdown.style.width=this.anchor.offsetWidth+'px';},get_value:function(){return Text.getActiveQuery(this.delimiter);},check_value:function(){if(DOM.getText(this.element).lastIndexOf(this.delimiter)==-1){this.hide();return;}
var value=this.get_value();if(value==this.delimiter&&!this.visible){this.set_message('Mention Something');this.show();}
if(value!=this.value){this.dirty_results();this.value=value;}},setup_anchor:function(){return this.element.parentNode.parentNode;},_onblur:function(event){this.fixBR();this.hide();},_onfocus:function(event){this.fixBR();this.deselectToken();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.results_text='';if(this.typeahead_icon){show(this.typeahead_icon);}},_onkeydown:function(event){event=$E(event);var code=event?event_get_keypress_keycode(event):-1;if(window.getSelection){var node=Text.getFocusNode(),offset=Text.getFocusOffset();if((code==KEYS.RIGHT||code==KEYS.DELETE)&&offset==node.length){node=node.nextSibling;}else if((code==KEYS.LEFT||code==KEYS.BACKSPACE)&&offset==0){node=node.previousSibling;}
if(this.isToken(node)){this.selectToken(node);}}else if(code==KEYS.RETURN){Text.insertBreak();event.kill();}
if(this.visible){if(code==KEYS.UP||code==KEYS.DOWN||code==KEYS.RETURN){event.kill();}
return this.parent._onkeydown(event);}},_onkeypress:function(event){if(this.visible){return this.parent._onkeypress(event);}},_onkeyup:function(event){this.check_value();if(this.visible){return this.parent._onkeyup(event);}},_onselect:function(selected){if(!selected){return;}
var value=this.value,nodes=this.element.childNodes;this.shouldClean=false;for(var i=0,l=nodes.length;i<l;i++){var node=nodes[i];if(this.isText(node)){var text=node.data,index=text.lastIndexOf(value,Text.getFocusOffset());if(index>-1){var token=this.createToken(selected);var prefix=document.createTextNode(text.substring(0,index).replace(/\s*$/g,'')+' ');node.data=' '+text.substring(index+value.length).replace(/^\s*/g,'');this.element.insertBefore(token,node);this.element.insertBefore(prefix,token);this.focusAfter(token);break;}}}
this.hide();},fixBR:function(){if(document.selection){return;}
var last=this.element.lastChild;if(!last||!this.isBreak(last)){this.element.appendChild($N('br'));}},createToken:function(obj){var element=this.element,token=$N('a',{className:'token',href:'#'}),input=$N('input',{type:'hidden',name:element.id+'[]',value:obj.i}),spanX=$N('span',{className:'x'});token.unselectable='on';token.contentEditable=false;token.setContent($N('span',$N('span',$N('span',$N('span',[obj.t,input,spanX])))));DOMStorage.setData(token,'token',true);Event.listen(token,'focus',Event.kill);Event.listen(spanX,'click',this.removeToken.bind(this,token));Event.listen(token,'click',this.selectToken.bind(this,token));Event.listen(token,'mousedown',this.selectToken.bind(this,token));return token;},removeToken:function(token){if(!token){return;}
var prev=token.previousSibling||this.element.insertBefore(document.createTextNode(''),token);DOM.remove(token);this.focusNode(prev,prev.length);},selectToken:function(token,event){if(event){event.kill();}
if(!token){return;}
this.deselectToken();CSS.addClass(token,'token_selected');this.token=token;this.buffer.focus();},deselectToken:function(){if(!this.token){return;}
CSS.removeClass(this.token,'token_selected');this.token=null;},focusNode:function(node,offset){if(!node.data){node.data=' ';}
this.normalize();setTimeout(function(){this.element.focus();Text.setFocus(node,offset||0);}.bind(this),0);},focusAfter:function(node){this.normalize();setTimeout(function(){this.element.focus();Text.setFocusAfter(node);}.bind(this),0);},normalize:function(){var node=this.element.firstChild;while(node){var next=node.nextSibling;if(this.isText(node)&&this.isText(next)){node.data+=next.data;this.element.removeChild(next);}else{node=node.nextSibling;}}},cleanup:function(){if(!this.shouldClean){return;}
this.shouldClean=false;var nodes=this.element.childNodes,dirty=false;for(var i=nodes.length;i--;){var node=nodes[i];if(!this.isText(node)&&!this.isToken(node)&&!this.isBreak(node)){this.element.replaceChild(document.createTextNode(DOM.getText(node)),node);dirty=true;}}
if(dirty){this.normalize();}
this.shouldClean=true;},focusInput:function(){this.element.focus();},getMessage:function(){var message='';$A(this.element.childNodes).each(function(node){if(this.isText(node)){message+=node.data;}else if(this.isToken(node)){var input=DOM.find(node,'input');message+='<fb:name uid="'+input.value+'" />';}else if(this.isBreak(node)){message+="\n";}},this);return message;},clearMessage:function(){this.element.empty();},isBreak:function(node){return DOM.isNode(node,'br');},isText:function(node){return DOM.isNode(node,['#text','#whitespace']);},isToken:function(node){return DOM.isNode(node,'a')&&DOMStorage.getData(node,'token');}});var Text=(function(){var functions={insertBreak:bagofholding,getRange:bagofholding,getSelection:bagofholding,getActiveQuery:bagofholding,getFocusNode:bagofholding,getFocusOffset:bagofholding,setFocus:bagofholding,setFocusAfter:bagofholding,setFocusBefore:bagofholding};if(window.getSelection){functions={insertBreak:function(){},getRange:function(selection){selection=selection||this.getSelection();return selection.rangeCount>0?selection.getRangeAt(0):null;},getSelection:function(){return window.getSelection();},getActiveQuery:function(delimiter){var range=this.getRange();var node=this.getFocusNode(range);var value=this.getFocusValue(range,node);var offset=this.getFocusOffset(range,node);if(!range||!range.collapsed||!value){return'';}
var index=value.lastIndexOf(delimiter,offset);var prev=node.previousSibling;if(index<0||(index==0&&prev&&prev.data&&DOM.isNode(prev,['#text','#whitespace']))||(index>0&&(/\w/).test(value.charAt(index-1)))){return'';}
return value.slice(index,offset);},getFocusNode:function(range){range=range||this.getRange();return range.endContainer;},getFocusValue:function(range,node){range=range||this.getRange();node=node||this.getFocusNode(range);return node.data;},getFocusOffset:function(range,node){range=range||this.getRange();return range.endOffset||0;},setFocus:function(node,offset){if(!node){return;}
this.getSelection().collapse(node,offset);},setFocusAfter:function(node,offset){if(!offset&&offset!==0){offset=1;}
this.setFocus(node.nextSibling,offset);},setFocusBefore:function(node,offset){}};}
else if(document.selection){functions={insertBreak:function(){var range=this.getRange();range.pasteHTML('<br/>');range.moveEnd('character',1);range.collapse();range.select();},getRange:function(){return this.getSelection().createRange();},getSelection:function(){return document.selection;},getActiveQuery:function(delimiter){var range=this.getRange();var node=this.getFocusNode(range);var value=this.getFocusValue(range,node);var offset=this.getFocusOffset(range,node);var index=value.lastIndexOf(delimiter,offset);if(index<0||(index>0&&(/\w/).test(value.charAt(index-1)))){return'';}
return value.slice(index,offset);},getFocusNode:function(range){range=range||this.getRange();return range.parentElement();},getFocusValue:function(range,node){range=range||this.getRange();node=node||this.getFocusNode(range);return node.innerText;},getFocusOffset:function(range,node){range=range||this.getRange();node=node||this.getFocusNode(range);var parent=node,offset=0;while(parent==node){range.moveStart('character',-1);parent=range.parentElement();offset++;}
return offset-1;},setFocus:function(node,offset){var range=this.getRange();var element=range.parentElement();var length=0,children=[],prev=node.previousSibling;while(prev){var temp=prev.previousSibling;children.push(element.removeChild(prev));prev=temp;}
range.moveToElementText(element);range.collapse();range.moveEnd('character',(offset+length));range.collapse(false);range.select();for(var i=0;i<children.length;i++){element.insertBefore(children[i],element.firstChild);}},setFocusAfter:function(node){var range=this.getRange();range.moveToElementText(node);range.moveEnd('character',2);range.collapse(false);range.select();},setFocusBefore:function(node){var range=this.getRange();range.moveToElementText(node);range.moveStart('character',-2);range.collapse();range.select();}};}
return functions;})();

function resend_confirmation_email(){hide($('confirm_error'));hide($('confirm_status'));show($('confirm_progress'));new AsyncRequest().setURI('/ajax/confirm_email.php').setData({resend:1}).setHandler(function(response){hide($('confirm_progress'));if(response){var payload=response.getPayload();if(payload&&payload.success){DOM.setContent($('confirm_status'),HTML(payload.msg));show($('confirm_status'));}else{DOM.setContent($('confirm_error'),HTML(payload.msg));show($('confirm_error'));}}else{DOM.setContent($('confirm_error'),HTML(payload.msg));show($('confirm_error'));}}).send();}
function verify_confirmation_code(on_success_fn){hide($('confirm_error'));hide($('confirm_status'));show($('confirm_progress'));var data=serialize_form($('confirm_form'));new AsyncRequest().setURI('/ajax/confirm_email.php').setData(data).setHandler(function(response){hide($('confirm_progress'));if(response){var payload=response.getPayload();if(payload&&payload.success){DOM.setContent($('confirm_status'),HTML(payload.msg));show($('confirm_status'));if(ge('confirm_email_banner')){animation(ge('confirm_email_banner')).to('height',0).hide().go();}
on_success_fn();}else{DOM.setContent($('confirm_error'),HTML(payload.msg));show($('confirm_error'));}}else{DOM.setContent($('confirm_error'),HTML(payload.msg));show($('confirm_error'));}}).send();return false;}
function handle_require_email_conf_response(target_fn,error_fn,precursor_fn,response){if(precursor_fn){precursor_fn();}
if(response){var payload=response.getPayload();if(payload&&payload.require_conf){var confirm_button=Dialog.newButton('confirm_email',_tx("Confirm"),null,bind(null,verify_confirmation_code,function(){Dialog.getCurrent().setAutohide(750);}));var dialog=new Dialog().setTitle(payload.dialog_title).setBody(payload.dialog_body).setButtons([confirm_button,Dialog.CANCEL]).show();}else if(target_fn){target_fn(response);}}else if(error_fn){error_fn(response);}}

function UIComposerAttachmentArea(composer,root){this.composer=composer;this.root=root;this.area=root.find('div.UIComposer_AttachmentArea_Cache');this.cache={};this.visible=null;this.attachment={};this.dirtyOnReset=false;var closeButton=root.find('a.UIComposer_AttachmentArea_CloseButton');Event.listen(closeButton,'click',function(event){Event.kill(event);composer.reset();});}
UIComposerAttachmentArea.prototype={show:function(attachment,extraData){this.composer.addState(UIComposer.STATE.ATTACHMENT_AREA);this.attachment=attachment;this.dirtyOnReset=false;var app_id=attachment.app_id;if(this.cache[app_id]&&!extraData){this.showAttachment(app_id);}else{this.loadAttachment(app_id,extraData);}},loadAttachment:function(app_id,extraData){this.composer.refreshHeight();var data={app_id:app_id,composer_id:this.composer.id,stream_id:this.composer.target_id};if(extraData){copy_properties(data,{data:extraData});}
new AsyncRequest().setURI(UIComposerAttachmentArea.ENDPOINT).setData(data).setHandler(UIComposerAttachmentArea.handleResponse.bind(this,extraData)).setErrorHandler(UIComposer.handleError.bind(this.composer)).setTransportErrorHandler(UIComposer.handleError.bind(this.composer)).send();},showAttachment:function(app_id){if(!this.composer.hasState(UIComposer.STATE.ATTACHMENT_AREA)){return;}
this.visible=this.cache[app_id];this.visible.addClass(UIComposerAttachmentArea.CLASS.VISIBLE);this.composer.addState(UIComposer.STATE.ATTACHMENT_LOADED);this.composer.refreshHeight(this.composer.removeHeight.bind(this.composer));this.fireAttachmentEvent('load');},createAttachment:function(payload){var element=$N('div',{className:UIComposerAttachmentArea.CLASS.CACHED});this.area.appendChild(element).setContent(HTML(payload.html));return element;},setAttachment:function(controller){if(this.attachment){this.attachment.controller=controller;controller.initialize(this.composer,this.cache[this.attachment.app_id],this.attachment.app_id);}
return this;},getAttachment:function(){if(this.attachment&&this.attachment.controller){return this.attachment.controller;}
return null;},getData:function(){if(this.attachment&&this.attachment.controller){return this.attachment.controller.getData();}
return null;},getEndpoint:function(){if(this.attachment&&this.attachment.controller){return this.attachment.controller.getEndpoint();}
return null;},post:function(){if(!this.visible){return;}
var data=this.getData();var endpoint=this.getEndpoint();if(!data||!endpoint){return;}
data.composer_id=this.composer.id;this.composer.removeState(UIComposer.STATE.ATTACHMENT_LOADED);this.composer.refreshHeight();new AsyncRequest().setURI(endpoint).setData(data).setHandler(UIComposerAttachmentArea.handleResponse.bind(this,null)).setErrorHandler(UIComposer.handleError.bind(this.composer)).send();},reset:function(){if(!this.visible){return;}
this.visible.removeClass(UIComposerAttachmentArea.CLASS.VISIBLE);this.visible=null;if(this.dirtyOnReset){var app_id=this.attachment.app_id;this.cache[app_id].remove();this.cache[app_id]=null;}
this.fireAttachmentEvent('reset');},fireAttachmentEvent:function(event){if(this.attachment&&this.attachment.controller){this.attachment.controller[event]();}}};copy_properties(UIComposerAttachmentArea,{handleResponse:function(extraData,response){var app_id=this.attachment.app_id;var attachment=this.cache[app_id];var payload=response.getPayload();var error=response.getError();var errIsWarning=response.getErrorIsWarning();if(error&&errIsWarning){UIComposer.showError(response.getErrorSummary(),response.getErrorDescription());}
if(!attachment){this.cache[app_id]=this.createAttachment(payload);this.dirtyOnReset=!!extraData;}else{attachment.setContent(HTML(payload.html));this.dirtyOnReset=true;}
this.showAttachment(app_id);}});copy_properties(UIComposerAttachmentArea,{CLASS:{CACHED:'UIComposer_Attachment_Cached',VISIBLE:'UIComposer_Attachment_Visible'},ENDPOINT:'/ajax/composer/attachment.php',PARAM_STRUCTURE:'app_data[attachment][params]'});

function UIComposer(root,input,user,overrides){var options={stream:null,target_id:0,endpoint:'/updatestatus.php',attachments:[],context_data:{},clear_message:true,privacy_widget:null,privacy_widget_options:{},input_max_length:0,typeahead_source:null,loc_activated:false};copy_properties(options,overrides);if(!root){throw new Error('UIComposer instantiated with no root.');return false;}
this.id=root.id;this.root=root;this.holder=root.parentNode;this.input=input;this.button=root.find('input.UIComposer_Button');this.last_loc=null;this.user=user;this.stream=options.stream;this.endpoint=options.endpoint;this.target_id=options.target_id;this.context_data=options.context_data;this.clear_message=options.clear_message;this.privacy_widget=options.privacy_widget;this.privacy_widget_options=options.privacy_widget_options;if(options.loc_activated){this.addState(UIComposer.STATE.LOC_ACTIVATED);}
this.shouldHide=true;this.resetState=[root.className,UIComposer.STATE.INPUT_FOCUSED,UIComposer.STATE.ATTACHMENT_LIST].join(' ');this.initializeDialog();this.initializeTextarea(options.input_max_length,options.typeahead_source);this.initializeAttachments(options.attachments);this.initializeEvents();this.clearMessage();UIComposer.storeInstance(this.id,this);onunloadRegister(function(){delete UIComposer.instances[root.id];},true);}
UIComposer.prototype={initializeDialog:function(){var share=Dialog.newButton('share',_tx("Share"),null,function(){this.shouldHide=false;this.post();return false;}.bind(this));var width=this.hasState(UIComposer.STATE.PIC_OUTSIDE)?UIComposer.DIALOG_WIDTH_PIC:UIComposer.DIALOG_WIDTH;this.dialog=new Dialog().setButtons([share,Dialog.CANCEL]).setTitle('Publish Story').setContentWidth(width).setCancelHandler(function(){this.shouldHide=false;this.reset();return false;}.bind(this)).setStackable(true).setModal(true).setBody('');},initializeAttachments:function(attachments){if(!attachments.length){return;}
var action;this.apps=attachments.map(function(attachment){var app_id=attachment.app_id;if(attachment.action!==undefined){action={app:app_id,type:attachment.action};}
return app_id;});this.attachments=attachments;this.attachmentCell=this.root.find('td.UIComposer_TDAttachments');this.attachmentBlind=this.root.find('div.UIComposer_Attachments');this.attachmentRoot=this.root.find('div.UIComposer_AttachmentArea');this.attachmentList=new UIComposerAttachmentList(this,this.attachmentBlind);this.attachmentArea=new UIComposerAttachmentArea(this,this.attachmentRoot);if(action){this.loadAttachment(action.app,action.type);}},initializeTextarea:function(maxLength,typeaheadSource){new TextAreaControl(this.input).setMaxLength(maxLength).setAutogrow(true).onfocus();this.input.onfocus='';var detector=new UrlDetector(this.input);detector.subscribe('urlDetected',this.autoScrape.bind(this));detector.setSuppressDetectionCheck(this.hasState.bind(this,UIComposer.STATE.ATTACHMENT_LOADED));if(!typeaheadSource){return;}
this.initializeTagger(typeaheadSource);},initializeTagger:function(source){if(!source||ua.firefox()<3||ua.safariPreWebkit()){return;}
var input=$N('div',{id:this.input.id,className:'tokenizer',contentEditable:true},document.createTextNode(''));CSS.setStyle(input,'width',this.input.offsetWidth+'px');DOM.replace(this.input,input);this.input=input;var initialize=function(){var tagger=new typeahead_tagger(input,source);this.focusInput=tagger.focusInput.bind(tagger);this.getMessage=tagger.getMessage.bind(tagger);this.clearMessage=tagger.clearMessage.bind(tagger);removeEventBase(input,'focus',initialize);}.bind(this);addEventBase(input,'focus',initialize);},initializeEvents:function(){addEventBase(this.input,'focus',this.focus.bind(this));Event.listen(this.button,'click',this.post.bind(this));var loc_button=this.root.scry('a.UIComposer_LocationButton')[0];if(loc_button){loc_button.listen('click',this.toggleLocSetting.bind(this));}
if(this.attachments){var cancelHide=function(){this.shouldHide=false;}.bind(this);Event.listen(this.root,'click',cancelHide);Event.listen(this.root,'mousedown',cancelHide);Event.listen(document.body,'click',function(){if(this.shouldHide){this.blur();}
this.shouldHide=true;}.bind(this));}},focus:function(){if(this.attachmentList&&!this.hasState(UIComposer.STATE.ATTACHMENT_LIST)&&!this.hasState(UIComposer.STATE.ATTACHMENT_AREA)){this.attachmentList.show();}
if(!this.hasState(UIComposer.STATE.ATTACHMENT_AREA)){this.showPrivacyWidget();this.showLocWidget();if(this.hasState(UIComposer.STATE.LOC_ACTIVATED)){this.populateLoc();}}
return this.addState(UIComposer.STATE.INPUT_FOCUSED);},blur:function(){if(this.privacy_widget&&this.privacy_widget.dialogOpen()){if(!this.privacy_widget_token){this.privacy_widget_token=this.privacy_widget.subscribe('closeDialog',function(){this.privacy_widget.unsubscribe(this.privacy_widget_token);delete this.privacy_widget_token;}.bind(this));}}else{if(this.attachmentList&&this.hasState(UIComposer.STATE.ATTACHMENT_LIST)&&!this.hasState(UIComposer.STATE.ATTACHMENT_AREA)){this.removeState(UIComposer.STATE.INPUT_FOCUSED);this.attachmentList.hide();this.hideLocWidget();if(!this.getMessage()){this.clearMessage();}}
if(!this.hasState(UIComposer.STATE.INPUT_FOCUSED)){this.hidePrivacyWidget();}
this.hidePrivacyWidgetCallout();}
return this;},autoScrape:function(event,url){this.loadAttachment(UIComposer.APP_ID_POSTED,null,{url:url});},attach:function(){this.dialog.hide();CSS.setStyle(this.holder,'paddingTop',this.padding+'px');DOM.prependContent(this.holder,this.root);this.input.focus();},detach:function(callback){this.padding=parseInt(CSS.getStyle(this.holder,'paddingTop'),10);var padding=parseInt(CSS.getStyle(this.root,'marginBottom'),10)
+this.root.offsetHeight
+this.padding;this.dialog.onloadRegister(function(){DOM.find(this.dialog._pd.content,'div.dialog_body').appendChild(this.root);CSS.setStyle(this.holder,'paddingTop',padding+'px');if(callback){setTimeout(callback,500);}}.bind(this)).show();},setAttachment:function(controller){this.attachmentArea.setAttachment(controller);return this;},getAttachment:function(){return this.attachmentArea.getAttachment();},getRequiredHeight:function(){return UIComposer.getVerticalSpace(this.attachmentList.root)
+UIComposer.getVerticalSpace(this.attachmentArea.root);},refreshHeight:function(callback){if(!this.attachmentBlind){return;}
return UIComposer.animation(this.attachmentBlind,callback).to('height',this.getRequiredHeight()+'px').go();},removeHeight:function(){this.attachmentBlind.setStyle('height','');return this;},setAttachmentColSpan:function(colSpan){this.attachmentCell.colSpan=colSpan;return this;},loadAttachment:function(app_id,action,extraData){var attachment=this.attachments[this.apps.indexOf(app_id)];if(this.hasState(UIComposer.STATE.ATTACHMENT_AREA)){this.reset(false,false);}
if(!attachment){this.input.blur();return this.blur();}
if(!action){action=attachment.is_fluid?'select':'swap';}
this.attachmentList[action](attachment,null,extraData);this.focus();},showAttachment:function(attachment,extraData){if(attachment.supports_privacy){this.showPrivacyWidget();}else{this.hidePrivacyWidget();}
this.hideLocWidget();this.setAttachmentColSpan(1);this.attachmentArea.show(attachment,extraData);return this;},reset:function(clearMessage,focusInput){var callback=bagofholding;if(this.root.parentNode!=this.holder){callback=this.attach.bind(this);}
if(this.attachments){this.attachmentBlind.setStyle('height',this.getRequiredHeight()+'px');this.attachmentList.reset();this.attachmentArea.reset();this.setAttachmentColSpan(2);}
CSS.setClass(this.root,this.resetState);this.removeLoc();this.refreshHeight(callback);this.enable();if(clearMessage){this.clearMessage();}
if(focusInput!==false){this.focusInput();}
this.shouldHide=true;return this;},addState:function(state){this.root.addClass(state);return this;},removeState:function(state){this.root.removeClass(state);return this;},hasState:function(state){return this.root.hasClass(state);},toggleState:function(state){CSS.toggleClass(this.root,state);return this;},disable:function(){this.input.disabled=true;this.addState(UIComposer.STATE.INPUT_DISABLED).disableButton();return this;},enable:function(){this.input.disabled=false;this.removeState(UIComposer.STATE.INPUT_DISABLED).enableButton();return this;},disableButton:function(){var dialogButton=this.dialog.getButtonElement('share');if(dialogButton){dialogButton.disabled=true;dialogButton.addClass('inputsubmit_disabled');}
this.button.disabled=true;this.addState(UIComposer.STATE.BUTTON_DISABLED);return this;},enableButton:function(){var dialogButton=this.dialog.getButtonElement('share');if(dialogButton){dialogButton.disabled=false;dialogButton.removeClass('inputsubmit_disabled');}
this.button.disabled=false;this.removeState(UIComposer.STATE.BUTTON_DISABLED);return this;},isDisabled:function(){return this.input.disabled||this.button.disabled;},getPrivacyData:function(){if(this.privacy_widget){return this.privacy_widget.getData();}
return null;},getData:function(endpoint){var data={};var message=this.getMessage();if(message&&message.indexOf('<fb:name')>0){Util.log(message);return null;}
if(endpoint==this.endpoint){if(!message){return null;}
copy_properties(data,this.target_id>0?UIComposer.TARGET_DATA:UIComposer.HOME_DATA);copy_properties(data,{status:message,target_id:this.target_id,profile_id:this.user,privacy_data:{}});if(this.last_loc){this.last_loc.timestamp=Math.floor(this.last_loc.timestamp.getTime()/1000);data.composer_loc_data=JSON.encode(this.last_loc);}
if(this.attachmentArea&&this.attachmentArea.visible){copy_properties(data,this.attachmentArea.getData());}}else{data=this.attachmentArea.getData();if(data){copy_properties(data,{id:this.user,target_id:this.target_id,app_id:this.attachmentArea.attachment.app_id,action:'post',button:'publish_button',comment_text:message});if(this.attachmentArea.attachment.supports_privacy){data.privacy_data={};}}}
if(data){data.composer_id=this.id;if(this.privacy_widget&&data.privacy_data){copy_properties(data.privacy_data,this.getPrivacyData());}
if(this.context_data){copy_properties(data,this.context_data);}}
return data;},getEndpoint:function(){var endpoint;if(this.hasState(UIComposer.STATE.ATTACHMENT_LOADED)){endpoint=this.attachmentArea.getEndpoint();}
return endpoint||this.endpoint;},post:function(){if(this.isDisabled()){return;}
if(this.privacy_widget_options.everyone_warning&&this.privacy_widget&&this.privacy_widget.isEveryonePrivacy()){this.showConfirmEveryonePrivacyDialog();return;}
this._post();},_post:function(){var endpoint=this.getEndpoint();var data=this.getData(endpoint);this.logActions();if(!data){return;}
this.disable();new AsyncRequest().setURI(endpoint).setData(data).setHandler(bind(this,handle_require_email_conf_response,UIComposer.handleResponse.bind(this),null,null)).setErrorHandler(UIComposer.handleError.bind(this)).setFinallyHandler(this.enable.bind(this)).send();},logActions:function(){var data={target_id:this.target_id};if(this.attachments&&!is_empty(this.attachmentArea.attachment)){data.app_id=this.attachmentArea.attachment.app_id;}
if(this.privacy_widget){data.privacy_default_value=this.privacy_widget.getDefaultValue();data.privacy_value=this.privacy_widget.getValue();}
new AsyncSignal('/ajax/composer/logging.php',data).send();},publish:function(response){var stream=this.stream;if(stream){var story=response,status;if(response.getPayload){var payload=response.getPayload();status=payload.status;story=payload.markup;}
story=HTML(story).getRootNode();var displayDelay=500;stream.addContent(story,displayDelay);if(stream.setStatus&&status){setTimeout(function(){stream.setStatus(status);},displayDelay);}}
if(this.privacy_widget){this.privacy_widget.reset();}
return this;},populateLoc:function(){var new_results=false;var _populateLoc=function(pos){if(!this.hasState(UIComposer.STATE.LOC_ACTIVATED)||!this.hasState(UIComposer.STATE.INPUT_FOCUSED)||this.hasState(UIComposer.STATE.ATTACHMENT_AREA)){return;}
if(this.last_loc&&new_results!==false&&pos.coords.accuracy>=this.last_loc.coords.accuracy){return;}
new_results=true;var desc=pos.desc.label||pos.desc.street||pos.desc.region;if(!desc){return;}
var field=this.root.find('div.UIComposer_LocationField');field.setContent(_tx("near {place}",{place:desc}));this.last_loc=pos;if(!shown(field)){animation(field).to('height','auto').from('height',0).show().duration(100).ease(animation.ease.end).go();}};var error_count=0;var _errorCase=function(locError){if(++error_count>=2){return this.removeLoc();}};var _finder=function(){navigator.geolocation.getCurrentPosition(_populateLoc.bind(this),_errorCase.bind(this),{maximumAge:1000*60*60,enableHighAccuracy:false});navigator.geolocation.getCurrentPosition(_populateLoc.bind(this),_errorCase.bind(this),{maximumAge:1000*60*10,enableHighAccuracy:true});};Bootloader.loadComponents(['geolocation'],_finder.bind(this));},removeLoc:function(){var field=this.root.scry('div.UIComposer_LocationField')[0];if(field){field.empty();hide(field);}
this.last_loc=null;},toggleLocSetting:function(){this.toggleState(UIComposer.STATE.LOC_ACTIVATED);var loc_activated=this.hasState(UIComposer.STATE.LOC_ACTIVATED);new AsyncRequest('/ajax/geo/setting.php').setData({collect:loc_activated}).setErrorHandler(bagofholding).setTransportErrorHandler(bagofholding).send();if(loc_activated){this.populateLoc();}else{this.removeLoc();}
return false;},showLocWidget:function(){this.addState(UIComposer.STATE.LOC_WIDGET_SHOWN);},hideLocWidget:function(){this.removeLoc();this.removeState(UIComposer.STATE.LOC_WIDGET_SHOWN);},showPrivacyWidget:function(){this.addState(UIComposer.STATE.PRIVACY_WIDGET_SHOWN);if(this.privacy_widget_options.callout){this.showPrivacyWidgetCallout();}},hidePrivacyWidget:function(){this.removeState(UIComposer.STATE.PRIVACY_WIDGET_SHOWN);this.hidePrivacyWidgetCallout();},showPrivacyWidgetCallout:function(){CSS.setStyle(this.root.find('div.UIComposer_PrivacyWidgetCallout'),'display','block');},hidePrivacyWidgetCallout:function(){var nodes=this.root.scry('div.UIComposer_PrivacyWidgetCallout');if(nodes.length){CSS.setStyle(nodes[0],'display','none');}},closePrivacyWidgetCallout:function(){this.savePrivacyWidgetData('close','callout');this.hidePrivacyWidgetCallout();},savePrivacyWidgetData:function(data_key,response_key,callback){response_key=response_key||data_key;callback=callback||bagofholding;var data={};data[data_key]=true;new AsyncRequest().setData(data).setURI('/ajax/privacy/save_composer_data.php').setHandler(function(response){var payload=response.getPayload();this.privacy_widget_options[response_key]=payload[response_key];callback();}.bind(this)).setErrorHandler(bagofholding).setTransportErrorHandler(bagofholding).send();},showConfirmEveryonePrivacyDialog:function(){new Dialog().setAsync(new AsyncRequest().setURI('/ajax/privacy/confirm_everyone_dialog.php')).setHandler(this.savePrivacyWidgetData.bind(this,'seen_everyone','everyone_warning',this._post.bind(this))).show();},getContextData:function(){return this.context_data;},focusInput:function(){this.input.select();this.input.focus();},getMessage:function(){return this.input.value.trim();},clearMessage:function(){this.input.value='';this.input.setStyle('height','');}};copy_properties(UIComposer,{instances:{},getInstance:function(id){return this.instances[id]||null;},storeInstance:function(id,composer){this.instances[id]=composer;},handleError:function(response){var error=response.getError();var payload=response.getPayload();switch(error){case kError_Platform_CallbackValidationFailure:return UIComposer.showError(payload.errorTitle,payload.errorMessage);case kError_Platform_ApplicationResponseInvalid:return UIComposer.showError(payload.errorTitle,payload.showDebug);default:this.shouldHide=false;this.reset();return UIComposer.showError(response.getErrorSummary(),response.getErrorDescription());}},handleResponse:function(response){var error=response.getError();var errIsWarning=response.getErrorIsWarning();this.reset(this.clear_message).publish(response);if(error&&errIsWarning){UIComposer.showError(response.getErrorSummary(),response.getErrorDescription());}},showError:function(title,message){new ErrorDialog().setTitle(title).setBody(message||_tx("There was an application error. Please try again later.")).setButtons([Dialog.OK]).show();},getVerticalSpace:function(element){var height=element.offsetHeight;if(height){height+=parseInt(element.getStyle('marginTop'),10)||0;height+=parseInt(element.getStyle('marginBottom'),10)||0;}
return height;},animation:function(element,callback){return animation(element).ondone(callback||bagofholding).ease(animation.ease.end).duration(200);}});copy_properties(UIComposer,{DIALOG_WIDTH:560,DIALOG_WIDTH_PIC:620,APP_ID_POSTED:2309869772,HOME_DATA:{action:'HOME_UPDATE',home_tab_id:1,profile_id:null,status:null,target_id:null},TARGET_DATA:{action:'PROFILE_UPDATE',profile_id:null,status:null,target_id:null},STATE:{PIC_NONE:'UIComposer_STATE_PIC_NONE',PIC_INSIDE:'UIComposer_STATE_PIC_INSIDE',PIC_OUTSIDE:'UIComposer_STATE_PIC_OUTSIDE',INPUT_FOCUSED:'UIComposer_STATE_INPUT_FOCUSED',INPUT_DISABLED:'UIComposer_STATE_INPUT_DISABLED',BUTTON_DISABLED:'UIComposer_STATE_BUTTON_DISABLED',ATTACHMENT_LIST:'UIComposer_STATE_ATTACHMENT_LIST',ATTACHMENT_AREA:'UIComposer_STATE_ATTACHMENT_AREA',ATTACHMENT_LOADED:'UIComposer_STATE_ATTACHMENT_LOADED',PRIVACY_WIDGET_SHOWN:'UIComposer_STATE_PRIVACY_WIDGET_SHOWN',LOC_ACTIVATED:'UIComposer_STATE_LOC_ACTIVATED',LOC_WIDGET_SHOWN:'UIComposer_STATE_LOC_WIDGET_SHOWN'}});

function UIComposerAttachmentList(composer,root){this.composer=composer;this.root=root.find('ul.UIComposer_AttachmentList');this.mask=root.find('div.UIComposer_AttachmentMask');this.maskLabel=root.find('span.UIComposer_AttachmentLink');this.selected=null;var more=root.scry('li.UIComposer_More_Actuator')[0];var menu=ge('UIComposer_'+composer.id+'_Dropdown');var items=$A(root.scry('li.UIComposer_Attachment'));var menuItems=(menu&&$A(menu.scry('li')))||[];this.composer.attachments.each(function(attachment,index){attachment.index=index;var item=items[index],menuItem=menuItems[index];var load=this.select.bind(this,attachment);if(item){attachment.item=item;Event.listen(item,'click',load);}
if(menuItem){attachment.menuItem=menuItem;Event.listen(menuItem,'click',load);if(!this.swinger&&menuItem.hasClass('UIComposer_Swinger')){this.swinger=attachment;}}},this);if(menu&&more){more=more.find('a');dropmenu(more).registerHTMLMenu(menu).setPosition(dropmenu.ALIGN_LEFT).addHook('show',CSS.addClass.curry(more,'UIComposer_More_Selected')).addHook('hide',CSS.removeClass.curry(more,'UIComposer_More_Selected'));Event.listen(menu,'mousedown',function(){composer.shouldHide=false;});}}
UIComposerAttachmentList.prototype={swap:function(attachment){if(!attachment.item.hasClass('hidden_elem')){return;}
attachment.item.removeClass('hidden_elem');attachment.menuItem.addClass('hidden_elem');this.swinger.item.addClass('hidden_elem');this.swinger.menuItem.removeClass('hidden_elem');this.swinger=attachment;},select:function(attachment,internal,extraData){this.swap(attachment);this.selected=attachment.item;var offsetDir,offsetTransition;var offset=this.selected.offsetLeft;if(!intl_locale_is_rtl()){offsetDir='left';offset=this.selected.offsetLeft
-parseInt(this.mask.getStyle('paddingLeft'),10);}else{offsetDir='right';offset=this.root.offsetWidth
-this.selected.offsetLeft
-this.selected.offsetWidth
-parseInt(this.mask.getStyle('paddingRight'),10);}
this.mask.setStyle(offsetDir,offset+'px');this.maskLabel.setContent(attachment.caption);this.maskLabel.setStyle('backgroundImage','url('+attachment.icon+')');this.maskLabel.addClass('UIComposer_SelectedAttachment');var showAttachment=function(attachment){this.root.setStyle('display','');this.composer.showAttachment(attachment,extraData);}.bind(this,attachment);if(internal){offsetTransition=function(){CSS.setOpacity(this.root,0);UIComposer.animation(this.mask).to(offsetDir,'0px').go();showAttachment();}.bind(this);}else{offsetTransition=function(){CSS.setOpacity(this.root,0);CSS.setStyle(this.mask,offsetDir,'0px');showAttachment();}.bind(this);}
if(attachment.is_fluid){offsetTransition();}else{this.composer.detach(offsetTransition);}},reset:function(){if(this.maskLabel){CSS.removeClass(this.maskLabel,'UIComposer_SelectedAttachment');}
CSS.setOpacity(this.root,1);},show:function(){this.root.setStyle('display','block');this.composer.addState(UIComposer.STATE.ATTACHMENT_LIST);this.composer.refreshHeight();},hide:function(){this.root.setStyle('display','none');this.composer.removeState(UIComposer.STATE.ATTACHMENT_LIST);this.composer.refreshHeight();}};

function emu_Client(_unitId,_unitType,_contextType,_root,_iData,_frameStates,_flags,_hash){this.unitId=_unitId;this.unitType=_unitType;this.contextType=_contextType;this.root=_root;this.iData=_iData;this.flags=_flags;this.hash=_hash;this.frameStates={};this.eventFrameId=null;this.setStates(_frameStates);DOMStorage.setData(this.root,'emuClient',this);}
copy_properties(emu_Client,{constants:{EMU_FRAME_EVENT_INIT:1,EMU_FRAME_EVENT_CLICK:2,EMU_FRAME_EVENT_SUBMIT:3,EMU_SERVER_COMMAND_RENDER_FRAME:1000,EMU_SERVER_COMMAND_SET_FRAME_STATE:1001,EMU_SERVER_COMMAND_PLAY_VIDEO:1003,EMU_CLIENT_COMMAND_FRAME_EVENT:2000,EMU_LINK_TARGET_DEFAULT:1,EMU_LINK_TARGET_NEW_WINDOW:2,EMU_FRAME_CONTEXT_TARGET_INLINE:1,EMU_FRAME_CONTEXT_TARGET_DIALOG:2,EMU_FRAME_EVENT_HANDLER:'/ajax/emu/h.php'},getParentDivId:function(unitId){return'emu_'+unitId;},getClient:function(unitId){var emuParent=ge(emu_Client.getParentDivId(unitId));if(!emuParent){return null;}
return DOMStorage.getData(emuParent,'emuClient');}});copy_properties(emu_Client.prototype,{getFrameDivId:function(frameId){return emu_Client.getParentDivId(this.unitId)+'_'+frameId;},_emuCmdHandler:function(asyncResponse){var payload=asyncResponse.getPayload();for(var i=0;i<payload.length;i++){var cmd=payload[i];switch(cmd.cmd){case emu_Client.constants.EMU_SERVER_COMMAND_RENDER_FRAME:if(emu_Client.constants.EMU_FRAME_CONTEXT_TARGET_INLINE==cmd.params.surface.targetType){var frameDivId=this.getFrameDivId(cmd.params.surface.targetId);var frame=ge(frameDivId);if(!frame){var frame=$N('div',{'id':frameDivId});this.root.appendChild(frame);}
set_inner_html(frame,cmd.params.surface.buffer);}else if(emu_Client.constants.EMU_FRAME_CONTEXT_TARGET_DIALOG==cmd.params.surface.targetType){if(!this.root.dialog||!this.root.dialog._showing){this.root.dialog=new Dialog();}
var d=this.root.dialog;if(cmd.params.surface.buffer){d.setBody(cmd.params.surface.buffer);}
if(cmd.params.surface.title){d.setTitle(cmd.params.surface.title);}
if(cmd.params.surface.width){d.setContentWidth(cmd.params.surface.width);}
d.setButtons(Dialog.OK).show();}
break;case emu_Client.constants.EMU_SERVER_COMMAND_SET_FRAME_STATE:this.frameStates[cmd.params.frameId]=cmd.params.state;break;}}
this.eventFrameId=null;},_emuErrorHandler:function(response){var progressElement=ge('submit_progress_'+this.eventFrameId);if(progressElement){CSS.addClass(progressElement,'hidden');}
frameDiv=ge(this.getFrameDivId(this.eventFrameId));if(frameDiv){var inputs=get_all_form_inputs(frameDiv);for(var i=0;i<inputs.length;i++){inputs[i].disabled=false;}}
this.eventFrameId=null;},setStates:function(states){for(var fn in states){this.frameStates[fn]=states[fn];}},onEvent:function(frameId,eventType,eventData){if(this.eventFrameId){return;}
this.eventFrameId=frameId;switch(eventType){case emu_Client.constants.EMU_FRAME_EVENT_CLICK:var ed=eventData;break;case emu_Client.constants.EMU_FRAME_EVENT_SUBMIT:var ed=serialize_form(eventData);var formInputs=get_all_form_inputs(eventData);for(var i=0;i<formInputs.length;i++){formInputs[i].disabled=true;}
var progressElement=ge('submit_progress_'+this.eventFrameId);if(progressElement){CSS.removeClass(progressElement,'hidden');}
break;}
var params={'fss':this.frameStates,'ut':this.unitType,'ct':this.contextType,'f':this.flags,'x':this.hash,'ida':this.iData,'fid':frameId,'et':eventType,'ed':ed,'rt':'a'};var r=new AsyncRequest();r.setURI(emu_Client.constants.EMU_FRAME_EVENT_HANDLER).setData(params).setHandler(bind(this,'_emuCmdHandler')).setErrorHandler(bind(this,'_emuErrorHandler')).setTransportErrorHandler(bind(this,'_emuErrorHandler')).send();},onRedirect:function(frameId,eventData,target){var f=this.root.appendChild($N('form',{'action':emu_Client.constants.EMU_FRAME_EVENT_HANDLER,'method':'POST','target':(emu_Client.constants.EMU_LINK_TARGET_NEW_WINDOW==target)?'_blank':'','style':{'display':'none'}}));var p={'ut':this.unitType,'ct':this.contextType,'f':this.flags,'x':this.hash,'ida':this.iData,'fid':frameId,'et':emu_Client.constants.EMU_FRAME_EVENT_CLICK,'rt':'h'};for(var edt in eventData){p['ed['+edt+']']=eventData[edt];}
for(var fn in this.frameStates){p['fss['+fn+']']=this.frameStates[fn];}
if(ge('post_form_id')){p['post_form_id']=$('post_form_id').value;}
for(var pn in p){f.appendChild($N('input',{'type':'hidden','name':pn,'value':p[pn]}));}
f.submit();this.root.removeChild(f);}});function emu_redirect_wrapper(obj){emu_Client.getClient(obj.adId).onRedirect(obj.frameId,obj.eventData,obj.target);return false;}
function emu_action_wrapper(obj){emu_Client.getClient(obj.adId).onEvent(obj.frameId,obj.eventType,obj.eventData);return false;}

function EmuUIController(adId,frameId,state){this.adId=adId;this.frameId=frameId;this.state=state;this.emuFrame=$('emu_'+this.adId+'_'+this.frameId);DOMStorage.setData(this.emuFrame,'emuUIController',this);this._init();}
copy_properties(EmuUIController.prototype,{_init:abstractMethod,_getMoreUserContentText:abstractMethod,_initHiddenToggler:function(){var toggleLinks=DOM.scry(this.emuFrame,'a.UIMutableFilterList_Toggle');for(var i=0;i<toggleLinks.length;i++){toggleLinks[i].listen('click',this._toggleHidden.bind(this));}},_toggleHidden:function(){var hiddenDiv=DOM.find(this.emuFrame,'div.hidden_user_content');var showLink=DOM.find(this.emuFrame,'a.UIMutableFilterList_Show');var hideLink=DOM.find(this.emuFrame,'a.UIMutableFilterList_Hide');if(!shown(hiddenDiv)){animation(hiddenDiv).show().from('height',0).to('height','auto').from('opacity',0).to('opacity',1).duration(200).ease(animation.ease.both).go();showLink.addClass('hidden');hideLink.removeClass('hidden');}else{animation(hiddenDiv).to('height',0).from('opacity',1).to('opacity',0).hide().duration(200).ease(animation.ease.both).blind().go();showLink.removeClass('hidden');hideLink.addClass('hidden');}
return false;}});copy_properties(EmuUIController,{getController:function(adId,frameId){var emuFrame=$('emu_'+adId+'_'+frameId);var ret=DOMStorage.getData(emuFrame,'emuUIController');return ret;}});function CommentableEmuUIController(adId,frameId,state){this.parent.construct(this,adId,frameId,state);}
CommentableEmuUIController.extend('EmuUIController');copy_properties(CommentableEmuUIController.prototype,{_getCommentInput:abstractMethod,_init:function(){this._initCommentHandlers();this._initHiddenToggler();},_initCommentHandlers:function(){var commentInput=this._getCommentInput();if(commentInput){commentInput.listen('focus',this._commentOnFocus.bind(this));}
var submitBtn=DOM.scry(this.emuFrame,'input.submit_post')[0];if(submitBtn){submitBtn.listen('click',this._commentOnSubmit.bind(this));}},_commentOnFocus:function(){var submitBtn=DOM.find(this.emuFrame,'input.submit_post');submitBtn.disabled=false;submitBtn.removeClass('hidden');},_commentOnSubmit:function(evt){var commentInput=this._getCommentInput();var comment=commentInput.value;var placeholder=commentInput.getControl().getPlaceholderText();if(!comment||(comment==placeholder)){$E(evt).kill();}else{var progress=DOM.find(this.emuFrame,'img.submit_progress');progress.removeClass('hidden');}}});function emu_delete_video_comment(video_id,comment_id){new Dialog().setTitle(_tx("Delete Comment")).setBody(_tx("Are you sure you want to delete this comment?")).setButtons([{name:'delete',label:_tx("Delete"),handler:bind(this,function(){new AsyncRequest().setURI('/ajax/motion_comment.php').setData({v:video_id,d:comment_id}).setHandler(function(response){hide($('comment_'+comment_id));}).send();})},Dialog.CANCEL]).show();}
function CommentEmuUIController(adId,frameId,state){this.parent.construct(this,adId,frameId,state);return this;}
CommentEmuUIController.extend('CommentableEmuUIController');copy_properties(CommentEmuUIController.prototype,{_getMoreUserContentText:function(numHidden){if(numHidden==1){return _tx("1 more comment");}else{return _tx("{count} more comments",{'count':numHidden});}},_getCommentInput:function(){return DOM.scry(this.emuFrame,'input[name="comment"]')[0];}});function GiftEmuUIController(adId,frameId,state){this.parent.construct(this,adId,frameId,state);return this;}
GiftEmuUIController.extend('CommentableEmuUIController');copy_properties(GiftEmuUIController.prototype,{_init:function(){this.parent._init();this._adjustGiftsInIE6();},_adjustGiftsInIE6:function(){if(!(ua.ie()<7)){return;}
var giftImgs=DOM.scry(this.emuFrame,'img.wall_mini_gift_image');var hiddenDiv=DOM.scry(this.emuFrame,'div.hidden_user_content')[0];if(hiddenDiv){hiddenDiv.removeClass('hidden');}
for(var i=0;i<giftImgs.length;i++){var giftImg=giftImgs[i];giftImg.setStyle('width',giftImg.offsetWidth+1+'px');giftImg.setStyle('height',giftImg.offsetHeight+1+'px');adjustImage(giftImg);}
if(hiddenDiv){hiddenDiv.addClass('hidden');}},_getMoreUserContentText:function(numHidden){if(numHidden==1){return _tx("1 more gift");}else{return _tx("{count} more gifts",{'count':numHidden});}},_getCommentInput:function(){return DOM.scry(this.emuFrame,'textarea[name="gift_message"]')[0];}});copy_properties(GiftEmuUIController,{onFriendTokenAdded:function(formId,token){var formDiv=$(formId);var giftTo=DOM.find(formDiv,'input[name="gift_to"]');giftTo.value=token.i;CSS.removeClass(DOM.find(formDiv,'div.gift_form_wrapper'),'hidden');CSS.removeClass(DOM.find(formDiv,'div.gift_form_submit'),'hidden');},onFriendTokenRemoved:function(formId,token){var formDiv=$(formId);var giftTo=DOM.find(formDiv,'input[name="gift_to"]');giftTo.value=null;}});function InviteEmuUIController(adId,frameId,state){this.parent.construct(this,adId,frameId,state);return this;}
InviteEmuUIController.extend('CommentableEmuUIController');copy_properties(InviteEmuUIController.prototype,{_init:function(){this.parent._init();},_getCommentInput:function(){return DOM.scry(this.emuFrame,'input[name="email_list"]')[0];}});function EventEmuUIController(adId,frameId,state){this.parent.construct(this,adId,frameId,state);return this;}
EventEmuUIController.extend('CommentableEmuUIController');copy_properties(EventEmuUIController,{EVENT_STATE_INITIAL:1,EVENT_STATE_JUST_RSVP:2});copy_properties(EventEmuUIController.prototype,{_init:function(){var changeRSVPLink=DOM.scry(this.emuFrame,'a.rsvp_change')[0];if(changeRSVPLink){changeRSVPLink.listen('click',this._change_rsvp.bind(this));}
var rsvpRadios=DOM.scry(this.emuFrame,'input[name="rsvp_status_dummy"]');if(rsvpRadios){for(var i=0;i<rsvpRadios.length;i++){var radio=rsvpRadios[i];radio.listen('click',this._rsvp.bind(this,radio));}}
if(this.state==EventEmuUIController.EVENT_STATE_JUST_RSVP){this._updateRsvpStatusBg();this._initCommentHandlers();}
this._initHiddenToggler();},_change_rsvp:function(){var rsvpStatus=DOM.find(this.emuFrame,'div.rsvp_status');var rsvpInputs=DOM.find(this.emuFrame,'div.rsvp_inputs');var rsvpChange=DOM.find(this.emuFrame,'a.rsvp_change');CSS.addClass(rsvpStatus,'hidden');CSS.addClass(rsvpChange,'hidden');CSS.removeClass(rsvpInputs,'hidden');return false;},_rsvp:function(radioInput){var rsvpInputs=DOM.find(this.emuFrame,'div.rsvp_inputs');var progress=DOM.find(this.emuFrame,'img.rsvp_progress');var data={'linkId':3,'linkParam':radioInput.value}
emu_Client.getClient(this.adId).onEvent(this.frameId,emu_Client.constants.EMU_FRAME_EVENT_CLICK,data);CSS.addClass(rsvpInputs,'hidden');CSS.removeClass(progress,'hidden');},_updateRsvpStatusBg:function(){var statusPhrase=DOM.find(this.emuFrame,'span.rsvp_status_phrase');animation(statusPhrase).to('backgroundColor','#FFFFFF').from('#FFE8CC').duration(3000).go();},_getCommentInput:function(){return DOM.scry(this.emuFrame,'textarea[name="rsvp_comment"]')[0];},_getMoreUserContentText:function(numHidden){if(numHidden==1){return _tx("1 more RSVP from a friend");}else{return _tx("{count} more RSVPs from friends",{'count':numHidden});}}});copy_properties(EventEmuUIController,{onFriendTokenAdded:function(formId,token){var formDiv=$(formId);CSS.removeClass(DOM.find(formDiv,'div.invite_form_message'),'hidden');CSS.removeClass(DOM.find(formDiv,'div.invite_form_submit'),'hidden');}});function FanEmuUIController(adId,frameId,state){this.parent.construct(this,adId,frameId,state);return this;}
FanEmuUIController.extend('EmuUIController');copy_properties(FanEmuUIController.prototype,{_init:function(){this._initHiddenToggler();},_getMoreUserContentText:function(numHidden){numHidden-=3;if(numHidden==1){return _tx("1 more fan");}else{return _tx("{count} more fans",{'count':numHidden});}},justFanned:function(){var fanText=DOM.find(this.emuFrame,'div.fan_link');fanText.setStyle('backgroundColor','#fffccc');animation(fanText).duration(3000).checkpoint().to('backgroundColor','#FFFFFF').duration(1000).go();}});function PollEmuUIController(adId,frameId,state,isNile){this.isNile=isNile;this.parent.construct(this,adId,frameId,state);return this;}
PollEmuUIController.extend('EmuUIController');copy_properties(PollEmuUIController,{STATE_INITIAL:1,STATE_JUST_ANSWERED:2,STATE_ANSWERED:3});copy_properties(PollEmuUIController.prototype,{animateResults:function(){var resultBars=DOM.scry(this.emuFrame,'div.result_bar');for(var i=0;i<resultBars.length;i++){var bar=resultBars[i];var width=bar.offsetWidth;bar.setStyle('width','0px');animation(bar).from('width',0).to('width',width).duration(500).ease(animation.ease.both).go();}},_init:function(){if(this.state==PollEmuUIController.STATE_INITIAL){this._initAnswerRadios();}else{var friendCountLink=DOM.scry(this.emuFrame,'a.friend_count_link')[0];if(friendCountLink){friendCountLink.listen('click',this._onShowFriendsClick.bind(this));}}},_initAnswerRadios:function(){var answerRadios=this._findHelper(DOM.scry,'input[name="answer"]');if(answerRadios){for(var i=0;i<answerRadios.length;i++){var radio=answerRadios[i];radio.listen('click',this._onAnswer.bind(this,radio));}}},_onShowFriendsClick:function(){var friendVotePics=this._findHelper(DOM.scry,'div.friend_vote_pics');for(var i=0;i<friendVotePics.length;i++){var friendVotePic=friendVotePics[i];if(!shown(friendVotePic)){animation(friendVotePic).from('height',0).to('height','auto').duration(200).show().go();}else{animation(friendVotePic).to('height',0).duration(200).hide().go();}}
return false;},_onAnswer:function(radioInput){var answerId=radioInput.value;var container=this._findHelper(DOM.find,'div.answer_form');var progress=this._findHelper(DOM.find,'img.submit_progress');var radioArr=DOM.scry(container,'input.inputradio');var OFFSET_X=8;var radioVector=Vector2.getElementPosition(radioInput);var containerVector=Vector2.getElementPosition(container);var progressVector=new Vector2(OFFSET_X,radioVector.y-containerVector.y,'document');for(var i=0;i<radioArr.length;i++){radioArr[i].disabled=true;}
progressVector.setElementPosition(progress);radioInput.setStyle('visibility','hidden');progress.removeClass('hidden');var data={'linkId':2,'linkParam':answerId};emu_Client.getClient(this.adId).onEvent(this.frameId,emu_Client.constants.EMU_FRAME_EVENT_CLICK,data);},_findHelper:function(func,ele){if(!this.isNile){return func.call(null,this.emuFrame,ele);}
var poll_results=DOM.scry($('emu_'+this.adId),'div.poll_results');if(poll_results.length>0){return func.call(null,this.emuFrame,ele);}else{var radios_as_copy=ge('emu_poll_itb_'+this.adId);return func.call(null,radios_as_copy,ele);}}});function emu_ClickableBody(emu_container){var title=DOM.scry(emu_container,'a.ad_title');var clickableBody=DOM.scry(emu_container,'a.clickable_body');if(title.length&&clickableBody.length){title=title[0];clickableBody=clickableBody[0];clickableBody.listen('mouseover',function(){CSS.addClass(title,'underlined_title');});clickableBody.listen('mouseout',function(){CSS.removeClass(title,'underlined_title');});}}

function FeedFormBase(){this._storyType=63;this._feedData=null;this._uri='/fbml/ajax/prompt_feed.php';this._buttonCallback=null;this._isNile=false;this._supportsUserMessage=false;this._userMessagePrompt='';this._userMessage={value:''};this._currentSize=0;this._connectLocation=0;};FeedFormBase.SIZES={"small":1,"medium":2};FeedFormBase.AUTO_PUBLISH_OPTIONS={"never":2,"small":4,"medium":5};FeedFormBase.shouldShowLoadingToSelf=false;FeedFormBase.shouldShowLoadingToOthers=false;FeedFormBase.prototype.setStoryType=function(storyType){this._storyType=storyType;return this;};FeedFormBase.prototype.setForm=function(id){if(this._elements){Util.error('Cannot use both setForm and setElements.  Pick one or the other.');return null;}
this._form=$(id);return this;};FeedFormBase.prototype.setElements=function(elements){if(this._form){Util.error('Cannot use both setForm and setElements.  Pick one or the other.');return null;}
this._elements=elements;return this;}
FeedFormBase.prototype.setFeedData=function(feedData){this._feedData=feedData;return this;};FeedFormBase.prototype.setAppId=function(appId){this._appid=appId;return this;};FeedFormBase.prototype.setConnectLocation=function(connectLocation){this._connectLocation=connectLocation;return this;};FeedFormBase.prototype.setUserMessagePrompt=function(userMessagePrompt){this._userMessagePrompt=userMessagePrompt;return this;};FeedFormBase.prototype.setUserMessage=function(userMessage){if(userMessage){this._userMessage=userMessage;}
return this;};FeedFormBase.prototype.setURI=function(uri){this._uri=uri;return this;};FeedFormBase.prototype.setContinuation=function(continuation){this._continuation=continuation;return this;};FeedFormBase.prototype.setButtonCallback=function(callback){this._buttonCallback=callback;return this;}
FeedFormBase.prototype._selectSize=function(option){var size=option['size'];if(size!=this._currentSize){CSS.removeClass(this._selectedSize,'Tabset_selected');animation($('preview_'+this._currentSize)).to('opacity',0).hide().duration(150).go();animation($('preview_'+size)).duration(150).checkpoint().show().from('opacity',0).to('opacity',1).duration(150).go();this._selectedSize=option;this._currentSize=size;CSS.addClass(this._selectedSize,'Tabset_selected');}
return false;};FeedFormBase.prototype.attachHandlers=function(dialog){if(!this._isNile){this._attachSizeHandlers(dialog);}
var links=$('preview_container').scry('a');links.forEach(function(link){link.listen('click',function(e){e.kill();})});if(this._supportsUserMessage){$('feedform_user_message').focus();}
return this;}
FeedFormBase.prototype._attachSizeHandlers=function(dialog){var options=this._selectorOptions;var id_prefix=this._feedformFilter;for(var i=0;i<options.length;i++){var node=$(id_prefix+'_'+options[i]['size']);var anchor=$(id_prefix+'_'+options[i]['size']+'_anchor');var size=options[i]['size'];options[i]['node']=node;if(CSS.hasClass(node,'Tabset_selected')){this._selectedSize=options[i];this._currentSize=size;}
addEventBase(anchor,'click',this._selectSize.bind(this,options[i]),size);}
return true;}
FeedFormBase.prototype._finish=function(){this._enableSubmitButtons();if(this._dialog){this._dialog.hide();}
if(this._continuation){this._continuation();}};FeedFormBase.prototype.shouldShowLoading=function(){return false;}
FeedFormBase.prototype.showDialog=function(async){this._dialog=new Dialog().setContentWidth(580).setClassName('interaction_form').setAsync(async).setHandler(this.handleButton.bind(this)).onloadRegister(this.attachHandlers.bind(this));if(this.shouldShowLoading()){this._dialog.show();}
return this;};FeedFormBase.prototype._confirm=function(data){if(this._isNile&&this._supportsUserMessage){user_message=$('feedform_user_message').value;this._userMessage.value=data.user_message=user_message;}
new AsyncRequest().setURI(this._uri).setData(data).setContextData('nectar_isaction',true).setHandler(this.showConfirmed.bind(this)).send();};FeedFormBase.prototype.handleButton=function(button){if(this._buttonCallback){this._buttonCallback(button);}
if(button.name=="publish"){this.confirmFeed();return false;}else if(button.name=="cancel"){this.cancelFeed();}};FeedFormBase.prototype.cancelFeed=function(){this._finish();}
FeedFormBase.prototype.attachProperties=function(userData){copy_properties(this,userData);if(this._continuationJS){this._continuation=new Function(this._continuationJS);}
return this;};FeedFormBase.prototype._showBase=function(data){var async=new AsyncRequest().setURI(this._uri).setHandler(function(r){var user_data=r.getPayload().userData;this.attachProperties(user_data);if(user_data['no_dialog_shown']){this._finish();}
return true;}.bind(this)).setContextData('nectar_isaction',true).setErrorHandler(this._showApplicationError.bind(this)).setData(data);this.showDialog(async);return this;};FeedFormBase.prototype.showConfirmedWithMessage=function(msg){var confirmation='<div class="interim_status">'+msg+'</div>';var title=_tx("Post Published");if(this._dialog){this._dialog.setBody(confirmation);this._dialog.setTitle(title);this._dialog.setButtons(Dialog.OK);this._dialog.setButtonsMessage('');}else{$('dialog_body').innerHTML=confirmation;}
setTimeout(this._finish.bind(this),2500);return false;};FeedFormBase.prototype._enableSubmitButtons=function(){var feedFormSubmitButtons=['send','publish'];for(var i=0;i<feedFormSubmitButtons.length;i++){var button=ge(feedFormSubmitButtons[i]);if(button){button.disabled=false;break;}}}
FeedFormBase.prototype._showApplicationError=function(response){this._enableSubmitButtons();var showError=function(showMsg){(new ErrorDialog()).showError(response.getPayload().errorTitle,showMsg?(response.getPayload().errorMessage):_tx("There was an application error. Please try again later."));}
var err=response.getError();if(err==kError_Platform_CallbackValidationFailure){showError(true);}else if(err==kError_Platform_ApplicationResponseInvalid){if(response.getPayload().showDebug){showError(true);}else{if(this._continuation){this._continuation();}else{showError(false);}}}else{ErrorDialog.showAsyncError(response);}
return false;};function FeedForm(){this.parent.construct(this);}
FeedForm.extend('FeedFormBase');FeedForm.prototype._setPublishButtonText=function(text){this.publish_button.value=text;}
FeedForm.prototype._setCancelButtonText=function(text){this.cancel_button.value=text;}
FeedForm.prototype.shouldShowLoading=function(){return FeedFormBase.shouldShowLoadingToSelf;}
FeedForm.prototype.show=function(){var more={};if(this._form){more={callback:this._form.getAttribute('action'),elements:serialize_form(this._form)};}else if(this._elements){more.elements=this._elements;}
var data={app_id:this._appid,feedform_type:this._storyType,feed_info:this._feedData,user_message_prompt:this._userMessagePrompt,user_message:this._userMessage.value,preview:true,feed_target_type:'self_feed',extern:this._connectLocation};copy_properties(data,more);return this._showBase(data);}
FeedForm.prototype.cancelFeed=function(){this._finish();}
FeedForm.prototype.showConfirmed=function(){var msg=this.is_never_publish?_tx("Setting Saved."):_tx("The post is now visible on your Wall and your friends' home pages.");this.showConfirmedWithMessage(msg);}
FeedForm.prototype.confirmFeed=function(){var data={feed_info:this._feedData,feedform_type:this._storyType,preview:false,feed_target_type:'self_feed',app_id:this._appid,size:FeedFormBase.SIZES[this._currentSize],extern:this._connectLocation};this._confirm(data);};function MultiFeedForm(){this.parent.construct(this);}
MultiFeedForm.extend('FeedFormBase');MultiFeedForm.prototype.setPrefillId=function(prefillId){if(prefillId>0){this._prefillId=prefillId;}else{this._prefillId=null;}
return this;};MultiFeedForm.prototype.removeRecipient=function(user){this._toIds=this._toIds.filter(function(u){return u!=user;});if(this._toIds.length==0){this._finish();}else{DOM.remove('sp'+user);}
return false;};MultiFeedForm.prototype.showConfirmed=function(){var msg=_tx("The post is now visible on your friend's Wall.");this.showConfirmedWithMessage(msg);}
MultiFeedForm.prototype.confirmFeed=function(){var data={feed_info:this._feedData,feedform_type:this._storyType,to_ids:this._toIds,preview:false,feed_target_type:'multi_feed',app_id:this._appid,size:FeedFormBase.SIZES[this._currentSize],extern:this._connectLocation};this._confirm(data);};MultiFeedForm.prototype.shouldShowLoading=function(){return FeedFormBase.shouldShowLoadingToOthers;}
MultiFeedForm.prototype.show=function(){var ids=[];if(this._prefillId){ids.push(this._prefillId);}else{var inputs=this._form.getElementsByTagName('input');for(var i=0;i<inputs.length;i++){if(inputs[i].getAttribute('fb_protected')=='true'&&(inputs[i].name=='ids[]'||inputs[i].name=='friend_selector_id')&&(inputs[i].type!='checkbox'||inputs[i].checked)){ids.push(inputs[i].value);}}}
this._toIds=ids;var data={app_id:this._appid,to_ids:this._toIds,callback:this._form.action,preview:true,form_id:this._form.id,prefill:(this.prefillId>0),elements:serialize_form(this._form),user_message_prompt:this._userMessagePrompt,user_message:this._userMessage.value,feed_target_type:'multi_feed',extern:this._connectLocation};return this._showBase(data);};MultiFeedForm.prototype.attachHandlers=function(dialog){for(var i=0;i<this._toIds.length;i++){var person_link=ge('spl_'+this._toIds[i]);if(person_link){person_link.onclick=this.removeRecipient.bind(this,this._toIds[i]);}}
this.parent.attachHandlers(dialog);return this;};function TargetFeedForm(){this.parent.construct(this);}
TargetFeedForm.extend('MultiFeedForm');TargetFeedForm.prototype.confirmFeed=function(){var data={feed_info:this._feedData,feedform_type:this._storyType,to_ids:this._toIds,preview:false,feed_target_type:'target_feed',app_id:this._appid,size:FeedFormBase.SIZES[this._currentSize],extern:this._connectLocation};this._confirm(data);};TargetFeedForm.prototype.setTarget=function(target){this._toIds=[target];return this;}
TargetFeedForm.prototype.show=function(){var data={app_id:this._appid,to_ids:this._toIds,feed_info:this._feedData,preview:true,prefill:(this.prefillId>0),user_message_prompt:this._userMessagePrompt,user_message:this._userMessage.value,feed_target_type:'target_feed',extern:this._connectLocation};return this._showBase(data);};

var FBML=(function(){var invoked_dialogs={};if(typeof typeaheadpro!='undefined'){function friendSelector(obj,source,properties){var idInput=document.createElement('INPUT');idInput.name=obj.getAttribute('idname');idInput.type='hidden';idInput.setAttribute('fb_protected','true');idInput.typeahead=this;if(obj.form){obj.form.appendChild(idInput);}
this._idInput=idInput;return this.parent.construct(this,obj,source,properties);}
friendSelector.extend('typeaheadpro');friendSelector.prototype.updateID=function(obj){if(obj.i){this._idInput.value=obj.i;}else if(obj.is){this._idInput.value=obj.is;}else{this._idInput.value='';}}
friendSelector.prototype.destroy=function(){this._idInput.parentNode.removeChild(this._idInput);this._idInput.typeahead=null;this._idInput=null;this.parent.destroy();}
friendSelector.prototype._onselect=function(obj){this.updateID(obj);this.parent._onselect(obj);}}else{friendSelector=null;}
var Contexts=new Object();function err(msg){if(window.console){window.console.log('Facebook FBML Mock AJAX ERROR: '+msg);}
return false;}
function attachCurlFromObject(ajax_params,container,pre_fn,post_fn){if(!ajax_params['url']){return err("no input with id url in form");}
if(!ajax_params['fb_sig_api_key']){return err("no input with id fb_api_key in form");}
if(pre_fn){pre_fn();}
attachCurlFromFormValues(ajax_params,container,post_fn);}
function attachCurlFromFormValues(ajax_params,container,post_fn){new AsyncRequest().setURI('/fbml/ajax/attach.php').setData(ajax_params).setMethod('POST').setHandler(function(response){if(post_fn){post_fn();}
if(!container.removed){set_inner_html(container,response.getPayload().html);}}.bind(this)).send();}
function attachFromPreview(context){if(context=='wall'){var attachments=wallAttachments;}else if(context=='message'){var attachments=inboxAttachments;}
if(attachments){var parent=ge(attachments.edit_id);var inputs=attachments.get_all_form_elements(parent);var params=Object();for(var i=0;i<inputs.length;i++){if(!(inputs[i].type=="radio"||inputs[i].type=="checkbox")||inputs[i].checked){params[inputs[i].name]=inputs[i].value;}}
params['context']=attachments.context;params['action']='edit';attachCurlFromFormValues(params,parent);}}
function clickRewriteAjax(app_id,loggedIn,targetId,url,form,loadingHTML){this.requireLogin(app_id,function(){return _clickRewriteAjax(targetId,url,form,loadingHTML);});return false;}
function _clickRewriteAjax(targetId,url,form,loadingHTML){var target=ge(targetId);if(!target){return err("target "+targetId+" not found");}
var hContext=target.getAttribute("fbcontext");var sContext=FBML.Contexts[hContext];if(!form){return err("You must either specify a clickrewriteform (an id) or use the clickrewrite attribute inside a form");}
var owner_id=typeof this.PROFILE_OWNER_ID=='undefined'?0:this.PROFILE_OWNER_ID;var post=serialize_form(form);post["fb_mockajax_context"]=sContext;post["fb_mockajax_context_hash"]=hContext;post["fb_mockajax_url"]=url;post["fb_target_id"]=owner_id;post["fb_mockajax_rewrite_id"]=targetId;new AsyncRequest().setURI('/fbml/mock_ajax_proxy.php').setMethod("POST").setFBMLForm().setData(post).setHandler(function(response){var ma=response.getPayload();if(ma.ok){set_inner_html(target,ma.html);}else{return err(ma["error_message"]);}
FBML.mockAjaxResponse=ma;return ma.ok;}.bind(this)).setErrorHandler(function(response){return err("Failed to successfully retrieve data from Facebook when making mock AJAX call to rewrite id "+targetId);}.bind(this)).send();if(loadingHTML){DOM.setContent(target,HTML(loadingHTML));}
return false;}
function clickToShow(targetId){return clickToSetDisplay(targetId,"");}
function clickToShowDialog(targetId){var dialog_elem=null;if(dialog_elem=ge(targetId)){var dialog_content=dialog_elem.parentNode.innerHTML;dialog_elem.id='dialog_invoked_'+dialog_elem.id;var elem=dialog_elem.cloneNode(true);DOM.setContent(dialog_elem,'');var dialog=new Dialog().setImmediateRendering(true).setStackable(true).setBody(dialog_content).setFullBleed(true).show();invoked_dialogs[dialog_elem.id]={'elem':elem,'dialog':dialog};}
return false;}
function closeDialogInvoked(targetId){var hidden_dialog_elem=null;var dialog_target_id='dialog_invoked_'+targetId;for(dialog_id in invoked_dialogs){if(hidden_dialog_elem=ge(dialog_id)){var old_id=hidden_dialog_elem.id.replace('dialog_invoked_','');var old_elem=null;if(old_elem=ge(old_id)){old_elem.id='dialog_closed_'+old_id;}
var parent=hidden_dialog_elem.parentNode;DOM.setContent(parent,'');parent.appendChild(invoked_dialogs[dialog_id].elem);invoked_dialogs[dialog_id].elem.id=old_id;}}
if(invoked_dialogs[dialog_target_id].dialog){invoked_dialogs[dialog_target_id].dialog.hide();}}
function clickToHide(targetId){return clickToSetDisplay(targetId,"none");}
function clickToToggle(targetId){var target=ge(targetId);if(!target){return err("Could not find target "+targetId);}else{target.style.display=(target.style.display=="none")?'':'none';return false;}}
function clickToSetDisplay(targetId,disp){var target=ge(targetId);if(!target){return err("Could not find target "+targetId);}else{target.style.display=disp;return false;}}
function clickToEnable(targetId){return clickToSetDisabled(targetId,'');}
function clickToDisable(targetId){return clickToSetDisabled(targetId,'disabled');}
function clickToSetDisabled(targetId,disabled){var target=ge(targetId);if(!target){return err("Could not find target "+targetId);}else{target.disabled=disabled;return false;}}
function fbmlLogin(app_id,form_id){new AsyncRequest().setURI('/ajax/api/tos.php').setData({app_id:app_id,grant_perm:1,profile_id:typeof PROFILE_OWNER_ID=='undefined'?0:PROFILE_OWNER_ID,api_key:$('api_key').value,auth_token:$('auth_token').value,connect:this.connectParams}).setHandler(bind(this,function(response){if(response.getPayload()){var sig_params=response.getPayload();if(form_id){var form=ge(form_id);addHiddenInputs(form,sig_params);if(this.loginContinuation){this.loginContinuation=this.loginContinuation.bind(form);}}
if(this.sendParams){if(this.loginContinuation){this.loginContinuation=this.loginContinuation.bind(null,sig_params);}}}
this.loginDialog&&this.loginDialog.hide();this.loginContinuation&&this.loginContinuation();this.loginCancellation=this.loginContinuation=this.loginDialog=null;})).send();}
function cancelLogin(){this.loginCancellation&&this.loginCancellation();this.loginDialog&&this.loginDialog.hide();this.loginContinuation=this.loginCancellation=this.loginDialog=null;}
function addHiddenInputs(form_obj,form_hidden_inputs){var i;for(i=form_obj.childNodes.length-1;i>=0;i--){if(form_obj.childNodes[i].name&&form_obj.childNodes[i].name.indexOf('fb_sig')==0){form_obj.removeChild(form_obj.childNodes[i]);}}
for(keyVar in form_hidden_inputs){DOM.appendContent(form_obj,$N('input',{name:keyVar,value:form_hidden_inputs[keyVar],type:'hidden'}));}}
function _promptPermissionHandler(form,button){this.grantedPerms=true;if(form){DOM.appendContent(form,$N('input',{name:'fb_perms_approved',value:'1',type:'hidden'}));}
Dialog.getCurrent()._submitForm('POST','/fbml/ajax/permissions.php',button);return false;}
function _promptPermissionCloseHandler(next_js,form){if(window.ApiExtendedPermissions&&window.ApiExtendedPermissions.closeHandler){window.ApiExtendedPermissions.closeHandler();}
if(this.grantedPerms){next_js();}
if(form){form.submit();}}
function promptPermission(app_id,perms,next_js,form){var async=new AsyncRequest().setURI('/fbml/ajax/permissions.php').setData({app_id:app_id,perms:perms});this.grantedPerms=false;var dialog=new Dialog().setAsync(async).setHandler(_promptPermissionHandler.bind(this,form)).setCloseHandler(_promptPermissionCloseHandler.bind(this,next_js,form)).show();}
function promptPermissionPro(app_id,perms,callback){var async=new AsyncRequest().setURI('/fbml/ajax/permissions.php').setData({app_id:app_id,perms_string:perms});this.grantedPerms=false;var self=this;var dialog=new Dialog().setAsync(async).setHandler(_promptPermissionHandler.bind(this,null)).setCloseHandler(function(){_promptPermissionCloseHandler.call(self,bagofholding,null);if(self.grantedPerms&&this.getUserData()){callback(this.getUserData().profile_id);}}).show();}
function showPermissionDialog(perms,callback,form){FB.init({"apiKey":PlatformCanvasController.singleton.api_key,"xdChannelUrl":"/xd_receiver_v0.4.php"});FB.ensureInit(function(){FB.Connect.showPermissionDialog(perms,callback);});}
function showFeedDialog(app_id,template_bundle_id,template_data,body_general,target_id,continuation,user_message_prompt,user_message){var feed_data={template_id:template_bundle_id,template_data:template_data,body_general:body_general};var feedform;if(target_id&&(!hasArrayNature(target_id)||target_id.length>0)){if(hasArrayNature(target_id)){target_id=target_id[0];}
feedform=new TargetFeedForm().setTarget(target_id);}else{feedform=new FeedForm();}
feedform.setContinuation(continuation).setFeedData(feed_data).setAppId(app_id).setUserMessagePrompt(user_message_prompt).setUserMessage(user_message).show();}
function closeLoginDialog(){if(this.loginDialog){this.loginDialog.close();}}
function requireLogin(app_id,continuation,cancellation,form,send_params,need_connect_params){if(this.loginDialog){return;}
var form_id=form?form.id:'';this.sendParams=send_params;this.connectParams=need_connect_params?need_connect_params:false;this.loginDialog=new Dialog().setStackable(true).setClassName('api_confirmation');this.loginContinuation=continuation;this.loginCancellation=cancellation;new AsyncRequest().setURI('/ajax/api/tos.php').setData({login_form_id:form_id,app_id:app_id,profile_id:typeof PROFILE_OWNER_ID=='undefined'?0:PROFILE_OWNER_ID}).setReadOnly(true).setHandler(bind(this,function(continuation,response){var resp=response.getPayload();if(resp){this.loginDialog.setTitle(resp.title).setBody(resp.content).show();}else{continuation();this.loginCancellation=null;this.loginContinuation=null;this.loginDialog=null;}},continuation)).setErrorHandler(bind(this,function(response){if(response.getError()==kError_Async_NotLoggedIn){uri=new URI('/login.php').setSubdomain('www').addQueryData({next:document.location.href});goURI(uri);}else{ErrorDialog.showAsyncError(response);}})).send();}
function sendRequest(request_form,app_id,request_type,invite,preview,is_multi,prefill){var message='';if(!preview){if(is_multi){request_form.onSubmit=fsth.captured_event;}
message=$('message').value;}
if(prefill){var ids=[];ids.push(prefill);}else{var inputs=request_form.getElementsByTagName('input');var ids=[];var emails=[];for(var i=0;i<inputs.length;i++){if(inputs[i].getAttribute('fb_protected')=='true'&&(inputs[i].name=='ids[]'||inputs[i].name=='friend_selector_id')&&(inputs[i].type!='checkbox'||inputs[i].checked)){ids.push(inputs[i].value);}
else if(inputs[i].getAttribute('fb_protected')=='true'&&inputs[i].name=='emails[]'){emails.push(inputs[i].value);}}}
var data={app_id:app_id,to_ids:ids,to_emails:emails,request_type:request_type,invite:invite,content:request_form.getAttribute('content'),preview:preview,is_multi:is_multi,form_id:request_form.id,prefill:(prefill>0),message:message,donot_send:ge('donotsend')?$('donotsend').checked:false};var async=new AsyncRequest().setURI('/fbml/ajax/prompt_send.php').setData(data);if(preview){new Dialog().setClassName('req_dialog').setAsync(async).setStackable(true).show();}else{async.setHandler(function(result){request_form.submit();}).send();}
return false;}
function cancelDialog(elem){if(Dialog.getCurrent()){Dialog.getCurrent().hide();return;}
generic_dialog.get_dialog(elem).fade_out(100);}
function removePreviewRecipients(id){var span=$('sp'+id);var recipients_list=span.parentNode;recipients_list.removeChild(span);for(var i=0;i<recipients_list.childNodes.length;i++){if(recipients_list.childNodes[i].nodeName=='SPAN'){return false;}}
generic_dialog.get_dialog(recipients_list).fade_out(100);return false;}
function removeTokenizerRecipient(id,request_form,is_multi){var inputs=request_form.getElementsByTagName('input');for(var i=0;i<inputs.length;i++){if(((inputs[i].name=='emails[]')||(inputs[i].name=='ids[]'))&&(inputs[i].value==id)){delNode=inputs[i].parentNode.parentNode.parentNode.parentNode.parentNode.token;if(delNode){delNode.remove(false);}}}
removePreviewRecipients(id);return false;}
function removeReqRecipient(userid,request_form,is_multi){if(is_multi){if(fs.selected_ids[userid]){fs.unselect(userid);fs.force_reset();}
else{removeTokenizerRecipient(userid,request_form,is_multi);return false;}}else{var inputs=request_form.getElementsByTagName('input');for(var i=0;i<inputs.length;i++){if(inputs[i].getAttribute('fb_protected')=='true'&&inputs[i].value==userid){if(inputs[i].name=='ids[]'){if(inputs[i].type=='checkbox'){if(inputs[i].checked){inputs[i].click();}}else{inputs[i].parentNode.parentNode.parentNode.parentNode.parentNode.token.remove(true);}}else if(inputs[i].name=='friend_selector_id'){inputs[i].typeahead.select_suggestion(false);inputs[i].typeahead.set_value('');inputs[i].value='';}}}}
removePreviewRecipients(userid);return false;}
var stripLinks=function(container){var links=container.getElementsByTagName('a');for(var i=0;i<links.length;i++){if(!links[i].getAttribute('flash')){addEventBase(links[i],'click',Event.kill);}}
var forms=container.getElementsByTagName('form');for(var i=0;i<forms.length;i++){forms[i].onsubmit=function(){return false;};}}
var enforceStyle=function(element,styles){for(styleName in styles){element.style[styleName]=styles[styleName];}}
var registerFBJSBridge=function(appid,bridgeHash){var sb=fbjs_sandbox.getSandbox(appid);if(sb){sb.setBridgeHash(bridgeHash);}}
var submitForm=function(form,event){if(form.onsubmit){try{if(!form.onsubmit(event)){return;}}catch(e){if(e.message=="Object doesn't support this action"){if(!form.onsubmit()){return;}}else{throw e;}}}
form.submit();}
return{friendSelector:friendSelector,Contexts:Contexts,attachCurlFromObject:attachCurlFromObject,attachFromPreview:attachFromPreview,clickRewriteAjax:clickRewriteAjax,clickToShow:clickToShow,clickToShowDialog:clickToShowDialog,clickToHide:clickToHide,clickToEnable:clickToEnable,clickToDisable:clickToDisable,clickToToggle:clickToToggle,closeDialogInvoked:closeDialogInvoked,sendRequest:sendRequest,removeTokenizerRecipient:removeTokenizerRecipient,removeReqRecipient:removeReqRecipient,cancelDialog:cancelDialog,addHiddenInputs:addHiddenInputs,fbmlLogin:fbmlLogin,cancelLogin:cancelLogin,requireLogin:requireLogin,closeLoginDialog:closeLoginDialog,showFeedDialog:showFeedDialog,promptPermission:promptPermission,promptPermissionPro:promptPermissionPro,showPermissionDialog:showPermissionDialog,stripLinks:stripLinks,enforceStyle:enforceStyle,registerFBJSBridge:registerFBJSBridge,submitForm:submitForm};})();

function PageCacheFeedTracking(){this.data=[];}
copy_properties(PageCacheFeedTracking.prototype,{register:function(metadata,hash,type,undo,cat){var newEntry={'meta':metadata,'h':hash,'type':type,'undo':undo,'cat':cat};this.data.push(newEntry);},dispatch:function(){var async=new AsyncRequest().setMethod('POST').setURI('/ajax/feed_tracking_pagecache.php').setReadOnly(true).setOption('bundle',true).setData({'data':this.data}).send();return 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|\'|"|\\.|,|!|\\?|<br>|$)';Emote._regex=new RegExp(regexStr);Emote._emoteOrderMap={};for(var i=0;i<emoteOrder.length;i++){Emote._emoteOrderMap[emoteOrder[i]]=i;}
Emote._initialized=true;},htmlEmote:function(str,txtFn){if(typeof txtFn!='function'){txtFn=htmlize;}
if(!Emote._initialized){Emote._init();}
var start=0;var strRemaining=str;var retArr=[];while(true){var matchObj=Emote._regex.exec(strRemaining);if(!matchObj||!matchObj.length){break;}
var match=matchObj[1];var matchKey=Emote._emoteMap[match][1];var matchIndex=strRemaining.indexOf(match);var chunk=strRemaining.substring(0,matchIndex);if(chunk){retArr.push(txtFn(chunk));}
retArr.push('<span class="emote_text">');retArr.push(match);retArr.push('</span><img class="emote_img" ');var matchOrder;if(typeof(matchOrder=Emote._emoteOrderMap[matchKey])=='undefined'){retArr.push('src="');retArr.push(Emote._imageBase);retArr.push(matchKey);retArr.push('.gif" ');}else{var matchPos=((matchOrder*-16)-590);retArr.push('src="');retArr.push(Emote._blankImgSrc);retArr.push('" style="background:url(');retArr.push(Emote._imageURL);retArr.push(') ');retArr.push(matchPos);retArr.push('px -84px no-repeat" ');}
retArr.push('alt="');retArr.push(match);retArr.push('" />');strRemaining=strRemaining.substring(matchIndex+match.length);}
if(strRemaining){retArr.push(txtFn(strRemaining));}
return retArr.join('');}};

function feedcomment_get_feedback_sources(){return{'FEEDBACK_SOURCE_PROFILE':0,'FEEDBACK_SOURCE_NEWS_FEED':1,'FEEDBACK_SOURCE_OBJECT':2,'FEEDBACK_SOURCE_MOBILE':3,'FEEDBACK_SOURCE_EMAIL':4,'FEEDBACK_SOURCE_API':5,'FEEDBACK_SOURCE_OBJECTS_PAGE':6};}
function feedcomment_show_error(target_fbid,item_id,source,error_text){var comments_target=_feedcomment_get_comments_target_div(target_fbid,item_id);if(comments_target){CSS.addClass(comments_target,'has_error');}
var error_target=_feedcomment_get_error_target(target_fbid,item_id);if(!error_target){error_target=_feedcomment_get_add_comment_form(target_fbid,item_id);}
if(error_text&&error_target){DOM.setText(error_target,error_text);}}
function feedcomment_hide_error(target_fbid,item_id,source){var comments_target=_feedcomment_get_comments_target_div(target_fbid,item_id);if(comments_target){CSS.removeClass(comments_target,'has_error');}}
function feedcomment_set_comment_target(target_fbid,item_id,source){var comments_box=_feedcomment_get_comments_target_wrapper(target_fbid,item_id);var comments_box_inner_divs=comments_box.getElementsByTagName('div');for(var i=0;i<comments_box_inner_divs.length;i++){if(CSS.hasClass(comments_box_inner_divs[i],'target_comments')){CSS.removeClass(comments_box_inner_divs[i],'selected_target_comments');}}
var comments_target=_feedcomment_get_comments_target_div(target_fbid,item_id);if(comments_target){CSS.addClass(comments_target,'selected_target_comments');feed_comment_show_add_button(target_fbid,item_id,source);}}
function feedcomment_submit(target_fbid,item_id,source,target_owner,type_id,assoc_object_id,link_data_str,check_hash,source_app_id){var add_comment_form=_feedcomment_get_add_comment_form(target_fbid,item_id);var add_comment_textarea=_feedcomment_get_add_comment_textarea(target_fbid,item_id);var comment_button=_feedcomment_get_add_comment_button(target_fbid,item_id);var publish_checkbox=_feedcomment_get_publish_story_checkbox(target_fbid,item_id);var credits_giver_input=_feedcomment_get_credits_giver_input(target_fbid,item_id);var num_credits=(credits_giver_input&&parseInt(credits_giver_input.value,10))||0;var feedcomment_arguments=arguments;var publish_story=true;if(publish_checkbox){publish_story=publish_checkbox.checked;}
var onResponse=function(asyncResponse){var payload=asyncResponse.getPayload();if('userData'in payload&&payload.userData=='nux'){if(asyncResponse.isReplay()){return;}
new Dialog(payload).setButtons([{label:_tx("Confirm"),handler:function(){feedcomment_submit.apply(this,feedcomment_arguments)},name:'confirm_comment'},Dialog.CANCEL]).show();}else{feedcomment_add_comment_onsuccess(payload,target_fbid,item_id,source);}}
var onTransportFail=function(response){feedcomment_show_error(target_fbid,item_id,source,_tx("Please try again later."));};var onFail=function(response){if(payload=response.getPayload()){if(payload.errTitle||payload.errBody){var error_text=payload.errBody?payload.errBody:payload.errTitle;feedcomment_show_error(target_fbid,item_id,source,error_text);}else{onTransportFail(response);}}else{onTransportFail(response);}};var comment_text=(add_comment_textarea.getControl&&add_comment_textarea.getControl().getValue())||'';comment_text=trim(comment_text);if(comment_text){var endpoint=num_credits?'/ajax/giftcredits/prompt.php':'/ajax/inline_comments.php';var post_data={'assoc_object_id':assoc_object_id,'check_hash':check_hash,'comment_text':comment_text,'item_id':item_id,'link_data':link_data_str,'source':source,'target_fbid':target_fbid,'target_owner':target_owner,'type_id':type_id,'source_app_id':source_app_id,'num_credits':num_credits,'publish_story':publish_story};if(num_credits){var fragment=_feedcomment_get_commentable_item_div(target_fbid,item_id,source).getAttribute('id');post_data={app_id:19675640871,receiver:target_owner,back_url:URI.getRequestURI().setFragment(fragment).toString(),order_info:JSON.encode(post_data)};}
comment_button.disabled=true;add_comment_textarea.disabled=true;new AsyncRequest().setURI(endpoint).setData(post_data).setContextData('clicktype','Write Comment').setHandler(bind(this,handle_require_email_conf_response,onResponse,null,null)).setErrorHandler(onFail).setFinallyHandler(function(){comment_button.disabled=false;add_comment_textarea.disabled=false;}).send();}else{feed_comment_cancel_add_box_onblur();animation(add_comment_textarea).to('background','#fff').from('#fcc').duration(140).go();}
return status;}
function feedcomment_add_comment_onsuccess(result,target_fbid,item_id,source){var add_comment_form=_feedcomment_get_add_comment_form(target_fbid,item_id);var add_comment_textarea=_feedcomment_get_add_comment_textarea(target_fbid,item_id);var comment_button=_feedcomment_get_add_comment_button(target_fbid,item_id);var publish_checkbox=_feedcomment_get_publish_story_checkbox(target_fbid,item_id);var credits_giver_input=_feedcomment_get_credits_giver_input(target_fbid,item_id);var num_credits=(credits_giver_input&&parseInt(credits_giver_input.value,10))||0;if(num_credits&&'title'in result&&'body'in result){new Dialog(result).show();return;}
if(!Rect.getViewportBounds().contains(Rect.getElementBounds(comment_button))){var scroll_offset=-1*Math.max(getViewportHeight()/2,100);animation(DOMScroll.getScrollRoot()).to('scrollTop',Vector2.getElementPosition(comment_button).y+scroll_offset).ease(animation.ease.end).duration(1500).go();}
if('last_comment'in result){feedcomment_append_comment(target_fbid,item_id,result.last_comment,result.comment_count,source);}else{feedcomment_sync_with_markup(target_fbid,item_id,result.all_comments_html,result.comment_count,source);}
if(credits_giver_input){if('balance_html'in result){var balance_divs=DOM.scry(document.body,'div.comments_add_box span.balance_text');var node=HTML(result.balance_html);for(var i=balance_divs.length-1;i>=0;--i){balance_divs[i].setContent(node);}}
credits_giver_input.value=0;DOM.find(add_comment_form,'div.credits_giver_row').removeClass('credits_giver_row_revealed');}
add_comment_textarea.value='';if(add_comment_textarea.getControl){add_comment_textarea.getControl().setPlaceholderText(_tx("Write another comment..."));}
feed_comment_hide_add_box(target_fbid,item_id,source,false);}
function feed_comment_record_add_box_onblur(timeoutId){feed_comment_record_add_box_onblur.timeoutId=timeoutId;}
function feed_comment_cancel_add_box_onblur(){var timeoutId=feed_comment_record_add_box_onblur.timeoutId;if(timeoutId){clearTimeout(timeoutId);}}
function feed_comment_hide_add_box(target_fbid,item_id,source,onblur_event){var add_comment_textarea=_feedcomment_get_add_comment_textarea(target_fbid,item_id);if(add_comment_textarea){var has_entered_text=add_comment_textarea.getControl&&add_comment_textarea.getControl().getValue();if(!has_entered_text){var commentable_item=_feedcomment_get_commentable_item_div(target_fbid,item_id,source);var comments=_feedcomment_get_feed_comments(target_fbid,item_id);var hovering_over_link=(DOM.scry(commentable_item,'a.feedback_hover').length>0);if(!(onblur_event&&hovering_over_link)){var num_comments=DOM.scry(comments,'div.ufi_section').length;var has_likes=(DOM.scry(commentable_item,'div.has_likes').length>0);if(num_comments==0&&!has_likes){CSS.addClass(commentable_item,'collapsed_comments');CSS.removeClass(commentable_item,'expanded_comments');if(CSS.hasClass(commentable_item,'story_ff')){CSS.addClass(commentable_item,'ff_collapsed_comments');CSS.removeClass(commentable_item,'ff_expanded_comments');}}}
if(add_comment_textarea.getControl){window.setTimeout(function(){CSS.addClass(commentable_item,'hidden_add_button');},1);}}
feedcomment_hide_credits_nux_tip(target_fbid,item_id);}}
function feed_comment_show_add_button(target_fbid,item_id,source){var commentable_item=_feedcomment_get_commentable_item_div(target_fbid,item_id,source);CSS.removeClass(commentable_item,'hidden_add_button');}
function _feed_comment_update_count(target_fbid,item_id,target_comment_count,source){var target_selector=_feedcomment_get_comments_target_selector(target_fbid,item_id);if(target_selector){if(target_comment_count==0){CSS.removeClass(target_selector,'target_with_comments');CSS.addClass(target_selector,'target_no_comments');}else{if(CSS.hasClass(target_selector,'target_no_comments')){CSS.removeClass(target_selector,'target_no_comments');CSS.addClass(target_selector,'target_with_comments');}}}
var count_span=_feedcomment_get_target_comment_count_span(target_fbid,item_id);if(count_span){set_inner_html(count_span,target_comment_count.toString());}
var commentable_item=_feedcomment_get_commentable_item_div(target_fbid,item_id,source);var item_total_count=0;if(target_selector){var target_counts=DOM.scry(commentable_item,'.target_count');for(var i=0;i<target_counts.length;i++){item_total_count+=parseInt(target_counts[i].innerHTML,10);}}else{item_total_count=target_comment_count;}
feedback_update_toggle_counts(target_fbid,item_id,source,item_total_count);if(item_total_count==0){CSS.removeClass(commentable_item,'with_comments');CSS.addClass(commentable_item,'no_comments');}else{if(CSS.hasClass(commentable_item,'no_comments')){CSS.removeClass(commentable_item,'no_comments');CSS.addClass(commentable_item,'with_comments');}
if(CSS.hasClass(commentable_item,'autoexpand_mode')){toggle_feedcomments_box_open(target_fbid,item_id,source,false);}}}
function load_all_feed_comments(target_fbid,item_id,target_owner,type_id,assoc_object_id,source,check_hash){if(!assoc_object_id){assoc_object_id=0;}
if(!source){var sources=feedcomment_get_feedback_sources();source=sources['FEEDBACK_SOURCE_PROFILE'];}
var add_comment_form=_feedcomment_get_add_comment_form(target_fbid,item_id);var onResponse=function(asyncResponse){var result=asyncResponse.getPayload();feedcomment_sync_with_markup(target_fbid,item_id,result.all_comments_html,result.comment_count,source);};var onFail=function(response){if(payload=response.getPayload()){if(payload.errTitle||payload.errBody){var error_text=payload.errBody?payload.errBody:payload.errTitle;feedcomment_show_error(target_fbid,item_id,source,error_text);}else{onTransportFail(response);}}else{onTransportFail(response);}};new AsyncRequest().setURI('/ajax/inline_comments.php').setData({'assoc_object_id':assoc_object_id,'check_hash':check_hash,'get_all':1,'item_id':item_id,'target_fbid':target_fbid,'target_owner':target_owner,'type_id':type_id,'source':source}).setHandler(onResponse).setErrorHandler(onFail).send();}
function feedcomment_sync_with_markup(target_fbid,item_id,markup,comment_count,source){var feed_comments=_feedcomment_get_feed_comments(target_fbid,item_id);if(feed_comments){set_inner_html(feed_comments,markup);_feed_comment_update_count(target_fbid,item_id,comment_count,source);}
feedcomment_hide_error(target_fbid,item_id,source);}
function feedcomment_remove_comment(target_fbid,item_id,comment_id,comment_count,source){var comment=_feedcomment_get_comment(target_fbid,item_id,comment_id);if(comment){DOM.remove(comment);_feed_comment_update_count(target_fbid,item_id,comment_count,source);}
feedcomment_hide_error(target_fbid,item_id,source);}
function feedcomment_append_comment(target_fbid,item_id,markup,comment_count,source){var feed_comments=_feedcomment_get_feed_comments(target_fbid,item_id);if(feed_comments){DOM.appendContent(feed_comments,HTML(markup));_feed_comment_update_count(target_fbid,item_id,comment_count,source);}
feedcomment_hide_error(target_fbid,item_id,source);}
function feedcomment_emote(target_fbid,item_id){var feed_comments=_feedcomment_get_feed_comments(target_fbid,item_id);if(!feed_comments){return;}
if(DOMStorage.getData(feed_comments,'emote_magic')){return;}
var nodes=DOM.scry(feed_comments,'div.comment_actual_text');for(var i=0;i<nodes.length;i++){var node=nodes[i];var comment=node.innerHTML;var emotiveComment=Emote.htmlEmote(comment,HTML);if(comment!=emotiveComment){DOM.setContent(node,HTML(emotiveComment));}}
DOMStorage.setData(feed_comments,'emote_magic',true);onunloadRegister(DOMStorage.removeData.bind(DOMStorage,feed_comments,'emote_magic'));}
function remove_feed_comment_dialog(target_fbid,item_id,comment_id,target_owner,source,type_id,assoc_object_id,check_hash){var add_comment_form=_feedcomment_get_add_comment_form(target_fbid,item_id);var onResponse=function(asyncResponse){var result=asyncResponse.getPayload();feedcomment_remove_comment(target_fbid,item_id,comment_id,result.comment_count,source);};var onFail=function(response){if(payload=response.getPayload()){if(payload.errTitle||payload.errBody){var error_text=payload.errBody?payload.errBody:payload.errTitle;feedcomment_show_error(target_fbid,item_id,source,error_text);}else{onTransportFail(response);}}else{onTransportFail(response);}};new Dialog().setTitle(_tx("Delete Comment")).setBody(_tx("Are you sure you want to delete this comment?")).setButtons([{name:'delete',label:_tx("Delete"),handler:bind(this,function(){new AsyncRequest().setURI('/ajax/inline_comments.php').setData({'assoc_object_id':assoc_object_id,'check_hash':check_hash,'del_id':comment_id,'item_id':item_id,'source':source,'target_fbid':target_fbid,'target_owner':target_owner,'type_id':type_id}).setContextData('clicktype','Delete Comment').setHandler(onResponse).setErrorHandler(onFail).send();})},Dialog.CANCEL]).show();}
function toggle_feedcomments_box_open(sole_target_fbid,item_id,source,focus){var commentable_item=_feedcomment_get_commentable_item_div(sole_target_fbid,item_id,source);if(commentable_item){CSS.removeClass(commentable_item,'collapsed_comments');CSS.addClass(commentable_item,'expanded_comments');if(CSS.hasClass(commentable_item,'story_ff')){CSS.removeClass(commentable_item,'ff_collapsed_comments');CSS.addClass(commentable_item,'ff_expanded_comments');}
var first_textarea=_feedcomment_get_first_item_textarea(commentable_item);if(first_textarea&&focus){first_textarea.focus();}}}
function toggle_feedcomments_box(sole_target_fbid,item_id,source,focus){var commentable_item=_feedcomment_get_commentable_item_div(sole_target_fbid,item_id,source);if(commentable_item){CSS.toggleClass(commentable_item,'expanded_comments');CSS.toggleClass(commentable_item,'collapsed_comments');if(CSS.hasClass(commentable_item,'story_ff')){CSS.toggleClass(commentable_item,'ff_expanded_comments');CSS.toggleClass(commentable_item,'ff_collapsed_comments');}
var first_textarea=_feedcomment_get_first_item_textarea(commentable_item);if(first_textarea&&focus){if(CSS.hasClass(commentable_item,'expanded_comments')){first_textarea.focus();}}}}
function _feedcomment_get_commentable_item_div(target_fbid,item_id,source){var commentable_item;var sources=feedcomment_get_feedback_sources();if(source==sources['FEEDBACK_SOURCE_OBJECT']||source==sources['FEEDBACK_SOURCE_OBJECTS_PAGE']){commentable_item=ge('commentable_item_'+item_id);}else{commentable_item=ge('div_story_'+item_id+'_'+target_fbid);if(!commentable_item){commentable_item=ge('div_story_'+item_id);}}
return commentable_item;}
function feedback_update_toggle_counts(target_fbid,item_id,source,count){var commentable_item=_feedcomment_get_commentable_item_div(target_fbid,item_id,source);if(commentable_item){var links=DOM.scry(commentable_item,'span.feedback_link_count');for(var i=0;i<links.length;++i){var link=links[i];DOM.setText(link,count);}}}
function _feedcomment_get_comments_target_wrapper(target_fbid,item_id){return ge('comments_box_'+item_id);}
function _feedcomment_get_comments_target_div(target_fbid,item_id){return _feedcomment_get_first_existing_elem('feed_comments_target',target_fbid,item_id);}
function _feedcomment_get_comments_target_selector(target_fbid,item_id){return ge('target_selector_'+item_id+'_'+item_id+'_'+target_fbid);}
function _feedcomment_get_target_comment_count_span(target_fbid,item_id){return _feedcomment_get_first_existing_elem('target_comment_count',target_fbid,item_id);}
function _feedcomment_get_feed_comments(target_fbid,item_id){return _feedcomment_get_first_existing_elem('feed_comments',target_fbid,item_id);}
function _feedcomment_get_add_comment_form(target_fbid,item_id){return _feedcomment_get_first_existing_elem('add_comment',target_fbid,item_id);}
function _feedcomment_get_error_target(target_fbid,item_id){return _feedcomment_get_first_existing_elem('feed_comments_error',target_fbid,item_id);}
function _feedcomment_get_add_comment_textarea(target_fbid,item_id){return _feedcomment_get_first_existing_elem('add_comment_text',target_fbid,item_id);}
function _feedcomment_get_publish_story_checkbox(target_fbid,item_id){return _feedcomment_get_first_existing_elem('publish_story',target_fbid,item_id);}
function _feedcomment_get_credits_giver_input(target_fbid,item_id){return _feedcomment_get_first_existing_elem('credits_giver',target_fbid,item_id);}
function _feedcomment_get_first_item_textarea(commentable_item){var textareas=commentable_item.getElementsByTagName('textarea');if(textareas.length>0){return textareas[0];}else{return null;}}
function _feedcomment_get_add_comment_button(target_fbid,item_id){return _feedcomment_get_first_existing_elem('submit_comment',target_fbid,item_id);}
function _feedcomment_get_add_comment_wrapper(target_fbid,item_id){var elem;if(elem=ge('add_comment_wrapper_'+item_id+'_'+target_fbid)){return elem;}else{return ge('add_comment_wrapper_'+item_id+'_'+target_fbid);}}
function _feedcomment_get_comment(target_fbid,item_id,comment_id){var elem;if(elem=ge('comment_'+item_id+'_'+target_fbid+'_'+comment_id)){return elem;}else{return ge('comment_'+target_fbid+'_'+comment_id);}}
function _feedcomment_get_first_existing_elem(prefix,target_fbid,item_id){var elem;if(elem=ge(prefix+'_'+item_id+'_'+target_fbid)){return elem;}else if(elem=ge(prefix+'_'+target_fbid)){return elem;}else{return ge(prefix+'_'+item_id)}}
function _feedcomment_get_credits_nux_tip(target_fbid,item_id){return _feedcomment_get_first_existing_elem('credits_nux_tip',target_fbid,item_id);}
function feedcomment_log_ufi_with_credits(){new AsyncRequest().setURI('/ajax/giftcredits/log.php').send();}
function feedcomment_show_credits_nux_tip(target_fbid,item_id){var elem=_feedcomment_get_credits_nux_tip(target_fbid,item_id);var input_elem=_feedcomment_get_credits_giver_input(target_fbid,item_id);if(!elem||!input_elem){return;}
if(!shown(elem)){Vector2.getElementPosition(input_elem,'document').add(-5,25).setElementPosition(elem);$('content').appendChild(elem);animation(elem).to('opacity',1).from(0).show().duration(200).go();}
var timeoutId=DOMStorage.getData(elem,'nuxTipTimeoutId');if(timeoutId){clearTimeout(timeoutId);DOMStorage.removeData(elem,'nuxTipTimeoutId');}}
function feedcomment_hide_credits_nux_tip(target_fbid,item_id){var elem=_feedcomment_get_credits_nux_tip(target_fbid,item_id);if(!elem){return;}
DOMStorage.setData(elem,'nuxTipTimeoutId',setTimeout(hide.bind(null,elem),150));}
function feedcomment_increment_credits_input(input_id){var input_elem=$(input_id);if(!input_elem){return;}
var default_increment=10;var cur_value=parseInt(input_elem.value,10)||0;if(cur_value<0){cur_value=0;}
input_elem.value=cur_value+default_increment;return true;}
function feedcomment_verify_credits(input_elem){if(input_elem.value==''){input_elem.value=0;}else if(!/^\d*$/.test(input_elem.value)){input_elem.value=0;animation(input_elem).to('background','#fff').from('#fcc').duration(140).go();}}

function ft(metadata,hash,type,undo,cat){undo=undo?1:0;var asyncRequestPost=new AsyncSignal('/ajax/f.php',{'meta':metadata,'h':hash,'type':type,'undo':undo,'cat':cat}).send();return true;}

function pymkGrid(grid_id,show_explanation){copy_properties(this,{used_ids:[],boxes_displayed:0,payload_timeouts:0,grid_id:null,pymk_more_link:null,show_explanation:null});if(grid_id&&ge(grid_id)){this.show_explanation=!!show_explanation;this.grid_obj=$(grid_id);var id_divs=DOM.scry(this.grid_obj,'div.friend_grid_col');for(var i=0;i<id_divs.length;i++){this.used_ids.push(parseInt(id_divs[i].getAttribute('id').substring(3)));this.boxes_displayed++;}
var more_link=DOM.scry(this.grid_obj,'a.show_more');if(more_link){this.pymk_more_link=more_link[0];}}else{Util.error('pymkGrid: Either the grid you have specified is invalid or is not detectable in the DOM.');}}
copy_properties(pymkGrid.prototype,{addFriend:function(uid,page,score,source,log){this.modifyFriendship(uid,'add',null,page,score,source,log);return;},hideFriend:function(uid,page,score,source){this.modifyFriendship(uid,'blacklist',null,page,score,source);return;},modifyFriendship:function(uid,action_type,home_panel,page,score,source,log){var friend_data=this.getGridData($('fg_'+uid));var asyncData={used:this.used_ids,replace:uid,get:1,explanation:this.show_explanation,page:page};if(action_type=='blacklist'){asyncData.blacklist=true;asyncData.blacklist_type='blacklist';asyncData.score=score;asyncData.source=source;}else if(log){asyncData.log=true;asyncData.score=score;asyncData.source=source;}
new AsyncRequest().setURI('/ajax/friend_guess.php').setData(asyncData).setHandler(bind(this,this.asyncHandleModify)).setReplayable(false).send();var friend_box=$('fg_'+uid);animation(friend_box).from('opacity',1).to('opacity',0).duration(300).go();if(home_panel){home_panel.addTo('outgoing',home_panel.constructGridItem(friend_data));}
return;},asyncHandleRefresh:function(async){payload=async.getPayload();if(payload.victim&&payload.victim.length>0){for(var i=0;i<payload.victim.length;i++){if(this.used_ids[i]){animation($('fg_'+this.used_ids[i])).from('opacity',1).to('opacity',0).duration(300).go();}}
for(var i=0;i<payload.victim.length;i++){if(this.used_ids[i]){this.replaceItem(this.used_ids[i],payload.victim[i]);}}
for(var i=0;i<payload.victim.length;i++){this.used_ids.unshift(payload.victim[i].uid);}}
if(!payload.more){this._hideMoreLink();}},asyncHandleModify:function(async){payload=async.getPayload();if(payload.victim&&payload.victim.length>0){this.replaceItem(payload.replace,payload.victim[0]);}else{this.hideItem(payload.replace);}
return;},replaceItem:function(replace,victim){var replace_id='fg_'+replace;var box_id='fg_'+victim.uid;if(!ge(box_id)){var new_box=DOM.create('div',{id:box_id,className:'friend_grid_col clearfix'},HTML(victim.box_content));DOM.replace($(replace_id),new_box);animation($(box_id)).from('opacity',0).to('opacity',1).duration(400).go();this.used_ids.push(victim.uid);}else{this.hideItem(replace);}},hideItem:function(replace){this.payload_timeouts++;var replace_id='fg_'+replace;var anim=null;var suggestions=$$('#home_sidebar .sidebar_item.pymk');if(1==suggestions.length&&1==$$('#pymk_ajax_grid .friend_grid_row').length){anim=animation(suggestions[0]);}else{hide('fg_add_'+replace);$(replace_id).unreplaceable=true;var pymkRow=$(replace_id).parentNode;var collapseRow=true;for(var i=0;i<pymkRow.childNodes.length;i++){if(!pymkRow.childNodes[i].unreplaceable){collapseRow=false;break;}}
if(collapseRow){anim=animation(pymkRow).ondone(DOM.remove.bind(null,pymkRow));}}
if(anim){anim.to('height',0).duration(550).hide().ease(animation.ease.end).go();}
this._hideMoreLink();},constructGridItem:function(grid_data){return this.constructRawGridItem(grid_data.uid,grid_data.content);},constructRawGridItem:function(uid,item_content){var gridItem=document.createElement('div');CSS.addClass(gridItem,'friend_grid_col');gridItem.setAttribute('id','friend_'+uid);gridItem.innerHTML=item_content;return gridItem;},getGridData:function(grid_object){if(CSS.hasClass(grid_object,'friend_grid_col')){var gridData={content:grid_object.innerHTML,uid:grid_object.getAttribute('id').toString().slice(3)}
return gridData;}},_removeID:function(uid){for(var i=0;i<this.used_ids.length;i++){if(this.used_ids[i]==uid){this.used_ids.splice(i,1);}}
return;},_hideMoreLink:function(){if(this.pymk_more_link){this.pymk_more_link.style.visibility='hidden';this.pymk_more_link=null;}}});function pymk_friend_added(link_object){pymk_add_friend(link_object.uid,link_object.render_explanation,null,link_object.page);}
function pymk_page_added(args){pymk_add_friend(args.uid,args.has_explanation,null,args.page,args.score,args.source,args.log);}
function pymk_add_friend(uid,has_explanation,existingGrid,page,score,source,log){if(!existingGrid){existingGrid=new pymkGrid('pymk_ajax_grid',has_explanation||false);}
existingGrid.addFriend(uid,page,score,source,log);}
function pymk_hide_friend(uid,has_explanation,existingGrid,page,score,source){if(!existingGrid){existingGrid=new pymkGrid('pymk_ajax_grid',has_explanation);}
if(!score){score=-1;}
if(!source){source='u';}
existingGrid.hideFriend(uid,page,score,source);}

FriendSuggesterDialog={_dialog:null,_close_handler:null,_newcomer:null,show:function(newcomer,friend_added,close_handler,ref){this._close_handler=close_handler||bagofholding;friend_added=friend_added||false;this._newcomer=newcomer;var async=new AsyncRequest().setURI('/ajax/friend_suggester.php').setData({newcomer:newcomer,friend_added:friend_added}).setContextData('clicktype','Suggest a Friend',ref==="profile_others");this._dialog=new Dialog().setAsync(async).show();},cancelMultiselect:function(){this._dialog.hide();this._close_handler(false,null);},submitMultiselect:function(){var data=serialize_form($('friend_suggester_popup_form'));if(!data['ids']){try{fs.notice_show(_tx("You have not selected any friends. Select friends by clicking on their pictures."),true);}catch(ex){this.cancelMultiselect();Util.error('SUGGEST: could not warn user submitting an empty selection: %x',ex);}
return false;}
data['suggest']=1;var async=new AsyncRequest().setURI('/ajax/friend_suggester.php').setData(data);var dialog=new Dialog().setAsync(async);dialog.setCloseHandler(this._close_handler.bind(null,true,dialog));dialog.show();}};

function InlineParticipants(targetId,asyncUri){this.asyncUri=asyncUri;this.target=$(targetId);this.targetId=targetId;if((!this.target)||this.target.pending){return;}
if(this.target.cached){toggle(this.targetId);}else{this.initializeFromTarget();this.fetchParticipants();}}
copy_properties(InlineParticipants.prototype,{fetchParticipants:function(){this.target.pending=true;new AsyncRequest().setURI(this.asyncUri).setMethod('GET').setReadOnly(true).setData(this.getFetchData()).setHandler(bind(this,'fetchedActorsResponse')).setErrorHandler(bind(this,'fetchedActorsError')).send();this.loadTimeout=setTimeout(this.showLoadIndicator.bind(this),200);},showLoadIndicator:function(){this.loadTimeout=null;if(this.target.pending){this.loading=true;CSS.addClass(this.target,'participants_loading');show(this.target);}},hideLoadIndicator:function(){if(this.loadTimeout){clearTimeout(this.loadTimeout);this.loadTimeout=null;}
if(this.loading){CSS.removeClass(this.target,'participants_loading');}},getSearchUri:function(){return this.target.getAttribute("search_href");},fetchedActorsResponse:function(asyncResponse){var payload=asyncResponse.getPayload();var show_more=payload["has_more"];var actors=payload["actors"];var nameContainers=[];if(!actors){return this.fetchedActorsError();}
this.hideLoadIndicator();for(var i=0;i<actors.length;i++){var container=this.createNameContainer(actors[i]);this.target.appendChild(container);}
if(show_more){var search_uri=this.getSearchUri();var search_text=payload['more_text']||this.getSearchText();if(search_uri){var search_link=$N('a',{href:search_uri,className:'see_all'},search_text);this.target.appendChild(search_link);}}
this.target.pending=false;this.target.cached=true;animation(this.target).show().from('opacity',0).to('opacity',1).duration(450).go();},getSearchText:function(){return _tx("See all...");},fetchedActorsError:function(asyncResponse){this.target.pending=false;var search_uri=this.getSearchUri();if(search_uri){goURI(search_uri);}else{hide(this.target);}},createNameContainer:function(spec){var container=$N("div",{title:spec.name,className:"name_container "+
(spec.div_class||"")},null);if(env_get('gk_nile_home')){var img=new RoundedImage(spec.img_src);img.setAlt(spec.name);if(this.cornerBackground){img.setBackground(this.cornerBackground);}
var pic=img.render();}else{var pic=new Image();pic.alt=spec.name;pic.src=spec.img_src;pic.width='50';pic.height='50';}
var pic_link=$N('a',{className:"pic_container",href:spec.profile_href,onclick:spec.profile_onclick||''},pic);container.appendChild(pic_link);var name_link=$N('a',{href:spec.profile_href,onclick:spec.profile_onclick||''},spec.first_name);container.appendChild($N('span',{className:"name"},name_link));return container;}});function StoryParticipants(targetId,linkData,hash){var asyncUri='/ajax/feed_participants_ajax.php';this.parent.construct(this,targetId,asyncUri);this.linkData=linkData;this.hash=hash;}
copy_properties(StoryParticipants.prototype,{initializeFromTarget:function(){this.storyKey=this.target.getAttribute("story_key");this.storyUser=this.target.getAttribute("user");},getFetchData:function(){if(this.linkData){return{sid:this.storyKey,uid:this.storyUser,link_data:this.linkData,hash:this.hash};}else{return{sid:this.storyKey,uid:this.storyUser};}}});StoryParticipants.extend('InlineParticipants');function MutualFriends(targetId){var asyncUri='/ajax/mutual_friends_ajax.php';this.parent.construct(this,targetId,asyncUri);}
copy_properties(MutualFriends.prototype,{initializeFromTarget:function(){this.friend=this.target.getAttribute("friend");},getFetchData:function(){return{uid:this.friend};},getSearchText:function(){return _tx("See all mutual friends");}});MutualFriends.extend('InlineParticipants');function SearchMutualFriends(targetId){this.parent.construct(this,targetId);}
copy_properties(SearchMutualFriends.prototype,{getFetchData:function(){return{uid:this.friend,max:8};}});SearchMutualFriends.extend('MutualFriends');function SuggestionReceivers(targetId,suggesters,newcomer,receiver){var asyncUri='/ajax/suggestion_receivers_ajax.php';copy_properties(this,{suggesters:suggesters,newcomer:newcomer,receiver:receiver});this.parent.construct(this,targetId,asyncUri);}
copy_properties(SuggestionReceivers.prototype,{getFetchData:function(){return{suggesters:this.suggesters,newcomer:this.newcomer,receiver:this.receiver};},initializeFromTarget:bagofholding});SuggestionReceivers.extend('InlineParticipants');function LikeParticipants(feedback_params,target_id,search_uri){var asyncUri='/ajax/like/participants.php';copy_properties(this,{feedback_params:feedback_params,search_uri:search_uri,cornerBackground:RoundedImage.BACKGROUND_GIRLIE});this.parent.construct(this,target_id,asyncUri);}
copy_properties(LikeParticipants.prototype,{getFetchData:function(){return{feedback_params:JSON.encode(this.feedback_params)};},getSearchUri:function(){return this.search_uri;},fetchedActorsResponse:function(response){LikeController.informUpdateState(this.feedback_params.target_fbid,response.getPayload().like_state_info);this.parent.fetchedActorsResponse(response);},initializeFromTarget:bagofholding});LikeParticipants.extend('InlineParticipants');

function KeyEventController(){copy_properties(this,{handlers:{}});document.onkeyup=this.onkeyevent.bind(this,'onkeyup');document.onkeydown=this.onkeyevent.bind(this,'onkeydown');document.onkeypress=this.onkeyevent.bind(this,'onkeypress');}
copy_properties(KeyEventController,{instance:null,getInstance:function(){return KeyEventController.instance||(KeyEventController.instance=new KeyEventController());},defaultFilter:function(event,type){event=$E(event);return KeyEventController.filterEventTypes(event,type)&&KeyEventController.filterEventTargets(event,type)&&KeyEventController.filterEventModifiers(event,type);},filterEventTypes:function(event,type){if(type==='onkeydown'){return true;}
return false;},filterEventTargets:function(event,type){var target=$E(event).getTarget();if(DOM.isNode(target,['input','select','textarea','object','embed'])){if(target.type!='checkbox'&&target.type!='radio'){return false;}}
return true;},filterEventModifiers:function(event,type){if(event.ctrlKey||event.altKey||event.metaKey||event.repeat){return false;}
return true;},registerKey:function(key,callback,filter_callback){if(filter_callback===undefined){filter_callback=KeyEventController.defaultFilter;}
var ctl=KeyEventController.getInstance();var eqv=ctl.mapKey(key);if(is_empty(ctl.handlers)){onunloadRegister(ctl.resetHandlers.bind(ctl));}
for(var ii=0;ii<eqv.length;ii++){key=eqv[ii];if(!ctl.handlers[key]){ctl.handlers[key]=[];}
ctl.handlers[key].push({callback:callback,filter:filter_callback});}},keyCodeMap:{'[':[219],']':[221],'`':[192],'LEFT':[KEYS.LEFT,KeyCodes.Left],'RIGHT':[KEYS.RIGHT,KeyCodes.Right],'RETURN':[KEYS.RETURN],'TAB':[KEYS.TAB],'DOWN':[KEYS.DOWN,KeyCodes.Down],'UP':[KEYS.UP,KeyCodes.Up],'ESCAPE':[KEYS.ESC]}});copy_properties(KeyEventController.prototype,{mapKey:function(k){if(typeof(k)=='number'){return[k];}
if(KeyEventController.keyCodeMap[k.toUpperCase()]){return KeyEventController.keyCodeMap[k.toUpperCase()];}
var l=k.charCodeAt(0);var u=k.toUpperCase().charCodeAt(0);if(l!=u){return[l,u];}
return[l];},onkeyevent:function(type,e){e=$E(e);var evt=null;var handlers=this.handlers[e.keyCode];var callback,filter,abort;if(handlers){for(var ii=0;ii<handlers.length;ii++){callback=handlers[ii].callback;filter=handlers[ii].filter;try{if(!filter||filter(e,type)){abort=callback(e,type);if(abort===false){return Event.kill(e);}}}catch(exception){Util.error('Uncaught exception in key handler: %x',exception);}}}
return true;},resetHandlers:function(){this.handlers={};}});

function UntrustedLink(dom,hash,evt){this.dom=dom;this.url=dom.href;this.hash=hash;this.dom.listen('click',this.onclick.bind(this));this.dom.listen('mousedown',this.onmousedown.bind(this));this.dom.listen('mouseup',this.onmouseup.bind(this));this.dom.listen('mouseout',this.onmouseout.bind(this));this.onmousedown($E(evt));}
UntrustedLink.bootstrap=function(dom,hash,evt){if(dom.__untrusted){return;}
dom.__untrusted=true;new UntrustedLink(dom,hash,evt);}
UntrustedLink.prototype.getRewrittenURI=function(){return(new URI('/l.php')).setQueryData({u:this.url,h:this.hash}).setSubdomain('www');}
UntrustedLink.prototype.onclick=function(){(function(){this.dom.href=this.url;}).bind(this).defer(100);this.dom.href=this.getRewrittenURI();}
UntrustedLink.prototype.onmousedown=function(evt){if(evt.button==2){this.dom.href=this.getRewrittenURI();}}
UntrustedLink.prototype.onmouseup=function(){this.dom.href=this.getRewrittenURI();}
UntrustedLink.prototype.onmouseout=function(){this.dom.href=this.url;}

function UIPagelet(element,src,context_data,data){this._element=ge(element||$N('div'));this._src=src||null;this._context_data=context_data||{};this._data=data||{};this._handler=bagofholding;return this;}
copy_properties(UIPagelet.prototype,{getElement:function(){return this._element;},setHandler:function(handler){this._handler=handler;return this;},go:function(src,data){if(arguments.length>=2||typeof src=='string'){this._src=src;this._data=data||{};}else if(arguments.length==1){this._data=src;}
this.refresh();return this;},refresh:function(){var handler=function(response){this._element.setContent(HTML(response.getPayload()));this._handler();}.bind(this);new AsyncRequest().setURI(this._src).setMethod('GET').setData({data:JSON.encode(merge(this._context_data,this._data))}).setReadOnly(true).setHandler(handler).setOption('bundle',true).send();return this;}});

function UISelectList(){this._callback=bagofholding;this.container=$N('div',{className:'UISelectList clearfix'});this._mode=UISelectList.MULTI_SELECT_MODE;this._inputName='UISelectList_name_'+gen_unique();this._inputs=null;this._labels=null;}
copy_properties(UISelectList,{MULTI_SELECT_MODE:1,SINGLE_SELECT_MODE:2,MULTI_SELECT_MODE_CHECKED_CLASS_NAME:'UISelectList_check_Checked',SINGLE_SELECT_MODE_CHECKED_CLASS_NAME:'UISelectList_radio_Checked'});UISelectList.prototype={setMode:function(mode){if(mode!=UISelectList.MULTI_SELECT_MODE&&mode!=UISelectList.SINGLE_SELECT_MODE){Util.error('invalid mode %s passed to UISelectList.selectMode',mode);return this;}
if(DOM.scry(this.container,'div.UISelectList_Item').length){Util.error("You have to set `mode' before adding any items to "+"UISelectList");return this;}
this._mode=mode;return this;},setCallback:function(fn){this._callback=fn;return this;},addItem:function(label,checked,key){var item={label:label,checked:checked,key:key};this._renderItem(item);return this;},addItems:function(new_items){for(var k=0;k<new_items.length;k++){this.addItem(new_items[k].label,new_items[k].checked,new_items[k].key);}
return this;},clearItems:function(){DOM.empty(this.container);return this;},getElement:function(){return this.container;},reset:function(){var inputs=this._getInputs();var labels=this._getLabels();for(var i=0;i<inputs.length;i++){inputs[i].checked=inputs[i].defaultChecked;CSS.conditionClass(labels[i],this._getCheckedClass(),inputs[i].checked);}},_renderItem:function(item){var input_id='UISelectList'+gen_unique();var input=$N('input',{type:this._getInputType(),id:input_id,name:this._inputName});input.checked=item.checked;input.defaultChecked=item.checked;var link=$N('a',{className:'UISelectList_Label',href:'#'},item.label);if(item.checked){link.addClass(this._getCheckedClass());}
link.listen('click',Event.kill);link.listen('mouseup',this._linkClicked.bind(this,input));input.listen('click',this._clicked.bind(this,input,link,item.key));this.container.appendContent($N('div',{className:'UISelectList_Item'},[input,link]));},_getInputs:function(){return this._inputs||(this._inputs=DOM.scry(this.container,'input'));},_getLabels:function(){return this._labels||(this._labels=DOM.scry(this.container,'a.UISelectList_Label'));},_getInputType:function(){if(this._mode==UISelectList.MULTI_SELECT_MODE){return'checkbox';}
return'radio';},_getCheckedClass:function(){if(this._mode==UISelectList.MULTI_SELECT_MODE){return UISelectList.MULTI_SELECT_MODE_CHECKED_CLASS_NAME;}
return UISelectList.SINGLE_SELECT_MODE_CHECKED_CLASS_NAME;},_linkClicked:function(input,e){input.click();},_clicked:function(input,label,key,e){var clickedElemChecked;if(this._mode==UISelectList.SINGLE_SELECT_MODE){var inputs=this._getInputs();var labels=this._getLabels();if(inputs.length!=labels.length){Util.log('error');return $E(e).stop();}
for(var i=0;i<inputs.length;i++){var checked=input==inputs[i];CSS.conditionClass(labels[i],this._getCheckedClass(),checked);}
clickedElemChecked=true;}else{clickedElemChecked=input.checked;CSS.conditionClass(label,this._getCheckedClass(),input.checked);}
this._callback(clickedElemChecked,key);$E(e).stop();}};

function Barrier(ops_num,callback){if(ops_num===undefined||ops_num<0||callback===undefined){Util.error('You must provide a non-negative number of outstanding '
+'operations and a callback for Barrier constructor.');return null;}
if(ops_num==0){callback();return;}
this.ops_num=ops_num;this.callback=callback;}
copy_properties(Barrier.prototype,{notify:function(){if(this.ops_num<=0){Util.error('Barrier.notify is called more times than it is supposed to be.');return;}
this.ops_num--;if(this.ops_num==0){this.callback();}}});

function PageCache(max_page_num,max_ttl){if(this===window){return new PageCache(max_page_num,max_ttl);}
this._MAX_PAGE_NUM=typeof max_page_num=='undefined'?5:max_page_num;this._MAX_TTL=typeof max_ttl=='undefined'?600000:max_ttl;this._storage={}}
copy_properties(PageCache.prototype,{_normalizeURI:function(uri){return new URI(uri).getUnqualifiedURI().setFragment('').removeQueryData('ref').toString();},addPage:function(uri,properties){uri=this._normalizeURI(uri);if(!this._storage[uri]){this._storage[uri]={};}
var page=this._storage[uri];copy_properties(page,properties);page.accessTime=page.genTime=(new Date()).getTime();this._clearCache();},updatePage:function(uri,obj){uri=this._normalizeURI(uri);if(!this._storage[uri]){return;}
copy_properties(this._storage[uri],obj);},isPageInCache:function(uri){return!!this._storage[this._normalizeURI(uri)];},invalidatePage:function(uri){uri=this._normalizeURI(uri);delete this._storage[uri];},getPage:function(uri){this._clearCache();uri=this._normalizeURI(uri);var page=this._storage[uri];if(!page){return null;}
page.accessTime=(new Date()).getTime();return page;},_clearCache:function(){var cur_time=(new Date()).getTime();var oldest=null
var page_num=0;for(var uri in this._storage){var page=this._storage[uri];var ttl=page.ttl||this._MAX_TTL;if(page.genTime<cur_time-ttl){delete this._storage[uri];continue;}
if(!oldest||this._storage[oldest].accessTime>page.accessTime){oldest=uri;}
page_num++;}
if(page_num>this._MAX_PAGE_NUM&&oldest){delete this._storage[oldest];}}});

var Quickling={isActive:function(){return Quickling._is_active||false;},isFeatureEnabled:function(feature){return Quickling._capabilities&&Quickling._capabilities[feature];},init:function(version,session_length,features,prefetch){if(Quickling._is_initialized){return;}
copy_properties(Quickling,{_is_initialized:true,_is_active:true,_session_length:session_length,_capabilities:features,_is_in_transition:false,_prefetch:prefetch,_version:version});Quickling._instrumentTimeoutFunc('setInterval');Quickling._instrumentTimeoutFunc('setTimeout');PageTransitions.registerHandler(Quickling._transitionHandler);if(Quickling.isFeatureEnabled('page_cache')){Quickling._cache=new PageCache();Quickling._invalidate_msgs=[];Arbiter.subscribe(Arbiter.NEW_NOTIFICATIONS,Quickling._onNotifications);Arbiter.subscribe(Arbiter.REPLAYABLE_AJAX,Quickling._onReplayableAjax);Arbiter.subscribe(Arbiter.PAGECACHE_INVALIDATE,Quickling._onCacheInvalidates);}
if(!Quickling.isFeatureEnabled('domain_rewrite')){PageTransitions._rewriteSubDomain=PageTransitions._revertSubDomain=function(uri){return uri;};}},_onNotifications:function(type,notifications){Util.log('Invalidate PageCache due to new notifications');Quickling._cache=new PageCache();Quickling._invalidate_msgs=[];},_onCacheInvalidates:function(type,msgs){if(Quickling.isFeatureEnabled('page_cache')&&msgs&&msgs.length){for(var ii=0;ii<msgs.length;ii++){if(parseInt(msgs[ii])===0){if(Quickling._is_in_transition&&!Quickling.isFeatureEnabled('flush_cache_in_transition')){break;}
if(Quickling._cache.isPageInCache(PageTransitions.getMostRecentURI())&&!Quickling.isFeatureEnabled('flush_cache_in_page_write')){break;}
Util.log('The whole PageCache is invalidated by the server');Quickling._cache=new PageCache();Quickling._invalidate_msgs=[];return;}}
Quickling._invalidate_msgs=Quickling._invalidate_msgs.concat(msgs);}},_refresh_pagelets:function(){if(is_empty(window.__listeners)){return;}
for(var ii=0;ii<Quickling._invalidate_msgs;ii++){var msg=Quickling._invalidate_msgs[ii];if(msg in window.__listeners){window.__listeners[msg].forEach(function(pagelet){pagelet.refresh();});}}},registerPageCacheHook:function(callback,id){if(!Quickling._is_initialized||!Quickling._is_active||Quickling._is_in_transition||!Quickling.isFeatureEnabled('page_cache')){return;}
var page,cur_uri=PageTransitions.getMostRecentURI();if(page=Quickling._cache.getPage(cur_uri)){if(id){for(var ii=0;ii<page.replays.length;ii++){if(page.replays[ii][0]==id){page.replays.splice(ii,1);ii--;}}}
page.replays.push([id,callback]);}},_onReplayableAjax:function(type,request){if(Quickling._is_in_transition){return;}
var regex=Quickling._whitelist_regex;if(!regex){regex=Quickling._whitelist_regex=new RegExp(env_get('pagecache_whitelist_regex'));}
if(regex.test(URI(request.getURI()).getPath())){return;}
Quickling.registerPageCacheHook(bind(request,request.replayResponse),request._replayKey);},_startQuicklingTransition:function(){Quickling._is_in_transition=true;window.channelManager&&window.channelManager.setActionRequest(true);},_stopQuicklingTransition:function(){(function(){Quickling._is_in_transition=false;}).defer();},goHashOrGoHere:function(where){var uri=URI.getRequestURI();var hash=uri.getFragment();if(hash.startsWith('/')){var dest_url=hash;}else{var dest_url=where;}
setTimeout(function(){PageTransitions.go(dest_url,true);},0);},isPageActive:function(uri){if(uri=='#'){return false;}
var uri=new URI(uri);if(uri.getDomain()&&uri.getDomain()!=URI().getDomain()){return false;}
var regex=Quickling.isPageActive.regex;if(!regex){regex=Quickling.isPageActive.regex=new RegExp(env_get('quickling_inactive_page_regex'));}
if(!Quickling.isFeatureEnabled('full_platform')){query=uri.getQueryData();if(query['_fb_qsub']&&query['_fb_qsub'].startsWith('apps')){if(!query['_fb_q']){return false;}}}
var testURIString=uri.getPath();var queryData=uri.getQueryData();if(queryData){testURIString+='?'+URI.implodeQuery(queryData);}
if(regex.test(testURIString)){return false;}
return true;},_invoke_callbacks:function(hooks){if(hooks){for(var ii=0;ii<hooks.length;ii++){try{eval('(function() {'+hooks[ii]+'})();');}catch(exception){Util.error('Error %x in executing cached hooks: %s',exception,hooks[ii].toString());}}}},_transitionHandler:function(uri){if(Quickling._isTimeToRefresh()){return false;}
if(!Quickling.isPageActive(uri)){return false;}
uri=PageTransitions._revertSubDomain(uri);removeHook('onafterloadhooks');removeHook('onloadhooks');_runHooks('onleavehooks');Quickling._startQuicklingTransition();var page;if(Quickling.isFeatureEnabled('page_cache')&&(page=Quickling._cache.getPage(PageTransitions.getMostRecentURI()))){Quickling._invoke_callbacks(page.onpagecache);page.incremental_updates=AsyncRequest.stashBundledRequest();window.ads_refreshing=false;}
if(Quickling.isFeatureEnabled('page_cache')&&(page=Quickling._cache.getPage(uri))){var barrier=new Barrier(2,function(){$('content').style.visibility="visible";Quickling._invoke_callbacks(page.onafterload);Quickling._invoke_callbacks(page.onafterpagecache);Quickling._stopQuicklingTransition();});AsyncRequest.setBundledRequestProperties({stashedRequests:page.incremental_updates,callback:bind(barrier,barrier.notify),onInitialResponse:Quickling._onInitialResponse,extra_data:{uri:uri.getQualifiedURI().toString(),version:Quickling._version},start_immediately:true});Quickling._preBootloadHandler();Bootloader.loadResources(page.bootload,null,true);document.title=page.title||'Facebook';var body_class=page.body_class||'';CSS.setClass(document.body,body_class
+(CSS.hasClass(document.body,'chat_body')?' chat_body':''));var content_div=$('content');content_div.style.visibility="hidden";DOM.setContent(content_div,HTML(page.html).setDeferred(true));if(content_div&&content_div.style.height=='1234px'){content_div.style.height='';}
PageTransitions.transitionComplete();Quickling._invoke_callbacks(page.onload);Quickling._refresh_pagelets();page.replays.forEach(function(pair){pair[1]();});PageTransitions.restoreScrollPosition();barrier.notify();}else{var quickling_param={version:Quickling._version};uri=new URI(uri).addQueryData({quickling:quickling_param});var prefetch=Quickling._prefetch[uri.getPath()];if(prefetch&&prefetch.length){Bootloader.loadResources(prefetch);}
new AsyncRequest().setPreBootloadHandler(Quickling._preBootloadHandler).setInitialHandler(Quickling._onInitialResponse).setHandler(Quickling._onresponse).setFinallyHandler(PageTransitions.transitionComplete).setMethod('GET').setReadOnly(true).setOption('useIframeTransport',true).setURI(uri).send();}
return true;},_preBootloadHandler:function(response){var content_div=ge('content');if(content_div){content_div.style.height='1234px';DOM.empty(content_div);}
DOMScroll.scrollTo(new Vector2(0,0,'document'),false);return response&&!response.getPayload().redirect;},_onInitialResponse:function(response){var payload=response.getPayload();if(!payload){return true;}
if(payload.redirect){var redirect_uri=PageTransitions._rewriteSubDomain(payload.redirect);if(payload.force||!Quickling.isPageActive(redirect_uri)){go_or_replace(window.location,URI(payload.redirect).removeQueryData('quickling'),true);}else{PageTransitions.go(redirect_uri,true);}
return false;}
if(payload.version&&payload.version!=Quickling._version){go_or_replace(window.location,URI(payload.uri).removeQueryData('quickling'),true);return false;}
return true;},_onresponse:function(response,exec_callbacks){var payload=response.payload;document.title=payload.title||'Facebook';var body_class=payload.body_class||'';CSS.setClass(document.body,body_class
+(CSS.hasClass(document.body,'chat_body')?' chat_body':''));if(payload.hasOnbeforeshow){$('content').style.visibility='hidden';}
for(var div_id in payload.content){var div=ge(div_id);var content=payload.content[div_id];if(div){if(content===undefined||content===null){Util.warn('Content for div id: '+div_id+' is null');}else{var html_content=HTML(content).setDeferred(true);DOM.setContent(div,html_content);}}else{Util.warn('Unknown content div id: '+div_id);}}
if(Quickling.isFeatureEnabled('page_cache')&&payload.page_cache_ttl){Quickling._cache.addPage(PageTransitions.getNextURI(),{title:payload.title,body_class:payload.body_class,html:payload.content['content'],onload:response.onload,onafterload:response.onafterload,bootload:response.bootload,onpagecache:payload.onpagecache,onafterpagecache:payload.onafterpagecache,ttl:payload.page_cache_ttl,replays:[]});}
var content_div=ge('content');if(content_div&&content_div.style.height=='1234px'){content_div.style.height='';}
Quickling._stopQuicklingTransition();if(exec_callbacks){Quickling._invoke_callbacks(response.onload);onafterloadRegister(function(){Quickling._invoke_callbacks(response.onafterload);});}},_isTimeToRefresh:function(){Quickling._load_count=(Quickling._load_count||0)+1;return Quickling._load_count>=Quickling._session_length;},_instrumentTimeoutFunc:function(original_name){window[original_name+'_native']=(function(orig){var _native=function _native(func,delay){return orig(func,delay);};return _native;})(window[original_name]);window[original_name]=function _setTimeout(func,delay,clear_on_quickling_event){var timeout_id=window[original_name+'_native'](func,delay);if(delay>0){onunloadRegister(function(){clearInterval(timeout_id);},clear_on_quickling_event);}
return timeout_id;};}};

function Template(source){copy_properties(this,{_templateSource:source});}
copy_properties(Template.prototype,{getSource:function(){return this._templateSource;},render:function(template_data){var replaceFunction=function(data,all_matches,operator,key){var translator=htmlize;switch(operator){case'H':translator=function(s){return s;};break;}
return data[key]?translator(data[key]):'';}.curry(template_data||{});return this._templateSource.replace(/\$(H)?{(\w+)\}/g,replaceFunction);}});var TemplateRegistry={_storage:{},registerTemplate:function(name,template){if(typeof(template)=="string"){template=new Template(template);}
this._storage[name]=template;return this;},unregisterTemplate:function(name){delete this._storage[name];},hasTemplate:function(name){return name in this._storage;},getTemplate:function(name){if(this.hasTemplate(name)){return this._storage[name];}
return null;},registerServerSideTemplate:function(path,callback,synchronous,evaluate){callback=callback||bagofholding;synchronous=!!synchronous;evaluate=!!evaluate;if(this.hasTemplate(path)){callback();return this;}
var async=new AsyncRequest(path).setReadOnly(true).setMethod('GET').setOption('asynchronous',!synchronous).setOption('suppressEvaluation',!evaluate)
if(!synchronous){async.setErrorHandler(bind(this,this._registerErrorHandler,path)).setHandler(bind(this,this._registerHandler,path,callback));}
async.send();if(synchronous){this.registerTemplate(path,new Template(async.transport.responseText));callback();}
return this;},_registerErrorHandler:function(path,response){Util.warn('Failed to register template "%s"',path);},_registerHandler:function(path,evaluate,callback,response){var payload=response.getPayload();var template=null;if(evaluate){if(payload.template){template=payload.template;}}else{template=payload;}
if(template){this.registerTemplate(path,template);callback();}else{Util.error('No template found in response payload');}},_onRegisterTemplate:function(type,data){if(type=='template/registerTemplate'){if(!data||!data.name||!data.template){Util.warn('TemplateRegister: Invalid template data.')}else{this.registerTemplate(data.name,data.template);}
return false;}
Util.warn('TemplateRegister: Invalid arbiter message type: %s',type);return true;}}
Arbiter.subscribe('template/registerTemplate',TemplateRegistry._onRegisterTemplate.bind(TemplateRegistry),Arbiter.SUBSCRIBE_ALL);

function TemplateObject(template,data){data=data||{};if(!(template instanceof Template)){if(TemplateRegistry.hasTemplate(template)){template=TemplateRegistry.getTemplate(template);}else if(template instanceof URI){TemplateRegistry.registerServerSideTemplate(template.toString(),null,true);template=TemplateRegistry.getTemplate(template);}}
if(template==null){throw new Error("Template could not be found");}
var rendered_source=template.render(data);copy_properties(this,{_nodes:HTML(rendered_source).getNodes(),_template:template});TemplateObject.bindNodes(this._nodes,this);}
copy_properties(TemplateObject,{bindNodes:function(nodes,scope){var all_nodes=[];for(var i=0;i<nodes.length;i++){if(nodes[i].nodeType==DOM.NODE_TYPES.ELEMENT){all_nodes.push(nodes[i]);var node_collection=nodes[i].getElementsByTagName('*');all_nodes=all_nodes.concat(to_array(node_collection));}}
for(var i=0;i<all_nodes.length;i++){var bind_point=all_nodes[i].getAttribute('bindPoint');var listeners=all_nodes[i].getAttribute('listen');if(bind_point){if(hasArrayNature(scope[bind_point])){scope[bind_point].push(all_nodes[i]);}else{scope[bind_point]=all_nodes[i];}}
if(listeners){listeners.replace(/(\w+) *: *(\w+)/g,function(node,match_str,event_name,handler){if(typeof(this[handler])=="function"){Event.listen(node,event_name,bind(this,this[handler]));}else{Event.listen(node,event_name,bind(this,TemplateObject._eventWrapper,handler));}}.bind(scope,all_nodes[i]));}}},_eventWrapper:function(handler_name,event){if(typeof(this[handler_name])=="function"){return this[handler_name](event);}else{Util.warn('Event wrapper [%s] not defined for template object',handler_name);return true;}}});copy_properties(TemplateObject.prototype,{getNodes:function(){return this._nodes;}});

function LikeController(){}
copy_properties(LikeController,{saveChangeLike:function(feedback_params,like_exists,check_hash){var target_fbid=feedback_params.target_fbid;LikeController.informChangeLike(target_fbid,like_exists);var data={feedback_params:JSON.encode(feedback_params),should_delete:!like_exists,check_hash:check_hash};var handler=bind(null,LikeController.changeLikeResponse,target_fbid,like_exists);new AsyncRequest().setURI('/ajax/like/like.php').setData(data).setHandler(handler).setErrorHandler(handler).send();},changeLikeResponse:function(target_fbid,like_exists,response){if(response.isReplay()){LikeController.informChangeLike(target_fbid,like_exists);}else{if(response.getError()){if(!response.getErrorIsWarning()){LikeController.informChangeLike(target_fbid,!like_exists);}
ErrorDialog.showAsyncError(response);}}},informChangeLike:function(target_fbid,like_exists){LikeController.informUpdateState(target_fbid,{exists:like_exists});},informUpdateState:function(target_fbid,message){Arbiter.inform('like/update/'+target_fbid,message);}});function LikeComponent(feedback_params,exists,container_id){copy_properties(this,{feedback_params:feedback_params,exists:exists,container_id:container_id,container:null});Arbiter.subscribe('like/update/'+feedback_params.target_fbid,this.updateState.bind(this));}
copy_properties(LikeComponent.prototype,{updateState:function(type,message){if(!this.init()){return;}
this._updateState(message);},_updateState:function(message){if(typeof message.exists!='undefined'){this._updateLikeState(message.exists);}},_updateLikeState:function(exists){if(exists==this.exists){return;}
this.exists=exists;this.updateClasses();},init:function(){this.container=ge(this.container_id);return!!this.container;},updateClasses:function(){CSS.conditionClass(this.container,'like_exists',this.exists);CSS.conditionClass(this.container,'like_not_exists',!this.exists);}});function LikeLink(feedback_params,exists,container_id){this.parent.construct(this,feedback_params,exists,container_id);}
LikeLink.extend('LikeComponent');function LikeBox(feedback_params,exists,has_other_users,container_id){copy_properties(this,{has_other_users:has_other_users,animating:false,pending_animation:false});this.parent.construct(this,feedback_params,exists,container_id);}
copy_properties(LikeBox,{BOX_ANIM_TIME:200,SENTENCE_ANIM_TIME:200,PIC_ANIM_TIME:300});copy_properties(LikeBox.prototype,{init:function(){if(!this.parent.init()){return false;}
copy_properties(this,{sentence_container:DOM.find(this.container,'div.like_sentence_container'),sentence_exists:DOM.find(this.container,'div.like_sentence_exists'),sentence_not_exists:DOM.find(this.container,'div.like_sentence_not_exists')});return true;},updateClasses:function(){this.parent.updateClasses();var has_likes=this.exists||this.has_other_users;CSS.conditionClass(this.container,'has_likes',has_likes);CSS.conditionClass(this.container,'no_likes',!has_likes);},onDoneAnimating:function(){this.animating=false;if(this.pending_animation){this.pending_animation=false;this._animate();}else{this.updateClasses();}},_updateState:function(message){if(message.sentence_exists&&message.sentence_not_exists){this._updateSentences(HTML(message.sentence_exists),HTML(message.sentence_not_exists));if(!this.init()){return false;}}
this.parent._updateState(message);},_updateSentences:function(sentence_exists,sentence_not_exists){if(sentence_exists!=this.sentence_exists.innerHTML){DOM.setContent(this.sentence_exists,sentence_exists);}
if(sentence_not_exists!=this.sentence_not_exists.innerHTML){DOM.setContent(this.sentence_not_exists,sentence_not_exists);}},_updateLikeState:function(exists){if(exists==this.exists){return;}
this.exists=exists;if(this.animating){this.pending_animation=!this.pending_animation;return false;}
this._animate();},_animate:function(){this.animating=true;var was_expanded=(!this.exists||this.has_other_users);var expanded=(this.exists||this.has_other_users);var ondone=bind(this,'onDoneAnimating');if(!was_expanded&&expanded){ondone();CSS.setOpacity(this.sentence_container,0);animation(this.container).from('height','0px').to('height','auto').duration(LikeBox.BOX_ANIM_TIME).show().go();animation(this.sentence_container).to('opacity',1).duration(LikeBox.BOX_ANIM_TIME).go();return;}else if(was_expanded&&!expanded){var close_ondone=bind(this,function(){ondone();feed_comment_hide_add_box(this.feedback_params.target_fbid,this.feedback_params.item_id,this.feedback_params.source,false);});animation(this.sentence_container).to('opacity',0).duration(LikeBox.BOX_ANIM_TIME).go();animation(this.container).to('height','0px').duration(LikeBox.BOX_ANIM_TIME).hide().ondone(close_ondone).go();return;}
var sentence_show=this.exists?this.sentence_exists:this.sentence_not_exists;var sentence_hide=this.exists?this.sentence_not_exists:this.sentence_exists;animation(sentence_hide).to('opacity',0).duration(LikeBox.SENTENCE_ANIM_TIME).hide().go();var sentence_show_anim=animation(sentence_show).from('opacity',0).to('opacity',1).duration(LikeBox.SENTENCE_ANIM_TIME).show();var viewer_pic=DOM.scry(this.container,'div.like_participant_viewer')[0];if(!viewer_pic){sentence_show_anim.ondone(ondone);}
sentence_show_anim.go();animation(this.sentence_container).from('height',Vector2.getElementDimensions(sentence_hide).y).to('height',Vector2.getElementDimensions(sentence_show).y).duration(LikeBox.SENTENCE_ANIM_TIME).go();if(viewer_pic){var border_pic=DOM.scry(this.container,'div.like_participant_border')[0];if(this.exists){CSS.setOpacity(viewer_pic,0);var viewer_anim=animation(viewer_pic).from('width','0px').to('width','auto').show().duration(LikeBox.PIC_ANIM_TIME).checkpoint().to('opacity',1).duration(LikeBox.PIC_ANIM_TIME).ondone(ondone);if(border_pic){animation(border_pic).to('opacity',0).hide().duration(LikeBox.PIC_ANIM_TIME).ondone(bind(viewer_anim,viewer_anim.go)).go();}else{viewer_anim.go();}}else{var viewer_anim=animation(viewer_pic).to('opacity',0).duration(LikeBox.PIC_ANIM_TIME).checkpoint().to('width','0px').duration(LikeBox.PIC_ANIM_TIME);if(border_pic){var border_anim=animation(border_pic).from('opacity',0).to('opacity',1).show().duration(LikeBox.PIC_ANIM_TIME).ondone(ondone);viewer_anim.ondone(bind(border_anim,border_anim.go));}else{viewer_anim.ondone(ondone);}
viewer_anim.go();}}}});LikeBox.extend('LikeComponent');

function pymk_refresh(onResponse,onError){if(window.pymk_refreshing){return;}
var possible=['pymk_hp_box'];var locations=[];for(var i=0;i<possible.length;i++){if(ge(possible[i])){locations.push(possible[i]);}}
if(locations.length==0){return;}
var data={'locations':locations};var _onResponse=function(response){window.pymk_refreshing=false;var divs=response.getPayload();for(var id in divs){var location=ge(id);if(location){if(divs[id].length>0){location.replace(HTML(divs[id]));}else{hide(location);}}}
if(onResponse){onResponse(response);}}
var _onError=function(response){window.pymk_refreshing=false;if(onError){onError(response);}}
new AsyncRequest().setURI('/ajax/pymk_refresh.php').setData(data).setOption('bundle',true).setHandler(_onResponse).setErrorHandler(_onError).setReplayable(false).send();window.pymk_refreshing=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=ge('filter_init')?$('filter_init').value:'';$('search').sf.value=ge('filter_sf')?$('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').setReadOnly(true).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();}
var SearchDashboardKeyboardHandler=function(){return{right_arrow_key_handler:function(event,type){if(event.ctrlKey){if($('search_dashboard_next_session').href){goURI($('search_dashboard_next_session').href);}}else{if($('search_dashboard_next_query').href){goURI($('search_dashboard_next_query').href);}}
return false;},left_arrow_key_handler:function(event,type){if(event.ctrlKey){if($('search_dashboard_prev_session').href){goURI($('search_dashboard_prev_session').href);}}else{if($('search_dashboard_prev_query').href){goURI($('search_dashboard_prev_query').href);}}
return false;},right_arrow_key_filter:function(event,type){return true;}}}();

var share_data=null;var share_last_comment={p:null,t:null};function share_internal_config(params){if(share_last_comment.p==params){params+='&c='+escapeURI(share_last_comment.t?share_last_comment.t:'');}else{share_last_comment.p=params;}
var async=new AsyncRequest().setURI('/ajax/share_dialog.php?'+params).setMethod('GET').setReadOnly(true);var dialog=new Dialog().setAsync(async).setContentWidth(445).setStackable(true).show();return false;}
function share_show_error(params){var dialog=new Dialog().setTitle(_tx("Invalid URL")).setBody(_tx("Sorry, you have entered an invalid URL.")).setButtons(Dialog.OK).show();return false;}
function share_is_shareable(url){return(/(?:https?:\/\/)?\w+\.\w+/.test(url));}
function share_internal_bookmarklet(){if(/http:\/\/[^\/]*?\/posted?\.php/.test(document.location.href)){var dialog=new Dialog().setClassName('share_congratulations').setTitle(_tx("Share")).setBody('<div class="status"><h2>'+_tx("You've successfully installed the bookmarklet.")+'</h2><p>'
+_tx("Click it on an external site to share it with your friends.")+'</p></div>').setButtons(Dialog.OK).show();}else{throw 0;}}
function share_show_delete_dialog(context,href){var dialog=new contextual_dialog();dialog.set_context(context);dialog.show_choice(_tx("Are you sure you want to delete this item?"),_tx("Deleting this item will also remove all its comments."),_tx("Delete Item"),function(){_share_delete_clicked(this,context,href);},_tx("Cancel"),function(){generic_dialog.get_dialog(this).hide();});return false;}
function _share_delete_clicked(button,context,href){while(context.parentNode&&!CSS.hasClass(context,'sharebox_item')){context=context.parentNode;}
if(!CSS.hasClass(context,'sharebox_item')){return false;}
generic_dialog.get_dialog(button).hide();new AsyncRequest().setURI(href).send();DOM.remove(context);}
function share_play_video(share_id,unique_id){_share_log_play_content(share_id,'video');if(holder=ge(unique_id+'_holder')){if(container=holder.parentNode.parentNode){CSS.addClass(container,'playing');}}
return false;}
function _share_log_play_content(share_id,media_type){new AsyncRequest().setURI('/ajax/shareplay_ajax.php').setData({s:share_id,m:media_type}).send();}
function share_composer_method(obj,method){if(method!="send"){obj.focus();}
var tabs=obj.parentNode.parentNode.getElementsByTagName('a');for(var i=0;i<tabs.length;i++){CSS.removeClass(tabs[i],'selected');}
CSS.addClass(obj,'selected');while(!CSS.hasClass(obj,'share_composer')&&obj){obj=obj.parentNode;}
if(!obj){Util.error("Could not find share composer");return true;}
CSS.setClass(obj,'share_composer share_status_'+method);return false;}
function share_send_onsubmit(obj){return _share_onsubmit_to('ids','send',obj);}
function share_wallpost_onsubmit(obj){return _share_onsubmit_to('wall_id','wall',obj);}
function share_post_onsubmit(obj,privacy_widget){return _share_onsubmit('post',obj,privacy_widget);}
function _share_onsubmit_to(ids,post_action,obj){var ids=$(ids);if(!ids.tokenizer||ids.tokenizer.count_names()==0){new ErrorDialog().showError(_tx("This field is required."),_tx("You must specifiy at least one recipient for this message."));return false;}
return _share_onsubmit(post_action,obj);}
function _share_onsubmit(post_action,obj,privacy_widget)
{var post=serialize_form(obj);post.action=post_action;var inputs=obj.getElementsByTagName('input');for(var i=0;i<inputs.length;i++){inputs[i].disabled=true;}
var inputs=obj.getElementsByTagName('textarea');for(var i=0;i<inputs.length;i++){inputs[i].disabled=true;}
share_last_comment.t=inputs[0].value;var divs=obj.getElementsByTagName('div');for(var i=0;i<divs.length;i++){if(typeof divs[i].tokenizer!='undefined'){divs[i].tokenizer.disable();}else if(!CSS.hasClass(divs[i],'tokenizer')){CSS.addClass(divs[i],'tokenizer_locked');}}
while(!CSS.hasClass(obj,'dialog_content')&&obj){obj=obj.parentNode;}
if(!obj){Util.error("Could not locate base element for dialog");return false;}
post.privacy_data={};if(privacy_widget){copy_properties(post.privacy_data,privacy_widget.getData());}
new AsyncRequest().setURI('/ajax/share.php').setData(post).setHandler(share_post_send_callback.bind(obj)).send();}
function share_post_send_callback(response){payload=response.getPayload();if(payload['html']){set_inner_html(this,payload['html']);if(payload['redr']){setTimeout(function(){goURI(payload['redr']);},3000);}else{var gd=generic_dialog.get_dialog(this);var tmout=payload['timeout']||3000;if(gd){gd.fade_out(500,tmout);}else if(payload['close']){setTimeout(function(){self.close();},tmout);}}}else if(payload['redr']){goURI(payload['redr']);}}
function share_scroll_to_comment(share_id,comment_id){var target;var target_offset;if(share_id&&comment_id){target=ge('comment_'+share_id+'_'+share_id+'_'+comment_id);if(!target){target=ge('comment_'+share_id+'_'+comment_id);}
target_offset=-10;}else{target=ge('share_footer'+share_id);target_offset=0;}
if(target){var target_top=Vector2.getElementPosition(target).y-100;animation(DOMScroll.getScrollRoot()).to('scrollTop',(target_top+target_offset)/2).duration(750).go();window.setTimeout(function(){target_top=Vector2.getElementPosition(target).y;animation(DOMScroll.getScrollRoot()).to('scrollTop',target_top+target_offset).ease(animation.ease.end).duration(750).go();},750);}}
Arbiter.inform("template\/registerTemplate", {"name":"\/templates\/UIActionMenu.tmpl","template":"\n<div class=\"UIActionMenu\" bindPoint=\"root\">\n  <span class=\"UIActionMenu_ButtonOuter\">\n    <span class=\"UIActionMenu_ButtonInner\"><\/span>\n    <span class=\"UIActionMenu_Icon\" bindPoint=\"icon\"><\/span>\n    <span class=\"UIActionMenu_Text\" bindPoint=\"text\"><\/span>\n    <span class=\"UIActionMenu_Chevron\"><\/span>\n  <\/span>\n  <div class=\"UIActionMenu_Menu\" bindPoint=\"menu\"><\/div>\n<\/div>\n"}, Arbiter.BEHAVIOR_PERSISTENT);

function UIActionMenu(title){copy_properties(this,{_dirty:true,_title:title,root:null,icon:null,text:null,menu:null});this._selected=false;this._contentCallback=bagofholding;this.parent.construct(this,URI('/templates/UIActionMenu.tmpl'));this._initialize();}
UIActionMenu.extend('TemplateObject');copy_properties(UIActionMenu,{ICONS:{LOCK:'UIActionMenu_Lock'},COLORS:{BLUE:'UIActionMenu_Blue'}});UIActionMenu.prototype._initialize=function(){var cancel=false,init=null;init=Event.listen(this.root,'mousedown',function(){DOM.setContent(this.menu,this._getContent());init.remove();}.bind(this));if(ua.ie()){Event.listen(this.root,'mousedown',function(event){if(this.menuVisible()&&!DOM.contains(this.menu,event.getTarget())){document.body.blur();}}.bind(this));Event.listen(this.root,'activate',this.showMenu.bind(this));Event.listen(this.root,'deactivate',this.hideMenu.bind(this));Event.listen(this.root,'selectstart',Event.kill);}else{this.input=$N('input',{type:'button'});DOM.insertBefore(this.input,DOM.find(this.root,'span.UIActionMenu_ButtonInner'));Event.listen(this.root,'mousedown',function(event){var target=event.getTarget();if(DOM.contains(this.menu,target)){if(!DOM.isNode(target,'input')){setTimeout(function(){this.input.focus();}.bind(this),100);}
cancel=true;return;}
this.toggleMenu();this.input.focus();return false;}.bind(this));Event.listen(this.input,'blur',function(event){if(cancel){cancel=false;return;}
this.hideMenu();}.bind(this));}};UIActionMenu.prototype.menuVisible=function(){return CSS.hasClass(this.root,'UIActionMenu_Active');};UIActionMenu.prototype.hideMenu=function(){CSS.removeClass(this.root,'UIActionMenu_Active');return this;};UIActionMenu.prototype.showMenu=function(){CSS.addClass(this.root,'UIActionMenu_Active');return this;};UIActionMenu.prototype.toggleMenu=function(){if(this.menuVisible()){return this.hideMenu();}else{return this.showMenu();}};UIActionMenu.prototype.setAlignRight=function(right){CSS.conditionClass(this.root,'UIActionMenu_AlignRight',right);return this;};UIActionMenu.prototype.setContentCallback=function(fn){this._contentCallback=fn;return this;};UIActionMenu.prototype.setSuppressButton=function(suppress){CSS.conditionClass(this.root,'UIActionMenu_SuppressButton',suppress);return this;};UIActionMenu.prototype.setColor=function(color){switch(color){case UIActionMenu.COLORS.BLUE:CSS.addClass(this.root,color);break;default:CSS.removeClass(this.root,color);}
return this;};UIActionMenu.prototype.setIcon=function(icon){switch(icon){case UIActionMenu.ICONS.LOCK:CSS.addClass(this.root,'UIActionMenu_IconIncluded');CSS.addClass(this.icon,icon);break;default:CSS.removeClass(this.root,'UIActionMenu_IconIncluded');Util.error('invalid icon passed to `UIActionMenu.setIcon`');}
return this;};UIActionMenu.prototype._getContent=function(){var content=this._contentCallback();if(this.input){var inputs=DOM.scry(content,'input');inputs.each(function(input){Event.listen(input,'blur',function(){this.input.focus();}.bind(this));},this);}
return content;};UIActionMenu.prototype.setTitle=function(title){this._title=title;DOM.setContent(this.text,this._title);return this;};UIActionMenu.prototype.getNodes=function(){DOM.setContent(this.text,this._title);this._dirty=false;return[this.root];};

UIIntentionalStory={setup:function(root,data){if(!root||!data){return null;}
if(data.unfollow){var hover=Event.listen(root,'mouseover',function(){this.createUnfollowMenu(root,data);hover.remove();}.bind(this));}},createUnfollowMenu:function(root,data){var menuRoot=root.scry('div.UIStory_Hide')[0];if(!menuRoot){return;}
var title=data.title;data=data.unfollow;var menu=new UIActionMenu();var list=new UISelectList();var listCallback=function(root,menu,list,checked,data){menu.hideMenu();list.reset();var unfollowData=copy_properties({storyID:root.id},data);UIIntentionalStream.instance.unfollow(unfollowData);}.bind(this,root,menu,list);list.setMode(UISelectList.SINGLE_SELECT_MODE).setCallback(listCallback);data.users.each(function(user){list.addItem(HTML(user.hideString),false,user);});if(data.app){list.addItem(HTML(data.app.hideString),false,data.app);}
menu.setTitle(title).setContentCallback(list.getElement.bind(list)).setSuppressButton(true).setAlignRight(true);menuRoot.setContent(menu.getNodes());},_moreDetails:{},expandStory:function(story_id,actor_id,newest,oldest){var data=UIIntentionalStream.instance.getCurrentParams();data.expand_story_uid=actor_id;data.newest=newest;data.oldest=oldest;var kwargs={expandStoryID:story_id};hide($(story_id).find('div.UIIntentionalStory_CollapsedStories'));UIIntentionalStream.instance.refresh(UIIntentionalStream.REFRESH_EXPAND,data,kwargs);},morePrivacyDetails:function(fbid,row,elem){if(is_empty(this._moreDetails)){onunloadRegister(function(){this._moreDetails={};}.bind(this));}
if(this._moreDetails[fbid]){return;}
this._moreDetails[fbid]=true;new AsyncRequest().setURI('/ajax/privacy/more_details.php').setData({fbid:fbid,privacy_data:row}).setHandler(function(response){var explanation=response.getPayload().explanation;DOM.setContent(DOM.find(elem,'span.UITooltip_Text'),explanation);}).setErrorHandler(bagofholding).setTransportErrorHandler(bagofholding).send();}};

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;}

function tz_calculate(timestamp){var d=new Date();var raw_offset=d.getTimezoneOffset()/30;var time_sec=d.getTime()/1000;var time_diff=Math.round((timestamp-time_sec)/1800);var rounded_offset=Math.round(raw_offset+time_diff)%48;if(rounded_offset==0){return 0;}else if(rounded_offset>24){rounded_offset-=Math.ceil(rounded_offset/48)*48;}else if(rounded_offset<-28){rounded_offset+=Math.ceil(rounded_offset/-48)*48;}
return rounded_offset*30;}
function ajax_tz_set(tzForm){var timestamp=tzForm.time.value;var gmt_off=-tz_calculate(timestamp);var cur_gmt_off=tzForm.tz_gmt_off.value;if(gmt_off!=cur_gmt_off){var ajaxUrl='/ajax/autoset_timezone_ajax.php';new AsyncSignal(ajaxUrl,{user:tzForm.user.value,gmt_off:gmt_off}).send();}}
function tz_autoset(){var tz_form=ge('tz_autoset_form');if(tz_form){ajax_tz_set(tz_form);}}

function VideoHistogram(){this.videos={};this.video_payloads={};this.listening=false;this.checking=false;}
VideoHistogram.prototype.start=function(swf_id){var new_video=document[swf_id]||window[swf_id];this.videos[swf_id]=new_video;this.listening=true;}
VideoHistogram.prototype.videoFinished=function(swf_id,payload){this.videos[swf_id]=null;this.setPayload(swf_id,payload);this.updateServer();}
VideoHistogram.prototype.setPayload=function(swf_id,payload){this.video_payloads[swf_id]=payload;}
VideoHistogram.prototype.updateServer=function(){var big_payload=[];for(var swf_id in this.video_payloads){var video_report=this.video_payloads[swf_id];this.video_payloads[swf_id]=null;if(video_report){big_payload.push(video_report);}}
var json_payload=JSON.encode(big_payload);new AsyncSignal('/video/motion_log.php',{'h':json_payload}).send();this.listening=false;this.checking=false;}
VideoHistogram.prototype.checkStatus=function(){if(this.listening){this.checking=true;for(var v in this.videos){if(this.videos[v].reportTime){this.videos[v].reportTime();}}
this.updateServer(