
(function(){window.$G=function(_){document.observe('dom:loaded',_);return this;};window.$g=function(_){Event.observe(window,'load',_);return this;};window.$gg=function(_){Event.observe(window,'unload',_);return this;};var
_data={},_CONST={DOMAIN:'gays.com',BASE_URL:''},_timer={},_frag=document.createElement('div'),rFalse=function(){return false;},showError=function(error){if(error instanceof Error){alert(error.lineNumber+'||'+e.message);}else{alert(error);}},Gays=window.Gays={init:function(data){document.domain=_data.domain=data.domain||_CONST.DOMAIN;_data.baseUrl=data.baseUrl||_CONST.BASE_URL;_data.userId=data.userId||'';_data.userName=data.userName||'';_data.userAvatar=data.userAvatar||'';_data.timeOffset=data.time?Math.floor(((new Date).getTime()-data.time)/1000)*1000:0;window.onkeydown=function(e){if(e.keyCode==27)return false;}
$g(function(){_data.pageLoaded=true;});},pageLoaded:function(){return _data.pageLoaded==true;},getDomain:function(){return _data.domain||_CONST.DOMAIN;},getBaseUrl:function(){return _data.baseUrl||_CONST.BASE_URL;},getUserId:function(){return _data.userId;},getUserName:function(){return _data.userName;},getProfileUrl:function(id){return Gays.getBaseUrl()+'/profile/'+_data.userId;},getUserAvatar:function(){return _data.userAvatar;},getTimeOffset:function(){return _data.timeOffset;},getServDate:function(){var date=new Date;date.setTime(date.getTime()-_data.timeOffset);return date;}};Gays.Util={exists:function(object){return!(typeof(object)=='undefined'||object==null);},isArray:function(object){return object instanceof Array;},isFunction:function(object){return typeof object=='function';},isBoolean:function(object){return typeof object=='boolean';},isString:function(object){return typeof object=='string';},isNumber:function(object){return typeof object=='number';},param:function(inputValue,defaultValue){return this.exists(inputValue)?inputValue:defaultValue;},extend:function(destination,source,filter){var key;switch(typeof filter){case'function':for(key in source){if(!!filter(destination[key],source[key])){destination[key]=source[key];}}
break;case'boolean':for(key in source){destination[key]=((filter?source[key]:destination[key])||source[key]);}
break;default:for(key in source){destination[key]=source[key];}
break;}
return destination;},keys:function(object){var results=[];for(var key in object)
results.push(key);return results;},each:function(object,fn){if(typeof(fn)=='function'&&object){if(object instanceof Array){for(var i=0;i<object.length;i++){fn(object[i],i,object);}}else{for(var i in object){fn(object[i],i,object);}}}},call:function(fn){try{if(this.isFunction(fn)){var i=1,args=[];for(;i<arguments.length;i++)
args[args.length]=arguments[i];return fn.apply(null,args);}}catch(e){}},now:function(){return new Date();},delay:function(name,fn,time){this.stopDelay(name);try{_timer[name]=setTimeout(fn,time);}catch(e){delete _timer[name];}},stopDelay:function(name){if(_timer[name]){clearTimeout(_timer[name]);delete _timer[name];}},escapeHTML:function(string){return string.toString().replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');},unescapeHTML:function(string){return string.replace(/<\w+(\s+("[^"]*"|'[^']*'|[^>])+)?>|<\/\w+>/gi,'').replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&amp;/g,'&');},fillTemplate:function(template,data){for(var key in data){template=template.replace(new RegExp('#'+key+'#','g'),function(){return data[key];});}
return template;},praseJSON:function(str){try{return eval('('+str+')');}catch(e){return null;}},parseHTML:function(template,data){var result=document.createDocumentFragment(),node;if(data)template=this.fillTemplate(template,data);_frag.innerHTML=template;while(_frag.firstChild){node=_frag.removeChild(_frag.firstChild);if(node.nodeType==1)result.appendChild(node);}
_frag.innerHTML='';return result;},renderLink:(function(){var pattern=/(?:(https?):\/\/|www\.)\S+/gi,urlClean=/[.,;?]+$/i;function toLink(url,protocol){var clean=urlClean.exec(url),end='';if(clean){end=clean[0];url=url.slice(0,clean.index);}
var href=protocol?url:'http://'+url;return'<a href="'+href+'" class="hyperL external" target="_blank"'+' title="'+href+'"'+'>'+url+'</a>'+end;}
return function(text){return text.toString().replace(pattern,toLink);}})(),popupWindow:function(url,name,props){var wname='gays_com_'+(new Date).getTime();window.name=wname;url=url.replace(/([^?]+)\??(.*)/i,'$1?opener='+wname+'&$2');return window.open(url,name,props);},resizeTextarea:function(t){t=$(t);var lines=t.value.split('\n'),lineNumber=0,self=this;lines.each(function(line){var lineLength=line.length;if(lineLength>=t.cols){lineNumber+=Math.floor(lineLength/t.cols);}});currentRows=lines.length+lineNumber;if(currentRows>t.rows){t.rows=currentRows;}},showInputCount:function(input,limit,infoId){input=$(input);var rest=limit-input.value.length;if(rest<1){rest=0;input.value=input.value.substr(0,limit);if(Object.isFunction(arguments[3])){return arguments[3]();}}
if(Object.isUndefined(this._infoData)){this._infoData=$(infoId).innerHTML;}
$(infoId).update((new Template(this._infoData)).evaluate({amount:rest+' character'+(rest!=1?'s':'')}));$(infoId).setStyle({display:'block'});},checkTextarea:function(input,limit,infoId,resize){this.showInputCount(input,limit,infoId,arguments[4]||null);resize&&this.resizeTextarea(input);},showTip:function(tipIds,expiretime){if(expiretime<100){expiretime*=1000;}
if(!Object.isArray(tipIds)){tipIds=[tipIds];}
var options=Object.extend({duration:0.25},arguments[2]||{});setTimeout(function(){tipIds.each(function(it){new Effect.BlindUp(it,options);});},expiretime);},preloadImg:function(){$A(arguments).each(function(it){$(document.body).insert(new Element('img',{src:it,width:0,height:0}));});},activeMenus:function(menuClassName){$G(function(){var actClass='ACT',showSubMenu=null,subMenus=$('navMain').select('li[id^="navMain"]'),waitTime=10,actClasses=new Hash();subMenus.each(function(it){var link=it.down('span'),subMenu=it.down('ul');if(!subMenu||!subMenu.childElements().size())return;var subMenuHandle=it.down('div');if($(subMenuHandle.parentNode).hasClassName(actClass)){actClasses.set($(subMenuHandle.parentNode).identify(),1);}
var offset=link.positionedOffset(),dim=link.getDimensions();subMenu.addClassName(menuClassName).setStyle({display:'block',left:'-1000px',top:'-1000px'});setTimeout(function(){subMenu.setStyle({display:'none',left:(offset.left+1)+'px',top:(offset.top+dim.height)+'px'})},10);link.observe('mouseover',function(){showSubMenu=subMenu;subMenus.each(function(m){var ul=m.down('ul');if(ul&&(ul!=subMenu)){ul.setStyle({display:'none'});}});setTimeout(function(){if(showSubMenu==subMenu){subMenu.setStyle({display:'block'});}},waitTime);});link.observe('mouseout',function(){showSubMenu=null;setTimeout(function(){if(null==showSubMenu){subMenu.setStyle({display:'none'});}},waitTime);});subMenuHandle.observe('mouseover',function(){showSubMenu=subMenu;$(this.parentNode).addClassName(actClass);});subMenuHandle.observe('mouseout',function(){if(!actClasses.get($(this.parentNode).id)){$(this.parentNode).removeClassName(actClass);}
showSubMenu=null;setTimeout(function(){if(null==showSubMenu){subMenu.setStyle({display:'none'});}},waitTime);});});});},ajaxUpdater:function(id,url){var options={method:'get',evalScripts:true};Object.extend(options,arguments[2]||{});return new Ajax.Updater(id,url,options);},SelectItem:{itemsId:'HolderListResult',selectedClass:'selected',init:function(itemsId,selectedClass){var self=this;this.itemsId=itemsId;this.selectedClass=selectedClass;$(itemsId).setStyle({zIndex:1}).select('li').each(function(it){it.observe('click',function(event){var input=it.down('input');if(event.element()!=input){input.checked=!input.checked;}
self.setColor(input);});});},selectItem:function(status,name){var self=this;$$('input[name="'+name+'"]').each(function(it){it.checked=status;});$(this.itemsId).select('li').each(function(it){self.setColor(it.down('input'));});},setColor:function(input){var p=$(input);while(p.tagName.toUpperCase()!='LI')
p=$(p.parentNode);if(input.checked){p.addClassName(this.selectedClass);}else{p.removeClassName(this.selectedClass);}}},openLW:function(url,options){if(!myLightWindow)return;if(new Date().getTime()-this.clickLWTime<1000)return;myLightWindow.activateWindow(Object.extend({href:url,type:'page'},options||{}));this.clickLWTime=new Date().getTime();},closeLW:function(){setTimeout(function(){myLightWindow.deactivate()},(arguments[0]||2)*1000);},setCaretPosition:function(field){if(document.selection){var t=$(field),r=t.createTextRange();r.moveStart('character',t.value.length);r.collapse();r.select();}},loadScript:function(url,callback,node){if(!Object.isUndefined(this[url])){if(Object.isFunction(callback))callback();return;}
this[url]=1;var ts=+new Date,ret=url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+ts+"$2");url=ret+((ret==url)?(url.match(/\?/)?"&":"?")+"_="+ts:"");var script=new Element('script',{type:'text/javascript',src:url}),node=$(node||$$('head')[0]),done=false,rs=null;script.onload=script.onreadystatechange=function(){rs=this.readyState;if(!done&&(!rs||["loaded","complete"].include(rs))){done=true;if(Object.isFunction(callback))callback();script.onload=script.onreadystatechange=null;script.remove();}}
node.insert(script);},changeInputsFileStyle:function(id,opts){opts=Object.extend({node:null,image:null,inputWidth:null,inputSize:null,className:'gfile'},opts||{});var div=new Element('div'),input=new Element('input'),node=opts.image?new Element('img',{src:opts.image}):opts.node;div.addClassName(opts.className).insert(input).insert(node).hide();var file=$(id).show().insert({after:div}).observe('change',function(){div.down('input').setValue($F(this));}).setStyle({opacity:0});setTimeout(function(){div.show();input.setStyle({width:(opts.inputWidth?opts.inputWidth:(file.getWidth()-node.getWidth())-6)+'px'});if(opts.inputSize){input.writeAttribute('size',opts.inputSize);}},200);div.setStyle({zIndex:-1,position:'relative',top:-(file.getHeight())+'px',width:'330px'});},submitForm:function(f){var canSubmit=Object.isUndefined(this.s);setTimeout(function(){if(canSubmit){$(f).submit();}},10);this.s=1;},autoWindowSize:function(){var docEl=document.documentElement,viewHeight=!-[1,]?docEl.offsetHeight:window.innerHeight,viewWidth=!-[1,]?docEl.offsetWidth:window.innerWidth,height=docEl.scrollHeight,width=docEl.scrollWidth,extPx=!-[1,]?4:0;if(height>viewHeight||width>viewWidth){height-=viewHeight-extPx,width-=viewWidth-extPx;window.resizeBy(width,height);}}};Gays.Cookie={get:function(key){var match=document.cookie.match(new RegExp(key+'=([^;]+)(?:;|$)'));return match?match[1]:null;},set:function(key,value,expire){var date=new Date(),expires=';expires=';date.setTime(date.getTime()+expire);expires+=date.toGMTString();document.cookie=key+'='+value+expires+';path=/';},has:function(key){return!!this.get(key);},remove:function(key){this.set(key,'',-1);}};Gays.Google={loadAnalytics:function(id){$g(function(){Gays.Util.loadScript('http://www.google-analytics.com/ga.js',function(){window.pageTracker=_gat._getTracker(id);window.pageTracker._trackPageview();});});},loadApi:function(key,callback){if(!Object.isUndefined(this[key])){eval(callback+'()');return;}
this[key]=1;$g(function(){Gays.Util.loadScript('http://www.google.com/jsapi?key='+key+'&callback='+callback);});},loadMap:function(options){return google.load('maps','2',options);},loadSearch:function(options){return google.load('search','1',options);}};(function(){_CONST.CONTACT={STATE_UNDEFINED:-1,STATE_OFFLINE:0,STATE_ACTIVE:1,STATE_IDLE:2,STORE_DATA:0,STORE_STATE:1,STORE_FRIEND:2};var _data={contact:{},fetchData:{}},Contact=Gays.Contact={_fetch:function(options){if(!options&&!options.url)return;if(!isNaN(options.id))options.id=[options.id];if(Gays.Util.isArray(options.id)&&options.id.length){var key='&pl[]=',url=Gays.getBaseUrl()+options.url+'?r='+(new Date()).getTime()+
key+options.id.join(key);new Ajax.Request(url,{method:'get',asynchronous:!!options.async,onSuccess:function(response){var data=Gays.Util.call(options.dataFilter,response.responseText);if(data){Gays.Util.call(options.success,data);}else{Gays.Util.call(options.fail);}},onFailure:function(){Gays.Util.call(options.fail);}});}},fetchState:function(options){options=options||{};options.id=options.id||Gays.Util.keys(this.getAll()),options.url='/wio/online_status';options.storeType=_CONST.CONTACT.STORE_STATE;options.dataFilter=function(data){return Gays.Util.praseJSON(data)||{};};this._fetch(options);},fetchData:function(options){var self=this;options=options||{};options.storeType=_CONST.CONTACT.STORE_DATA;options.url='/chat/get_user_information';options.dataFilter=function(data){var id,data=Gays.Util.praseJSON(data);for(id in data)_data.fetchData[id]=1;data&&self._store(data,options.storeType);return data;};this._fetch(options);},updateState:function(id,state){var data={};data[id]={state:state};this._store(data,_CONST.CONTACT.STORE_STATE);},_store:function(data,storeType){var
CONTACT=_CONST.CONTACT,util=Gays.Util,contact=this.getAll();for(var id in data){var newData=data[id],oldData=contact[id];if(oldData){switch(storeType){case CONTACT.STORE_STATE:if(util.exists(newData.state)){oldData.state=newData.state;}
continue;case CONTACT.STORE_FRIEND:if(util.exists(newData.friend)){oldData.friend=newData.friend;}
continue;}}else if(newData.name||newData.avatar){contact[id]={name:newData.name,avatar:newData.avatar,status:util.param(newData.status,''),link:this.getProfileUrl(id),friend:util.param(newData.friend,false,true),state:util.param(newData.state,CONTACT.STATE_UNDEFINED,true)};}}},removeData:function(id){delete this.getAll()[id];},exists:function(id){return id&&id in this.getAll();},addFriend:function(data){if(data){for(var id in data)
data[id].friend=true;this._store(data);}},get:function(id){return this.getAll()[id]||null;},getByName:function(input,options){options=options||{};var id,data=this.getAll(),result=[],partial=[];for(id in data){if(!data[id].friend)continue;var contact=data[id],name=contact.name,pos=options.ignoreCase?name.toLowerCase().indexOf(input.toLowerCase()):name.indexOf(input);while(pos!=-1){if(pos==0&&name.length!=input.length){result.push({id:id,data:contact,left:'',match:name.substr(0,input.length),right:name.substr(input.length)});break;}else if(input.length>=options.partialChars&&options.partialSearch&&pos!=-1){if(options.fullSearch||/\s/.test(name.substr(pos-1,1))){partial.push({id:id,data:contact,left:name.substr(0,pos),match:name.substr(pos,input.length),right:name.substr(pos+input.length)});break;}}
pos=options.ignoreCase?name.toLowerCase().indexOf(input.toLowerCase(),pos+1):name.indexOf(input,pos+1);}}
if(partial.length){result=result.concat(partial.slice(0,options.choices-result.length));}
return result;},getAll:function(){return _data.contact;},getFriends:function(){var id,results={},data=this.getAll();for(id in data){if(data[id].friend)results[id]=data[id];}
return results;},getState:function(id){var data=this.get(id);return data?data.state:_CONST.CONTACT.STATE_UNDEFINED;},getName:function(id){var data=this.get(id);if(data)return data.name;return'';},getProfileUrl:function(id){return Gays.getBaseUrl()+'/profile/'+id;},isFriend:function(id){var contact=this.get(id);return contact&&contact.friend;},isOnline:function(id){var contact=this.get(id);return contact&&contact.state>0;},remove:function(id,url){this.removeData(id);new Ajax.Request(url,{method:'get'});},finder:function(input,update,options){return new this.AC(input,update,null,options);},AC:Class.create(Autocompleter.Local,{setOptions:function(options){this.options=Object.extend({choices:10,partialChars:0,partialSearch:true,ignoreCase:true,fullSearch:false,showTyping:false,showHiddenTyping:false,stopTabKey:false,onShow:function(element,update){Gays.AC.fixPosition(element,update);new Effect.Appear(update,{duration:0.15});},selector:function(instance){var result=[],entry=instance.getToken(),matchs=Contact.getByName(entry,instance.options),tItem='<li uid="#uid#"><img src="#avatar#" alt="avatar" />#left#<strong>#match#</strong>#right#</li>';for(var i=0,match;i<matchs.length;i++){match=matchs[i];result.push(Gays.Util.fillTemplate(tItem,{uid:match.id,avatar:match.data.avatar,left:match.left,match:match.match,right:match.right}));}
if(options.showTyping&&result.size()){result.unshift('<li>'+entry+'</li>');}
if(options.showHiddenTyping&&result.length){result.unshift('<li style="width:0;height:0;margin:0;padding:0"><div style="display:none">'+entry+'</div></li>');}
return'<ul>'+result.join('')+'</ul>';}},options||{});},onKeyPress:function($super,event){if(this.options.stopTabKey&&event.keyCode==9){this.markNext();this.render();event.stop();}else{$super(event);}}})};})();(function(Gays){var _data={init:false,state:_CONST.CONTACT.STATE_UNDEFINED,timer:null,handler:{},period:10,scrollX:0,scrollY:0,focus:true},IdleChecker=Gays.IdleChecker={EVENT:{IDLE:'idle',ACTIVE:'active'},init:function(period){if(_data.init)return;_data.init=true;var self=this;self.setPeriod(period);Event.observe(document,'click',self.active);Event.observe(document,'keydown',self.active);Event.observe(document,'mousemove',function(){if(_data.focus)self.active();});Event.observe(window,'resize',self.active);Event.observe(window,'focus',self.active);Event.observe(window,'blur',self.onBlur);},regHandler:function(name,handler){if(name&&typeof(handler)=='function'){if(!_data.handler[name])_data.handler[name]=[];_data.handler[name].push(handler);}},_callHandler:function(name){try{var handlers=_data.handler[name||''],args=[],i=0;if(handlers){for(i=1;i<arguments.length;i++){args.push(arguments[i]);}
for(i=0;i<handlers.length;i++){handlers[i].apply(null,args);}}}catch(e){}},sendPresence:function(){var system=Gays.Chat.getSystem();system&&system.sendPresence(_CONST.CONTACT,_data.state);},_checkIdle:function(){if(_data.focus){if(Gays.Util.exists(document.body.scrollTop)&&(_data.scrollX!=document.body.scrollLeft||_data.scrollY!=document.body.scrollTop)){_data.scrollX=document.body.scrollLeft;_data.scrollY=document.body.scrollTop;_data.focus=true;return false;}else if(Gays.Util.exists(window.pageYOffset)&&(_data.scrollX!=window.pageXOffset||_data.scrollY!=window.pageYOffset)){_data.scrollX=window.pageXOffset;_data.scrollY=window.pageYOffset;_data.focus=true;return false;}}
return true;},setPeriod:function(second){if(second&&!isNaN(second))_data.period=second;},check:function(){if(_data.timer){clearTimeout(_data.timer);_data.timer=null;this.check();}else{var self=this;_data.timer=setTimeout(function(){self._checkIdle()?self.idle():self.active();},_data.period*1000);}},onBlur:function(){_data.focus=false;},idle:function(){var CONTACT=_CONST.CONTACT,self=Gays.IdleChecker;if(!self.isIdle()){_data.state=CONTACT.STATE_IDLE;self.sendPresence();self._callHandler(self.EVENT.IDLE);}
self.check();},active:function(){var CONTACT=_CONST.CONTACT,self=Gays.IdleChecker,focus=_data.focus;_data.focus=true;if(!self.isActive()){_data.state=CONTACT.STATE_ACTIVE;self.sendPresence();self._callHandler(self.EVENT.ACTIVE);}else if(!focus){self._callHandler(self.EVENT.ACTIVE);}
self.check();},isFocus:function(){return _data.focus;},isBlur:function(){return!_data.focus;},isIdle:function(){return _data.state==_CONST.CONTACT.STATE_IDLE;},isActive:function(){return _data.state==_CONST.CONTACT.STATE_ACTIVE;}};})(Gays);Gays.Sound=(function(){var player,attr={id:'soundPlayer',width:'1px',height:'1px'},param={allowscriptaccess:'always',quality:'high',wmode:'transparent'},inited=false;function playerHTML(src){var html='',attrs='',params='',key;if(!src)return'';for(key in attr){attrs+=key+'="'+attr[key]+'" ';}
if('onhelp'in window){params='<param name="movie" value="'+src+'" />';for(key in param){params+='<param name="'+key+'" value="'+param[key]+'"\/>';}
html='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ';html+=attrs+'>'+params;html+='<\/object>'}else{params='src="'+src+'" ';for(key in param){params+=key+'="'+param[key]+'" ';}
html='<embed type="application/x-shockwave-flash" ';html+=attrs+params;html+='\/>'}
return html;}
return{init:function(src){if(!inited){inited=true;document.write('<div style="height:0;width:0;">'+playerHTML(src)+'</div>');player=document.getElementById(attr.id);}},play:function(src,noDetect){if(player&&player.playSound&&/\.(?:mp3)$/i.test(src)){player.playSound(src,!!noDetect);}}};})();(function(Gays){var _data={init:false,contacts:{},sections:{},windows:{},messages:{},msgUrl:'',sound:'',cookie:'',isError:false,uiReady:false,connReady:false,reconnTimer:null,reconnDelay:0,reconnTimes:0,docTitle:'',docTitleAlt:'New Chat Message',docTitleTimer:null,noc:0,nocLock:true},_CHAT_CONST={CONFIG:{MESSAGES_URL:'',SYSTEM_URL:'',TIME_TITLE_FLASH:1,TIME_STOP_TYPING:5,TIME_INC_RECONN:5,TIME_LOCK_NOC:2,TIMES_IM_RECONN:3},RELINK:{NONE:0,READY:1,START:2,LOCK:4},ERROR:{INIT:0,INIT_COOKIE:1,LOAD_UI:2,LOAD_SYSTEM:4,RESTORE:8,DISCONNECT:16},COOKIE:{NAME:'chat',EXPIRE:86400000,SID:'sid',NOC:'noc',LIST:'list',CHAT:'chat',REGEX_SID:/sid:([a-z\d]+)?\|/i,REGEX_NOC:/noc:(\d+)?\|/i,REGEX_LIST:/list:{((?:#?[a-z]+:\d){4})?}\|/i,REGEX_CHAT:/chat:{((?:#?\d+:\[-?\d+(?:~-?\d+){5}\])*)}\|/i,REGEX_LIST_ITEM:/([a-z]+):(\d)/gi,REGEX_CHAT_ITEM:/(\d+):\[(-?\d+(?:~-?\d+){5})\]/gi},NOTIFY:{NONE:'',LOAD:'load',SEND:'send',CONN_ERROR:'connError',NO_CONTACT:'noContact',UNREAD_MESSAGE:'message',TYPING:'typing',OFFLINE:'offline'},LIST:{TYPE_WRAP:'wrap',TYPE_OPEN:'open',TYPE_ACTIVE:'active',TYPE_IDLE:'idle',TYPE_OFFLINE:'offline',STATE_COLLAPSEED:0,STATE_EXPANDED:1},WINDOW:{LEN_NAME:30,LEN_STATUS:45,LEN_INPUT_ROWS:5,LEN_INPUT_ONE_ROW:40,INPUT_LINE_HEIGHT:17,GRID_X:211,GRID_Y:11,GRID_H_AREA:300,GRID_H_SPACE:40,GRID_V_SPACE:40,STATE_CLOSE:0,STATE_OPEN:1,STATE_MINI:2},MESSAGE:{STATE_SENT:1,STATE_READ:1,STATE_NOT_SENT:0,STATE_UNREAD:0,GAP_TIME:60,MSG_TIME_PATTERN:/^(#T#(\d{13})#)?.+/},UI:{CHAT_SWITCHER:'#chatSwitcher',CHAT_NOC:'#chatNOC',CHAT_TIP:'#chatTip',WRAP:'#chat',SYSTEM:'#chat #chatSystem',PANEL:'#chat #chatPanel',NOTIFY:'#chat #chatNotify',RECONNECT:'#chat #chatReconnect',RECONNECT_DELAY:'#chat #chatConnDelay',RECONNECT_NOW:'#chat #chatConn',SECTION_WRAP:'#chat #chatSections',WINDOW_WRAP:'#chat #chatWindows',UNREAD:'.unread',AVATAR:'.avatar',CONTACT:'.contact',WINDOW:'.window',MESSAGE:'.message',SECTION_OPENED:'.opened',SECTION_ACTIVE:'.active',SECTION_IDLE:'.idle',SECTION_OFFLINE:'.offline',SECTION_HEADER:'.header',SECTION_LIST:'.list',WINDOW_MOVE_HANDLER:'.header',WINDOW_MINI:'.controls .mini',WINDOW_CLOSE:'.controls .close',WINDOW_USER_STATE:'.header .state',WINDOW_MESSAGES:'.messages',WINDOW_NOTIFY:'.notify',WINDOW_INPUT:'textarea',WINDOW_STATUS_BAR:'.statusBar',MESSAGE_META:'.meta',MESSAGE_CONTENT:'.content',MESSAGE_LOADING:'.msgLoading',TEMPLATE_WRAP:'#chat #chatTemplate',TEMPLATE_CONTACT:'#chat #chatTemplateCcontact',TEMPLATE_WINDOW:'#chat #chatTemplateWindow',TEMPLATE_MESSAGE:'#chat #chatTemplateMessage',TEMPLATE_DOC_TITLE_ALT:'#chatBrowerTitle'}},ChatContact=function(id){this.id=id;this.section=null;this.window=null;this.presence={};this.sMsgs=0;this.unread=0;this.onRestore=false;this.lastState=_CONST.CONTACT.STATE_UNDEFINED;this.relink=_CHAT_CONST.RELINK.NONE;this._createUI();},ChatWindow=function(id){var contact=Chat.getContact(id);contact.window=this;this.id=id;this.contact=contact;this.state=_CHAT_CONST.WINDOW.STATE_CLOSE;this.x=this.y=0;this.gridIndex=-1;this.msgStack=[];this.lastMsg=null;this.lastGapMsg=null;this.onRestore=false;this.chatbale=false;this._createUI();},ChatMessage=function(data){this.from=data.from;this.to=data.to;this.content=data.content;this.date=new Date(data.date+Gays.getTimeOffset());this.loss=data.loss||false;this._createUI();},ChatSection=function(ui,type){var LIST=_CHAT_CONST.LIST;this.unread=0;this.type=type||LIST.TYPE_OFFLINE;this.state=LIST.STATE_EXPANDED;this._loadUI(ui);},ChatWindowGrid={minX:_CHAT_CONST.WINDOW.GRID_X,minY:_CHAT_CONST.WINDOW.GRID_Y,hArea:_CHAT_CONST.WINDOW.GRID_H_AREA,hSpace:_CHAT_CONST.WINDOW.GRID_H_SPACE,vSpace:_CHAT_CONST.WINDOW.GRID_V_SPACE,areaMax:0,windows:[],init:function(){var vMax=parseInt(this.vArea/this.vSpace),hMax=parseInt(this.hArea/this.hSpace);this.areaMax=vMax<hMax?vMax:hMax;this.vArea=this.areaMax*this.vSpace;this.maxY=this.minY+this.vArea;},genPos:function(){var i=0;while(this.windows[i]&&this.windows.length>i++);var
area=parseInt(i/(this.areaMax||i)),index=i%(this.areaMax||i),x=index*this.hSpace,y=index*this.vSpace;return pos={x:x+this.minX+area*this.hArea,y:y+this.minY};},register:function(cWindow){this.unregister(cWindow);if(cWindow instanceof ChatWindow){var index=this._genIndex(cWindow.x,cWindow.y);if(index<0){cWindow.gridIndex=-1;}else{this.windows[index]=cWindow;cWindow.gridIndex=index;}}},unregister:function(cWindow){if(cWindow instanceof ChatWindow){var index=cWindow.gridIndex;if(index>=0){this.windows[index]=null;cWindow.gridIndex=-1;}}},_isOnGrid:function(x,y){return x>=this.minX&&y>=this.minY&&y<this.maxY;},_genIndex:function(x,y){if(this._isOnGrid(x,y)){x-=this.minX;y-=this.minY;var
area=parseInt(x/this.hArea),areaX=x%this.hArea,index=areaX/this.hSpace;if(areaX%this.hSpace==0&&y%this.vSpace==0&&y/this.vSpace==index){return area*this.areaMax+index;}}
return-1;}},ChatSystem={system:null,iframe:null,url:'',loadLimit:3,_handler:{},init:function(iframe,url){try{if(iframe&&url){this.iframe=iframe;this.setUrl(url);Event.observe(iframe,'load',this._hdlLoad);this.load();}else{throw new Error('ChatSystem.init() error');}}catch(error){Chat.setError(_CHAT_CONST.ERROR.LOAD_SYSTEM,error);}},setUrl:function(url){this.url=url;},_hdlLoad:function(){var self=ChatSystem,iframe=self.iframe,system;if(iframe.src==self.url){try{system=(iframe.contentWindow||iframe).Jabber;}catch(error){Chat.setError(_CHAT_CONST.ERROR.LOAD_SYSTEM,error);}}else{self.load();}
system&&self._bindSystem(system);},load:function(){if(Chat.hasError())return;if(this.url&&this.loadLimit){this.loadLimit--;this.iframe.src=this.url;}else{Chat.setError(_CHAT_CONST.ERROR.LOAD_SYSTEM,new Error('Can\'t load chat communication system!'));}},getSystem:function(){return this.system;},_bindSystem:function(system){if(system&&system!=this.system){this.system=system;this._regHandler();}},_regHandler:function(){var system=this.system;if(system){system.regHandler(system.EVENT.CONNECT,this._hdlConnect);system.regHandler(system.EVENT.DISCONNECT,this._hdlDisconnect);system.regHandler(system.EVENT.MESSAGE,this._hdlMessage);system.regHandler(system.EVENT.PRESENCE,this._hdlPresence);system.regHandler(system.EVENT.TYPING,this._hdlTyping);system.regHandler(system.EVENT.STOPTYPING,this._hdlStopTyping);for(var event in this._handler){var i=0,hdls=this._handler[event];for(;i<hdls.length;i++){system.regHandler(event,hdls[i]);}}}},_hdlConnect:function(){Chat._connReady(true);_data.nocDelay=setTimeout(function(){delete _data.nocDelay;Chat._lockNOC(false);Chat._showNOC();},_CHAT_CONST.CONFIG.TIME_LOCK_NOC*1000);Chat._offlineCheck();},_hdlDisconnect:function(){Chat._connReady(false);Chat._offlineCheck(true);},_hdlMessage:function(id,content){ChatHelper.start({id:id,async:true,success:function(id){var contact=Chat._newContact(id);contact.setState(_CONST.CONTACT.STATE_ACTIVE);if(!contact||!Chat._newWindow(id))return;var msg={from:id,to:Gays.getUserId(),content:content};msg.content=content.replace(_CHAT_CONST.MESSAGE.MSG_TIME_PATTERN,function(m,p,t){if(t)msg.date=parseInt(t);return m.slice(p.length);});Chat._newMessage(msg,true);contact.updateSection(true);contact.incUnread();Chat.notify(_CHAT_CONST.NOTIFY.UNREAD_MESSAGE);}},true);},_hdlPresence:function(id,resource,presence){ChatHelper.start({id:id,async:true,success:function(id){Chat._newContact(id).updatePresence(resource,presence);}},true);},_hdlTyping:function(id,stop){var NOTIFY=_CHAT_CONST.NOTIFY,cWindow=Chat.getWindow(id);cWindow&&cWindow.statusBarNotify(stop?NOTIFY.NONE:NOTIFY.TYPING);},_hdlStopTyping:function(id){ChatSystem._hdlTyping(id,true);},sendMessage:function(id,content){if(this.system&&id&&content){try{return this.system.sendMessage(id,content);}catch(e){return false;}}
return false;},sendState:function(id,state){if(this.system&&id&&state){try{return this.system.sendState(id,state);}catch(e){return false;}}
return false;}},ChatHelper={startUrl:'/chat/make_link/',stopUrl:'/chat/rm_link/',_request:function(options){var self=this,caller=arguments.callee.caller;if(caller==this.start||caller==this.stop){var url=Gays.getBaseUrl()+options.url+options.id,ajaxOpt={method:'get',asynchronous:true};if(options.link){ajaxOpt.onSuccess=function(response){var result=/^\s*(\d)\s*$/m.exec(response.responseText);result=result?parseInt(result[1]):2;if(result==1)Chat.getContact(options.id)._offlineCheck();Gays.Util.call(options.link,result);};}
new Ajax.Request(url,ajaxOpt);}},start:function(options,noLink,data){data=data||null;if(!options&&!options.id)return;if(Gays.Contact.exists(options.id)){Gays.Util.call(options.success,options.id,data);if(!Gays.Contact.isFriend(options.id)&&!noLink){options.url=this.startUrl;this._request(options,data);}}else{var self=this;Gays.Contact.fetchData({id:options.id,async:true,success:function(data){if(options.id in data)self.start(options,noLink,data);else Gays.Util.call(options.fail);},fail:options.fail});}},stop:function(options){if(options&&options.id){if(arguments[1]){Gays.Util.call(options.success,options.id);}else{options.url=this.stopUrl;this._request(options);}}}},Chat=Gays.Chat={init:function(options){if(_data.init)return;_data.init=true;try{options=options||{};_data.cookie=options.cookie||_CHAT_CONST.COOKIE.NAME;_data.msgUrl=options.msgUrl||_CHAT_CONST.CONFIG.MESSAGES_URL;_data.sound=options.sound;_data.reconnTimes=_CHAT_CONST.CONFIG.TIMES_IM_RECONN;ChatWindowGrid.init();}catch(error){this.setError(_CHAT_CONST.ERROR.INIT,error);}
var self=this;$G(function(){self._initCookie();});this._loadUI();this._loadSystem(options.sysUrl||_CHAT_CONST.CONFIG.SYSTEM_URL);},_loadSystem:function(url){var iframe=$$(_CHAT_CONST.UI.SYSTEM)[0];ChatSystem.init(iframe,url);},getSystem:function(){return ChatSystem.getSystem();},_loadUI:function(){try{var
UI=_CHAT_CONST.UI,self=this,ui=_data.ui={switcher:$$(UI.CHAT_SWITCHER)[0],noc:$$(UI.CHAT_NOC)[0],tip:$$(UI.CHAT_TIP)[0],wrap:$$(UI.WRAP)[0],panel:$$(UI.PANEL)[0],notify:$$(UI.NOTIFY)[0],reconn:$$(UI.RECONNECT)[0],delay:$$(UI.RECONNECT_DELAY)[0],sections:$$(UI.SECTION_WRAP)[0],windows:$$(UI.WINDOW_WRAP)[0]};this._loadSections(ui.sections);this._loadTemplate();this._regHandler();}catch(error){this.setError(_CHAT_CONST.ERROR.LOAD_UI,error);}
self._restore();},_getUI:function(name){var
UI=_CHAT_CONST.UI,ui=_data.ui;name=name||UI.WRAP;if(!ui)return null;switch(name){case UI.WRAP:return ui.wrap;case UI.SECTION_WRAP:return ui.sections;case UI.WINDOW_WRAP:return ui.windows;case UI.NOTIFY:return ui.notify;case UI.CHAT_SWITCHER:return ui.switcher;case UI.CHAT_NOC:return ui.noc;case UI.CHAT_TIP:return ui.tip;case UI.PANEL:return ui.panel;case UI.RECONNECT:return ui.reconn;case UI.RECONNECT_DELAY:return ui.delay;}},_addUI:function(object){if(object instanceof ChatContact){object.updateSection();}else if(object instanceof ChatWindow){var wrap=this._getUI(_CHAT_CONST.UI.WINDOW_WRAP);if(wrap){var ui=object.getUI();if(ui&&ui.parentNode!=wrap)wrap.appendChild(ui);}}else if(object instanceof ChatMessage){var userId=Gays.getUserId(),contactId=object.getContactId(),contact,cWindow;if(contactId!=userId){cWindow=this.getWindow(contactId);if(!cWindow){contact=this.getContact(contactId)||this._newContact(contactId);cWindow=this._newWindow(contactId);}
cWindow.addMessage(object);}}},_delUI:function(object){if(object instanceof ChatContact||object instanceof ChatWindow){var ui=object.getUI();ui&&ui.parentNode&&ui.parentNode.removeChild(ui);}},_regHandler:function(){var self=this,switcher=this._getUI(_CHAT_CONST.UI.CHAT_SWITCHER),reconnect=$$(_CHAT_CONST.UI.RECONNECT_NOW)[0];if(switcher){switcher.onclick=rFalse;Event.observe(switcher,'click',function(){self.tipNotify();self.togglePanel();});}
if(reconnect){reconnect.onclick=rFalse;Event.observe(reconnect,'click',function(){_data.reconnDelay=0;_data.reconnTimes=_CHAT_CONST.CONFIG.TIMES_IM_RECONN;self.reconnect();});}
Gays.IdleChecker.regHandler(Gays.IdleChecker.EVENT.ACTIVE,function(){self.titleNotify(true);});},_loadTemplate:function(){try{var UI=_CHAT_CONST.UI,wrap=$$(UI.TEMPLATE_WRAP)[0],contact=$$(UI.TEMPLATE_CONTACT)[0],cWindow=$$(UI.TEMPLATE_WINDOW)[0],message=$$(UI.TEMPLATE_MESSAGE)[0],altTitle=$$(UI.TEMPLATE_DOC_TITLE_ALT)[0];_data.template={contact:contact.innerHTML.replace(/asrc="/gi,'src="'),window:cWindow.innerHTML.replace(/asrc="/gi,'src="'),message:message.innerHTML};_data.docTitle=document.title;if(altTitle)_data.docTitleAlt=altTitle.value+document.title;wrap.parentNode.removeChild(wrap);}catch(error){_data.template.contact=_data.template.window=_data.template.message='';throw error;}},_getTContact:function(){return _data.template.contact;},_getTWindow:function(){return _data.template.window;},_getTMessage:function(){return _data.template.message;},cookieName:function(){return _data.cookie;},_initCookie:function(){try{var
COOKIE=_CHAT_CONST.COOKIE,cookie=this._getCookie(),match=null,value='',result=[];match=cookie.match(COOKIE.REGEX_SID)||[];result.push(COOKIE.SID+':'+(match[1]||''));match=cookie.match(COOKIE.REGEX_NOC)||[];result.push(COOKIE.NOC+':'+(match[1]||0));match=cookie.match(COOKIE.REGEX_LIST)||[];result.push(COOKIE.LIST+':{'+(match[1]||'wrap:0#open:1#active:1#idle:1')+'}');match=cookie.match(COOKIE.REGEX_CHAT)||[];result.push(COOKIE.CHAT+':{'+(match[1]||'')+'}');this._setCookie(result.join('|')+'|');}catch(error){Chat.setError(_CHAT_CONST.ERROR.INIT_COOKIE,error);}},_getCookie:function(type){var COOKIE=_CHAT_CONST.COOKIE,name=this.cookieName(),result=name?Gays.Cookie.get(name):'',match;if(result&&type){switch(type){case COOKIE.SID:match=COOKIE.REGEX_SID;break;case COOKIE.NOC:match=COOKIE.REGEX_NOC;break;case COOKIE.LIST:match=COOKIE.REGEX_LIST;break;case COOKIE.CHAT:match=COOKIE.REGEX_CHAT;break;}
match=result.match(match);result=match?match[1]:'';}
return result||'';},_setCookie:function(cookie){var name=this.cookieName();name&&Gays.Cookie.set(name,cookie,_CHAT_CONST.COOKIE.EXPIRE);},_delCookie:function(){if(navigator.cookieEnabled)
var name=this.getCookieName();name&&Gays.Cookie.remove(name);},_store:function(type,key,value){var COOKIE=_CHAT_CONST.COOKIE,cookie=this._getCookie();if(cookie){switch(type){case COOKIE.SID:cookie=cookie.replace(COOKIE.REGEX_SID,function(m,$1){return COOKIE.SID+':'+value+'|';});break;case COOKIE.NOC:cookie=cookie.replace(COOKIE.REGEX_NOC,function(m,$1){return COOKIE.NOC+':'+value+'|';});break;case COOKIE.LIST:cookie=cookie.replace(COOKIE.REGEX_LIST,function(m,$1){var result=[],noMatch=true;$1.replace(COOKIE.REGEX_LIST_ITEM,function(m,$1){if($1==key){noMatch=false;m=$1+':'+(value||0);}
result.push(m);});noMatch&&result.push(key+':'+value);return type+':{'+result.join('#')+'}|';});break;case COOKIE.CHAT:cookie=cookie.replace(COOKIE.REGEX_CHAT,function(m,$1){var result=[],noMatch=true;$1.replace(COOKIE.REGEX_CHAT_ITEM,function(m,$1){if($1==key){noMatch=false;m=value?$1+':['+value.join('~')+']':'';}
m&&result.push(m);});noMatch&&value&&result.push(key+':['+value.join('~')+']');return type+':{'+result.join('#')+'}|';});break;}
this._setCookie(cookie);}},_storeNOC:function(num){num=parseInt(num)||0;this._store(_CHAT_CONST.COOKIE.NOC,null,num);},_storeSection:function(section){if(section instanceof ChatSection){this._store(_CHAT_CONST.COOKIE.LIST,section.type,section.state);}},_storePanel:function(){this._store(_CHAT_CONST.COOKIE.LIST,_CHAT_CONST.LIST.TYPE_WRAP,this.isOpen()?1:0);},_storeChat:function(object,remove){if(object instanceof ChatWindow&&object.contact){this._store(_CHAT_CONST.COOKIE.CHAT,object.id,remove?null:[object.x,object.y,object.state,object.contact.sMsgs,object.contact.unread,object.contact.getState()]);}},_restoreSection:function(){var self=this,value=this._getCookie(_CHAT_CONST.COOKIE.LIST);value.replace(_CHAT_CONST.COOKIE.REGEX_LIST_ITEM,function(m,$1,$2){var list=self.getSection($1),state=parseInt($2);if(list){list.toggle(state);}else if($1==_CHAT_CONST.LIST.TYPE_WRAP){self.togglePanel(state);}});},_getLastChats:function(){var COOKIE=_CHAT_CONST.COOKIE,value=this._getCookie(COOKIE.CHAT),chat={};value.replace(COOKIE.REGEX_CHAT_ITEM,function(m,$1,$2){chat[$1]=$2.split('~');});return chat;},_restore:function(){if(this.hasError())return;try{var self=this,friends=Gays.Contact.getFriends(),lastChats=this._getLastChats();function newContact(id){var contact=self._newContact(id);if(id in lastChats){var props=lastChats[id];contact.restore({x:parseInt(props[0]),y:parseInt(props[1]),window:parseInt(props[2]),sMsgs:parseInt(props[3]),unread:parseInt(props[4]),state:parseInt(props[5])});delete lastChats[id];}}
for(var id in friends){newContact(id);}
var nfIds=Gays.Util.keys(lastChats);nfIds.length&&Gays.Contact.fetchData({id:nfIds,async:true,success:function(data){for(var id in data){newContact(id);}},fail:function(){self.setError(_CHAT_CONST.ERROR.RESTORE);}});this._restoreSection();this._uiReady(true);}catch(e){this._uiReady(false);}},_storeData:function(object){if(object instanceof ChatContact){this._getContacts()[object.id]=object;}else if(object instanceof ChatWindow){this._getWindows()[object.id]=object;}else if(object instanceof ChatMessage){this._getMessages(object.getContactId()).push(object);}else if(object instanceof ChatSection){this._getSections()[object.type]=object;}},_removeData:function(object){if(object instanceof ChatContact){this._removeData(object.window);if(object.section){this._delUI(object);object.section.remove(object);}
delete this._getContacts()[object.id];}else if(object instanceof ChatWindow){this._delUI(object);this._storeChat(object,true);if(object.contact)delete object.contact.window;delete this._getWindows()[object.id];}},_getSections:function(){return _data.sections||(_data.sections={});},getSection:function(type){if(type)return this._getSections()[type]||null;return null;},_loadSections:function(wrap){if(wrap){var
UI=_CHAT_CONST.UI,LIST=_CHAT_CONST.LIST,type,blocks={};blocks[LIST.TYPE_OPEN]=wrap.select(UI.SECTION_OPENED)[0];blocks[LIST.TYPE_ACTIVE]=wrap.select(UI.SECTION_ACTIVE)[0];blocks[LIST.TYPE_IDLE]=wrap.select(UI.SECTION_IDLE)[0];blocks[LIST.TYPE_OFFLINE]=wrap.select(UI.SECTION_OFFLINE)[0];for(type in blocks){this._storeData(new ChatSection(blocks[type],type));}}},_getContacts:function(){return _data.contacts||(_data.contacts={});},getContact:function(id){return this._getContacts()[id]||null;},_newContact:function(id){var contact=this.getContact(id);if(!contact&&Gays.Contact.get(id)){contact=new ChatContact(id);this._storeData(contact);this._addUI(contact);}
return contact;},_getWindows:function(){return _data.windows||(_data.windows={});},getWindow:function(id){return this._getWindows()[id]||null;},_newWindow:function(id){var cWindow=this.getWindow(id);if(!cWindow&&this.getContact(id)){cWindow=new ChatWindow(id);this._storeData(cWindow);this._addUI(cWindow);}
return cWindow;},getWindowState:function(id){var cWindow=this.getWindow(id);return cWindow?cWindow.getState():_CHAT_CONST.WINDOW.STATE_CLOSE;},_getMessages:function(id){var list=_data.messages;return list[id]||(list[id]=[]);},_newMessage:function(data){var message=null,userId=Gays.getUserId();if(userId&&data&&data.content){var cId=data.to==userId?data.from:data.to;if(cId&&cId!=userId){message=new ChatMessage(data);this._storeData(message);this._addUI(message);}}
return message;},notify:function(type){var
UI=_CHAT_CONST.UI,NOTIFY=_CHAT_CONST.NOTIFY,caller=arguments.callee.caller,uiNotify=this._getUI(UI.NOTIFY),uiSections=this._getUI(UI.SECTION_WRAP);if(type==NOTIFY.CONN_ERROR||caller==this.setError||this.hasError()){type=NOTIFY.CONN_ERROR;this.titleNotify(true);this.tipNotify(type);this.windowsNotify(type);}else if(type==NOTIFY.LOAD&&caller==this._checkReady){type=NOTIFY.LOAD;this.tipNotify(type);this.windowsNotify(type);}else if(type==NOTIFY.NO_CONTACT||this.noContact()){type=NOTIFY.NO_CONTACT;this.tipNotify(type);}else if(type==NOTIFY.UNREAD_MESSAGE){type='';this.soundNotify(type);this.tipNotify(type);this.titleNotify();}else{type='';this.tipNotify(type);this.windowsNotify(type);}
uiNotify&&(uiNotify.className=type);uiSections&&(uiSections.style.display=type?'none':'block');},tipNotify:function(type){var
NOTIFY=_CHAT_CONST.NOTIFY,ui=this._getUI(_CHAT_CONST.UI.CHAT_TIP);if(type==NOTIFY.CONN_ERROR||this.hasError()){type=NOTIFY.CONN_ERROR;}else if(type==NOTIFY.UNREAD_MESSAGE||this.hasUnread()){type=NOTIFY.UNREAD_MESSAGE;}
if(ui)ui.className=type||NOTIFY.NONE;},titleNotify:function(stop){if(stop===true){clearInterval(_data.docTitleTimer);_data.docTitleTimer=null;document.title=_data.docTitle;}else{var self=this;if(!_data.docTitleTimer&&Gays.IdleChecker.isBlur()){_data.docTitleTimer=setInterval(function(){self._titleFlasher();},_CHAT_CONST.CONFIG.TIME_TITLE_FLASH*1000);}}},soundNotify:function(type){if(Gays.IdleChecker.isIdle()||Gays.IdleChecker.isBlur()){var sound=this.getSound();sound&&Gays.Sound.play(sound,false);}},windowsNotify:function(type){var
NOTIFY=_CHAT_CONST.NOTIFY,windows=this._getWindows();if(type==NOTIFY.CONN_ERROR||this.hasError()){type=NOTIFY.CONN_ERROR;}
for(var id in windows){windows[id].notify(type);}},_titleFlasher:function(){if(document.title==_data.docTitle){document.title=_data.docTitleAlt;}else{document.title=_data.docTitle;}},hasUnread:function(){var id,contacts=this._getContacts();for(id in contacts){if(contacts[id].unread)return true;}
return false;},checkUnread:function(){var
NOTIFY=_CHAT_CONST.NOTIFY,hasUnread=this.hasUnread();this.tipNotify(hasUnread?NOTIFY.UNREAD_MESSAGE:NOTIFY.NONE);},togglePanel:function(state){state=Gays.Util.param(state,!this.isOpen());state?this.showPanel():this.hidePanel();},showPanel:function(){var ui=this._getUI(_CHAT_CONST.UI.PANEL);ui.style.display='block';this._storePanel();},hidePanel:function(){var ui=this._getUI(_CHAT_CONST.UI.PANEL);ui.style.display='none';this._storePanel();},isOpen:function(){var ui=this._getUI(_CHAT_CONST.UI.PANEL);return ui&&(ui.offsetWidth>0||ui.offsetHeight>0);},noContact:function(){var sections=this._getSections();for(var type in sections){if(type!=_CHAT_CONST.LIST.TYPE_OFFLINE&&sections[type].hasContact())return false;}
return true;},getPosition:function(){var offset,ui=this._getUI();if(ui){offset=ui.positionedOffset();return{x:offset[0],y:offset[1]};}
return null;},getSound:function(){return _data.sound;},_getMessageUrl:function(id,num){return _data.msgUrl+'?pl='+id;},_lockNOC:function(state){if(typeof(state)=='boolean'){_data.nocLock=state;}
return _data.nocLock;},_showNOC:function(){if(this._lockNOC())return;var num=_data.noc,ui=this._getUI(_CHAT_CONST.UI.CHAT_NOC);if(ui)Gays.UI.setText(ui,num);this._storeNOC(num);},_updateNOC:function(oldState,newState){var num=_data.noc;if(oldState<1&&newState>0){num++}else if(oldState>0&&newState<1){num--}
if(num!=_data.noc){_data.noc=num;this._showNOC();}},_uiReady:function(state){if(Gays.Util.isBoolean(state)){if(_data.uiReady=state){this._checkReady();}else{this.setError(_CHAT_CONST.ERROR.LOAD_UI,new Error('Fail to restore chat data!'));}}
return _data.uiReady;},_connReady:function(state){if(Gays.Util.isBoolean(state)){if(_data.connReady=!!(state&&this.getSystem())){_data.reconnDelay=0;_data.reconnTimes=_CHAT_CONST.CONFIG.TIMES_IM_RECONN;this.reconnect(false);this._checkReady();}else{if(_data.reconnTimes){this.reconnect();_data.reconnTimes--;}else{this.delayReconnect();}
this.setError(_CHAT_CONST.ERROR.DISCONNECT,new Error('Connection lost!'));}}
return _data.connReady;},isReady:function(){return this._uiReady()&&this._connReady();},_checkReady:function(){if(this.isReady()){this.clearError();}else{this.notify(_CHAT_CONST.NOTIFY.LOAD);}},hasError:function(){return _data.isError;},setError:function(code,error){_data.isError=true;var system=this.getSystem();if(system&&system.isConnect()){system.disconnect();}else{this.notify(_CHAT_CONST.NOTIFY.CONN_ERROR);}},clearError:function(){_data.isError=false;this.notify(_CHAT_CONST.NOTIFY.NONE);},regSysHandler:function(name,handler){if(name&&Gays.Util.isFunction(handler)){var handlers=ChatSystem._handler[name];ChatSystem._handler[name]=handlers||(handlers=[]);handlers.push(handler);}},start:function(id){var self=this;ChatHelper.start({id:id,success:function(id){self._newContact(id)&&self._newWindow(id).open();}});},reconnect:function(stop){clearInterval(_data.reconnTimer);_data.reconnTimer=null;var system=this.getSystem(),uiConn=this._getUI(_CHAT_CONST.UI.RECONNECT);if(stop){if(uiConn)uiConn.className='wait';}else{if(uiConn)uiConn.className='conn';if(system)system.connect();}},delayReconnect:function(){if(!_data.reconnTimer){var self=this,system=this.getSystem(),uiConn=this._getUI(_CHAT_CONST.UI.RECONNECT),uiDelay=this._getUI(_CHAT_CONST.UI.RECONNECT_DELAY);function updateTime(time){Gays.UI.setText(uiDelay,time>60?parseInt(time/60)+'m '+(time%60):time);}
if(uiConn)uiConn.className='wait';updateTime(_data.timeReconnet=_data.reconnDelay+=_CHAT_CONST.CONFIG.TIME_INC_RECONN);_data.reconnTimer=setInterval(function(){updateTime(--_data.timeReconnet);if(_data.timeReconnet<1){self.reconnect();}},1000);}},_offlineCheck:function(stop){var id,contacts=this._getContacts();for(id in contacts){contacts[id]._offlineCheck(stop);}}};ChatContact.prototype={_offlineCheck:function(stop){if(stop&&this._offlineCheckDelay){clearTimeout(this._offlineCheckDelay);this._offlineCheckDelay=null;}else if(!this._offlineCheckDelay){var CONTACT=_CONST.CONTACT,self=this,isFriend=Gays.Contact.isFriend(self.id);if(self.lastState!=CONTACT.STATE_OFFLINE){this._offlineCheckDelay=setTimeout(function(){self._offlineCheckDelay=null;if(Gays.Contact.getState(self.id)<CONTACT.STATE_ACTIVE){if(isFriend){Gays.Contact.updateState(self.id,CONTACT.STATE_OFFLINE);self.window&&self.window.updatePresence(CONTACT.STATE_OFFLINE);}else{self.relink=_CHAT_CONST.RELINK.READY;self.setState(self.lastState);self.window&&self.window.notify();}}},3*1000);}else{Gays.Contact.updateState(self.id,CONTACT.STATE_OFFLINE);}}},_createUI:function(){var
UI=_CHAT_CONST.UI,item,data=Gays.Contact.get(this.id),template=Chat._getTContact();item=Gays.Util.parseHTML(template,{uid:this.id,name:data.name,avatar:data.avatar}).firstChild;if(item){item=$(item);this.ui={item:item,unread:item.select(UI.UNREAD)[0],avatar:item.select(UI.AVATAR)[0]};}
if(!data.friend)item.className+=' nonFriend';this._regHandler();},getUI:function(name){var
UI=_CHAT_CONST.UI,ui=this.ui;name=name||UI.CONTACT;if(!ui)return null;switch(name){case UI.CONTACT:return ui.item;case UI.UNREAD:return ui.unread;case UI.AVATAR:return ui.avatar;}},getPosition:function(){var offset,ui=this.getUI();if(ui){offset=ui.positionedOffset();return{x:offset[0],y:offset[1]};}
return null;},getAvatarPosition:function(){var offset,ui=this.getUI(_CHAT_CONST.UI.AVATAR);if(ui){var offset=ui.positionedOffset();return{x:offset[0],y:offset[1]}}
return null;},updatePresence:function(resource,presence){var
CONTACT=_CONST.CONTACT,RELINK=_CHAT_CONST.RELINK,state=CONTACT.STATE_OFFLINE,active=false,idle=false;if(presence==CONTACT.STATE_OFFLINE){if(!(resource in this.presence))return;delete this.presence[resource];}else{if(this.presence[resource]==presence)return;this.presence[resource]=presence;}
for(var rc in this.presence){switch(this.presence[rc]){case CONTACT.STATE_ACTIVE:active=true;break;case CONTACT.STATE_IDLE:idle=true;break;}}
switch(true){case active:state=CONTACT.STATE_ACTIVE;break;case idle:state=CONTACT.STATE_IDLE;break;}
if(state==CONTACT.STATE_OFFLINE&&!Gays.Contact.isFriend(this.id)&&(this.unread||!(this.window&&this.window.isClose()))){if(this.relink!=RELINK.START||this.relink!=RELINK.LOCK){this.relink=RELINK.READY;}}else{if(!Gays.Contact.isFriend(this.id)){if(state!=CONTACT.STATE_OFFLINE){this.relink=RELINK.NONE;this._offlineCheck(true);}
this.setState(state);}else if(state!=CONTACT.STATE_OFFLINE){clearTimeout(this._offlineNotifyDelay);this._offlineNotifyDelay=null;this._offlineCheck(true);this.setState(state);}else if(!this._offlineNotifyDelay){var self=this;this._offlineNotifyDelay=setTimeout(function(){self._offlineNotifyDelay=null;self.setState(_CONST.CONTACT.STATE_OFFLINE);},10*1000);}}},setState:function(state){this.lastState=state;Chat._updateNOC(Gays.Contact.getState(this.id),state);Gays.Contact.updateState(this.id,state);this.updateSection();Chat.notify();if(!this.onRestore&&this.window){this.window.updatePresence(state);Chat._storeChat(this.window);}},updateSection:function(onChat){var
CONTACT=_CONST.CONTACT,LIST=_CHAT_CONST.LIST,section;if(onChat||this.onChat()){section=LIST.TYPE_OPEN;}else{switch(this.getState()){case CONTACT.STATE_ACTIVE:section=LIST.TYPE_ACTIVE;break;case CONTACT.STATE_IDLE:section=LIST.TYPE_IDLE;break;default:section=LIST.TYPE_OFFLINE;break;}}
if(section=Chat.getSection(section)){section.add(this);}},_updateUnread:function(){var ui=this.getUI(_CHAT_CONST.UI.UNREAD);if(ui){var display=!!this.unread;Gays.UI.setText(ui,this.unread);ui.style.display=display?'block':'none';}
this.onRestore||Chat._storeChat(this.window);},incUnread:function(){this.unread++;this.sMsgs++;this._updateUnread();this.section&&this.section.addUnread();},clearUnread:function(){if(this.unread){this.section&&this.section.removeUnread(this.unread);this.unread=0;this._updateUnread();Chat.checkUnread();}},_regHandler:function(){var self=this;Event.observe(this.ui.item,'click',function(){self._hdlClick();});},_hdlClick:function(){if(!this.window)Chat._newWindow(this.id);this.window.open();},getId:function(){return this.id;},getState:function(){return Gays.Contact.getState(this.id);},restore:function(data){if(data){this.onRestore=true;this.lastState=data.state;this.sMsgs=parseInt(data.sMsgs)||0;this.restoreUnread(data.unread);Chat._newWindow(this.id).restore(data);this.onRestore=false;}},restoreUnread:function(num){if(num=parseInt(num)||0){this.unread+=num;this._updateUnread();this.section&&this.section.addUnread(num);}},onChat:function(){return this.unread||(this.window&&!this.window.isClose());},isVisible:function(){var ui=this.getUI();return ui&&(ui.offsetWidth>0||ui.offsetHeight>0);}};ChatSection.prototype={_loadUI:function(ui){var UI=_CHAT_CONST.UI;this.ui={item:ui,header:ui.select(UI.SECTION_HEADER)[0],unread:ui.select(UI.UNREAD)[0],list:ui.select(UI.SECTION_LIST)[0]};this._regHandler();},_regHandler:function(){var self=this;if(this.ui.header&&this.ui.unread){Event.observe(this.ui.header,'click',function(){self.toggle();});}},_updateUnreadUI:function(){var ui=this.ui.unread;if(ui){var display=(this.unread&&this.isCollapsed());Gays.UI.setText(ui,this.unread);ui.style.display=display?'block':'none';}},addUnread:function(num){num=parseInt(num)||1;this.unread+=num;this._updateUnreadUI();},removeUnread:function(num){num=parseInt(num)||0;this.unread-=num;this._updateUnreadUI();},display:function(){this.ui.item.style.display=this.ui.header&&this.hasContact()?'block':'none';},add:function(contact){if(contact instanceof ChatContact&&contact.section!=this){var uiList=this.ui.list,uiContact=contact.getUI();if(uiList&&uiContact){uiList.appendChild(uiContact);contact.section&&contact.section.remove(contact);contact.unread&&this.addUnread(contact.unread);contact.section=this;this.display();}}},remove:function(contact){if(contact instanceof ChatContact&&contact.section==this){contact.unread&&this.removeUnread(contact.unread);contact.section=null;this.display();}},expand:function(){if(this.isCollapsed()){this.ui.item.removeClassName('collapse');this.state=_CHAT_CONST.LIST.STATE_EXPANDED;Chat._storeSection(this);this._updateUnreadUI();}},collapse:function(){if(this.isExpanded()){this.ui.item.addClassName('collapse');this.state=_CHAT_CONST.LIST.STATE_COLLAPSEED;Chat._storeSection(this);this._updateUnreadUI();}},toggle:function(state){state=Gays.Util.param(state,this.isCollapsed());state?this.expand():this.collapse();},contactCount:function(){var count=0,i=0,nodes=this.ui.list.childNodes;for(;i<nodes.length;i++){nodes[i].nodeType==1&&count++;}
return count;},hasContact:function(){return!!this.ui.list.firstChild;},isCollapsed:function(){return this.state==_CHAT_CONST.LIST.STATE_COLLAPSEED;},isExpanded:function(){return this.state==_CHAT_CONST.LIST.STATE_EXPANDED;},isVisible:function(){var ui=this.ui.item;return ui&&(ui.offsetWidth>0||ui.offsetHeight>0);}};ChatWindow.prototype={_createUI:function(){var
UI=_CHAT_CONST.UI,LEN_NAME=_CHAT_CONST.WINDOW.LEN_NAME,LEN_STATUS=_CHAT_CONST.WINDOW.LEN_STATUS,data=Gays.Contact.get(this.id),template=Chat._getTWindow(),suffix='...',name=data.name,status=Gays.Util.unescapeHTML(data.status),shortName=name.length>LEN_NAME?name.slice(0,LEN_NAME-suffix.length)+suffix:name,shortStatus=status.length>LEN_STATUS?status.slice(0,LEN_STATUS-suffix.length)+suffix:status,item=Gays.Util.parseHTML(template,{uid:this.id,name:name.replace(/"/g,'\\"'),shortName:Gays.Util.escapeHTML(shortName),avatar:data.avatar,link:data.link,status:data.status.replace(/"/g,'\\"'),shortStatus:Gays.Util.escapeHTML(shortStatus)}).firstChild;if(item){item=$(item);this.ui={item:item,handle:item.select(UI.WINDOW_MOVE_HANDLER)[0],mini:item.select(UI.WINDOW_MINI)[0],close:item.select(UI.WINDOW_CLOSE)[0],state:item.select(UI.WINDOW_USER_STATE)[0],messages:item.select(UI.WINDOW_MESSAGES)[0],notify:item.select(UI.WINDOW_NOTIFY)[0],input:item.select(UI.WINDOW_INPUT)[0],statusBar:item.select(UI.WINDOW_STATUS_BAR)[0]};}
if(!data.friend)item.className+=' nonFriend';this._regHandler();this.updatePresence(this.contact.getState());},getUI:function(name){var
UI=_CHAT_CONST.UI,ui=this.ui;name=name||UI.WINDOW;if(!ui)return null;switch(name){case UI.WINDOW:return ui.item;case UI.WINDOW_NOTIFY:return ui.notify;case UI.WINDOW_INPUT:return ui.input;case UI.WINDOW_STATUS_BAR:return ui.statusBar;case UI.WINDOW_USER_STATE:return ui.state;case UI.WINDOW_MESSAGES:return ui.messages;case UI.WINDOW_MOVE_HANDLER:return ui.handle;case UI.WINDOW_MINI:return ui.mini;case UI.WINDOW_CLOSE:return ui.close;}},_regHandler:function(){var self=this,docEl=document.documentElement,avatar=Element.select(self.ui.handle,'a.avatar')[0];function mouseMove(event){event=event||window.event;self._move(dx+Event.pointerX(event),dy+Event.pointerY(event));}
function mouseUp(){docEl.onmouseup=docEl.onmousemove=null;self._moved();return false;}
function stopEvent(event){if(window.event){window.event.cancelBubble=true;}else{event.stopPropagation();}}
self.ui.mini.onclick=function(event){self.mini();stopEvent(event||null);return false;};self.ui.close.onclick=function(event){self.close();stopEvent(event||null);return false;};self.ui.item.onclick=function(){self.activate();};self.ui.input.onkeydown=function(event){self._hdlInput(event||window.event);};self.ui.mini.onmousedown=this.ui.close.onmousedown=rFalse;self.ui.handle.onclick=avatar.onmousedown=stopEvent;self.ui.handle.onmousedown=function(event){event=event||window.event;dx=self.x-Event.pointerX(event);dy=self.y-Event.pointerY(event);docEl.onmousemove=mouseMove;docEl.onmouseup=mouseUp;};self.ui.handle.onmouseup=mouseUp;self.ui.handle.onselectstart=function(){return false;};},getId:function(){return this.id;},getPosition:function(){return{x:this.x,y:this.y};},notify:function(type){var
CONTACT=_CONST.CONTACT,NOTIFY=_CHAT_CONST.NOTIFY,ui=this.getUI(_CHAT_CONST.UI.WINDOW_NOTIFY),presence=Gays.Contact.getState(this.id),className='notify ';this.chatbale=false;if(type==NOTIFY.CONN_ERROR||Chat.hasError()){className+=NOTIFY.CONN_ERROR;}else if(type==NOTIFY.LOAD||presence==CONTACT.STATE_UNDEFINED||!Chat.isReady()){className+=NOTIFY.LOAD;}else if(type==NOTIFY.OFFLINE||presence==CONTACT.STATE_OFFLINE){className+=NOTIFY.OFFLINE;}else if(type==NOTIFY.SEND){className+=NOTIFY.SEND;this.chatbale=true;}else{this.chatbale=true;}
if(ui&&className){ui.className=className;}},statusBarNotify:function(type){var ui=this.getUI(_CHAT_CONST.UI.WINDOW_STATUS_BAR),classNames=['statusBar'];switch(type){case _CHAT_CONST.NOTIFY.TYPING:classNames.push('typing');break;}
ui.className=classNames.join(' ');},updatePresence:function(state){var
CONTACT=_CONST.CONTACT,ui=this.getUI(_CHAT_CONST.UI.WINDOW_USER_STATE),className='item state ',notify=_CHAT_CONST.NOTIFY.NONE;switch(state){case CONTACT.STATE_IDLE:className+='idle';break;case CONTACT.STATE_ACTIVE:className+='active';break;case CONTACT.STATE_OFFLINE:className+='offline';notify=_CHAT_CONST.NOTIFY.OFFLINE;break;}
ui.className=className;this.notify(notify);},isClose:function(){return!this._isVisible()&&this.state==_CHAT_CONST.WINDOW.STATE_CLOSE;},isOpen:function(){return this._isVisible()&&this.state==_CHAT_CONST.WINDOW.STATE_OPEN;},isMini:function(){return!this._isVisible()&&this.state==_CHAT_CONST.WINDOW.STATE_MINI;},_isVisible:function(){var ui=this.getUI();return ui.offsetWidth>0||ui.offsetHeight>0;},activate:function(focus){this.onRestore||this.contact.clearUnread();focus!==false&&this.getUI(_CHAT_CONST.UI.WINDOW_INPUT).focus();var lastActive=_data.lastActive;if(lastActive!=this){if(lastActive instanceof ChatWindow)lastActive.deactivate();this.ui.item.style.zIndex=1;_data.lastActive=this;}},deactivate:function(){this.ui.item.style.zIndex=0;},close:function(){var ui=this.getUI();if(ui&&!this.isClose()){this.state=_CHAT_CONST.WINDOW.STATE_CLOSE;ui.style.display='none';ChatWindowGrid.unregister(this);this.resetInput();if(Gays.Contact.isFriend(this.id)){this.store();}else if(!this.contact.unread){Chat._storeChat(this,true);ChatHelper.stop({id:this.id});}
this.contact.updateSection();if(!Gays.Contact.isOnline(this.id)){Chat.notify();}}},mini:function(){var ui=this.getUI();if(ui&&!this.isMini()){this.state=_CHAT_CONST.WINDOW.STATE_MINI;if(this.onRestore){ui.style.display='none';this.contact.updateSection();}else{this._fadeOut();this.store();}}},open:function(focus){var ui=this.getUI();if(ui&&!this.isOpen()){this.onRestore||this.park();this.state=_CHAT_CONST.WINDOW.STATE_OPEN;ui.style.display='block';this.contact.updateSection();this.scrollDown();this.activate(focus);if(!this.onRestore){new Effect.Highlight(ui,{startcolor:'#e3e8cd',endcolor:'#a2a2a2'});this.store();}}else{this.activate();}},_fadeOut:function(){if(!this._isVisible())return;var dist={x:0,y:0},pos={x:0,y:0},uiWindow=this.getUI(),dim=uiWindow.getDimensions(),template='<div id="#id#" style="background:white;border:6px solid #a2a2a2;position:absolute;z-index:1000;width:#width#px;height:#height#px;top:#top#px;left:#left#px;"></div>';ui=Gays.Util.parseHTML(template,{id:'frame_'+this.id,width:dim.width,height:dim.height,left:this.x,top:this.y}).firstChild;uiWindow.style.display='none';if(ui){ui=$(ui);uiWindow.parentNode.appendChild(ui);if(this.contact.isVisible()){pos=this.contact.getAvatarPosition();}
dist.x=pos.x-this.x;dist.y=pos.y-this.y;var duration=0.4
new Effect.Move(ui,{x:dist.x,y:dist.y,duration:duration,afterFinish:function(effect){ui.remove();}});new Effect.Scale(ui,1,{duration:duration});}},_move:function(x,y){var ui=this.ui.item;ui.style.left=(this.x=x)+'px';ui.style.top=(this.y=y)+'px';},_moved:function(){ChatWindowGrid.register(this);this.store();},park:function(x,y){if(this.isClose()){var pos=ChatWindowGrid.genPos();x=pos.x,y=pos.y;this._move(parseInt(x),parseInt(y));this._moved();}},addMessage:function(message){if(message instanceof ChatMessage){var
GAP_TIME=_CHAT_CONST.MESSAGE.GAP_TIME*1000,msgMetaUI=message.getUI(_CHAT_CONST.UI.MESSAGE_META),showMeta=true;if((this.lastMsg&&this.lastMsg.getAuthorId()==message.getAuthorId())&&(this.lastGapMsg&&(message.getTime()-this.lastGapMsg.getTime())<GAP_TIME)){showMeta=false;}else{this.lastGapMsg=message;}
msgMetaUI.style.display=showMeta?'block':'none';this.lastMsg=message;this.getUI(_CHAT_CONST.UI.WINDOW_MESSAGES).appendChild(message.getUI());this.scrollDown();this.notify(_CHAT_CONST.NOTIFY.NONE);this.statusBarNotify(_CHAT_CONST.NOTIFY.NONE);}},sendStack:function(){if(!this.msgStack.length)return;var content,success,userId=Gays.getUserId(),online=Gays.Contact.isOnline(this.id);while(msg=this.msgStack.shift()){content='#T#'+msg.date+'#'+msg.content;success=online&&ChatSystem.sendMessage(this.id,content);Chat._newMessage({from:userId,to:this.id,date:msg.date,content:Gays.Util.escapeHTML(msg.content),loss:!success});if(success){this.contact.sMsgs++;}}
this.store();this.notify();},sendMessage:function(content){var self=this,contact=self.contact,RELINK=_CHAT_CONST.RELINK;self.msgStack.push({content:content,date:Gays.getServDate().getTime()});if(contact.relink==RELINK.READY){contact.relink=RELINK.START;self.notify(_CHAT_CONST.NOTIFY.SEND);ChatHelper.start({id:self.id,async:true,link:function(result){if(result==1){contact.relink=RELINK.NONE;}else{contact.relink=RELINK.LOCK;contact.setState(_CONST.CONTACT.STATE_OFFLINE);}
self.sendStack();}});}else if(contact.relink!=RELINK.START){self.sendStack();}},_fetchMessage:function(num){if(this.onRestore&&(num=parseInt(num))){var self=this,cId=this.id,userId=Gays.getUserId(),url=Chat._getMessageUrl(cId,num),uiLoading=this.getUI().select(_CHAT_CONST.UI.MESSAGE_LOADING)[0];if(url){uiLoading&&(uiLoading.style.display='block');new Ajax.Request(url,{method:'get',asynchronous:true,onSuccess:function(response){var messages=response.responseText.evalJSON();for(var i=0,msg;i<messages.length;i++){msg=messages[i];msg.body=msg.body.replace(_CHAT_CONST.MESSAGE.MSG_TIME_PATTERN,function(m,p,t){msg.time=t?parseInt(t):parseInt(msg.time+'000');return m.slice(p.length);});}
messages.sort(function(a,b){return a.time<=b.time?-1:1;}).each(function(item){Chat._newMessage({from:item.dir?userId:cId,to:item.dir?cId:userId,content:item.body,date:item.time});});},onComplete:function(){uiLoading&&(uiLoading.style.display='none');}});}}},setTyping:function(stop){if(stop){clearTimeout(this._typing);ChatSystem.sendState(this.id,'paused');this._typing=null;}else if(!this._typing){var self=this;ChatSystem.sendState(this.id,'composing');this._typing=setTimeout(function(){self.setTyping(true);},_CHAT_CONST.CONFIG.TIME_STOP_TYPING*1000);}},resetInput:function(){var ui=this.getUI(_CHAT_CONST.UI.WINDOW_INPUT);if(ui){ui.value='';ui.setAttribute('rows',1);ui.style.height=_CHAT_CONST.WINDOW.INPUT_LINE_HEIGHT+'px';}},scrollDown:function(){var ui=this.getUI(_CHAT_CONST.UI.WINDOW_MESSAGES);ui.scrollTop=ui.scrollHeight;},store:function(){if(!this.onRestore){var remove=false;if(arguments.callee.caller==this.close&&!this.contact.sMsgs)remove=true;Chat._storeChat(this,remove);}},restore:function(data){if(data){var WINDOW=_CHAT_CONST.WINDOW;this.onRestore=true;this.updatePresence(data.state);this._move(data.x,data.y);this._fetchMessage(data.sMsgs);switch(data.window){case WINDOW.STATE_MINI:this.mini();break;case WINDOW.STATE_OPEN:this.open(false);break;}
this.onRestore=false;}},_hdlInput:function(event){var WINDOW=_CHAT_CONST.WINDOW,input=this.ui.input,online=Gays.Contact.isOnline(this.id);this.contact.clearUnread();switch(event.keyCode){case Event.KEY_ESC:online&&this.setTyping(true);this.resetInput();break;case Event.KEY_RETURN:if(this.chatbale&&/\S/.test(input.value)&&online){this.sendMessage(input.value);this.resetInput();}
Event.stop(event);break;default:online&&this.setTyping();var len=input.value.length,maxOneRow=WINDOW.LEN_INPUT_ONE_ROW,maxRows=WINDOW.LEN_INPUT_ROWS,rows=parseInt(len/maxOneRow)+1,cRows=input.getAttribute('rows')-0,maxCharReached=len&&len%maxOneRow==0&&cRows<5&&rows>cRows,textTooLong=input.scrollHeight>input.clientHeight&&cRows<5;if(maxCharReached||textTooLong){input.setAttribute('rows',cRows+1);input.style.height=(WINDOW.INPUT_LINE_HEIGHT*(cRows+1))+'px';}
break;}}};ChatMessage.prototype={_createUI:function(){var
UI=_CHAT_CONST.UI,contactId=this.getContactId(),template=Chat._getTMessage(),type=[this.isSend()?'me':'',this.loss?'loss':''].join(' '),item=Gays.Util.parseHTML(template,{author:this.getAuthorName(),date:this._genUIDate(),content:Gays.Util.renderLink(this.content),type:type}).firstChild;if(item){item=$(item);this.ui={item:item,meta:item.select(UI.MESSAGE_META)[0],content:item.select(UI.MESSAGE_CONTENT)[0]};}},getUI:function(name){var
UI=_CHAT_CONST.UI,ui=this.ui;name=name||UI.MESSAGE;if(!ui)return null;switch(name){case UI.MESSAGE:return ui.item;case UI.MESSAGE_META:return ui.meta;case UI.MESSAGE_CONTENT:return ui.content;}},isSend:function(){return this.from==Gays.getUserId();},getContactId:function(){return this.isSend()?this.to:this.from;},getAuthorId:function(){return this.from;},getAuthorName:function(){return this.isSend()?Gays.getUserName():Gays.Contact.getName(this.from);},getTime:function(){return this.date.getTime();},_genUIDate:function(){var result='',now=new Date,date=this.date,year=date.getFullYear(),month=date.getMonth(),day=date.getDate(),hours=date.getHours(),minutes=date.getMinutes();if(now.getFullYear()!=year||now.getMonth()!=month||now.getDate()!=day){if((month+=1)<10)month='0'+month;if(day<10)day='0'+day;result=year+'-'+month+'-'+day+' ';}
if(minutes<10)minutes='0'+minutes;return result+=hours+':'+minutes;}};ChatSection.constructor=ChatSection;ChatContact.constructor=ChatContact;ChatWindow.constructor=ChatWindow;ChatMessage.constructor=ChatMessage;})(Gays);Gays.UI={getText:function(ui){return ui?'textContent'in ui?ui.textContent:ui.innerText:'';},setText:function(ui,text){if(ui.textContent==undefined){ui.innerText=text;}else{ui.textContent=text;}},removeFriend:function(list,id,url){if(list&&id&&url){var ui=$('member_'+id);if(ui&&confirm('Are you sure?')){ui.remove();Gays.Contact.remove(id,url);this.resetRowsColor($$(list+' li'));}}},resetRowsColor:function(items){for(var i=0;i<items.length;i++){items[i].className=i%2?'odd':'even';}},memberList:function(items,check){var
myId=Gays.getUserId(),ids=[],indicators=[],chats=[];members=[],$$(items).each(function(item,i){var id=item.id.replace(/[^\d]/g,'');if(id!=myId){ids.push(id);indicators.push(item.select('img.wioIndicator')[0]);chats.push(item.select('a.chat')[0]);members.push(item);}});if(ids.length){function bindChat(ui,i){ui.onclick=function(){var data={},id=ids[i];if(!Gays.Contact.exists(id)){data[id]={name:members[i].select('.username a')[0].innerHTML,avatar:members[i].select('img[class^=userAvatar]')[0].src,status:members[i].select('.statusText')[0].innerHTML,friend:false};Gays.Contact._store(data);}
Gays.Chat.start(id);window.scrollTo(0,0);return false;};}
chats.each(bindChat);indicators.each(bindChat);check&&Gays.Contact.fetchState({id:ids,success:function(data){ids.each(function(id,i){var indicator=indicators[i],chat=chats[i];if(indicator&&chat&&(id in data)){indicator.style.display=chat.style.display=data[id]?'':'none';}});}});}}};(function(NS){var
CONST={PERCENTAGE:/^(-?\d+)%$/,POINTER_GAY:10,POINTER_WIDTH:23,H_SPACE:16,V_SPACE:33,MIN_WIDTH:71,MAX_WIDTH:503,MIN_HEIGHT:53,MAX_HEIGHT:520,H_MARGIN:36,V_MARGIN:8,DELAY:300},offset=function(element){var top=0,left=0;do{top+=element.offsetTop||0;left+=element.offsetLeft||0;element=element.offsetParent;}while(element);return{left:left,top:top};},posPointer=function(pointer,position,isRight){pointer.style[!isRight?'right':'left']='auto';pointer.style[isRight?'right':'left']=position;},dom=function(tag,className){var element=document.createElement(tag);element.className=className||'';return element;},grpDiv=function(classNames,container){var group=[],i=0;for(;i<classNames.length;i++){group.push(container.appendChild(dom('div',classNames[i])));}
return group;},newBubble=function(){var ui={shell:dom('div','bubble'),body:dom('div','bubble_body'),content:dom('span','bubble_content'),pointer:dom('div','bubble_pointer')};ui.corners=grpDiv(['bubble_lt','bubble_lb','bubble_rt','bubble_rb'],ui.shell);ui.horizontal=grpDiv(['bubble_left','bubble_right'],ui.shell);ui.vertical=grpDiv(['bubble_top','bubble_bottom'],ui.shell);ui.horizontal.push(ui.body);ui.vertical.push(ui.body);ui.body.appendChild(ui.content);ui.shell.appendChild(ui.body);ui.shell.appendChild(ui.pointer);return ui;},hdlMouseOver=function(bubble,event,options){if(!bubble._container)return;bubble._clearTimer();bubble.content(options.content);bubble.show();bubble.autoSize(options.width);bubble.posPointer(options.pointer||bubble._pointerPos);bubble.park(this,options);},hdlMouseOut=function(bubble){if(!bubble._container)return;bubble._clearTimer();bubble.delayHide(CONST.DELAY);},Bubble=NS.Bubble=function(){var self=this;this.ui=newBubble();this.visable=false;this._timer=null;this._container=null;this._offset=null;this.ui.body.onmouseover=function(){self._clearTimer();self.ui.body.onmouseout=function(){self.delayHide(CONST.DELAY);};};};Bubble.prototype={_clearTimer:function(){if(this._timer){clearTimeout(this._timer);this._timer=null;}},show:function(){this.visable=true;this.ui.shell.style.display='block';},hide:function(){this.visable=false;this.ui.shell.style.display='none';},delayHide:function(time){var self=this;if(!self._container)return;self._clearTimer();self._timer=setTimeout(function(){self.hide();},time);},content:function(html){if(typeof html==='string'){this.ui.content.innerHTML=html;}
return this.ui.content.innerHTML;},width:function(value){value=Math.min(Math.max(parseInt(value),CONST.MIN_WIDTH),CONST.MAX_WIDTH);value-=CONST.H_SPACE;value+='px';for(var i=0,element;i<this.ui.vertical.length;i++){element=this.ui.vertical[i];element.style.width=value;}},height:function(value){value=Math.min(Math.max(parseInt(value),CONST.MIN_HEIGHT),CONST.MAX_HEIGHT);value-=CONST.V_SPACE;value+='px';for(var i=0,element;i<this.ui.horizontal.length;i++){element=this.ui.horizontal[i];element.style.height=value;}},posPointer:function(position,setDefault){if(setDefault){if(!isNaN(position)||CONST.PERCENTAGE.test(position))this._pointerPos=position;return;}
if(position===null||!this._container)return;if(!isNaN(position)){position=new Number(position);var bubbleWidth=this.ui.shell.offsetWidth,isRight=position<0;position=(CONST.POINTER_GAP<position?CONST.POINTER_GAP:CONST.POINTER_GAP+CONST.POINTER_WIDTH<bubbleWidth-position?position:bubbleWidth-CONST.POINTER_GAP-CONST.POINTER_WIDTH)+'px';posPointer(this.ui.pointer,position,isRight);}else if(CONST.PERCENTAGE.test(position)){var bubbleWidth=this.ui.shell.offsetWidth,percentage=CONST.PERCENTAGE.exec(position)[1]-0,isRight=percentage<0;percentage=Math.abs(percentage)-Math.floor(Math.abs(percentage/100))*100;position=bubbleWidth*(percentage/100);position=CONST.POINTER_GAP>position?CONST.POINTER_GAP+'px':percentage+'%';posPointer(this.ui.pointer,position,isRight);}},position:function(x,y){var shell=this.ui.shell;if(isNaN(x)||isNaN(y)){return{x:shell.offsetLeft,y:shell.offsetTop};}else{shell.style.left=parseInt(x)+'px';shell.style.top=parseInt(y)+'px';}},park:function(element){if(!this._container)return;this.trigger=element;var elementOffset=offset(element),deltaOffset={left:elementOffset.left-this._offset.left+(element.offsetWidth/2)-(this.ui.pointer.offsetLeft+Math.round(CONST.POINTER_WIDTH/2)),top:elementOffset.top-this._offset.top-this.ui.shell.offsetHeight};this.position(deltaOffset.left,deltaOffset.top);},autoSize:function(width){if(!this._container)return;width=parseInt(width);if(isNaN(width))this.resetSize();else width=Math.min(Math.max(width,CONST.MIN_WIDTH),CONST.MAX_WIDTH);this.width(width||(this.ui.content.clientWidth+CONST.H_SPACE));this.height(this.ui.content.clientHeight+CONST.V_SPACE);width&&this.height(this.ui.content.clientHeight+CONST.V_SPACE);},resetSize:function(){this.height(CONST.MAX_HEIGHT);this.width(CONST.MAX_WIDTH);},container:function(container){this._container=container;this._offset=offset(container);container.appendChild(this.ui.shell);return this._container;},bind:function(element,options){var self=this;element.onmouseover=function(event){hdlMouseOver.call(this,self,event||window.event,options);};element.onmouseout=function(){hdlMouseOut.call(this,self);};}};})(Gays.UI);Gays.Connection={suffix:'Handle',formSerialize:'',formName:'connectionForm',loadingText:'Please wait...',submitFriend:'submitFriend',submitId:'submit',cancelId:'cancel',dontKnow:'through_dontknow',noticeFinish:'noticeFinish',doNext:function(el){var f=el.form,els=f.elements,x,nextEl;for(var i=0,len=els.length;i<len;i++){x=els[i];if(el==x&&(nextEl=els[i+1])){if(nextEl.focus)nextEl.focus();}}},observeAction:function(){var submitFriend=$(this.submitFriend),submit=$(this.submitId),formSerialize=$(this.formName).serialize();if(submitFriend){if(formSerialize!=this.formSerialize){submitFriend.hide();submit.show();}else{submitFriend.show();submit.hide();}}},init:function(){var self=this;$$('input[type="checkbox"]').each(function(it){if(!it.checked)return;$(it.id.dasherize().camelize()+self.suffix).setStyle({display:'block'});});if(!$(this.submitFriend)){$(this.submitId).show();}
this.formSerialize=$(this.formName).serialize();},showHide:function(o){if($(o)==null){return;}
if($(o).id==this.dontKnow){if($(o).checked){$(this.cancelId).show();$(this.submitId).hide();if($(this.submitFriend))$(this.submitFriend).hide();}else{$(this.cancelId).hide();$(this.submitId).show();if($(this.submitFriend))$(this.submitFriend).show();this.observeAction();}
return;}
this.observeAction();var id=$(o).id.dasherize().camelize()+this.suffix;if(!$(id)){return;}
$(id).setStyle({display:$(o).checked?'block':'none'});this.doNext(o);},reset:function(){this.observeAction();var self=this;$(this.formName).reset();$(this.formName).select('div.form_error').each(function(it){if(!it.innerHTML.stripTags().blank()){it.hide();var input=it.next('input');input.value='';}});$$('div[id$='+self.suffix+']').each(function(it){var checkbox=$(it.id.gsub(self.suffix,'').underscore());if(checkbox.checked){$(it).setStyle({display:'block'});}else{$(it).setStyle({display:'none'});}});this.showHide($(this.dontKnow));this.init();}};Gays.ExpandableBox={lastTime:null,expireTime:1,setPreference:function(id,url,obj,collapseText,expandText){if(this.lastTime!=null&&((new Date().getTime())-this.lastTime)/1000<this.expireTime){return;}
this.lastTime=new Date().getTime();var box=$(id);obj=$(obj);new Ajax.Request(url,{method:'get',onSuccess:function(){var p=$(obj.parentNode);$(obj).remove();if(box.getStyle('display')!='none'){p.insert(expandText);box.setStyle({display:'none'});}else{p.insert(collapseText);box.setStyle({display:'block'});}}});},toggle:function(obj,id,collapseText,expandText){Effect.toggle(id,'blind',{afterFinish:function(){$(obj).down('img').src=$(id).visible()?collapseText:expandText;}});}};Gays.Search={getFriends:function(id,url){id=$(id);if(id.innerHTML==''){Gays.Util.ajaxUpdater(id,url);}
id.toggle();}};Gays.PMS={classes:{clickClass:'selected'},setThreadAndBlockIds:function(){this.threadIds=this.getThreadIds('HolderThread');this.newsletterIds=this.getThreadIds('HolderNewsletter');this.threadBlockIds=this.getThreadBlockIds('HolderThread').concat(this.getThreadBlockIds('HolderNewsletter'));this.parameters={thread_ids:this.threadIds.join(' '),newsletter_ids:this.newsletterIds.join(' ')};},deleteMessages:function(url,e){this.setThreadAndBlockIds();var self=this;if(this.threadIds.size()+this.newsletterIds.size()<1){return alert('Please select some threads to delete');}
if(!confirm('Are you sure?')){return;}
new Ajax.Request(url,{parameters:self.parameters,onComplete:function(){self.updateInboxCount();self.updateThreadCount();self.threadBlockIds.each(function(it){$(it).remove();});}});},markMessages:function(url,e){this.setThreadAndBlockIds();var self=this;if(this.threadIds.size()+this.newsletterIds.size()<1){return alert('Please select some threads to mark as unread');}
new Ajax.Request(url,{parameters:self.parameters,onComplete:function(){window.location.reload();}});},getThreadIds:function(prefix){var threadIds=[];$$('input[id^='+prefix+']').each(function(it){if(!it.checked)return;threadIds.push(it.value);});return threadIds;},getThreadBlockIds:function(prefix){var threadBlockIds=[];$$('input[id^='+prefix+']').each(function(it){if(!it.checked)return;threadBlockIds.push(it.id.sub(/_$/,''));});return threadBlockIds;},replyMessage:function(id,formId,updateId,updateUrl,e){var self=this;new Ajax.Request($(formId).action,{parameters:$(formId).serialize(),onComplete:function(res){$(id).update(res.responseText);Gays.Util.ajaxUpdater(updateId,updateUrl);self.updateThreadCount();}});return false;},selectMessage:function(status){var self=this;$$('input[id^=HolderThread], input[id^=HolderNewsletter]').each(function(it){it.checked=(status=="none"?false:true);var block=$(it.id.sub(/_$/,''));it.checked?block.addClassName(self.classes.clickClass):block.removeClassName(self.classes.clickClass);});},initThreadsEvents:function(className){var self=this;$$('.'+className+" li").each(function(it){var clickRequest=self.clickOneRequest.bindAsEventListener(this,it,$(it.id+'_'),self.classes.clickClass);it.observe('click',clickRequest);});},clickOneRequest:function(e,block,checkbox,className){if(e.element().tagName.toUpperCase()!='INPUT'){checkbox.checked=!checkbox.checked;}
checkbox.checked?block.addClassName(className):block.removeClassName(className);},updateInboxCount:function(){Gays.Util.ajaxUpdater(INBOX_COUNT_UPDATE,INBOX_COUNT_URL);},updateThreadCount:function(){Gays.Util.ajaxUpdater(INBOX_THREAD_COUNT_UPDATE,INBOX_THREAD_COUNT_URL);}};Gays.Profile={Edit:{addFindmeService:function(id,url,serviceId,serviceUrl){Gays.Util.ajaxUpdater(id,url,{method:'post',parameters:Object.toQueryString({service_id:serviceId,service_url:serviceUrl})});}},showLiveFeed:function(feedId,clickObj,obj){$(clickObj.parentNode,feedId).invoke('toggle');$(clickObj.parentNode).visible()?$($(obj).parentNode).hide():$($(obj).parentNode).show();if(arguments[3]){$(arguments[3]).scrollTo();}}};Gays.Browse={getCities:function(id,imageObj,imageOpen,imageClose,url){var self=this;if($(id).innerHTML==''){Gays.Util.ajaxUpdater(id,url,{onComplete:function(){self.toggle(id,imageObj,imageOpen,imageClose);}});}else{self.toggle(id,imageObj,imageOpen,imageClose);}},toggleRegion:function(id){$$('#browseMembers ul').invoke('hide');$(id).visible()?new Effect.Fade(id,{duration:0.3}):new Effect.Appear(id,{duration:0.3});},toggle:function(id,imageObj,imageOpen,imageClose){var id=$(id);if(id.visible()){$(imageObj).src=imageOpen;new Effect.Fade(id,{duration:0.3});}else{$(imageObj).src=imageClose;new Effect.Appear(id,{duration:0.3});}},detectBackButton:function(){var c=Gays.Cookie,url=window.location.href;if(!c.has('browser_referer_url')){return;}
if(!/(\/gsearch\?|\/browse)/.test(url)){c.remove('browser_referer_url');}
$G(function(){$$('a[href$=/browse]').each(function(it){it.observe('click',function(){c.remove('browser_referer_url');});});});}};Gays.Media={Tag:{lists:null,approveTag:function(url,element){new Ajax.Request(url,{method:'get',onComplete:function(res){if(res.responseText!=''){$(element).remove();}}});},setLists:function(selector){if(!this.lists){this.lists=$$(selector);this.radios=$$(selector+' input[type=radio]');}},filterTags:function(selector,entry,profileLinkId){this.setLists(selector);if(!entry){this.resetTags(profileLinkId);return;}
entry=entry.toLowerCase();foundNEntries=0;foundEntry=null;this.lists.each(function(it){var name=it.down('label').innerHTML.toLowerCase(),findEntry=false;if(name.startsWith(entry)){findEntry=true;}else{name.split(' ').each(function(name){if(name.startsWith(entry)){findEntry=true;throw $break;}});}
if(findEntry){it.down('input').enable();it.show();foundEntry=it;foundNEntries++;}else{it.down('input').disable();it.hide();}});if(foundNEntries==1){var input=foundEntry.down('input');input.checked=true;$(profileLinkId).value=$F(input);}else{$(profileLinkId).value='';this.radios.each(function(it){it.checked=false;});}},resetTags:function(profileLinkId){if(this.lists){this.lists.invoke('show');$(profileLinkId).value='';this.radios.each(function(it){it.enable().checked=false;});}}},haveEnoughSize:function(img,minWidth,minHeight){var size=$(img).getDimensions();return(size.width>=minWidth)&&(size.height>=minHeight);}};Gays.Request={classes:{clickClass:'selected'},friendIds:{selectAll:'HolderFriendRequestsSelectAll',count:'HolderFriendRequests',confirmLink:'HolderFriendRequestsConfirm',prefix:'HolderFriendRequest'},relationshipIds:{count:'HolderRelationshipRequests'},recommendIds:{count:'HolderRecommendRequests'},tagIds:{selectAll:'HolderTagRequestsSelectAll',videosCount:'HolderTagVideoRequests',photosCount:'HolderTagPhotoRequests',confirmLink:'HolderTagRequestsConfirm',prefix:'HolderTagRequest'},notificationsUrl:null,notificationsId:'',setCookie:function(){var paths=document.location.href.split('/');paths.pop();var profileLink=paths.last();if($('HolderNoticeHint'))new Effect.BlindUp('HolderNoticeHint',{duration:0.25});Gays.Cookie.set('tipOfRequest'+profileLink,'Y',365*24*60*60*1000);},ignore:function(url,nodeId,requestType){if(!confirm('Are you sure?')){return false;}
var self=this;new Ajax.Request(url,{onComplete:function(res){$(nodeId).remove();if(requestType=='friend'||requestType=='recommend'||requestType=='relationship'){self.decreaseRequestsCount(1,requestType);}else{if(url.include('photo')){self.decreaseRequestsCount({photos:1},requestType);}else{self.decreaseRequestsCount({videos:1},requestType);}}}});},approve:function(url,nodeId){var self=this;new Ajax.Request(url,{onComplete:function(){$(nodeId).remove();if(url.include('photo')){self.decreaseRequestsCount({photos:1},'tag');}else{self.decreaseRequestsCount({videos:1},'tag');}}});},decreaseRequestsCount:function(num,requestType){var self=this,options={};this.setCookie();switch(requestType){case'recommend':options=this.recommendIds;case'relationship':options=this.relationshipIds;case'friend':options=this.friendIds;var uiCont=$(options.count),count=Math.max(0,parseInt(uiCont.innerHTML)-num);uiCont.update(count);if(!count){var p=$(uiCont.parentNode);p.next(0).show();p.remove();}
break;default:options=this.tagIds;var uiVideosCount=$(options.videosCount),uiPhotosCount=$(options.photosCount),videosCount=Math.max(0,parseInt(uiVideosCount.innerHTML)-(Object.isNumber(num.videos)?num.videos:0)),photosCount=Math.max(0,parseInt(uiPhotosCount.innerHTML)-(Object.isNumber(num.photos)?num.photos:0));uiVideosCount.update(videosCount);uiPhotosCount.update(photosCount);if(videosCount==0&&photosCount==0){var p=$(uiVideosCount.parentNode);p.next(0).show();p.remove();}}
$$('#content-Main li.HolderRequests').each(function(it,i){it.removeClassName('odd').removeClassName('even').addClassName((i+1)%2?'odd':'even');});if(!$$('#friends li.HolderRequests').size()){$('friends').update('No open requests');}
if(this.notificationsUrl&&$(this.notificationsId)){new Ajax.Request(this.notificationsUrl,{method:'get',onComplete:function(xhr){var html=xhr.responseText.replace(/\r|\n/g,'');html=/^\s*<div class=[^>]+>(\s*\S+\s*)+<\/div>\s*$/i.test(html)?html:'';Element.update(self.notificationsId,html);}});}},initRequestsEvents:function(className,notificationsUrl,notificationsId){this.notificationsUrl=notificationsUrl;this.notificationsId=notificationsId;},confirm:function(element,url,requestId,profile){if(!element._sent){element._sent=true;var self=this,indicator=Element.select(element,'img')[0];indicator&&indicator.show();new Ajax.Request(url,{evalScripts:false,onSuccess:function(request,json){$('request_'+requestId).remove();$('success_'+requestId).show().addClassName('HolderRequests');self.decreaseRequestsCount(1,'friend');var data={};data[profile.id]=profile;Gays.Contact.addFriend(data);}});}
return false;}};Gays.AC={elementForm:null,locationNotFound:null,locationNotFoundVisible:false,hasFocusEvent:false,canRun:function(id,event){if((event||window.event).keyCode!=Event.KEY_RETURN)return true;var popw=$(id+"_auto_complete")||$(id);if(!popw)return true;return popw.getStyle('display')=='none';},fixPosition:function(element,update){var parentNode=element.getOffsetParent(),pos;if(['absolute','relative'].include(parentNode.getStyle('position'))){pos=element.positionedOffset();}else{pos=element.cumulativeOffset();}
pos.top+=element.getHeight();update.setStyle({position:'absolute',left:pos.left+'px',top:pos.top+'px'});},onShow:function(element,update){var lists=update.select('ul li');if(lists.size()==1){if($F(element).toLowerCase()==lists.first().innerHTML.toLowerCase()){return;}}
Gays.AC.fixPosition(element,update);if(Gays.AC.locationNotFound){Gays.AC.locationNotFoundVisible=Gays.AC.locationNotFound.visible();Gays.AC.locationNotFound.hide();}
Effect.Appear(update,{duration:0.15});},onHide:function(element,update){if((element.readAttribute('isForcus')!=0)&&update.select('ul li').size()){return;}
if(Gays.AC.locationNotFound&&Gays.AC.locationNotFoundVisible){Gays.AC.locationNotFound.show();}
new Effect.Fade(update,{duration:0.15});element.value+=' ';element.value=element.value.strip();$(update).hide();},keyDown:function(element,update,tip,loading,noMatchData,event){var keyCode=(event||window.event).keyCode;if(keyCode==Event.KEY_TAB||keyCode==Event.KEY_RETURN||(Prototype.Browser.WebKit>0&&keyCode==0)){$(element).writeAttribute('isForcus',0);return;}
var self=this;if(!self.elementForm){setTimeout(function(){if(!self.elementForm){var elementForm=$($(element).parentNode);while(elementForm.tagName!='FORM')
elementForm=elementForm.parentNode;if(elementForm){self.elementForm=elementForm;Event.observe(elementForm,'submit',function(){self.elementForm=null;self.hasFocusEvent=false;if($(noMatchData))self.locationNotFound.remove();});}}},100);}
setTimeout(function(){if($F(element).blank()){$(update).hide();$(tip).show();}else{$(tip).hide();}
$(loading,tip,noMatchData).each(function(it){if(!it)return;if(it.readAttribute('position')=='reset'){self.createEl(element,it.id,it.readAttribute('right'),it.innerHTML);}});},500);if(!$(noMatchData)){return;}
setTimeout(function(){if(!$(noMatchData))return;$(noMatchData).hide();if($F(element).blank()){$(noMatchData).hide();}else{self.noMatchData=$(noMatchData);setTimeout(function(){self.keyDownEvent($(element),$(update),$(tip),$(loading),$(noMatchData))},2000);}},500);},keyDownEvent:function(element,update,tip,loading,noMatchData){if(!$(noMatchData))return;if(loading.visible()){return;}
var offset=element.cumulativeOffset(),ul=update.down('ul');if(ul&&ul.childElements().size()>0){noMatchData.hide();}else{update.hide();noMatchData.setStyle({top:(offset.top+element.getHeight())+'px',left:offset.left+'px'}).show();}},createNoMatchData:function(element,noMatchData,right,content){this.locationNotFound=this.createEl(element,noMatchData,false,content).removeClassName('auto_complete').addClassName('locationNotFound');},createTip:function(element,tip,right,content,contentLength){var el=this.createEl(element,tip,right,content||'<ul><li>Start typing</li></ul>');if(contentLength){el.setStyle({width:contentLength+'px'});}},createLoading:function(element,loading,right,content,contentLength){this.createEl(element,loading,right,content||'<ul><li><img src="/images/loading.gif" alt="loading" />Loading list of towns/cities</li></ul>').setStyle({width:(contentLength||198)+'px'});},createEl:function(element,obj,right,content){element=$(element);var offset=element.cumulativeOffset(),left=offset.left,top=offset.top-3;if(!this.hasFocusEvent){$(element.id+'_auto_complete').observe('scroll',function(){element.focus();setTimeout(function(){element.writeAttribute('isForcus',1)},50);}).observe('click',function(){element.onblur();});this.hasFocusEvent=false;}
if(!$(obj)){obj=new Element('div',{id:obj}).addClassName('auto_complete').update(content).hide();document.body.appendChild(obj);}
if(right){$(obj).addClassName('info').setStyle({position:'absolute',top:(top)+'px',left:(left+2+element.getWidth())+'px',height:'20px',width:'200px',overflow:'hidden'}).writeAttribute('right','y');}else{$(obj).setStyle({position:'absolute',top:(top+element.getHeight())+'px',left:left+'px',width:element.getWidth()+'px',height:'20px',overflow:'hidden'}).writeAttribute('right',null);}
return $(obj).writeAttribute('position',null);}};Gays.AutoComplete=(function(){var
isIE=!-[1,],_CONST={NOTIFY_CLASS:'auto_complete_notify'},stopRequest=function(instance){if(instance.xhr){instance.xhr.abort();instance.xhr=null;}},fixPosition=function(input,result){var pos,parent=input.getOffsetParent();if(['absolute','relative'].include(parent.getStyle('position'))){pos=input.positionedOffset();}else{pos=input.cumulativeOffset();}
pos.top+=input.getHeight();Element.setStyle(result,{left:(pos.left||0)+'px',top:(pos.top||0)+'px'});result._posFixed=true;},hdlInput=function(event,instance){switch(event.keyCode){case Event.KEY_RETURN:case Event.KEY_TAB:case Event.KEY_LEFT:case Event.KEY_RIGHT:case Event.KEY_UP:case Event.KEY_DOWN:break;case Event.KEY_ESC:instance.reset();break;default:stopRequest(instance);instance.hideResult();if(/\S/.test(this.value))instance.notifyTyping();}},AutoComplete=function(options){var self=this;this._options=options;this.uiInput=$(options.input);this.uiResult=$(options.result);this.tip=options.tip||'';if(options.notify){this._uiNotify=$(options.notify);}
isIE&&this._regHandler();var instance=this.instance=new Ajax.Autocompleter(this.uiInput,this.uiResult,options.url,{method:options.method||'get',minChars:options.minChars,callback:options.params,afterUpdateElement:options.select,onCreate:function(ajax){self.xhr=ajax.transport;self.notifyLoading();},onShow:function(input,result){result._posFixed||fixPosition(input,result);if(typeof options.show=='function'){var items=result.getElementsByTagName('li');options.show.call(self,input,result,items);}else{Effect.Appear(result,{duration:0.15});}},onHide:function(input,result){if(typeof options.hide=='function'){options.hide.call(self,input,result);}else{self.hideResult();}}});isIE||this._regHandler();instance.options.onComplete=function(request){if(request.responseText)instance.updateChoices(request.responseText);else instance.stopIndicator();}
instance.startIndicator=function(){};instance.stopIndicator=function(){self.notifyLoading(true);};instance.render=function(){if(this.entryCount>0){for(var i=0;i<this.entryCount;i++)
this.index==i?Element.addClassName(this.getEntry(i),'selected'):Element.removeClassName(this.getEntry(i),'selected');if(this.hasFocus){this.show();this.active=true;}}else{this.active=false;this.hide();self.notifyNoData();}};};AutoComplete.constructor=AutoComplete;AutoComplete.prototype={_regHandler:function(){var self=this;this.uiInput.onkeydown=function(event){hdlInput.call(this,event||window.event,self);};this.uiInput.onfocus=function(){if(this.value==self.tip)this.value='';self.notifyTyping();};Event.observe(this.uiInput,'blur',function(){stopRequest(self);if(self.instance.observer){clearTimeout(self.instance.observer);self.instance.observer=null;}
if(!/\S/.test(this.value))this.value=self.tip;self._notify();});},_notify:function(type){var uiNotify=this._uiNotify;if(!uiNotify)return;if(isIE){this._uiNotify=uiNotify.cloneNode(true);this._uiNotify.className=type?_CONST.NOTIFY_CLASS+' '+type:_CONST.NOTIFY_CLASS;uiNotify.parentNode.replaceChild(this._uiNotify,uiNotify);}else{uiNotify.className=type?_CONST.NOTIFY_CLASS+' '+type:_CONST.NOTIFY_CLASS;}},notifyTyping:function(stop){this._notify(stop?'':'typing');},notifyLoading:function(stop){this._notify(stop?'':'loading');},notifyNoData:function(stop){this._notify(stop?'':'no_match');},reset:function(){this.uiInput.value='';Element.hide(this.uiResult);Gays.Util.call(this._options.reset,this);},hideResult:function(){this.uiResult.style.display='none';}};return AutoComplete;})();Gays.LightBox={show:function(id,left,top){var box=$(id).cloneNode(true);$(id).remove();document.body.appendChild(box);if(Object.isUndefined(left)||Object.isUndefined(top)){var boxDim=box.getDimensions(),docDim=document.viewport.getDimensions(),docScrollOffsets=document.viewport.getScrollOffsets(),left=(docDim.width-boxDim.width)/2+docScrollOffsets.left,top=(docDim.height-boxDim.height)/2+docScrollOffsets.top;}
box.setStyle({position:'absolute',left:(left-10)+'px',top:top+'px',zIndex:999,display:'block'});},hide:function(id){$(id).setStyle({display:'none'});}};Gays.Invite={liPath:"#HolderInvitedPeople li",act:'selected',actIcon:'<span><!-- --></span>',skipedIds:[],init:function(liPath,act,actIcon){!Object.isUndefined(liPath)&&(this.liPath=liPath);!Object.isUndefined(act)&&(this.act=act);!Object.isUndefined(actIcon)&&(this.actIcon=actIcon);var self=this;$$(this.liPath).each(function(it){it.observe('click',function(){this.hasClassName(self.act)?self.deactive(this):self.active(this);});});},invite:function(url,opts){var userIds=[],self=this;$$(this.liPath+'.'+this.act).each(function(it){userIds.push(it.readAttribute('uid'));});var nUserIds=userIds.size();if(!nUserIds){return;}
if(opts.container==null){var form=new Element('form',{action:url,method:'post'});form.insert('<input type="hidden" name="user_ids" value="'+userIds.join(' ')+'" />'+'<input type="hidden" name="object_id" value="'+opts.object_id+'" />');$(document.body).insert(form);form.submit();return;}
new Ajax.Request(url,{method:'post',parameters:{user_ids:userIds.join(' '),object_id:opts.object_id},onSuccess:function(){$(opts.container).update('<div class="noticeSuccess"><p>You successfully invited '+nUserIds+' friend'+(nUserIds>1?'s':'')+' to '+opts.object_name.escapeHTML()+' </p></div>');myLightWindow.resizeTo.height=150;myLightWindow._processWindow();Gays.Util.closeLW(3);if(Object.isFunction(opts.callback)){opts.callback.apply();}},onFailure:function(){alert('Network connection problem, Please try it again, Thanks!');}});},canNotInvite:function(li){return this.skipedIds.include(li.readAttribute('uid'));},active:function(li){if(this.canNotInvite(li))return;li.addClassName(this.act).insert({top:this.actIcon});},deactive:function(li){if(this.canNotInvite(li)||!li.hasClassName(this.act))return;li.removeClassName(this.act).down('span').remove();},select:function(selectAll){var self=this;$$(this.liPath).each(function(it){selectAll?self.active(it):self.deactive(it);});}};Gays.SwfUpload={cancelledFiles:[],failedFiles:[],success:false,uploadFiles:0,uploadedFiles:0,fileDialogComplete:function(nSelectedFiles){try{if(nSelectedFiles<1)return;var files=[],self=this,stats=this.getStats(),fileObj=null,filesObj=[];allFiles=stats.files_queued+stats.upload_cancelled+stats.successful_uploads+self.customSettings.queueErrors.keys().size();allFiles.times(function(index){fileObj=self.getFile(index);if(fileObj){if(Gays.SwfUpload.cancelledFiles.include(fileObj.id)||Gays.SwfUpload.failedFiles.include(fileObj.id)){self.cancelUpload(fileObj.id);return;}
var isExists=false;filesObj.each(function(it){if(it.name==fileObj.name&&it.size==fileObj.size&&it.filestatus==fileObj.filestatus){isExists=true;throw $break;}});if(isExists){self.cancelUpload(fileObj.id);}else{filesObj.push(fileObj);}}});self.customSettings.totalBytes=0;var photoNo=0,canUpload=false;filesObj.each(function(fileObj){photoNo++;if(self.customSettings.queueErrors.get(fileObj.id)){Gays.SwfUpload.cancelledFiles.push(fileObj.id);}else{canUpload=true;self.customSettings.totalBytes+=fileObj.size;}
var data={photoNo:photoNo,fileId:self.customSettings.fileIdPrefix+fileObj.id,fileName:fileObj.name,fileStatusId:self.customSettings.statusPrefix+fileObj.id,fileStatusMessage:self.customSettings.queueErrors.get(fileObj.id)||self.customSettings.text.wait,fileObjId:fileObj.id,fileCancelId:self.customSettings.cancelPrefix+fileObj.id,fileCancelText:self.customSettings.text.cancel};var t=new Template(self.customSettings.template);files.push(t.evaluate(data));});Gays.SwfUpload.uploadFiles=files.size();$(this.customSettings.filesId).update(files.join("\n")+this.customSettings.uploadButton);if(canUpload){$(self.customSettings.uploadId).show();}}catch(ex){}},fileQueueError:function(fileObj,errorCode,message){this.cancelUpload(fileObj.id);this.customSettings.queueErrors.set(fileObj.id,message);$(this.customSettings.progressId).show().update(this.customSettings.text.fileError.gsub('{file}',fileObj.name));},uploadStart:function(fileObj){$(this.customSettings.cancelPrefix+fileObj.id).hide();this.addFileParam(fileObj.id,this.customSettings.albumId,$F(this.customSettings.albumId));return true;},uploadProgress:function(fileObj,bytesLoaded,totalBytes){},uploadError:function(fileObj,errorCode,message){if($(this.customSettings.statusPrefix+fileObj.id)){$(this.customSettings.statusPrefix+fileObj.id).update(Gays.SwfUpload.getUploadError(errorCode,message));}},uploadSuccess:function(fileObj,serverData){if(/^[0-9]+$/.test(serverData)){$(this.customSettings.statusPrefix+fileObj.id).update(this.customSettings.text.uploadComplete);$(this.customSettings.cancelPrefix+fileObj.id).hide();Gays.SwfUpload.uploadedFiles++;var percent=Gays.SwfUpload.uploadedFiles*1.0/Gays.SwfUpload.uploadFiles*100;var progressImage="<div style=\"margin-top:3px;width:"+(percent*4.3)+"px;background:#2F5F00;padding:2px;color:white;font-weight:bold;text-align:center;\">"+Gays.SwfUpload.uploadedFiles+" / "+Gays.SwfUpload.uploadFiles+"</div>";$(this.customSettings.progressId).show().update(this.customSettings.text.uploadStart+progressImage);Gays.SwfUpload.success=true;}else{Gays.SwfUpload.failedFiles.push(fileObj.id);$(this.customSettings.statusPrefix+fileObj.id).update("<span style=\"background:#b50000; color:white\">"+serverData+"</span>");$(this.customSettings.cancelPrefix+fileObj.id).show();}
if(!this.getStats().files_queued){if(Gays.SwfUpload.success){var self=this;setTimeout(function(){location.href=self.customSettings.redirectUrl},500);}else{$(this.customSettings.progressId).update(this.customSettings.text.uploadError);$(swfu.customSettings.uploadId).hide();}}},uploadComplete:function(fileObj){try{this.startUpload();}catch(ex){}},cancelUploadFile:function(fileId){try{$(swfu.customSettings.fileIdPrefix+fileId).hide();var fileObj=swfu.getFile(fileId);if(fileObj){this.cancelledFiles.push(fileObj.id);swfu.customSettings.totalBytes-=fileObj.size;}
swfu.cancelUpload(fileId);Gays.SwfUpload.uploadFiles--;Gays.SwfUpload.uploadedFiles--;var canUpload=false,hasErrors=false;$(swfu.customSettings.filesId).childElements().each(function(it){if(it.getStyle('display')!='none'&&!it.innerHTML.include(swfu.customSettings.uploadId)){if(self.customSettings.queueErrors.get(fileId)){hasErrors=true;}else{canUpload=true;throw $break;}}});if(canUpload){$(swfu.customSettings.uploadId).show();}else{$(swfu.customSettings.uploadId).hide();}
if(!hasErrors){$(swfu.customSettings.progressId).hide();}}catch(ex){}},getUploadError:function(errorCode,message){Gays.SwfUpload.uploadedFiles++;if(Gays.SwfUpload.uploadedFiles>=Gays.SwfUpload.uploadFiles){if(Gays.SwfUpload.success){var self=this;setTimeout(function(){location.href=self.customSettings.redirectUrl},500);}else{$(this.customSettings.progressId).update(this.customSettings.text.uploadError);$(swfu.customSettings.uploadId).hide();}}
switch(errorCode){case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:return"Upload Error: "+errorCode+",  "+message;break;case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:return"Configuration Error: "+errorCode;break;case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:return"Upload Failed: "+errorCode;break;case SWFUpload.UPLOAD_ERROR.IO_ERROR:return"Server (IO) Error: "+errorCode;break;case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:return"Security Error: "+errorCode;break;case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:return"Upload limit exceeded: "+errorCode;break;case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND:return"File not found.";break;case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:return"Failed Validation.  Upload skipped";break;case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:return"Cancelled";break;case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:return"Stopped";break;default:return'Unhandled Error: '+errorCode;}}};Gays.Location={init:function(opts){opts=this.opts=Object.extend({field:'current_location_id',defaultCountryId:null,defaultCity:null,defaultCityId:null,defaultRegion:null,loadRegionsUrl:null,loadCountriesUrl:null,searchCityUrl:null,usId:840,error:$('error_for_current_location_id'),errorMessage:null},opts||{});this.country=$('locationCountry');this.region=$('locationRegion');this.city=$('locationCity');this.locationCities=$('locationCities');this.searchButton=$('locationSearch');this.hasPreSelectedCountry=$('hasPreSelectedCountry')&&$F('hasPreSelectedCountry');if(this.opts.error&&this.opts.errorMessage){var self=this;$g(function(){self.opts.error.update("<p>"+opts.errorMessage+"</p>");});}
if(!(this.country&&this.region&&this.city&&this.locationCities&&this.searchButton)){if($('locationCountries')&&$('locationRegions')&&$('locationCities_')){this.init2();}
if($('currentLocationCountrycurrent_location')&&this.hasPreSelectedCountry){$('currentLocationCountrycurrent_location').childElements().each(function(country){if(country.value==opts.defaultCountryId){country.selected=true;_changeCountry();throw $break;}});}
return;}
$(opts.field).setValue(opts.defaultCityId);this.city.setValue(opts.usId==$F(this.country)||opts.defaultCity==opts.defaultRegion?opts.defaultCity:opts.defaultCity+', '+opts.defaultRegion)
this.city.disabled=true;this.loadCountries().initObservers();},init2:function(){var country=$('locationCountries'),region=$('locationRegions'),city=$('locationCities_'),currentLocation=$(this.opts.field),self=this,loadRegions=function(){currentLocation.setValue('');var countryId=$F(country),defaultRegion=self.opts.defaultRegion;region.update();city.update();if(!countryId)return;new Ajax.Request(self.opts.loadRegionsUrl,{method:'get',parameters:{country_id:countryId},onSuccess:function(res){var regionElems=[];res.responseText.evalJSON().each(function(reg){regionElems.push('<option value="'+reg+'" title="'+reg+'">'+reg+'</option>');});region.update(regionElems.join(''));if(!region.empty()){if(!defaultRegion){region.childElements()[0].selected=true;}else{region.childElements().each(function(it){if(it.value==defaultRegion){it.selected=true;throw $break;}});}}
loadCities();}});},loadCities=function(){currentLocation.setValue('');city.update();var defaultCityId=self.opts.defaultCityId;new Ajax.Request(self.opts.searchCityUrl,{method:'get',parameters:{country_id:$F(country),region:$F(region),city:'all'},onSuccess:function(res){var cities=res.responseText.evalJSON(),cityElems=[];cities.sortBy(function(it){return it.city_name;}).each(function(ct){cityElems.push('<option value="'+ct.city_id+'" title="'+ct.city_name+'">'+ct.city_name+'</option>');});city.update(cityElems.join(''));if(!defaultCityId){city.childElements()[0].selected=true;}else{city.childElements().each(function(it){if(it.value==defaultCityId){it.selected=true;throw $break;}});}
updateCityId();}});},updateCityId=function(){currentLocation.setValue($F(city));};country.observe('change',loadRegions);region.observe('change',loadCities);city.observe('change',updateCityId);new Ajax.Request(self.opts.loadCountriesUrl,{method:'get',onSuccess:function(res){var defaultCountryId=self.opts.defaultCountryId,countryElems=['<option value="">Select country</option>'];res.responseText.evalJSON().each(function(it){if(it.id!='0'){countryElems.push('<option value="'+it.id+'" title="'+it.name+'">'+it.name+'</option>');}});country.update(countryElems.join(''));if(defaultCountryId){country.childElements().each(function(it){if(it.value==defaultCountryId){it.selected=true;throw $break;}});}else{country.childElements()[0].selected=true;}
loadRegions();}});},initObservers:function(){var self=this;this.city.onkeydown=function(e){if((e||window.event).keyCode==Event.KEY_RETURN){self.searchCity();return false;}
setTimeout(function(){self.updateSearchButton()},400);}
this.country.observe('change',function(){var countryId=$F(this);self.updateSearchButton();$(self.opts.field).setValue('');$(self.city).setValue('');self.opts.error.hide();self.locationCities.hide();self.showRegions();});this.region.observe('change',function(){self.updateSearchButton();});Event.observe(this.searchButton,'click',function(){self.searchCity()});return this;},updateSearchButton:function(){var noCountry=['','0'].include($F(this.country));this.city.disabled=($F(this.country)==this.opts.usId)?!$F(this.region):noCountry;if(noCountry||$F(this.city).strip()==''){this.searchButton.removeClassName('button').addClassName('buttonAlt').disabled=true;}else{this.searchButton.removeClassName('buttonAlt').addClassName('button').disabled=false;}},showRegions:function(){var regionNode=this.region,countryId=$F(this.country);if(countryId!=this.opts.usId){regionNode.hide();return;}
if(regionNode.childElements().size()){regionNode.show();return;}
var defaultRegion=this.opts.defaultRegion;regionNode.insert('<option value="">Select region</option>');new Ajax.Request(this.opts.loadRegionsUrl,{method:'get',parameters:{country_id:countryId},onSuccess:function(res){res.responseText.evalJSON().each(function(region){regionNode.insert('<option value="'+region+'">'+region+'</option>');});if(!defaultRegion){regionNode.show().childElements()[0].selected=true;}else{regionNode.show().childElements().each(function(it){if(it.value==defaultRegion){it.selected=true;throw $break;}});}}});},loadCountries:function(){var self=this;self.country.insert('<option value="">Select country</option>');new Ajax.Request(self.opts.loadCountriesUrl,{method:'get',onSuccess:function(res){var defaultCountryId=self.opts.defaultCountryId;res.responseText.evalJSON().each(function(it){self.country.insert('<option value="'+it.id+'">'+it.name+'</option>');});if(defaultCountryId){self.country.childElements().each(function(it){if(it.value==defaultCountryId){it.selected=true;throw $break;}});}else{self.country.childElements()[0].selected=true;}
self.updateSearchButton();self.showRegions();}});return this;},searchCity:function(){var self=this,countryId=$F(this.country),region=$F(self.region),city=$F(self.city).gsub(/,.+$/,'').strip();if(!countryId||!city)return;new Ajax.Request(self.opts.searchCityUrl,{method:'get',parameters:{country_id:countryId,region:region,city:city},onSuccess:function(res){var cities=res.responseText;if(!cities){self.opts.error.update('<p>There is no matched city can be found</p>').show();self.locationCities.hide();return;}
self.opts.error.hide();self.locationCities.show();cities=cities.evalJSON();var firstCity=cities.shift(),defaultCityId=self.opts.defaultCityId,field=self.opts.field,cityInfo=firstCity.city_name+', '+firstCity.city_region;$('locationCitiesFirst').update('<input type="radio" id="'+field+'_first" name="'+field+'_" onclick="Gays.Location.selectCity('+firstCity.city_id+', \''+self.h(cityInfo)+'\')" '+
(defaultCityId==firstCity.city_id?' checked="checked"':'')+' /> '+'<label for="'+field+'_first">'+cityInfo+'</label>');var hasCity=cities.size();if(hasCity){otherCities=$('locationCitiesOthers').update();cities.each(function(city,index){cityInfo=city.city_name+", "+city.city_region;var id=field+'_'+index;otherCities.insert('<li><input type="radio" id="'+id+'" name="'+field+'_"  onclick="Gays.Location.selectCity('+city.city_id+', \''+self.h(cityInfo)+'\')" '+
(defaultCityId==city.city_id?' checked="checked"':'')+' /> '+'<label for="'+id+'">'+cityInfo+'</label>'+'</li>');});}
$$('#locationCitiesOr, #locationCitiesOthers').invoke(hasCity?'show':'hide');}});},selectCity:function(cityId,cityInfo){$(this.opts.field).setValue(cityId);if(this.opts.usId==$F(this.country)){cityInfo=cityInfo.split(',')
cityInfo.pop();cityInfo=cityInfo.join(',');}
this.city.setValue(cityInfo);},h:function(s){return s.gsub("'","\\'").gsub('"','\\"');}};
/*
 * History plugin
 * @author Shen Junru
 * @date 2010-02
 */
(function(NS){var _data={disable:true,curHash:window.location.hash,history:{},keyCount:0,keyCheck:/[^\w\d]/,pattern:/^(?:#?([\w\d]+)|#\$([\w\d]+)\$)\/(.+)$/,watcher:null},log=function(error){_data.log&&_data.log(error);},iframe=(function(){if(document.documentElement.addBehavior&&(!document.documentMode||document.documentMode<8)){var iframe=document.createElement('iframe');iframe.id='ajax_history';iframe.style.display='none';return iframe;}
return null;})(),iframeOptions={url:'/history_maker.html',domain:'',random:1},updateIframe=function(hash){iframeOptions.random^=1;iframe.src=iframeOptions.url+'?domain='+iframeOptions.domain+'&r='+iframeOptions.random+(hash||'');},iframeDocument=function(){return iframe?iframe.contentDocument||iframe.contentWindow.document:null;},serialize=function(object,separator){var result=[],key,val;for(key in object){val=object[key];if(val!=null)result.push(encodeURIComponent(key)+'='+
encodeURIComponent(object[key].toString()));}
return result.join(separator);},unserialize=function(value,separator){var result={},params=value.split(separator);for(var i=0;i<params.length;i++){var tmp=params[i].split('=');if(tmp.length==2){result[decodeURIComponent(tmp[0])]=decodeURIComponent(tmp[1]);}}
return params.length?result:null;},storeHash=function(key,value){return _data.history[key].hash=key+'/'+value;},generateHash=function(hKey,params){if(_data.keyCount>1){var hash=[];for(var key in _data.history){var value=serialize(hKey==key?params:_data.history[key].data(),'&');if(value){hash.push(storeHash(key,value));}}
hash=hash.join('|');return hash?'#'+'$'+hKey+'$/'+hash:'';}else{var hash=serialize(params,'&');return hash?'#'+storeHash(hKey,hash):'';}},parseHash=function(hash,keep){var data,concert=false,match=_data.pattern.exec(hash);if(match){data=match[3];if(match[1]){data=keep?data:unserialize(data,'&');}else{var temp,part,parts=data.split('|');concert=true,data={};while(temp=parts.shift()){part=arguments.callee(temp,true);if(part&&part.key in _data.history){data[part.key]={data:unserialize(part.data,'&'),modify:_data.history[part.key].hash!=temp};_data.history[part.key].hash=temp;}}}
return{concert:concert,data:data,key:match[1]||match[2]};}
return null;},callHandler=function(hash,load){try{if(hash){hash=parseHash(hash);if(hash.concert){_data.concert&&_data.concert(hash.key,hash.data);}else if(hash.key in _data.history){_data.history[hash.key].hdl(hash.data);}}else if(!load){if(_data.keyCount>1){_data.concert&&_data.concert();}else{for(var key in _data.history){_data.history[key].hdl();}}}}catch(error){log(error);}},currentHash=function(){return iframe?iframeDocument().location.hash:window.location.hash;},watchHistory=function(){var hash=currentHash();if(_data.curHash==hash)return;if(iframe)window.location.hash=hash;_data.curHash=hash;callHandler(hash);},startWatcher=function(){if(!_data.watcher)_data.watcher=window.setInterval(watchHistory,100);if(iframe&&iframeOptions.domain)iframe.detachEvent('onload',startWatcher);},addHistory=(function(){var changeHash=iframe?function(hash){var idoc=iframeDocument();if(hash.length>3&&_data.curHash!=hash){idoc.open();idoc.close();window.location.hash=idoc.location.hash=hash;_data.curHash=window.location.hash;}}:function(hash){if(hash.length>3&&_data.curHash!=hash){window.location.hash=hash;_data.curHash=window.location.hash;}};return function(hKey,params){var hash=generateHash(hKey,params);changeHash(hash);};})(),History=function(options){if(typeof(options.key)==='string'&&typeof(options.handler)==='function'){if(_data.keyCheck.test(options.key)){throw new Error('Invalid key of ajax history handler!');}
if(options.key in _data.history){throw new Error('Existing key of ajax history handler!');}
this.key=options.key;this.handler=options.handler;this.params=options.params||{};this.getData=options.getData;_data.history[options.key]={hdl:options.handler,data:options.getData,hash:''};_data.keyCount++;}
return null;};History.constructor=History;History.prototype={make:function(params){if(!(this.key in _data.history))return;try{var key,temp={},data={};for(key in this.params)temp[key]=data[key]=this.params[key];if(params)for(key in params)temp[key]=data[key]=params[key];if(_data.keyCount>1&&_data.concert){_data.concert(this.key,temp,true);}else{this.handler(temp,true);}
addHistory(this.key,data);}catch(error){log(error);}},unregister:function(){if(this.key in _data.history){delete _data.history[this.key];_data.keyCount--;}}};NS.history=function(options){try{var history=new History(options);_data.disable=false;return history;}catch(error){log(error);return null;}};NS.history.init=function(options){if(_data.inited)return;_data.inited=true;if(!options)return;if(iframe&&'domain'in options){iframeOptions.domain=options.domain;if('ifmUrl'in options){iframeOptions.url=options.ifmUrl;}
addHistory=function(hKey,params){var hash=generateHash(hKey,params);if(hash.length>3&&_data.curHash!=hash){window.location.hash=hash;_data.curHash=window.location.hash;updateIframe(hash);}};}};NS.history.log=function(object){if(typeof object==='function')_data.log=object;};NS.history.check=function(object){return object instanceof History;};NS.history.concert=function(handler){if(typeof(handler)==='function'){_data.concert=handler;}};NS.history.getHandler=function(key){return key&&key in _data.history?_data.history[key].hdl:function(){};};$G(function(){if(_data.disable)return;callHandler.delay(2,window.location.hash,true);var initOptions=null;if(document.domain!=window.location.hostname){initOptions={domain:document.domain};}
NS.history.init(initOptions);if('onhashchange'in window){window.onhashchange=function(){if(window.location.hash!=_data.curHash){callHandler(_data.curHash=window.location.hash);}};}else if(iframe){document.body.appendChild(iframe);if(iframeOptions.domain){iframe.attachEvent('onload',startWatcher);updateIframe(window.location.hash);}}else{startWatcher();}});})(Gays);Ajax.Responders.register({onComplete:function(request,transport){var c=transport.responseText;if(!(c.include('id="startpage-splash">')&&c.include('id="signupFormHolder">')))return;var url=window.location.href;if(!url.include('/frontend')){window.location.href='/';}else{if(url.include('frontend_dev.php')){window.location.href='/frontend_dev.php';}else if(url.include('frontend_testing')){window.location.href='/frontend_testing.php';}}}});(function(){$G(function(){window.bindBubble=function(wrap){var bubbleTriggers=$$((wrap||'')+' a.hint');if(bubbleTriggers.length){var bubble=new Gays.UI.Bubble();bubble.container(document.body);bubble.posPointer('20%',true);bubbleTriggers.each(function(item){var content=item.getAttribute('title');if(content){bubble.bind(item,{content:content,width:item.getAttribute('bubblewidth'),pointer:item.getAttribute('bubblepointer')});item.removeAttribute('title');item.removeAttribute('bubblewidth');item.removeAttribute('bubblepointer');}});}};window.bindBubble();Gays.history.init({domain:Gays.getDomain()});if(typeof $googleAnalytics!='undefined')Gays.Google.loadAnalytics($googleAnalytics);});Gays.Browse.detectBackButton();})();})();