//speeddate compiled js file. Compile time:2012-01-26 12-03\n
Function.prototype.forUser=function(){var _method=this,bindingArgs=Array.prototype.slice.call(arguments,0);return function(){var _this=this;var args=Array.prototype.slice.call(arguments,0);var uid=bindingArgs[0]||args[0];if(!uid)return;SD.User.fetch(SD.User.get(uid),function(user){if(uid===bindingArgs[0]){args.unshift(user);}else{args[0]=user;}
_method.apply(_this,args);},bindingArgs[1]);return this;}};Function.prototype.bindForUser=function(){var _method=this,bindingArgs=Array.prototype.slice.call(arguments,0),context=bindingArgs.shift(),uid=bindingArgs.shift();return function(){var args=bindingArgs.concat(Array.prototype.slice.call(arguments,0));if(!uid)return;SD.User.fetch(SD.User.get(uid),function(user){args.unshift(user);_method.apply(context,args);});return this;}};Function.prototype.interpolate=function(){var str=new String(this());return str.interpolate.apply(str,arguments);};if(!Array.prototype.every){Array.prototype.every=Array.prototype.all;}
if(!Array.prototype.forEach){Array.prototype.forEach=Array.prototype.each;}
Enumerable.every=Enumerable.all;Enumerable.forEach=Enumerable.each;String.prototype.ucfirst=function(){return this.substr(0,1).toUpperCase()+this.substr(1);};String.prototype.excerpt=function(nLen){return this.truncate(nLen-1,'\u2026');};if(!String.prototype.trim){String.prototype.trim=String.prototype.strip;}
String.prototype.substitute=function(obj){var prefix="#{",suffix="}",str=this;for(var i in obj){str=str.replace(prefix+i+suffix,obj[i]);}
return str;};String.prototype.toXML=function(){if(window.DOMParser){var parser=new DOMParser();var parsed=parser.parseFromString(this,"text/xml");return parsed.firstChild||parsed;}else{var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");xmlDoc.async="false";xmlDoc.loadXML(this);return xmlDoc.firstChild||xmlDoc;}}
String.prototype.toXMLDoc=function(){if(window.DOMParser){var parser=new DOMParser();var parsed=parser.parseFromString("<root>"+this+"</root>","text/xml");return parsed.firstChild||parsed;}else{var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");xmlDoc.async="false";xmlDoc.loadXML("<root>"+this+"</root>");return xmlDoc.firstChild||xmlDoc;}}
Prototype.Browser.IE6=Prototype.Browser.IE&&parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5))==6;Prototype.Browser.IE7=Prototype.Browser.IE&&parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5))==7;Prototype.Browser.IE8=Prototype.Browser.IE&&!Prototype.Browser.IE6&&!Prototype.Browser.IE7;Prototype.Browser.isSlow=Prototype.Browser.IE6;Prototype.Browser.FF3=(/Firefox\/3.0/).test(navigator.userAgent);Prototype.Browser.getName=function(){if(Prototype.Browser.Gecko)return"firefox";if(Prototype.Browser.IE6)return"ie6";if(Prototype.Browser.IE7)return"ie7";if(Prototype.Browser.IE8)return"ie8";if(Prototype.Browser.Webkit)return"webkit";if(Prototype.Browser.Opera)return"webkit";if(Prototype.Browser.MobileSafari)return"mobile-webkit";};Date.now=function(){return(new Date()).getTime();}
Element.GCScheduler={cache:Prototype.getElementCache(),timer:null,batch:50,batchDelay:10,elements:[],eventsToClear:['onclick','onmouseover','onmouseout','onfocus','onblur','onkeydown','onkeypress','onmouseenter','onmouseleave','onsubmit'],scheduleToClear:function(elements){if(!elements)return;if(!Object.isArray(elements)){elements=[elements];}
this.elements.push.apply(this.elements,elements);if(!this.timer){this.timer=window.setInterval(Element.GCScheduler._gc,this.batchDelay);}},_gc:function(){var i,limit=Element.GCScheduler.batch,elements=Element.GCScheduler.elements,len=elements.length,_this=Element.GCScheduler;for(i=0;i<len&&limit;i++,limit--){_this.purge(elements[i]);elements[i]=null;}
if(limit!==0||i===len){_this.elements=[];window.clearInterval(_this.timer);_this.timer=null;}else{_this.elements.splice(0,_this.batch);}},purge:function(element){if(!element)return;if(element._prototypeUID&&this.cache[element._prototypeUID[0]]){element.stopObserving();this.cache[element._prototypeUID[0]]=null;delete this.cache[element._prototypeUID[0]];}
if(element.nodeName&&element.nodeName.toUpperCase()=='IMG'){element.src='about:blank';}
var ev;for(var i=0,len=this.eventsToClear.length;i<len;i++){try{ev=this.eventsToClear[i];element[ev]&&(element[ev]=null);}catch(e){return;}}}};Element.addMethods({update:Element.update.wrap(function(proceed,element,content){var descendants=element.descendants();if(descendants.length>0){Element.GCScheduler.scheduleToClear(descendants);}
return proceed(element,content);}),replace:Element.replace.wrap(function(proceed,element,content){Element.GCScheduler.scheduleToClear(element);return proceed(element,content);}),observeOnce:function(element,eventName,handler){var h;$(element).observe(element,eventName,h=function(e){handler(e);element.stopObserving(element,eventName,h);});return element;},getAbsoluteOffsets:function(element,relativeToPage){element=$(element);var offset=element.cumulativeOffset();var scrolls={top:0,left:0};element.ancestors().each(function(el){scrolls.top+=el.scrollTop;scrolls.left+=el.scrollLeft;if(el.getStyle('position')=='fixed'){throw $break;}});offset.left-=scrolls.left;offset.top-=scrolls.top;if(relativeToPage){var viewportOffsets=document.viewport.getScrollOffsets();offset.left+=viewportOffsets.left;offset.top+=viewportOffsets.top;}
offset[0]=offset.left;offset[1]=offset.top;return offset;},getTrueZ:function(element,refElement){refElement=refElement||document.body;return parseInt(element.ancestors().inject(0,function(acc,el){if(el==refElement)throw $break;return el.getStyle('z-index')||acc;}),10);},getTrueVisibility:function(element){return element.isInDOMTree()&&!element.ancestors().some(function(el){return el.getStyle('visibility')=='hidden'||el.getStyle('display')=='none';});},getTruePositioning:function(element){element=$(element);var hasAbsoluteParent=false;var hasRelativeParent=false;var hasFixedParent=false;if(element.getStyle('position')=='fixed'){return'fixed';}
element.ancestors().each(function(a){var pos=a.getStyle('position');hasFixedParent=hasFixedParent||pos=='fixed';hasAbsoluteParent=hasAbsoluteParent||pos=='absolute';hasRelativeParent=hasRelativeParent||pos=='relative';});if(hasFixedParent){return'fixed';}else if(hasAbsoluteParent){return'absolute';}else if(hasRelativeParent){return'relative';}else{return'static';}},setWidth:function(element,w){var borderRightWidth=parseInt(element.getStyle("border-right-width")||0)||0;var borderLeftWidth=parseInt(element.getStyle("border-left-width")||0)||0;var paddingRight=parseInt(element.getStyle("padding-right")||0)||0;var paddingLeft=parseInt(element.getStyle("padding-left")||0)||0;element.setStyle({'width':(w-borderRightWidth-borderLeftWidth-paddingRight-paddingLeft)+'px'});return element;},setHeight:function(element,h){var borderTopWidth=parseInt(element.getStyle("border-top-width")||0)||0;var borderBottomWidth=parseInt(element.getStyle("border-bottom-width")||0)||0;var paddingTop=parseInt(element.getStyle("padding-top")||0)||0;var paddingBottom=parseInt(element.getStyle("padding-bottom")||0)||0;element.setStyle({'height':(h-borderTopWidth-borderBottomWidth-paddingTop-paddingBottom)+'px'});return element;},isInDOMTree:function(element){return[element.ownerDocument.documentElement,element.ownerDocument,element.ownerDocument.body].include(element.ancestors().last());}});Ajax.advancedUpdater=function(options){var element=$(options.element);var url=options.url;var frequency=options.frequency;var method=options.method||'post';var maxFrequency=options.maxFrequency||Infinity;var maxRequests=options.maxRequests||Infinity;var decay=options.decay||1;var counter=0;var timer;var makeRequest=function(){return new Ajax.Request(url,{method:method,onSuccess:function(transport){try{element.update(transport.responseText);}catch(e){}}});};var updateFrequency=function(){frequency=frequency*decay;if(frequency>maxFrequency){frequency=maxFrequency;}
return frequency;}
var callFunction=function(){counter++;if(counter>maxRequests){clearTimeout(timer);return;}
updateFrequency();makeRequest();timer=setTimeout(callFunction,frequency*1000);}
callFunction();return{getTimer:function(){return timer;},getCount:function(){return count;},getDecay:function(){return decay;}}};document.scrollToTopAnimated=function(){new Effect.Tween(null,document.viewport.getScrollOffsets().top,0,{duration:0.5},function(p){scrollTo(0,p);});};
var SD=SD||{};SD.log=function(x){};SD.info=function(x){};SD.error=function(x){};SD.warn=function(x){};
SD.Error={_errorCount:0,_maxErrorCount:50,_onErrorDumpers:$H(),_getExpsValues:function(){var exps=[];$H(SD.ExperimentManager).each(function(elm){var expName=elm[0];var exp=elm[1];if(exp.hasOwnProperty('value')){exps.push("exp_"+exp.id+"="+exp.value);}});return exps;},_getDumps:function(){var dumps={};this._onErrorDumpers.each(function(pair){dumps[pair[0]]=pair[1]();});return dumps;},registerErrorDumper:function(dumperName,func){this._onErrorDumpers.set(""+dumperName,func);},onError:function(errorMsg,url,lineNumber){this._errorCount++;if(this._errorCount>this._maxErrorCount){return;}
if(!url&&!lineNumber&&errorMsg=='Script error.'){return;}
var exps=null;var browser=null;var dumps=null;var dumpExceptions={};try{exps=this._getExpsValues();}catch(e){dumpExceptions['exps']=e;}
try{browser=Prototype.Browser.getName();}catch(e){dumpExceptions['browser']=e;}
try{dumps=this._getDumps();}catch(e){dumpExceptions['dumps']=e;}
this.record({error:errorMsg,url:url,line_number:lineNumber,window_url:window.location.href,experiments:exps.join(" , "),browser:browser,dumps:Object.toJSON(dumps),dump_exceptions:Object.toJSON(dumpExceptions)});},record:function(params){new Ajax.Request(SD.NavUtils.link('ajax','log_js_error'),{method:'post',parameters:params});},logToServer:function(infoMessage,data){}}
SD=window.SD||{};Event=window.Event||{};SD.Event={init:function(){Event.observe&&Event.observe(window,'unload',function(){SD.Event.stopObserving(SD.Event);SD.Event.stopForwarding(SD.Event);SD.Event.__sd__delegates=null;});},__sd__eventStore:{},__sd__forwardedEventStore:{},observe:function(source,eventName,eventHandler){if(typeof eventName!='string')
throw"Invalid event name passed to SD.Event.observe";if(typeof eventHandler!='function')
throw"Invalid eventHandler passed to SD.Event.observe";if(typeof source!='object'||source==null){source=SD.Event;}
source.__sd__eventStore=source.__sd__eventStore||{};source.__sd__eventStore[eventName]=source.__sd__eventStore[eventName]||[];source.__sd__eventStore[eventName].push(eventHandler);return eventHandler;},observeOnce:function(source,eventName,eventHandler){eventHandler.__sd__oneTimeObserve=true;return SD.Event.observe(source,eventName,eventHandler);},stopObserving:function(source,eventName,eventHandler){if(typeof source!='object'||source==null){source=SD.Event;}
var eventStore=source.__sd__eventStore;if(!eventStore){return source;}
if(arguments.length<=1){source.__sd__eventStore={};SD.Event.stopForwarding(source||SD.Event);return source;}
var eventBucket=eventName&&source.__sd__eventStore&&source.__sd__eventStore[eventName];if(!eventBucket||eventBucket.length===0){return source;}
if(arguments.length==2){eventBucket.length=0;SD.Event.stopForwarding(source,eventName);return source;}
if(typeof eventHandler=='function'){for(var i=0,len=eventBucket.length;i<len;++i){if(eventBucket[i]===eventHandler){eventBucket.splice(i,1);return source;}}}
return source;},fire:function(source,eventName,memo,eventRunner){SD.log('Fired Event: '+eventName+' '+memo);var result=[];if(typeof eventName!='string'){var msg='Invalid event name passed to SD.Event.fire';SD.log(msg);throw msg;return result;}
if(typeof source!='object'||source==null){source=SD.Event;}
eventRunner=eventRunner||SD.Event.eventRunner;result=eventRunner(source,eventName,memo)||[];if(source!=SD.Event){result=result.concat(eventRunner(source,eventName,memo,SD.Event.__sd__eventStore));}
return result;},eventRunner:function(source,eventName,memo,eventStore){var result=[];if(typeof source!='object'||source==null){source=SD.Event;}
eventStore=eventStore||source.__sd__eventStore;if(eventStore&&eventStore[eventName]&&eventStore[eventName].length>0){var event={memo:memo,source:source,name:eventName};for(var i=0,eventBucket=eventStore[eventName];i<eventBucket.length;i++){try{result=result.concat(eventBucket[i].call(source,event));if(eventBucket[i]&&eventBucket[i].__sd__oneTimeObserve){eventBucket.splice(i,1);i--;}}catch(error){SD.log('Error firing event:'+eventName+' '+error.message);}}}
return result;},fireDeferred:function(source,eventName,memo,resultCallback){return setTimeout(function(){resultCallback?resultCallback(SD.Event.fire(source,eventName,memo)):SD.Event.fire(source,eventName,memo);},1);},forward:function(source,sourceEventName,targetEventName,eventNormalizer){if(arguments.length>2&&typeof source!='object'||source==null){source=SD.Event;}
if(arguments.length==2){targetEventName=sourceEventName;sourceEventName=source;source=SD.Event;}
if(typeof sourceEventName!='string'||typeof targetEventName!='string')
throw'Invalid event name passed to SD.Event.forward';if(!source.__sd__forwardedEventStore){source.__sd__forwardedEventStore={};}
var eventHandler=function(e){return SD.Event.fire(e.source,targetEventName,eventNormalizer?eventNormalizer(e.memo):e.memo);};if(!source.__sd__forwardedEventStore[sourceEventName]){source.__sd__forwardedEventStore[sourceEventName]={};}
source.__sd__forwardedEventStore[sourceEventName][targetEventName]=eventHandler;SD.Event.observe(source,sourceEventName,eventHandler);return source;},stopForwarding:function(source,sourceEventName,targetEventName){var fes;if(arguments.length<=1){if(typeof source!='object'||source==null){source=SD.Event;}
source.__sd__forwardedEventStore={};return source;}
if(arguments.length==2){if(typeof source=="object"||source==null){if(source===null){source=SD.Event;}
if(typeof sourceEventName!=='string'){throw'Invalid event name passed to SD.Event.stopForwarding';}
fes=source.__sd__forwardedEventStore[sourceEventName];if(fes){for(var i in fes){SD.Event.stopObserving(source,sourceEventName,fes[i]);}
source.__sd__forwardedEventStore[sourceEventName]={};}
return source;}else{targetEventName=sourceEventName;sourceEventName=source;source=SD.Event;if(typeof sourceEventName!='string'||typeof targetEventName!='string'){throw'Invalid event name passed to SD.Event.stopForwarding';}}}
fes=source.__sd__forwardedEventStore;if(fes&&fes[sourceEventName]&&fes[sourceEventName][targetEventName]){SD.Event.stopObserving(source,sourceEventName,fes[sourceEventName][targetEventName]);fes[sourceEventName][targetEventName]=null;delete fes[sourceEventName][targetEventName];}
return source;},__sd__delegates:{},delegate:function(typeName,eventName,eventHandler){if(arguments.length==2&&typeof eventName=='object'){for(var i in eventName){this.delegate(typeName,i,eventName[i]);}
return;}
if(!this.__sd__delegates[eventName]){this.__sd__delegates[eventName]={};this._registerBaseEvent(eventName);}
if(!this.__sd__delegates[eventName][typeName]){this.__sd__delegates[eventName][typeName]=[];}
this.__sd__delegates[eventName][typeName].push(eventHandler);},_registerBaseEvent:function(eventName){var eventHandler=function(event){if(!SD.Event){return;}
event=event||window.event;if(event.srcElement&&!event.target){event.target=event.srcElement;}
if(event.type=='mouseout'){if(event.toElement&&!event.relatedTarget){event.relatedTarget=event.toElement;}}else if(event.type=='mouseover'){if(event.fromElement&&!event.relatedTarget){event.relatedTarget=event.fromElement;}}
var sdTypes=SD.Event._getTypes(event.target);if(sdTypes.length==0){var c=0;var node=event.target;do{sdTypes=SD.Event._getTypes(node);if(sdTypes.length>0){event.sdTarget=node;break;}
c++;}
while((node=node.parentNode)&&c<6)}else{event.sdTarget=event.target;}
if(eventName=='mouseenter'||eventName=='mouseleave'){if(!event.sdTarget||!event.relatedTarget||SD.Utils.Element.contains(event.sdTarget,event.relatedTarget)){return;}}
var eventHandlerPool;for(var j=0;j<sdTypes.length;j++){eventHandlerPool=SD.Event.__sd__delegates[eventName][sdTypes[j]];if(eventHandlerPool){for(var i=0;i<eventHandlerPool.length;i++){eventHandlerPool[i](event);}}}};switch(eventName){case'focus':this._addOnFocusListener(eventName,eventHandler);break;case'blur':this._addOnBlurListener(eventName,eventHandler);break;case'mouseenter':this._addEventListener('mouseover',eventHandler,false);break;case'mouseleave':this._addEventListener('mouseout',eventHandler,false);break;default:this._addEventListener(eventName,eventHandler,false);}},_addOnFocusListener:function(eventName,eventHandler){if(document.addEventListener){document.addEventListener(eventName,eventHandler,true);}else{document.attachEvent("onfocusin",eventHandler);}},_addOnBlurListener:function(eventName,eventHandler){if(document.addEventListener){document.addEventListener(eventName,eventHandler,true);}else{document.attachEvent("onfocusout",eventHandler);}},_addEventListener:function(eventName,eventHandler,capture){if(document.addEventListener){document.addEventListener(eventName,eventHandler,capture);}else{document.attachEvent("on"+eventName,eventHandler);}},_getTypes:function(el){var sdType=el&&el.getAttribute&&el.getAttribute("sdType");return sdType?sdType.split(' '):[];}};SD.Event.init();SD.EVENTS={DOM_LOADED:"SD.EVENTS:DOM_LOADED",UPDATE_IND_COUNTS_REQUESTED:"SD.EVENTS:UPDATE_IND_COUNTS_REQUESTED",INCREMENT_IND_COUNT_REQUESTED:"SD.EVENTS:INCREMENT_IND_COUNT_REQUESTED"};
var Base64=(function(){var keyStr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";var obj={encode:function(input){var output="";var chr1,chr2,chr3;var enc1,enc2,enc3,enc4;var i=0;do{chr1=input.charCodeAt(i++);chr2=input.charCodeAt(i++);chr3=input.charCodeAt(i++);enc1=chr1>>2;enc2=((chr1&3)<<4)|(chr2>>4);enc3=((chr2&15)<<2)|(chr3>>6);enc4=chr3&63;if(isNaN(chr2)){enc3=enc4=64;}else if(isNaN(chr3)){enc4=64;}
output=output+keyStr.charAt(enc1)+keyStr.charAt(enc2)+
keyStr.charAt(enc3)+keyStr.charAt(enc4);}while(i<input.length);return output;},decode:function(input){var output="";var chr1,chr2,chr3;var enc1,enc2,enc3,enc4;var i=0;input=input.replace(/[^A-Za-z0-9\+\/\=]/g,"");do{enc1=keyStr.indexOf(input.charAt(i++));enc2=keyStr.indexOf(input.charAt(i++));enc3=keyStr.indexOf(input.charAt(i++));enc4=keyStr.indexOf(input.charAt(i++));chr1=(enc1<<2)|(enc2>>4);chr2=((enc2&15)<<4)|(enc3>>2);chr3=((enc3&3)<<6)|enc4;output=output+String.fromCharCode(chr1);if(enc3!=64){output=output+String.fromCharCode(chr2);}
if(enc4!=64){output=output+String.fromCharCode(chr3);}}while(i<input.length);return output;}};return obj;})();var MD5=(function(){var hexcase=0;var b64pad="";var chrsz=8;var safe_add=function(x,y){var lsw=(x&0xFFFF)+(y&0xFFFF);var msw=(x>>16)+(y>>16)+(lsw>>16);return(msw<<16)|(lsw&0xFFFF);};var bit_rol=function(num,cnt){return(num<<cnt)|(num>>>(32-cnt));};var str2binl=function(str){var bin=[];var mask=(1<<chrsz)-1;for(var i=0;i<str.length*chrsz;i+=chrsz)
{bin[i>>5]|=(str.charCodeAt(i/chrsz)&mask)<<(i%32);}
return bin;};var binl2str=function(bin){var str="";var mask=(1<<chrsz)-1;for(var i=0;i<bin.length*32;i+=chrsz)
{str+=String.fromCharCode((bin[i>>5]>>>(i%32))&mask);}
return str;};var binl2hex=function(binarray){var hex_tab=hexcase?"0123456789ABCDEF":"0123456789abcdef";var str="";for(var i=0;i<binarray.length*4;i++)
{str+=hex_tab.charAt((binarray[i>>2]>>((i%4)*8+4))&0xF)+
hex_tab.charAt((binarray[i>>2]>>((i%4)*8))&0xF);}
return str;};var binl2b64=function(binarray){var tab="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var str="";var triplet,j;for(var i=0;i<binarray.length*4;i+=3)
{triplet=(((binarray[i>>2]>>8*(i%4))&0xFF)<<16)|(((binarray[i+1>>2]>>8*((i+1)%4))&0xFF)<<8)|((binarray[i+2>>2]>>8*((i+2)%4))&0xFF);for(j=0;j<4;j++)
{if(i*8+j*6>binarray.length*32){str+=b64pad;}
else{str+=tab.charAt((triplet>>6*(3-j))&0x3F);}}}
return str;};var md5_cmn=function(q,a,b,x,s,t){return safe_add(bit_rol(safe_add(safe_add(a,q),safe_add(x,t)),s),b);};var md5_ff=function(a,b,c,d,x,s,t){return md5_cmn((b&c)|((~b)&d),a,b,x,s,t);};var md5_gg=function(a,b,c,d,x,s,t){return md5_cmn((b&d)|(c&(~d)),a,b,x,s,t);};var md5_hh=function(a,b,c,d,x,s,t){return md5_cmn(b^c^d,a,b,x,s,t);};var md5_ii=function(a,b,c,d,x,s,t){return md5_cmn(c^(b|(~d)),a,b,x,s,t);};var core_md5=function(x,len){x[len>>5]|=0x80<<((len)%32);x[(((len+64)>>>9)<<4)+14]=len;var a=1732584193;var b=-271733879;var c=-1732584194;var d=271733878;var olda,oldb,oldc,oldd;for(var i=0;i<x.length;i+=16)
{olda=a;oldb=b;oldc=c;oldd=d;a=md5_ff(a,b,c,d,x[i+0],7,-680876936);d=md5_ff(d,a,b,c,x[i+1],12,-389564586);c=md5_ff(c,d,a,b,x[i+2],17,606105819);b=md5_ff(b,c,d,a,x[i+3],22,-1044525330);a=md5_ff(a,b,c,d,x[i+4],7,-176418897);d=md5_ff(d,a,b,c,x[i+5],12,1200080426);c=md5_ff(c,d,a,b,x[i+6],17,-1473231341);b=md5_ff(b,c,d,a,x[i+7],22,-45705983);a=md5_ff(a,b,c,d,x[i+8],7,1770035416);d=md5_ff(d,a,b,c,x[i+9],12,-1958414417);c=md5_ff(c,d,a,b,x[i+10],17,-42063);b=md5_ff(b,c,d,a,x[i+11],22,-1990404162);a=md5_ff(a,b,c,d,x[i+12],7,1804603682);d=md5_ff(d,a,b,c,x[i+13],12,-40341101);c=md5_ff(c,d,a,b,x[i+14],17,-1502002290);b=md5_ff(b,c,d,a,x[i+15],22,1236535329);a=md5_gg(a,b,c,d,x[i+1],5,-165796510);d=md5_gg(d,a,b,c,x[i+6],9,-1069501632);c=md5_gg(c,d,a,b,x[i+11],14,643717713);b=md5_gg(b,c,d,a,x[i+0],20,-373897302);a=md5_gg(a,b,c,d,x[i+5],5,-701558691);d=md5_gg(d,a,b,c,x[i+10],9,38016083);c=md5_gg(c,d,a,b,x[i+15],14,-660478335);b=md5_gg(b,c,d,a,x[i+4],20,-405537848);a=md5_gg(a,b,c,d,x[i+9],5,568446438);d=md5_gg(d,a,b,c,x[i+14],9,-1019803690);c=md5_gg(c,d,a,b,x[i+3],14,-187363961);b=md5_gg(b,c,d,a,x[i+8],20,1163531501);a=md5_gg(a,b,c,d,x[i+13],5,-1444681467);d=md5_gg(d,a,b,c,x[i+2],9,-51403784);c=md5_gg(c,d,a,b,x[i+7],14,1735328473);b=md5_gg(b,c,d,a,x[i+12],20,-1926607734);a=md5_hh(a,b,c,d,x[i+5],4,-378558);d=md5_hh(d,a,b,c,x[i+8],11,-2022574463);c=md5_hh(c,d,a,b,x[i+11],16,1839030562);b=md5_hh(b,c,d,a,x[i+14],23,-35309556);a=md5_hh(a,b,c,d,x[i+1],4,-1530992060);d=md5_hh(d,a,b,c,x[i+4],11,1272893353);c=md5_hh(c,d,a,b,x[i+7],16,-155497632);b=md5_hh(b,c,d,a,x[i+10],23,-1094730640);a=md5_hh(a,b,c,d,x[i+13],4,681279174);d=md5_hh(d,a,b,c,x[i+0],11,-358537222);c=md5_hh(c,d,a,b,x[i+3],16,-722521979);b=md5_hh(b,c,d,a,x[i+6],23,76029189);a=md5_hh(a,b,c,d,x[i+9],4,-640364487);d=md5_hh(d,a,b,c,x[i+12],11,-421815835);c=md5_hh(c,d,a,b,x[i+15],16,530742520);b=md5_hh(b,c,d,a,x[i+2],23,-995338651);a=md5_ii(a,b,c,d,x[i+0],6,-198630844);d=md5_ii(d,a,b,c,x[i+7],10,1126891415);c=md5_ii(c,d,a,b,x[i+14],15,-1416354905);b=md5_ii(b,c,d,a,x[i+5],21,-57434055);a=md5_ii(a,b,c,d,x[i+12],6,1700485571);d=md5_ii(d,a,b,c,x[i+3],10,-1894986606);c=md5_ii(c,d,a,b,x[i+10],15,-1051523);b=md5_ii(b,c,d,a,x[i+1],21,-2054922799);a=md5_ii(a,b,c,d,x[i+8],6,1873313359);d=md5_ii(d,a,b,c,x[i+15],10,-30611744);c=md5_ii(c,d,a,b,x[i+6],15,-1560198380);b=md5_ii(b,c,d,a,x[i+13],21,1309151649);a=md5_ii(a,b,c,d,x[i+4],6,-145523070);d=md5_ii(d,a,b,c,x[i+11],10,-1120210379);c=md5_ii(c,d,a,b,x[i+2],15,718787259);b=md5_ii(b,c,d,a,x[i+9],21,-343485551);a=safe_add(a,olda);b=safe_add(b,oldb);c=safe_add(c,oldc);d=safe_add(d,oldd);}
return[a,b,c,d];};var core_hmac_md5=function(key,data){var bkey=str2binl(key);if(bkey.length>16){bkey=core_md5(bkey,key.length*chrsz);}
var ipad=new Array(16),opad=new Array(16);for(var i=0;i<16;i++)
{ipad[i]=bkey[i]^0x36363636;opad[i]=bkey[i]^0x5C5C5C5C;}
var hash=core_md5(ipad.concat(str2binl(data)),512+data.length*chrsz);return core_md5(opad.concat(hash),512+128);};var obj={hexdigest:function(s){return binl2hex(core_md5(str2binl(s),s.length*chrsz));},b64digest:function(s){return binl2b64(core_md5(str2binl(s),s.length*chrsz));},hash:function(s){return binl2str(core_md5(str2binl(s),s.length*chrsz));},hmac_hexdigest:function(key,data){return binl2hex(core_hmac_md5(key,data));},hmac_b64digest:function(key,data){return binl2b64(core_hmac_md5(key,data));},hmac_hash:function(key,data){return binl2str(core_hmac_md5(key,data));},test:function(){return MD5.hexdigest("abc")==="900150983cd24fb0d6963f7d28e17f72";}};return obj;})();if(!Function.prototype.bind){Function.prototype.bind=function(obj)
{var func=this;return function(){return func.apply(obj,arguments);};};}
if(!Function.prototype.prependArg){Function.prototype.prependArg=function(arg)
{var func=this;return function(){var newargs=[arg];for(var i=0;i<arguments.length;i++){newargs.push(arguments[i]);}
return func.apply(this,newargs);};};}
if(!Array.prototype.indexOf)
{Array.prototype.indexOf=function(elt)
{var len=this.length;var from=Number(arguments[1])||0;from=(from<0)?Math.ceil(from):Math.floor(from);if(from<0){from+=len;}
for(;from<len;from++){if(from in this&&this[from]===elt){return from;}}
return-1;};}
(function(callback){var Strophe;function $build(name,attrs){return new Strophe.Builder(name,attrs);}
function $msg(attrs){return new Strophe.Builder("message",attrs);}
function $iq(attrs){return new Strophe.Builder("iq",attrs);}
function $pres(attrs){return new Strophe.Builder("presence",attrs);}
Strophe={VERSION:"1.0.1",NS:{HTTPBIND:"http://jabber.org/protocol/httpbind",BOSH:"urn:xmpp:xbosh",CLIENT:"jabber:client",AUTH:"jabber:iq:auth",ROSTER:"jabber:iq:roster",PROFILE:"jabber:iq:profile",DISCO_INFO:"http://jabber.org/protocol/disco#info",DISCO_ITEMS:"http://jabber.org/protocol/disco#items",MUC:"http://jabber.org/protocol/muc",SASL:"urn:ietf:params:xml:ns:xmpp-sasl",STREAM:"http://etherx.jabber.org/streams",BIND:"urn:ietf:params:xml:ns:xmpp-bind",SESSION:"urn:ietf:params:xml:ns:xmpp-session",VERSION:"jabber:iq:version",STANZAS:"urn:ietf:params:xml:ns:xmpp-stanzas"},addNamespace:function(name,value)
{Strophe.NS[name]=value;},Status:{ERROR:0,CONNECTING:1,CONNFAIL:2,AUTHENTICATING:3,AUTHFAIL:4,CONNECTED:5,DISCONNECTED:6,DISCONNECTING:7,ATTACHED:8},LogLevel:{DEBUG:0,INFO:1,WARN:2,ERROR:3,FATAL:4},ElementType:{NORMAL:1,TEXT:3},TIMEOUT:1.1,SECONDARY_TIMEOUT:0.1,forEachChild:function(elem,elemName,func)
{var i,childNode;for(i=0;i<elem.childNodes.length;i++){childNode=elem.childNodes[i];if(childNode.nodeType==Strophe.ElementType.NORMAL&&(!elemName||this.isTagEqual(childNode,elemName))){func(childNode);}}},isTagEqual:function(el,name)
{return el.tagName.toLowerCase()==name.toLowerCase();},_xmlGenerator:null,_makeGenerator:function(){var doc;if(window.ActiveXObject){doc=new ActiveXObject("Microsoft.XMLDOM");doc.appendChild(doc.createElement('strophe'));}else{doc=document.implementation.createDocument('jabber:client','strophe',null);}
return doc;},xmlElement:function(name)
{if(!name){return null;}
var node=null;if(!Strophe._xmlGenerator){Strophe._xmlGenerator=Strophe._makeGenerator();}
node=Strophe._xmlGenerator.createElement(name);var a,i,k;for(a=1;a<arguments.length;a++){if(!arguments[a]){continue;}
if(typeof(arguments[a])=="string"||typeof(arguments[a])=="number"){node.appendChild(Strophe.xmlTextNode(arguments[a]));}else if(typeof(arguments[a])=="object"&&typeof(arguments[a].sort)=="function"){for(i=0;i<arguments[a].length;i++){if(typeof(arguments[a][i])=="object"&&typeof(arguments[a][i].sort)=="function"){node.setAttribute(arguments[a][i][0],arguments[a][i][1]);}}}else if(typeof(arguments[a])=="object"){for(k in arguments[a]){if(arguments[a].hasOwnProperty(k)){node.setAttribute(k,arguments[a][k]===null?"":arguments[a][k]);}}}}
return node;},xmlescape:function(text)
{text=text.replace(/\&/g,"&amp;");text=text.replace(/</g,"&lt;");text=text.replace(/>/g,"&gt;");return text;},xmlTextNode:function(text)
{text=Strophe.xmlescape(text);if(!Strophe._xmlGenerator){Strophe._xmlGenerator=Strophe._makeGenerator();}
return Strophe._xmlGenerator.createTextNode(text);},getText:function(elem)
{if(!elem){return null;}
var str="";if(elem.childNodes.length===0&&elem.nodeType==Strophe.ElementType.TEXT){str+=elem.nodeValue;}
for(var i=0;i<elem.childNodes.length;i++){if(elem.childNodes[i].nodeType==Strophe.ElementType.TEXT){str+=elem.childNodes[i].nodeValue;}}
return str;},copyElement:function(elem)
{var i,el;if(elem.nodeType==Strophe.ElementType.NORMAL){el=Strophe.xmlElement(elem.tagName);for(i=0;i<elem.attributes.length;i++){el.setAttribute(elem.attributes[i].nodeName.toLowerCase(),elem.attributes[i].value);}
for(i=0;i<elem.childNodes.length;i++){el.appendChild(Strophe.copyElement(elem.childNodes[i]));}}else if(elem.nodeType==Strophe.ElementType.TEXT){el=Strophe.xmlTextNode(elem.nodeValue);}
return el;},escapeNode:function(node)
{return node.replace(/^\s+|\s+$/g,'').replace(/\\/g,"\\5c").replace(/ /g,"\\20").replace(/\"/g,"\\22").replace(/\&/g,"\\26").replace(/\'/g,"\\27").replace(/\//g,"\\2f").replace(/:/g,"\\3a").replace(/</g,"\\3c").replace(/>/g,"\\3e").replace(/@/g,"\\40");},unescapeNode:function(node)
{return node.replace(/\\20/g," ").replace(/\\22/g,'"').replace(/\\26/g,"&").replace(/\\27/g,"'").replace(/\\2f/g,"/").replace(/\\3a/g,":").replace(/\\3c/g,"<").replace(/\\3e/g,">").replace(/\\40/g,"@").replace(/\\5c/g,"\\");},getNodeFromJid:function(jid)
{if(jid.indexOf("@")<0){return null;}
return jid.split("@")[0];},getDomainFromJid:function(jid)
{var bare=Strophe.getBareJidFromJid(jid);if(bare.indexOf("@")<0){return bare;}else{var parts=bare.split("@");parts.splice(0,1);return parts.join('@');}},getResourceFromJid:function(jid)
{var s=jid.split("/");if(s.length<2){return null;}
s.splice(0,1);return s.join('/');},getBareJidFromJid:function(jid)
{return jid.split("/")[0];},log:function(level,msg)
{return;},debug:function(msg)
{this.log(this.LogLevel.DEBUG,msg);},info:function(msg)
{this.log(this.LogLevel.INFO,msg);},warn:function(msg)
{this.log(this.LogLevel.WARN,msg);},error:function(msg)
{this.log(this.LogLevel.ERROR,msg);},fatal:function(msg)
{this.log(this.LogLevel.FATAL,msg);},serialize:function(elem)
{var result;if(!elem){return null;}
if(typeof(elem.tree)==="function"){elem=elem.tree();}
var nodeName=elem.nodeName;var i,child;if(elem.getAttribute("_realname")){nodeName=elem.getAttribute("_realname");}
result="<"+nodeName;for(i=0;i<elem.attributes.length;i++){if(elem.attributes[i].nodeName!="_realname"){result+=" "+elem.attributes[i].nodeName.toLowerCase()+"='"+elem.attributes[i].value.replace(/&/g,"&amp;").replace(/'/g,"&apos;").replace(/</g,"&lt;")+"'";}}
if(elem.childNodes.length>0){result+=">";for(i=0;i<elem.childNodes.length;i++){child=elem.childNodes[i];if(child.nodeType==Strophe.ElementType.NORMAL){result+=Strophe.serialize(child);}else if(child.nodeType==Strophe.ElementType.TEXT){result+=child.nodeValue;}}
result+="</"+nodeName+">";}else{result+="/>";}
return result;},_requestId:0,_connectionPlugins:{},addConnectionPlugin:function(name,ptype)
{Strophe._connectionPlugins[name]=ptype;}};Strophe.Builder=function(name,attrs)
{if(name=="presence"||name=="message"||name=="iq"){if(attrs&&!attrs.xmlns){attrs.xmlns=Strophe.NS.CLIENT;}else if(!attrs){attrs={xmlns:Strophe.NS.CLIENT};}}
this.nodeTree=Strophe.xmlElement(name,attrs);this.node=this.nodeTree;};Strophe.Builder.prototype={tree:function()
{return this.nodeTree;},toString:function()
{return Strophe.serialize(this.nodeTree);},up:function()
{this.node=this.node.parentNode;return this;},attrs:function(moreattrs)
{for(var k in moreattrs){if(moreattrs.hasOwnProperty(k)){this.node.setAttribute(k,moreattrs[k]);}}
return this;},c:function(name,attrs)
{var child=Strophe.xmlElement(name,attrs);this.node.appendChild(child);this.node=child;return this;},cnode:function(elem)
{this.node.appendChild(elem);this.node=elem;return this;},t:function(text)
{var child=Strophe.xmlTextNode(text);this.node.appendChild(child);return this;}};Strophe.Handler=function(handler,ns,name,type,id,from,options)
{this.handler=handler;this.ns=ns;this.name=name;this.type=type;this.id=id;this.options=options||{matchbare:false};if(!this.options.matchBare){this.options.matchBare=false;}
if(this.options.matchBare){this.from=Strophe.getBareJidFromJid(from);}else{this.from=from;}
this.user=true;};Strophe.Handler.prototype={isMatch:function(elem)
{var nsMatch;var from=null;if(this.options.matchBare){from=elem.getAttribute('from')&&Strophe.getBareJidFromJid(elem.getAttribute('from'));}else{from=elem.getAttribute('from');}
nsMatch=false;if(!this.ns){nsMatch=true;}else{var self=this;Strophe.forEachChild(elem,null,function(elem){if(elem.getAttribute("xmlns")==self.ns){nsMatch=true;}});nsMatch=nsMatch||elem.getAttribute("xmlns")==this.ns;}
if(nsMatch&&(!this.name||Strophe.isTagEqual(elem,this.name))&&(!this.type||elem.getAttribute("type")===this.type)&&(!this.id||elem.getAttribute("id")===this.id)&&(!this.from||from===this.from)){return true;}
return false;},run:function(elem)
{var result=null;try{result=this.handler(elem);}catch(e){if(e.sourceURL){Strophe.fatal("error: "+this.handler+" "+e.sourceURL+":"+
e.line+" - "+e.name+": "+e.message);}else if(e.fileName){if(typeof(console)!="undefined"){console.trace();console.error(this.handler," - error - ",e,e.message);}
Strophe.fatal("error: "+this.handler+" "+
e.fileName+":"+e.lineNumber+" - "+
e.name+": "+e.message);}else{Strophe.fatal("error: "+this.handler);}
throw e;}
return result;},toString:function()
{return"{Handler: "+this.handler+"("+this.name+","+
this.id+","+this.ns+")}";}};Strophe.TimedHandler=function(period,handler)
{this.period=period;this.handler=handler;this.lastCalled=new Date().getTime();this.user=true;};Strophe.TimedHandler.prototype={run:function()
{this.lastCalled=new Date().getTime();return this.handler();},reset:function()
{this.lastCalled=new Date().getTime();},toString:function()
{return"{TimedHandler: "+this.handler+"("+this.period+")}";}};Strophe.Request=function(elem,func,rid,sends)
{this.id=++Strophe._requestId;this.xmlData=elem;this.data=Strophe.serialize(elem);this.origFunc=func;this.func=func;this.rid=rid;this.date=NaN;this.sends=sends||0;this.abort=false;this.dead=null;this.age=function(){if(!this.date){return 0;}
var now=new Date();return(now-this.date)/1000;};this.timeDead=function(){if(!this.dead){return 0;}
var now=new Date();return(now-this.dead)/1000;};this.xhr=this._newXHR();};Strophe.Request.prototype={getResponse:function()
{var node=null;if(this.xhr.responseXML&&this.xhr.responseXML.documentElement){node=this.xhr.responseXML.documentElement;if(node.tagName=="parsererror"){Strophe.error("invalid response received");Strophe.error("responseText: "+this.xhr.responseText);Strophe.error("responseXML: "+
Strophe.serialize(this.xhr.responseXML));throw"parsererror";}}else if(this.xhr.responseText){Strophe.error("invalid response received");Strophe.error("responseText: "+this.xhr.responseText);Strophe.error("responseXML: "+
Strophe.serialize(this.xhr.responseXML));}
return node;},_newXHR:function()
{var xhr=null;if(window.XMLHttpRequest){xhr=new XMLHttpRequest();if(xhr.overrideMimeType){xhr.overrideMimeType("text/xml");}}else if(window.ActiveXObject){xhr=new ActiveXObject("Microsoft.XMLHTTP");}
xhr.onreadystatechange=this.func.prependArg(this);return xhr;}};Strophe.Connection=function(service,sendFunction)
{this.sendFunction=sendFunction||SD.XMPP.sendXMPPString;this.service=service;this.jid="";this.rid=Math.floor(Math.random()*4294967295);this.sid=null;this.streamId=null;this.do_session=false;this.do_bind=false;this.timedHandlers=[];this.handlers=[];this.removeTimeds=[];this.removeHandlers=[];this.addTimeds=[];this.addHandlers=[];this._idleTimeout=null;this._disconnectTimeout=null;this.authenticated=false;this.disconnecting=false;this.connected=false;this.errors=0;this.paused=false;this.hold=1;this.wait=60;this.window=5;this._data=[];this._requests=[];this._uniqueId=Math.round(Math.random()*10000);this._sasl_success_handler=null;this._sasl_failure_handler=null;this._sasl_challenge_handler=null;this._idleTimeout=setTimeout(this._onIdle.bind(this),100);for(var k in Strophe._connectionPlugins){if(Strophe._connectionPlugins.hasOwnProperty(k)){var ptype=Strophe._connectionPlugins[k];var F=function(){};F.prototype=ptype;this[k]=new F();this[k].init(this);}}};Strophe.Connection.prototype={reset:function()
{this.rid=Math.floor(Math.random()*4294967295);this.sid=null;this.streamId=null;this.do_session=false;this.do_bind=false;this.timedHandlers=[];this.handlers=[];this.removeTimeds=[];this.removeHandlers=[];this.addTimeds=[];this.addHandlers=[];this.authenticated=false;this.disconnecting=false;this.connected=false;this.errors=0;this._requests=[];this._uniqueId=Math.round(Math.random()*10000);},pause:function()
{this.paused=true;},resume:function()
{this.paused=false;},getUniqueId:function(suffix)
{if(typeof(suffix)=="string"||typeof(suffix)=="number"){return++this._uniqueId+":"+suffix;}else{return++this._uniqueId+"";}},connect:function(jid,pass,callback,wait,hold)
{this.jid=jid;this.pass=pass;this.connect_callback=callback;this.disconnecting=false;this.connected=false;this.authenticated=false;this.errors=0;this.wait=wait||this.wait;this.hold=hold||this.hold;this.domain=Strophe.getDomainFromJid(this.jid);var body=this._buildBody().attrs({to:this.domain,"xml:lang":"en",wait:this.wait,hold:this.hold,content:"text/xml; charset=utf-8",ver:"1.6","xmpp:version":"1.0","xmlns:xmpp":Strophe.NS.BOSH});this._changeConnectStatus(Strophe.Status.CONNECTING,null);this._requests.push(new Strophe.Request(body.tree(),this._onRequestStateChange.bind(this).prependArg(this._connect_cb.bind(this)),body.tree().getAttribute("rid")));this._throttledRequestHandler();},attach:function(jid,sid,rid,callback,wait,hold,wind)
{this.jid=jid;this.sid=sid;this.rid=rid;this.connect_callback=callback;this.domain=Strophe.getDomainFromJid(this.jid);this.authenticated=true;this.connected=true;this.wait=wait||this.wait;this.hold=hold||this.hold;this.window=wind||this.window;this._changeConnectStatus(Strophe.Status.ATTACHED,null);},xmlInput:function(elem)
{return;},xmlOutput:function(elem)
{return;},rawInput:function(data)
{return;},rawOutput:function(data)
{return;},send:function(elem)
{if(elem===null){return;}
if(typeof(elem.sort)==="function"){for(var i=0;i<elem.length;i++){this.sendFunction(Strophe.serialize(elem[i]));}}else if(typeof(elem.tree)==="function"){this.sendFunction(Strophe.serialize(elem.tree()));}else{this.sendFunction(Strophe.serialize(elem));}},flush:function()
{clearTimeout(this._idleTimeout);this._onIdle();},sendIQ:function(elem,callback,errback,timeout){var timeoutHandler=null;var that=this;if(typeof(elem.tree)==="function"){elem=elem.tree();}
var id=elem.getAttribute('id');if(!id){id=this.getUniqueId("sendIQ");elem.setAttribute("id",id);}
var handler=this.addHandler(function(stanza){if(timeoutHandler){that.deleteTimedHandler(timeoutHandler);}
var iqtype=stanza.getAttribute('type');if(iqtype==='result'){if(callback){callback(stanza);}}else if(iqtype==='error'){if(errback){errback(stanza);}}else{throw{name:"StropheError",message:"Got bad IQ type of "+iqtype};}},null,'iq',null,id);if(timeout){timeoutHandler=this.addTimedHandler(timeout,function(){that.deleteHandler(handler);if(errback){errback(null);}
return false;});}
this.send(elem);return id;},_queueData:function(element){if(element===null||!element.tagName||!element.childNodes){throw{name:"StropheError",message:"Cannot queue non-DOMElement."};}
this._data.push(element);},_sendRestart:function()
{this._data.push("restart");this._throttledRequestHandler();clearTimeout(this._idleTimeout);this._idleTimeout=setTimeout(this._onIdle.bind(this),100);},addTimedHandler:function(period,handler)
{var thand=new Strophe.TimedHandler(period,handler);this.addTimeds.push(thand);return thand;},deleteTimedHandler:function(handRef)
{this.removeTimeds.push(handRef);},addHandler:function(handler,ns,name,type,id,from,options)
{var hand=new Strophe.Handler(handler,ns,name,type,id,from,options);this.addHandlers.push(hand);return hand;},deleteHandler:function(handRef)
{this.removeHandlers.push(handRef);},disconnect:function(reason)
{this._changeConnectStatus(Strophe.Status.DISCONNECTING,reason);Strophe.info("Disconnect was called because: "+reason);if(this.connected){this._disconnectTimeout=this._addSysTimedHandler(3000,this._onDisconnectTimeout.bind(this));this._sendTerminate();}},_changeConnectStatus:function(status,condition)
{for(var k in Strophe._connectionPlugins){if(Strophe._connectionPlugins.hasOwnProperty(k)){var plugin=this[k];if(plugin.statusChanged){try{plugin.statusChanged(status,condition);}catch(err){Strophe.error(""+k+" plugin caused an exception "+"changing status: "+err);}}}}
if(this.connect_callback){try{this.connect_callback(status,condition);}catch(e){Strophe.error("User connection callback caused an "+"exception: "+e);}}},_buildBody:function()
{var bodyWrap=$build('body',{rid:this.rid++,xmlns:Strophe.NS.HTTPBIND});if(this.sid!==null){bodyWrap.attrs({sid:this.sid});}
return bodyWrap;},_removeRequest:function(req)
{Strophe.debug("removing request");var i;for(i=this._requests.length-1;i>=0;i--){if(req==this._requests[i]){this._requests.splice(i,1);}}
req.xhr.onreadystatechange=function(){};this._throttledRequestHandler();},_restartRequest:function(i)
{var req=this._requests[i];if(req.dead===null){req.dead=new Date();}
this._processRequest(i);},_processRequest:function(i)
{var req=this._requests[i];var reqStatus=-1;try{if(req.xhr.readyState==4){reqStatus=req.xhr.status;}}catch(e){Strophe.error("caught an error in _requests["+i+"], reqStatus: "+reqStatus);}
if(typeof(reqStatus)=="undefined"){reqStatus=-1;}
var time_elapsed=req.age();var primaryTimeout=(!isNaN(time_elapsed)&&time_elapsed>Math.floor(Strophe.TIMEOUT*this.wait));var secondaryTimeout=(req.dead!==null&&req.timeDead()>Math.floor(Strophe.SECONDARY_TIMEOUT*this.wait));var requestCompletedWithServerError=(req.xhr.readyState==4&&(reqStatus<1||reqStatus>=500));if(primaryTimeout||secondaryTimeout||requestCompletedWithServerError){if(secondaryTimeout){Strophe.error("Request "+
this._requests[i].id+" timed out (secondary), restarting");}
req.abort=true;req.xhr.abort();req.xhr.onreadystatechange=function(){};this._requests[i]=new Strophe.Request(req.xmlData,req.origFunc,req.rid,req.sends);req=this._requests[i];}
if(req.xhr.readyState===0){Strophe.debug("request id "+req.id+"."+req.sends+" posting");req.date=new Date();try{req.xhr.open("POST",this.service,true);}catch(e2){Strophe.error("XHR open failed.");if(!this.connected){this._changeConnectStatus(Strophe.Status.CONNFAIL,"bad-service");}
this.disconnect();return;}
var sendFunc=function(){req.xhr.send(req.data);};if(req.sends>1){var backoff=Math.pow(req.sends,3)*1000;setTimeout(sendFunc,backoff);}else{sendFunc();}
req.sends++;this.xmlOutput(req.xmlData);this.rawOutput(req.data);}else{Strophe.debug("_processRequest: "+
(i===0?"first":"second")+" request has readyState of "+
req.xhr.readyState);}},_throttledRequestHandler:function()
{if(!this._requests){Strophe.debug("_throttledRequestHandler called with "+"undefined requests");}else{Strophe.debug("_throttledRequestHandler called with "+
this._requests.length+" requests");}
if(!this._requests||this._requests.length===0){return;}
if(this._requests.length>0){this._processRequest(0);}
if(this._requests.length>1&&Math.abs(this._requests[0].rid-
this._requests[1].rid)<this.window-1){this._processRequest(1);}},_onRequestStateChange:function(func,req)
{Strophe.debug("request id "+req.id+"."+req.sends+" state changed to "+
req.xhr.readyState);if(req.abort){req.abort=false;return;}
var reqStatus;if(req.xhr.readyState==4){reqStatus=0;try{reqStatus=req.xhr.status;}catch(e){}
if(typeof(reqStatus)=="undefined"){reqStatus=0;}
if(this.disconnecting){if(reqStatus>=400){this._hitError(reqStatus);return;}}
var reqIs0=(this._requests[0]==req);var reqIs1=(this._requests[1]==req);if((reqStatus>0&&reqStatus<500)||req.sends>5){this._removeRequest(req);Strophe.debug("request id "+
req.id+" should now be removed");}
if(reqStatus==200){if(reqIs1||(reqIs0&&this._requests.length>0&&this._requests[0].age()>Math.floor(Strophe.SECONDARY_TIMEOUT*this.wait))){this._restartRequest(0);}
Strophe.debug("request id "+
req.id+"."+
req.sends+" got 200");func(req);this.errors=0;}else{Strophe.error("request id "+
req.id+"."+
req.sends+" error "+reqStatus+" happened");if(reqStatus===0||(reqStatus>=400&&reqStatus<600)||reqStatus>=12000){this._hitError(reqStatus);if(reqStatus>=400&&reqStatus<500){this._changeConnectStatus(Strophe.Status.DISCONNECTING,null);this._doDisconnect();}}}
if(!((reqStatus>0&&reqStatus<10000)||req.sends>5)){this._throttledRequestHandler();}}},_hitError:function(reqStatus)
{this.errors++;Strophe.warn("request errored, status: "+reqStatus+", number of errors: "+this.errors);if(this.errors>4){this._onDisconnectTimeout();}},_doDisconnect:function()
{Strophe.info("_doDisconnect was called");this.authenticated=false;this.disconnecting=false;this.sid=null;this.streamId=null;this.rid=Math.floor(Math.random()*4294967295);if(this.connected){this._changeConnectStatus(Strophe.Status.DISCONNECTED,null);this.connected=false;}
this.handlers=[];this.timedHandlers=[];this.removeTimeds=[];this.removeHandlers=[];this.addTimeds=[];this.addHandlers=[];},_dataRecv:function(req)
{try{var elem=req.getResponse();}catch(e){if(e!="parsererror"){throw e;}
this.disconnect("strophe-parsererror");}
if(elem===null){return;}
this.xmlInput(elem);this.rawInput(Strophe.serialize(elem));var i,hand;while(this.removeHandlers.length>0){hand=this.removeHandlers.pop();i=this.handlers.indexOf(hand);if(i>=0){this.handlers.splice(i,1);}}
while(this.addHandlers.length>0){this.handlers.push(this.addHandlers.pop());}
if(this.disconnecting&&this._requests.length===0){this.deleteTimedHandler(this._disconnectTimeout);this._disconnectTimeout=null;this._doDisconnect();return;}
var typ=elem.getAttribute("type");var cond,conflict;if(typ!==null&&typ=="terminate"){cond=elem.getAttribute("condition");conflict=elem.getElementsByTagName("conflict");if(cond!==null){if(cond=="remote-stream-error"&&conflict.length>0){cond="conflict";}
this._changeConnectStatus(Strophe.Status.CONNFAIL,cond);}else{this._changeConnectStatus(Strophe.Status.CONNFAIL,"unknown");}
this.disconnect();return;}
var self=this;Strophe.forEachChild(elem,null,function(child){var i,newList;newList=self.handlers;self.handlers=[];for(i=0;i<newList.length;i++){var hand=newList[i];try{if(hand.isMatch(child)&&(self.authenticated||!hand.user)){if(hand.run(child)){self.handlers.push(hand);}}else{self.handlers.push(hand);}}catch(e){}}});},_sendTerminate:function()
{Strophe.info("_sendTerminate was called");var body=this._buildBody().attrs({type:"terminate"});if(this.authenticated){body.c('presence',{xmlns:Strophe.NS.CLIENT,type:'unavailable'});}
this.disconnecting=true;var req=new Strophe.Request(body.tree(),this._onRequestStateChange.bind(this).prependArg(this._dataRecv.bind(this)),body.tree().getAttribute("rid"));this._requests.push(req);this._throttledRequestHandler();},_connect_cb:function(req)
{Strophe.info("_connect_cb was called");this.connected=true;var bodyWrap=req.getResponse();if(!bodyWrap){return;}
this.xmlInput(bodyWrap);this.rawInput(Strophe.serialize(bodyWrap));var typ=bodyWrap.getAttribute("type");var cond,conflict;if(typ!==null&&typ=="terminate"){cond=bodyWrap.getAttribute("condition");conflict=bodyWrap.getElementsByTagName("conflict");if(cond!==null){if(cond=="remote-stream-error"&&conflict.length>0){cond="conflict";}
this._changeConnectStatus(Strophe.Status.CONNFAIL,cond);}else{this._changeConnectStatus(Strophe.Status.CONNFAIL,"unknown");}
return;}
if(!this.sid){this.sid=bodyWrap.getAttribute("sid");}
if(!this.stream_id){this.stream_id=bodyWrap.getAttribute("authid");}
var wind=bodyWrap.getAttribute('requests');if(wind){this.window=parseInt(wind,10);}
var hold=bodyWrap.getAttribute('hold');if(hold){this.hold=parseInt(hold,10);}
var wait=bodyWrap.getAttribute('wait');if(wait){this.wait=parseInt(wait,10);}
var do_sasl_plain=false;var do_sasl_digest_md5=false;var do_sasl_anonymous=false;var mechanisms=bodyWrap.getElementsByTagName("mechanism");var i,mech,auth_str,hashed_auth_str;if(mechanisms.length>0){for(i=0;i<mechanisms.length;i++){mech=Strophe.getText(mechanisms[i]);if(mech=='DIGEST-MD5'){do_sasl_digest_md5=true;}else if(mech=='PLAIN'){do_sasl_plain=true;}else if(mech=='ANONYMOUS'){do_sasl_anonymous=true;}}}else{var body=this._buildBody();this._requests.push(new Strophe.Request(body.tree(),this._onRequestStateChange.bind(this).prependArg(this._connect_cb.bind(this)),body.tree().getAttribute("rid")));this._throttledRequestHandler();return;}
if(Strophe.getNodeFromJid(this.jid)===null&&do_sasl_anonymous){this._changeConnectStatus(Strophe.Status.AUTHENTICATING,null);this._sasl_success_handler=this._addSysHandler(this._sasl_success_cb.bind(this),null,"success",null,null);this._sasl_failure_handler=this._addSysHandler(this._sasl_failure_cb.bind(this),null,"failure",null,null);this.send($build("auth",{xmlns:Strophe.NS.SASL,mechanism:"ANONYMOUS"}).tree());}else if(Strophe.getNodeFromJid(this.jid)===null){this._changeConnectStatus(Strophe.Status.CONNFAIL,'x-strophe-bad-non-anon-jid');this.disconnect();}else if(do_sasl_digest_md5){this._changeConnectStatus(Strophe.Status.AUTHENTICATING,null);this._sasl_challenge_handler=this._addSysHandler(this._sasl_challenge1_cb.bind(this),null,"challenge",null,null);this._sasl_failure_handler=this._addSysHandler(this._sasl_failure_cb.bind(this),null,"failure",null,null);this.send($build("auth",{xmlns:Strophe.NS.SASL,mechanism:"DIGEST-MD5"}).tree());}else if(do_sasl_plain){auth_str=Strophe.getBareJidFromJid(this.jid);auth_str=auth_str+"\u0000";auth_str=auth_str+Strophe.getNodeFromJid(this.jid);auth_str=auth_str+"\u0000";auth_str=auth_str+this.pass;this._changeConnectStatus(Strophe.Status.AUTHENTICATING,null);this._sasl_success_handler=this._addSysHandler(this._sasl_success_cb.bind(this),null,"success",null,null);this._sasl_failure_handler=this._addSysHandler(this._sasl_failure_cb.bind(this),null,"failure",null,null);hashed_auth_str=Base64.encode(auth_str);this.send($build("auth",{xmlns:Strophe.NS.SASL,mechanism:"PLAIN"}).t(hashed_auth_str).tree());}else{this._changeConnectStatus(Strophe.Status.AUTHENTICATING,null);this._addSysHandler(this._auth1_cb.bind(this),null,null,null,"_auth_1");this.send($iq({type:"get",to:this.domain,id:"_auth_1"}).c("query",{xmlns:Strophe.NS.AUTH}).c("username",{}).t(Strophe.getNodeFromJid(this.jid)).tree());}},_sasl_challenge1_cb:function(elem)
{var attribMatch=/([a-z]+)=("[^"]+"|[^,"]+)(?:,|$)/;var challenge=Base64.decode(Strophe.getText(elem));var cnonce=MD5.hexdigest(Math.random()*1234567890);var realm="";var host=null;var nonce="";var qop="";var matches;this.deleteHandler(this._sasl_failure_handler);while(challenge.match(attribMatch)){matches=challenge.match(attribMatch);challenge=challenge.replace(matches[0],"");matches[2]=matches[2].replace(/^"(.+)"$/,"$1");switch(matches[1]){case"realm":realm=matches[2];break;case"nonce":nonce=matches[2];break;case"qop":qop=matches[2];break;case"host":host=matches[2];break;}}
var digest_uri="xmpp/"+this.domain;if(host!==null){digest_uri=digest_uri+"/"+host;}
var A1=MD5.hash(Strophe.getNodeFromJid(this.jid)+":"+realm+":"+this.pass)+":"+nonce+":"+cnonce;var A2='AUTHENTICATE:'+digest_uri;var responseText="";responseText+='username='+
this._quote(Strophe.getNodeFromJid(this.jid))+',';responseText+='realm='+this._quote(realm)+',';responseText+='nonce='+this._quote(nonce)+',';responseText+='cnonce='+this._quote(cnonce)+',';responseText+='nc="00000001",';responseText+='qop="auth",';responseText+='digest-uri='+this._quote(digest_uri)+',';responseText+='response='+this._quote(MD5.hexdigest(MD5.hexdigest(A1)+":"+
nonce+":00000001:"+
cnonce+":auth:"+
MD5.hexdigest(A2)))+',';responseText+='charset="utf-8"';this._sasl_challenge_handler=this._addSysHandler(this._sasl_challenge2_cb.bind(this),null,"challenge",null,null);this._sasl_success_handler=this._addSysHandler(this._sasl_success_cb.bind(this),null,"success",null,null);this._sasl_failure_handler=this._addSysHandler(this._sasl_failure_cb.bind(this),null,"failure",null,null);this.send($build('response',{xmlns:Strophe.NS.SASL}).t(Base64.encode(responseText)).tree());return false;},_quote:function(str)
{return'"'+str.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"';},_sasl_challenge2_cb:function(elem)
{this.deleteHandler(this._sasl_success_handler);this.deleteHandler(this._sasl_failure_handler);this._sasl_success_handler=this._addSysHandler(this._sasl_success_cb.bind(this),null,"success",null,null);this._sasl_failure_handler=this._addSysHandler(this._sasl_failure_cb.bind(this),null,"failure",null,null);this.send($build('response',{xmlns:Strophe.NS.SASL}).tree());return false;},_auth1_cb:function(elem)
{var iq=$iq({type:"set",id:"_auth_2"}).c('query',{xmlns:Strophe.NS.AUTH}).c('username',{}).t(Strophe.getNodeFromJid(this.jid)).up().c('password').t(this.pass);if(!Strophe.getResourceFromJid(this.jid)){this.jid=Strophe.getBareJidFromJid(this.jid)+'/strophe';}
iq.up().c('resource',{}).t(Strophe.getResourceFromJid(this.jid));this._addSysHandler(this._auth2_cb.bind(this),null,null,null,"_auth_2");this.send(iq.tree());return false;},_sasl_success_cb:function(elem)
{Strophe.info("SASL authentication succeeded.");this.deleteHandler(this._sasl_failure_handler);this._sasl_failure_handler=null;if(this._sasl_challenge_handler){this.deleteHandler(this._sasl_challenge_handler);this._sasl_challenge_handler=null;}
this._addSysHandler(this._sasl_auth1_cb.bind(this),null,"stream:features",null,null);this._sendRestart();return false;},_sasl_auth1_cb:function(elem)
{var i,child;for(i=0;i<elem.childNodes.length;i++){child=elem.childNodes[i];if(child.nodeName=='bind'){this.do_bind=true;}
if(child.nodeName=='session'){this.do_session=true;}}
if(!this.do_bind){this._changeConnectStatus(Strophe.Status.AUTHFAIL,null);return false;}else{this._addSysHandler(this._sasl_bind_cb.bind(this),null,null,null,"_bind_auth_2");var resource=Strophe.getResourceFromJid(this.jid);if(resource){this.send($iq({type:"set",id:"_bind_auth_2"}).c('bind',{xmlns:Strophe.NS.BIND}).c('resource',{}).t(resource).tree());}else{this.send($iq({type:"set",id:"_bind_auth_2"}).c('bind',{xmlns:Strophe.NS.BIND}).tree());}}
return false;},_sasl_bind_cb:function(elem)
{if(elem.getAttribute("type")=="error"){Strophe.info("SASL binding failed.");this._changeConnectStatus(Strophe.Status.AUTHFAIL,null);return false;}
var bind=elem.getElementsByTagName("bind");var jidNode;if(bind.length>0){jidNode=bind[0].getElementsByTagName("jid");if(jidNode.length>0){this.jid=Strophe.getText(jidNode[0]);if(this.do_session){this._addSysHandler(this._sasl_session_cb.bind(this),null,null,null,"_session_auth_2");this.send($iq({type:"set",id:"_session_auth_2"}).c('session',{xmlns:Strophe.NS.SESSION}).tree());}else{this.authenticated=true;this._changeConnectStatus(Strophe.Status.CONNECTED,null);}}}else{Strophe.info("SASL binding failed.");this._changeConnectStatus(Strophe.Status.AUTHFAIL,null);return false;}
return true;},_sasl_session_cb:function(elem)
{if(elem.getAttribute("type")=="result"){this.authenticated=true;this._changeConnectStatus(Strophe.Status.CONNECTED,null);}else if(elem.getAttribute("type")=="error"){Strophe.info("Session creation failed.");this._changeConnectStatus(Strophe.Status.AUTHFAIL,null);return false;}
return false;},_sasl_failure_cb:function(elem)
{if(this._sasl_success_handler){this.deleteHandler(this._sasl_success_handler);this._sasl_success_handler=null;}
if(this._sasl_challenge_handler){this.deleteHandler(this._sasl_challenge_handler);this._sasl_challenge_handler=null;}
this._changeConnectStatus(Strophe.Status.AUTHFAIL,null);return false;},_auth2_cb:function(elem)
{if(elem.getAttribute("type")=="result"){this.authenticated=true;this._changeConnectStatus(Strophe.Status.CONNECTED,null);}else if(elem.getAttribute("type")=="error"){this._changeConnectStatus(Strophe.Status.AUTHFAIL,null);this.disconnect();}
return false;},_addSysTimedHandler:function(period,handler)
{var thand=new Strophe.TimedHandler(period,handler);thand.user=false;this.addTimeds.push(thand);return thand;},_addSysHandler:function(handler,ns,name,type,id)
{var hand=new Strophe.Handler(handler,ns,name,type,id);hand.user=false;this.addHandlers.push(hand);return hand;},_onDisconnectTimeout:function()
{Strophe.info("_onDisconnectTimeout was called");var req;while(this._requests.length>0){req=this._requests.pop();req.abort=true;req.xhr.abort();req.xhr.onreadystatechange=function(){};}
this._doDisconnect();return false;},_onIdle:function()
{var i,thand,since,newList;while(this.addTimeds.length>0){this.timedHandlers.push(this.addTimeds.pop());}
while(this.removeTimeds.length>0){thand=this.removeTimeds.pop();i=this.timedHandlers.indexOf(thand);if(i>=0){this.timedHandlers.splice(i,1);}}
var now=new Date().getTime();newList=[];for(i=0;i<this.timedHandlers.length;i++){thand=this.timedHandlers[i];since=thand.lastCalled+thand.period;if(since-now<=0){if(thand.run()){newList.push(thand);}}else{newList.push(thand);}}
this.timedHandlers=newList;var body,time_elapsed;if(this.authenticated&&this._requests.length===0&&this._data.length===0&&!this.disconnecting){}
if(this._requests.length<2&&this._data.length>0&&!this.paused){body=this._buildBody();for(i=0;i<this._data.length;i++){if(this._data[i]!==null){if(this._data[i]==="restart"){body.attrs({to:this.domain,"xml:lang":"en","xmpp:restart":"true","xmlns:xmpp":Strophe.NS.BOSH});}else{body.cnode(this._data[i]).up();}}}
delete this._data;this._data=[];this._requests.push(new Strophe.Request(body.tree(),this._onRequestStateChange.bind(this).prependArg(this._dataRecv.bind(this)),body.tree().getAttribute("rid")));this._processRequest(this._requests.length-1);}
if(this._requests.length>0){time_elapsed=this._requests[0].age();if(this._requests[0].dead!==null){if(this._requests[0].timeDead()>Math.floor(Strophe.SECONDARY_TIMEOUT*this.wait)){this._throttledRequestHandler();}}
if(time_elapsed>Math.floor(Strophe.TIMEOUT*this.wait)){Strophe.warn("Request "+
this._requests[0].id+" timed out, over "+Math.floor(Strophe.TIMEOUT*this.wait)+" seconds since last activity");this._throttledRequestHandler();}}
clearTimeout(this._idleTimeout);this._idleTimeout=setTimeout(this._onIdle.bind(this),100);}};if(callback){callback(Strophe,$build,$msg,$iq,$pres);}})(function(){window.Strophe=arguments[0];window.$build=arguments[1];window.$msg=arguments[2];window.$iq=arguments[3];window.$pres=arguments[4];});
String.prototype.parseColor=function(){var color='#';if(this.slice(0,4)=='rgb('){var cols=this.slice(4,this.length-1).split(',');var i=0;do{color+=parseInt(cols[i]).toColorPart()}while(++i<3);}else{if(this.slice(0,1)=='#'){if(this.length==4)for(var i=1;i<4;i++)color+=(this.charAt(i)+this.charAt(i)).toLowerCase();if(this.length==7)color=this.toLowerCase();}}
return(color.length==7?color:(arguments[0]||this));};Element.collectTextNodes=function(element){return $A($(element).childNodes).collect(function(node){return(node.nodeType==3?node.nodeValue:(node.hasChildNodes()?Element.collectTextNodes(node):''));}).flatten().join('');};Element.collectTextNodesIgnoreClass=function(element,className){return $A($(element).childNodes).collect(function(node){return(node.nodeType==3?node.nodeValue:((node.hasChildNodes()&&!Element.hasClassName(node,className))?Element.collectTextNodesIgnoreClass(node,className):''));}).flatten().join('');};Element.setContentZoom=function(element,percent){element=$(element);element.setStyle({fontSize:(percent/100)+'em'});if(Prototype.Browser.WebKit)window.scrollBy(0,0);return element;};Element.getInlineOpacity=function(element){return $(element).style.opacity||'';};Element.forceRerendering=function(element){try{element=$(element);var n=document.createTextNode(' ');element.appendChild(n);element.removeChild(n);}catch(e){}};var Effect={_elementDoesNotExistError:{name:'ElementDoesNotExistError',message:'The specified DOM element does not exist, but is required for this effect to operate'},Transitions:{linear:Prototype.K,sinoidal:function(pos){return(-Math.cos(pos*Math.PI)/2)+.5;},reverse:function(pos){return 1-pos;},flicker:function(pos){var pos=((-Math.cos(pos*Math.PI)/4)+.75)+Math.random()/4;return pos>1?1:pos;},wobble:function(pos){return(-Math.cos(pos*Math.PI*(9*pos))/2)+.5;},pulse:function(pos,pulses){return(-Math.cos((pos*((pulses||5)-.5)*2)*Math.PI)/2)+.5;},spring:function(pos){return 1-(Math.cos(pos*4.5*Math.PI)*Math.exp(-pos*6));},none:function(pos){return 0;},full:function(pos){return 1;}},DefaultOptions:{duration:1.0,fps:100,sync:false,from:0.0,to:1.0,delay:0.0,queue:'parallel'},tagifyText:function(element){var tagifyStyle='position:relative';if(Prototype.Browser.IE)tagifyStyle+=';zoom:1';element=$(element);$A(element.childNodes).each(function(child){if(child.nodeType==3){child.nodeValue.toArray().each(function(character){element.insertBefore(new Element('span',{style:tagifyStyle}).update(character==' '?String.fromCharCode(160):character),child);});Element.remove(child);}});},multiple:function(element,effect){var elements;if(((typeof element=='object')||Object.isFunction(element))&&(element.length))
elements=element;else
elements=$(element).childNodes;var options=Object.extend({speed:0.1,delay:0.0},arguments[2]||{});var masterDelay=options.delay;$A(elements).each(function(element,index){new effect(element,Object.extend(options,{delay:index*options.speed+masterDelay}));});},PAIRS:{'slide':['SlideDown','SlideUp'],'blind':['BlindDown','BlindUp'],'appear':['Appear','Fade']},toggle:function(element,effect,options){element=$(element);effect=(effect||'appear').toLowerCase();return Effect[Effect.PAIRS[effect][element.visible()?1:0]](element,Object.extend({queue:{position:'end',scope:(element.id||'global'),limit:1}},options||{}));}};Effect.DefaultOptions.transition=Effect.Transitions.sinoidal;Effect.ScopedQueue=Class.create(Enumerable,{initialize:function(){this.effects=[];this.interval=null;},_each:function(iterator){this.effects._each(iterator);},add:function(effect){var timestamp=new Date().getTime();var position=Object.isString(effect.options.queue)?effect.options.queue:effect.options.queue.position;switch(position){case'front':this.effects.findAll(function(e){return e.state=='idle'}).each(function(e){e.startOn+=effect.finishOn;e.finishOn+=effect.finishOn;});break;case'with-last':timestamp=this.effects.pluck('startOn').max()||timestamp;break;case'end':timestamp=this.effects.pluck('finishOn').max()||timestamp;break;}
effect.startOn+=timestamp;effect.finishOn+=timestamp;if(!effect.options.queue.limit||(this.effects.length<effect.options.queue.limit))
this.effects.push(effect);if(!this.interval)
this.interval=setInterval(this.loop.bind(this),15);},remove:function(effect){this.effects=this.effects.reject(function(e){return e==effect});if(this.effects.length==0){clearInterval(this.interval);this.interval=null;}},loop:function(){var timePos=new Date().getTime();for(var i=0,len=this.effects.length;i<len;i++)
this.effects[i]&&this.effects[i].loop(timePos);}});Effect.Queues={instances:$H(),get:function(queueName){if(!Object.isString(queueName))return queueName;return this.instances.get(queueName)||this.instances.set(queueName,new Effect.ScopedQueue());}};Effect.Queue=Effect.Queues.get('global');Effect.Base=Class.create({position:null,start:function(options){if(options&&options.transition===false)options.transition=Effect.Transitions.linear;this.options=Object.extend(Object.extend({},Effect.DefaultOptions),options||{});this.currentFrame=0;this.state='idle';this.startOn=this.options.delay*1000;this.finishOn=this.startOn+(this.options.duration*1000);this.fromToDelta=this.options.to-this.options.from;this.totalTime=this.finishOn-this.startOn;this.totalFrames=this.options.fps*this.options.duration;this.render=(function(){function dispatch(effect,eventName){if(effect.options[eventName+'Internal'])
effect.options[eventName+'Internal'](effect);if(effect.options[eventName])
effect.options[eventName](effect);}
return function(pos){if(this.state==="idle"){this.state="running";dispatch(this,'beforeSetup');if(this.setup)this.setup();dispatch(this,'afterSetup');}
if(this.state==="running"){pos=(this.options.transition(pos)*this.fromToDelta)+this.options.from;this.position=pos;dispatch(this,'beforeUpdate');if(this.update)this.update(pos);dispatch(this,'afterUpdate');}};})();this.event('beforeStart');if(!this.options.sync)
Effect.Queues.get(Object.isString(this.options.queue)?'global':this.options.queue.scope).add(this);},loop:function(timePos){if(timePos>=this.startOn){if(timePos>=this.finishOn){this.render(1.0);this.cancel();this.event('beforeFinish');if(this.finish)this.finish();this.event('afterFinish');return;}
var pos=(timePos-this.startOn)/this.totalTime,frame=(pos*this.totalFrames).round();if(frame>this.currentFrame){this.render(pos);this.currentFrame=frame;}}},cancel:function(){if(!this.options.sync)
Effect.Queues.get(Object.isString(this.options.queue)?'global':this.options.queue.scope).remove(this);this.state='finished';},event:function(eventName){if(this.options[eventName+'Internal'])this.options[eventName+'Internal'](this);if(this.options[eventName])this.options[eventName](this);},inspect:function(){var data=$H();for(property in this)
if(!Object.isFunction(this[property]))data.set(property,this[property]);return'#<Effect:'+data.inspect()+',options:'+$H(this.options).inspect()+'>';}});Effect.Parallel=Class.create(Effect.Base,{initialize:function(effects){this.effects=effects||[];this.start(arguments[1]);},update:function(position){this.effects.invoke('render',position);},finish:function(position){this.effects.each(function(effect){effect.render(1.0);effect.cancel();effect.event('beforeFinish');if(effect.finish)effect.finish(position);effect.event('afterFinish');});}});Effect.Tween=Class.create(Effect.Base,{initialize:function(object,from,to){object=Object.isString(object)?$(object):object;var args=$A(arguments),method=args.last(),options=args.length==5?args[3]:null;this.method=Object.isFunction(method)?method.bind(object):Object.isFunction(object[method])?object[method].bind(object):function(value){object[method]=value};this.start(Object.extend({from:from,to:to},options||{}));},update:function(position){this.method(position);}});Effect.Event=Class.create(Effect.Base,{initialize:function(){this.start(Object.extend({duration:0},arguments[0]||{}));},update:Prototype.emptyFunction});Effect.Opacity=Class.create(Effect.Base,{initialize:function(element){this.element=$(element);if(!this.element)throw(Effect._elementDoesNotExistError);if(Prototype.Browser.IE&&(!this.element.currentStyle.hasLayout))
this.element.setStyle({zoom:1});var options=Object.extend({from:this.element.getOpacity()||0.0,to:1.0},arguments[1]||{});this.start(options);},update:function(position){this.element.setOpacity(position);}});Effect.Move=Class.create(Effect.Base,{initialize:function(element){this.element=$(element);if(!this.element)throw(Effect._elementDoesNotExistError);var options=Object.extend({x:0,y:0,mode:'relative'},arguments[1]||{});this.start(options);},setup:function(){this.element.makePositioned();this.originalLeft=parseFloat(this.element.getStyle('left')||'0');this.originalTop=parseFloat(this.element.getStyle('top')||'0');if(this.options.mode=='absolute'){this.options.x=this.options.x-this.originalLeft;this.options.y=this.options.y-this.originalTop;}},update:function(position){this.element.setStyle({left:(this.options.x*position+this.originalLeft).round()+'px',top:(this.options.y*position+this.originalTop).round()+'px'});}});Effect.MoveBy=function(element,toTop,toLeft){return new Effect.Move(element,Object.extend({x:toLeft,y:toTop},arguments[3]||{}));};Effect.Scale=Class.create(Effect.Base,{initialize:function(element,percent){this.element=$(element);if(!this.element)throw(Effect._elementDoesNotExistError);var options=Object.extend({scaleX:true,scaleY:true,scaleContent:true,scaleFromCenter:false,scaleMode:'box',scaleFrom:100.0,scaleTo:percent},arguments[2]||{});this.start(options);},setup:function(){this.restoreAfterFinish=this.options.restoreAfterFinish||false;this.elementPositioning=this.element.getStyle('position');this.originalStyle={};['top','left','width','height','fontSize'].each(function(k){this.originalStyle[k]=this.element.style[k];}.bind(this));this.originalTop=this.element.offsetTop;this.originalLeft=this.element.offsetLeft;var fontSize=this.element.getStyle('font-size')||'100%';['em','px','%','pt'].each(function(fontSizeType){if(fontSize.indexOf(fontSizeType)>0){this.fontSize=parseFloat(fontSize);this.fontSizeType=fontSizeType;}}.bind(this));this.factor=(this.options.scaleTo-this.options.scaleFrom)/100;this.dims=null;if(this.options.scaleMode=='box')
this.dims=[this.element.offsetHeight,this.element.offsetWidth];if(/^content/.test(this.options.scaleMode))
this.dims=[this.element.scrollHeight,this.element.scrollWidth];if(!this.dims)
this.dims=[this.options.scaleMode.originalHeight,this.options.scaleMode.originalWidth];},update:function(position){var currentScale=(this.options.scaleFrom/100.0)+(this.factor*position);if(this.options.scaleContent&&this.fontSize)
this.element.setStyle({fontSize:this.fontSize*currentScale+this.fontSizeType});this.setDimensions(this.dims[0]*currentScale,this.dims[1]*currentScale);},finish:function(position){if(this.restoreAfterFinish)this.element.setStyle(this.originalStyle);},setDimensions:function(height,width){var d={};if(this.options.scaleX)d.width=width.round()+'px';if(this.options.scaleY)d.height=height.round()+'px';if(this.options.scaleFromCenter){var topd=(height-this.dims[0])/2;var leftd=(width-this.dims[1])/2;if(this.elementPositioning=='absolute'){if(this.options.scaleY)d.top=this.originalTop-topd+'px';if(this.options.scaleX)d.left=this.originalLeft-leftd+'px';}else{if(this.options.scaleY)d.top=-topd+'px';if(this.options.scaleX)d.left=-leftd+'px';}}
this.element.setStyle(d);}});Effect.Highlight=Class.create(Effect.Base,{initialize:function(element){this.element=$(element);if(!this.element)throw(Effect._elementDoesNotExistError);var options=Object.extend({startcolor:'#ffff99'},arguments[1]||{});this.start(options);},setup:function(){if(this.element.getStyle('display')=='none'){this.cancel();return;}
this.oldStyle={};if(!this.options.keepBackgroundImage){this.oldStyle.backgroundImage=this.element.getStyle('background-image');this.element.setStyle({backgroundImage:'none'});}
if(!this.options.endcolor)
this.options.endcolor=this.element.getStyle('background-color').parseColor('#ffffff');if(!this.options.restorecolor)
this.options.restorecolor=this.element.getStyle('background-color');this._base=$R(0,2).map(function(i){return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16)}.bind(this));this._delta=$R(0,2).map(function(i){return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i]}.bind(this));},update:function(position){this.element.setStyle({backgroundColor:$R(0,2).inject('#',function(m,v,i){return m+((this._base[i]+(this._delta[i]*position)).round().toColorPart());}.bind(this))});},finish:function(){this.element.setStyle(Object.extend(this.oldStyle,{backgroundColor:this.options.restorecolor}));}});Effect.ScrollTo=function(element){var options=arguments[1]||{},scrollOffsets=document.viewport.getScrollOffsets(),elementOffsets=$(element).cumulativeOffset();if(options.offset)elementOffsets[1]+=options.offset;return new Effect.Tween(null,scrollOffsets.top,elementOffsets[1],options,function(p){scrollTo(scrollOffsets.left,p.round());});};Effect.Fade=function(element){element=$(element);var oldOpacity=element.getInlineOpacity();var options=Object.extend({from:element.getOpacity()||1.0,to:0.0,afterFinishInternal:function(effect){if(effect.options.to!=0)return;effect.element.hide().setStyle({opacity:oldOpacity});}},arguments[1]||{});return new Effect.Opacity(element,options);};Effect.Appear=function(element){element=$(element);var options=Object.extend({from:(element.getStyle('display')=='none'?0.0:element.getOpacity()||0.0),to:1.0,afterFinishInternal:function(effect){effect.element.forceRerendering();},beforeSetup:function(effect){effect.element.setOpacity(effect.options.from).show();}},arguments[1]||{});return new Effect.Opacity(element,options);};Effect.Puff=function(element){element=$(element);var oldStyle={opacity:element.getInlineOpacity(),position:element.getStyle('position'),top:element.style.top,left:element.style.left,width:element.style.width,height:element.style.height};return new Effect.Parallel([new Effect.Scale(element,200,{sync:true,scaleFromCenter:true,scaleContent:true,restoreAfterFinish:true}),new Effect.Opacity(element,{sync:true,to:0.0})],Object.extend({duration:1.0,beforeSetupInternal:function(effect){Position.absolutize(effect.effects[0].element);},afterFinishInternal:function(effect){effect.effects[0].element.hide().setStyle(oldStyle);}},arguments[1]||{}));};Effect.BlindUp=function(element){element=$(element);element.makeClipping();return new Effect.Scale(element,0,Object.extend({scaleContent:false,scaleX:false,restoreAfterFinish:true,afterFinishInternal:function(effect){effect.element.hide().undoClipping();}},arguments[1]||{}));};Effect.BlindDown=function(element){element=$(element);var elementDimensions=element.getDimensions();return new Effect.Scale(element,100,Object.extend({scaleContent:false,scaleX:false,scaleFrom:0,scaleMode:{originalHeight:elementDimensions.height,originalWidth:elementDimensions.width},restoreAfterFinish:true,afterSetup:function(effect){effect.element.makeClipping().setStyle({height:'0px'}).show();},afterFinishInternal:function(effect){effect.element.undoClipping();}},arguments[1]||{}));};Effect.SwitchOff=function(element){element=$(element);var oldOpacity=element.getInlineOpacity();return new Effect.Appear(element,Object.extend({duration:0.4,from:0,transition:Effect.Transitions.flicker,afterFinishInternal:function(effect){new Effect.Scale(effect.element,1,{duration:0.3,scaleFromCenter:true,scaleX:false,scaleContent:false,restoreAfterFinish:true,beforeSetup:function(effect){effect.element.makePositioned().makeClipping();},afterFinishInternal:function(effect){effect.element.hide().undoClipping().undoPositioned().setStyle({opacity:oldOpacity});}});}},arguments[1]||{}));};Effect.DropOut=function(element){element=$(element);var oldStyle={top:element.getStyle('top'),left:element.getStyle('left'),opacity:element.getInlineOpacity()};return new Effect.Parallel([new Effect.Move(element,{x:0,y:100,sync:true}),new Effect.Opacity(element,{sync:true,to:0.0})],Object.extend({duration:0.5,beforeSetup:function(effect){effect.effects[0].element.makePositioned();},afterFinishInternal:function(effect){effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle);}},arguments[1]||{}));};Effect.Shake=function(element){element=$(element);var options=Object.extend({distance:20,duration:0.5},arguments[1]||{});var distance=parseFloat(options.distance);var split=parseFloat(options.duration)/10.0;var oldStyle={top:element.getStyle('top'),left:element.getStyle('left')};return new Effect.Move(element,{x:distance,y:0,duration:split,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:-distance*2,y:0,duration:split*2,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:distance*2,y:0,duration:split*2,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:-distance*2,y:0,duration:split*2,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:distance*2,y:0,duration:split*2,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:-distance,y:0,duration:split,afterFinishInternal:function(effect){effect.element.undoPositioned().setStyle(oldStyle);}});}});}});}});}});}});};Effect.SlideDown=function(element){element=$(element).cleanWhitespace();var oldInnerBottom=element.down().getStyle('bottom');var elementDimensions=element.getDimensions();return new Effect.Scale(element,100,Object.extend({scaleContent:false,scaleX:false,scaleFrom:window.opera?0:1,scaleMode:{originalHeight:elementDimensions.height,originalWidth:elementDimensions.width},restoreAfterFinish:true,afterSetup:function(effect){effect.element.makePositioned();effect.element.down().makePositioned();if(window.opera)effect.element.setStyle({top:''});effect.element.makeClipping().setStyle({height:'0px'}).show();},afterUpdateInternal:function(effect){effect.element.down().setStyle({bottom:(effect.dims[0]-effect.element.clientHeight)+'px'});},afterFinishInternal:function(effect){effect.element.undoClipping().undoPositioned();effect.element.down().undoPositioned().setStyle({bottom:oldInnerBottom});}},arguments[1]||{}));};Effect.SlideUp=function(element){if(!$(element)){return;}
element=$(element).cleanWhitespace();var oldInnerBottom=element.down().getStyle('bottom');var elementDimensions=element.getDimensions();return new Effect.Scale(element,window.opera?0:1,Object.extend({scaleContent:false,scaleX:false,scaleMode:'box',scaleFrom:100,scaleMode:{originalHeight:elementDimensions.height,originalWidth:elementDimensions.width},restoreAfterFinish:true,afterSetup:function(effect){effect.element.makePositioned();effect.element.down().makePositioned();if(window.opera)effect.element.setStyle({top:''});effect.element.makeClipping().show();},afterUpdateInternal:function(effect){effect.element.down().setStyle({bottom:(effect.dims[0]-effect.element.clientHeight)+'px'});},afterFinishInternal:function(effect){effect.element.hide().undoClipping().undoPositioned();effect.element.down().undoPositioned().setStyle({bottom:oldInnerBottom});}},arguments[1]||{}));};Effect.Squish=function(element){return new Effect.Scale(element,window.opera?1:0,{restoreAfterFinish:true,beforeSetup:function(effect){effect.element.makeClipping();},afterFinishInternal:function(effect){effect.element.hide().undoClipping();}});};Effect.Grow=function(element){element=$(element);var options=Object.extend({direction:'center',moveTransition:Effect.Transitions.sinoidal,scaleTransition:Effect.Transitions.sinoidal,opacityTransition:Effect.Transitions.full},arguments[1]||{});var oldStyle={top:element.style.top,left:element.style.left,height:element.style.height,width:element.style.width,opacity:element.getInlineOpacity()};var dims=element.getDimensions();var initialMoveX,initialMoveY;var moveX,moveY;switch(options.direction){case'top-left':initialMoveX=initialMoveY=moveX=moveY=0;break;case'top-right':initialMoveX=dims.width;initialMoveY=moveY=0;moveX=-dims.width;break;case'bottom-left':initialMoveX=moveX=0;initialMoveY=dims.height;moveY=-dims.height;break;case'bottom-right':initialMoveX=dims.width;initialMoveY=dims.height;moveX=-dims.width;moveY=-dims.height;break;case'center':initialMoveX=dims.width/2;initialMoveY=dims.height/2;moveX=-dims.width/2;moveY=-dims.height/2;break;}
return new Effect.Move(element,{x:initialMoveX,y:initialMoveY,duration:0.01,beforeSetup:function(effect){effect.element.hide().makeClipping().makePositioned();},afterFinishInternal:function(effect){new Effect.Parallel([new Effect.Opacity(effect.element,{sync:true,to:1.0,from:0.0,transition:options.opacityTransition}),new Effect.Move(effect.element,{x:moveX,y:moveY,sync:true,transition:options.moveTransition}),new Effect.Scale(effect.element,100,{scaleMode:{originalHeight:dims.height,originalWidth:dims.width},sync:true,scaleFrom:window.opera?1:0,transition:options.scaleTransition,restoreAfterFinish:true})],Object.extend({beforeSetup:function(effect){effect.effects[0].element.setStyle({height:'0px'}).show();},afterFinishInternal:function(effect){effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle);}},options));}});};Effect.Shrink=function(element){element=$(element);var options=Object.extend({direction:'center',moveTransition:Effect.Transitions.sinoidal,scaleTransition:Effect.Transitions.sinoidal,opacityTransition:Effect.Transitions.none},arguments[1]||{});var oldStyle={top:element.style.top,left:element.style.left,height:element.style.height,width:element.style.width,opacity:element.getInlineOpacity()};var dims=element.getDimensions();var moveX,moveY;switch(options.direction){case'top-left':moveX=moveY=0;break;case'top-right':moveX=dims.width;moveY=0;break;case'bottom-left':moveX=0;moveY=dims.height;break;case'bottom-right':moveX=dims.width;moveY=dims.height;break;case'center':moveX=dims.width/2;moveY=dims.height/2;break;}
return new Effect.Parallel([new Effect.Opacity(element,{sync:true,to:0.0,from:1.0,transition:options.opacityTransition}),new Effect.Scale(element,window.opera?1:0,{sync:true,transition:options.scaleTransition,restoreAfterFinish:true}),new Effect.Move(element,{x:moveX,y:moveY,sync:true,transition:options.moveTransition})],Object.extend({beforeStartInternal:function(effect){effect.effects[0].element.makePositioned().makeClipping();},afterFinishInternal:function(effect){effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle);}},options));};Effect.Pulsate=function(element){element=$(element);var options=arguments[1]||{},oldOpacity=element.getInlineOpacity(),transition=options.transition||Effect.Transitions.linear,reverser=function(pos){return 1-transition((-Math.cos((pos*(options.pulses||5)*2)*Math.PI)/2)+.5);};return new Effect.Opacity(element,Object.extend(Object.extend({duration:2.0,from:0,afterFinishInternal:function(effect){effect.element.setStyle({opacity:oldOpacity});}},options),{transition:reverser}));};Effect.Fold=function(element){element=$(element);var oldStyle={top:element.style.top,left:element.style.left,width:element.style.width,height:element.style.height};element.makeClipping();return new Effect.Scale(element,5,Object.extend({scaleContent:false,scaleX:false,afterFinishInternal:function(effect){new Effect.Scale(element,1,{scaleContent:false,scaleY:false,afterFinishInternal:function(effect){effect.element.hide().undoClipping().setStyle(oldStyle);}});}},arguments[1]||{}));};Effect.Morph=Class.create(Effect.Base,{initialize:function(element){this.element=$(element);if(!this.element)throw(Effect._elementDoesNotExistError);var options=Object.extend({style:{}},arguments[1]||{});if(!Object.isString(options.style))this.style=$H(options.style);else{if(options.style.include(':'))
this.style=options.style.parseStyle();else{this.element.addClassName(options.style);this.style=$H(this.element.getStyles());this.element.removeClassName(options.style);var css=this.element.getStyles();this.style=this.style.reject(function(style){return style.value==css[style.key];});options.afterFinishInternal=function(effect){effect.element.addClassName(effect.options.style);effect.transforms.each(function(transform){effect.element.style[transform.style]='';});};}}
this.start(options);},setup:function(){function parseColor(color){if(!color||['rgba(0, 0, 0, 0)','transparent'].include(color))color='#ffffff';color=color.parseColor();return $R(0,2).map(function(i){return parseInt(color.slice(i*2+1,i*2+3),16);});}
this.transforms=this.style.map(function(pair){var property=pair[0],value=pair[1],unit=null;if(value.parseColor('#zzzzzz')!='#zzzzzz'){value=value.parseColor();unit='color';}else if(property=='opacity'){value=parseFloat(value);if(Prototype.Browser.IE&&(!this.element.currentStyle.hasLayout))
this.element.setStyle({zoom:1});}else if(Element.CSS_LENGTH.test(value)){var components=value.match(/^([\+\-]?[0-9\.]+)(.*)$/);value=parseFloat(components[1]);unit=(components.length==3)?components[2]:null;}
var originalValue=this.element.getStyle(property);return{style:property.camelize(),originalValue:unit=='color'?parseColor(originalValue):parseFloat(originalValue||0),targetValue:unit=='color'?parseColor(value):value,unit:unit};}.bind(this)).reject(function(transform){return((transform.originalValue==transform.targetValue)||(transform.unit!='color'&&(isNaN(transform.originalValue)||isNaN(transform.targetValue))));});},update:function(position){var style={},transform,i=this.transforms.length;while(i--)
style[(transform=this.transforms[i]).style]=transform.unit=='color'?'#'+
(Math.round(transform.originalValue[0]+
(transform.targetValue[0]-transform.originalValue[0])*position)).toColorPart()+
(Math.round(transform.originalValue[1]+
(transform.targetValue[1]-transform.originalValue[1])*position)).toColorPart()+
(Math.round(transform.originalValue[2]+
(transform.targetValue[2]-transform.originalValue[2])*position)).toColorPart():(transform.originalValue+
(transform.targetValue-transform.originalValue)*position).toFixed(3)+
(transform.unit===null?'':transform.unit);this.element.setStyle(style,true);}});Effect.Transform=Class.create({initialize:function(tracks){this.tracks=[];this.options=arguments[1]||{};this.addTracks(tracks);},addTracks:function(tracks){tracks.each(function(track){track=$H(track);var data=track.values().first();this.tracks.push($H({ids:track.keys().first(),effect:Effect.Morph,options:{style:data}}));}.bind(this));return this;},play:function(){return new Effect.Parallel(this.tracks.map(function(track){var ids=track.get('ids'),effect=track.get('effect'),options=track.get('options');var elements=[$(ids)||$$(ids)].flatten();return elements.map(function(e){return new effect(e,Object.extend({sync:true},options))});}).flatten(),this.options);}});Element.CSS_PROPERTIES=$w('backgroundColor backgroundPosition borderBottomColor borderBottomStyle '+'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth '+'borderRightColor borderRightStyle borderRightWidth borderSpacing '+'borderTopColor borderTopStyle borderTopWidth bottom clip color '+'fontSize fontWeight height left letterSpacing lineHeight '+'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+'maxWidth minHeight minWidth opacity outlineColor outlineOffset '+'outlineWidth paddingBottom paddingLeft paddingRight paddingTop '+'right textIndent top width wordSpacing zIndex');Element.CSS_LENGTH=/^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;String.__parseStyleElement=document.createElement('div');String.prototype.parseStyle=function(){var style,styleRules=$H();if(Prototype.Browser.WebKit)
style=new Element('div',{style:this}).style;else{String.__parseStyleElement.innerHTML='<div style="'+this+'"></div>';style=String.__parseStyleElement.childNodes[0].style;}
Element.CSS_PROPERTIES.each(function(property){if(style[property])styleRules.set(property,style[property]);});if(Prototype.Browser.IE&&this.include('opacity'))
styleRules.set('opacity',this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1]);return styleRules;};if(document.defaultView&&document.defaultView.getComputedStyle){Element.getStyles=function(element){var css=document.defaultView.getComputedStyle($(element),null);return Element.CSS_PROPERTIES.inject({},function(styles,property){styles[property]=css[property];return styles;});};}else{Element.getStyles=function(element){element=$(element);var css=element.currentStyle,styles;styles=Element.CSS_PROPERTIES.inject({},function(results,property){results[property]=css[property];return results;});if(!styles.opacity)styles.opacity=element.getOpacity();return styles;};}
Effect.Methods={morph:function(element,style){element=$(element);new Effect.Morph(element,Object.extend({style:style},arguments[2]||{}));return element;},visualEffect:function(element,effect,options){element=$(element);var s=effect.dasherize().camelize(),klass=s.charAt(0).toUpperCase()+s.substring(1);new Effect[klass](element,options);return element;},highlight:function(element,options){element=$(element);new Effect.Highlight(element,options);return element;}};$w('fade appear grow shrink fold blindUp blindDown slideUp slideDown '+'pulsate shake puff squish switchOff dropOut').each(function(effect){Effect.Methods[effect]=function(element,options){element=$(element);Effect[effect.charAt(0).toUpperCase()+effect.substring(1)](element,options);return element;};});$w('getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles').each(function(f){Effect.Methods[f]=Element[f];});Element.addMethods(Effect.Methods);
if(Object.isUndefined(Effect))
throw("dragdrop.js requires including script.aculo.us' effects.js library");var Droppables={drops:[],remove:function(element){this.drops=this.drops.reject(function(d){return d.element==$(element)});},add:function(element){element=$(element);var options=Object.extend({greedy:true,hoverclass:null,tree:false},arguments[1]||{});if(options.containment){options._containers=[];var containment=options.containment;if(Object.isArray(containment)){containment.each(function(c){options._containers.push($(c))});}else{options._containers.push($(containment));}}
if(options.accept)options.accept=[options.accept].flatten();Element.makePositioned(element);options.element=element;this.drops.push(options);},findDeepestChild:function(drops){deepest=drops[0];for(i=1;i<drops.length;++i)
if(Element.isParent(drops[i].element,deepest.element))
deepest=drops[i];return deepest;},isContained:function(element,drop){var containmentNode;if(drop.tree){containmentNode=element.treeNode;}else{containmentNode=element.parentNode;}
return drop._containers.detect(function(c){return containmentNode==c});},isAffected:function(point,element,drop){return((drop.element!=element)&&((!drop._containers)||this.isContained(element,drop))&&((!drop.accept)||(Element.classNames(element).detect(function(v){return drop.accept.include(v)})))&&Position.within(drop.element,point[0],point[1]));},deactivate:function(drop){if(drop.hoverclass)
Element.removeClassName(drop.element,drop.hoverclass);this.last_active=null;},activate:function(drop){if(drop.hoverclass)
Element.addClassName(drop.element,drop.hoverclass);this.last_active=drop;},show:function(point,element){if(!this.drops.length)return;var drop,affected=[];this.drops.each(function(drop){if(Droppables.isAffected(point,element,drop))
affected.push(drop);});if(affected.length>0)
drop=Droppables.findDeepestChild(affected);if(this.last_active&&this.last_active!=drop)this.deactivate(this.last_active);if(drop){Position.within(drop.element,point[0],point[1]);if(drop.onHover)
drop.onHover(element,drop.element,Position.overlap(drop.overlap,drop.element));if(drop!=this.last_active)Droppables.activate(drop);}},fire:function(event,element){if(!this.last_active)return;Position.prepare();if(this.isAffected([Event.pointerX(event),Event.pointerY(event)],element,this.last_active))
if(this.last_active.onDrop){this.last_active.onDrop(element,this.last_active.element,event);return true;}},reset:function(){if(this.last_active)
this.deactivate(this.last_active);}};var Draggables={drags:[],observers:[],register:function(draggable){if(this.drags.length==0){this.eventMouseUp=this.endDrag.bindAsEventListener(this);this.eventMouseMove=this.updateDrag.bindAsEventListener(this);this.eventKeypress=this.keyPress.bindAsEventListener(this);Event.observe(document,"mouseup",this.eventMouseUp);Event.observe(document,"mousemove",this.eventMouseMove);Event.observe(document,"keypress",this.eventKeypress);}
this.drags.push(draggable);},unregister:function(draggable){this.drags=this.drags.reject(function(d){return d==draggable});if(this.drags.length==0){Event.stopObserving(document,"mouseup",this.eventMouseUp);Event.stopObserving(document,"mousemove",this.eventMouseMove);Event.stopObserving(document,"keypress",this.eventKeypress);}},activate:function(draggable){if(draggable.options.delay){this._timeout=setTimeout(function(){Draggables._timeout=null;window.focus();Draggables.activeDraggable=draggable;}.bind(this),draggable.options.delay);}else{window.focus();this.activeDraggable=draggable;}},deactivate:function(){this.activeDraggable=null;},updateDrag:function(event){if(!this.activeDraggable)return;var pointer=[Event.pointerX(event),Event.pointerY(event)];if(this._lastPointer&&(this._lastPointer.inspect()==pointer.inspect()))return;this._lastPointer=pointer;this.activeDraggable.updateDrag(event,pointer);},endDrag:function(event){if(this._timeout){clearTimeout(this._timeout);this._timeout=null;}
if(!this.activeDraggable)return;this._lastPointer=null;this.activeDraggable.endDrag(event);this.activeDraggable=null;},keyPress:function(event){if(this.activeDraggable)
this.activeDraggable.keyPress(event);},addObserver:function(observer){this.observers.push(observer);this._cacheObserverCallbacks();},removeObserver:function(element){this.observers=this.observers.reject(function(o){return o.element==element});this._cacheObserverCallbacks();},notify:function(eventName,draggable,event){if(this[eventName+'Count']>0)
this.observers.each(function(o){if(o[eventName])o[eventName](eventName,draggable,event);});if(draggable.options[eventName])draggable.options[eventName](draggable,event);},_cacheObserverCallbacks:function(){['onStart','onEnd','onDrag'].each(function(eventName){Draggables[eventName+'Count']=Draggables.observers.select(function(o){return o[eventName];}).length;});}};var Draggable=Class.create({initialize:function(element){var defaults={handle:false,reverteffect:function(element,top_offset,left_offset){var dur=Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02;new Effect.Move(element,{x:-left_offset,y:-top_offset,duration:dur,queue:{scope:'_draggable',position:'end'}});},endeffect:function(element){var toOpacity=Object.isNumber(element._opacity)?element._opacity:1.0;new Effect.Opacity(element,{duration:0.2,from:0.7,to:toOpacity,queue:{scope:'_draggable',position:'end'},afterFinish:function(){Draggable._dragging[element]=false}});},zindex:1000,revert:false,quiet:false,scroll:false,scrollSensitivity:20,scrollSpeed:15,snap:false,delay:0};if(!arguments[1]||Object.isUndefined(arguments[1].endeffect))
Object.extend(defaults,{starteffect:function(element){element._opacity=Element.getOpacity(element);Draggable._dragging[element]=true;new Effect.Opacity(element,{duration:0.2,from:element._opacity,to:0.7});}});var options=Object.extend(defaults,arguments[1]||{});this.element=$(element);if(options.handle&&Object.isString(options.handle))
this.handle=this.element.down('.'+options.handle,0);if(!this.handle)this.handle=$(options.handle);if(!this.handle)this.handle=this.element;if(options.scroll&&!options.scroll.scrollTo&&!options.scroll.outerHTML){options.scroll=$(options.scroll);this._isScrollChild=Element.childOf(this.element,options.scroll);}
Element.makePositioned(this.element);this.options=options;this.dragging=false;this.eventMouseDown=this.initDrag.bindAsEventListener(this);Event.observe(this.handle,"mousedown",this.eventMouseDown);Draggables.register(this);},destroy:function(){Event.stopObserving(this.handle,"mousedown",this.eventMouseDown);Draggables.unregister(this);},currentDelta:function(){return([parseInt(Element.getStyle(this.element,'left')||'0'),parseInt(Element.getStyle(this.element,'top')||'0')]);},initDrag:function(event){if(!Object.isUndefined(Draggable._dragging[this.element])&&Draggable._dragging[this.element])return;if(Event.isLeftClick(event)){var src=Event.element(event);if((tag_name=src.tagName.toUpperCase())&&(tag_name=='INPUT'||tag_name=='SELECT'||tag_name=='OPTION'||tag_name=='BUTTON'||tag_name=='TEXTAREA'))return;var pointer=[Event.pointerX(event),Event.pointerY(event)];var pos=this.element.cumulativeOffset();this.offset=[0,1].map(function(i){return(pointer[i]-pos[i])});Draggables.activate(this);Event.stop(event);}},startDrag:function(event){this.dragging=true;if(!this.delta)
this.delta=this.currentDelta();if(this.options.zindex){this.originalZ=parseInt(Element.getStyle(this.element,'z-index')||0);this.element.style.zIndex=this.options.zindex;}
if(this.options.ghosting){this._clone=this.element.cloneNode(true);this._originallyAbsolute=(this.element.getStyle('position')=='absolute');if(!this._originallyAbsolute)
Position.absolutize(this.element);this.element.parentNode.insertBefore(this._clone,this.element);}
if(this.options.scroll){if(this.options.scroll==window){var where=this._getWindowScroll(this.options.scroll);this.originalScrollLeft=where.left;this.originalScrollTop=where.top;}else{this.originalScrollLeft=this.options.scroll.scrollLeft;this.originalScrollTop=this.options.scroll.scrollTop;}}
Draggables.notify('onStart',this,event);if(this.options.starteffect)this.options.starteffect(this.element);},updateDrag:function(event,pointer){if(!this.dragging)this.startDrag(event);if(!this.options.quiet){Position.prepare();Droppables.show(pointer,this.element);}
Draggables.notify('onDrag',this,event);this.draw(pointer);if(this.options.change)this.options.change(this);if(this.options.scroll){this.stopScrolling();var p;if(this.options.scroll==window){with(this._getWindowScroll(this.options.scroll)){p=[left,top,left+width,top+height];}}else{p=Position.page(this.options.scroll);p[0]+=this.options.scroll.scrollLeft+Position.deltaX;p[1]+=this.options.scroll.scrollTop+Position.deltaY;p.push(p[0]+this.options.scroll.offsetWidth);p.push(p[1]+this.options.scroll.offsetHeight);}
var speed=[0,0];if(pointer[0]<(p[0]+this.options.scrollSensitivity))speed[0]=pointer[0]-(p[0]+this.options.scrollSensitivity);if(pointer[1]<(p[1]+this.options.scrollSensitivity))speed[1]=pointer[1]-(p[1]+this.options.scrollSensitivity);if(pointer[0]>(p[2]-this.options.scrollSensitivity))speed[0]=pointer[0]-(p[2]-this.options.scrollSensitivity);if(pointer[1]>(p[3]-this.options.scrollSensitivity))speed[1]=pointer[1]-(p[3]-this.options.scrollSensitivity);this.startScrolling(speed);}
if(Prototype.Browser.WebKit)window.scrollBy(0,0);Event.stop(event);},finishDrag:function(event,success){this.dragging=false;if(this.options.quiet){Position.prepare();var pointer=[Event.pointerX(event),Event.pointerY(event)];Droppables.show(pointer,this.element);}
if(this.options.ghosting){if(!this._originallyAbsolute)
Position.relativize(this.element);delete this._originallyAbsolute;Element.remove(this._clone);this._clone=null;}
var dropped=false;if(success){dropped=Droppables.fire(event,this.element);if(!dropped)dropped=false;}
if(dropped&&this.options.onDropped)this.options.onDropped(this.element);Draggables.notify('onEnd',this,event);var revert=this.options.revert;if(revert&&Object.isFunction(revert))revert=revert(this.element);var d=this.currentDelta();if(revert&&this.options.reverteffect){if(dropped==0||revert!='failure')
this.options.reverteffect(this.element,d[1]-this.delta[1],d[0]-this.delta[0]);}else{this.delta=d;}
if(this.options.zindex)
this.element.style.zIndex=this.originalZ;if(this.options.endeffect)
this.options.endeffect(this.element);Draggables.deactivate(this);Droppables.reset();},keyPress:function(event){if(event.keyCode!=Event.KEY_ESC)return;this.finishDrag(event,false);Event.stop(event);},endDrag:function(event){if(!this.dragging)return;this.stopScrolling();this.finishDrag(event,true);Event.stop(event);},draw:function(point){var pos=this.element.cumulativeOffset();if(this.options.ghosting){var r=Position.realOffset(this.element);pos[0]+=r[0]-Position.deltaX;pos[1]+=r[1]-Position.deltaY;}
var d=this.currentDelta();pos[0]-=d[0];pos[1]-=d[1];if(this.options.scroll&&(this.options.scroll!=window&&this._isScrollChild)){pos[0]-=this.options.scroll.scrollLeft-this.originalScrollLeft;pos[1]-=this.options.scroll.scrollTop-this.originalScrollTop;}
var p=[0,1].map(function(i){return(point[i]-pos[i]-this.offset[i])}.bind(this));if(this.options.snap){if(Object.isFunction(this.options.snap)){p=this.options.snap(p[0],p[1],this);}else{if(Object.isArray(this.options.snap)){p=p.map(function(v,i){return(v/this.options.snap[i]).round()*this.options.snap[i]}.bind(this));}else{p=p.map(function(v){return(v/this.options.snap).round()*this.options.snap}.bind(this));}}}
var style=this.element.style;if((!this.options.constraint)||(this.options.constraint=='horizontal'))
style.left=p[0]+"px";if((!this.options.constraint)||(this.options.constraint=='vertical'))
style.top=p[1]+"px";if(style.visibility=="hidden")style.visibility="";},stopScrolling:function(){if(this.scrollInterval){clearInterval(this.scrollInterval);this.scrollInterval=null;Draggables._lastScrollPointer=null;}},startScrolling:function(speed){if(!(speed[0]||speed[1]))return;this.scrollSpeed=[speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed];this.lastScrolled=new Date();this.scrollInterval=setInterval(this.scroll.bind(this),10);},scroll:function(){var current=new Date();var delta=current-this.lastScrolled;this.lastScrolled=current;if(this.options.scroll==window){with(this._getWindowScroll(this.options.scroll)){if(this.scrollSpeed[0]||this.scrollSpeed[1]){var d=delta/1000;this.options.scroll.scrollTo(left+d*this.scrollSpeed[0],top+d*this.scrollSpeed[1]);}}}else{this.options.scroll.scrollLeft+=this.scrollSpeed[0]*delta/1000;this.options.scroll.scrollTop+=this.scrollSpeed[1]*delta/1000;}
Position.prepare();Droppables.show(Draggables._lastPointer,this.element);Draggables.notify('onDrag',this);if(this._isScrollChild){Draggables._lastScrollPointer=Draggables._lastScrollPointer||$A(Draggables._lastPointer);Draggables._lastScrollPointer[0]+=this.scrollSpeed[0]*delta/1000;Draggables._lastScrollPointer[1]+=this.scrollSpeed[1]*delta/1000;if(Draggables._lastScrollPointer[0]<0)
Draggables._lastScrollPointer[0]=0;if(Draggables._lastScrollPointer[1]<0)
Draggables._lastScrollPointer[1]=0;this.draw(Draggables._lastScrollPointer);}
if(this.options.change)this.options.change(this);},_getWindowScroll:function(w){var T,L,W,H;with(w.document){if(w.document.documentElement&&documentElement.scrollTop){T=documentElement.scrollTop;L=documentElement.scrollLeft;}else if(w.document.body){T=body.scrollTop;L=body.scrollLeft;}
if(w.innerWidth){W=w.innerWidth;H=w.innerHeight;}else if(w.document.documentElement&&documentElement.clientWidth){W=documentElement.clientWidth;H=documentElement.clientHeight;}else{W=body.offsetWidth;H=body.offsetHeight;}}
return{top:T,left:L,width:W,height:H};}});Draggable._dragging={};var SortableObserver=Class.create({initialize:function(element,observer){this.element=$(element);this.observer=observer;this.lastValue=Sortable.serialize(this.element);},onStart:function(){this.lastValue=Sortable.serialize(this.element);},onEnd:function(){Sortable.unmark();if(this.lastValue!=Sortable.serialize(this.element))
this.observer(this.element)}});var Sortable={SERIALIZE_RULE:/^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/,sortables:{},_findRootElement:function(element){while(element.tagName.toUpperCase()!="BODY"){if(element.id&&Sortable.sortables[element.id])return element;element=element.parentNode;}},options:function(element){element=Sortable._findRootElement($(element));if(!element)return;return Sortable.sortables[element.id];},destroy:function(element){element=$(element);var s=Sortable.sortables[element.id];if(s){Draggables.removeObserver(s.element);s.droppables.each(function(d){Droppables.remove(d)});s.draggables.invoke('destroy');delete Sortable.sortables[s.element.id];}},create:function(element){element=$(element);var options=Object.extend({element:element,tag:'li',dropOnEmpty:false,tree:false,treeTag:'ul',overlap:'vertical',constraint:'vertical',containment:element,handle:false,only:false,delay:0,hoverclass:null,ghosting:false,quiet:false,scroll:false,scrollSensitivity:20,scrollSpeed:15,format:this.SERIALIZE_RULE,elements:false,handles:false,onChange:Prototype.emptyFunction,onUpdate:Prototype.emptyFunction},arguments[1]||{});this.destroy(element);var options_for_draggable={revert:true,quiet:options.quiet,scroll:options.scroll,scrollSpeed:options.scrollSpeed,scrollSensitivity:options.scrollSensitivity,delay:options.delay,ghosting:options.ghosting,constraint:options.constraint,handle:options.handle};if(options.starteffect)
options_for_draggable.starteffect=options.starteffect;if(options.reverteffect)
options_for_draggable.reverteffect=options.reverteffect;else
if(options.ghosting)options_for_draggable.reverteffect=function(element){element.style.top=0;element.style.left=0;};if(options.endeffect)
options_for_draggable.endeffect=options.endeffect;if(options.zindex)
options_for_draggable.zindex=options.zindex;var options_for_droppable={overlap:options.overlap,containment:options.containment,tree:options.tree,hoverclass:options.hoverclass,onHover:Sortable.onHover};var options_for_tree={onHover:Sortable.onEmptyHover,overlap:options.overlap,containment:options.containment,hoverclass:options.hoverclass};Element.cleanWhitespace(element);options.draggables=[];options.droppables=[];if(options.dropOnEmpty||options.tree){Droppables.add(element,options_for_tree);options.droppables.push(element);}
(options.elements||this.findElements(element,options)||[]).each(function(e,i){var handle=options.handles?$(options.handles[i]):(options.handle?$(e).select('.'+options.handle)[0]:e);options.draggables.push(new Draggable(e,Object.extend(options_for_draggable,{handle:handle})));Droppables.add(e,options_for_droppable);if(options.tree)e.treeNode=element;options.droppables.push(e);});if(options.tree){(Sortable.findTreeElements(element,options)||[]).each(function(e){Droppables.add(e,options_for_tree);e.treeNode=element;options.droppables.push(e);});}
this.sortables[element.identify()]=options;Draggables.addObserver(new SortableObserver(element,options.onUpdate));},findElements:function(element,options){return Element.findChildren(element,options.only,options.tree?true:false,options.tag);},findTreeElements:function(element,options){return Element.findChildren(element,options.only,options.tree?true:false,options.treeTag);},onHover:function(element,dropon,overlap){if(Element.isParent(dropon,element))return;if(overlap>.33&&overlap<.66&&Sortable.options(dropon).tree){return;}else if(overlap>0.5){Sortable.mark(dropon,'before');if(dropon.previousSibling!=element){var oldParentNode=element.parentNode;element.style.visibility="hidden";dropon.parentNode.insertBefore(element,dropon);if(dropon.parentNode!=oldParentNode)
Sortable.options(oldParentNode).onChange(element);Sortable.options(dropon.parentNode).onChange(element);}}else{Sortable.mark(dropon,'after');var nextElement=dropon.nextSibling||null;if(nextElement!=element){var oldParentNode=element.parentNode;element.style.visibility="hidden";dropon.parentNode.insertBefore(element,nextElement);if(dropon.parentNode!=oldParentNode)
Sortable.options(oldParentNode).onChange(element);Sortable.options(dropon.parentNode).onChange(element);}}},onEmptyHover:function(element,dropon,overlap){var oldParentNode=element.parentNode;var droponOptions=Sortable.options(dropon);if(!Element.isParent(dropon,element)){var index;var children=Sortable.findElements(dropon,{tag:droponOptions.tag,only:droponOptions.only});var child=null;if(children){var offset=Element.offsetSize(dropon,droponOptions.overlap)*(1.0-overlap);for(index=0;index<children.length;index+=1){if(offset-Element.offsetSize(children[index],droponOptions.overlap)>=0){offset-=Element.offsetSize(children[index],droponOptions.overlap);}else if(offset-(Element.offsetSize(children[index],droponOptions.overlap)/2)>=0){child=index+1<children.length?children[index+1]:null;break;}else{child=children[index];break;}}}
dropon.insertBefore(element,child);Sortable.options(oldParentNode).onChange(element);droponOptions.onChange(element);}},unmark:function(){if(Sortable._marker)Sortable._marker.hide();},mark:function(dropon,position){var sortable=Sortable.options(dropon.parentNode);if(sortable&&!sortable.ghosting)return;if(!Sortable._marker){Sortable._marker=($('dropmarker')||Element.extend(document.createElement('DIV'))).hide().addClassName('dropmarker').setStyle({position:'absolute'});document.getElementsByTagName("body").item(0).appendChild(Sortable._marker);}
var offsets=dropon.cumulativeOffset();Sortable._marker.setStyle({left:offsets[0]+'px',top:offsets[1]+'px'});if(position=='after')
if(sortable.overlap=='horizontal')
Sortable._marker.setStyle({left:(offsets[0]+dropon.clientWidth)+'px'});else
Sortable._marker.setStyle({top:(offsets[1]+dropon.clientHeight)+'px'});Sortable._marker.show();},_tree:function(element,options,parent){var children=Sortable.findElements(element,options)||[];for(var i=0;i<children.length;++i){var match=children[i].id.match(options.format);if(!match)continue;var child={id:encodeURIComponent(match?match[1]:null),element:element,parent:parent,children:[],position:parent.children.length,container:$(children[i]).down(options.treeTag)};if(child.container)
this._tree(child.container,options,child);parent.children.push(child);}
return parent;},tree:function(element){element=$(element);var sortableOptions=this.options(element);var options=Object.extend({tag:sortableOptions.tag,treeTag:sortableOptions.treeTag,only:sortableOptions.only,name:element.id,format:sortableOptions.format},arguments[1]||{});var root={id:null,parent:null,children:[],container:element,position:0};return Sortable._tree(element,options,root);},_constructIndex:function(node){var index='';do{if(node.id)index='['+node.position+']'+index;}while((node=node.parent)!=null);return index;},sequence:function(element){element=$(element);var options=Object.extend(this.options(element),arguments[1]||{});return $(this.findElements(element,options)||[]).map(function(item){return item.id.match(options.format)?item.id.match(options.format)[1]:'';});},setSequence:function(element,new_sequence){element=$(element);var options=Object.extend(this.options(element),arguments[2]||{});var nodeMap={};this.findElements(element,options).each(function(n){if(n.id.match(options.format))
nodeMap[n.id.match(options.format)[1]]=[n,n.parentNode];n.parentNode.removeChild(n);});new_sequence.each(function(ident){var n=nodeMap[ident];if(n){n[1].appendChild(n[0]);delete nodeMap[ident];}});},serialize:function(element){element=$(element);var options=Object.extend(Sortable.options(element),arguments[1]||{});var name=encodeURIComponent((arguments[1]&&arguments[1].name)?arguments[1].name:element.id);if(options.tree){return Sortable.tree(element,arguments[1]).children.map(function(item){return[name+Sortable._constructIndex(item)+"[id]="+
encodeURIComponent(item.id)].concat(item.children.map(arguments.callee));}).flatten().join('&');}else{return Sortable.sequence(element,arguments[1]).map(function(item){return name+"[]="+encodeURIComponent(item);}).join('&');}}};Element.isParent=function(child,element){if(!child.parentNode||child==element)return false;if(child.parentNode==element)return true;return Element.isParent(child.parentNode,element);};Element.findChildren=function(element,only,recursive,tagName){if(!element.hasChildNodes())return null;tagName=tagName.toUpperCase();if(only)only=[only].flatten();var elements=[];$A(element.childNodes).each(function(e){if(e.tagName&&e.tagName.toUpperCase()==tagName&&(!only||(Element.classNames(e).detect(function(v){return only.include(v)}))))
elements.push(e);if(recursive){var grandchildren=Element.findChildren(e,only,recursive,tagName);if(grandchildren)elements.push(grandchildren);}});return(elements.length>0?elements.flatten():[]);};Element.offsetSize=function(element,type){return element['offset'+((type=='vertical'||type=='height')?'Height':'Width')];};
var CropDraggable=Class.create(Draggable,{initialize:function(element){this.options=Object.extend({drawMethod:function(){}},arguments[1]||{});this.element=$(element);this.handle=this.element;this.delta=this.currentDelta();this.dragging=false;this.eventMouseDown=this.initDrag.bindAsEventListener(this);Event.observe(this.handle,"mousedown",this.eventMouseDown);Draggables.register(this);},draw:function(point){var pos=Element.cumulativeOffset(this.element),d=this.currentDelta();pos[0]-=d[0];pos[1]-=d[1];var p=[0,1].map(function(i){return(point[i]-pos[i]-this.offset[i]);}.bind(this));this.options.drawMethod(p);}});var Cropper={};Cropper.Img=Class.create({initialize:function(element,options){this.options=Object.extend({ratioDim:{x:0,y:0},minWidth:0,minHeight:0,displayOnInit:false,onEndCrop:Prototype.emptyFunction,captureKeys:true,onloadCoords:null,maxWidth:0,maxHeight:0,autoIncludeCSS:true},options||{});this.img=$(element);this.clickCoords={x:0,y:0};this.dragging=false;this.resizing=false;this.isWebKit=/Konqueror|Safari|KHTML/.test(navigator.userAgent);this.isIE=/MSIE/.test(navigator.userAgent);this.isOpera8=/Opera\s[1-8]/.test(navigator.userAgent);this.ratioX=0;this.ratioY=0;this.attached=false;this.fixedWidth=(this.options.maxWidth>0&&(this.options.minWidth>=this.options.maxWidth));this.fixedHeight=(this.options.maxHeight>0&&(this.options.minHeight>=this.options.maxHeight));if(typeof this.img=='undefined'){return;}
if(this.options.autoIncludeCSS){$$('script').each(function(s){if(s.src.match(/\/cropper([^\/]*)\.js/)){var path=s.src.replace(/\/cropper([^\/]*)\.js.*/,''),style=document.createElement('link');style.rel='stylesheet';style.type='text/css';style.href=path+'/cropper.css';style.media='screen';document.getElementsByTagName('head')[0].appendChild(style);}});}
if(this.options.ratioDim.x>0&&this.options.ratioDim.y>0){var gcd=this.getGCD(this.options.ratioDim.x,this.options.ratioDim.y);this.ratioX=this.options.ratioDim.x/gcd;this.ratioY=this.options.ratioDim.y/gcd;}
this.subInitialize();if(this.img.complete||this.isWebKit){this.onLoad();}else{Event.observe(this.img,'load',this.onLoad.bindAsEventListener(this));}},getGCD:function(a,b){if(b===0){return a;}
return this.getGCD(b,a%b);},onLoad:function(){var cNamePrefix='imgCrop_';var insertPoint=this.img.parentNode;var fixOperaClass='';if(this.isOpera8){fixOperaClass=' opera8';}
this.imgWrap=new Element('div',{'class':cNamePrefix+'wrap'+fixOperaClass});this.north=new Element('div',{'class':cNamePrefix+'overlay '+cNamePrefix+'north'}).insert(new Element('span'));this.east=new Element('div',{'class':cNamePrefix+'overlay '+cNamePrefix+'east'}).insert(new Element('span'));this.south=new Element('div',{'class':cNamePrefix+'overlay '+cNamePrefix+'south'}).insert(new Element('span'));this.west=new Element('div',{'class':cNamePrefix+'overlay '+cNamePrefix+'west'}).insert(new Element('span'));var overlays=[this.north,this.east,this.south,this.west];this.dragArea=new Element('div',{'class':cNamePrefix+'dragArea'});overlays.each(function(o){this.dragArea.insert(o);},this);this.handleN=new Element('div',{'class':cNamePrefix+'handle '+cNamePrefix+'handleN'});this.handleNE=new Element('div',{'class':cNamePrefix+'handle '+cNamePrefix+'handleNE'});this.handleE=new Element('div',{'class':cNamePrefix+'handle '+cNamePrefix+'handleE'});this.handleSE=new Element('div',{'class':cNamePrefix+'handle '+cNamePrefix+'handleSE'});this.handleS=new Element('div',{'class':cNamePrefix+'handle '+cNamePrefix+'handleS'});this.handleSW=new Element('div',{'class':cNamePrefix+'handle '+cNamePrefix+'handleSW'});this.handleW=new Element('div',{'class':cNamePrefix+'handle '+cNamePrefix+'handleW'});this.handleNW=new Element('div',{'class':cNamePrefix+'handle '+cNamePrefix+'handleNW'});this.selArea=new Element('div',{'class':cNamePrefix+'selArea'});[new Element('div',{'class':cNamePrefix+'marqueeHoriz '+cNamePrefix+'marqueeNorth'}).insert(new Element('span')),new Element('div',{'class':cNamePrefix+'marqueeVert '+cNamePrefix+'marqueeEast'}).insert(new Element('span')),new Element('div',{'class':cNamePrefix+'marqueeHoriz '+cNamePrefix+'marqueeSouth'}).insert(new Element('span')),new Element('div',{'class':cNamePrefix+'marqueeVert '+cNamePrefix+'marqueeWest'}).insert(new Element('span')),this.handleN,this.handleNE,this.handleE,this.handleSE,this.handleS,this.handleSW,this.handleW,this.handleNW,new Element('div',{'class':cNamePrefix+'clickArea'})].each(function(o){this.selArea.insert(o);},this);this.imgWrap.appendChild(this.img);this.imgWrap.appendChild(this.dragArea);this.dragArea.appendChild(this.selArea);this.dragArea.appendChild(new Element('div',{'class':cNamePrefix+'clickArea'}));insertPoint.appendChild(this.imgWrap);this.startDragBind=this.startDrag.bindAsEventListener(this);Event.observe(this.dragArea,'mousedown',this.startDragBind);this.onDragBind=this.onDrag.bindAsEventListener(this);Event.observe(document,'mousemove',this.onDragBind);this.endCropBind=this.endCrop.bindAsEventListener(this);Event.observe(document,'mouseup',this.endCropBind);this.resizeBind=this.startResize.bindAsEventListener(this);this.handles=[this.handleN,this.handleNE,this.handleE,this.handleSE,this.handleS,this.handleSW,this.handleW,this.handleNW];this.registerHandles(true);if(this.options.captureKeys){this.keysBind=this.handleKeys.bindAsEventListener(this);Event.observe(document,'keypress',this.keysBind);}
var x=new CropDraggable(this.selArea,{drawMethod:this.moveArea.bindAsEventListener(this)});this.setParams();},registerHandles:function(registration){for(var i=0;i<this.handles.length;i++){var handle=$(this.handles[i]);if(registration){var hideHandle=false;if(this.fixedWidth&&this.fixedHeight){hideHandle=true;}else if(this.fixedWidth||this.fixedHeight){var isCornerHandle=handle.className.match(/([S|N][E|W])$/),isWidthHandle=handle.className.match(/(E|W)$/),isHeightHandle=handle.className.match(/(N|S)$/);if(isCornerHandle||(this.fixedWidth&&isWidthHandle)||(this.fixedHeight&&isHeightHandle)){hideHandle=true;}}
if(hideHandle){handle.hide();}else{Event.observe(handle,'mousedown',this.resizeBind);}}else{handle.show();Event.stopObserving(handle,'mousedown',this.resizeBind);}}},setParams:function(){this.imgW=this.img.width;this.imgH=this.img.height;$(this.north).setStyle({height:0});$(this.east).setStyle({width:0,height:0});$(this.south).setStyle({height:0});$(this.west).setStyle({width:0,height:0});$(this.imgWrap).setStyle({'width':this.imgW+'px','height':this.imgH+'px'});$(this.selArea).hide();var startCoords={x1:0,y1:0,x2:0,y2:0},validCoordsSet=false;if(this.options.onloadCoords!==null){startCoords=this.cloneCoords(this.options.onloadCoords);validCoordsSet=true;}else if(this.options.ratioDim.x>0&&this.options.ratioDim.y>0){startCoords.x1=Math.ceil((this.imgW-this.options.ratioDim.x)/2);startCoords.y1=Math.ceil((this.imgH-this.options.ratioDim.y)/2);startCoords.x2=startCoords.x1+this.options.ratioDim.x;startCoords.y2=startCoords.y1+this.options.ratioDim.y;validCoordsSet=true;}
this.setAreaCoords(startCoords,false,false,1);if(this.options.displayOnInit&&validCoordsSet){this.selArea.show();this.drawArea();this.endCrop();}
this.attached=true;},remove:function(){if(this.attached){this.attached=false;if(this.imgWrap&&this.imgWrap.parentNode){this.imgWrap.parentNode.insertBefore(this.img,this.imgWrap);this.imgWrap.parentNode.removeChild(this.imgWrap);}
Event.stopObserving(this.dragArea,'mousedown',this.startDragBind);Event.stopObserving(document,'mousemove',this.onDragBind);Event.stopObserving(document,'mouseup',this.endCropBind);this.registerHandles(false);if(this.options.captureKeys){Event.stopObserving(document,'keypress',this.keysBind);}}},reset:function(){if(!this.attached){this.onLoad();}else{this.setParams();}
this.endCrop();},handleKeys:function(e){var dir={x:0,y:0};if(!this.dragging){switch(e.keyCode){case(37):dir.x=-1;break;case(38):dir.y=-1;break;case(39):dir.x=1;break;case(40):dir.y=1;break;}
if(dir.x!==0||dir.y!==0){if(e.shiftKey){dir.x*=10;dir.y*=10;}
this.moveArea([this.areaCoords.x1+dir.x,this.areaCoords.y1+dir.y]);this.endCrop();Event.stop(e);}}},calcW:function(){return(this.areaCoords.x2-this.areaCoords.x1);},calcH:function(){return(this.areaCoords.y2-this.areaCoords.y1);},moveArea:function(point){this.setAreaCoords({x1:point[0],y1:point[1],x2:point[0]+this.calcW(),y2:point[1]+this.calcH()},true,false);this.drawArea();},cloneCoords:function(coords){return{x1:coords.x1,y1:coords.y1,x2:coords.x2,y2:coords.y2};},setAreaCoords:function(coords,moving,square,direction,resizeHandle){if(moving){var targW=coords.x2-coords.x1,targH=coords.y2-coords.y1;if(coords.x1<0){coords.x1=0;coords.x2=targW;}
if(coords.y1<0){coords.y1=0;coords.y2=targH;}
if(coords.x2>this.imgW){coords.x2=this.imgW;coords.x1=this.imgW-targW;}
if(coords.y2>this.imgH){coords.y2=this.imgH;coords.y1=this.imgH-targH;}}else{if(coords.x1<0){coords.x1=0;}
if(coords.y1<0){coords.y1=0;}
if(coords.x2>this.imgW){coords.x2=this.imgW;}
if(coords.y2>this.imgH){coords.y2=this.imgH;}
if(direction!==null){if(this.ratioX>0){this.applyRatio(coords,{x:this.ratioX,y:this.ratioY},direction,resizeHandle);}else if(square){this.applyRatio(coords,{x:1,y:1},direction,resizeHandle);}
var mins=[this.options.minWidth,this.options.minHeight],maxs=[this.options.maxWidth,this.options.maxHeight];if(mins[0]>0||mins[1]>0||maxs[0]>0||maxs[1]>0){var coordsTransX={a1:coords.x1,a2:coords.x2},coordsTransY={a1:coords.y1,a2:coords.y2},boundsX={min:0,max:this.imgW},boundsY={min:0,max:this.imgH};if((mins[0]!==0||mins[1]!==0)&&square){if(mins[0]>0){mins[1]=mins[0];}else if(mins[1]>0){mins[0]=mins[1];}}
if((maxs[0]!==0||maxs[0]!==0)&&square){if(maxs[0]>0&&maxs[0]<=maxs[1]){maxs[1]=maxs[0];}else if(maxs[1]>0&&maxs[1]<=maxs[0]){maxs[0]=maxs[1];}}
if(mins[0]>0){this.applyDimRestriction(coordsTransX,mins[0],direction.x,boundsX,'min');}
if(mins[1]>1){this.applyDimRestriction(coordsTransY,mins[1],direction.y,boundsY,'min');}
if(maxs[0]>0){this.applyDimRestriction(coordsTransX,maxs[0],direction.x,boundsX,'max');}
if(maxs[1]>1){this.applyDimRestriction(coordsTransY,maxs[1],direction.y,boundsY,'max');}
coords={x1:coordsTransX.a1,y1:coordsTransY.a1,x2:coordsTransX.a2,y2:coordsTransY.a2};}}}
this.areaCoords=coords;},applyDimRestriction:function(coords,val,direction,bounds,type){var check;if(type=='min'){check=((coords.a2-coords.a1)<val);}
else{check=((coords.a2-coords.a1)>val);}
if(check){if(direction==1){coords.a2=coords.a1+val;}
else{coords.a1=coords.a2-val;}
if(coords.a1<bounds.min){coords.a1=bounds.min;coords.a2=val;}else if(coords.a2>bounds.max){coords.a1=bounds.max-val;coords.a2=bounds.max;}}},applyRatio:function(coords,ratio,direction,resizeHandle){var newCoords;if(resizeHandle=='N'||resizeHandle=='S'){newCoords=this.applyRatioToAxis({a1:coords.y1,b1:coords.x1,a2:coords.y2,b2:coords.x2},{a:ratio.y,b:ratio.x},{a:direction.y,b:direction.x},{min:0,max:this.imgW});coords.x1=newCoords.b1;coords.y1=newCoords.a1;coords.x2=newCoords.b2;coords.y2=newCoords.a2;}else{newCoords=this.applyRatioToAxis({a1:coords.x1,b1:coords.y1,a2:coords.x2,b2:coords.y2},{a:ratio.x,b:ratio.y},{a:direction.x,b:direction.y},{min:0,max:this.imgH});coords.x1=newCoords.a1;coords.y1=newCoords.b1;coords.x2=newCoords.a2;coords.y2=newCoords.b2;}},applyRatioToAxis:function(coords,ratio,direction,bounds){var newCoords=Object.extend(coords,{}),calcDimA=newCoords.a2-newCoords.a1,targDimB=Math.floor(calcDimA*ratio.b/ratio.a),targB=null,targDimA=null,calcDimB=null;if(direction.b==1){targB=newCoords.b1+targDimB;if(targB>bounds.max){targB=bounds.max;calcDimB=targB-newCoords.b1;}
newCoords.b2=targB;}else{targB=newCoords.b2-targDimB;if(targB<bounds.min){targB=bounds.min;calcDimB=targB+newCoords.b2;}
newCoords.b1=targB;}
if(calcDimB!==null){targDimA=Math.floor(calcDimB*ratio.a/ratio.b);if(direction.a==1){newCoords.a2=newCoords.a1+targDimA;}
else{newCoords.a1=newCoords.a1=newCoords.a2-targDimA;}}
return newCoords;},drawArea:function(){var areaWidth=this.calcW(),areaHeight=this.calcH();var px='px',params=[this.areaCoords.x1+px,this.areaCoords.y1+px,areaWidth+px,areaHeight+px,this.areaCoords.x2+px,this.areaCoords.y2+px,(this.img.width-this.areaCoords.x2)+px,(this.img.height-this.areaCoords.y2)+px];var areaStyle=this.selArea.style;areaStyle.left=params[0];areaStyle.top=params[1];areaStyle.width=params[2];areaStyle.height=params[3];var horizHandlePos=Math.ceil((areaWidth-6)/2)+px,vertHandlePos=Math.ceil((areaHeight-6)/2)+px;this.handleN.style.left=horizHandlePos;this.handleE.style.top=vertHandlePos;this.handleS.style.left=horizHandlePos;this.handleW.style.top=vertHandlePos;this.north.style.height=params[1];var eastStyle=this.east.style;eastStyle.top=params[1];eastStyle.height=params[3];eastStyle.left=params[4];eastStyle.width=params[6];var southStyle=this.south.style;southStyle.top=params[5];southStyle.height=params[7];var westStyle=this.west.style;westStyle.top=params[1];westStyle.height=params[3];westStyle.width=params[0];this.subDrawArea();this.forceReRender();},forceReRender:function(){if(this.isIE||this.isWebKit){var n=document.createTextNode(' ');var d,el,fixEL,i;if(this.isIE){fixEl=this.selArea;}
else if(this.isWebKit){fixEl=document.getElementsByClassName('imgCrop_marqueeSouth',this.imgWrap)[0];d=new Element('div');d.style.visibility='hidden';var classList=['SE','S','SW'];for(i=0;i<classList.length;i++){el=document.getElementsByClassName('imgCrop_handle'+classList[i],this.selArea)[0];if(el.childNodes.length){el.removeChild(el.childNodes[0]);}
el.appendChild(d);}}
fixEl.appendChild(n);fixEl.removeChild(n);}},startResize:function(e){this.startCoords=this.cloneCoords(this.areaCoords);this.resizing=true;this.resizeHandle=Event.element(e).classNames().toString().replace(/([^N|NE|E|SE|S|SW|W|NW])+/,'');Event.stop(e);},startDrag:function(e){this.selArea.show();this.clickCoords=this.getCurPos(e);this.setAreaCoords({x1:this.clickCoords.x,y1:this.clickCoords.y,x2:this.clickCoords.x,y2:this.clickCoords.y},false,false,null);this.dragging=true;this.onDrag(e);Event.stop(e);},getCurPos:function(e){var el=this.imgWrap,wrapOffsets=Element.cumulativeOffset(el);while(el.nodeName!='BODY'){wrapOffsets[1]-=el.scrollTop||0;wrapOffsets[0]-=el.scrollLeft||0;el=el.parentNode;}
return{x:Event.pointerX(e)-wrapOffsets[0],y:Event.pointerY(e)-wrapOffsets[1]};},onDrag:function(e){if(this.dragging||this.resizing){var resizeHandle=null,curPos=this.getCurPos(e),newCoords=this.cloneCoords(this.areaCoords),direction={x:1,y:1};if(this.dragging){if(curPos.x<this.clickCoords.x){direction.x=-1;}
if(curPos.y<this.clickCoords.y){direction.y=-1;}
this.transformCoords(curPos.x,this.clickCoords.x,newCoords,'x');this.transformCoords(curPos.y,this.clickCoords.y,newCoords,'y');}else if(this.resizing){resizeHandle=this.resizeHandle;if(resizeHandle.match(/E/)){this.transformCoords(curPos.x,this.startCoords.x1,newCoords,'x');if(curPos.x<this.startCoords.x1){direction.x=-1;}}else if(resizeHandle.match(/W/)){this.transformCoords(curPos.x,this.startCoords.x2,newCoords,'x');if(curPos.x<this.startCoords.x2){direction.x=-1;}}
if(resizeHandle.match(/N/)){this.transformCoords(curPos.y,this.startCoords.y2,newCoords,'y');if(curPos.y<this.startCoords.y2){direction.y=-1;}}else if(resizeHandle.match(/S/)){this.transformCoords(curPos.y,this.startCoords.y1,newCoords,'y');if(curPos.y<this.startCoords.y1){direction.y=-1;}}}
this.setAreaCoords(newCoords,false,e.shiftKey,direction,resizeHandle);this.drawArea();Event.stop(e);}},transformCoords:function(curVal,baseVal,coords,axis){var newVals=[curVal,baseVal];if(curVal>baseVal){newVals.reverse();}
coords[axis+'1']=newVals[0];coords[axis+'2']=newVals[1];},endCrop:function(){this.dragging=false;this.resizing=false;this.options.onEndCrop&&this.options.onEndCrop(this.areaCoords,{width:this.calcW(),height:this.calcH()});},subInitialize:function(){},subDrawArea:function(){}});Cropper.ImgWithPreview=Class.create(Cropper.Img,{subInitialize:function(){this.hasPreviewImg=false;if(typeof(this.options.previewWrap)!='undefined'&&this.options.minWidth>0&&this.options.minHeight>0){this.previewWrap=$(this.options.previewWrap);this.previewImg=this.img.cloneNode(false);this.previewImg.id='imgCrop_'+this.previewImg.id;this.options.displayOnInit=true;this.hasPreviewImg=true;this.previewWrap.addClassName('imgCrop_previewWrap');this.previewWrap.setStyle({width:this.options.minWidth+'px',height:this.options.minHeight+'px'});this.previewWrap.appendChild(this.previewImg);}},subDrawArea:function(){if(this.hasPreviewImg){var calcWidth=this.calcW(),calcHeight=this.calcH();var dimRatio={x:this.imgW/calcWidth,y:this.imgH/calcHeight};var posRatio={x:calcWidth/this.options.minWidth,y:calcHeight/this.options.minHeight};var calcPos={w:Math.ceil(this.options.minWidth*dimRatio.x)+'px',h:Math.ceil(this.options.minHeight*dimRatio.y)+'px',x:'-'+Math.ceil(this.areaCoords.x1/posRatio.x)+'px',y:'-'+Math.ceil(this.areaCoords.y1/posRatio.y)+'px'};var previewStyle=this.previewImg.style;previewStyle.width=calcPos.w;previewStyle.height=calcPos.h;previewStyle.left=calcPos.x;previewStyle.top=calcPos.y;}}});
SD.Effect=new function(){function doEffect(oConfig,fEffect){if(oConfig.beforeStart){oConfig.beforeStart();};if(oConfig.beforeSetup){oConfig.beforeSetup();};if(oConfig.afterSetup){oConfig.afterSetup();};if(oConfig.beforeUpdate){oConfig.beforeUpdate();};fEffect();if(oConfig.afterUpdate){oConfig.afterUpdate();};if(oConfig.afterFinish){oConfig.afterFinish();};return null;};this.BlindDown=function(oElement,oConfig){if(Prototype.Browser.isSlow){return doEffect(oConfig,function(){$(oElement).show();});}
return Effect.BlindDown(oElement,oConfig);};this.BlindUp=function(oElement,oConfig){if(Prototype.Browser.isSlow){return doEffect(oConfig,function(){$(oElement).hide();});}
return Effect.BlindUp(oElement,oConfig);};};
window.onerror=function(errorMsg,url,lineNumber){SD.log(' errorMsg: '+errorMsg+' url: '+url+' lineNumber: '+lineNumber);SD.Error.onError.bind(SD.Error).delay(1,errorMsg,url,lineNumber);return true;};if(typeof console=='undefined'){var console={_out:function(a){var s='';for(var i=0;i<a.length;i++){s+=a[i]+"\n\n";}},debug:function(){console._out(arguments);},info:function(){console._out(arguments);},log:function(){console._out(arguments);}}}
SD.Utils={};SD.Utils.buildContext=function(context,event){context=context||{};if(event){SD.Utils._augmentWithEvent(context,event);}
if(context.sourceMember&&!context.sourceMemberId){context.sourceMemberId=context.sourceMember.uid;}
var srcEl=$(context.sourceElement);context.modTooltip=(context.modTooltip===false)?false:srcEl!=null&&srcEl.isInDOMTree()&&srcEl.getTrueVisibility();return context;};SD.Utils._augmentWithEvent=function(obj,event){obj.sourceElement=event.srcElement||event.target;if('pageX'in event){obj.pageX=event.pageX;obj.pageY=event.pageY;}else{obj.pageX=event.clientX+document.body.scrollLeft+document.documentElement.scrollLeft;obj.pageY=event.clientY+document.body.scrollTop+document.documentElement.scrollTop;}
obj.clientX=event.clientX;obj.clientY=event.clientY;return obj;};SD.Utils._removeOn=function(string){return string.replace(/^on([A-Z])/,function(full,first){return first.toLowerCase();});};SD.Utils.Class={setOptions:function(options){this.options=SD.Utils.Object.merge(this.options||{},options||{},true);for(var option in this.options){if(typeof this.options[option]=='function'&&(/^on[A-Z]/).test(option)){this.observe(SD.Utils._removeOn(option),this.options[option]);delete this.options[option];}}
return this;},observe:SD.Event.observe.methodize(),observeOnce:SD.Event.observeOnce.methodize(),stopObserving:SD.Event.stopObserving.methodize(),fire:SD.Event.fire.methodize(),fireDeferred:SD.Event.fireDeferred.methodize(),forward:SD.Event.forward.methodize(),stopForwarding:SD.Event.stopForwarding.methodize()};SD.Utils.Profiler=(function(){var _functions=$H({});return{log:SD.Console?SD.Console.log:function(){},getTime:function(){return(new Date()).getTime();},profile:function(funcName){this.log('profiling:'+funcName);var func=eval(funcName);_functions.set(funcName,{count:0,totalTime:0,name:funcName});var f=func.wrap(function(proceed){var parent=eval(funcName.substr(0,funcName.lastIndexOf('.')));_functions.get(funcName).count++;var start=SD.Utils.Profiler.getTime();try{var args=$A(arguments);args.splice(0,1);var returnValue=proceed.apply(parent,args);}catch(e){SD.Utils.Profiler.log('Exception in '+funcName,e.message);}
_functions.get(funcName).totalTime+=SD.Utils.Profiler.getTime()-start;return returnValue;});eval(funcName+'=f');},showProfile:function(funcName){var obj=_functions.get(funcName);this.log(funcName,' Avg='+(obj.count&&Math.round(100*obj.totalTime/obj.count)/100)+'ms ',' Count: '+obj.count,' Total Time: '+obj.totalTime+'ms');},showProfiles:function(){this.log('------------------------');_functions.each(function(pair){SD.Utils.Profiler.showProfile(pair.key);});},showEvents:function(){SD.Event.fire2=SD.Event.fire;SD.Event.fire=function(a,b,c){SD.Console.log(b);SD.Event.fire2(a,b,c);};}}})();SD.Utils.Element={repaint:function(el){try{el=$(el);var n=document.createTextNode(' ');el.appendChild(n);el.removeChild(n);}catch(e){}},_getRelativeRegionOffsets:function(refRegion,targetRegion){return{left:targetRegion.left-refRegion.left,right:refRegion.left+refRegion.width-(targetRegion.left+targetRegion.width),top:targetRegion.top-refRegion.top,bottom:refRegion.top+refRegion.height-(targetRegion.top+targetRegion.height)};},getRelativeOffsets:function(targetEl){var vpDimensions=document.viewport.getDimensions();var vpOffsets=document.viewport.getScrollOffsets();var elOffsets=targetEl.cumulativeOffset();return this._getRelativeRegionOffsets({top:vpOffsets[1],left:vpOffsets[0],width:vpDimensions.width,height:vpDimensions.height},{top:elOffsets.top,left:elOffsets.left,width:targetEl.offsetWidth,height:targetEl.offsetHeight});},isPartiallyInView:function(targetEl){var offsets=this.getRelativeOffsets(targetEl);var vpDimensions=document.viewport.getDimensions();return((offsets.top<0&&offsets.bottom<0)||(offsets.top>0&&offsets.bottom<0&&offsets.top<vpDimensions.height)||(offsets.top<0&&offsets.bottom>0&&offsets.bottom<vpDimensions.height)||(offsets.top>0&&offsets.bottom>0))&&((offsets.left<0&&offsets.right<0)||(offsets.left>0&&offsets.right<0&&offsets.left<vpDimensions.width)||(offsets.left<0&&offsets.right>0&&offsets.right<vpDimensions.width)||(offsets.left>0&&offsets.right>0));},isInView:function(targetEl){var offsets=this.getRelativeOffsets(targetEl);return offsets.top>=0&&offsets.left>=0&&offsets.bottom>=0&&offsets.right>=0;},isVisible:function(el){return $(el).ancestors().all(function(el){return el.style.display!='none'});},contains:document.documentElement.contains?function(container,node){return container.contains(node);}:document.compareDocumentPosition?function(container,node){return container==node||!!(container.compareDocumentPosition(node)&16);}:function(container,node){if(node)do{if(node==container)return true;}while((node=node.parentNode));return false;}};SD.Utils.Dom={injectCSS:function(cssText){var domStyle=document.createElement('style');domStyle.setAttribute("type","text/css");if(domStyle.styleSheet){domStyle.styleSheet.cssText=cssText;}else{domStyle.appendChild(document.createTextNode(cssText));}
document.getElementsByTagName('head')[0].appendChild(domStyle);return domStyle;}};SD.Utils.Object={mergeArrays:function(a1,a2,isCloned){for(var i=0;i<a2.length;++i){if(a2[i]!==null&&a2[i]!==undefined&&!isNaN(a2[i])){a1[i]=a2[i];}}
return a1;},merge:function(obj1,obj2,isCloned,isExclusive){isCloned=isCloned===false?false:true;obj1=isCloned?this.clone(obj1):obj1;var o1,o2;for(var i in obj2){o1=obj1[i];o2=obj2[i];if(isExclusive&&o1!==undefined){continue;}
if(typeof o1=='object'&&!(o1 instanceof Array)&&!(o1 instanceof RegExp)&&o1!==null){if(typeof o2=='object'&&!(o2 instanceof Array)&&!(o2 instanceof RegExp)&&o2!==null){obj1[i]=arguments.callee.call(this,o1,o2,isCloned,isExclusive);}
else{obj1[i]=o2;}}
else if(o1 instanceof Array&&o2 instanceof Array){for(var j=0,len=o2.length;j<len;++j){o1[j]=o2[j];}}
else if(typeof o2=='object'&&!(o2 instanceof Array)&&!(o2 instanceof RegExp)&&o2!==null){obj1[i]=this.clone(o2);}
else{obj1[i]=o2;}}
return obj1;},exclusiveMerge:function(obj1,obj2,isCloned){return this.merge(obj1,obj2,isCloned,true);},clone:function(obj){var newObj={};var o;for(var i in obj){o=obj[i];if(o instanceof Array){newObj[i]=o.concat();}else if(o instanceof RegExp){newObj[i]=eval(o.toString());}else if(o==null){newObj[i]=o;}else if(typeof o=='object'&&o.nodeValue==null){newObj[i]=arguments.callee.call(this,o);}else{newObj[i]=o;}}
return newObj;}};SD.Utils.Position={areIntersecting:function(elA,elB){var posa=Position.cumulativeOffset(elA);var posb=Position.cumulativeOffset(elB);var dima=elA.getDimensions();var dimb=elB.getDimensions();return(Math.max(posa[0],posb[0])<=Math.min(posa[0]+dima.width,posb[0]+dimb.width)&&Math.max(posa[1],posb[1])<=Math.min(posa[1]+dima.height,posb[1]+dimb.height));}}
SD.Utils.JSON={mapCommands:function(jsonCommands,cmdData,context,fullData){context=context||window;fullData=fullData||cmdData;for(var i in cmdData){if(typeof jsonCommands[i]=='function'){if(jsonCommands[i].call(context,cmdData[i],fullData)===true){return true;}
continue;}
if(typeof cmdData[i]=='string'||typeof cmdData[i]=='number'){if(typeof jsonCommands[i]=='object'&&typeof jsonCommands[i]['_'+cmdData[i]]=='function'){if(jsonCommands[i]['_'+cmdData[i]].call(context,cmdData[i],fullData)===true){return true;}}else if(typeof jsonCommands[i]=='object'&&typeof jsonCommands[i]['_']=='function'){if(jsonCommands[i]['_'].call(context,cmdData[i],fullData)===true){return true;}}}else if(typeof jsonCommands[i]=='object'&&typeof cmdData[i]=='object'&&cmdData[i]!==null&&!(cmdData[i]instanceof Array)){return arguments.callee.call(this,jsonCommands[i],cmdData[i],context,fullData);}}}}
SD.Utils.Blinker=function(options){var pe=options.periodicalExecuter||SD.Utils.PeriodicalExecuter(500);var times=options.times||Infinity;var onAction=options.onAction||function(){};var offAction=options.offAction||function(){};var stopSensor=options.stopSensor||function(){};var onEnd=options.onEnd||options.offAction||function(){};var counter=0;var blinkingState=true;var retValue;var blinker={isRunning:false,start:function(){pe.register(blink);this.isRunning=true;},stop:function(){pe.unregister(blink);this.isRunning=false;},reset:function(){counter=0;}};var blink=function(){if(stopSensor(counter)){reset();return true;}
counter++;try{(blinkingState?onAction:offAction)();}catch(e){}
blinkingState=!blinkingState;if(counter>=times){try{onEnd();}catch(e){}
reset();return true;}};var reset=function(){blinker.isRunning=false;counter=0;};return blinker;};SD.Utils.PeriodicalExecuter=function(interval){interval=interval||300;var isRunning=false;var timer=null;var registrars=[];var unregister=function(){for(var i=0,len=arguments.length;i<len;++i){if(typeof arguments[i]=='function'){registrars=registrars.without(arguments[i]);}else{registrars.splice(arguments[i],1);}}
if(registrars.length==0){stop();}};var execute=function(){var indexesOfFuncsToUnregister=[];for(var i=0,len=registrars.length;i<len;++i){if(registrars[i]()===true){indexesOfFuncsToUnregister.push(i);}}
if(indexesOfFuncsToUnregister.length){unregister.apply(null,indexesOfFuncsToUnregister);}};var start=function(){if(isRunning){return;}
timer=setInterval(execute,interval);isRunning=true;};var stop=function(){if(isRunning){clearInterval(timer);}
isRunning=false;};return{register:function(){for(var i=0,len=arguments.length;i<len;++i){registrars.push(arguments[i]);}
if(!isRunning){start();}},unregister:unregister}};SD.Utils.IdGenerator={generate:(function(){var _counter=0;return function(prefix){return(prefix||'sd_ui')+(_counter++);};})(),generateCollection:function(){var col={};for(var i=0;i<arguments.length;i++){col[arguments[i]]=this.generate();}
return col;}};SD.Utils.connect=function(f,fContext,g,gContext){if(f==null){f=function(){};}
if(arguments.length==2){g=fContext;fContext=null;}else if(arguments.length==3){gContext=g;g=fContext;fContext="__context__";}
if(f&&f.__connectedFunctions){f.__connectedFunctions.push({func:g,context:gContext});return f;}else{var newF=function(){fContext=fContext=="__context__"?this:fContext;f&&f.apply(fContext,arguments);if(newF.__connectedFunctions){var gFunc;for(var i=0;i<newF.__connectedFunctions.length;i++){gFunc=newF.__connectedFunctions[i];gFunc.func.apply(gFunc.context,arguments);}}};newF.__connectedFunctions=[{func:g,context:gContext}];return newF;}};SD.Utils.disconnect=function(f,g){if(f&&f.__connectedFunctions){for(var i=0;i<f.__connectedFunctions.length;i++){if(f.__connectedFunctions[i].func===g){f.__connectedFunctions.splice(i,1);break;}}
if(f&&f.__connectedFunctions.length==0){f.__connectedFunctions=null;delete f.__connectedFunctions;}}
return f;};SD.Utils.Parser={parse:function(options){var parseLibrary=options.parseLibrary||this.parseLibrary;var domRoot=$(options.domRoot);var context=options.context;for(var className in parseLibrary){domRoot.select('.'+className).each(function(el){parseLibrary[className]&&parseLibrary[className].call(context,el,domRoot);el.removeClassName(className);},this);}
options.onParse&&options.onParse();},parseLibrary:{}};SD.Utils.BasePopulator={appendTop:function(options){options.domRoot.insert({top:this.merge(options.template,options.data)});options.onpopulate&&options.onpopulate();},append:function(options){options.domRoot.insert({bottom:this.merge(options.template,options.data)});options.onpopulate&&options.onpopulate();},populate:function(options){$(options.domRoot).update(this.merge(options.template,options.data));options.onpopulate&&options.onpopulate();}};SD.Utils.Populator=Object.extend({merge:function(template,data){template=(typeof template=='function')?template():template;return template.interpolate(data);}},SD.Utils.BasePopulator);SD.Utils.NestedPopulator=Object.extend({merge:function(template,data){var tpl=typeof template=='function'?template():template;data=(typeof data=='function')?data():data;var buf='';for(var key in data){if(typeof data[key]=='string'){tpl=tpl.replace('${'+key+'}',data[key]);}else if(data[key].data instanceof Array&&data[key].template){buf='';for(var i=0;i<data[key].data.length;++i){buf+=SD.Utils.NestedPopulator.merge(data[key].template,data[key].data[i]);}
tpl=tpl.replace('${'+key+'}',buf);}else if(typeof data[key].data=='object'&&data[key].template){tpl=tpl.replace('${'+key+'}',SD.Utils.NestedPopulator.merge(data[key].template,data[key].data));}}
return tpl;}},SD.Utils.BasePopulator);SD.Utils.formatedSeconds=function(secs,format){if(secs===undefined)return"0:00";secs=parseInt(secs);var s=0,m=0,h=0;s=secs%60;m=parseInt((secs%3600)/60);h=parseInt(secs/3600);var t=format;t=((t.match(/h/g)||[]).length==1)?t.replace('h',h):t.replace('hh',this.stringFormat(h,2,"0"));t=((t.match(/m/g)||[]).length==1)?t.replace('m',m):t.replace('mm',this.stringFormat(m,2,"0"));t=((t.match(/s/g)||[]).length==1)?t.replace('s',s):t.replace('ss',this.stringFormat(s,2,"0"));return t;};SD.Utils.stringFormat=function(value,paddingLength,paddingSymbol){value+="";if(paddingLength>value.length){(paddingLength-value.length).times(function(){value=paddingSymbol+value});}
return value;};SD.Utils.String={htmlSafeFormat:function(str){return str.replace(/</,'&lt;').replace(/>/,'&gt;');}};SD.Utils.XBridge={_observingInterval:200,_commands:{},dispatch:function(targetWnd,cmdString){targetWnd.name=cmdString;},observe:function(observedWindow,cmds){var XBridge=SD.Utils.XBridge,commands=cmds||{},initName=observedWindow.name;for(var i in XBridge._commands){commands[i]=XBridge._commands[i];}
var listener=function(){var cmdArray,paramArray,cmd;if(initName!==observedWindow.name){cmdArray=observedWindow.name.split(';');for(var i=0;i<cmdArray.length;i++){paramArray=cmdArray[i].split(':');cmd=paramArray.shift();commands[cmd]&&commands[cmd].apply(null,paramArray);}
observedWindow.name=initName;}};return window.setInterval(listener,XBridge._observingInterval);},stopObserving:function(observingTimer){observingTimer&&window.clearInterval(observingTimer);}};Object.safeExtend=function(destination,source){for(var p in source){if(typeof source[p]=='function'&&typeof destination[p]=='function'){destination[p]=SD.Utils.connect(source[p],destination[p]);}else{destination[p]=source[p];}}
return destination;};SD.Utils.mixin=function(mix){if(arguments.length<=1){return mix;}else if(arguments.length>2){var args=Array.prototype.slice.call(arguments,2);var result=SD.Utils.mixin.apply(null,[Object.extend(mix,arguments[1])].concat(args));}else{return Object.extend(mix,arguments[1]);}
return result;};SD.Utils.safeMixin=function(mix){if(arguments.length<=1){return mix;}else if(arguments.length>2){var args=Array.prototype.slice.call(arguments,2);var result=SD.Utils.mixin.apply(null,[Object.extend(mix,arguments[1])].concat(args));}else{return Object.safeExtend(mix,arguments[1]);}
return result;};SD.Utils.exec=function(text){if(!text)return text;if(!document.head){document.head=document.getElementsByTagName('head')[0];}
if(window.execScript){window.execScript(text);}else{var script=document.createElement('script');script.setAttribute('type','text/javascript');script.text=text;document.head.insertBefore(script,document.head.firstChild);document.head.removeChild(script);}
return text;};SD.Utils.dumpError=function(error){var str='';for(var i in error){str+=i+': '+error[i]+'\n';}
alert(str);};SD.Utils.Date={};SD.Utils.Date.Entities={months:["January","February","March","April","May","June","July","August","September","October","November","December"],monthsShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]};SD.Utils.Date.getFormatedTime=function(template,date){var d=date?(new Date(+date)):(new Date());return template.interpolate({hours:d.getHours().toPaddedString(2),minutes:d.getMinutes().toPaddedString(2),timeOfDay:(d.getHours()>12)?'PM':'AM',month:d.getMonth()+1,day:d.getDate(),year:d.getFullYear(),year_short:(d.getFullYear()+'').substr(-2),HOURS:(d.getHours()>12)?(d.getHours()-12):d.getHours(),MONTH_SHORT:SD.Utils.Date.Entities.monthsShort[d.getMonth()],MONTH:SD.Utils.Date.Entities.months[d.getMonth()]});};SD.Utils.HashArray=function(){this.keys={};var args=arguments;if(Object.isArray(args[0])){args=args[0];}
for(var i=0,len=args.length;i<len;i++){this.push(args[i]);}};Object.extend(SD.Utils.HashArray.prototype,(function(){var hash={length:0,each:each,include:include,join:join,map:map,pop:pop,push:push,slice:slice,sliceToArray:sliceToArray,toArray:toArray,toObject:toObject,toString:toString,without:without};function push(key){if(!(key in this.keys)&&key!==undefined&&key!==null){this.length+=1;this.keys[key]=key;}
return this.length;}
function pop(){var last,length=this.length,keys=this.keys;for(var key in keys){length-=1;if(length)continue;last=this.keys[key];}
this.without(last);return last;}
function each(iterator,context){var c=0;for(var key in this.keys){iterator.call(context,this.keys[key],c);c+=1;}}
function map(iterator,context){var c=0,result=[];for(var key in this.keys){result[result.length]=iterator.call(context,this.keys[key],c);c+=1;}
return result;}
function without(key){if(key in this.keys){this.length-=1;delete this.keys[key];}
return this;}
function sliceToArray(start,end){var c=0,newKeys=[];if(end===undefined){end=this.length;}
if(start>=end)return[];for(var key in this.keys){if(c<start)continue;newKeys[newKeys.length]=this.keys[key];c+=1;if(c===end)break;}
return newKeys;}
function slice(start,end){var c=0,newKeys=new SD.Utils.HashArray();if(end===undefined){end=this.length;}
if(end<0){end=Math.max(0,this.length+end);}
if(end===0){return newKeys;}
if(start===undefined){return this;}
if(start<0){start=Math.max(0,this.length+start);}
if(start>=end)return newKeys;for(var key in this.keys){if(c>=start){newKeys.push(this.keys[key]);}
c+=1;if(c===end)break;}
return newKeys;}
function include(key){return(key in this.keys);}
function toArray(){var a=[];for(var key in this.keys){a[a.length]=this.keys[key];}
return a;}
function toObject(){return this.keys;}
function toString(){return this.join();}
function join(delimiter){return this.toArray().join(delimiter);}
return hash;})());SD.Utils.TimedLock={lockers:{},lock:function(key,lockTime){this.isLocked(key)&&this.unlock(key);this.lockers[key]=setTimeout(function(){this.unlock(key);}.bind(this),lockTime*1000);},isLocked:function(key){return!!(this.lockers[key]&&this.lockers.hasOwnProperty(key));},unlock:function(key){if(this.lockers[key]){clearTimeout(this.lockers[key]);}
delete this.lockers[key];}};SD.Utils.deferredQueue=function(){var fns=arguments,pointer=-1,execNext=function(){pointer+=1;if(pointer<fns.length){try{fns[pointer](execNext);}catch(e){}}};execNext();}
SD.Utils.PromoPositioner=Class.create({initialize:function(dom,zIndex){this.dom=dom;this.domProxy=null;this.trackTimer=null;this.zIndex=zIndex||1100;this.status='demoted';},promote:function(){if(this.status=='promoted'){return;}
this.status='promoted';this.domProxy=$(document.createElement('div'));this.dom.parentNode.insertBefore(this.domProxy,this.dom);this.domProxy.clonePosition(this.dom);document.body.appendChild(this.dom);this.dom.style.position='absolute';this.dom.style.zIndex=this.zIndex;this.startTracking();},demote:function(){if(this.status=='demoted'){return;}
this.status='demoted';clearInterval(this.trackTimer);this.dom.style.position='';this.domProxy.parentNode.insertBefore(this.dom,this.domProxy);this.domProxy.parentNode.removeChild(this.domProxy);this.domProxy=null;this.dom.style.top=this.dom.style.left='';this.dom.style.zIndex=1;},startTracking:function(){this.track();clearInterval(this.trackTimer);this.trackTimer=setInterval(this.track.bind(this),200);},track:function(){var offsets=this.domProxy.getAbsoluteOffsets();this.dom.style.top=offsets.top+'px';this.dom.style.left=offsets.left+'px';},destroy:function(){if(this.status=='promoted'){this.demote();}
this.dom=null;this.domProxy=null;clearInterval(this.trackTimer);}});SD.Utils.getPosition=function(dom){var curP=$(dom).getStyle('position');var p=curP;$(dom).ancestors().each(function(el){curP=el.getStyle('position');if(curP=='fixed'){p='fixed';throw $break;}else if(curP=='absolute'){p='absolute';}else if(curP=='relative'&&p!='absolute'){p='relative';}});return p;};SD.Utils.ScreenMask=Class.create({partitionClassName:"sd-partition",initialize:function(options){this.options=options||{};this.domIntersectors=[];this.intersectors=[];this.partitions=[];this.domHolder=$(this.options.domHolder||Prototype.Browser.WebKit?document.documentElement:document.body);this.domCoordsRef=$(this.options.domCoordsRef||this.domHolder);this.positioning=this.options.positioning||'absolute';this.resolveSpaceCoords();this.initMask();if(Object.prototype.toString.call(this.options.domToMask)!='[object Array]'){this.options.domToMask=[this.options.domToMask];}
this.options.domToMask&&this.maskElements.apply(this,this.options.domToMask);this.options.recreateOnWindowResize&&this.observeWindowResize();this.options.recreateOnWindowScroll&&this.observeWindowScroll();},observeWindowResize:function(){Event.observe(window,'resize',(this.boundOnWindowResize=this.onWindowResize.bind(this)));},observeWindowScroll:function(){Event.observe(window,'scroll',(this.boundOnWindowScroll=this.onWindowScroll.bind(this)));},onWindowResize:function(){this.recreateDomIntersectors()},onWindowScroll:function(){this.recreateDomIntersectors()},recreateDomIntersectors:function(){this._clean();this.resolveSpaceCoords();this.initMask();for(var i=0;i<this.domIntersectors.length;i++){this.addIntersector(this.getDomCoordinates(this.domIntersectors[i]));}},resolveSpaceCoords:function(){this.spaceCoords=this.options.spaceCoords?this.options.spaceCoords:(typeof this.domCoordsRef=='function')?this.domCoordsRef():this.getDomCoordinates(this.domCoordsRef);},initMask:function(){this.partitions.push(new SD.Utils.Partition({coords:this.spaceCoords,domHolder:this.domCoordsRef,className:this.partitionClassName,positioning:this.positioning,zIndex:this.options.zIndex}));},maskElements:function(){var dom,newDoms=[];for(var i=0;i<arguments.length;i++){dom=$(arguments[i]);if(this.domIntersectors.indexOf(dom)==-1){if(!dom.__sdPositioning){dom.__sdPositioning=SD.Utils.getPosition(dom);}
this.domIntersectors.push(dom);newDoms.push(dom);}}
for(var i=0;i<newDoms.length;i++){this.addIntersector(this.getDomCoordinates(newDoms[i]));}},getDomCoordinates:function(dom){var offsets=$(dom).getAbsoluteOffsets();var coords;if(this.position=='absolute'){if(dom.__sdPositioning=='fixed'){coords={x0:offsets.left+this.domCoordsRef.scrollLeft,y0:offsets.top+this.domCoordsRef.scrollTop,x1:offsets.left+dom.offsetWidth+this.domCoordsRef.scrollLeft,y1:offsets.top+dom.offsetHeight+this.domCoordsRef.scrollTop};}else{coords={x0:offsets.left,y0:offsets.top,x1:offsets.left+dom.offsetWidth,y1:offsets.top+dom.offsetHeight};}}else{if(dom.__sdPositioning=='fixed'){coords={x0:offsets.left+this.domCoordsRef.scrollLeft,y0:offsets.top+this.domCoordsRef.scrollTop,x1:offsets.left+dom.offsetWidth+this.domCoordsRef.scrollLeft,y1:offsets.top+dom.offsetHeight+this.domCoordsRef.scrollTop};}else{coords={x0:offsets.left,y0:offsets.top,x1:offsets.left+dom.offsetWidth-this.domCoordsRef.scrollLeft,y1:offsets.top+dom.offsetHeight-this.domCoordsRef.scrollTop};}}
if(dom.__sdMaskOffsetLeft){coords.x0+=dom.__sdMaskOffsetLeft}
if(dom.__sdMaskOffsetRight){coords.x1+=dom.__sdMaskOffsetRight}
if(dom.__sdMaskOffsetTop){coords.y0+=dom.__sdMaskOffsetTop}
if(dom.__sdMaskOffsetBottom){coords.y1+=dom.__sdMaskOffsetBottom}
return coords;},addIntersector:function(iCoords){var intersector=new SD.Utils.Rect(iCoords);this.intersectors.push(intersector);this._partition(intersector);},destroy:function(){this._clean();this.boundOnWindowResize&&Event.stopObserving(window,'resize',this.boundOnWindowResize);this.boundOnWindowScroll&&Event.stopObserving(window,'scroll',this.boundOnWindowScroll);this.domIntersectors=null;this.domHolder=null;this.domCoordsRef=null;this.options=null;},reset:function(){this._clean();this.initMask();},_clean:function(){for(var i=0;i<this.partitions.length;i++){this.partitions[i].destroy();}
this.partitions=[];this.intersectors=[];},_partition:function(intersector){var newPartitions=[];var intersectingPartitions=this._findIntersectingPartitions(intersector.coords);if(intersectingPartitions.length==0)return;for(var i=0;i<intersectingPartitions.length;i++){delete this.partitions[intersectingPartitions[i].index];newPartitions=newPartitions.concat(this._splitPartition(intersectingPartitions[i].partition,intersector));}
this.partitions=this.partitions.compact().concat(newPartitions);},_findIntersectingPartitions:function(iCoords){var candidates=[],pCoords;for(var i=0;i<this.partitions.length;i++){pCoords=this.partitions[i].coords;if(Math.max(iCoords.x0,pCoords.x0)<Math.min(iCoords.x1,pCoords.x1)&&Math.max(iCoords.y0,pCoords.y0)<Math.min(iCoords.y1,pCoords.y1)){candidates.push({partition:this.partitions[i],index:i});}}
return candidates;},_splitPartition:function(partition,intersector){var np=[],p=partition.coords,i=intersector.coords,hash=(i.x0>p.x0?'1':'0')+
(i.x0>=p.x1?'1':'0')+
(i.x1>=p.x0?'1':'0')+
(i.x1>=p.x1?'1':'0')+' '+
(i.y0>p.y0?'1':'0')+
(i.y0>=p.y1?'1':'0')+
(i.y1>=p.y0?'1':'0')+
(i.y1>=p.y1?'1':'0');partition.destroy();switch(hash){case'1011 0010':np.push(this._buildPartition(p.x0,p.y0,i.x0,p.y1),this._buildPartition(i.x0,i.y1,p.x1,p.y1));break;case'0010 0010':np.push(this._buildPartition(p.x0,i.y1,i.x1,p.y1),this._buildPartition(i.x1,p.y0,p.x1,p.y1));break;case'0010 1011':np.push(this._buildPartition(p.x0,p.y0,i.x1,i.y0),this._buildPartition(i.x1,p.y0,p.x1,p.y1));break;case'1011 1011':np.push(this._buildPartition(p.x0,p.y0,i.x0,p.y1),this._buildPartition(i.x0,p.y0,p.x1,i.y0));break;case'1010 0010':np.push(this._buildPartition(p.x0,p.y0,i.x0,p.y1),this._buildPartition(i.x0,i.y1,i.x1,p.y1),this._buildPartition(i.x1,p.y0,p.x1,p.y1));break;case'0010 1010':np.push(this._buildPartition(p.x0,p.y0,i.x1,i.y0),this._buildPartition(p.x0,i.y1,i.x1,p.y1),this._buildPartition(i.x1,p.y0,p.x1,p.y1));break;case'1010 1011':np.push(this._buildPartition(p.x0,p.y0,i.x0,p.y1),this._buildPartition(i.x0,p.y0,i.x1,i.y0),this._buildPartition(i.x1,p.y0,p.x1,p.y1));break;case'1011 1010':np.push(this._buildPartition(p.x0,p.y0,i.x0,p.y1),this._buildPartition(i.x0,p.y0,p.x1,i.y0),this._buildPartition(i.x0,i.y1,p.x1,p.y1));break;case'1010 1010':np.push(this._buildPartition(p.x0,p.y0,i.x0,p.y1),this._buildPartition(i.x0,p.y0,i.x1,i.y0),this._buildPartition(i.x1,p.y0,p.x1,p.y1),this._buildPartition(i.x0,i.y1,i.x1,p.y1));break;case'0011 0010':np.push(this._buildPartition(p.x0,i.y1,p.x1,p.y1));break;case'0011 1010':np.push(this._buildPartition(p.x0,p.y0,p.x1,i.y0),this._buildPartition(p.x0,i.y1,p.x1,p.y1));break;case'0011 1011':np.push(this._buildPartition(p.x0,p.y0,p.x1,i.y0));break;case'0010 0011':np.push(this._buildPartition(i.x1,p.y0,p.x1,p.y1));break;case'1010 0011':np.push(this._buildPartition(p.x0,p.y0,i.x0,p.y1),this._buildPartition(i.x1,p.y0,p.x1,p.y1));break;case'1011 0011':np.push(this._buildPartition(p.x0,p.y0,i.x0,p.y1));break;}
return np;},_buildPartition:function(x0,y0,x1,y1){return new SD.Utils.Partition({coords:{x0:x0,y0:y0,x1:x1,y1:y1},domHolder:this.domHolder,className:this.partitionClassName,positioning:this.positioning,zIndex:this.options.zIndex});}});SD.Utils.Rect=Class.create({initialize:function(coords){this.coords=coords;},getWidth:function(){return this.coords.x1-this.coords.x0;},getHeight:function(){return this.coords.y1-this.coords.y0;},setWidth:function(w){this.coords.x1=this.coords.x0+w;return this;},setHeight:function(h){this.coords.y1=this.coords.y0+h;return this;}});SD.Utils.Partition=Class.create(SD.Utils.Rect,{initialize:function($super,options){$super(options.coords);this.domHolder=$(options.domHolder);this.className=options.className;this.dom=document.createElement('div');this.dom.className=this.className;this.dom.style.position=options.positioning||'absolute';this.dom.style.top=this.coords.y0+'px';this.dom.style.left=this.coords.x0+'px';this.dom.style.width=this.getWidth()+'px';this.dom.style.height=this.getHeight()+'px';if(options.zIndex!=null){this.dom.style.zIndex=options.zIndex;}
this.domHolder.appendChild(this.dom);},setWidth:function($super,w){$super(w);this.dom.style.width=this.getWidth()+'px';return this;},setHeight:function($super,h){$super(h);this.dom.style.height=this.getHeight()+'px';return this;},destroy:function(){this.domHolder.removeChild(this.dom);this.domHolder=null;this.dom=null;this.coords=null;}});SD.Utils.lambda=function(val){return function(){return typeof val=='function'?val():val;}};SD.Utils.getValue=function(val){return typeof val=='function'?val():val;};SD.Utils.Cloner={doClone:function(newObj,objToClone){newObj=newObj||{};var p,ptype;for(var i in objToClone){p=objToClone[i];ptype=typeof p;if(ptype=='string'||ptype=='number'||ptype=='boolean'||p==null){newObj[i]=p;}else if(typeof p=='object'){newObj[i]=p.clone?p.clone():arguments.callee.call({},p);}else if(Object.prototype.toString(p)=='[object Array]'&&objToClone.hasOwnProperty(i)){newObj[i]=p.concat();}else if(p instanceof RegExp){newObj[i]=eval(p.toString());}else if(typeof p=="function"&&objToClone.hasOwnProperty(i)){newObj[i]=p;}}
return newObj;},clone:function(obj){var f=function(objToClone){this.doClone(this,objToClone);};f.prototype=this.constructor.prototype;var clonedObject=new f(obj);f=null;this.onClone&&this.onClone();return clonedObject;}};SD.Utils.LLNode=Class.create({initialize:function(value,id,weight){this.id=id||this.id||SD.Utils.IdGenerator.generate('LLNode');this.parentList=null;this.prevNode=null;this.nextNode=null;this.weight=weight||1;this.setNodeValue(value);},setBefore:function(node){if(!node)return;this.nextNode=node;this.prevNode=node.prevNode;node.prevNode=this;},setAfter:function(node){if(!node)return;this.prevNode=node;this.nextNode=node.nextNode;node.nextNode=this;},setNodeValue:function(value){this.value=value;},getNodeValue:function(){return typeof this.value=='function'?this.value():this.value;},destroy:function(){for(var prop in this){delete this[prop];}}});SD.Utils.ILinkedList={Events:{ADD_NODE:'SD.Utils.ILinkedList.ADD_NODE',REMOVE_NODE:'SD.Utils.ILinkedList.REMOVE_NODE'}}
SD.Utils.LinkedList=Class.create(Enumerable,{initialize:function(id){this.id=id||SD.Utils.IdGenerator.generate('LinkedList');this.first=null;this.last=null;this.length=0;},_each:function(iterator){var node=this.first;while(node){iterator(node);node=node.nextNode;}},getLength:function(){return this.length;},has:function(node){return node&&(node instanceof SD.Utils.LLNode)&&node.parentList==this;},add:function(node){if(node==null||this.has(node)){return node;}
if(Object.prototype.toString.call(node)=="[object Array]"){var a=[];for(var i=0;i<node.length;i++){a.push(this.add(node[i]));}
return a;}
if(!(node instanceof SD.Utils.LLNode)){node=new SD.Utils.LLNode(node);}
node.parentList=this;this.length+=1;this.insertAfter(node,this.last);SD.Event.fire(this,SD.Utils.ILinkedList.Events.ADD_NODE,{node:node})
return node;},adopt:function(node){if(!node||!(node instanceof SD.Utils.LLNode)||!node.parentList==this){return node;}
node.parentList=this;return node;},remove:function(node){if(!this.has(node)){return null;}
if(node.prevNode){node.prevNode.nextNode=node.nextNode;}else{this.first=node.nextNode;}
if(node.nextNode){node.nextNode.prevNode=node.prevNode;}else{this.last=node.prevNode;}
this.length-=1;node.parentList=null;SD.Event.fire(this,SD.Utils.ILinkedList.Events.REMOVE_NODE,{node:node});return node;},insertAfter:function(node,ref){if(!node){return node}
if(node instanceof SD.Utils.LLNode&&node.parentList!=this){this.adopt(node);}
ref=this.has(ref)?ref:this.last;if(!ref){this.first=this.last=node;return node;}
node.setAfter(ref);if(ref==this.last){this.last=node;}
if(!this.first){this.first=node;}
return node;},insertBefore:function(node,ref){if(!node){return node}
if(node instanceof SD.Utils.LLNode&&node.parentList!=this){this.adopt(node);}
ref=this.has(ref)?ref:this.first;if(!ref){this.first=this.last=node;return node;}
node.setBefore(ref);if(ref==this.first){this.first=node;}
if(!this.last){this.last=node;}
return node;},indexOf:function(item,i){i||(i=0);if(this.length==0){return-1;}
if(i<0){i=this.length+i;}
var c,node;if(i<this.length/2){for(c=0,node=this.first;node;c++,node=node.nextNode){if(node.getNodeValue()==item&&c>=i){return c;}}}else{for(c=this.length-1,node=this.last;node;c--,node=node.prevNode){if(node.getNodeValue()==item&&c>=i){return c;}}}
return-1;},flush:function(){if(this.length==0){return;}
this.first=null;this.last=null;this.length=0;},toArray:function(){return this.map(Prototype.K);},fromArray:function(nodes){this.flush();for(var i=0;i<nodes.length;i++)
nodes[i].parentList=null;this.add(nodes);},sortBy:function(iterator,context){this.fromArray(this.toArray().sortBy(iterator,context));},clone:function(){var ll=new this.constructor();this.each(function(node){var value=(node.value&&node.value.clone)?node.value.clone():node.value;ll.add(new SD.Utils.LLNode(value,null,node.weight));});return ll;}});SD.Utils.LinkedListIterator=Class.create({initialize:function(linkedList){this.list=linkedList;this.reset();this.setup();},setup:function(){this.boundOnNodeRemoved=this._onNodeRemoved.bind(this);SD.Event.observe(this.list,SD.Utils.ILinkedList.Events.REMOVE_NODE,this.boundOnNodeRemoved);},_onNodeRemoved:function(e){var removedNode=e.memo.node;var c=this.cursor;if(c&&!c.parentList&&c.nextNode==removedNode.nextNode){c.nextNode=removedNode.nextNode;}},setCursor:function(node){if(node==null){this.hasEnded=true;return;}
this.cursor=node;},reset:function(){this.isPaused=false;this.hasStarted=false;this.hasEnded=false;this.cursor=null;},hasNext:function(){if(this.isPaused){return false;}
var c=this.cursor;if(this.list.length==0){this.hasEnded=true;this.cursor=null;return false;}
if(!this.hasStarted||!c){return!!this.list.first;}
return c&&c!=this.list.last&&!this.hasEnded;},getNext:function(){if(!this.hasStarted){return this.list.first;}
var c=this.cursor;return this.hasNext()?(c?c.nextNode:this.list.first):null;},iterate:function(){if(this.isPaused){return null;}
this.hasStarted=true;var next=this.getNext();this.setCursor(next);return next;},destroy:function(){SD.Event.stopObserving(this.list,SD.Utils.ILinkedList.Events.REMOVE_NODE,this.boundOnNodeRemoved);for(var prop in this){delete this[prop];}},clone:function(){return new this.constructor(this.linkedList.clone());},pause:function(){this.isPaused=true;},resume:function(){this.isPaused=false;}});SD.Utils.RoundRobinLinkedListIterator=Class.create(SD.Utils.LinkedListIterator,{initialize:function($super,linkedList,repeats){$super(linkedList);this._repeats=this.repeats=repeats||1;},setWeights:function(weights){if(!weights||this.hasStarted)return;if(Object.prototype.toString.call(weights)!="[object Array]"){weights=[+weights||1];}
for(var i=0,node=this.list.first;i<weights.length&&node;i++,node=node.nextNode){node.weight=weights[i]<1?1:weights[i];}},reset:function($super){$super();this._repeats=this.repeats;},setCursor:function(node){if(node==null){this.hasEnded=true;return;}
if(!node._weight){node._weight=node.weight-1;}else{node._weight-=1;}
this.cursor=node;},hasNext:function(){if(this.isPaused){return false;}
if(this.list.length==0||this._repeats==0){this.hasEnded=true;this.cursor=null;return false;}
return!this.hasEnded&&(!this.isCursorAtEnd()||this._repeats>1);},isCursorAtEnd:function(){return this.cursor?!!(this.cursor==this.list.last&&this.cursor._weight===0):false;},getNext:function(startNode){var c=startNode||this.cursor,nextNode;if(this.hasEnded){return null;}
if(this.list.length==0){nextNode=null;}else{if(!this.hasStarted){nextNode=this.list.first;}else{nextNode=c?((c._weight>0?c:c.nextNode)||this.list.first):this.list.first;}}
if(nextNode==this.list.last&&nextNode._weight===0){this._repeats-=1;}
return nextNode;},getNextWithFilter:function(filter){var c=0,startNode=this.getNext(),node=startNode,listLength=this.list.getLength();while(node){c+=1;if(c>listLength){return null;}
if(filter(node)){return node;}
node=node.nextNode||this.list.first;}
return null;},clone:function(){return new this.constructor(this.linkedList.clone(),this.repeats);}});SD.Utils.Validators={isEmpty:function(v){return v==null||v.length==0;},isEmail:function(v){return!this.isEmpty(v)&&/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/.test(v);},isNumber:function(v){return!this.isEmpty(v)&&!isNaN(v)&&!/^\s+$/.test(v);},isDigits:function(v){return!this.isEmpty(v)&&!/[^\d]/.test(v);},isAlpha:function(v){return!this.isEmpty(v)&&/^[a-zA-Z]+$/.test(v);},isAlphaNum:function(v){return!this.isEmpty(v)&&!/\W/.test(v)},isDate:function(v){return!this.isEmpty()&&!isNaN(new Date(v));},isUrl:function(v){return!this.isEmpty()&&/^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i.test(v);},isDateAu:function(v){if(this.isEmpty())return false;var regex=/^(\d{2})\/(\d{2})\/(\d{4})$/;if(!regex.test(v))return false;var d=new Date(v.replace(regex,'$2/$1/$3'));return(parseInt(RegExp.$2,10)==(1+d.getMonth())&&parseInt(RegExp.$1,10)==d.getDate()&&parseInt(RegExp.$3,10)==d.getFullYear());}};SD.Utils.UI={showSections:function(sectionIds){for(var sec in sectionIds){$(sectionIds[sec]).hide();}
for(var i=1;i<arguments.length;i++){if(sectionIds[arguments[i]]){$(sectionIds[arguments[i]]).style.display='block';}}}};SD.assert=function(expr,message){if(expr===true){console.log('***** PASSED! ****** '+message);}else{console.log('##### FAILED! ###### '+message);}};SD.assertEq=function(expr1,expr2,message){if(expr1===expr2){console.log('***** PASSED! ****** '+message);}else{console.log('##### FAILED! ###### '+message);console.log('##### Expected: '+expr2);console.log('##### Got:      '+expr1);}};SD.TestRunner={run:function(tests){var test;var args=[].slice.call(arguments);if(args.length>1){args.shift();tests.push.apply(tests,args.flatten());}
try{for(var i=0;i<tests.length;i++){test=tests[i];console.log('-------------------- '+test.name+' ----------------------');var startTime=+new Date;test.setup&&test.setup();test.run();test.tearDown&&test.tearDown();console.log('runtime: '+((+new Date)-startTime)+'ms');}}catch(e){console.log(e);}}};SD.S={};SD.S.Module={plug:function(module){if(typeof module!='function'){return this;}
return new module(this);},mergePlug:function(module){var mInstance=this.plug(module);var selection=this;for(var i in selection){if(mInstance[i]||typeof selection[i]!='function')
continue;(function(key){mInstance[key]=function(){selection[key].apply(selection,arguments);return mInstance;};})(i);}
return mInstance;},unplug:function(){return this.selection;}}
SD.S.Numbers=function(selection){this.selection=selection;};SD.S.Numbers.Proto={toInt:function(){if(!this.selection)return this;for(var i=0;i<this.selection.length;i++){this.selection[i]=parseInt(this.selection[i]);}
return this;},toString:function(){return this;}};SD.Utils.mixin(SD.S.Numbers.prototype,SD.S.Numbers.Proto,SD.S.Module);Array.prototype.plug=SD.S.Module.plug;Array.prototype.mergePlug=SD.S.Module.mergePlug;Ajax.Iframe={_c:0,_callback_prefix:'tmp_callback',_transport_name_prefix:'iframe_transport_',Request:Class.create({initialize:function(url,options){options=options||{};this.onFailure=options.onFailure;this.onSuccess=options.onSuccess;this.url=url;this.parameters=options.parameters||{};this.callbackName=options.callbackName||'callback';this.callbackValue=Ajax.Iframe._callback_prefix+Ajax.Iframe._c++;this.createCallback();this.parameters[this.callbackName]=this.callbackValue;this.transportName=options.transportName||(Ajax.Iframe._transport_name_prefix+Ajax.Iframe._c++);this.method=options.method||'post';this.timer=null;this.timeoutTime=options.timeoutTime||60;this.send();},send:function(){this.form=this.createForm(this.url,this.method,this.parameters);this.transport=this.createTransport(this.transportName);if(this.onFailure){this.transport.onerror=this.failure.bind(this,{success:false,message:'Error: Could not process request'})}
this.form.target=this.transport.name;this.form.submit();if(this.timeoutTime>0){clearTimeout(this.timer);this.timer=setTimeout(this.timeout.bind(this,{success:false,message:'Error: Could not process request'}),this.timeoutTime*1000);}},createTransport:function(name){var wrapper=document.createElement('div');document.body.appendChild(wrapper);wrapper.style.display='none';wrapper.innerHTML="<iframe name='"+name+"'></iframe>";return wrapper.firstChild;},createForm:function(url,method,params){params=params||{};var form=document.createElement('form');form.action=url;form.method=method;form.style.display='none';var input;for(var name in params){input=document.createElement('input');input.type='hidden';input.name=name;input.value=params[name];form.appendChild(input);}
document.body.appendChild(form);return form;},createCallback:function(){window[this.callbackValue]=this.success.bind(this);},success:function(data){if(this.isComplete)return;if(this.onSuccess){try{this.onSuccess({responseJSON:data});}catch(e){}}
this.complete(data);},failure:function(data){if(this.isComplete)return;if(this.onFailure){try{this.onFailure({responseJSON:data});}catch(e){}}
this.complete(data);},timeout:function(data){if(this.isComplete)return;if(this.onTimeout){try{this.onTimeout({responseJSON:data});}catch(e){}}else{return this.failure(data);}
this.complete(data);},complete:function(data){if(this.isComplete)return;this.isComplete=true;if(this.onComplete){try{this.onComplete({responseJSON:data});}catch(e){}}
this.destroy();},destroy:function(){clearTimeout(this.timer);delete window[this.callbackValue];if(this.transport){this.transport.parentNode.parentNode.removeChild(this.transport.parentNode);delete this.transport;}
if(this.form){this.form.parentNode.removeChild(this.form);delete this.form;}}})};
SD.RunnableManager={setupRules:function(rules){this.rules=$H();rules&&this.addRules(rules);},addRules:function(rules){if(rules==null)return this;var ruleDef;if(arguments.length==2){ruleDef={};ruleDef[arguments[0]]=arguments[1];this.addRules(ruleDef);return this;}
if(typeof rules=="function"){ruleDef={};ruleDef[SD.Utils.IdGenerator.generate('Rule')]=rules;this.rules.update(ruleDef);return this;}else if(Object.prototype.toString.call(rules)=="[object Array]"){for(var i=0;i<rules.length;i++){this.addRules(rules[i]);}
return this;}else if(rules===Object(rules)){for(var i in rules){rules[i]!==Object(rules[i])&&(rules[i]=SD.Utils.lambda(rules[i]));}
this.rules.update(rules);}else{this.addRules(SD.Utils.lambda(rules));return this;}
return this;},removeRule:function(ruleId){this.rules.set(ruleId);return this;},removeAllRules:function(){this.rules=$H();return this;},canRun:function(context,runnable){var firstFailingRuleName;var canRunVal=this.rules.every(function(rulePair){var retValue=!!rulePair.value.call(this,context,runnable);if(!retValue){firstFailingRuleName=rulePair.key;}
return retValue},this);if(context.debug){if(!canRunVal){console.log('id: '+runnable.id+', sig: '+runnable.sig+', failing rule: '+firstFailingRuleName);}}
if(this.flow){return canRunVal&&this.flow.canRun(context,runnable);}else if(this.manager){return canRunVal&&this.manager.canRun(context,runnable);}
return canRunVal;}};SD.IRunnable={Events:{INIT:'SD.IRunnable.Events.INIT',DESTROY:'SD.IRunnable.Events.DESTROY',STARTED:'SD.IRunnable.Events.STARTED',ENDED:'SD.IRunnable.Events.ENDED'}};SD.Runnable=Class.create(SD.RunnableManager,{initialize:function($super,options){this.options||(this.options=(options||{}));this.isRunning=false;this.isContextLocked=false;this.setupRules(this.options.rules);this.onBeforeRun=[];this.onAfterRun=[];this.setupRunQueues();SD.Event.fire(this,SD.IRunnable.Events.INIT);},setupRunQueues:function(){if(this.options.onBeforeRun){this.onBeforeRun=this.onBeforeRun.concat(this.options.onBeforeRun);}
SD.Event.observe(this,SD.IRunnable.Events.STARTED,this._execQueue.bind(this,this.onBeforeRun));if(this.options.onAfterRun){this.onAfterRun=this.onAfterRun.concat(this.options.onAfterRun);}
SD.Event.observe(this,SD.IRunnable.Events.ENDED,this._execQueue.bind(this,this.onAfterRun));},_execQueue:function(queue,e){for(var i=0;i<queue.length;i++){try{queue[i].call(this,e);}catch(ex){}}},run:function(context){context=context||this.context||{};this.isRunning=true;this.setContext(context);if(!this.canRun(this.context,this)){SD.Event.fire(this,SD.IRunnable.Events.STARTED,{runBlocked:true});this.endRun({runBlocked:true});return null;}
SD.Event.fire(this,SD.IRunnable.Events.STARTED,{runBlocked:false});return this._run(this.context);},_run:function(){},setContext:function(context){if(this.isContextLocked){return;}
if(context){this.context=context;this.context.actionId=this.id;}},lockContext:function(){this.isContextLocked=true;},unlockContext:function(){this.isContextLocked=false;},onClone:function(){},set:function(property,value){this[property]=value;return this;},get:function(property){return this[property];},endRun:function(endContext){endContext=endContext||{};this.isRunning=false;SD.Event.fire(this,SD.IRunnable.Events.ENDED,endContext);this.onEndRun(endContext);},onEndRun:function(endContext){},destroy:function($super){SD.Event.fire(this,SD.IRunnable.Events.DESTROY);for(var prop in this){delete this[prop];}
$super();}});SD.IPriority={};SD.IPriority.REGULAR='REGULAR';SD.IPriority.IMMEDIATE='IMMEDIATE';SD.IPriority.PASSTHROUGH='PASSTHROUGH';SD.UIType={};SD.UIType.NONE='NONE';SD.UIType.TOOLTIP='TOOLTIP';SD.UIType.POPUP='POPUP';SD.Action=Class.create(SD.Runnable,{initialize:function($super,options){this.options=options||{};this.type='action';this.sig=this.options.sig;this.id=this.options.id||SD.Utils.IdGenerator.generate('Action');this.llNode=null;this.manager=this.options.manager||SD.FlowManager;this.flow=this.options.flow;this.async=this.options.async;this.uiType=this.options.uiType||SD.UIType.NONE;this.priority=this.options.priority||SD.IPriority.REGULAR;this.priorityWeight=this.options.priorityWeight||0;this.callFunc=this.options.callFunc||Prototype.emptyFunction;this.callContext=this.options.callContext||this;this.weight=this.options.weight||1;$super(this.options);this.setup();},setup:function(){},_run:function(context){try{this.callFunc.call(this.callContext,context,this);}catch(e){this.endRun();return;}
if(!this.isAsync()){this.endRun();}},isAsync:function(){return this.async==null?this.uiType==SD.UIType.POPUP:this.async;},setParentFlow:function(flow){this.flow=flow;return this;},endParentFlow:function(){this.flow&&this.flow.endFlow();},setWeight:function(weight){this.weight=weight;if(this.llNode){this.llNode.weight=this.weight;}},destroy:function($super){for(var prop in this){delete this[prop];}
$super();},clone:function(options){options=options||{};var callContext=this.callContext==this?null:this.callContext;var action=new this.constructor({id:options.id||this.id,manager:options.manager||this.manager,sig:options.sig||this.sig,flow:null,async:options.async||this.async,uiType:options.uiType||this.uiType,priority:options.priority||this.priority,priorityWeight:options.priorityWeight||this.priorityWeight,callFunc:options.callFunc||this.callFunc,callContext:options.callContext||callContext,rules:this.rules&&this.rules.clone(),onBeforeRun:options.onBeforeRun?this.onBeforeRun.concat(options.onBeforeRun):this.onBeforeRun,onAfterRun:options.onAfterRun?this.onAfterRun.concat(options.onAfterRun):this.onAfterRun,weight:options.weight||this.weight});if(options.rules){action.addRules(options.rules);}
action.context=this.context;action.onClone&&action.onClone();return action;}});SD.IFlow={Events:{ITEM_ADDED:'SD.IFlow.Events.ITEM_ADDED',ITEM_REMOVED:'SD.IFlow.Events.ITEM_REMOVED',FLOW_FLUSHED:'SD.IFlow.Events.FLOW_FLUSHED'}};SD.Flow=Class.create(SD.Runnable,{initialize:function($super,options){this.type='flow';this.options=options||{};this.llNode=null;this.sig=this.options.sig;this.id=this.options.id||SD.Utils.IdGenerator.generate('Flow');this.flow=this.options.flow;this.manager=this.options.manager||SD.FlowManager;this.queue=this.options.queue||new SD.Utils.LinkedList();this.iteratorConstructor=this.options.iteratorConstructor||SD.Utils.LinkedListIterator;this.iterator=this.options.iterator||this.getIterator();this.priority=this.options.priority||SD.IPriority.REGULAR;this.weight=this.options.weight||1;this.isBlocking=this.options.blocking;this.hasRun=false;$super(this.options);this.setup();},setup:function(){this.setupBlocking();this.options.runnables&&this.add(this.options.runnables);SD.Event.observe(this,SD.IRunnable.Events.ENDED,this.onEnd);},setupBlocking:function(){var onRunnableEnded=function(e){if(!e.memo.runBlocked){this.hasRun=true}}.bind(this);this.queue.each(function(node){SD.Event.observe(node.value,SD.IRunnable.Events.ENDED,onRunnableEnded);});SD.Event.observe(this,SD.IFlow.Events.ITEM_ADDED,function(e){SD.Event.observe(e.memo.item,SD.IRunnable.Events.ENDED,onRunnableEnded);});},_run:function(context){var _this=this;if(this.iterator.hasNext()&&this.isRunning){var childRunnable=this.iterator.iterate().value;childRunnable.onEndRun=function(){delete this.onEndRun;_this._run(context);};childRunnable.run(context);}else{this.endRun();}},add:function(runnable){var i;if(arguments.length>1){for(i=0;i<arguments.length;i++){this.add(arguments[i]);}
return this;}
if(Object.prototype.toString.call(runnable)=="[object Array]"){for(i=0;i<runnable.length;i++){this.add(runnable[i]);}
return this;}
if(runnable==null||runnable!=Object(runnable)||runnable==this){return this;}
if(typeof runnable=='function'){runnable=new SD.Action({sig:'inlineFunction',callFunc:runnable});}else if(!(runnable instanceof SD.Runnable)){runnable=new SD.Action(runnable);}
if(runnable instanceof SD.Runnable){runnable.llNode=new SD.Utils.LLNode(runnable,null,runnable.weight);this.queue.add(runnable.llNode);runnable.setParentFlow(this);}
SD.Event.fire(this,SD.IFlow.Events.ITEM_ADDED,{item:runnable});this.onAdd&&this.onAdd(runnable);return this;},jumpTo:function(runnableId,index){index=index||0;var nodes=this.queue.filter(function(node){return node.value.id==runnableId});if(nodes[index]){nodes[index].prevNode?this.iterator.setCursor(nodes[index].prevNode):this.iterator.reset();}},has:function(runnable){return this.queue.has(runnable.llNode);},remove:function(runnable){if(runnable instanceof SD.Runnable&&this.has(runnable)){this.queue.remove(runnable.llNode);}else{throw'Trying to remove nonrunnable object from flow with id='+this.id;}
SD.Event.fire(this,SD.IFlow.Events.ITEM_REMOVED,{item:runnable});return this;},getIterator:function(queue){if(this.iterator){return this.iterator;}
return new this.iteratorConstructor(queue||this.queue);},setParentFlow:function(flow){this.flow=flow;return this;},setWeight:function(weight){this.weight=weight;if(this.llNode){this.llNode.weight=this.weight;}},flush:function(){this.queue.flush();this.iterator.reset();SD.Event.fire(this,SD.IFlow.Events.FLOW_FLUSHED);return this;},onAdd:function(runnable){},onEnd:function(e){this.rewind();if(this.isBlocking&&this.flow&&this.hasRun){this.hasRun=false;this.endParentFlow();}
this.hasRun=false;},rewind:function(){this.iterator.reset();},getLength:function(){return this.queue.getLength();},destroy:function($super){for(var prop in this){delete this[prop];}
$super();},endParentFlow:function(){this.flow&&this.flow.endFlow();},endFlow:function(){this.isRunning=false;},getFirst:function(){return this.queue.first&&this.queue.first.value;},getLast:function(){return this.queue.last&&this.queue.last.value;},getNext:function(context){context=context||{};var next=this.iterator.getNextWithFilter(function(node){var runnable=node.value;var origContext=runnable.context;runnable.setContext(context);var result=!!runnable.canRun(context,runnable);runnable.context=origContext;return result;});return next&&next.value;},clone:function(options){options=options||{};var flow=new this.constructor({id:options.id||this.id,sig:options.sig||this.sig,flow:options.flow||this.flow,manager:options.manager||this.manager,iteratorConstructor:options.iteratorConstructor||this.iteratorConstructor,priority:options.priority||this.priority,rules:this.rules&&this.rules.clone(),onBeforeRun:options.onBeforeRun?this.onBeforeRun.concat(options.onBeforeRun):this.onBeforeRun,onAfterRun:options.onAfterRun?this.onAfterRun.concat(options.onAfterRun):this.onAfterRun,weight:options.weight||this.weight,blocking:this.isBlocking});if(options.rules){flow.addRules(options.rules);}
this.queue.each(function(node){flow.add(node.value.clone());});if(options.runnables){flow.add(options.runnables);}
flow.context=this.context;flow.onClone&&flow.onClone();return flow;},pause:function(){this.iterator&&this.iterator.pause()},resume:function(){this.iterator&&this.iterator.resume()}});SD.RoundRobinBurstFlow=Class.create(SD.Flow,{initialize:function($super,options){options=options||{};options.sig=options.sig||'RoundRobinBurstFlow';options.iteratorConstructor=SD.Utils.RoundRobinLinkedListIterator;this.enableCloning=options.enableCloning==null?true:options.enableCloning;this.burstRuns=options.burstRuns||1;this.isBlocking=options.blocking||false;this.hasRun=false;this.runNext=false;$super(options);},setupBlocking:function(){var runCount=0,blockedRunCount=0,_this=this;function end(){runCount=0;blockedRunCount=0;_this.runNext=false;_this.endFlow();}
var onRunnableEnded=function(e){if(!_this.isRunning){return;}
if(e.memo&&e.memo.runBlocked){blockedRunCount+=1;_this.iterator.cursor._weight=0;}else{_this.hasRun=true;runCount+=1;}
if(runCount>=_this.burstRuns||blockedRunCount>=_this.getLength()){if(_this.runNext){_this.runNext=false;_this.iterator.cursor._weight=0;}else{end();}}};this.queue.each(function(node){SD.Event.observe(node.value,SD.IRunnable.Events.ENDED,onRunnableEnded);});SD.Event.observe(this,SD.IFlow.Events.ITEM_ADDED,function(e){SD.Event.observe(e.memo.item,SD.IRunnable.Events.ENDED,onRunnableEnded);});},endParentFlow:function(){this.flow.endFlow();},onEnd:function(){if(this.isBlocking&&this.flow&&this.hasRun){this.hasRun=false;this.endParentFlow();}
this.hasRun=false;},getIterator:function(queue){return new this.iteratorConstructor(queue||this.queue,Infinity);},clone:function(options,forceCloning){if(!forceCloning&&!this.enableCloning){return this;}
options=options||{};var flow=new this.constructor({id:options.id||this.id,sig:options.sig||this.sig,flow:options.flow||this.flow,blocking:options.blocking||this.isBlocking,manager:options.manager||this.manager,queue:this.queue.clone(),priority:options.priority||this.priority,rules:this.rules&&this.rules.clone(),onBeforeRun:options.onBeforeRun?this.onBeforeRun.concat(options.onBeforeRun):this.onBeforeRun,onAfterRun:options.onAfterRun?this.onAfterRun.concat(options.onAfterRun):this.onAfterRun,weight:options.weight||this.weight,skipSetup:true});if(options.rules){flow.addRules(options.rules);}
flow.context=this.context;flow.onClone&&flow.onClone();return flow;}});SD.FifoExecFlow=Class.create(SD.Flow,{initialize:function($super,options){options=options||{};options.sig=options.sig||'FifoExecFlow';$super(options);SD.Event.observe(null,SD.IRunnable.Events.ENDED,function(e){if(this.has(e.source)){this.queue.remove(this.queue.first);}}.bind(this));},onAdd:function($super,runnable){$super(runnable);if(!runnable){return;}
if(this.getLength()==1){this.run();}}});SD.IRunnable={Events:{INIT:'SD.IRunnable.Events.INIT',DESTROY:'SD.IRunnable.Events.DESTROY',STARTED:'SD.IRunnable.Events.STARTED',ENDED:'SD.IRunnable.Events.ENDED'}};SD.RunnableRegistry={_registry:{},init:function(){SD.Event.observe(null,SD.IRunnable.Events.INIT,this.onRunnableInit);SD.Event.observe(null,SD.IRunnable.Events.DESTROY,this.onRunnableDestroy);},onRunnableInit:function(e){SD.RunnableRegistry.add(e.source);},onRunnableDestroy:function(e){SD.RunnableRegistry.remove(e.source);},get:function(runnableId){return this._registry[runnableId];},add:function(runnable){var i;if(arguments.length>1){for(i=0;i<arguments.length;i++){this.add(arguments[i]);}
return this;}
this._registry[runnable.id]=runnable;return this;},remove:function(runnable){typeof runnable=='string'?(this._registry[runnable]=null):(this._registry[runnable.id]=null);return this;}};SD.FlowStopAction=Class.create(SD.Action,{initialize:function($super,options){options=options||{};options.callFunc=function(){this.flow&&this.flow.endFlow();}
$super(options);},clone:function(options){options=options||{};options.id=options.id||this.id;return new this.constructor(options);}});SD.FlowJumpAction=Class.create(SD.Action,{initialize:function($super,options){options=options||{};var jumpRules=options.jumpRules;this.jumpRules=jumpRules||[];if(Object.prototype.toString.call(jumpRules)=='[object Array]'){this.jumpRules=jumpRules;}else if(jumpRules===Object(jumpRules)){this.jumpRules=[jumpRules];}
options.callFunc=this._resolveJump;options.callContext=this;$super(options);},_resolveJump:function(context){for(var i=0;i<this.jumpRules.length;i++){if(this.jumpRules[i].when?this.jumpRules[i].when(context):true){this.flow&&this.flow.jumpTo(this.jumpRules[i].jumpTo);return;}}},clone:function(options){options=options||{};options.jumpRules=options.jumpRules||this.jumpRules.concat();options.id=options.id||this.id;return new this.constructor(options);}});SD.FlowManager=SD.Utils.mixin({},SD.RunnableManager,{debug:false,initialize:function(){this.setupRules();this.execFlows={main:new SD.FifoExecFlow({id:'main',manager:this}),priority:new SD.FifoExecFlow({id:'priority',manager:this})};this.setup();},reset:function(){this.execFlows={main:new SD.FifoExecFlow({id:'main',manager:this}),priority:new SD.FifoExecFlow({id:'priority',manager:this})};this.removeAllRules();},setup:function(){},run:function(runnable,context){if(Object.prototype.toString.call(runnable)=="[object Array]"){for(var i=0;i<runnable.length;i++){if(Object.prototype.toString.call(runnable[i])=="[object Array]"){this.run(runnable[i][0],runnable[i][1]);}else{this.run(runnable[i],{});}}
return this;}
context=context||{};context.debug=this.debug;if(context.debug){console.log('context: '+JSON.stringify(context,null,'\t'));if(SD.Flows){console.log('resolved flow: '+SD.Flows.resolveFlow(context));}}
SD.Event.fire(this,SD.FlowManager.Events.BEFORE_RUN,{runnable:runnable,context:context});runnable.setContext(context);runnable.lockContext();var runPriority=runnable.get('priority');switch(runPriority){case SD.IPriority.IMMEDIATE:this.execFlows.priority.add(runnable);break;case SD.IPriority.REGULAR:this.execFlows.main.add(runnable);break;case SD.IPriority.PASSTHROUGH:runnable.run(context);break;}
return this;},execFlowMethod:function(methodName,flowId){var flow=this.execFlows[flowId];if(!flow||typeof flow[methodName]!='function'){return;}
var args=[].slice.call(arguments,2);flow[methodName].apply(flow,args);},Events:{BEFORE_RUN:'SD.FlowManager.Events.BEFORE_RUN'}});SD.FlowManager.initialize();
SD.Console=new function(){var oSDConsole=null;var oToolbar=null;var oConsole=null;var oButtonClose=null;var oButtonShowProfiles=null;var nLineCount=1;function createConsole(){oSDConsole=DIV({'class':'sd-console','style':'display: none'},oToolbar=DIV({'class':'toolbar'},oButtonClose=BUTTON({'class':'actionbutton actionbutton-plain'},'Close'),oButtonShowProfiles=BUTTON({'class':'actionbutton actionbutton-plain'},'Show Profiles')),oConsole=DIV({'class':'console'},''));oButtonClose.observe('click',function(e){SD.Console.hide();});oButtonShowProfiles.observe('click',function(e){SD.Utils.showProfiles();});Element.insert(document.body,{'top':oSDConsole});};function addLine(oMessage){oConsole.appendChild(DIV({'class':'line'},nLineCount+' | '+oMessage));nLineCount++;};this.show=function(){if(!oSDConsole){createConsole();}
oSDConsole.show();};this.hide=function(){oSDConsole.hide();};this.log=function(){SD.Console.show();addLine($A(arguments).join(', '));};};if(typeof console=='undefined'){var console={debug:SD.Console.log,log:SD.Console.log,info:SD.Console.log};}
SD.FbConnect=new function(){this.basicPublish=null;this.permissions={};this._params={};this.reInitialize=function(newParams){for(var i in newParams){if(newParams.hasOwnProperty(i)){this._params[i]=newParams[i];}}
this.initFB(this._params);};this.initialize=function(fbConnectApi,checkLoginStatus,session){var params={};params.appId=fbConnectApi;params.status=checkLoginStatus;params.cookie=true;params.xfbml=true;params.oauth=true;if(session){params.session=session;}
this.initFB(params);};this.initFB=function(params){this._params=params;FB.init(params);FB.Event.subscribe('auth.login',function(response){if(SD.Config.reloadAfterFBLogin){window.location.reload();}
var me=SD.User.getByFbUserId(FB.getUserID());SD.User.fetch(me,this._updateMyDataFromFb.bind(this));}.bind(this));if(FB.getAuthResponse()){var me=SD.User.getByFbUserId(FB.getUserID());SD.User.fetch(me,this._updateMyDataFromFb.bind(this));}
SD.FbConnect._subscribeToLikeEvents();};this._updateMyDataFromFb=function(me){var myself=SD.Model&&SD.Model.getMyself();if(myself){myself.name=myself.name.split(" ")[0];}};this.popupRequestDialog=function(fbml,title){title=title||'Invite your friends to join you on SpeedDate!';width=760;height=650;this.popupDialog(fbml,title,width,height);};this.popupPhotoImportDialog=function(fbml,title){fbml=fbml||' ';title=title||'Import your Facebook photos';width=760;height=650;this.popupDialog(fbml,title,width,height);};this.popupDialog=function(fbml,title,width,height){var fbml_=fbml||' ';var title_=title||' ';var width_=width||760;var height_=height||650;FB.ui({method:'fbml.dialog',fbml:(fbml_),size:{width:width_,height:height_},width:width_,height:height_});var dialog=new FB.UI.FBMLPopupDialog(title);dialog.setFBMLContent(fbml);dialog.setContentWidth(width);dialog.setContentHeight(height);dialog.show();};this.publishToWall=function(publishObj,callback){var publishObjCopy=SD.Utils.Object.clone(publishObj);if(!SD.XConnect.hasFacebookSession()){publishObjCopy.display='popup';}
FB.ui(publishObjCopy,function(publishResponse){if(publishResponse&&publishResponse.post_id){SD&&SD.ExperimentManager&&SD.ExperimentManager.recordOutput('FBConnectSignupPostToWall',1,1);}else{SD&&SD.ExperimentManager&&SD.ExperimentManager.recordOutput('FBConnectSignupSkippedPostToWall',1,1);}
callback&&callback(publishResponse);});};this.setPermissions=function(permissions){this.permissions=permissions;};this.hasPermission=function(permission){if(!this.permissions){return false;}
return this.permissions[permission]==true;};this.shareNotification=function(notificationType){if(SD.XConnect.hasFacebookOAuth()){this._submitShareNotification(notificationType);}else{SD.XConnect.openFacebookAuthenticate(function(result){if(result){this._submitShareNotification(notificationType);}}.bind(this),{permissions:SD.Config.defaultFbPermissions});}};this._submitShareNotification=function(notificationType){new Ajax.Request(SD.NavUtils.link('ajax','publish_notification',{'notificationType':notificationType}),{method:'post',onSuccess:function(e){if(e&&e.responseJSON&&e.responseJSON.result){SD.UIController.infoMessage('Feed story has been published!',3);}else{}}.bind(this),onFailure:function(e){}.bind(this)});};this._recordLike=function(){new Ajax.Request(SD.NavUtils.link('ajax','facebook_like'),{method:'post',onSuccess:function(){},onFailure:function(){}});};this._subscribeToLikeEvents=function(){FB.Event.subscribe('edge.create',function(url){if(url=="http://www.facebook.com/speeddate"){SD.FbConnect._recordLike();}
SD.Event.fire(null,SD.FbConnect.Events.LIKE,{});});FB.Event.subscribe('edge.remove',function(url){if(url=="http://www.facebook.com/speeddate"){SD.ExperimentManager.recordOutput('FBUnlike',1,1);}});},this.Events={LIKE:"SD.FbConnect.Events:LIKE"};};
SD.Data=SD.Data||{};SD.Data.IDGenerator=Class.create({initialize:function(sig){this.sig=sig||'sd';this.counter=0;},generate:function(){return this.sig+(this.counter++);}});SD.Data.ICursor={Events:{CURSOR_MOVED:"SD.Data.ICursor.Events:CURSOR_MOVED",CURSOR_AT_START:"SD.Data.ICursor.Events:CURSOR_AT_START",CURSOR_AT_END:"SD.Data.ICursor.Events:CURSOR_AT_END"}};SD.Data.CursorAdjuster=Class.create({initialize:function(){},onAdd:function(){},onRemove:function(){}});SD.Data.SimpleCursor=Class.create({initialize:function(options){this.options=options||{};this.dataStore=options.dataStore;this.pointer=this.pointer||0;this._observers=[];},setup:function(){var boundedOnDataAdd=this.onDataAdd.bind(this);var boundedOnDataRemove=this.onDataRemove.bind(this);this._observers.push({context:this.dataStore,event:SD.Data.IStore.Events.RECORD_ADDED,observer:boundedOnDataAdd},{context:this.dataStore,event:SD.Data.IStore.Events.RECORD_REMOVED,observer:boundedOnDataRemove});SD.Event.observe(this.dataStore,SD.Data.IStore.Events.RECORD_ADDED,boundedOnDataAdd);SD.Event.observe(this.dataStore,SD.Data.IStore.Events.RECORD_REMOVED,boundedOnDataRemove);},onDataAdd:function(e){},onDataRemove:function(e){var index=e.memo.index;if(this.getMax()==0){this.pointer=0;}else if(this.pointer>index){this.moveBy(-1);}else if(this.pointer==index&&index!=0){this.moveBy(-1);}},getMax:function(){return this.dataStore.getLength()-1;},getMin:function(){return 0;},moveTo:function(pos){var maxPosition=this.getMax();if(maxPosition==0||pos<0){pos=0;}else if(pos>maxPosition){pos=maxPosition;}
this.prevPointer=this.pointer;this.pointer=pos;this.onMove();SD.Event.fire(this,SD.Data.ICursor.Events.CURSOR_MOVED,{prevPointer:this.prevPointer,pointer:this.pointer});},onMove:function(){var dataLength=this.dataStore.getLength();if(this.pointer==0){SD.Event.fire(this,SD.Data.ICursor.Events.CURSOR_AT_START,{pointer:this.pointer});}else if(this.pointer==dataLength-1){SD.Event.fire(this,SD.Data.ICursor.Events.CURSOR_AT_END,{pointer:this.pointer});}},moveBy:function(pos){this.moveTo(this.pointer+pos);},moveToEnd:function(){this.moveTo(this.data.length-1);},moveToStart:function(){this.moveTo(0);},getPointer:function(){return this.pointer;},isAtEnd:function(){var max=this.getMax();return(max==0||this.pointer==max);},destroy:function(){var observerDef;for(var i;i<this._observers.length;i++){observerDef=this._observers[i];SD.Event.stopObserving(observerDef.context,observerDef.event,observerDef.observer);}
this.dataSource=null;}});SD.Data.IStore={Events:{RECORD_ADDED:"SD.Data.IStore.Events:RECORD_ADDED",RECORD_REMOVED:"SD.Data.IStore.Events:RECORD_REMOVED",ALL_RECORDS_REMOVED:"SD.Data.IStore.Events:ALL_RECORDS_REMOVED",BEFORE_ALL_RECORDS_REMOVED:"SD.Data.IStore.Events:BEFORE_ALL_RECORDS_REMOVED",RECORD_UPDATED:"SD.Data.IStore.Events:RECORD_UPDATED"}};SD.Data.Store=Class.create({initialize:function(options){this.options=options||{};this.data=[];this.idGenerator=new SD.Data.IDGenerator;this.idField=this.options.idField||'id';this.hashData={};if(this.options.data){this.add(this.options.data);}
this.onInit();},assignId:function(record){record[this.idField]=this.idGenerator.generate();},add:function(record){if(Object.prototype.toString.call(record)=='[object Array]'){for(var i=0,len=record.length;i<len;i++){this.add(record[i]);}
return this;}
if(!record||Object.prototype.toString.call(record)!='[object Object]'||this.onBeforeAdd(record)===false){return this;}
if(!(this.idField in record)){this.assignId(record);}
var position=this._addToArray(record);this._addToHash(record);this.onAdd(record,position);SD.Event.fire(this,SD.Data.IStore.Events.RECORD_ADDED,{record:record,position:position});return this;},_resolveToRecord:function(record,recursiveCallback){var r;if(this.data.length==0||!record){return null;}
if(Object.prototype.toString.call(record)=='[object Array]'){while((r=record.shift())){recursiveCallback.call(this,r);}
return null;}else if((typeof record=='string'||typeof record=='number')){var records=this.getById(record);if(records){if(Object.prototype.toString.call(records)=='[object Array]'){while((r=records.shift())){recursiveCallback.call(this,r);}
return null;}else{record=records}}else{return null;}}
if(!this.hasRecord(record)){return null;}
return record;},remove:function(recordData){var record=this._resolveToRecord(recordData,this.remove);if(record==null){return this}
this._removeFromArray(record);this._removeFromHash(record);this.onRemove(record);SD.Event.fire(this,SD.Data.IStore.Events.RECORD_REMOVED,{record:record});if(this.data.length==0){SD.Event.fire(this,SD.Data.IStore.Events.ALL_RECORDS_REMOVED);}
return this;},removeAll:function(){SD.Event.fire(this,SD.Data.IStore.Events.BEFORE_ALL_RECORDS_REMOVED);this.data.length=0;this.hashData={};SD.Event.fire(this,SD.Data.IStore.Events.ALL_RECORDS_REMOVED);},update:function(recordData,updater){if(typeof updater!='function'){return this}
var _this=this;var record=this._resolveToRecord(recordData,function(rd){_this.update(rd,updater);});if(record==null){return this}
try{updater(record);}catch(e){return this;}
this.onUpdate(record);SD.Event.fire(this,SD.Data.IStore.Events.RECORD_UPDATED,{record:record});return this;},_addToArray:function(record){this.data.push(record);return this.data.length-1;},_addToHash:function(record){var id=record[this.idField];if(id in this.hashData){this.hashData[id].push(record);}else{this.hashData[id]=[record];}},_without:function(arr,record){for(var i=0,len=arr.length;i<len;i++){if(arr[i]==record){arr.splice(i,1);return;}}},_removeFromArray:function(record){this._without(this.data,record);},_removeFromHash:function(record){if(this.hasRecord(record)){var id=record[this.idField];this._without(this.hashData[id],record);if(this.hashData[id].length===0){delete this.hashData[id];}}},onBeforeAdd:function(record){if(!(this.idField in record)){record[this.idField]=this.idGenerator.generate();}},onInit:function(){},onAdd:function(record,position){},onRemove:function(record){},onUpdate:function(record){},getRecordId:function(record){return record[this.idField];},hasRecord:function(record){var id=(typeof record=='string'||typeof record=='number')?record:record[this.idField];return id in this.hashData;},getRecords:function(){return this.data;},getLength:function(){return this.data.length;},getById:function(id){return this.hashData[id]?this.hashData[id].length>1?this.hashData[id]:this.hashData[id][0]:null;},filter:function(iterator){var result=[];for(var i=0,data=this.data,len=data.length;i<len;++i){iterator(data[i],i)&&result.push(data[i]);}
return result;},filterByField:function(field,value){var result=[];for(var i=0,data=this.data,len=data.length;i<len;++i){if(data[i][field]===value){result.push(data[i]);}}
return result;},destroy:function(){this.data=null;this.hashData=null;this.options=null;this.idGenerator=null;SD.Event.stopObserving(this);}});SD.Data.UniqStore=Class.create(SD.Data.Store,{onBeforeAdd:function(record){return!this.hasRecord(record);}});SD.Data.ISortedStore={Events:{ORDER_CHANGED:'SD.Data.ISortedStore:ORDER_CHANGED'}};SD.Data.UniqOrderedStore=Class.create(SD.Data.UniqStore,{initialize:function($super,options){this.comparator=options.comparator;$super(options);},_getIndexOfInsertion:function(record){var mid,min,max,comparator=this.comparator,data=this.data,index;if(data.length==0){return 0;}else if(data.length==1){return comparator(data[0],record)>0?0:1;}else{mid=Math.floor((data.length-1)/2);min=0;max=data.length-1;while(index==null){if(comparator(data[mid],record)>0){if(mid==min){index=mid;break;}
max=mid;mid=Math.floor((mid-min)/2)+min;}else{if(mid==max-1){index=comparator(data[mid+1],record)>0?mid+1:mid+2;break;}
min=mid;mid=Math.floor((max-mid)/2)+mid;}}
return index;}},_addToArray:function(record){var index=this._getIndexOfInsertion(record);this.data.splice(index,0,record);return index;},sort:function(){this.data.sort(this.comparator);this.onSort();SD.Event.fire(this,SD.Data.ISortedStore.ORDER_CHANGED);return this;},onSort:function(){},getAt:function(index){return this.data[index];},getFirst:function(){return this.getAt(0);},getLast:function(){var len=this.getLength();if(len==0)return null;return this.getAt(len-1);},destroy:function($super){this.comparator=null;SD.Event.stopObserving(this);$super();}});SD.Store={};SD.Store.BuddiesClass=Class.create(SD.Data.UniqStore,{initialize:function($super,options){$super(options);}});SD.Store.Buddies=new SD.Store.BuddiesClass({idField:'uid'});SD.Store.AlertsClass=Class.create(SD.Data.UniqStore,{onInit:function(){this.blockedSequentialEvents={'I_WANTED_TO_DATE_IS_ONLINE':1,'WANTED_TO_DATE_ME_IS_ONLINE':1,'I_FLIRTED_IS_ONLINE':1,'FLIRTED_ME_IS_ONLINE':1,'I_WINKED_AT_IS_ONLINE':1,'WINKED_AT_ME_IS_ONLINE':1,'I_FAVORITED_IS_ONLINE':1,'FAVORITED_ME_IS_ONLINE':1,'COMPATIBLE_MATCH_IS_ONLINE':1};},setup:function(){var _this=this;SD.Event.observe(null,SD.User.Events.DATE_RESULT_FETCHED,function(event){if(!event.memo.user||(event.memo.user&&event.memo.user.uid==null)){return;}
SD.User.fetch(SD.User.get(event.memo.user.uid),function(user){if(!user){return};_this.add({type:(event.memo.success?'MATCH_FOUND':'NO_MATCH_FOUND'),uid:user.uid});});});SD.Event.observe(null,SD.Date.Events.DATE_OVER,function(event){if(!event.memo.otherUser||(event.memo.otherUser&&event.memo.otherUser.uid==null)){return;}
SD.User.fetch(SD.User.get(event.memo.otherUser.uid),function(user){if(!(user&&user.uid)){return};var reasonCode=event.memo.reasonCode;if(reasonCode!=SD.ReasonCodes.TIME_FINISHED&&reasonCode!=SD.ReasonCodes.USER_LEFT&&reasonCode!=SD.ReasonCodes.USER_DISCONNECTED){return;}
if(reasonCode!=SD.ReasonCodes.TIME_FINISHED){_this.add({type:'NO_MATCH_FOUND',uid:user.uid});}else{_this.add({type:'PENDING_MATCH',uid:user.uid});}});});},onBeforeAdd:function($super,record){if($super(record)===false){return false;}
if(record.uid){var other=SD.User.get(record.uid);if(SD.BuddyList.Controller.isBuddyBlocked(other)){return false;}}
var len=this.getLength();if(len==0){return true;}
var lastRecord=this.getRecords()[len-1];if(lastRecord.uid===record.uid&&this.blockedSequentialEvents[lastRecord.type]&&this.blockedSequentialEvents[record.type]){return false;}else{return true;}},onAdd:function(record,pos){if(record.type=="NO_MATCH_FOUND"||record.type=="MATCH_FOUND"){var targetUID=record.uid;var pendingMatches=this.filterByField('type','PENDING_MATCH');for(var i=0;i<pendingMatches.length;++i){if(targetUID==pendingMatches[i].uid){this.remove(pendingMatches[i]);}}}}});SD.Store.Alerts=new SD.Store.AlertsClass();Event.observe(document,'dom:loaded',function(){SD.Store.Alerts.setup()});
SD.UI=SD.UI||{};SD.UI.Component=Class.create({templateSet:null,initTemplate:null,preamble:function(options){var cproto=this.constructor.prototype,cProtoOwnParseLibrary;if(cproto.hasOwnProperty('parseLibrary')&&!cproto.parseLibrary.__merged){cProtoOwnParseLibrary=cproto.parseLibrary;delete cproto.parseLibrary;cproto.parseLibrary=cproto.parseLibrary?SD.Utils.mixin({},cproto.parseLibrary,cProtoOwnParseLibrary):cProtoOwnParseLibrary;cproto.parseLibrary.__merged=true;}
if(options.parseLibrary){this.parseLibrary=SD.Utils.mixin({},this.parseLibrary,options.parseLibrary);}},initialize:function(options){this.preamble(options);this.options=options||{};this.id=options.id||SD.Utils.IdGenerator.generate();this.domHolder=options.domHolder&&$(options.domHolder);this.paneHolder=options.paneHolder;this.container=options.container;this.templates=options.templates||this.templateSet;if(typeof this.templates=='function'){this.templates=this.templates();}
this.initTemplate=options.initTemplate||this.initTemplate;if(typeof this.initTemplate=='function'){this.initTemplate=this.initTemplate();}
this.populator=options.populator||SD.Utils.Populator;this.parser=options.parser||SD.Utils.Parser;this.data=this.dataFilter(options.data||{});if(this.data._url){this.load(this.data._url,this.domHolder,this.setup.bind(this));}else if(this.data._content){this.loadContent(this.data._content,this.domHolder);this.setup();}else{if(this.initTemplate){this.render(this.domHolder,this.initTemplate,this.data);}
this.parse(this.domHolder,this.parseLibrary);this.setup();}},setup:function(){},render:function(domRoot,template,data){this.populator.append({domRoot:domRoot,template:template,data:data});},parse:function(domRoot,parseLibrary){this.parser.parse({domRoot:domRoot,parseLibrary:parseLibrary,context:this});},parseLibrary:{},dataFilter:function(data){return data;},destroy:function(){this.domHolder=null;this.paneHolder=null;this.container=null;this.data=null;this.parseLibrary=null;this.populator=null;this.parser=null;this.options=null;this.onDestroy();},onDestroy:function(){},load:function(url,domRoot,callback){return new Ajax.Request(url,{method:'get',onSuccess:function(transport){this.loadContent(transport.responseText,domRoot);callback&&callback();}.bind(this)});},loadContent:function(content,domRoot,method){method=method||'replace';if(method==='replace'){$(domRoot).update(content);}else if(method==='add'){$(domRoot).insert({bottom:content});}
this.parse(domRoot,this.parseLibrary||{});},close:function(){this.onClose();},setActive:function(){this.onActivate();},setInactive:function(){this.onInactivate();},setAttention:function(){this.onAttention();},onActivate:function(){},onInactivate:function(){},onAttention:function(){},onClose:function(){}});SD.UI.Container=Class.create(SD.UI.Component,{initialize:function($super,options){options=options||{};this.itemStore=options.itemStore||this.getItemStore();SD.Event.observe(this.itemStore,SD.Data.IStore.Events.ALL_RECORDS_REMOVED,function(e){this.activeItem=null;}.bind(this));this.activeItem=null;$super(options);},getItemStore:function(){return this.itemStore?this.itemStore:new SD.Data.Store();},addItem:function(item){item.container=this;this.itemStore.add(item);this._onItemAdd(item);SD.Event.fire(this,SD.UI.Container.Events.ITEM_ADDED,{id:item.id});return item;},_onItemAdd:function(item){},removeItem:function(id){var item=typeof id=='object'?id:this.itemStore.getById(id);this.itemStore.remove(item);this._onItemRemove(item);SD.Event.fire(this,SD.UI.Container.Events.ITEM_REMOVED,{id:id});return item;},_onItemRemove:function(item){},removeAllItems:function(){this.itemStore.removeAll();},getCount:function(){return this.itemStore.getLength();},getById:function(id){return this.itemStore.getById(id);},getItems:function(){return this.itemStore.getRecords();},hasItem:function(item){return this.itemStore.hasRecord(item);},getActiveItem:function(){return this.activeItem;},setActive:function($super){$super();this.getItems().each(function(item){item.setActive()});},setInactive:function($super){$super();this.getItems().each(function(item){item.setInactive()});},setAttention:function($super){$super();this.getItems().each(function(item){item.setAttention()});},activateItem:function(item){if(this.activeItem===item){return;}
this.activeItem&&this.activeItem.setInactive();this.activeItem=item;item.setActive();},setItemInactive:function(item){if(this.activeItem===item){this.activeItem=null;}
item&&item.setInactive();},destroy:function(){this.itemStore.destroy();this.activeItem=null;this.removeAllItems();}});SD.UI.Container.Events={ITEM_REMOVED:'SD.UI.Container.Events:ITEM_REMOVED',ITEM_ADDED:'SD.UI.Container.Events:ITEM_ADDED'};
(function(){Element.addMethods({'hoverIntent':function(elem,f,g){elem=$(elem);var cfg={sensitivity:7,interval:100,timeout:0};cfg=Object.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).stopObserving('mousemove',track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var parent=e.relatedTarget;while(parent&&parent!=elem){try{parent=parent.parentNode;}catch(error){parent=elem;}}
if(parent==this){return false;}
var ev=Object.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}
if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).observe("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).stopObserving("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return elem.observe('mouseover',handleHover).observe('mouseout',handleHover);}});})();
var isIE=(navigator.appVersion.indexOf("MSIE")!=-1)?true:false;var isWin=(navigator.appVersion.toLowerCase().indexOf("win")!=-1)?true:false;var isOpera=(navigator.userAgent.indexOf("Opera")!=-1)?true:false;function ControlVersion()
{var version;var axo;var e;try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");version=axo.GetVariable("$version");}catch(e){}
if(!version)
{try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");version="WIN 6,0,21,0";axo.AllowScriptAccess="always";version=axo.GetVariable("$version");}catch(e){}}
if(!version)
{try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");version=axo.GetVariable("$version");}catch(e){}}
if(!version)
{try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");version="WIN 3,0,18,0";}catch(e){}}
if(!version)
{try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");version="WIN 2,0,0,11";}catch(e){version=-1;}}
return version;}
function GetSwfVer(){var flashVer=-1;if(navigator.plugins!=null&&navigator.plugins.length>0){if(navigator.plugins["Shockwave Flash 2.0"]||navigator.plugins["Shockwave Flash"]){var swVer2=navigator.plugins["Shockwave Flash 2.0"]?" 2.0":"";var flashDescription=navigator.plugins["Shockwave Flash"+swVer2].description;var descArray=flashDescription.split(" ");var tempArrayMajor=descArray[2].split(".");var versionMajor=tempArrayMajor[0];var versionMinor=tempArrayMajor[1];if(descArray[3]!=""){tempArrayMinor=descArray[3].split("r");}else{tempArrayMinor=descArray[4].split("r");}
var versionRevision=tempArrayMinor[1]>0?tempArrayMinor[1]:0;var flashVer=versionMajor+"."+versionMinor+"."+versionRevision;}}
else if(navigator.userAgent.toLowerCase().indexOf("webtv/2.6")!=-1)flashVer=4;else if(navigator.userAgent.toLowerCase().indexOf("webtv/2.5")!=-1)flashVer=3;else if(navigator.userAgent.toLowerCase().indexOf("webtv")!=-1)flashVer=2;else if(isIE&&isWin&&!isOpera){flashVer=ControlVersion();}
return flashVer;}
function DetectFlashVer(reqMajorVer,reqMinorVer,reqRevision)
{versionStr=GetSwfVer();if(versionStr==-1){return false;}else if(versionStr!=0){if(isIE&&isWin&&!isOpera){tempArray=versionStr.split(" ");tempString=tempArray[1];versionArray=tempString.split(",");}else{versionArray=versionStr.split(".");}
var versionMajor=versionArray[0];var versionMinor=versionArray[1];var versionRevision=versionArray[2];if(versionMajor>parseFloat(reqMajorVer)){return true;}else if(versionMajor==parseFloat(reqMajorVer)){if(versionMinor>parseFloat(reqMinorVer))
return true;else if(versionMinor==parseFloat(reqMinorVer)){if(versionRevision>=parseFloat(reqRevision))
return true;}}
return false;}}
function AC_AddExtension(src,ext)
{if(src.indexOf('?')!=-1)
return src.replace(/\?/,ext+'?');else
return src+ext;}
function AC_Generateobj(objAttrs,params,embedAttrs)
{var str='';if(isIE&&isWin&&!isOpera)
{str+='<object ';for(var i in objAttrs)
str+=i+'="'+objAttrs[i]+'" ';for(var i in params)
str+='><param name="'+i+'" value="'+params[i]+'" /> ';str+='></object>';}else{str+='<embed ';for(var i in embedAttrs)
str+=i+'="'+embedAttrs[i]+'" ';str+='> </embed>';}
return str;}
function AC_FL_GetContent(){var ret=AC_GetArgs
(arguments,".swf","movie","clsid:d27cdb6e-ae6d-11cf-96b8-444553540000","application/x-shockwave-flash");return(AC_Generateobj(ret.objAttrs,ret.params,ret.embedAttrs));}
function AC_FL_RunContent(){var ret=AC_GetArgs
(arguments,".swf","movie","clsid:d27cdb6e-ae6d-11cf-96b8-444553540000","application/x-shockwave-flash");document.write(AC_Generateobj(ret.objAttrs,ret.params,ret.embedAttrs));}
function AC_GetArgs(args,ext,srcParamName,classid,mimeType){var ret=new Object();ret.embedAttrs=new Object();ret.params=new Object();ret.objAttrs=new Object();for(var i=0;i<args.length;i=i+2){var currArg=args[i].toLowerCase();switch(currArg){case"classid":break;case"pluginspage":ret.embedAttrs[args[i]]=args[i+1];break;case"src":case"movie":args[i+1]=AC_AddExtension(args[i+1],ext);ret.embedAttrs["src"]=args[i+1];ret.params[srcParamName]=args[i+1];break;case"onafterupdate":case"onbeforeupdate":case"onblur":case"oncellchange":case"onclick":case"ondblClick":case"ondrag":case"ondragend":case"ondragenter":case"ondragleave":case"ondragover":case"ondrop":case"onfinish":case"onfocus":case"onhelp":case"onmousedown":case"onmouseup":case"onmouseover":case"onmousemove":case"onmouseout":case"onkeypress":case"onkeydown":case"onkeyup":case"onload":case"onlosecapture":case"onpropertychange":case"onreadystatechange":case"onrowsdelete":case"onrowenter":case"onrowexit":case"onrowsinserted":case"onstart":case"onscroll":case"onbeforeeditfocus":case"onactivate":case"onbeforedeactivate":case"ondeactivate":case"type":case"codebase":ret.objAttrs[args[i]]=args[i+1];break;case"id":case"width":case"height":case"align":case"vspace":case"hspace":case"class":case"title":case"accesskey":case"name":case"tabindex":ret.embedAttrs[args[i]]=ret.objAttrs[args[i]]=args[i+1];break;default:ret.embedAttrs[args[i]]=ret.params[args[i]]=args[i+1];}}
ret.objAttrs["classid"]=classid;if(mimeType)ret.embedAttrs["type"]=mimeType;return ret;}
SD.ReasonCodes={TIME_FINISHED:"timeFinished",USER_REPORTED:"userReported",USER_LEFT:"userLeft",USER_DISCONNECTED:"userDisconnected",BUSY:"busy",USER_INVALID:"userInvalid",VERSION_OBSOLETE:"versionObsolete",NOT_AVAILABLE:"notAvailable",JINGLE_FAILED:"jingleFailed"};
SD.BrowserDetect={init:function(){this.browser=this.searchString(this.dataBrowser)||"An unknown browser";this.version=(this.searchVersion(navigator.userAgent)||this.searchVersion(navigator.appVersion)||"an unknown version");this.OS=this.searchString(this.dataOS)||"an unknown OS";},searchString:function(data){for(var i=0;i<data.length;i++){var dataString=data[i].string;var dataProp=data[i].prop;this.versionSearchString=data[i].versionSearch||data[i].identity;if(dataString){if(dataString.indexOf(data[i].subString)!=-1){return data[i].identity;}}
else if(dataProp){return data[i].identity;}}},searchVersion:function(dataString){var index=dataString.indexOf(this.versionSearchString);if(index==-1){return;}
return parseFloat(dataString.substring(index+this.versionSearchString.length+1));},dataBrowser:[{string:navigator.userAgent,subString:"OmniWeb",versionSearch:"OmniWeb/",identity:"OmniWeb"},{string:navigator.vendor,subString:"Apple",identity:"Safari"},{prop:window.opera,identity:"Opera"},{string:navigator.vendor,subString:"iCab",identity:"iCab"},{string:navigator.vendor,subString:"KDE",identity:"Konqueror"},{string:navigator.userAgent,subString:"Firefox",identity:"Firefox"},{string:navigator.vendor,subString:"Camino",identity:"Camino"},{string:navigator.userAgent,subString:"Netscape",identity:"Netscape"},{string:navigator.userAgent,subString:"MSIE",identity:"Explorer",versionSearch:"MSIE"},{string:navigator.userAgent,subString:"Gecko",identity:"Mozilla",versionSearch:"rv"},{string:navigator.userAgent,subString:"Mozilla",identity:"Netscape",versionSearch:"Mozilla"}],dataOS:[{string:navigator.platform,subString:"Win",identity:"Windows"},{string:navigator.platform,subString:"Mac",identity:"Mac"},{string:navigator.platform,subString:"Linux",identity:"Linux"}]};SD.BrowserDetect.init();
SD.Cookie={create:function(name,value,days){var timeout=days&&days*24*60*60*1000;this._create(name,value,timeout);},_create:function(name,value,timeout){var expires="";if(timeout){var date=new Date();date.setTime(date.getTime()+timeout);expires="; expires="+date.toGMTString();}
document.cookie=name+"="+value+expires+"; path=/;";},read:function(name){var nameEQ=name+"=";var ca=document.cookie.split(';');for(var i=0;i<ca.length;i++){var c=ca[i];while(c.charAt(0)==' '){c=c.substring(1,c.length);}
if(c.indexOf(nameEQ)===0){return c.substring(nameEQ.length,c.length);}}
return null;},erase:function(name){this.create(name,"",-1);}};SD.Cookie.CounterWithTimeout=function(name,timeout){var _name='';var _timeout=0;var _values=null;var _load=function(){if(_values){return;}
var data=SD.Cookie.read(_name);_values=[];if(data){var values=data.split(',');var validAfter=Date.now()-_timeout;values.each(function(val){if(val>=validAfter){_values.push(val);}});}};var _save=function(){SD.Cookie._create(_name,_values.join(','),_timeout);};this.getValue=function(nocache){if(nocache){_values=null;_load();}
return _values.length;};this.increment=function(){_values.push(Date.now());_save();};this.reset=function(){_values=[];_save();}
if(!name){throw"cannot create counter w/o a name";}
if(!timeout){throw"if u dont need a timeout, use regular cookies";}
_name="counter_"+name;if(SD.Model.getMyself()){_name+="_"+SD.Model.getMyself().uid;}
_timeout=timeout*60*1000;_load();};SD.Cookie.PopupBlocker=function(name,days){var _name='';var _days=0;this.isBlocked=function(){return SD.Cookie.read(_name)}
this.block=function(){SD.Cookie.create(_name,1,_days)}
this.unblock=function(){SD.Cookie.erase(_name);}
_days=days;_name="SD_popupBlocker_"+name;if(SD.Model.getMyself()){_name+="_"+SD.Model.getMyself().uid;}}
SD.Tracking=new function(){function getFromHTML(sElement,sPrefix){if(!sElement){return null;}
var sId=$(sElement).id;var sTrackingElement=$(sId+':'+sPrefix);if(sTrackingElement){return sTrackingElement.innerHTML.strip();}
return null;};function setToHTML(sElement,sPrefix,sValue){sValue=sValue||'';if(!sElement){return null;}
var sId=$(sElement).id;var sTrackingElement=$(sId+':'+sPrefix);if(sTrackingElement){return sTrackingElement.innerHTML=sValue.strip();}
return null;}
this.getTrackingObject=function(sCode,sLocation,sReason,sElement){sElement=$(sElement);return SD.Config.getPaymentTrackingString(sCode||getFromHTML(sElement,'tc'),sLocation||getFromHTML(sElement,'tl'),sReason||getFromHTML(sElement,'tr'));};this.setElementTrackingCode=function(sElement,sCode){setToHTML(sElement,'tc',sCode);};this.setElementTrackingReason=function(sElement,sReason){setToHTML(sElement,'tr',sReason);};this.setElementTrackingLocation=function(sElement,sLocation){setToHTML(sElement,'tl',sLocation);};this.sendTrackingObject=function(tobj){siteURL=SD.Config.siteURL;url=siteURL+"/index.php?page=tracking&tobj="+tobj+"&tr_c=1&tr_p="+SD.Config.platform['platformId'];new Ajax.Request(url,{method:'get',onSuccess:function(){}});};this.getAndSendTrackingObject=function(sCode,sLocation,sReason,sElement){var tobj=this.getTrackingObject(sCode,sLocation,sReason,sElement);this.sendTrackingObject(tobj);};this.recordAction=function(className,trackingAction,params){siteURL=SD.Config.siteURL;url=siteURL+"/index.php?page=tracking&action=track&tAction="+trackingAction+"&class="+className;new Ajax.Request(url,{method:'post',parameters:params,onSuccess:function(){},onError:function(){}});}};
SD.Nav={initialized:false,historyUrl:'historyhelper.php',titlePrefix:'SpeedDate.com',sLoading:'Loading...',panelPrefix:'index.php?page=',panels:[{id:'speeddate',url:'',valid:false,title:'',noServer:true},{id:'search',url:'',valid:false,title:'search panel',noServer:false},{id:'members',url:'',valid:false,title:'members panel',noServer:false},{id:'likes_me',url:'',valid:false,title:'likes_me panel',noServer:false},{id:'my_results',url:'',valid:false,title:'my_results panel',noServer:false},{id:'messages',url:'',valid:false,title:'messages panel',noServer:false},{id:'profile',url:'',valid:false,title:'profile panel',noServer:false},{id:'site',url:'',valid:false,title:'site panel',noServer:false},{id:'default',url:'',valid:false,title:'default panel',noServer:false}],defaultPanel:'speeddate',baseUrl:'',pageUrl:'',activePath:'',activePathOld:null,activePanelId:'',activePanelIdOld:'',oHash:null,oHashOld:null,sTitle:null,sTitleOld:null,historyIndex:0,historyDisableUpdates:true,init:function(currentUrl){SD.Event.observe(null,SD.Nav.Events.HASH_CHANGE,function(e){SD.Nav.proxyTrackAnalytics&&SD.Nav.proxyTrackAnalytics(1,e.memo.hashNew);});SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){SD.Nav.proxyTrackAnalytics&&SD.Nav.proxyTrackAnalytics(e.memo.flirtee);});SD.Event.observe(null,SD.Nav.Events.INITIALIZED,SD.Nav.onContentLoad);SD.Event.observe(null,SD.Nav.Events.CONTENT_LOADED,SD.Nav.onContentLoad);if(currentUrl&&currentUrl.substr(0,this.panelPrefix.length)==this.panelPrefix){if(self.location.href.indexOf('#')==-1){self.location.href=self.location.href+'#'+currentUrl;}
var url=this.encode(currentUrl);if(url.charAt(0)!='#')
url='#'+url;this.activePath=url;var aHash=this.activePath.match(/#.+/g);var sHash=aHash?aHash[0]:'#';this.oHash=sHash.gsub('#','').toQueryParams();this.activePanelId=this.oHash.page;}
this.initialized=true;document.observe('dom:loaded',SD.Nav.onLoad.bind(SD.Nav));},onLoad:function(){this.historyIframe=$('history-iframe');this.pageUrl=self.location.href;this.history=[];if(this.pageUrl.indexOf('#')!=-1){this.pageUrl=this.pageUrl.substring(0,this.pageUrl.indexOf('#'));}
this.baseUrl=this.pageUrl.substring(0,this.pageUrl.lastIndexOf('/')+1);this.updateUrls(document.body);var initialActivePanelId=window.initialActivePanelId||this.defaultPanel;var activePanel=SD.Nav.getPanelById(initialActivePanelId);if(activePanel){activePanel.valid=true;this.lastRoot=$('content-'+initialActivePanelId);}
if(this.historyIframe){this.historyIframe.observe("load",function(ev){this.historyDisableUpdates=false;}.bindAsEventListener(this));}
this.setupNetworkActivityIndicator();if('onhashchange'in window){this.setupHashChange();}else{new PeriodicalExecuter(this.hashChangeHandlerProxyFromPE.bind(this),0.2);}
this.route();SD.Event.fire(null,SD.Nav.Events.INITIALIZED);},route:function(){var aHash=this.activePath.match(/#.+/g);var sHash=aHash?aHash[0]:'#';var oHash=sHash.gsub('#','').toQueryParams();if(this.extraRouting(oHash))return;this.navigateTo(this.decode(location.href));},extraRouting:function(oHash){if(oHash.page=='profile'&&oHash.action=='my_account'&&oHash.subpanel){SD.MyAccount.loadExpandFocusMenuItem(oHash.subpanel,oHash.focus);return true;}else if(oHash.page=='profile'&&oHash.action=='my_profile'&&oHash.subpanel){SD.MyProfile.activateTabMenu(oHash.subpanel,oHash.mode);return true;}
return false;},setupHashChange:function(){window.onhashchange=function(){SD.Nav.hashChangeHandlerProxyFromEvent.bind(SD.Nav).defer();};},parseUrlForJSExec:function(){if(location.hash.length<2){return false;}
var base=location.href.slice(0,location.href.indexOf('#')),hash=location.href.gsub('#','').toQueryParams();if(hash.jscall){SD.JSExecuter.parseAndExec(hash);delete hash.jscall;delete hash.jsparams;delete hash.jsdelay;location.replace(base+'#index.php?'+$H(hash).toQueryString());return true;}
return false;},hashChangeHandlerProxyFromEvent:function(){!this.parseUrlForJSExec()&&this.hashChangeHandler();},hashChangeHandlerProxyFromPE:function(){this.parseUrlForJSExec();this.hashChangeHandler();},hashChangeHandler:function(){var activePanel=this.getPanelById(this.activePanelId);if(window.location.href!=this.pageUrl+this.activePath||(activePanel&&activePanel.valid==false)){if(this.pageUrl==window.location.href.substring(0,this.pageUrl.length)){this.navigateTo(this.decode(window.location.href));if(this.historyIframe){this.historyIndex++;this.historyIframe.src=this.historyUrl+"?idx="+this.historyIndex+"&url="+escape(this.decode(self.location.href));this.historyDisableUpdates=true;}}}else if(this.historyIframe&&!this.historyDisableUpdates){var doc=this.historyIframe.contentWindow.document;var urlInput=doc.getElementById('history-url');var idxInput=doc.getElementById('history-idx');if(idxInput&&urlInput){if(idxInput.value!=this.historyIndex){window.location.href=this.encode(urlInput.value);this.navigateTo(urlInput.value);this.historyIndex=idxInput.value;}}}},setupNetworkActivityIndicator:function(){function updateIndicator(){(Ajax.activeRequestCount>0)?$('ajax-busy').show():$('ajax-busy').hide();}
Ajax.Responders.register({onCreate:function(){updateIndicator()},onComplete:function(){updateIndicator()},onException:function(){Ajax.activeRequestCount=Math.max(0,Ajax.activeRequestCount-1);updateIndicator();}});},updateLinks:function(root,encodeFunc){$(root)&&$(root).select('a').each(function(anchor){if(anchor.href&&anchor.rel!='nofollow'&&anchor.href.indexOf("page=payment")==-1){anchor.href=encodeFunc(anchor.href);}}.bind(this));},updateLinksInExternalPage:function(root){var externalEncodeFunc=function(url){return url.replace(SD.Config.siteURL+'/',SD.Config.siteURL+'/#');};SD.Nav.updateLinks(root,externalEncodeFunc.bind(this));},updateUrls:function(root){$(root).select('div.sd-command').each(function(e){SD.log('sd-command');if(e.hasClassName('sd-reload-buddies')){SD.log('sd-reload-buddies: '+e.innerHTML);var listStr="["+e.innerHTML+"]";var data=listStr.evalJSON(true);}else if(e.hasClassName('sd-update-profile')){SD.log('sd-update-profile');}else if(e.hasClassName('sd-external-redirect')){var navRedirectElement=e;var navRedirectUrl=navRedirectElement.innerHTML;navRedirectUrl=navRedirectUrl.replace(/&amp;/g,'&');location.href=navRedirectUrl;}else if(e.hasClassName('sd-nav-redirect')){var navRedirectUrl=e.innerHTML.replace(/&amp;/g,'&');this.invalidatePanel(this.getPanelFromDom(root));this.invalidateUrl(navRedirectUrl);this.redirectTo(this.encode(navRedirectUrl));}else if(e.hasClassName('sd-load-user')){var jsonData=SD.Base64.decode(e.innerHTML);var userData=jsonData.evalJSON();SD.User.importUserFromServer(userData);}else if(e.hasClassName('sd-load-users')){var jsonData=SD.Base64.decode(e.innerHTML);var usersData=jsonData.evalJSON();SD.User.importUsersFromServer(usersData);}else if(e.hasClassName('sd-exec-script')){try{SD.Utils.exec(e.innerHTML);}catch(exception){}}}.bind(this));this.updateLinks(root,this.encode.bind(this));var submitEventFunction=this.submitFormEventHandler.bind(this);var autoUploaderCallbackFunction=function(result){result=result.stripScripts();this.updateUrls((new Element("div")).update(result));}.bind(this);$(root).select('form').each(function(e){if(e.hasClassName("upload-profile-pic")){$(e).action+='&displayType=ajax';$(e).select('input').each(function(el){if(el.type=='file'){(new SD.AutoUploader(el,autoUploaderCallbackFunction));}}.bind(this));}else if(e.hasClassName("upload-profile-pic-popup")){$(e).action+='&displayType=ajax';$(e).select('input').each(function(el){if(el.type=='file'){(new SD.AutoUploader(el,autoUploaderCallbackFunction));}}.bind(this));}else if(e.hasClassName("upload-testimonial-pic")){$(e).action+='&displayType=ajax';(new SD.ImageUploader(e,function(result){this.updateUrls((new Element("div")).update(result));}.bindAsEventListener(this)));}else{e.addEventListener?e.addEventListener("submit",submitEventFunction,false):e.attachEvent("onsubmit",submitEventFunction);e=null;}}.bind(this));SD.Tooltip&&SD.Tooltip.Signup&&SD.Tooltip.Signup.init($(root));$(root).select('form').each(function(e){(new SD.CountryForm(e));}.bind(this));$(root).select('input.autocomplete').each(function(e){(new SD.AutoComplete(e));}.bind(this));$(root).select('div.result-message').each(function(e){(new SD.ResultMessage(e));}.bind(this));$(root).select('select.triggered-select').each(function(e){(new SD.TriggeredSelect(e));});var titleDiv=$(root).select('div.panel-title').first();if(titleDiv){this.updatePanelTitle(titleDiv.innerHTML);}else{this.updatePanelTitle('');}
SD.Nav.lastRoot=root;},redirectTo:function(url){SD.log('redirect:'+url);var curHash=location.href.include('#')?location.href.slice(location.href.indexOf('#')):'';if(curHash==url){location.href=url+(url.include('?')?'&':'?')+'_cb='+(new Date).getTime();}else{location.href=url;}},redirectTopTo:function(url){top.location.href=url;},submitFormEventHandler:function(ev){ev=ev||window.event;('preventDefault'in ev)&&ev.preventDefault();ev.returnValue=false;var target=ev.target||ev.srcElement;if(target.tagName=='INPUT'){target=target.form;}
var confirmDiv=$(target).select('div.confirm-message').first();if(confirmDiv){if(!confirm(confirmDiv.innerHTML)){return;}}
this.submitForm(target);},submitForm:function(form){form=$(form);var method=form.method?form.method.toLowerCase():'';if(method=='post'){form.request({parameters:{displayType:'ajax'},onComplete:function(transport){var container=form.up('div.inner-site');var content=SD.Nav.clearJS(transport.responseText);container.update(content);SD.Nav.updateUrls(container);}});}else{var action=form.action;if(action.substring(0,this.baseUrl.length)==this.baseUrl){action=action.substring(this.baseUrl.length);}
if(action.indexOf('?')==-1){action+='?';}else{action+='&';}
action+=$(form).serialize(false);self.location=this.pageUrl+'#'+action;}},navigateTo:function(url){url=this.encode(url);if(url.charAt(0)!='#'){url='#'+url;}
var activePathOld=this.activePath;this.oHashOld=this.oHash;this.activePath=url;var aHash=this.activePath.match(/#.+/g);var sHash=aHash?aHash[0]:'#';this.oHash=sHash.gsub('#','').toQueryParams();if(activePathOld!=this.activePath){SD.Event.fire.defer(null,SD.Nav.Events.HASH_CHANGE,{hashOld:this.oHashOld,hashNew:this.oHash});SD.Cookie.create('client-url',url,1);try{if(!this.oHashOld||this.oHash.page!=this.oHashOld.page){SD.Event.fire(null,SD.Nav.Events.PAGE_CHANGE,{hashOld:this.oHashOld,hashNew:this.oHash});}
if(!this.oHashOld||this.oHash.action!=this.oHashOld.action){SD.Event.fireDeferred(null,SD.Nav.Events.ACTION_CHANGE,{hashOld:this.oHashOld,hashNew:this.oHash});}}catch(error){}}
if(this.extraRouting(this.oHash)){return;}
var realUrl=this.decode(url);var panel=this.getPanelFromUrl(realUrl);if(!panel){return;}
this.activePathOld=null;if(this.oHash.page=='speeddate'){this.activatePanel('speeddate','members');}else{this.activatePanel(panel.id);}
if(!panel.noServer){if(panel.noCache||!panel.valid||realUrl!=panel.url){this.updatePanelTitle(this.sLoading);this.loadContent($('content-'+panel.id),realUrl,panel);}else{SD.Event.fire(null,SD.Nav.Events.PANEL_LOADED,{url:realUrl,panel:panel,element:$('content-'+panel.id)});}
var tabTitle=$$('#main-navigation .mod-'+panel.id+' .menu-item-text').first();if(tabTitle){tabTitle.href=this.encode(realUrl);}}else{SD.Event.fire(null,SD.Nav.Events.PANEL_LOADED,{url:realUrl,panel:panel,element:$('content-'+panel.id)});}
panel.url=realUrl;panel.valid=true;if(SD.ExperimentManager.ForeseeTest2323.value==1&&(SD.Config.platform.platformId==SD.Constants.PLATFORM.SITE)){try{if(typeof FSR!='undefined'){FSR.run();}}catch(e){}}},getPanelFromUrl:function(url){var panel=null;this.panels.each(function(p){var panelUrl=SD.Nav.panelPrefix+p.id;if(url.substring(0,panelUrl.length)==panelUrl){panel=p;}});if(!panel&&url.substring(0,this.panelPrefix.length)==this.panelPrefix){panel=this.getPanelById('default');}
return panel;},getPanelFromDom:function(dom){var panel;this.panels.each(function(p){if($('content-'+p.id)==dom){panel=p;}});return panel;},getPanelDom:function(panel){var panelId=typeof panel=='object'?panel.id:panel;return $('content-'+panelId);},getPanelTitle:function(panel){var dom=this.getPanelDom(panel);if(!dom)return;var titleDom=dom.select('.panel-title')[0];return titleDom?titleDom.innerHTML:'';},activatePanel:function(panelId,tabId){tabId=tabId||panelId;this.activePanelId=panelId;this.updatePanelTitle('');this.deactivateAllTabs();this.hideAllPanels();this.activateTab(tabId);this.showPanel(panelId);(panelId=='speeddate')?SD.Event.fire(null,SD.UIController.Events.SWITCHED_TO_SPEEDDATE):SD.Event.fire(null,SD.UIController.Events.SWITCHED_TO_OTHER_TABS);},activateTab:function(tabId){var tabs=$$('#main-navigation .mod-'+tabId);tabs.length&&tabs.invoke('addClassName','mod-current');},deactivateAllTabs:function(){var tabs=$$('#main-navigation .main-menu-item','#main-navigation .main-menu2-item');tabs.length&&tabs.invoke('removeClassName','mod-current');},hideAllPanels:function(){this.panels.each(function(p){SD.Nav.hidePanel(p)});},hidePanel:function(panel){if(typeof panel==='string'){panel=this.getPanelById(panel);}
$('content-'+panel.id).addClassName('inner-site-hidden');},showPanel:function(panel){if(typeof panel==='string'){panel=this.getPanelById(panel);}
$('content-'+panel.id).removeClassName('inner-site-hidden');},validateCurrent:function(){this.getPanelById(this.activePanelId).valid=true;},invalidatePanel:function(panel){if(typeof panel==='string'){panel=this.getPanelById(panel);}
panel&&(panel.valid=false);},invalidateUrl:function(url){url=this.decode(this.encode(url));this.panels.each(function(p){if(p.url==url){p.valid=false;}});},contentFilter:function(content){return content;},loadContent:function(el,url,panel){if(!url)return;(new Ajax.Request(url+"&displayType=ajax",{method:'get',onSuccess:function(transport){var content=SD.Nav.contentFilter(transport.responseText);el.update(this.clearJS(content));this.updateUrls(el);SD.Event.fireDeferred(null,SD.Nav.Events.CONTENT_LOADED,{url:url,element:el});SD.Event.fireDeferred(null,SD.Nav.Events.PANEL_LOADED,{url:url,panel:panel,element:el});}.bind(this)}));},clearJS:function(t){var sign='<!-- cut here';var idx=t.indexOf(sign);if(idx==-1){return t;}else{return t.substring(idx);}},encode:function(url){if(url.substring(0,1)=='/'){url=url.substring(1,url.length);}
if(this.baseUrl==url.substring(0,this.baseUrl.length)){url=url.substring(this.baseUrl.length,url.length);}
if(!url){return'#';}
var panel=null;this.panels.each(function(p){var panelUrl=this.panelPrefix+p.id;if(url.substring(0,panelUrl.length)==panelUrl){panel=p;}}.bind(this));if(panel||url=='close-popup'){return'#'+url;}else if(url.substring(0,this.panelPrefix.length)==this.panelPrefix){return'#'+url;}else{return url;}},decode:function(url){var pos=url.indexOf('#');return url.substring(pos+1,url.length);},updatePanelTitle:function(newTitle){newTitle=newTitle||'';if(newTitle!=this.sLoading&&this.sTitle!=newTitle){this.sTitleOld=this.sTitle;this.sTitle=newTitle;SD.Event.fire(null,SD.Nav.Events.TITLE_CHANGE,{'titleOld':this.sTitleOld,'titleNew':this.sTitle});}
document.title=this.titlePrefix+(newTitle?(' - '+newTitle):'');},getPanelById:function(panelId){var panel=null;this.panels.each(function(p){if(p.id==panelId){panel=p;}}.bind(this));return panel;},trackAnalytics:function(hash){var trackData;if(hash&&typeof hash=='object'&&hash.page){trackData=hash.action?'/'+hash.page+'/'+hash.action+'/':'/'+hash.page+'/';}else{trackData=this.decode(this.activePath);}
window.pageTracker&&window.pageTracker._trackPageview(trackData);},onContentLoad:function(e){var page=SD.Nav.oHash.page;var action=SD.Nav.oHash.action;var handlers=SD.Nav.onPanelLoadHandlers;if(handlers[page]){handlers[page]['default']&&handlers[page]['default'].call(SD.Nav,e);handlers[page][action]&&handlers[page][action].call(SD.Nav,e);}},onPanelLoadHandlers:{'members':(function(){var minMaxAgeSetup=function(){var minAge=$('s_min_age');var maxAge=$('s_max_age');minAge&&(minAge.onchange=function(){parseInt(maxAge.value,10)<parseInt(minAge.value,10)&&(maxAge.value=minAge.value)});maxAge&&(maxAge.onchange=function(){parseInt(maxAge.value,10)<parseInt(minAge.value,10)&&(minAge.value=maxAge.value)});};return{'default':function(){},'search':minMaxAgeSetup,'online_members':minMaxAgeSetup}})(),'likes_me':{'viewed_you':function(){SD.Indicators.Store.updateCounts({'newViewedMe':0});},'tagged_you':function(){SD.Indicators.Store.updateCounts({'newTaggedMe':0});},'favorited_you':function(){SD.Indicators.Store.updateCounts({'newFavoritedMe':0});},'want_to_date_you':function(){SD.Indicators.Store.updateCounts({'newInvitedMeToSpeedDate':0});},'flirted_with_you':function(){SD.Indicators.Store.updateCounts({'newEmailedMe':0});},'attempted_to_chat_with_you':function(){SD.Indicators.Store.updateCounts({'newTriedToChatWithMe':0});},'attempted_to_message_you':function(){SD.Indicators.Store.updateCounts({'newTriedToEmailMe':0});},'preference_analyzer_voted_you':function(){SD.Indicators.Store.updateCounts({'newChoseMe':0});}}}};SD.Nav.Events={PAGE_CHANGE:'SD.Nav.Events:PAGE_CHANGE',ACTION_CHANGE:'SD.Nav.Events:ACTION_CHANGE',HASH_CHANGE:'SD.Nav.Events:HASH_CHANGE',TITLE_CHANGE:'SD.Nav.Events:TITLE_CHANGE',PANEL_LOADED:'SD.Nav.Events:PANEL_LOADED',CONTENT_LOADED:'SD.Nav.Events:CONTENT_LOADED',INITIALIZED:'SD.Nav.Events:INITIALIZED',LAYOUT_UPDATED:'SD.Nav.Events:LAYOUT_UPDATED'};SD.JSExecuter={cleanRe:/[^0-9a-zA-Z\.\_\,\s]/g,validFunctionRe:/^SD.UIController.__url_[0-9a-zA-Z_]*$/,clean:function(str){return str&&str.strip().replace(this.cleanRe,'').replace('function','');},isValidFunction:function(fnStr){return fnStr.match(this.validFunctionRe);},prepareParams:function(str){str=this.clean(str);if(!str)return'';var a=str.split(',');for(var i=0;i<a.length;i++){a[i]=a[i].replace(' ','');if(isNaN(a[i])){a[i]="'"+a[i]+"'";}else{a[i]=a[i].indexOf('.')==-1?parseInt(a[i],10):parseFloat(a[i])}}
return a.join();},parseAndExec:function(jsParams){var fn=this.clean(jsParams.jscall),params=this.prepareParams(jsParams.jsparams),delay=parseFloat(jsParams.jsdelay)||0,expression="(function () {"+
fn+"("+params+")"+"}).delay("+delay+")";if(!fn||!this.isValidFunction(fn)){return;}
return this.evaluate(expression);},evaluate:function(str){try{return eval(str);}catch(e){return null;}}};
SD.NavUtils={submitForm:function(f){if(SD.Nav&&SD.Nav.initialized){SD.Nav.submitForm(f);}else{f.submit();}},getLocation:function(){if(SD.Nav&&SD.Nav.initialized){return SD.Nav.baseUrl+SD.Nav.decode(SD.Nav.activePath);}else{return self.location.href;}},setLocation:function(location){if(SD.Nav&&SD.Nav.initialized){location=SD.Nav.pageUrl+SD.Nav.encode(location);}
self.location.href=location;},arrayToQueryString:function(key,arr){if(arr.length==0){return''}
var a=[],str='';for(var i=0;i<arr.length;i++){a.push(encodeURIComponent(key)+'='+encodeURIComponent(arr[i]));}
return a.join('&');},queryString:function(obj){var vars=[];for(var key in obj){if(Object.isArray(obj[key])){vars.push(this.arrayToQueryString(key,obj[key]));}else if(typeof obj[key]=='object'&&obj[key]!==null){vars.push(this.queryString(obj[key]));}else{if(obj[key]==null){obj[key]='';}
vars.push(encodeURIComponent(key)+'='+encodeURIComponent(obj[key]));}}
return vars.join('&');},link:function(controller,action,params){var baseUrl=SD.Config.getLinkBase(controller,action||'');return!params?baseUrl:baseUrl+'&'+(typeof params=='string'?params:this.queryString(params));},linkSecure:function(controller,action,params){var baseUrl=SD.Config.getLinkBase(controller,action);baseUrl=baseUrl.replace(/^http:\/\/[^\/]+\//i,SD.Config.g_http_secure+'/');return!params?baseUrl:baseUrl+'&'+this.queryString(params);},getUrlHashParams:function(){var hash='';if(Prototype.Browser.IE6){hash=location.href.match(/#.+/g);hash=hash?hash[0]:'#';}else{hash=location.hash;}
return hash.gsub('#','').toQueryParams();},getUrlHashBase:function(){return location.hash.split('?')[0];},updateUrlHashParams:function(urlHashObject){var updatedUrlHashObject=$H(this.getUrlHashParams()).merge(urlHashObject).toObject();this.setUrlHashParams(updatedUrlHashObject);},setUrlHashParams:function(urlHashObject){if(urlHashObject){location.hash=this.getUrlHashBase()+'?'+$H(urlHashObject).toQueryString();}else{location.hash='';}},getPreviousTitle:function(){return SD.Nav.sTitleOld;},getCurrentTitle:function(){return SD.Nav.sTitle;},goTo:function(controller,action,params){location.hash=SD.Nav.encode(SD.NavUtils.link(controller,action,params));},goToUrl:function(url){location.hash=SD.Nav.encode(url);}};
SD.UI=SD.UI||{};SD.UI.Menu=Class.create({onMouseOutDelay:100,initialize:function(mainMenuItem,subMenu){this.state='closed';this.timer=null;this.mainMenuItem=$(mainMenuItem);this.subMenu=$(subMenu);this.subMenu.select('ul').first().style.display="block";this.subMenu.style.display="none";this.boundedCloseMenu=this.closeMenu.bind(this);this.setupShim();this.setupEvents();},setupShim:function(){if(Prototype.Browser.IE6){this.shim=$(document.createElement('IFRAME'));this.subMenu.parentNode.insertBefore(this.shim,this.subMenu);this.shim.addClassName('menu-iframe');this.shim.style.height=this.subMenu.offsetHeight+'px';this.shim.style.width=this.subMenu.offsetWidth+'px';}},setupEvents:function(){this.mainMenuItem.observe('mouseenter',this.onMouseOverMainMenuItem.bind(this));this.mainMenuItem.observe('mouseleave',this.onMouseOutMainMenuItem.bind(this));this.mainMenuItem.observe('click',this.onClickMainMenuItem.bind(this));this.subMenu.observe('mouseenter',this.onMouseOverSubMenu.bind(this));this.subMenu.observe('mouseleave',this.onMouseOutSubMenu.bind(this));this.subMenu.observe('click',this.onClickSubMenu.bind(this));},openMenu:function(){clearTimeout(this.timer);this.subMenu.style.display='block';if(this.shim){this.shim.style.display='block';}
this.state='open';},closeMenu:function(){clearTimeout(this.timer);this.subMenu.style.display='none';if(this.shim){this.shim.style.display='none';}
this.state='closed';},toggleMenu:function(){(this.state=='open')?this.closeMenu():this.openMenu();},onMouseOverMainMenuItem:function(){this.openMenu();},onMouseOutMainMenuItem:function(){clearTimeout(this.timer);this.timer=setTimeout(this.boundedCloseMenu,this.onMouseOutDelay);},onClickMainMenuItem:function(){this.toggleMenu();},onMouseOverSubMenu:function(){clearTimeout(this.timer);},onMouseOutSubMenu:function(){clearTimeout(this.timer);this.timer=setTimeout(this.boundedCloseMenu,this.onMouseOutDelay);},onClickSubMenu:function(){this.closeMenu();}});SD.UI.NewMenu=Class.create({initialize:function(options){this.id=SD.Utils.IdGenerator.generate();SD.UI.NewMenu.instances=SD.UI.NewMenu.instances||{};SD.UI.NewMenu.instances[this.id]=this;this.parentSelector=options.parentSelector;this.submenuSelector=options.submenuSelector;this.openedMenu=null;this.menus={};this.setup();},setup:function(){if(Prototype.Browser.IE6){this.setupShim();}
this.setupMenus();document.observe('mousedown',function(e){for(var i in this.menus){if($(e.target).descendantOf(this.menus[i].dom)||e.target==this.menus[i].dom){return;}}
this.closeAllMenus();}.bind(this));},setupMenus:function(){$$(this.parentSelector).each(function(domMenu){domMenu.id=domMenu.id||this.generateId();this.menus[domMenu.id]=new SD.UI.NewMenu.Menu({id:domMenu.id,dom:domMenu,domHandle:domMenu,domSubmenu:domMenu.select(this.submenuSelector).first(),domShim:this.domShim,menuManager:this});domMenu.setAttribute('sdType',domMenu.getAttribute('sdType')?(domMenu.getAttribute('sdType')+' menu'):'menu');domMenu.setAttribute('sdMainMenu',this.id);domMenu.setAttribute('sdMenu',domMenu.id);},this);},setupShim:function(){this.domShim=$(document.createElement('IFRAME'));$(document.body).insertBefore(this.domShim,document.body.firstChild);this.domShim.addClassName('menu-iframe');this.domShim.style.zIndex=1;},generateId:function(){return SD.UI.NewMenu.menuIdPrefix+(SD.UI.NewMenu.menuCount++);},onDocumentClick:function(wrapper){wrapper.isMarkedForClose=false;this.closeSubmenu(wrapper);},openMenu:function(menu){this.openedMenu&&this.openedMenu.close();menu&&menu.open();this.openedMenu=menu;},closeMenu:function(menu){menu&&menu.close();this.openedMenu=null;},closeAllMenus:function(){this.openedMenu&&this.closeMenu(this.openedMenu);}});SD.UI.NewMenu.menuCount=0;SD.UI.NewMenu.menuIdPrefix='sd-ui-menu-item';SD.UI.NewMenu.Menu=Class.create({initialize:function(options){this.id=options.id;this.dom=$(options.dom);this.domHandle=$(options.domHandle);this.domSubmenu=options.domSubmenu&&$(options.domSubmenu);this.domShim=Prototype.Browser.IE6?$(options.domShim):null;this.isOpen=false;this.menuManager=options.menuManager;this.setup();},setup:function(){this.domSubmenu&&this.domSubmenu.observe('click',this.onSubmenuClick.bind(this));this.dom.observe('mouseenter',this.onMouseEnter.bind(this));this.dom.observe('mouseleave',this.onMouseLeave.bind(this));},onSubmenuClick:function(e){if(this.domSubmenu&&this.domSubmenu.hasClassName('lib-stay-open-onclick')){if(e.target.tagName.toUpperCase()==='SELECT'){return;}}else{this.menuManager.closeMenu(this);}},onMouseEnter:function(e){this.menuManager.openMenu(this);},onMouseLeave:function(e){if(e.fromElement&&e.fromElement.tagName.toUpperCase()==='SELECT'){return}
this.menuManager.closeMenu(this);},open:function(){if(this.isOpeningBlocked)return;this.isOpen=true;if(!this.dom.hasClassName('mod-on')){this.dom.addClassName('mod-on');}
this.domShim&&this.showShim();},close:function(){if(this.isClosingBlocked)return;this.isOpen=false;this.dom.removeClassName('mod-on');this.domShim&&this.hideShim();},showShim:function(){this.positionShim();this.domShim.style.visibility='visible';},hideShim:function(){this.domShim.style.visibility='hidden';},positionShim:function(){if(this.domShim&&this.domSubmenu){var offsets=this.domSubmenu.cumulativeOffset();this.domShim.style.top=offsets.top+'px';this.domShim.style.left=offsets.left+'px';this.domShim.style.width=this.domSubmenu.offsetWidth+'px';this.domShim.style.height=this.domSubmenu.offsetHeight+'px';}}});
SD.Favicon={defaultPause:2000,defaultTitle:"SpeedDate.com",defaultIcon:"favicon.ico",defaultSequenceSteps:1000,_docHead:document.getElementsByTagName("head")[0],_loopTimer:null,change:function(iconURL,docTitle){this._stopAnimation();if(docTitle){document.title=docTitle;}
this._addLink(iconURL,true);},animate:function(iconSequence,titleSequence,pause,sequenceSteps){var _this=this;var index=0;this._preloadIcons(iconSequence);this.iconSequence=iconSequence;this.titleSequence=titleSequence;this.sequencePause=pause||this.defaultPause;this.sequenceCounter=sequenceSteps||this.defaultSequenceSteps;this.change(iconSequence[0],titleSequence[0]);this._loopTimer=setInterval(function(){_this._addLink(_this.iconSequence[index%_this.iconSequence.length]);document.title=_this.titleSequence[index%_this.titleSequence.length];index++;_this.sequenceCounter--;if(_this.sequenceCounter<0){_this.sequenceCounter=0;_this.change(_this.defaultIcon,_this.defaultTitle);}},_this.sequencePause);},animateTitle:function(titles,sequenceSteps){var str="";var anim=[];anim.push("SpeedDate.com");for(var i=0;i<titles.length;i++){anim.push(titles[i]);}
this.animate([SD.Config.siteURL+"/favicon.ico",SD.Config.siteURL+"/favicon2.ico",SD.Config.siteURL+"/favicon3.ico"],anim,1000,sequenceSteps);},setTitle:function(title){if(title===""||title===undefined){title=this.defaultTitle;}
this.change(this.defaultIcon,title);},_stopAnimation:function(){if(this._loopTimer){clearInterval(this._loopTimer);this._loopTimer=null;}},_preloadIcons:function(iconSequence){var dummyImageForPreloading=document.createElement("img");for(var i=0;i<iconSequence.length;i++){dummyImageForPreloading.src=iconSequence[i];}},_addLink:function(iconURL){var link=document.createElement("link");link.type="image/x-icon";link.rel="shortcut icon";link.href=iconURL;this._removeLinkIfExists();this._docHead.appendChild(link);},_removeLinkIfExists:function(){var links=this._docHead.getElementsByTagName("link");for(var i=0;i<links.length;i++){var link=links[i];if(link.type=="image/x-icon"&&link.rel=="shortcut icon"){this._docHead.removeChild(link);return;}}}};
SD.AutoUploader=Class.create({fileElement:null,formElement:null,iframeElement:null,callbackFunc:null,name:null,boundOnLoadData:null,initialize:function(fileElement,callback){this.fileElement=$(fileElement);this.formElement=fileElement.form;this.callbackFunc=callback;this.boundOnLoadData=this.onLoadData.bindAsEventListener(this);this.name="autouploader_"+Math.ceil(Math.random()*10000);var div=$(document.createElement('DIV'));div.addClassName('autouploader-iframe');this.formElement.appendChild(div);div.innerHTML="<iframe class=\"autouploader-iframe\" id=\""+this.name+"\" name=\""+this.name+"\"></iframe>";this.iframeElement=$(this.name);this.formElement.target=this.name;this.fileElement.observe("change",this.onChange.bindAsEventListener(this));},onChange:function(ev){SD.log("submit");this.iframeElement.observe("load",this.boundOnLoadData);this.formElement.submit();Ajax.activeRequestCount++;this.fileElement.disabled=true;},onLoadData:function(ev){Ajax.activeRequestCount--;this.iframeElement.stopObserving("load",this.boundOnLoadData);var result=this.iframeElement.contentWindow.document.body.innerHTML;if(this.callbackFunc!==null){this.callbackFunc(result);}}});
SD.CountryForm=Class.create({initialize:function(formElement){formElement=$(formElement);var countrySelect=formElement.select('select[name=country]').first();var cityInput=formElement.select('input[name=city]').first();var zipcodeInput=formElement.select('input[name=zipcode]').first();if(countrySelect&&cityInput&&zipcodeInput){countrySelect.observe('change',this.onChange.bindAsEventListener(this));this.onChange(null,countrySelect);}},onChange:function(ev,el){if(ev){el=Event.element(ev);}
var formElement=$(el.form);var cityInput=formElement.select('input[name=city]').first();var zipcodeInput=formElement.select('input[name=zipcode]').first();var country=el.options[el.selectedIndex].value;var trCity=cityInput.up('tr')
var trZip=zipcodeInput.up('tr')
if(country=='US'||country=='USt'||country=='CA'){if(trCity.getAttribute('sdHideMode')=='two-rows'){trCity.previous().hide();trCity.hide();trZip.previous().show();trZip.show();}else{trCity.hide();trZip.show();}}else{if(trCity.getAttribute('sdHideMode')=='two-rows'){trCity.previous().show();trCity.show();trZip.previous().hide();trZip.hide();}else{trCity.show();trZip.hide();}}}});$(document).observe('dom:loaded',function(){$$('form').each(function(f){(new SD.CountryForm(f));});});
SD.AutoComplete=Class.create({idElement:null,textElement:null,divElement:null,listingElement:null,iframe:null,timer:null,value:'',currentList:[],zIndex:null,initialize:function(idElement,zIndex)
{this.zIndex=zIndex;this.idElement=$(idElement);this.idElement.style.display='none';this.divElement=$(document.createElement('DIV'));this.divElement.addClassName('autocomplete');this.idElement.parentNode.insertBefore(this.divElement,this.idElement);this.textElement=$(document.createElement('INPUT'));this.textElement.type='TEXT';this.divElement.appendChild(this.textElement);this.textElement.className=this.idElement.className;this.textElement.removeClassName('autocomplete');this.createListing();var val=this.idElement.value;var pos=val.indexOf(',');this.textElement.value=(pos==-1)?val:val.substring(pos+1);this.textElement.observe('blur',this.onBlur.bindAsEventListener(this));this.textElement.observe('focus',this.onFocus.bindAsEventListener(this));},createListing:function()
{if(this.listingElement){this.listingElement.parentNode.removeChild(this.listingElement);}
this.listingElement=$(document.createElement('DIV'));this.listingElement.addClassName('autocomplete-listing');this.listingElement.style.display='none';this.listingElement.style.position='absolute';if(this.zIndex){this.listingElement.style.zIndex=this.zIndex;}
this.divElement.appendChild(this.listingElement);this.currentList.each(function(item){var a=$(document.createElement('A'));var span1=$(document.createElement('SPAN'));var span2=$(document.createElement('SPAN'));span1.addClassName('name');span2.addClassName('description');span1.innerHTML=item.name;span2.innerHTML=item.description;a.href='#';a.observe('click',function(ev){this.onClick(item);ev.stop();}.bindAsEventListener(this));a.appendChild(span1);a.appendChild(span2);this.listingElement.appendChild(a);}.bind(this));},onClick:function(item)
{SD.log("onClick(): id:"+item.id+", name:"+item.name);this.textElement.value=item.name;this.idElement.value=item.id+","+item.name;},onFocus:function(ev)
{SD.log("onFocus");this.timer=new PeriodicalExecuter(this.onTimer.bind(this),0.5);this.onTimer(null);},onBlur:function(ev)
{SD.log("onBlur");if(this.timer!==null){this.timer.stop();}
(new PeriodicalExecuter(function(pe){pe.stop();this.listingElement.style.display='none';this.listingElement.parentNode.removeChild(this.listingElement);this.divElement.appendChild(this.listingElement);var found=false;this.currentList.each(function(item){if(item.name.toLowerCase()==this.textElement.value.toLowerCase())
{this.onClick(item);found=true;}}.bind(this));if(!found)
{var item={id:0,name:this.textElement.value,desc:''};this.onClick(item);}}.bind(this),0.5));},onTimer:function(pe)
{if(this.textElement.value!=this.value)
{this.value=this.textElement.value;if(this.textElement.value.length<2)
{this.listingElement.style.display='none';}
else if(this.textElement.value.length>=2)
{var formElement=$(this.idElement.form);var params=formElement.serialize(true);params._name=this.idElement.name;params._value=this.textElement.value;var url='/autocomplete.php';(new Ajax.Request(url,{method:'GET',parameters:params,onSuccess:function(transport)
{this.currentList=transport.responseText.evalJSON();this.createListing();this.listingElement.style.display='block';this.divElement.removeChild(this.listingElement);$(document.body).appendChild(this.listingElement);this.listingElement.clonePosition(this.textElement,{setWidth:false,setHeight:false,offsetTop:this.textElement.getHeight()});}.bind(this)}));}}}});document.observe('dom:loaded',function(){$$('input.autocomplete').each(function(e){(new SD.AutoComplete(e));});});
SD.Tooltip=function(){var id='tt',topOffset=10,leftOffset=10,maxWidth=300,minWidth=120,dom,domTop,domContent,domBottom,shim,ie=!!document.all,width=0,height=0,timer,timeInterval=20,timerToStay,timeToStay1=4000,timeToStay2=8000,speed=10,endalpha=100,alpha=0,orientation='br',orientations={'tl':1,'tr':1,'bl':1,'br':1};return{defaultOrientation:'br',range:function(){var vDim=document.viewport.getDimensions(),vScrollOffsets=document.viewport.getScrollOffsets();return{x1:vScrollOffsets.left,y1:vScrollOffsets.top,x2:vDim.width+vScrollOffsets.left,y2:vDim.height+vScrollOffsets.top};},updateRange:function(){this._range=(typeof(this.range)=="function")?this.range():this.range;},setupShim:function(refEl){if(Prototype.Browser.IE6){shim=$(document.createElement('IFRAME'));refEl.parentNode.insertBefore(shim,refEl);shim.addClassName('menu-iframe');shim.style.height=refEl.offsetHeight+'px';shim.style.width=refEl.offsetWidth+'px';shim.style.zIndex=refEl.getStyle('z-index')||1;shim.style.display='none';shim.style.position='absolute';shim.style.filter='alpha(opacity=99)';}},buildDom:function(){dom=document.createElement('div');domTop=document.createElement('div');domContent=document.createElement('div');domBottom=document.createElement('div');dom.id=id;domTop.id=id+'top';domContent.id=id+'cont';domBottom.id=id+'bot';dom.appendChild(domTop);dom.appendChild(domContent);dom.appendChild(domBottom);dom.style.opacity=0;dom.style.filter='alpha(opacity=0)';document.body.appendChild(dom);Event.observe(document,'mousemove',this.onMouseMove.bind(this));this.setupShim(dom);},show:function(content,w,maxW,orientation){if(!this._range){this.updateRange();}
if(!dom){this.buildDom();}
this.setOrientation(orientation);dom.style.display='block';domContent.innerHTML=content;dom.style.width=w?w+'px':'auto';maxW=maxW||maxWidth;width=Math.max(Math.min(maxW,dom.offsetWidth),minWidth);height=dom.offsetHeight;if(!w&&ie){domTop.style.display='none';domBottom.style.display='none';dom.style.width=width;domTop.style.display='block';domBottom.style.display='block';}
dom.style.width=width+'px';shim&&shim.show();if(shim){shim.style.width=dom.offsetWidth+'px';shim.style.height=dom.offsetHeight+'px';}
clearInterval(timer);timer=setInterval(function(){SD.Tooltip.fade(1);},timeInterval);clearTimeout(timerToStay);timerToStay=setTimeout(function(){SD.Tooltip.hide();},content.length>20?timeToStay2:timeToStay1);},hide:function(){if(!dom){return;}
clearInterval(timer);clearTimeout(timerToStay);timer=setInterval(function(){SD.Tooltip.fade(-1);},timeInterval);},setOrientation:function(or){if(or&&orientations[or]){orientation=or;}else{orientation=this.defaultOrientation;}},getOrientation:function(){return orientation;},onMouseMove:function(e){if(!dom){return;}
var vScrollOffsets=document.viewport.getScrollOffsets();switch(orientation){case'tl':this.moveTo(e.clientX-leftOffset+vScrollOffsets.left-dom.offsetWidth,e.clientY-topOffset+vScrollOffsets.top-dom.offsetHeight);break;case'tr':this.moveTo(e.clientX+leftOffset+vScrollOffsets.left,e.clientY-topOffset+vScrollOffsets.top-dom.offsetHeight);break;case'bl':this.moveTo(e.clientX-leftOffset+vScrollOffsets.left-dom.offsetWidth,e.clientY+topOffset+vScrollOffsets.top);break;case'br':this.moveTo(e.clientX+leftOffset+vScrollOffsets.left,e.clientY+topOffset+vScrollOffsets.top);break;}},moveTo:function(x,y){if(x!=null&&!isNaN(x)){if(this._range){if(this._range.x1>x){x=this._range.x1;}
else if(this._range.x2<x+width){x=this._range.x2-width;}}
dom.style.left=x+'px';}
if(y!=null&&!isNaN(y)){if(this._range){if(this._range.y1>y){y=this._range.y1;}
else if(this._range.y2<y+height){y=(this._range.y2-height);}}
dom.style.top=y+'px';}
if(shim){shim.style.top=dom.style.top;shim.style.left=dom.style.left;}},fade:function(d){if(!dom){return;}
var a=alpha;if((a!=endalpha&&d==1)||(a!==0&&d==-1)){var i=speed;if(endalpha-a<speed&&d==1){i=endalpha-a;}else if(alpha<speed&&d==-1){i=a;}
alpha=a+(i*d);dom.style.opacity=alpha*0.01;dom.style.filter='alpha(opacity='+alpha+')';}else{clearInterval(timer);if(d==-1){dom.style.display='none';shim&&shim.hide();}}}};}();SD.Tooltip.Signup=Class.create({baseElement:null,iframe:null,tooltipDiv:null,isShown:false,currentFocusedElement:null,initialize:function(base){this.baseElement=$(base);var tips=this.baseElement.select('div.tooltip-text');if(tips.length==0){return;}
this.baseElement.select('input, select, textarea').each(function(baseElement){baseElement.observe('focus',this.onFocus.bindAsEventListener(this));baseElement.observe('blur',this.onBlur.bindAsEventListener(this));baseElement.observe('change',this.onChange.bind(this));}.bind(this));this.setupTooltip(tips.first());SD.Tooltip.Signup.items.push(this);this._onNavigatingAway=this._onNavigatingAway.bind(this);this._onContentLoaded=this._onContentLoaded.bind(this);this.setupExternalEvents();},setupTooltip:function(domTip){this.tooltipDiv=$(document.createElement('DIV')).addClassName('tooltip');var divB=$(document.createElement('DIV')).addClassName('b');var divC=$(document.createElement('DIV')).addClassName('c');this.tooltipDiv.appendChild(divB);divB.appendChild(divC);divC.appendChild(domTip);if(Prototype.Browser.IE6){this.iframe=$(document.createElement('IFRAME'));this.iframe.addClassName('menu-iframe');this.iframe.style.display='none';$(document.body).appendChild(this.iframe);}
this.tooltipDiv.hide();$(document.body).appendChild(this.tooltipDiv);},setupExternalEvents:function(){SD.Event.observe(null,SD.Nav.Events.HASH_CHANGE,this._onNavigatingAway);SD.Event.observe(null,SD.Tooltip.Signup.Events.TOOLTIP_SHOW,this.onShow.bind(this));this.pe=new PeriodicalExecuter(function(pe){this._checkForDestroy();}.bind(this),0.5);},_onNavigatingAway:function(){if(this.currentFocusedElement){try{this.currentFocusedElement.blur();}catch(e){this.onBlur();}
this.currentFocusedElement=null;}},_onContentLoaded:function(){this._checkForDestroy();},_checkForDestroy:function(){if(!this.baseElement.isInDOMTree()){this.destroy();}},onFocus:function(ev){SD.Tooltip.Signup.currentVisible=this;this.currentFocusedElement=ev.target;this.show.bind(this).delay(0.2);this.setZIndex(ev.target);},onBlur:function(ev){this.hide();},onShow:function(ev){if(ev.memo.source==this){return;}else{this.hide();}},onChange:function(){this.show();},show:function(){this.isShown=true;this.position();SD.Event.fire(null,SD.Tooltip.Signup.Events.TOOLTIP_SHOW,{source:this});},hide:function(){this.isShown=false;if(this.iframe){this.iframe.style.display='none';}
this.tooltipDiv&&this.tooltipDiv.hide();},setZIndex:function(refElement){var zIndex=$(refElement).getTrueZ()+1;if(this.iframe){this.iframe.style.zIndex=zIndex;}
this.tooltipDiv.style.zIndex=zIndex;},position:function(){this.tooltipDiv.clonePosition(this.baseElement,{setWidth:false,setHeight:false,offsetLeft:this.getInternalEdge(this.baseElement)-this.baseElement.cumulativeOffset().left});this.tooltipDiv.style.display='block';if(this.iframe){this.iframe.style.display='block';this.iframe.clonePosition(this.tooltipDiv);}},getInternalEdge:function(el){var innerRightEdge=-1;$(el).childElements().each(function(childEl){var x=childEl.cumulativeOffset().left+childEl.getWidth();if(childEl.tagName=='INPUT'&&childEl.type=='file'){if(SD.BrowserDetect&&SD.BrowserDetect.OS=='Mac'&&SD.BrowserDetect.browser=='Firefox'){x+=60;}}
innerRightEdge=Math.max(innerRightEdge,x);});return innerRightEdge;},destroy:function(){if(this.pe){this.pe.stop();}
if(this.tooltipDiv){this.tooltipDiv.update();this.iframe&&this.iframe.parentNode&&this.iframe.parentNode.removeChild(this.iframe);this.tooltipDiv.parentNode&&this.tooltipDiv.remove();}
this.tooltipDiv=null;this.iframe=null;this.baseElement=null;this.currentFocusedElement=null;if(this==SD.Tooltip.Signup.currentVisible){SD.Tooltip.Signup.currentVisible=null;}
SD.Tooltip.Signup.items=SD.Tooltip.Signup.items.without(this);SD.Event.stopObserving(null,SD.Nav.Events.HASH_CHANGE,this._onNavigatingAway);SD.Event.stopObserving(null,SD.Nav.Events.CONTENT_LOADED,this._onContentLoaded);}});Object.extend(SD.Tooltip.Signup,{currentVisible:null,items:[],init:function(root){var bases=root?root.select('.tooltip-base'):$$('.tooltip-base');bases.each(function(base){new SD.Tooltip.Signup(base);});SD.Event.observe(null,SD.Nav.Events.CONTENT_LOADED,function(e){var bases=e.memo.element.select('.tooltip-base');if(bases.length>0){SD.Tooltip.Signup.focusFirstItem(bases);}});SD.Event.observe(null,SD.UIController.Events.LAYOUT_UPDATED,function(){if(SD.Tooltip.Signup.currentVisible){SD.Tooltip.Signup.currentVisible.position();}});},destroyAllInEl:function(el){el=$(el);var itemsToDelete=SD.Tooltip.Signup.items.findAll(function(item){return item.baseElement.descendantOf(el);});itemsToDelete.length&&[].without.apply(SD.Tooltip.Signup.items,itemsToDelete);},onReposition:function(){var tooltip=SD.Tooltip.Signup.currentVisible;if(tooltip&&tooltip.isShown){if(Prototype.Browser.IE6||Prototype.Browser.IE7){tooltip.hide();}else{tooltip.position();}}},focusFirstItem:function(bases){if(bases.first()){var firstInput=bases.first().select('input, select, textarea').first();if(firstInput){firstInput._sd_focus_timer&&window.clearTimeout(firstInput._sd_focus_timer);firstInput._sd_focus_timer=window.setTimeout(function(){try{firstInput.focus();if(document.activeElement&&document.activeElement!=firstInput){SD.Tooltip.Signup.focusFirstItem.bind(SD.Tooltip.Signup).delay(1,bases);}}catch(e){SD.Tooltip.Signup.focusFirstItem.bind(SD.Tooltip.Signup).delay(1,bases);}},200);}}},Events:{TOOLTIP_SHOW:"SD.Tooltip.Signup.Events:TOOLTIP_SHOW"}});Event.observe(document,'dom:loaded',SD.Tooltip.Signup.init.bind(SD.Tooltip.Signup,document.body));Event.observe(window,'resize',SD.Tooltip.Signup.onReposition.bind(SD.Tooltip.Signup));Event.observe(window,'resize',SD.Tooltip.updateRange.bind(SD.Tooltip));Event.observe(window,'scroll',SD.Tooltip.updateRange.bind(SD.Tooltip));
function invite_select_all(checked,form_id){if(checked){check_all(form_id,true);}else{check_all(form_id,false);}}
function check_all(id,checked){var el=document.getElementById(id);for(var i=0;i<el.elements.length;i++){if(el.elements[i].getAttribute("type")!="checkbox"){continue;}
el.elements[i].checked=checked;}}
var _dominate=function(basis){var _styleAttribute=function(val){if(typeof(val)==""){return val;}else{var rv=[];for(var k in val){rv.push(String(k)+":"+String(val[k]));}
return rv.join(";");}};var _safeAttributeSet=function(_e,attr,val){attr=attr.toLowerCase();if(attr=='class'){val=val.split(" ");for(var v=0;v<val.length;v++){Element.addClassName(_e,val[v]);}}else if(attr=='style'){Element.setStyle(_e,_styleAttribute(val));}else if(attr.startsWith('observe')){Event.observe(_e,attr.substring(7).toLowerCase(),val);}else{_e.setAttribute(attr,val);}};var generateDOMElement=function(el){if(typeof(el)=='function')
return(el());else if((typeof(el)=='string')||(typeof(el)=='number'))
return(document.createTextNode(el));else
return(el);}
var createDOM=function(n,attrs){var _e;if(Prototype.Browser.IE&&(n=="input")&&attrs.name){_e=document.createElement('<input name="'+attrs.name+'"/>');}else{_e=document.createElement(n);}
_e=Element.extend(_e);if(n=="a"){_e.href="#";_e.onclick=function(){return false;};}
for(var attr in attrs){_safeAttributeSet(_e,attr,attrs[attr]);}
if((arguments!=null)&&(arguments.length>2)){var node_args=arguments[2];for(var i=1;i<node_args.length;++i){var obj=node_args[i];if(typeof(obj)=='object'&&obj.each){obj.each(function(el){_e.appendChild(generateDOMElement(el));});}else{_e.appendChild(generateDOMElement(obj));}}}
return _e;}
var _nodes=['table','tbody','thead','tr','th','td','a','strong','div','img','br','b','i','u','span','li','ul','ol','iframe','form','h1','input','button','h2','h3','h4','p','br','select','option','optgroup','label','textarea','em'];for(var i=0;i<_nodes.length;i++){var node=_nodes[i].toUpperCase();var nodeName=_nodes[i];var makeFunction=function(nodeName){return function(attrs){return createDOM(nodeName,attrs,arguments);};};basis[node]=makeFunction(nodeName);}};_dominate(self);
function FABridge(target,bridgeName)
{this.target=target;this.remoteTypeCache={};this.remoteInstanceCache={};this.remoteFunctionCache={};this.localFunctionCache={};this.bridgeID=FABridge.nextBridgeID++;this.name=bridgeName;this.nextLocalFuncID=0;FABridge.instances[this.name]=this;FABridge.idMap[this.bridgeID]=this;return this;}
FABridge.TYPE_ASINSTANCE=1;FABridge.TYPE_ASFUNCTION=2;FABridge.TYPE_JSFUNCTION=3;FABridge.TYPE_ANONYMOUS=4;FABridge.initCallbacks={}
FABridge.argsToArray=function(args)
{var result=[];for(var i=0;i<args.length;i++)
{result[i]=args[i];}
return result;}
function instanceFactory(objID)
{this.fb_instance_id=objID;return this;}
function FABridge__invokeJSFunction(args)
{var funcID=args[0];var throughArgs=args.concat();throughArgs.shift();var bridge=FABridge.extractBridgeFromID(funcID);return bridge.invokeLocalFunction(funcID,throughArgs);}
FABridge.addInitializationCallback=function(bridgeName,callback)
{var inst=FABridge.instances[bridgeName];if(inst!=undefined)
{callback.call(inst);return;}
var callbackList=FABridge.initCallbacks[bridgeName];if(callbackList==null)
{FABridge.initCallbacks[bridgeName]=callbackList=[];}
callbackList.push(callback);}
function FABridge__bridgeInitialized(bridgeName){var objects=document.getElementsByTagName("object");var ol=objects.length;var activeObjects=[];if(ol>0){for(var i=0;i<ol;i++){if(typeof objects[i].SetVariable!="undefined"){activeObjects[activeObjects.length]=objects[i];}}}
var embeds=document.getElementsByTagName("embed");var el=embeds.length;var activeEmbeds=[];if(el>0){for(var j=0;j<el;j++){if(typeof embeds[j].SetVariable!="undefined"){activeEmbeds[activeEmbeds.length]=embeds[j];}}}
var aol=activeObjects.length;var ael=activeEmbeds.length;var searchStr="bridgeName="+bridgeName;if((aol==1&&!ael)||(aol==1&&ael==1)){FABridge.attachBridge(activeObjects[0],bridgeName);}
else if(ael==1&&!aol){FABridge.attachBridge(activeEmbeds[0],bridgeName);}
else{var flash_found=false;if(aol>1){for(var k=0;k<aol;k++){var params=activeObjects[k].childNodes;for(var l=0;l<params.length;l++){var param=params[l];if(param.nodeType==1&&param.tagName.toLowerCase()=="param"&&param["name"].toLowerCase()=="flashvars"&&param["value"].indexOf(searchStr)>=0){FABridge.attachBridge(activeObjects[k],bridgeName);flash_found=true;break;}}
if(flash_found){break;}}}
if(!flash_found&&ael>1){for(var m=0;m<ael;m++){if(!activeEmbeds[m].attributes.getNamedItem("flashVars")){continue;}
var flashVars=activeEmbeds[m].attributes.getNamedItem("flashVars").nodeValue;if(flashVars.indexOf(searchStr)>=0){FABridge.attachBridge(activeEmbeds[m],bridgeName);break;}}}}
return true;}
FABridge.nextBridgeID=0;FABridge.instances={};FABridge.idMap={};FABridge.refCount=0;FABridge.extractBridgeFromID=function(id)
{var bridgeID=(id>>16);return FABridge.idMap[bridgeID];}
FABridge.attachBridge=function(instance,bridgeName)
{var newBridgeInstance=new FABridge(instance,bridgeName);FABridge[bridgeName]=newBridgeInstance;var callbacks=FABridge.initCallbacks[bridgeName];if(callbacks==null)
{return;}
for(var i=0;i<callbacks.length;i++)
{callbacks[i].call(newBridgeInstance);}
delete FABridge.initCallbacks[bridgeName]}
FABridge.blockedMethods={toString:true,get:true,set:true,call:true};FABridge.prototype={root:function()
{return this.deserialize(this.target.getRoot());},releaseASObjects:function()
{return this.target.releaseASObjects();},releaseNamedASObject:function(value)
{if(typeof(value)!="object")
{return false;}
else
{var ret=this.target.releaseNamedASObject(value.fb_instance_id);return ret;}},create:function(className)
{return this.deserialize(this.target.create(className));},makeID:function(token)
{return(this.bridgeID<<16)+token;},getPropertyFromAS:function(objRef,propName)
{if(FABridge.refCount>0)
{throw new Error("You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround.");}
else
{FABridge.refCount++;retVal=this.target.getPropFromAS(objRef,propName);retVal=this.handleError(retVal);FABridge.refCount--;return retVal;}},setPropertyInAS:function(objRef,propName,value)
{if(FABridge.refCount>0)
{throw new Error("You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround.");}
else
{FABridge.refCount++;retVal=this.target.setPropInAS(objRef,propName,this.serialize(value));retVal=this.handleError(retVal);FABridge.refCount--;return retVal;}},callASFunction:function(funcID,args)
{if(FABridge.refCount>0)
{throw new Error("You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround.");}
else
{FABridge.refCount++;retVal=this.target.invokeASFunction(funcID,this.serialize(args));retVal=this.handleError(retVal);FABridge.refCount--;return retVal;}},callASMethod:function(objID,funcName,args)
{if(FABridge.refCount>0)
{throw new Error("You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround.");}
else
{FABridge.refCount++;args=this.serialize(args);retVal=this.target.invokeASMethod(objID,funcName,args);retVal=this.handleError(retVal);FABridge.refCount--;return retVal;}},invokeLocalFunction:function(funcID,args)
{var result;var func=this.localFunctionCache[funcID];if(func!=undefined)
{result=this.serialize(func.apply(null,this.deserialize(args)));}
return result;},getTypeFromName:function(objTypeName)
{return this.remoteTypeCache[objTypeName];},createProxy:function(objID,typeName)
{var objType=this.getTypeFromName(typeName);instanceFactory.prototype=objType;var instance=new instanceFactory(objID);this.remoteInstanceCache[objID]=instance;return instance;},getProxy:function(objID)
{return this.remoteInstanceCache[objID];},addTypeDataToCache:function(typeData)
{newType=new ASProxy(this,typeData.name);var accessors=typeData.accessors;for(var i=0;i<accessors.length;i++)
{this.addPropertyToType(newType,accessors[i]);}
var methods=typeData.methods;for(var i=0;i<methods.length;i++)
{if(FABridge.blockedMethods[methods[i]]==undefined)
{this.addMethodToType(newType,methods[i]);}}
this.remoteTypeCache[newType.typeName]=newType;return newType;},addPropertyToType:function(ty,propName)
{var c=propName.charAt(0);var setterName;var getterName;if(c>="a"&&c<="z")
{getterName="get"+c.toUpperCase()+propName.substr(1);setterName="set"+c.toUpperCase()+propName.substr(1);}
else
{getterName="get"+propName;setterName="set"+propName;}
ty[setterName]=function(val)
{this.bridge.setPropertyInAS(this.fb_instance_id,propName,val);}
ty[getterName]=function()
{return this.bridge.deserialize(this.bridge.getPropertyFromAS(this.fb_instance_id,propName));}},addMethodToType:function(ty,methodName)
{ty[methodName]=function()
{return this.bridge.deserialize(this.bridge.callASMethod(this.fb_instance_id,methodName,FABridge.argsToArray(arguments)));}},getFunctionProxy:function(funcID)
{var bridge=this;if(this.remoteFunctionCache[funcID]==null)
{this.remoteFunctionCache[funcID]=function()
{bridge.callASFunction(funcID,FABridge.argsToArray(arguments));}}
return this.remoteFunctionCache[funcID];},getFunctionID:function(func)
{if(func.__bridge_id__==undefined)
{func.__bridge_id__=this.makeID(this.nextLocalFuncID++);this.localFunctionCache[func.__bridge_id__]=func;}
return func.__bridge_id__;},serialize:function(value)
{var result={};var t=typeof(value);if(t=="number"||t=="string"||t=="boolean"||t==null||t==undefined)
{result=value;}
else if(value instanceof Array)
{result=[];for(var i=0;i<value.length;i++)
{result[i]=this.serialize(value[i]);}}
else if(t=="function")
{result.type=FABridge.TYPE_JSFUNCTION;result.value=this.getFunctionID(value);}
else if(value instanceof ASProxy)
{result.type=FABridge.TYPE_ASINSTANCE;result.value=value.fb_instance_id;}
else
{result.type=FABridge.TYPE_ANONYMOUS;result.value=value;}
return result;},deserialize:function(packedValue)
{var result;var t=typeof(packedValue);if(t=="number"||t=="string"||t=="boolean"||packedValue==null||packedValue==undefined)
{result=this.handleError(packedValue);}
else if(packedValue instanceof Array)
{result=[];for(var i=0;i<packedValue.length;i++)
{result[i]=this.deserialize(packedValue[i]);}}
else if(t=="object")
{for(var i=0;i<packedValue.newTypes.length;i++)
{this.addTypeDataToCache(packedValue.newTypes[i]);}
for(var aRefID in packedValue.newRefs)
{this.createProxy(aRefID,packedValue.newRefs[aRefID]);}
if(packedValue.type==FABridge.TYPE_PRIMITIVE)
{result=packedValue.value;}
else if(packedValue.type==FABridge.TYPE_ASFUNCTION)
{result=this.getFunctionProxy(packedValue.value);}
else if(packedValue.type==FABridge.TYPE_ASINSTANCE)
{result=this.getProxy(packedValue.value);}
else if(packedValue.type==FABridge.TYPE_ANONYMOUS)
{result=packedValue.value;}}
return result;},addRef:function(obj)
{this.target.incRef(obj.fb_instance_id);},release:function(obj)
{this.target.releaseRef(obj.fb_instance_id);},handleError:function(value)
{if(typeof(value)=="string"&&value.indexOf("__FLASHERROR")==0)
{var myErrorMessage=value.split("||");if(FABridge.refCount>0)
{FABridge.refCount--;}
throw new Error(myErrorMessage[1]);return value;}
else
{return value;}}};ASProxy=function(bridge,typeName)
{this.bridge=bridge;this.typeName=typeName;return this;};ASProxy.prototype={get:function(propName)
{return this.bridge.deserialize(this.bridge.getPropertyFromAS(this.fb_instance_id,propName));},set:function(propName,value)
{this.bridge.setPropertyInAS(this.fb_instance_id,propName,value);},call:function(funcName,args)
{this.bridge.callASMethod(this.fb_instance_id,funcName,args);},addRef:function(){this.bridge.addRef(this);},release:function(){this.bridge.release(this);}};
SD.UserObject=Class.create(SD.Utils.Class,{initialize:function(uid,username,chat_id){this.uid=uid;this.username=username;this.chat_id=username&&!chat_id?SD.User.composeChatId(uid,username):chat_id;this.fetched=0;this.light_fetched=0;this.online=false;this.im_online=false;this._datingScore=null;this.short_public_url=SD.Config.isProduction?"www.spdt.me/u/"+uid:SD.Config.siteURL+"/p/"+uid;this.extraInfo={};this.pastDates=new SD.Utils.HashArray();this.unwantedDates=new SD.Utils.HashArray();this.wanted_dates=new SD.Utils.HashArray();this.injectedHot=false;this.recommendationFor=null;},mightDate:function(user){if(SD.BuddyList.Controller.isBuddyBlocked(user)){return false;}
var photoCheck=!this.filter_no_photo||user.has_photo;return photoCheck&&this.hasDated(user)&&!this.isUnwantedDate(user)&&!SD.UserInitiatedDate.amIDatingWith(user,false);},getDatingScore:function(){if(!this._datingScore&&this._datingScore!==0){if(this.extraInfo&&this.extraInfo.datingScore){this._datingScore=this.extraInfo.datingScore;}else{if(this.sex=='F'){this._datingScore=1000;}else if(this.sex=='M'){this._datingScore=2000;}else{this._datingScore=1500;}}}
return this._datingScore;},setDatingScore:function(newScore){this._datingScore=newScore>>>0;return this._datingScore;},hasDated:function(user){return!this.pastDates.include(user.uid);},isUnwantedDate:function(user){return this.unwantedDates.include(user.uid);},addUnwantedDate:function(user){this.unwantedDates.push(user.uid);},removeUnwantedDate:function(user){this.unwantedDates=this.unwantedDates.without(user.uid);},wantsToDate:function(user){return this.wanted_dates.include(user.uid);},update:function(u){for(var i in u){this[i]=u[i];}
SD.User._prepareDateParams(this);},rememberDating:function(user){this.pastDates.push(String(user.uid));this.wanted_dates=this.wanted_dates.without(user.uid);},invalidate:function(){this.fetched=0;},toHeShe:function(){switch(this.sex){case'F':return"she";case'M':return"he";}
return this.username;},toHisHer:function(){return this.sex=='F'?'her':'his';},toHimHer:function(){return this.sex=='F'?'her':'him';},toGuyGal:function(){return this.sex=='F'?'gal':'guy';},getDateFeedData:function(){return{uid:this.uid,username:this.username,age:this.age,image_url:this.image_url,city_name:this.city_name,country:this.statecode?this.statecode:this.country,sex:this.sex};},getFullJid:function(){this.xmpp_resource=this.xmpp_resource||SD.XMPP._resourceName;return this.chat_id+"/"+this.xmpp_resource;},isMobile:function(){return this.xmpp_resource=="mobile"||this.isIphone()||this.isAndroid();},isIphone:function(){return this.xmpp_resource=="iphone";},isAndroid:function(){return this.xmpp_resource=="android";},isFacebookUser:function(){return SD.User.isFacebookID(this.uid);},getFacebookUserId:function(){if(this._fbUserId){return this._fbUserId;}
if(this.isFacebookUser()){return this._fbUserId=SD.User.sdUserIdToFbUserId(this.uid);}
return-1;},dprRate:function(){if(!this.dpr){return 0;}
if(this.dpr.start<10||this.minutesAfterSignup()<4320){return 0.147;}
return parseInt(10000*this.dpr.both_participate/this.dpr.start)/10000;},minutesAfterSignup:function(){if(this._minutesAfterSignup){return this._minutesAfterSignup;}
this._minutesAfterSignup=parseInt((Date.now()/1000-this.created)/60);return this._minutesAfterSignup;},getInfosByCat:function(catId){var totalResult=[],result;if(Object.prototype.toString.call(catId)=="[object Array]"){for(var k=0;k<catId.length;k++){result=this.getInfosByCat(catId[k]);result&&result.length>0&&totalResult.push(result);}
return totalResult;}
return this.member_info[catId]&&this.member_info[catId].category_items;},getInfosById:function(infoId){var hash={};if(Object.prototype.toString.call(infoId)=="[object Array]"){for(var k=0;k<infoId.length;k++){hash[infoId[k]]=true;}}else{hash[infoId]=true;}
var catInfos;var infos=[];infos.infosById={};for(var i=0;i<this.member_info.length;i++){catInfos=this.member_info[i].category_items||[];for(var j=0;j<catInfos.length;j++){if(hash[catInfos[j].id]){infos[infos.length]=catInfos[j];infos.infosById[catInfos[j].id]=catInfos[j];}}}
return infos;},set:function(property,value){if(!property)return;var oldValue=this[property];this[property]=value;var memo={property:property,oldValue:oldValue,value:value};this.fire('user_changed:'+property,memo);this.fire('user_changed',memo);},getOnlineStatus:function(){if(this.online)
return 1;if(this.im_online)
return 2;return 0;}});SD.User={_users:{},_users_by_chat_id:{},_iVoted:{},_otherVoted:{},_lastFlirtee:null,_autoAddVeiwed:{},_addViewTimeout:10*60*1000,_viewedUsers:{},trimSpaceRE:/^\s+|\s+$/g,invalidCharRE:/[ ""&''\/:<>@\\]/g,FB_ID_START:1000000000,init:function(){var boundOnUserAvailable=this.onUserAvailable.bind(this);SD.Event.observe(null,SD.UserFilters.UI.Events.FILTER_CHANGED,this.onFilterChange.bind(this));SD.Event.observe(null,SD.Date.Events.RESULT_RECEIVED,this.onDateResult.bind(this));SD.Event.observe(null,SD.Online.Connections.Events.USER_AVAILABLE,this.onUserAvailable.bind(this));SD.Event.observe(null,SD.FBChat.Events.USER_AVAILABLE,this.onUserAvailable.bind(this));SD.Event.observe(null,SD.Online.Connections.Events.USER_UNAVAILABLE,this.onUserUnavailable.bind(this));SD.Event.observe(null,SD.FBChat.Events.USER_UNAVAILABLE,this.onUserUnavailable.bind(this));SD.Event.observe(null,SD.ClientUpdater.Events.WANTED_TO_DATE_ME_IS_ONLINE,boundOnUserAvailable);SD.Event.observe(null,SD.ClientUpdater.Events.I_WANTED_TO_DATE_IS_ONLINE,boundOnUserAvailable);SD.Event.observe(null,SD.ClientUpdater.Events.FLIRTED_ME_IS_ONLINE,boundOnUserAvailable);SD.Event.observe(null,SD.ClientUpdater.Events.I_FLIRTED_IS_ONLINE,boundOnUserAvailable);SD.Event.observe(null,SD.ClientUpdater.Events.WINKED_AT_ME_IS_ONLINE,boundOnUserAvailable);SD.Event.observe(null,SD.ClientUpdater.Events.I_WINKED_AT_IS_ONLINE,boundOnUserAvailable);SD.Event.observe(null,SD.ClientUpdater.Events.FAVORITED_ME_IS_ONLINE,boundOnUserAvailable);SD.Event.observe(null,SD.ClientUpdater.Events.I_FAVORITED_IS_ONLINE,boundOnUserAvailable);SD.Event.observe(null,SD.ClientUpdater.Events.COMPATIBLE_MATCH_IS_ONLINE,boundOnUserAvailable);(new PeriodicalExecuter(this.checkFlirteeInterest.bind(this),1));SD.User.Stats.init();},escapeUsername:function(username){username=username.replace(SD.User.trimSpaceRE,'');return username.replace(SD.User.invalidCharRE,function(a){return'\\'+a.charCodeAt(0).toString(16);});},defaultDomain:function(){return SD.Config.XMPPServer.serverURL;},composeChatId:function(uid,username){username=this.escapeUsername(username);return"sd-"+uid+"-"+username+"@"+SD.User.defaultDomain();},decomposeChatId:function(chat_id){var mat=new RegExp("sd-([^-/@]*)-([^-/@]*)([@/].*)?").exec(chat_id);return mat&&{uid:mat[1],username_id:mat[2]};},getChatUsername:function(chat_id){var decomposed=SD.User.decomposeChatId(chat_id);return"sd-"+decomposed.uid+"-"+decomposed.username_id;},createNewToken:function(oldToken){var rnd;do{rnd=Math.floor(Math.random()*10000);}while(oldToken==rnd);return rnd;},_prepareDateParams:function(user){if(user.wanted_dates instanceof Array){user.wanted_dates=new SD.Utils.HashArray(user.wanted_dates);}
if(user.pastDates instanceof Array){user.pastDates=new SD.Utils.HashArray(user.pastDates);}
if(user.unwantedDates instanceof Array){user.unwantedDates=new SD.Utils.HashArray(user.unwantedDates);}
return user;},get:function(uid,username,chat_id){var user=SD.User._users[uid];if(user){user.username=user.username_id=user.username||username;if(user.username&&!chat_id){chat_id=SD.User.composeChatId(uid,user.username);}
user.chat_id=user.chat_id||chat_id;SD.User._prepareDateParams(user);}else{user=new SD.UserObject(uid,username,chat_id);SD.User._users[uid]=user;}
if(user.chat_id){SD.User._setChatID(user);}
return user;},hasUser:function(uid){if(!SD.User._users[uid]){return false;}
var user=SD.User.get(uid),lastFetch=user.light_fetched||user.fetched,now=(new Date()).getTime();if(now-lastFetch>3000000&&!(user.isFacebookUser()&&lastFetch)){return false;}
return true;},makeParametersFromUser:function(user){return{token:user.token,uid:user.uid,chat_id:user.chat_id,username:user.username,lat:user.lat,lng:user.lng,birthday:user.birthday,country:user.country,country_from_ip:user.country_from_ip,category:user.category,group:SD.Config.mmsGroup,sex:user.sex,sex_pref:user.sex_pref,min_age:user.min_age,max_age:user.max_age,radius:user.radius,has_photo:user.has_photo,filter_country:((user.filter_country=='WW')?'':user.filter_country),filter_no_photo:user.filter_no_photo?user.filter_no_photo:0};},asList:function(list){list=list||[];return list.slice(-100).join(",");},datedWantedDate:function(user){new Ajax.Request(SD.NavUtils.link('ajax','datedwanttodate'),{method:'get',evalJSON:true,parameters:{other_memberid:user.uid},onSuccess:function(result){}});},getPastDates:function(user){return SD.User.asList(user.pastDates);},getWantedDates:function(user){return SD.User.asList(user.wanted_dates);},_setChatID:function(user){if(!user.chat_id){return;}
SD.User._users_by_chat_id[user.chat_id.toLowerCase()]=user;},getByFbUserId:function(fbUserId){return this.get(this.fbUserIdToSdUserId(fbUserId));},getByFBChatID:function(fbChatId){var parse=new RegExp("-([^-/@]*)?").exec(fbChatId);if(!parse||!parse[1]){console.log("could not create fb user from fb chat id");return null;}
var fbUserId=parseInt(parse[1]);if(FB._session&&FB._session['uid']&&(parseInt(FB._session['uid']))==fbUserId){return SD.Model.getMyself();}
var sdUserId=this.fbUserIdToSdUserId(fbUserId);var u=this.get(sdUserId,"Facebook Buddy",fbChatId);u.image_url="http://graph.facebook.com/"+fbUserId+"/picture?type=small";u.square_image_url="http://graph.facebook.com/"+fbUserId+"/picture?type=square";u.relation={};u.images=[];u.images[0]={thumbnail_url:u.image_url};return u;},fbUserIdToSdUserId:function(fbUserId){return this.FB_ID_START+parseInt(fbUserId);},sdUserIdToFbUserId:function(sdUserId){return sdUserId-this.FB_ID_START;},isFacebookID:function(id){return id>=SD.User.FB_ID_START;},getByChatID:function(chid){chid=SD.User.cleanChatID(chid);var ret=chid?SD.User._users_by_chat_id[chid.toLowerCase()]:null;if(!ret){var decomposed=SD.User.decomposeChatId(chid);if(decomposed){ret=SD.User.get(decomposed.uid,decomposed.username_id,chid);}}
return ret;},cleanChatID:function(chid){var ind=chid.indexOf("/");return ind==-1?chid:chid.substring(0,ind);},didVoteForMe:function(otherUser){SD.log("VOTE>checking vote of "+otherUser.username);if(SD.User._otherVoted[otherUser.uid]){SD.log("VOTE>result: true,"+otherUser.username);return true;}
SD.log("VOTE>result: false,"+otherUser.username);return false;},didIVoteFor:function(otherUser){SD.log("VOTE>checking my vote for "+otherUser.username);if(SD.User._iVoted[otherUser.uid]){SD.log("VOTE>result: true,"+otherUser.username);return true;}
SD.log("VOTE>result: false,"+otherUser.username);return false;},iVotedFor:function(otherUser){SD.log("VOTE>adding i voted for:"+otherUser.username);SD.User._iVoted[otherUser.uid]=true;},votedForMe:function(otherUser){SD.log("VOTE>adding other voted for me:"+otherUser.username);SD.User._otherVoted[otherUser.uid]=true;},addview:function(memberid,src){if(!Number(memberid))return;var now=new Date().getTime();if(this._viewedUsers[memberid]&&(this._viewedUsers[memberid]-now)<this._addViewTimeout){return;}
this._viewedUsers[memberid]=now;new Ajax.Request(SD.NavUtils.link('ajax','addview'),{method:'get',parameters:{src:src,viewid:memberid}});},addChatAttempt:function(memberid,callback){new Ajax.Request(SD.NavUtils.link('ajax','add_chat_attempt'),{method:'get',parameters:{other_memberid:memberid},onSuccess:function(result){callback();},onFailure:function(result){callback();}});},addMessageAttempt:function(memberid,callback){new Ajax.Request(SD.NavUtils.link('ajax','add_message_attempt'),{method:'get',parameters:{other_memberid:memberid},onSuccess:function(result){callback();},onFailure:function(result){callback();}});},_pendingFetch:{},_pendingLightFetch:{},_fetch:function(user,options){options=options||{};var now=Date.now();var lastFetched=user.fetched;var fetchEvent=SD.User.Events.USER_FETCHED;var pendingList=SD.User._pendingFetch;var fetchFunction=SD.User.do_fetch;if(options.lightFetch){lastFetched=Math.max(user.light_fetched,user.fetched);fetchEvent=SD.User.Events.USER_LIGHT_FETCHED;pendingList=SD.User._pendingLightFetch;fetchFunction=SD.User.do_light_fetch;}
if((!options.forceNow&&(now-lastFetched)<3000000)){SD.Event.fireDeferred(user,fetchEvent,{user:user});if(options.callback){options.callback(user);}}else{var pending=pendingList[user.uid]||[];if(options.callback){pending.push(options.callback);}
pendingList[user.uid]=pending;if(options.maxDelay){fetchFunction.delay(options.maxDelay);}else{fetchFunction.defer();}}},fetch:function(user,callback,maxDelay,forceNow){if(typeof user=='string'||typeof user=='number'){user=SD.User.get(user);}
SD.User._fetch(user,{callback:callback,maxDelay:maxDelay,forceNow:forceNow});},lightFetch:function(user,callback){SD.User._fetch(user,{callback:callback,lightFetch:true});},do_fetch:function(){var pendingFetch=SD.User._pendingFetch;SD.User._pendingFetch={};SD.User._do_fetch(pendingFetch,SD.User.Events.USER_FETCHED,false);},do_light_fetch:function(){var pendingFetch=SD.User._pendingLightFetch;SD.User._pendingLightFetch={};SD.User._do_fetch(pendingFetch,SD.User.Events.USER_LIGHT_FETCHED,true);},_do_fetch:function(pendingFetch,fetchEvent,lightfetch){var uids=$H(pendingFetch).keys();SD.User.fetchUsers(uids,function(users){var uidToUser={};$A(users).each(function(user){uidToUser[user.uid]=user;});$A(uids).each(function(uid){SD.Event.fireDeferred(null,fetchEvent,{user:uidToUser[uid]});$A(pendingFetch[uid]).each(function(callback){callback(uidToUser[uid]);});});},lightfetch);},fetchUsers:function(uidsArr,callBackFunc,lightfetch){if(uidsArr&&uidsArr.length>0){var now=Date.now();var toFetch=[];var alreadyFetched=[];var toFetchFromFB=[];uidsArr.each(function(uid){var user=SD.User.get(uid);var lastFetch=lightfetch?user.light_fetched:user.fetched;if(now-lastFetch>3000000&&!(user.isFacebookUser()&&lastFetch)){if(user.isFacebookUser()){toFetchFromFB.push(this.sdUserIdToFbUserId(uid));}else{toFetch.push(uid);}}else{alreadyFetched.push(uid);}}.bind(this));var sdFetchCompleted=toFetch.length<1;var fbFetchCompleted=toFetchFromFB.length<1;var returnUsers=[];alreadyFetched.each(function(uid){returnUsers.push(SD.User.get(uid));});var returnIfComplete=function(){if(sdFetchCompleted&&fbFetchCompleted){callBackFunc(returnUsers);}};returnIfComplete();var fetchFromSD=function(){new Ajax.Request(SD.NavUtils.link('ajax','getUsers'),{method:'get',evalJSON:true,parameters:{memberids:toFetch.join(","),lightfetch:lightfetch?1:0},onSuccess:function(result){var users=SD.User.importUsersFromServer(result.responseJSON,lightfetch);users.each(function(user){returnUsers.push(user);});sdFetchCompleted=true;returnIfComplete();}});};var fetchFromFB=function(){var fields="id,name,link,about,gender,picture,birthday,location,hometown,relationship_status";var ids=toFetchFromFB.join(',');FB.api('/?ids='+ids+"&fields="+fields,function(response){var users=SD.User.importUsersFromFacebook(response,lightfetch);users.each(function(user){returnUsers.push(user);});fbFetchCompleted=true;returnIfComplete();});};(toFetch.length>0)&&fetchFromSD();(toFetchFromFB.length>0)&&fetchFromFB();}
else{callBackFunc([]);}},updateUser:function(user){var oUser=SD.User.get(user.uid);$H(user).each(function(pair){oUser[pair.key]=pair.value;});SD.User._setChatID(oUser);return oUser;},importUserFromServer:function(jsonData,lightfetch){var user=SD.User.updateUser(jsonData);var now=Date.now();user.light_fetched=now;if(!lightfetch){user.fetched=now;}
user.uid=parseInt(user.uid);return user;},importUserFromFacebook:function(jsonData,lightfetch){var sdObj=this.internalizeFBUser(jsonData);var user=SD.User.updateUser(sdObj);var now=Date.now();user.light_fetched=now;if(!lightfetch){user.fetched=now;}
user.uid=parseInt(user.uid);return user;},internalizeFBUser:function(fbUser){var ret={};ret.uid=this.fbUserIdToSdUserId(fbUser['id']);ret.public_url=fbUser.link;ret.publicURL=fbUser.link;ret.short_public_url=fbUser.link;ret.username=fbUser.name;ret.name=fbUser.name;ret.sex=fbUser.gender=="male"?'M':'F';ret.chat_id="-"+fbUser.id+"@chat.facebook.com";ret.image_url=fbUser.picture;if(fbUser.birthday&&fbUser.birthday.length==10){ret.birthday=Date.parse(fbUser.birthday);}
if(ret.birthday&&!isNaN(ret.birthday)){ret.age=Math.floor((Date.now()-ret.birthday)/(365.25*24*60*60*1000));}
ret.member_info=[];ret.square_image_url="http://graph.facebook.com/"+fbUser['id']+"/picture?type=square";if(fbUser.location){ret.city_name=fbUser.location.name;}else if(fbUser.hometown){ret.city_name=fbUser.hometown.name;}
return ret;},importUsersFromServer:function(jsonData,lightfetch){var nus=$A(jsonData);var users=[];nus.each(function(u){users.push(SD.User.importUserFromServer(u,lightfetch));});return users;},importUsersFromFacebook:function(jsonData,lightfetch){if(!jsonData){return;}
var users=[];for(var i in jsonData){if(jsonData.hasOwnProperty(i)){users.push(this.importUserFromFacebook(jsonData[i],lightfetch));}}
return users;},insertNewUserToDictionary:function(user){SD.User.updateUser(user);},fetchDateResult:function(user){new Ajax.Request(SD.NavUtils.link('ajax','getdateresult'),{method:'get',evalJSON:true,parameters:{other_memberid:user.uid,control_id:SD.Model.control_id,memberid:SD.Model.getUserId()},onSuccess:function(result){SD.log('date result:{'+user.username+'}:'+result.responseJSON);SD.Event.fire(null,SD.User.Events.DATE_RESULT_FETCHED,{'user':user,'success':result.responseJSON});}});},fetchOldDates:function(user){new Ajax.Request(SD.NavUtils.link('ajax','getdates'),{method:'get',evalJSON:true,parameters:{memberid:user.uid,control_id:SD.Model.control_id},onSuccess:function(result){SD.log("fetchOldDates result:{"+user.username+"}:"+result.responseJSON);$A(result.responseJSON).each(function(uid){user.rememberDating(SD.User.get(uid));});}});},externalize:function(internalUser){var externalUser={};if(internalUser.uid){externalUser.userId=internalUser.uid;}
if(internalUser.username){externalUser.userName=internalUser.username;}
if(internalUser.image_url){externalUser.imageURL1=internalUser.image_url;externalUser.imageURL3=internalUser.image_url;}
if(internalUser.images){externalUser.images=internalUser.images;}
if(internalUser.birthday){externalUser.age=Math.floor((Date.now()-internalUser.birthday)/(365.25*24*60*60*1000));}
externalUser.location="";externalUser.member_info=internalUser.member_info;if(internalUser.city_name){externalUser.location+=internalUser.city_name;}
if(internalUser.country&&internalUser.country_name){if(internalUser.city_name){externalUser.location+=", ";}
externalUser.location+=(internalUser.country=="US"?internalUser.statecode:internalUser.country_name);}
$H(internalUser).each(function(pair){if(typeof(pair.value)=='string'||typeof(pair.value)=='number'||typeof(pair.value)=='boolean'){externalUser[pair.key]=pair.value;}});return externalUser;},internalize:function(externalUser){if(externalUser.userId){externalUser.uid=externalUser.userId;}
return SD.User.get(externalUser.uid);},reportMember:function(user,reason,chatHistory,source){new Ajax.Request(SD.NavUtils.link('ajax','report'),{method:'post',evalJSON:false,parameters:{other_memberid:user.uid,reason:reason,message_content:chatHistory,source:source,control_id:SD.Model.control_id,memberid:SD.Model.getUserId()}});SD.Model.getMyself().addUnwantedDate(user);SD.Event.fire(null,SD.BuddyList.Events.USER_BLOCK_CONFIRMED,{user:user});},saveChatHistory:function(userId,otherUserId,chatHistory,remainingTime){new Ajax.Request(SD.NavUtils.link('ajax','save_chat_history'),{method:'post',evalJSON:false,parameters:{memberid:userId,other_memberid:otherUserId,message_content:chatHistory,remaining_time:remainingTime}});},saveChatAsFlirt:function(sender,text){new Ajax.Request(SD.NavUtils.link('ajax','save_chat_as_flirt'),{method:'post',evalJSON:false,parameters:{other_memberid:sender.uid,text:text},onSuccess:function(result){SD.Event.fire(null,SD.User.Events.SAVED_CHAT_MSG_AS_FLIRT,{sender:sender,text:text});}});},sendFlirt:function(myUser,otherUser,flirt_message,predefined_id,gift_id,platform_id,callback){predefined_id=predefined_id||0;gift_id=gift_id||0;var params={memberid:SD.Model.getUserId(),other_memberid:otherUser.uid,control_id:SD.Model.control_id,text:flirt_message,predefined_id:predefined_id,gift_id:gift_id,platform_id:platform_id};new Ajax.Request(SD.NavUtils.link('ajax','sendflirt'),{method:'post',evalJSON:false,parameters:params,onSuccess:function(response){if(response.responseText==null||response.responseText=='null'){SD.Error.record({error:'Incorrect response from flirt request',url:SD.NavUtils.link('ajax','sendflirt',params),line_number:0,window_url:'',experiments:'',browser:Prototype.Browser.getName(),dumps:'',dump_exceptions:''});SD.UIController.infoMessage('We are sorry for the inconvenience, but we could not send your message at the moment, please try again later.',3);return;}
otherUser.fetched=false;SD.Event.fire(null,SD.User.Events.FLIRT_SENT,{user:myUser,otherUser:otherUser});if(callback){callback();}}});},sendWink:function(myUser,otherUser,callback){SD.log("sending wink");new Ajax.Request(SD.NavUtils.link('ajax','sendwink'),{method:'post',evalJSON:false,parameters:{memberid:SD.Model.getUserId(),other_memberid:otherUser.uid,control_id:SD.Model.control_id},onSuccess:function(result){otherUser.fetched=false;SD.Event.fire(null,SD.User.Events.WINK_SENT,{user:myUser,otherUser:otherUser});callback&&callback();}});},addRating:function(memberid,rating){new Ajax.Request(SD.NavUtils.link('ajax','add_rating'),{method:'get',parameters:{other_memberid:memberid,rating:rating}});},excludeUser:function(otherUserId,username){SD.log("excluding user from search results");var other=SD.User.get(otherUserId);username=username||other.username;new Ajax.Request(SD.NavUtils.link('ajax','excludeUser'),{method:'post',evalJSON:false,parameters:{memberid:SD.Model.getUserId(),otherUserId:otherUserId,otherUserUserName:username,control_id:SD.Model.control_id},onSuccess:function(result){var el=$$('div[memberid='+otherUserId+']').first();el&&el.addClassName('excluded');SD.Event.fire(null,SD.User.Events.USER_EXCLUDED,{uid:otherUserId});}});},undoExclusion:function(otherUserId,username){SD.log("undoing exclusion of user from search results");var other=SD.User.get(otherUserId);username=username||other.username;new Ajax.Request(SD.NavUtils.link('ajax','undoExclusion'),{method:'post',evalJSON:false,parameters:{memberid:SD.Model.getUserId(),otherUserId:otherUserId,otherUserUserName:username,control_id:SD.Model.control_id},onSuccess:function(result){$$('div[memberid='+result.request.parameters.otherUserId+']').first().removeClassName('excluded');}});},undoExclusionFromProfilePage:function(otherUserId,username){SD.log("undoing exclusion of user from search results");var other=SD.User.get(otherUserId);username=username||other.username;new Ajax.Request(SD.NavUtils.link('ajax','undoExclusion'),{method:'post',evalJSON:false,parameters:{memberid:SD.Model.getUserId(),otherUserId:otherUserId,otherUserUserName:username,control_id:SD.Model.control_id}});},sendVote:function(otherUser,vote){SD.log("sending vote");SD.Date.sendVote(otherUser,vote);},initDate:function(otherUser){SD.log("sending init date");SD.Date.initDateInServer(otherUser);},deleteDate:function(otherUser){SD.Date.deleteDateOnServer(otherUser);},endDate:function(otherUser){SD.log("sending end date:"+otherUser.uid);SD.Date.endDateOnServer(otherUser);},otherVoted:function(otherUser){SD.log("other voted!");if(!otherUser||otherUser.chat_id==SD.Model.getMyself().chat_id){SD.log("HOOPS, I did not date this guy");return;}
SD.User.votedForMe(otherUser);if(SD.User.didIVoteFor(otherUser)){SD.User.fetchDateResult(otherUser);}},login:function(){SD.log("logging in to the system");new Ajax.Request(SD.NavUtils.link('ajax','login'),{method:'get',evalJSON:true,parameters:{username:SD.Model.getMyself().username,password:"atester"},onSuccess:function(result){if(result.responseJSON){SD.log("could not log into the system, error code:"+result.responseJSON);}else{SD.log("logged into the system");SD.User.init();}}});},onDateResult:function(event){SD.Event.fire(null,SD.User.Events.DATE_RESULT_FETCHED,{user:event.memo.otherUser,success:(event.memo.result=="MATCH")});},onUserAvailable:function(e){if(SD.Model.getMyself().category=="B"){return;}
if(!e.memo.user){return;}
var user=SD.User.get(e.memo.user.uid);if(user){user.online=true;SD.Event.fire(null,SD.User.Events.USER_ONLINE,{user:user});}},onUserUnavailable:function(e){if(SD.Model.getMyself().category=="B"){return;}
if(!e.memo.user){return;}
var user=SD.User.get(e.memo.user.uid);if(user){user.online=false;SD.Event.fire(null,SD.User.Events.USER_OFFLINE,{user:user});}},checkFlirteeInterest:function(event){if(SD.Nav.activePath.indexOf('speeddate')==-1||SD.Date.isDating){this._lastFlirtee=null;return;}
var flirtee=SD.FlirtWink.Controller.getCurrentFlirtee();if(flirtee){if(this._lastFlirtee){if(flirtee==this._lastFlirtee&&!this._autoAddVeiwed[flirtee.uid]){this._lastFlirtee=null;this._autoAddVeiwed[flirtee.uid]=true;}else{this._lastFlirtee=flirtee;}}else{this._lastFlirtee=flirtee;}}},onFilterChange:function(event){SD.log("sending filter changes to the server as user preference");var me=SD.Model.getMyself();me.min_age=event.memo.min_age;me.max_age=event.memo.max_age;me.radius=event.memo.radius;me.filter_country=event.memo.filter_country;me.filter_no_photo=event.memo.filter_no_photo;me.token=this.createNewToken(me.token);var radiusToSaveInDb=0;if(event.memo.radius==0){radiusToSaveInDb=0;}else{radiusToSaveInDb=$('location').value;}
new Ajax.Request(SD.NavUtils.link('ajax','filterChange'),{method:'get',evalJSON:true,parameters:{min_age:event.memo.min_age,max_age:event.memo.max_age,radius:radiusToSaveInDb,filter_country:event.memo.filter_country,control_id:SD.Model.control_id,memberid:SD.Model.getUserId()},onSuccess:function(result){SD.log("filter change reflected to the server");SD.Event.fire(me,SD.User.Events.USER_CHANGED,{user:me});}});},distanceBetweenUsers:function(userA,userB){var toRad=function(n){return(n*Math.PI)/180;};var calculateDistance=function(lat1,lng1,lat2,lng2){var R=3963;var d=Math.acos(Math.sin(toRad(lat1))*Math.sin(toRad(lat2))+
Math.cos(toRad(lat1))*Math.cos(toRad(lat2))*Math.cos(toRad(lng2-lng1)))*R;return d;};var d=calculateDistance(userA.lat,userA.lng,userB.lat,userB.lng);return Math.floor(d);},renderDistance:function(user){var me=SD.Model.getMyself();var distance=SD.User.distanceBetweenUsers(me,user);return(distance==1)?"1 mile":(distance+" miles");},renderLocation:function(user){var location="";if(user.city_name){location+=user.city_name;}
if(user.country&&user.country_name){if(user.city_name){location+=", ";}
location+=(user.country=="US"&&user.statecode)?user.statecode:user.country_name;}
return location;},sendProfileNotification:function(myUser,otherUser,item,type,callback){var params={memberid:SD.Model.getUserId(),other_memberid:otherUser.uid,control_id:SD.Model.control_id,type:type,item:item};new Ajax.Request(SD.NavUtils.link('ajax','send_profile_notification'),{method:'post',evalJSON:false,parameters:params,onSuccess:function(response){if(response.responseText==null||response.responseText=='null'){SD.Error.record({error:'Incorrect response from notification request',url:SD.NavUtils.link('ajax','send_profile_notification',params),line_number:0,window_url:'',experiments:'',browser:Prototype.Browser.getName(),dumps:'',dump_exceptions:''});SD.UIController.infoMessage('We are sorry for the inconvenience, but we could not send your message at the moment, please try again later.',3);return;}
otherUser.fetched=false;SD.Event.fire(null,SD.User.Events.PROFILE_NOTIFICATION_SENT,{user:myUser,otherUser:otherUser});if(callback){callback();}}});},Events:{USER_FETCHED:'user:fetched',USER_LIGHT_FETCHED:'user:light_fetched',USER_CHANGED:'user:changed',DATE_RESULT_FETCHED:'user:datefetched',FLIRTS_FETCHED:'user:flirtsfetched',DATE_RESULT:'user:dateresult',VOTED:'user:voted',WINK_SENT:'user:wink_sent',FLIRT_SENT:'user:flirt_sent',USER_ONLINE:'user:online',USER_OFFLINE:'user:offline',SAVED_CHAT_MSG_AS_FLIRT:'user:saved_chat_msg_as_flirt',PROFILE_NOTIFICATION_SENT:'user:profile_notifitication_sent',USER_EXCLUDED:'user:excluded'}};SD.User.Stats={init:function(){SD.Event.observe(null,SD.UserFilters.UI.Events.START_SPEEDDATING,this.recordClickStart.bind(this));SD.Event.observe(null,SD.Date.Events.START_DATE,this.recordStartDate.bind(this));SD.Event.observe(null,SD.Date.Events.DATE_OVER,this.record3minDate.bind(this));SD.Event.observe(null,SD.ChatMsgListener.Events.NEW_MESSAGE,this.recordChat.bind(this));SD.Event.observe(null,SD.User.Events.FLIRT_SENT,this.recordFlirt.bind(this));SD.Event.observe(null,SD.User.Events.WINK_SENT,this.recordWink.bind(this));SD.Event.observe(null,SD.User.Events.DATE_RESULT_FETCHED,function(event){if(event.memo.success){this.recordMatch(event.memo.user);}}.bind(this));},recordChat:function(e){var msg=e.memo;if(msg.sender&&msg.sender.uid==SD.Model.getMyself().uid){var newCnt=this._recordAndCountOutputTemplate("usedChat",1);if(newCnt===false){return;}
if(newCnt==1){SD.ExperimentManager.recordOutput('BuddyListChatPlus1Day',1,1);}}},recordClickStart:function(){var newCnt=this._recordAndCountOutputTemplate("clickedStart",3);if(newCnt===false){return;}
if(newCnt==3){SD.ExperimentManager.recordOutput('ClickedStartSpeedDatingPlus3Days',1,1);}},recordFlirt:function(){var newCnt=this._recordAndCountOutputTemplate("flirted",3);if(newCnt===false){return;}
if(newCnt==1){SD.ExperimentManager.recordOutput('FlirtedPlus1Day',1,1);}else if(newCnt==3){SD.ExperimentManager.recordOutput('FlirtedPlus3Days',1,1);}},recordWink:function(){var newCnt=this._recordAndCountOutputTemplate("winked",3);if(newCnt===false){return;}
if(newCnt==1){SD.ExperimentManager.recordOutput('WinkedPlus1Day',1,1);}else if(newCnt==3){SD.ExperimentManager.recordOutput('WinkedPlus3Days',1,1);}},recordStartDate:function(){SD.ExperimentManager.recordOutput('StartDateOutput',1,1);var newCnt=this._recordAndCountOutputTemplate("clickedStart",3);if(newCnt===false){return;}
if(newCnt==3){SD.ExperimentManager.recordOutput('StartedDatePlus3Days',1,1);}},record3minDate:function(event){if(event.memo.otherUser&&event.memo.reasonCode&&event.memo.reasonCode==SD.ReasonCodes.TIME_FINISHED){var newCnt=this._recordAndCountOutputTemplate("3minDate",3);switch(newCnt){case 1:SD.ExperimentManager.recordOutput('Finished3minDatePlus1Day',1,1);break;case 3:SD.ExperimentManager.recordOutput('Finished3minDatePlus3Days',1,1);break;}}},recordMatch:function(otherUser){new Ajax.Request(SD.NavUtils.link('ajax','recordDateMatch'),{method:'post',parameters:{uid:otherUser.uid}});var newCnt=this._recordAndCountOutputTemplate("foundMatch",3);if(newCnt===false){return;}
if(newCnt==3){SD.ExperimentManager.recordOutput('FoundMatchPlus3Days',1,1);}},_recordAndCountOutputTemplate:function(label,countLimit){var count=SD.Cookie.read('o_'+label+'_cnt')||0;if(countLimit&&count>countLimit){return false;}
if(!SD.Cookie.read('o_'+label+'_today')){SD.Cookie.create('o_'+label+'_today',1,1);}else{return false;}
SD.Cookie.create('o_'+label+'_cnt',++count);return count;}};
SD.ProfileViewer={};SD.ProfileViewer.UI={};SD.ProfileViewer.UI.view=function(uid,onShow){SD.Event.fire(null,SD.UIController.Events.CLOSE_WELCOME_POPUP);if(uid==SD.Model.getMyself().uid){SD.NavUtils.goTo('profile','my_profile');}else{SD.FlirtWink.View.requestProfile(uid,'p');}
return false;};
SD.FlirtWink||(SD.FlirtWink={});SD.FlirtWink.Loader={flirteesBufferSize:10,_imgBuffer:[],_flirteesLastPreloadedIndex:0,_nLastFetchingFlirteesTime:0,_count_of_sequential_failed_requests:0,_preloadImageCount:5,MAX_COUNT_OF_SEQUENTIAL_FAILED_REQUESTS:5,init:function(flirteeStore){this.flirteeStore=flirteeStore;SD.Event.observe(null,SD.UIController.Events.DATING_FILTERS_UPDATED,this.onDateFiltersUpdated.bind(this));SD.Event.observe(null,SD.FlirtWink.Controller.Events.FLIRTEE_CHANGE_ATTEMPT,function(e){if(this.needMoreFlirtees()){this.requestMoreFlirtees(true);}
if(this._flirteesLastPreloadedIndex-this.flirteeStore.getCurrentFlirteeIndex()<this._preloadImageCount){this.preloadFlirtees(1);}}.bind(this));this.renewCanMakeRequest();},canMakeRequest:function(){return this._count_of_sequential_failed_requests<=this.MAX_COUNT_OF_SEQUENTIAL_FAILED_REQUESTS&&(!this._nLastFetchingFlirteesTime||(Date.now()-this._nLastFetchingFlirteesTime>5000));},allowNewSuccessiveRequests:function(){this._count_of_sequential_failed_requests=0;},renewCanMakeRequest:function(){this._nLastFetchingFlirteesTime=Date.now();},resetCanMakeRequest:function(){this._nLastFetchingFlirteesTime=0;},needMoreFlirtees:function(){return this.flirteesBufferSize>=this.flirteeStore.getFlirtees().length-this.flirteeStore.getCurrentFlirteeIndex();},preloadFlirtees:function(howMany){howMany=howMany||this._preloadImageCount;for(var i=this._flirteesLastPreloadedIndex;i<this._flirteesLastPreloadedIndex+howMany;i++){if(!this.flirteeStore.getFlirtee(i)){break;}
this._preloadImg(i);}
this._flirteesLastPreloadedIndex=i;},_preloadImg:function(i){var img=new Image;img.onload=img.onerror=function(){img=this._imgBuffer[i]=null;}.bind(this);img.src=this.flirteeStore.getFlirtee(i).image_url_large;this._imgBuffer[i]=img;},onFlirteesRetrieved:function(users){users=users||[];if(users.length==0){this._count_of_sequential_failed_requests++;}},requestMoreFlirtees:function(bQuiet,onSuccess,onError){if(this.canMakeRequest()){this.renewCanMakeRequest();if(!bQuiet){SD.Event.fire(null,SD.FlirtWink.Events.FLIRTEES_FETCH_BEGIN);}
this.loadNextFlirts(SD.Model.getMyself(),function(){this.onFlirteesRetrieved.apply(this,arguments);onSuccess&&onSuccess.apply(null,arguments);}.bind(this),function(){this.onFlirteesRetrieved.apply(this,arguments);onError&&onError.apply(null,arguments);}.bind(this));}},loadNextFlirts:function(user,onSuccess,onError){var me=SD.Model.getMyself();var parameters;if(me.signedin){parameters={control_id:SD.Model.control_id,memberid:user.uid};}else{parameters={control_id:SD.Model.control_id,memberid:SD.Model.getUserId(),min_age:$('min_age').value,max_age:$('max_age').value,country:$('country').value,me_type:$('me_type').value,you_type:$('you_type').value};}
parameters.p=Math.random();new Ajax.Request(SD.NavUtils.link('ajax','getNextFlirts'),{method:'get',evalJSON:true,parameters:parameters,onSuccess:function(result){var users=SD.User.importUsersFromServer($A(result.responseJSON).reject(function(u){return u.category=='B';}));onSuccess&&onSuccess(users);SD.Event.fire(null,SD.FlirtWink.Loader.Events.FLIRTS_FETCHED,{flirts:users});},onFailure:function(result){},onError:onError||Prototype.emptyFunction});},onDateFiltersUpdated:function(e){this.allowNewSuccessiveRequests();},Events:{FLIRTS_FETCHED:'SD.FlirtWink.Loader.Events.FLIRTS_FETCHED'}};SD.FlirtWink.Controller=new function(){var _flirtees=[];var _uidFlirteeHash={};var _flirteesCurrentIndex=0;var _isSendingWink=false;var _isSendingFlirt=false;var _isSendingProfileNotification=false;this.init=function(flirteeData){this.loader=SD.FlirtWink.Loader;this.loader.init(this);this.addFlirtees(flirteeData);this.loader.preloadFlirtees();SD.Event.observe(null,SD.User.Events.USER_EXCLUDED,function(e){this.removeFlirtee(e.memo.uid);}.bind(this));SD.Event.observe(null,SD.FlirtWink.Loader.Events.FLIRTS_FETCHED,this.onFlirtsFetched.bind(this));SD.Event.observe(null,SD.User.Events.WINK_SENT,this.onWinkSent.bind(this));SD.Event.observe(null,SD.User.Events.FLIRT_SENT,this.onFlirtSent.bind(this));SD.Event.observe(null,SD.User.Events.PROFILE_NOTIFICATION_SENT,this.onProfileNotificationSent.bind(this));SD.Event.observe(null,SD.FlirtWink.Events.FAVORITED,function(e){e.memo.user.relation.isFavorite=true;});SD.Event.observe(null,SD.FlirtWink.Events.FAVORITE_REMOVED,function(e){e.memo.user.relation.isFavorite=false;});SD.Event.observe(null,SD.Model.Events.MODEL_CHANGED,function(e){for(var i=0;i<_flirtees.length;i++){_flirtees[i].__match_rate_invalid=true;}});SD.Event.observe(null,SD.BuddyList.Events.USER_BLOCK_CONFIRMED,this.onFlirteeBlocked.bind(this));};this.getFlirtees=function(){return _flirtees;};this.getFlirtee=function(n){return _flirtees[n];};this.setFlirtee=function(index,callback){SD.Event.fire(null,SD.FlirtWink.Controller.Events.FLIRTEE_CHANGE_ATTEMPT);var oFlirtee;if(typeof index=='object'&&index!=null&&this.hasFlirtee(index)){oFlirtee=index;index=_flirtees.indexOf(oFlirtee);if(index==-1)return;}else{if(!_flirtees[index])return;oFlirtee=_flirtees[index];}
if(!oFlirtee){return;}
if(oFlirtee==this.getFlirtee())return;_flirteesCurrentIndex=index;if(SD.XMPP.isConnected()){SD.XMPP.sendDirectPresence(oFlirtee);}
callback&&callback(oFlirtee);SD.Event.fire(null,SD.FlirtWink.Controller.Events.FLIRTEE_CHANGE,{flirtee:oFlirtee,index:_flirteesCurrentIndex});};this.getPreviousFlirtee=function(){return this.getFlirtee(_flirteesCurrentIndex-1);};this.getNextFlirtee=function(){return this.getFlirtee(_flirteesCurrentIndex+1);};this.getCurrentFlirtee=function(){return this.getFlirtee(_flirteesCurrentIndex);};this.getCurrentFlirteeIndex=function(){return _flirteesCurrentIndex;};this.hasFlirtee=function(user){if(!user)return false;var uid=user;if(typeof user=='object'&&user.uid){uid=user.uid;}
return!!_uidFlirteeHash[uid];};this.next=function(callback){this.setFlirtee(_flirteesCurrentIndex+1,callback);};this.previous=function(callback){this.setFlirtee(_flirteesCurrentIndex-1,callback);};this.removeFlirtee=function(user){if(!user)return;var uid=typeof user=='object'?user.uid:user;if(SD.FlirtWink.View.mode=="profile"&&SD.Nav.activePanelId=="speeddate"){if(_uidFlirteeHash[uid]){delete _uidFlirteeHash[uid];}
for(var i=0;i<_flirtees.length;i++){if(_flirtees[i].uid==uid){_flirtees.splice(i,1);}}
var backHash=Object.extend({},SD.Nav.oHashOld);if(backHash.page){var page=backHash.page;var action=backHash.action;delete backHash.page;delete backHash.action;SD.NavUtils.goTo(page,action||'',backHash);}else{window.history.back();}
return;}
if(!_uidFlirteeHash[uid]){return;}
delete _uidFlirteeHash[uid];for(var i=0;i<_flirtees.length;i++){if(_flirtees[i].uid==uid){_flirtees.splice(i,1);if(_flirteesCurrentIndex>=i){if(_flirteesCurrentIndex>=_flirtees.length){this.setFlirtee(_flirtees.length-1);}else{this.setFlirtee(_flirteesCurrentIndex);}}
break;}}};this.addFlirtees=function(newFlirteesData){if(newFlirteesData&&'length'in newFlirteesData&&newFlirteesData.length>0){newFlirteesData.each(this.addFlirtee,this);}};this.addFlirtee=function(flirtee){if(!_uidFlirteeHash[flirtee.uid]){var user=flirtee instanceof SD.UserObject?flirtee:SD.User.importUserFromServer(flirtee);_uidFlirteeHash[flirtee.uid]=user;_flirtees.push(user);}};this.onFlirteeBlocked=function(e){this.removeFlirtee(e.memo.user);};this.onFlirtsFetched=function(e){this.addFlirtees(e.memo.flirts);SD.Event.fire(null,SD.FlirtWink.Events.FLIRTEES_FETCH_END);};this.wink=function(){var flirtee=this.getCurrentFlirtee();if(!_isSendingWink&&flirtee){SD.User.sendWink(SD.Model.getMyself(),flirtee);_isSendingWink=true;SD.Event.fireDeferred(null,SD.FlirtWink.Events.WINK,{uid:flirtee.uid,flirtMessage:'wink'});}};this.flirt=function(otherUser,flirt_message,predefined_id,gift_id,platform_id,onSuccess){if(!_isSendingFlirt){SD.User.sendFlirt(SD.Model.getMyself(),otherUser,flirt_message,predefined_id,gift_id,platform_id,function(){SD.Event.fireDeferred(null,SD.FlirtWink.Events.FLIRT,{uid:otherUser.uid,flirtMessage:flirt_message,giftId:gift_id});onSuccess&&onSuccess();});_isSendingFlirt=true;}};this.date=function(user,params,onSuccess){(new Ajax.Request(SD.NavUtils.link('ajax','wanttodate'),{method:'get',evalJSON:true,parameters:params,onComplete:function(result){if(result.responseJSON){SD.Model.getMyself().wanted_dates.push(user.uid);}
onSuccess&&onSuccess(result);SD.Event.fireDeferred(null,SD.FlirtWink.Events.DATE_WANTED,{user:user});}}));};this.removeDate=function(user,params,onResponse){(new Ajax.Request(SD.NavUtils.link('ajax','removewanttodate'),{method:'get',evalJSON:true,parameters:Object.extend(params||{},{'other_memberid':user.uid}),onComplete:function(result){onResponse&&onResponse(result);SD.Event.fireDeferred(null,SD.FlirtWink.Events.DATE_REQUEST_REMOVED,{user:user});}}));};this.adddate=function(user,params,onResponse){(new Ajax.Request(SD.NavUtils.link('ajax','addwanttodate'),{method:'get',evalJSON:true,parameters:params,onComplete:function(result){onResponse&&onResponse(result);SD.Event.fireDeferred(null,SD.FlirtWink.Events.DATE_WANTED,{user:user});}}));};this.favorite=function(user,onSuccess,onFailure){(new Ajax.Request(SD.NavUtils.link('ajax','addtofavorites'),{method:'get',evalJSON:true,parameters:{you_id:user.uid},onComplete:function(result){if(result.responseJSON){onSuccess&&onSuccess();SD.Event.fireDeferred(null,SD.FlirtWink.Events.FAVORITED,{user:user});}else{onFailure&&onFailure();}}}));};this.removeFavorite=function(user,params,onResponse){(new Ajax.Request(SD.NavUtils.link('ajax','removefavorite'),{method:'get',evalJSON:true,parameters:params,onComplete:function(result){onResponse&&onResponse(result.responseJSON);SD.Event.fireDeferred(null,SD.FlirtWink.Events.FAVORITE_REMOVED,{user:user});}}));};this.requestMorePhotos=function(user,params,onResponse){(new Ajax.Request(SD.NavUtils.link('ajax','askformorephoto'),{method:'get',evalJSON:true,parameters:params,onComplete:function(result){onResponse&&onResponse(result.responseJSON);SD.Event.fireDeferred(null,SD.FlirtWink.Events.MORE_PHOTOS_REQUESTED,{user:user});}}));};this.requestMoreInfo=function(user,params,onResponse){(new Ajax.Request(SD.NavUtils.link('ajax','askformoreprofileinfo'),{method:'get',evalJSON:true,parameters:params,onComplete:function(result){onResponse&&onResponse(result.responseJSON);SD.Event.fireDeferred(null,SD.FlirtWink.Events.MORE_INFO_REQUESTED,{user:user});}}));};this.sendProfileNotification=function(otherUser,item,type){if(!_isSendingProfileNotification){SD.User.sendProfileNotification(SD.Model.getMyself(),otherUser,item,type,function(){SD.Event.fireDeferred(null,SD.FlirtWink.Events.PROFILE_NOTIFICATION,{uid:otherUser.uid,flirtMessage:message});});_isSendingProfileNotification=true;}}
this.onWinkSent=function(e){_isSendingWink=false;var user=e.memo.otherUser;SD.FlirtWink.View.displayWinkSuccess(user);};this.onFlirtSent=function(e){_isSendingFlirt=false;var user=e.memo.otherUser;SD.FlirtWink.View.displayFlirtSuccess(user);};this.onProfileNotificationSent=function(e){_isSendingProfileNotification=false;var user=e.memo.otherUser;SD.FlirtWink.View.onProfileNotificationSent(user);}};SD.FlirtWink.Events={FLIRT:"SD.FlirtWink.Events:FLIRT",WINK:"SD.FlirtWink.Events:WINK",FLIRTEE_CHANGE:'flirtwink:flirteechange',FLIRTEES_FETCH_BEGIN:'flirtwink:flirteesfetchbegin',FLIRTEES_FETCH_END:'flirtwink:flirteesfetchend',DATE_WANTED:'flirtwink:wanttodate',FAVORITED:'flirtwink:favorited',DATE_REQUEST_REMOVED:'flirtwink:dateremoved',FAVORITE_REMOVED:'flirtwink:favoriteremoved',MORE_PHOTOS_REQUESTED:'SD.FlirtWink.Events:MORE_PHOTOS_REQUESTED',MORE_INFO_REQUESTED:'SD.FlirtWink.Events:MORE_INFO_REQUESTED',PROFILE_NOTIFICATION:'SD.FlirtWink.Events:PROFILE_NOTIFICATION'};SD.FlirtWink.Controller.Events={FLIRTEE_CHANGE:'SD.FlirtWink.Controller.Events.FLIRTEE_CHANGE',FLIRTEE_CHANGE_ATTEMPT:'SD.FlirtWink.Controller.Events.FLIRTEE_CHANGE_ATTEMPT'};
SD.FlirtWink||(SD.FlirtWink={});SD.FlirtWink.View=new function(){var _flirtee=null;var _profileTabs={};var _defaultProfileTabElId=null;this.mode='match';this.registrationComplete=false;this.initPhaseForPageMode=true;this.tweetFlirtee=function(){SD.XConnect.tweetProfile(this.getFlirtee().uid,"button.share_profile.browse_page");};this.init=function(){SD.Event.observe(null,SD.FlirtWink.Controller.Events.FLIRTEE_CHANGE,function(e){if(this.mode=='match'){this.requestProfile(e.memo.flirtee.uid);}}.bind(this));SD.Event.observe(null,SD.BuddyList.Events.USER_BLOCK_CONFIRMED,function(e){SD.FlirtWink.View.onUserBlock(e.memo.user&&e.memo.user.uid);});SD.Event.observe(null,SD.User.Events.USER_EXCLUDED,function(e){this.mode=='profile'&&SD.FlirtWink.View.onUserBlock(e.memo.uid);});SD.Event.observe(null,SD.Nav.Events.HASH_CHANGE,this.onHashChange.bind(this));SD.Event.observe(null,SD.FlirtWink.View.Events.MODE_CHANGED,this.onViewModeChange.bind(this));SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){var flirtee=e.memo.flirtee;if(flirtee){SD.User.addview(flirtee.uid,0);}
this.resolveMode();}.bind(this));this.resolveFlirtee();};this.onUserBlock=function(userId){if(_flirtee.uid&&userId==_flirtee.uid){if(this.mode=='match'){this.next();}else if(this.mode=='profile'){history.back();}}};this.onViewModeChange=function(e){if(this.mode=='match'){var controlFlirtee=SD.FlirtWink.Controller.getCurrentFlirtee();var viewFlirtee=SD.FlirtWink.View.getFlirtee();if(controlFlirtee!=viewFlirtee){this.setFlirtee(controlFlirtee);}}};this.onHashChange=function(e){if(SD.Nav.oHash.page=='speeddate'){this.resolveFlirtee();}};this.resolveFlirtee=function(){var hash=SD.NavUtils.getUrlHashParams();var uid=SD.Nav.oHash.uid||hash.uid||SD.FlirtWink.Controller.getCurrentFlirtee();if(uid){SD.User.fetch(uid,function(user){this.setFlirtee(user);}.bind(this));}};this.requestProfile=function(uid,mode){SD.Event.fire(null,SD.FlirtWink.View.Events.PROFILE_VIEW_REQUEST,{uid:uid});SD.NavUtils.goTo('speeddate',null,mode?{uid:uid,mode:mode}:{uid:uid});};this._onSetFlirtee=function(){!this.registrationComplete&&this.registerComponents();};this.resolveMode=function(){var hash=SD.NavUtils.getUrlHashParams();var mode=SD.Nav.oHash.mode||hash.mode;if(mode=='p'){this.turnToProfileMode();}else if(this.initPhaseForPageMode&&!SD.FlirtWink.Controller.hasFlirtee(this.getFlirtee())){this.turnToProfileMode({showBackLink:false});}else{this.turnToMatchMode();}
this.initPhaseForPageMode=false;};this._prepareBackLink=function(){var domBackLink=$("browse-back-link-top");var domBackLinkText=$("browse-back-link-text-top")?$("browse-back-link-text-top"):domBackLink;if(SD.Nav.oHashOld.mode=='p'){domBackLink.hide();this.showFlirtWink();}else{domBackLink.show();domBackLink.stopObserving('click');domBackLink.observe('click',function(e){e.stop();var backHash=Object.extend({},SD.Nav.oHashOld);if(backHash.page){var page=backHash.page;var action=backHash.action;delete backHash.page;delete backHash.action;SD.NavUtils.goTo(page,action||'',backHash);}else{window.history.back();}});var panelTitle=SD.Nav.getPanelTitle(SD.Nav.oHashOld.page);domBackLinkText.update('&laquo; Back'+(panelTitle?' to '+panelTitle:''));domBackLinkText.sdScrollTop=document.documentElement.scrollTop||document.body.scrollTop;}};this.hideFlirtWink=function(){$('flirtee-content').hide();var flirteePhoto=$('flirtwink-flirtee-image');flirteePhoto&&(flirteePhoto.src='about:blank');};this.showFlirtWink=function(){$('flirtee-content').show();};this.turnToMatchMode=function(){if(this.mode=='match'){return;}
this.mode='match';$('submenu-item-my_matches').select('a')[0].href='#index.php?page=speeddate';if(!$('submenu-item-my_matches').hasClassName('current')){$('submenu-item-my_matches').addClassName('current')}
this.flirtwinkSubNav&&this.flirtwinkSubNav.show();$("flirtwink-btn-next-bot").show();$("flirtwink-btn-prev-bot").show();$("flirtwink-btn-next").show();$("flirtwink-btn-prev").show();$('browse-back-link-top')&&$('browse-back-link-top').hide();SD.Event.fire(null,SD.FlirtWink.View.Events.MODE_CHANGED,{mode:this.mode});};this.turnToProfileMode=function(options){if(this.mode=='profile'){return;}
options=Object.extend({showBackLink:true,scrollToTop:true},options||{});this.mode='profile';options.showBackLink&&this._prepareBackLink();if(options.scrollToTop&&document.viewport.getScrollOffsets().top>100){document.scrollToTopAnimated();}
options.showBackLink&&$('browse-back-link-top')&&$('browse-back-link-top').show();$('submenu-item-my_matches').select('a')[0].href='#index.php?page=speeddate';$('submenu-item-my_matches').removeClassName('current');$("flirtwink-btn-next-bot").hide();$("flirtwink-btn-prev-bot").hide();$("flirtwink-btn-next").hide();$("flirtwink-btn-prev").hide();SD.Event.fire(null,SD.FlirtWink.View.Events.MODE_CHANGED,{mode:this.mode});};this.onPhoneVerified=function(){if(SD.Model.getMyself().has_phone){var el=$$('.mod-embed-sms')[0];el&&el.removeClassName('mod-embed-sms');}};this.setFlirtee=function(oUser){if(!oUser){return}
if(oUser==_flirtee){return;}
_flirtee=oUser;this._onSetFlirtee();SD.Event.fire(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,{'flirtee':oUser});};this.getFlirtee=function(){return _flirtee;};this.next=function(){if(this.mode=='match'){SD.FlirtWink.Controller.next();}};this.previous=function(){if(this.mode=='match'){SD.FlirtWink.Controller.previous();}};this.date=function(oUser,onSuccess,e){SD.Dialogs.dialogAddToDates(oUser,onSuccess,e);};this.removeDate=function(oUser,onSuccess){SD.FlirtWink.Controller.removeDate(oUser,{'other_memberid':oUser.uid},onSuccess);};this.chat=function(oUser,onSuccess,tc,e){tc=tc||SD.TrackingCodes.trigger.communication.chat.upgrade_to_chat_button._value;if(SD.Chat.needUpgradeForChat(oUser)){if(oUser.online||oUser.im_online){var context=SD.Utils.buildContext({sourceMember:oUser,sourceMemberId:oUser.uid},e);if(SD.UserInitiatedDate.shallTry(oUser)){context.sourceType=SD.UIController.PopupSourceTypes.DATE;SD.FlowManager.run(SD.Flows.date.clone(),context);}else{SD.User.addChatAttempt(oUser.uid,Prototype.emptyFunction);context.sourceType=SD.UIController.PopupSourceTypes.CHAT;SD.FlowManager.run(SD.Flows.preActionFlowOnly.clone(),context);}}else{inviteToDate();}}else{if(oUser.online){SD.Chat.chatWithUser(oUser);}else if(oUser.im_online){SD.Notification.IM.sendChatRequest(oUser);}else{inviteToDate();}}
function inviteToDate(){if(SD.Model.getMyself().wantsToDate(oUser)){SD.UIController.infoMessage(oUser.username+" is already invited to SpeedDate. We will notify you when "+oUser.username+" comes online.");}else{SD.FlowManager.run(SD.Flows.inviteToDate.clone(),SD.Utils.buildContext({sourceMember:oUser,onActionEnd:onSuccess},e));}}};this.requestMorePhotos=function(oUser){SD.FlirtWink.Controller.requestMorePhotos(oUser,{to_memberid:oUser.uid},this.moreInfoRequestResponse.bind(this));};this.requestMoreInfo=function(oUser){SD.FlirtWink.Controller.requestMoreInfo(oUser,{to_memberid:oUser.uid},this.moreInfoRequestResponse.bind(this));};this.registerComponents=function(){this.registerInputWink('flirtwink-btn-wink');this.registerInputShare('flirtwink-btn-share');this.registerInputViewConversation('flirtwink-btn-view-conversation');this.registerInputChat('flirtwink-btn-chat');this.registerInputFavorite('flirtwink-btn-favorite');this.registerInputNext('flirtwink-btn-next');this.registerInputNext('flirtwink-btn-next-bot');this.registerInputPrevious('flirtwink-btn-prev');this.registerInputPrevious('flirtwink-btn-prev-bot');this.registerProfileTabItems([{tabEl:'profile-aboutme-tab',contentEl:'profile-aboutme-tab-contents',defaultTab:true},{tabEl:'profile-photos-tab',contentEl:'profile-photos-tab-contents'},{tabEl:'profile-aboutmydate-tab',contentEl:'profile-aboutmydate-tab-contents'},{tabEl:'profile-datingquiz-tab',contentEl:'profile-datingquiz-tab-contents'},{tabEl:'profile-conversation-tab',contentEl:'profile-conversation-tab-contents'}]);if(SD.Config.isSite){this.registerProfileOutputs({basicInfoSection:'basic-info-section',moreAboutMeSection:'flirtwink-aboutme-info',fridayStaurdaySection:'flirtwink-friday-saturday-night-info',whoIwouldLikeToMeetSection:'flirtwink-who-idlike-to-meet-info',interestsSection:'flirtwink-interests-info'});this.registerDatingStatusOutput('profile-status-container','profile-status-text');}else{this.registerOutputAboutmeTabContents('flirtwink-aboutme-info','flirtwink-aboutme-content');}
this.registerOutputPhotosTabContents('profile-photos-tab-contents');this.registerOutputAboutmydateTabContents('profile-aboutmydate-tab-contents','profile-aboutmydate-tab');this.registerOutputDatingquizTabContents('profile-datingquiz-tab-contents','profile-datingquiz-tab');this.registerOutputConversationTabContents('profile-conversation-tab-contents');this.registerProfilePhotosNum('profile-photos-num');this.registerOutputReportPhoto('flirtwink-flirtee-report');this.registerOutputExcludeUserFromProfilePage('exclude-user-from-profile-page');this.registerOutputConversation('flirtwink-btn-view-conversation');this.registerOutputWink('flirtwink-btn-wink');this.registerOutputChat('flirtwink-btn-chat');this.registerOutputFlirteeUsername('flirtwink-flirtee-username');this.registerOutputFlirteeUsername('flirtwink-flirtee-username-local-event');this.registerOutputFlirteeAge('flirtwink-flirtee-age');this.registerOutputFlirteeCity('flirtwink-flirtee-city');this.registerOutputFlirteeCountry('flirtwink-flirtee-country');this.registerOutputFlirteeState('flirtwink-flirtee-state');this.registerOutputFlirteeDistance('flirtwink-flirtee-distance');this.registerOutputTaggingCloud('cloud_flirtwink');this.registerOutputFlirteeMatchedProfileInfos('flirtwink-flirtee-matched-profile-infos');if(!SD.Config.isSite){this.registerOutputFlirteeDetails2703(null,null,'flirtwink-flirtee-headline','flirtwink-flirtee-dealbreakers');}
this.registerOutputFlirteeImage('flirtwink-flirtee-image');this.registerOutputFlirteeMessage('flirtwink-flirtee-message');this.registerOutputFlirteeFeatured('flirtwink-flirtee-featured');this.registerOutputFlirteeNewMember('flirtwink-flirtee-new-member');this.registerOutputFlirteeRating('flirtwink-flirtee-rating');var cannedCtrl=this.setupCannedCtrl({domHandle:'flirtwink-canned-flirt-new',domSource:'icebreakers-data',domForm:'flirt-form',alignment:'left'});this.registerInputCannedFlirt(cannedCtrl,'flirt-message-top','counter-indicator-top','flirtwink-messaging-btn-top');this.registerOutputCannedFlirt(cannedCtrl);this.registerInputFlirtField('flirt-message-top',cannedCtrl,'flirtwink-messaging-btn-top');this.registerOutputFlirtField('flirt-message-top');this.registerInputFlirtSendButton('flirt-message-top',cannedCtrl,'flirtwink-messaging-btn-top','error-notify','virtual-gift');this.registerOutputLoading('flirtwink-loading');this.registerOutputSubnav('flirtwink-subnav-holder');this.registerOutputSMSOption('fw-sms-promo-username');this.registerOutputSendGift_3641('flirtwink-giftsend-btn-top');this.registerOutputFacebookLikeButton('facebook-like-button-frame');this.registerOutputTwitterTweetButton('twitter-tweet-button-frame');this.registerRequestProfileInfoSection('flirtwink-request-profile-info-section','flirtwink-request-profile-info-btn');this.registerZeroState('flirtee-zero-state');this.registerAdSection({domHolder:"profile-aboutme-tab-contents",domClose:"flirtwink-right-ad-section-close-handle"});this.registrationComplete=true;};this.registerZeroState=function(el){el=$(el);if(!el)return;this.domZero=el;};this.registerAdSection=function(options){if(!$(options.domClose)){return;}
$(options.domClose).onclick=function(){$(options.domHolder)&&$(options.domHolder).removeClassName('mod-ad');SD.Event.fire(null,SD.FlirtWink.View.Events.FLIRTWINK_LAYOUT_CHANGED);};};this.registerRequestProfileInfoSection=function(domSection,domButton){if(!$(domSection)||!$(domButton))return;$(domButton).onclick=function(){if(!_flirtee)return;if(SD.ExperimentManager.RequestMoreProfileInfoEmail_SDWEB116.value){new Ajax.Request(SD.NavUtils.link('ajax','ask_for_more_profile_info'),{method:'get',evalJSON:true,parameters:{to_memberid:_flirtee.uid},onComplete:function(result){if(result.responseJSON){SD.UIController.infoMessage(result.responseJSON.message);}}});}else{SD.ExperimentManager.recordOutput('RequestedProfileInfoOutput',1,1);SD.UIController.infoMessage("You have successfully asked "+_flirtee.username+" for more profile info.");}}
SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){var user=e.memo.flirtee;if(hasLessThan5Infos(user)){setMessages(user);$(domSection).show();}else{$(domSection).hide();}});function setMessages(user){$(domSection).select('.flirtwink-request-profile-info-subsection1')[0].update('Want to know more about '+user.username+'?');$(domSection).select('.flirtwink-request-profile-info-subsection2')[0].update('Ask '+user.toHimHer()+' to fill out more profile info.');$(domSection).select('u')[0].update('Ask '+user.toHimHer()+' &raquo;');}
function hasLessThan5Infos(user){var infosCount=user.getInfosByCat(3).length;infosCount+=user.getInfosById([17,71,1]).length;return infosCount<5;}};this.onProfileNotificationSent=function(user){this.displayProfileNotificationSuccess(user);};this.registerOutputAboutmeTabContents=function(oAboutMeInfoElement,oAboutMeContentElement){oAboutMeInfoElement=$(oAboutMeInfoElement)||null;oAboutMeContentElement=$(oAboutMeContentElement)||null;if(!oAboutMeInfoElement||!oAboutMeContentElement)return;SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){var oFlirtee=e.memo.flirtee;oAboutMeContentElement&&oAboutMeContentElement.update();var aboutMeCategories=['Basic Info','Appearance','Background','Interests','Lifestyle'];for(var i=0;i<oFlirtee.member_info.length;i++){if(aboutMeCategories.any(function(n){return n==oFlirtee.member_info[i].category_title;})){if(oFlirtee.member_info[i].category_items.length){oAboutMeContentElement&&oAboutMeContentElement.appendChild(DIV({'class':'category-title'},oFlirtee.member_info[i].category_title));var oCategoryItems=DIV({'class':'category-items'},'');var html='';for(var j=0;j<oFlirtee.member_info[i].category_items.length;j++){html+="<table width='100%'>"+"<tr>"+"<td class='category-item-title'>"+oFlirtee.member_info[i].category_items[j].title+': '+"</td>";html+="<td class='category-item-value'>"+oFlirtee.member_info[i].category_items[j].text_value+"</td>";html+="</tr>"+"</table>";}
oCategoryItems.innerHTML=html;oAboutMeContentElement&&oAboutMeContentElement.appendChild(oCategoryItems);}}}
oAboutMeInfoElement&&oAboutMeInfoElement.update();for(var k=0;k<oFlirtee.member_info[6].category_items.length;k++){if(oFlirtee.member_info[6].category_items[k].title=='More About Me'){oAboutMeInfoElement&&oAboutMeInfoElement.update('<div class="about-me-text">"'+oFlirtee.member_info[6].category_items[k].text_value+'"</div>');}}});};this.registerDatingStatusOutput=function(domContainer,domText){if(!$(domContainer)||!$(domText))return;SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){var oFlirtee=e.memo.flirtee;var catItems=oFlirtee.member_info[6].category_items||[];var item;for(var i=0;i<catItems.length;i++){if(catItems[i]['id']==77){item=catItems[i];}}
if(item){$(domText).update(item.text_value);$(domContainer).show();}else{$(domText).update();$(domContainer).hide();}});};this.registerProfileOutputs=function(domTargets){SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){e.memo.flirtee&&this.populateProfileOutputs(e.memo.flirtee,domTargets);}.bind(this));};this.populateProfileOutputs=function(user,domTargets){if(!user||!domTargets)return;var dom;if((dom=$(domTargets.basicInfoSection))){dom.update(this.basicInfoRenderer(user));}
if((dom=$(domTargets.moreAboutMeSection))){dom.update(this.moreAboutMeRenderer(user));}
if((dom=$(domTargets.fridayStaurdaySection))){dom.update(this.fridayStaurdayRenderer(user));}
if((dom=$(domTargets.whoIwouldLikeToMeetSection))){dom.update(this.whoIwouldLikeToMeetRenderer(user));}
if((dom=$(domTargets.interestsSection))){dom.update(this.interestsRenderer(user));if(user.profile_page_v5){dom.select('.suggest-item img, .suggest-item span').each(function(el){el.observe('click',SD.ProfileInfoOptionTooltip.onclick);el.observe('mouseover',SD.ProfileInfoOptionTooltip.setTimer);el.observe('mouseout',SD.ProfileInfoOptionTooltip.clearTimer);});}}};this.basicInfoRenderer=function(user){return[this.catTableRenderer(user,1),this.catTableRenderer(user,2),this.catTableRenderer(user,4)].join('');};this.interestsRenderer=function(user){return this.catRenderer(user,3);};this.moreAboutMeRenderer=function(user){return this.infoItemRenderer(user,6,1,{noTitle:true});};this.whoIwouldLikeToMeetRenderer=function(user){return this.infoItemRenderer(user,5,17,{titleClassName:"category-title"});};this.fridayStaurdayRenderer=function(user){return this.infoItemRenderer(user,4,71,{titleClassName:"category-title"});};this.infoItemRenderer=function(user,catId,subCatId,options){if(!user||catId==null||subCatId==null||!user.member_info[catId])return'';options=options||{};var titleClassName=options.titleClassName||"category-item-title";var textClassName=options.textClassName||"category-item-value";var html='';var catItems=user.member_info[catId].category_items||[];var item;for(var i=0;i<catItems.length;i++){if(catItems[i]['id']==subCatId){item=catItems[i];}}
if(item){html+=(options.noTitle?'':('<div class="'+titleClassName+'">'+item.title+'</div>'))+'<div class="'+textClassName+'">'+item.text_value+'</div>';}
return html;};this.catRenderer=function(user,catId,options){if(!user||catId==null||!user.member_info[catId]||user.member_info[catId].category_items.length==0)return'';options=options||{};var memberInfo=user.member_info[catId];var memberInfoItems=memberInfo.category_items;var html=[];html.push(options.noTitle?'':('<div class="category-title">'+memberInfo.category_title+'</div>'),'<div class="category-items">');for(var i=0;i<memberInfoItems.length;i++){if(user.profile_page_v5&&memberInfoItems[i].category_items_full){if(i==0){html.push('<div class="category-item-title">'+memberInfoItems[i].title+'</div>');}else{html.push('<div class="category-item-title has-up-border">'+memberInfoItems[i].title+'</div>');}
for(var j=0;j<memberInfoItems[i].category_items_full.length;j++){var img_style="";var div_style="";if(SD.AutoCompleteV2.default_images.any(function(el){return memberInfoItems[i].category_items_full[j].photo.indexOf(el)!=-1?true:false;})){div_style=' style="margin-top:58px"';img_style=' style="height:50px;"';}
var division='<div class="suggest-item"'+div_style+'>'
+'<span class="suggest-item-id" style="display: none;">'+memberInfoItems[i].category_items_full[j]._id.value+'</span>'
+'<img class="suggest-item-image" src="'+memberInfoItems[i].category_items_full[j].photo+'"'+img_style+'>'
+'<br/>'
+'<span class="suggest-item-name">'+SD.AutoCompleteV2.sanitize(memberInfoItems[i].category_items_full[j]._name.value)+'</span>'
+'<a name="'+memberInfoItems[i].id+'" class="fake-link no-hover no-remove"></a>'
+'</div>';html.push(division);}
html.push('<div class="spacer-20px"></div>');}else{html.push('<div class="category-item-title">'+memberInfoItems[i].title+'</div>','<div class="category-item-value">'+memberInfoItems[i].text_value+'</div>');}}
html.push('</div>');return html.join('');};this.catTableRenderer=function(user,catId,options){if(!user||catId==null||!user.member_info[catId]||(user.member_info[catId].category_items.length==0&&catId!=2)){return'';}
options=options||{};var memberInfo=user.member_info[catId];var memberInfoItems=memberInfo.category_items;var html=[];html.push(options.noTitle?'':('<div class="category-title">'+memberInfo.category_title+'</div>'),'<div class="category-items">','<table width="100%">');for(var i=0;i<memberInfoItems.length;i++){html.push('<tr>','<td class="category-item-title">'+memberInfoItems[i].title+'</td>','<td class="category-item-value">'+memberInfoItems[i].text_value+'</td>','</tr>');}
if(catId==2){html.push('<tr>','<td class="category-item-title">'+user.member_info[0].category_items[2].title+'</td>','<td class="category-item-value">'+user.member_info[0].category_items[2].text_value+'</td>','</tr>');html.push('<tr>','<td class="category-item-title">'+user.member_info[0].category_items[3].title+'</td>','<td class="category-item-value">'+user.member_info[0].category_items[3].text_value+'</td>','</tr>');}
html.push('</table></div>');return html.join('');};this.registerOutputInCommonTabContents=function(oElement,tabElement){oElement=$(oElement)||null;tabElement=$(tabElement)||null;if(!oElement||!tabElement)return;SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){oElement&&oElement.update();var matchedInfoHolder=this.matchedInfoRenderer(e.memo.flirtee);if(matchedInfoHolder){oElement&&oElement.update(matchedInfoHolder);tabElement&&tabElement.show();}else{tabElement&&tabElement.hide();var oCategoryItems=DIV({'class':'profile-tab-zero-state'},'');var html=e.memo.flirtee.username+" and you have not enough information to show the common interests!";oCategoryItems.innerHTML=html;oElement&&oElement.appendChild(oCategoryItems);}}.bind(this));};this.registerOutputPhotosTabContents=function(oElement){oElement=$(oElement)||null;if(!oElement)return;SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){oElement&&oElement.update('<div style="color:#999; font-size:18px; font-weight:bold; margin:48px auto; width:100px;">loading...</div>');});};this.registerOutputAboutmydateTabContents=function(oElement,tabElement){oElement=$(oElement)||null;tabElement=$(tabElement)||null;if(!oElement||!tabElement)return;SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){var oFlirtee=e.memo.flirtee;oElement&&oElement.update('<div style="color:#999; font-size:18px; font-weight:bold; margin:48px auto; width:100px;">loading...</div>');if(oFlirtee.__match_rate_invalid){if($('matching-score')){$('matching-score').innerHTML="";}}else{if($('matching-score')){if(oFlirtee['matching_score']>0){$('matching-score').innerHTML=oFlirtee['matching_score']+"%";}else{$('matching-score').innerHTML="0%";}}}});};this.registerOutputDatingquizTabContents=function(oElement,tabElement){oElement=$(oElement)||null;if(!oElement)return;SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){oElement&&oElement.update('<div style="color:#999; font-size:18px; font-weight:bold; margin:48px auto; width:100px;">loading...</div>');});};this.registerOutputConversationTabContents=function(oElement){oElement=$(oElement)||null;if(!oElement)return;SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){oElement&&oElement.update('<div style="color:#999; font-size:18px; font-weight:bold; margin:48px auto; width:100px;">loading...</div>');});};this.registerProfilePhotosNum=function(oElement){oElement=$(oElement)||null;if(!oElement)return;SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){var oFlirtee=e.memo.flirtee;if(oFlirtee.image_count>0){if(SD.Config.isSite){oElement&&oElement.update(oFlirtee.image_count);}else{oElement&&oElement.update('&nbsp;('+oFlirtee.image_count+')');}}else{oElement&&oElement.update();}});};this.registerProfileTabItems=function(tabItems){tabItems=tabItems||[];tabItems.each(function(tabItem,index){var oElId=tabItem.tabEl;_profileTabs[oElId]=tabItem.contentEl;if(tabItem.defaultTab){_defaultProfileTabElId=oElId;}
var oElement=$(oElId);oElement.observe('click',function(e){SD.FlirtWink.View.activateTabMenu(oElement.id);});});SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){SD.FlirtWink.View.activateTabMenu(_defaultProfileTabElId);for(var el in _profileTabs){var oEl=$(el)||null;oEl&&oEl.setAttribute('sdIsLoaded','false');}});};this.activateTabMenu=function(elId){for(var el in _profileTabs){var oEl=$(el)||null;var cEl=$(_profileTabs[el])||null;if(oEl&&cEl){if(el==elId){oEl.addClassName("selected-tab-item");cEl.show();var isLoaderTab=oEl.getAttribute('sdType')||null;var otherUser=_flirtee;if(isLoaderTab){if(oEl.getAttribute('sdTabType')=='photo'){if(oEl.getAttribute('sdIsLoaded')=='false'){cEl.update();this.largePhotoRenderer(cEl,otherUser);oEl.setAttribute('sdIsLoaded','true');}}else if(oEl.getAttribute('sdTabType')=='conversation'){if(oEl.getAttribute('sdIsLoaded')=='false'){var url=SD.NavUtils.link('messages','inline_thread',{id:otherUser.uid});new SD.Utils.Loader({domContent:cEl}).load(url);oEl.setAttribute('sdIsLoaded','true');}}else if(oEl.getAttribute('sdTabType')=='quiz'){if(oEl.getAttribute('sdIsLoaded')=='false'){var url=SD.NavUtils.link('profile','viral_quiz_view',{otherMemberId:otherUser.uid,fromFlirtWink:true});new SD.Utils.Loader({domContent:cEl}).load(url);oEl.setAttribute('sdIsLoaded','true');}}else if(oEl.getAttribute('sdTabType')=='match'){SD.ExperimentManager.recordOutput('UserViewedMatchViewOutput',1,1);if(oEl.getAttribute('sdIsLoaded')=='false'){var url=SD.NavUtils.link('profile','we_match_view',{otherMemberId:otherUser.uid,fromFlirtWink:true});var hideItem=function(el){el.style.display='none';}
var showItem=function(el){el.style.display='block';}
new SD.Utils.Loader({domContent:cEl,onContentRendered:function(){$$('.matching-table .ask-button').each(function(el){el.observe('click',SD.WeMatch.ask);});$$('.matching-table .property.answer .action.answer').each(function(el){el.observe('click',SD.WeMatch.answer);});$$('.matching-table .speed-verify-button').each(function(el){el.observe('click',SD.WeMatch.speedVerify);});}}).load(url);oEl.setAttribute('sdIsLoaded','true');}}}}else{oEl.removeClassName("selected-tab-item");cEl.hide();}}}}
this.registerInputShare=function(elId){$(elId).setAttribute('sdType','share');var setShareAttributes=function(user){if(user&&user.uid){var el=$(elId);el.setAttribute('sdUid',user.uid);el.setAttribute('sdUserName',user.username);}};var initFlirtee=SD.FlirtWink.Controller.getCurrentFlirtee();initFlirtee&&setShareAttributes(initFlirtee);SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){setShareAttributes(e.memo.flirtee)});};this.registerInputWink=function(elId){$(elId).setAttribute('sdType','wink');var setWinkAttributes=function(user){if(user&&user.uid){var el=$(elId);el.setAttribute('sdUid',user.uid);el.setAttribute('sdUserName',user.username);}};var initFlirtee=SD.FlirtWink.Controller.getCurrentFlirtee();initFlirtee&&setWinkAttributes(initFlirtee);SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){setWinkAttributes(e.memo.flirtee)});};this.registerInputFlirt=function(elId){$(elId).setAttribute('sdType','flirt');var setWinkAttributes=function(user){if(user&&user.uid){var el=$(elId);el.setAttribute('sdUid',user.uid);el.setAttribute('sdUserName',user.username);}};var initFlirtee=SD.FlirtWink.Controller.getCurrentFlirtee();initFlirtee&&setWinkAttributes(initFlirtee);SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){setWinkAttributes(e.memo.flirtee)});};this.registerInputDate=function(elId){$(elId).setAttribute('sdType','date');var setDateAttributes=function(user){if(user&&user.uid){var el=$(elId);el.setAttribute('sdUid',user.uid);el.setAttribute('sdUserName',user.username);}};var initFlirtee=SD.FlirtWink.Controller.getCurrentFlirtee();initFlirtee&&setDateAttributes(initFlirtee);SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){setDateAttributes(e.memo.flirtee)});};this.registerInputRemoveDate=function(oElement,getOtherUser,onSuccess,o){oElement=$(oElement);getOtherUser=getOtherUser||function(){return _flirtee;};o=o||{};oElement.observe('click',function(e){if(oElement.isBlocked)return;oElement.isBlocked=true;SD.Tooltip.hide();var oUser=getOtherUser();if(oElement.hasClassName("remove-date")){this.removeDate(oUser,function(){oElement.removeClassName("remove-date");oElement.addClassName("date");SD.UIController.infoMessage(oUser.username+" has been removed from the list of people you want to SpeedDate.");oElement.isBlocked=false;});}else{oElement.isBlocked=false;this.date(oUser,function(){oElement.removeClassName("date");oElement.addClassName("remove-date");!SD.Recommendation.isActive()&&SD.UIController.infoMessage("SpeedDating Request for User "+oUser.username+" Successful!");});}}.bind(this));oElement.observe('mouseover',function(e){SD.Tooltip.hide();if(o&&o.classMouseOver){e.target.addClassName(o.classMouseOver);}
var oUser=getOtherUser();if(oElement.hasClassName("remove-date")){SD.Tooltip.show('Remove <b>'+oUser.username+'</b> from members you want to SpeedDate.');}else{SD.Tooltip.show('Add <b>'+oUser.username+'</b> '+'to the list of members you want to SpeedDate. When both of you are online, we\'ll connect you!');}});oElement.observe("mouseout",function(e){if(o&&o.classMouseOver){e.target.removeClassName(o.classMouseOver);}
SD.Tooltip.hide();});};this.registerInputChat=function(oElement,getOtherUser,onSuccess,trackingCode,enableFunction,disableFunction){oElement=$(oElement);getOtherUser=getOtherUser||function(){return _flirtee;};var otherUser=getOtherUser();onSuccess=onSuccess||function(){};var tc=trackingCode?trackingCode:null;oElement.observe('click',function(e){SD.User.fetch(getOtherUser(),function(oUser){SD.FlirtWink.View.chat(oUser,onSuccess,tc,e);});});oElement.observe('mouseover',function(){SD.Tooltip.hide();var oUser=getOtherUser();if(!oUser.online&&!oUser.im_online){if(SD.Model.getMyself().wantsToDate(oUser)){SD.Tooltip.show('You already sent a SpeedDate&trade; invitation to <b>'+oUser.username+'</be>. We will notify you when '+oUser.username+' comes online.');}else if(SD.Model.getMyself().mightDate(oUser)){SD.Tooltip.show('<b>'+oUser.username+'</b> is not online right now. Invite '+oUser.username+' to SpeedDate and we\'ll let you know when '+oUser.toHeShe()+' comes online.');}else{SD.Tooltip.show('<b>'+oUser.username+'</b> is not online right now. Your message will be delivered when '+oUser.username+' comes online.');}
return;}
if(SD.Chat.needUpgradeForChat(oUser)){SD.UIController.userInfoMouseOverOutTrigger(function(){if(!oUser.online&&oUser.im_online){SD.Tooltip.show('<b>'+oUser.username+'</b> is online on SpeedDate IM.<br/>Click'+' to send a chat request to <b>'+oUser.username+'</b>.');}else{if(SD.UserInitiatedDate.shallTry(oUser)){SD.Tooltip.show('Click to start a SpeedDate&trade; with <b>'+oUser.username+'</b>.');}else{SD.Tooltip.show(SD.UIController.getInlineSubBadge()+'to chat with <b>'+oUser.username+'</b>.');}}});}else{if(oUser.online){SD.Tooltip.show('Chat with <b>'+oUser.username+'</b>');}else{SD.Tooltip.show('<b>'+oUser.username+'</b> is online on SpeedDate IM.<br/>Click to send a chat request');}}});oElement.observe('mouseout',SD.Tooltip.hide);var online=getOtherUser().online;if(online&&enableFunction){enableFunction();}else if(disableFunction){disableFunction();}
if(enableFunction){SD.Event.observe(null,SD.User.Events.USER_ONLINE,function(e){if(e.memo&&e.memo.user&&e.memo.user.uid==otherUser.uid){enableFunction();}});}
if(disableFunction){SD.Event.observe(null,SD.User.Events.USER_OFFLINE,function(e){if(e.memo&&e.memo.user&&e.memo.user.uid==otherUser.uid&&!otherUser.im_online){disableFunction();}});}};this.registerInputFavorite=function(oElement){oElement=$(oElement);var inactiveClassName="small-gray-no-click";oElement.setAttribute("sdType","favorite");oElement.setAttribute("sdClassOnFavorite",inactiveClassName);oElement.setAttribute("sdUid",_flirtee.uid);oElement.setAttribute("sdUserName",_flirtee.username);oElement.setAttribute("sdFavorite",_flirtee.relation.isFavorite);var setupButton=function(user){if(!user)return;oElement.setAttribute("sdUserName",user.username);oElement.setAttribute("sdUid",user.uid);oElement.setAttribute("sdFavorite",user.relation.isFavorite);if(user&&user.relation.isFavorite){oElement&&oElement.addClassName(inactiveClassName);}else{oElement&&oElement.removeClassName(inactiveClassName);}};setupButton(_flirtee);SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){setupButton(e.memo.flirtee);});};this.registerInputViewConversation=function(oElement){oElement=$(oElement);if(!oElement)return;oElement.observe('click',function(e){SD.Event.fire(null,SD.UI.Events.VIEW_CONVERSATION,{sourceMemberId:_flirtee.uid,viewMessageUrl:SD.NavUtils.goTo('messages','flirt',{id:_flirtee.uid}),domEvent:e});});oElement.observe('mouseover',function(e){SD.Tooltip.show('View your conversation history with <b>'+_flirtee.username+'</b>');});oElement.observe('mouseout',function(e){SD.Tooltip.hide();});};this.registerInputNext=function(oElement){oElement=$(oElement);if(!oElement){return;}
oElement.observe('click',function(){window.scrollTo(0,0);SD.FlirtWink.View.next();});};this.registerInputPrevious=function(oElement){oElement=$(oElement);if(!oElement){return;}
oElement.observe('click',function(){window.scrollTo(0,0);SD.FlirtWink.View.previous();});SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,this.onFlirteeChangePrevButtonManager.bind(this,oElement));};this.onFlirteeChangePrevButtonManager=function(btn){if(this.mode!='match')return;btn=btn||$('flirtwink-btn-prev');btn&&(btn.style.display=SD.FlirtWink.Controller.getPreviousFlirtee()?'':'none');};this.registerInputProfileOpener=function(oElement,uid){oElement=$(oElement);oElement.setAttribute('sdType','profile');oElement.setAttribute('sdUid',uid);};this.registerInputRequestPhotos=function(oElement){oElement=$(oElement);oElement.onclick=function(){SD.FlirtWink.View.requestMorePhotos(_flirtee);}};this.registerInputRequestInfo=function(oElement){oElement=$(oElement);oElement.onclick=function(){SD.FlirtWink.View.requestMoreInfo(_flirtee);}};this.registerOutputChat=function(oElement){oElement=$(oElement);var inactiveClass="secondarybutton-chat-inactive";var gray='small-gray';var grayNoClick='small-gray-no-click';var green='small-green';var updateView=function(oUser){if(oUser.online||oUser.im_online){oElement.removeClassName(inactiveClass);oElement.removeClassName(gray);oElement.removeClassName(grayNoClick);oElement.addClassName(green);}else{oElement.addClassName(inactiveClass);if(SD.Model.getMyself().wantsToDate(oUser)||!SD.Model.getMyself().mightDate(oUser)){oElement.addClassName(gray);oElement.addClassName(grayNoClick);oElement.removeClassName(green);}else{oElement.removeClassName(grayNoClick);oElement.addClassName(gray);oElement.removeClassName(green);}}};SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){var oUser=e.memo.flirtee;if($('chatButtonContent')){$('chatButtonContent').innerHTML=SD.Model.getMyself().mightDate(oUser)?'SpeedDate&trade; Now!':(SD.Model.getMyself().is_premium?'CHAT':'Subscribe and Chat');}
updateView(oUser);});SD.Event.observe(null,SD.User.Events.USER_ONLINE,function(e){if(_flirtee&&e.memo.user&&e.memo.user.uid==_flirtee.uid){updateView(_flirtee);}});SD.Event.observe(null,SD.User.Events.USER_OFFLINE,function(e){if(_flirtee&&e.memo.user&&e.memo.user.uid==_flirtee.uid){updateView(_flirtee);}});};this.registerOutputFlirt=function(oElement){oElement=$(oElement);SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){var oUser=e.memo.flirtee;SD.Tracking.setElementTrackingCode(oElement,SD.Config.restrictionReasons[oUser.relation.permissions.flirt_restriction_reason].tc)});};this.registerOutputTaggingCloud=function(cloudId,tagId){SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){var oElement=$('cloud-header2703');if(oElement){oElement.update((e.memo.flirtee.sex=='F'?'Her':'His')+' tags');}
var uids=[e.memo.flirtee.uid];SD.Tag.removeCloud(cloudId);SD.Tag.drawCloud(uids,cloudId);});};this.registerOutputFlirteeUsername=function(oElement){oElement=$(oElement);if(!oElement){return;}
SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){oElement.update('');oElement.update(e.memo.flirtee.username);});};this.registerOutputReportPhoto=function(oElement){oElement=$(oElement);if(!oElement){return;}
SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){oElement.update('Report Concern');oElement.setAttribute('sdUid',e.memo.flirtee.uid);oElement.setAttribute('sdUserName',e.memo.flirtee.username);});};this.registerOutputExcludeUserFromProfilePage=function(oElement){oElement=$(oElement);if(!oElement){return;}
SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){oElement.update('Don\'t show anymore');oElement.writeAttribute('sdUid',e.memo.flirtee.uid);oElement.writeAttribute('sdUserName',e.memo.flirtee.username);oElement.writeAttribute('sdType','excludeUserFromProfilePage');});};this.registerOutputWink=function(oElement){oElement=$(oElement);if(!oElement){return;}
SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){e.memo.flirtee.relation.permissions&&e.memo.flirtee.relation.permissions.can_wink?oElement.removeClassName('small-gray-no-click'):oElement.addClassName('small-gray-no-click');var el;if(SD.Config.isSite){(el=$('flirtwink-btn-wink-content'))&&el.update(e.memo.flirtee.username);}});};this.registerOutputRecommendation=function(oElement){oElement=$(oElement);if(!oElement){return;}
var hideRecommendation=function(){oElement.hide();};var showRecommendation=function(reference,recommended){var td0="<span style='font-size: 14px; font-weight: bold;'>"+"Our Private Matchmaker&trade; Recommends #{recommended_name}</span>, "+"<span style='font-size: 13px'>because you were interested in <b>#{reference_name}</b></span>";var td1="<img src='#{reference_pic}' height='40' width='40' style='margin-left: 8px;'>";try{var tds=oElement.select('table')[0].select('td');tds[0].innerHTML=td0.interpolate({recommended_name:recommended.username,reference_name:reference.username});tds[1].innerHTML=td1.interpolate({reference_pic:reference.square_image_url});oElement.show();}catch(e){oElement.hide();}};SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){try{var f=e.memo.flirtee;if(f&&f.recommendationFor){var rec=SD.User.get(f.recommendationFor);showRecommendation(rec,f);}else{hideRecommendation();}}catch(e){hideRecommendation();}});};this.registerOutputRequest=function(oElement){oElement=$(oElement);if(!oElement){return;}
SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){oElement.select('b').first().update(e.memo.flirtee.username);});};this.registerOutputConversation=function(oElement){oElement=$(oElement);if(!oElement){return;}
SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){$('flirtwink-btn-view-conversation-content')&&$('flirtwink-btn-view-conversation-content').update(e.memo.flirtee.username);});};this.registerOutputFlirteeAge=function(oElement){oElement=$(oElement);SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){oElement.update('');oElement.update(e.memo.flirtee.age);});};this.registerOutputFlirteeCity=function(oElement){oElement=$(oElement);SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){var sCity=e.memo.flirtee.city_name?e.memo.flirtee.city_name+',&nbsp;':'';oElement.update(sCity);});};this.registerOutputFlirteeCountry=function(oElement){oElement=$(oElement);SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){oElement.update(e.memo.flirtee.country_name?e.memo.flirtee.country_name+'&nbsp;':'');});};this.registerOutputFlirteeState=function(oElement){oElement=$(oElement);SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){oElement.update(e.memo.flirtee.statecode?e.memo.flirtee.statecode+',&nbsp;':'');});};this.registerOutputFlirteeDistance=function(oElement){oElement=$(oElement);SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){oElement.update('');oElement.update(e.memo.flirtee.relation.distance);});};this.registerOutputFlirteeMatchedProfileInfos=function(oElement){oElement=$(oElement);if(!oElement)return;SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){oElement.update('');var matchedInfoHolder='';if((e.memo.flirtee.matched_profile_infos['flirtee_matches'].length+
e.memo.flirtee.matched_profile_infos['you_match'].length+
e.memo.flirtee.matched_profile_infos['mutual'].length)>0){matchedInfoHolder='<div class="matched-profile-infos">';if(e.memo.flirtee.matched_profile_infos['flirtee_matches'].length>0){matchedInfoHolder+='<div class="matched-profile-info-title category-title">'+e.memo.flirtee.name+' matches your preferences:</div>';matchedInfoHolder+='<ul class="matched-profile-info-list">';for(var i=0;i<e.memo.flirtee.matched_profile_infos['flirtee_matches'].length;i++){matchedInfoHolder+='<li><span class="check">&#8730;&nbsp;</span>'+e.memo.flirtee.matched_profile_infos['flirtee_matches'][i]+'</li>';}
matchedInfoHolder+='</ul>';}
if(e.memo.flirtee.matched_profile_infos['you_match'].length>0){matchedInfoHolder+='<div class="matched-profile-info-title category-title">You match '+e.memo.flirtee.name+"'s preferences:</div>";matchedInfoHolder+='<ul class="matched-profile-info-list">';for(var i=0;i<e.memo.flirtee.matched_profile_infos['you_match'].length;i++){matchedInfoHolder+='<li><span class="check">&#8730;&nbsp;</span>'+e.memo.flirtee.matched_profile_infos['you_match'][i]+'</li>';}
matchedInfoHolder+='</ul>';}
if(e.memo.flirtee.matched_profile_infos['mutual'].length>0){matchedInfoHolder+='<div class="matched-profile-info-title category-title">You have in common:</div>';matchedInfoHolder+='<ul class="matched-profile-info-list">';for(var i=0;i<e.memo.flirtee.matched_profile_infos['mutual'].length;i++){matchedInfoHolder+='<li><span class="check">&#8730;&nbsp;</span>'+e.memo.flirtee.matched_profile_infos['mutual'][i]+'</li>';}
matchedInfoHolder+='</ul>';}
matchedInfoHolder+='<div>';}
oElement.update(matchedInfoHolder);});};this.registerOutputFlirteeDetails=function(oElement,oAboutMeElement){oElement=$(oElement);oAboutMeElement=$(oAboutMeElement);SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){var oFlirtee=e.memo.flirtee;oElement.update('');oAboutMeElement.update('');for(var i=0;i<oFlirtee.member_info.length;i++){if(oFlirtee.member_info[i].category_items.length&&(i!=6||oFlirtee.member_info[i].category_items.length>1)){oElement.appendChild(DIV({'class':'category-title'},oFlirtee.member_info[i].category_title));var oCategoryItems=DIV({'class':'category-items'},'');for(var j=0;j<oFlirtee.member_info[i].category_items.length;j++){if(oFlirtee.member_info[i].category_items[j].title=='More About Me'){oAboutMeElement.update('"'+oFlirtee.member_info[i].category_items[j].text_value+'"');}else{oCategoryItems.appendChild(DIV({'class':'category-item'},SPAN({},oFlirtee.member_info[i].category_items[j].title+': '),oFlirtee.member_info[i].category_items[j].text_value));}}
oElement.appendChild(oCategoryItems);}}
if(oFlirtee.is_premium){$(oElement.parentNode).addClassName('featured');}else{$(oElement.parentNode).removeClassName('featured');}});};this.registerOutputFlirteeDetails2703=function(oElement,oAboutMeElement,oHeadlineElement,oDealbreakersElement){oElement=$(oElement)||null;oAboutMeElement=$(oAboutMeElement)||null;oHeadlineElement=$(oHeadlineElement);oDealbreakersElement=$(oDealbreakersElement);SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){var oFlirtee=e.memo.flirtee;oElement&&oElement.update('');oAboutMeElement&&oAboutMeElement.update('');oHeadlineElement.update('');oDealbreakersElement.update('');var dealBreakerIds=["12","14","4","5","8","2","3","6","7"];var dealBreakers=[];for(var i=0;i<oFlirtee.member_info.length;i++){if(oFlirtee.member_info[i].category_items.length&&(i!=6||oFlirtee.member_info[i].category_items.length>1)){oElement&&oElement.appendChild(DIV({'class':'category-title'},oFlirtee.member_info[i].category_title));var oCategoryItems=DIV({'class':'category-items'},'');var html='';for(var j=0;j<oFlirtee.member_info[i].category_items.length;j++){if(oFlirtee.member_info[i].category_items[j].title=='More About Me'){oAboutMeElement&&oAboutMeElement.update('<div class="category-title">About Me</div><div class="about-me-text">"'+oFlirtee.member_info[i].category_items[j].text_value+'"</div>');}else{html+="<table width='100%'>"+"<tr>"+"<td class='category-item-title'>"+oFlirtee.member_info[i].category_items[j].title+': '+"</td>";html+="<td class='category-item-value'>"+oFlirtee.member_info[i].category_items[j].text_value+"</td>";html+="</tr>"+"</table>";}
if(dealBreakerIds.indexOf(oFlirtee.member_info[i].category_items[j].id)>-1){dealBreakers.push({"title":oFlirtee.member_info[i].category_items[j].title,"text_value":oFlirtee.member_info[i].category_items[j].text_value});}}
oCategoryItems.innerHTML=html;oElement&&oElement.appendChild(oCategoryItems);}}
$('thumbs2703')&&$('thumbs2703').setStyle({'padding':'15px 0px 0px 7px'});for(var j=0;j<oFlirtee.member_info[6].category_items.length;j++){if(oFlirtee.member_info[6].category_items[j].title=='Dating Status'){oHeadlineElement.update('<div class="headline-text2703">"'+oFlirtee.member_info[6].category_items[j].text_value+'"</div>');$('thumbs2703')&&$('thumbs2703').setStyle({'padding':'0px 0px 0px 7px'});}}
if(dealBreakers.length){html="<table width='100%'>";var oDealBreakerItems=DIV({'class':'dealbreakers2703 categories2703'});for(var k=0;k<dealBreakers.length;k++){html+="<tr>"+"<td class='category-item-title no-border'>"+dealBreakers[k].title+': '+"</td>"+"<td class='category-item-value no-border'>"+dealBreakers[k].text_value+"</td>"+"</tr>";}
html+="</table>";oDealBreakerItems.innerHTML=html;oDealbreakersElement.appendChild(oDealBreakerItems);}
if(oFlirtee.is_premium){oElement&&$(oElement.parentNode).addClassName('featured');}else{oElement&&$(oElement.parentNode).removeClassName('featured');}});};this.registerOutputFlirteeImage=function(oElement){oElement=$(oElement);oElement.observe('load',function(){this.style.visibility='';});SD.Event.observe(null,SD.FlirtWink.View.Events.PROFILE_VIEW_REQUEST,function(e){if(!SD.User.hasUser(e.memo.uid)){oElement.style.visibility='hidden';}});SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){var oFlirtee=e.memo.flirtee;oElement.src=oFlirtee.image_url_large;oElement[oFlirtee.is_premium?"addClassName":"removeClassName"]('featured');});};this.registerOutputFlirteeMessage=function(oElement){oElement=$(oElement);if(!SD.Model.getMyself().is_premium){SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){var oFlirtee=e.memo.flirtee;var messageContents='';var messageClassName='flirtee-message-overflirted';oElement.removeClassName(messageClassName);oElement.stopObserving('click');oElement.hide();if(!oFlirtee.relation.permissions.can_flirt||!oFlirtee.relation.permissions.can_wink){var trackingCode="";if(SD.Config.platform.platformId!=3){var interpolatedText=SD.Config.restrictionReasons[oFlirtee.relation.permissions.flirt_restriction_reason].text1.interpolate(oFlirtee);var heading=A({},interpolatedText);messageContents=SPAN({},heading,interpolatedText?BR():"",SD.Config.restrictionReasons[oFlirtee.relation.permissions.flirt_restriction_reason].before_link,A({},SD.Config.restrictionReasons[oFlirtee.relation.permissions.flirt_restriction_reason].link),SD.Config.restrictionReasons[oFlirtee.relation.permissions.flirt_restriction_reason].after_link);oElement.observe('click',function(event){event.stop();var trackingCode=SD.Config.restrictionReasons[oFlirtee.relation.permissions.flirt_restriction_reason].old_tc;var trackingObject=SD.Tracking.getTrackingObject(SD.Tracking.getTrackingObject(SD.Config.restrictionReasons[oFlirtee.relation.permissions.flirt_restriction_reason].tc),null,null,oElement);SD.UIController.upgradeMyself({'ti':oFlirtee.uid,'tc':trackingCode,'tobj':trackingObject});});oElement.addClassName(messageClassName);oElement.update(messageContents);oElement.show();}}});}};this.registerOutputFlirteeFeatured=function(oElement){oElement=$(oElement);if(!oElement){return;}
if(!SD.Model.getMyself().is_premium){oElement.observe('click',function(){if(SD.Model.getMyself().can_see_one_click_form){SD.UIController.oneClickSubscriptionPopup(15,_flirtee.uid);}else if(!SD.Model.getMyself().is_organic&&!SD.Model.getMyself().can_see_resubscribe){SD.UIController.speedVerifyPopup({sourceType:15,sourceMemberId:_flirtee.uid,forceVerify:true});}else{SD.UIController.upgradeMyself({'ti':_flirtee.uid,'tc':SD.TrackingCodes.trigger.banner.premium_badge._value});}});oElement.addClassName('common-clickable');}
SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){var oFlirtee=e.memo.flirtee;oElement.hide();if(oFlirtee.show_as_premium){oElement.show();}});};this.registerOutputFlirteeNewMember=function(oElement){oElement=$(oElement);oElement&&SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){var oFlirtee=e.memo.flirtee;oElement.hide();if(oFlirtee.show_as_new){oElement.show();}});};this.registerOutputLoading=function(oElement){oElement=$(oElement);SD.Event.observe(null,SD.FlirtWink.View.Events.PROFILE_VIEW_REQUEST,function(e){if(!SD.User.hasUser(e.memo.uid)){oElement.show();$('flirtee-content').addClassName('opacity30');}});SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){oElement.hide();$('flirtee-content').removeClassName('opacity30');});};this.registerOutputFlirteeRating=function(oElement){oElement=$(oElement);if(!oElement)return;SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){var oFlirtee=e.memo.flirtee;SD.UI.Rating.setStyle(oElement,oFlirtee.rating);oElement.setAttribute('sdRating',oFlirtee.rating);oElement.setAttribute('sdUserRating',oFlirtee.relation.rating);oElement.setAttribute('sdTotalRating',oFlirtee.total_rating);oElement.setAttribute('sdUid',oFlirtee.uid);oElement.setAttribute('sdUsername',oFlirtee.username);$(oElement.getAttribute('sdTotalRatingId')).update(oFlirtee.total_rating);});};this.registerOutputFacebookLikeButton=function(oElement){oElement=$(oElement);if(oElement){SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){var oFlirtee=e.memo.flirtee;var publicURL=oFlirtee.publicURL;publicURL=escape(publicURL).replace(/\+/g,'%2B').replace(/%20/g,'+').replace(/\*/g,'%2A').replace(/\//g,'%2F').replace(/@/g,'%40');generateNewIframe.curry('http://www.facebook.com/plugins/like.php?href='+publicURL+'&layout=button_count&show_faces=false&width=100&action=like&colorscheme=light&height=21').defer();});}
function generateNewIframe(src){var parentNode=oElement.parentNode;var oElementId=oElement.id;var html='<iframe id="'+oElementId+'" '+'scrolling="no" '+'frameborder="0" '+'style="border:none; overflow:hidden; width:100px; height:25px;" '+'allowTransparency="true" '+'src="'+src+'"></iframe>';oElement=null;parentNode.innerHTML=html;oElement=$('facebook-like-button-frame');}};this.registerOutputTwitterTweetButton=function(oElement){oElement=$(oElement);if(oElement){SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){var oFlirtee=e.memo.flirtee;var publicURL=oFlirtee.publicURL;publicURL=escape(publicURL).replace(/\+/g,'%2B').replace(/%20/g,'+').replace(/\*/g,'%2A').replace(/\//g,'%2F').replace(/@/g,'%40');oElement.hide();setTimeout(function(){oElement.src='http://platform.twitter.com/widgets/tweet_button.html?count=horizontal&lang=en&text=Tell%20me%20what%20you%20think%20of%20this%20person&url='+publicURL;oElement.show();},100);});}};this.registerOutputSendGift_3641=function(oElement){oElement=$(oElement);if(!oElement)return;oElement&&SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){oElement.onclick=function(){SD.UIController.giftsPopup(e.memo.flirtee.uid);}});};this.registerOutputSubnav=function(oElement){oElement=$(oElement);if(!oElement)return;this.flirtwinkSubNav=oElement;};this.registerOutputSMSOption=function(el){el=$(el);if(!el)return;SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){el.innerHTML=e.memo.flirtee.username;});}
this.registerOutputCannedFlirt=function(cannedCtrl){SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){var flirtee=e.memo.flirtee;if(flirtee.relation.cannedFlirts.length==0){cannedCtrl.hide();return;}else{cannedCtrl.show();}
cannedCtrl.removeAllItems();var a=flirtee.relation.cannedFlirts;for(var i=0;i<a.length;i++){cannedCtrl.addItem(a[i]);}});};this.setupCannedCtrl=function(options){return new SD.UI.Dropdown({form:options.domForm,name:options.domHandle,value:'',domHandle:options.domHandle,domSource:options.domSource,className:'frlirtwink-dropdown',alignment:options.alignment});};this.registerInputCannedFlirt=function(cannedCtrl,oBlockedElement,oCounterElement,oSendButton){if(!cannedCtrl)return;oBlockedElement=$(oBlockedElement);if(!oBlockedElement)return;oSendButton=$(oSendButton);if(!oSendButton)return;cannedCtrl.observe('change',function(){if(oBlockedElement.value&&oBlockedElement.value!=oBlockedElement.getAttribute("sdLabel")&&oBlockedElement.value.trim()!=""){oBlockedElement.setAttribute("sdLabel",oBlockedElement.value);oBlockedElement.setAttribute("edited",1);}
oBlockedElement.value=cannedCtrl.value;var sdClassLabel=oBlockedElement.getAttribute('sdClassLabel');if(!oBlockedElement.hasClassName(sdClassLabel)){oBlockedElement.addClassName(sdClassLabel);}
var sdDisabledClassLabel=oBlockedElement.getAttribute("sdDisabledClassLabel");if(sdDisabledClassLabel){oBlockedElement.addClassName(sdDisabledClassLabel);}
_flirtee&&updateButton(oSendButton.down('u'),_flirtee.relation.permissions.can_canned_flirt);});};this.registerOutputFlirtField=function(oElement){oElement=$(oElement);if(!oElement)return;SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){var newLabel="Type your message for "+e.memo.flirtee.username+" here...";oElement.value=newLabel;oElement.setAttribute('sdLabel',newLabel);oElement.setAttribute("edited",0);var sdDisabledClassLabel=oElement.getAttribute("sdDisabledClassLabel");if(sdDisabledClassLabel){oElement.removeClassName(sdDisabledClassLabel);}
var sdClassLabel=oElement.getAttribute('sdClassLabel');if(!oElement.hasClassName(sdClassLabel)){oElement.addClassName(sdClassLabel);}});};this.registerInputFlirtField=function(oFlirtInput,cannedCtrl,oSendButton){if(!cannedCtrl)return;oFlirtInput=$(oFlirtInput);if(!oFlirtInput)return;oSendButton=$(oSendButton);if(!oSendButton)return;oFlirtInput.value=oFlirtInput.innerHTML.trim();oFlirtInput.onfocus=function(){cannedCtrl&&cannedCtrl.selectByIndex(0);_flirtee&&_flirtee.relation.permissions&&updateButton(oSendButton.down('u'),_flirtee.relation.permissions.can_type_in_flirt);}};this.registerOutputConversationBox=function(oElement){return;var _this=SD.FlirtWink.View;this.conversationHolder=oElement=$(oElement);if(!oElement)return;this.restoreConversationHolder=function(){this.conversationHolder.insert({'top':this.conversationBoxLocker});this.conversationHolder.insert({'top':this.conversationBoxChatHistory});this.conversationHolder.insert({'top':this.conversationBoxMsgHistory});this.conversationHolder.insert({'top':this.conversationBoxInCommon});};this.conversationHolder.update('<div class="conversation-box-in-common"></div>'+'<div class="conversation-box-message-history"></div>'+'<div class="conversation-box-chat-history"></div>'+'<div class="conversation-box-locker"></div>');this.conversationBoxInCommon=this.conversationHolder.select(".conversation-box-in-common").first();this.conversationBoxMsgHistory=this.conversationHolder.select(".conversation-box-message-history").first();this.conversationBoxChatHistory=this.conversationHolder.select(".conversation-box-chat-history").first();this.conversationBoxLocker=this.conversationHolder.select(".conversation-box-locker").first();var doRender=function(user){_this.conversationBoxInCommon.update();_this.conversationBoxMsgHistory.update();_this.conversationBoxChatHistory.update();_this.conversationBoxLocker.update();_this.conversationBoxInCommon.update(SD.FlirtWink.View.matchedInfoRenderer(user))
if(!SD.Model.getMyself().is_premium){doRenderBoxLocker(user);}
var isMessageHistoryLoaded=false;SD.Communication.History.loadCommunicationHistory(user,function(records){_this.conversationBoxMsgHistory.update(_this.HistoryRenderer.renderHistory(records,user));isMessageHistoryLoaded=true;});var isChatHistoryLoaded=false;SD.Chat.History.loadCompleteChatHistory(user,function(records){_this.conversationBoxChatHistory.update(_this.HistoryRenderer.renderChatHistory(records,user));isChatHistoryLoaded=true;});function renderBoxLocker(){if(!SD.Model.getMyself().is_premium&&isMessageHistoryLoaded&&isChatHistoryLoaded){var messageCount=SD.Communication.History.getRecords(user.uid).msgCount;var chatCount=SD.Chat.History.getRecords(user.uid).length;if(messageCount+chatCount>0){doRenderBoxLocker(user);}}}};this.renderConversation=doRender;function doRenderBoxLocker(user){SD.FlirtWink.View.conversationBoxLocker.update(SD.FlirtWink.View.lockConversationRendererSimple(user));(function(){SD.FlirtWink.View.conversationBoxLocker.parentNode.scrollTop=SD.FlirtWink.View.conversationBoxLocker.offsetTop+SD.FlirtWink.View.conversationBoxLocker.offsetHeight;}).defer();}
SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){doRender(e.memo.flirtee);});var onFlirtWink=function(type,e){var messageRecord={messageType:type,actorId:SD.Model.getMyself().uid,time:Math.floor((new Date).getTime()/1000),message:e.memo.flirtMessage,read:0};if(e.memo.uid==_flirtee.uid){if(SD.Model.getMyself().is_premium){SD.Communication.History.addRecords(_flirtee.uid,'messages',messageRecord,0);var records=SD.Communication.History.getRecords(_flirtee.uid);_this.conversationBoxMsgHistory.update(_this.HistoryRenderer.renderHistory(records,_flirtee));_this.conversationHolder.scrollTop=_this.conversationBoxMsgHistory.offsetTop;}else{}}}
SD.Event.observe(null,SD.FlirtWink.Events.FLIRT,onFlirtWink.bind(null,1));SD.Event.observe(null,SD.FlirtWink.Events.WINK,onFlirtWink.bind(null,2));doRender(_flirtee);};function updateButton(btn){btn&&btn.update('Send Email');}
this.displayWinkSuccess=function(oUser){SD.UIController.infoMessage('You successfully winked at '+oUser.username+'.',5);};this.displayFlirtSuccess=function(oUser){SD.UIController.infoMessage('You successfully emailed '+oUser.username+'.',5);};this.displayProfileNotificationSuccess=function(user){SD.UIController.infoMessage('You successfully sent notification to '+user.username+'.',2);}
this.displayFavoriteResponse=function(oUser,isSuccess){var message=(isSuccess?oUser.username+' is now on your favorites list!':oUser.username+' could not be added to favorites list. Try again later.');SD.UIController.infoMessage(message,5);};this.moreInfoRequestResponse=function(jsonResponse){var okMessage=jsonResponse.message||"You request has been successfully sent!";if(jsonResponse.status===true){SD.UIController.infoMessage(okMessage,5);}else{SD.UIController.infoMessage(jsonResponse.message,5);}};this.largePhotoRenderer=function(dom,user){if(user.images.length==0){return}
user.images.each(function(img){var photo=new Image();photo.onload=this.pRenderer.bind(this,dom,photo);if(img.image_url_extralarge){photo.src=img.image_url_extralarge;}else{photo.src=img.image_url_large;}
return photo;},this);};var domSoftHyphen=document.createElement('span');domSoftHyphen.innerHTML='&shy;';domSoftHyphen.style.visibility='hidden';domSoftHyphen.style.fontSize='0px';this.pRenderer=function(dom,img){var maxWidth=parseInt($(dom).getStyle("width"))-10;img.width=Math.min(img.width,maxWidth);img.style.margin='5px';img.onload=null;dom.appendChild(img);if(Prototype.Browser.IE6){dom.appendChild(domSoftHyphen.cloneNode(true));}};this.lockConversationRenderer=function(user){var html='<div class="profile-locked-area">Hey <b>'+SD.Model.getMyself().username+'</b>, if you want to keep talking with <b>'+user.username+'</b> you ';if(SD.Model.getMyself().is_organic){html+='<a href="javascript:void(SD.UIController.upgradeMyself({'+'tc:SD.TrackingCodes.trigger.communication.flirt.not_responded._value,'+'ti:'+user.uid+','+'tobj:SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.UPGRADE_BUTTON_NOT_RESPONDED)'+'}));">need to <b>Subscribe</b></a>'}else{html+='<a href="javascript:void(0)" onclick="SD.UIController.speedVerifyPopup({forceVerify:true})">need to <b>SpeedVerify&trade; your account</b></a>';}
html+='</div>';return html;};this.lockConversationRendererSimple=function(user){var html='<div class="profile-locked-area">This conversation is locked.<br/>';html+='<a href="javascript:void(SD.UIController.upgradeMyself({'+'tc:SD.TrackingCodes.trigger.communication.flirt.not_responded._value,'+'ti:'+user.uid+','+'tobj:SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.UPGRADE_BUTTON_NOT_RESPONDED)'+'}));"><b>Subscribe to unlock it</b></a>';html+='</div>';return html;};this.matchedInfoRenderer=function(user){var i,html=[];if((user.matched_profile_infos['flirtee_matches'].length+
user.matched_profile_infos['you_match'].length+
user.matched_profile_infos['mutual'].length)>0){html[html.length]='<div class="matched-profile-infos">';if(user.matched_profile_infos['flirtee_matches'].length>0){html[html.length]='<div class="matched-profile-info-title category-title">'+user.name+' matches your preferences:</div>';html[html.length]='<ul class="matched-profile-info-list">';for(i=0;i<user.matched_profile_infos['flirtee_matches'].length;i++){html[html.length]='<li><span class="check">&#8730;&nbsp;</span>'+user.matched_profile_infos['flirtee_matches'][i]+'</li>';}
html[html.length]='</ul>';}
if(user.matched_profile_infos['you_match'].length>0){html[html.length]='<div class="matched-profile-info-title category-title">You match '+user.name+"'s preferences:</div>";html[html.length]='<ul class="matched-profile-info-list">';for(i=0;i<user.matched_profile_infos['you_match'].length;i++){html[html.length]='<li><span class="check">&#8730;&nbsp;</span>'+user.matched_profile_infos['you_match'][i]+'</li>';}
html[html.length]='</ul>';}
if(user.matched_profile_infos['mutual'].length>0){html[html.length]='<div class="matched-profile-info-title category-title">You have in common:</div>';html[html.length]='<ul class="matched-profile-info-list">';for(i=0;i<user.matched_profile_infos['mutual'].length;i++){html[html.length]='<li><span class="check">&#8730;&nbsp;</span>'+user.matched_profile_infos['mutual'][i]+'</li>';}
html[html.length]='</ul>';}
html[html.length]='<div>';}
return html.join('');};this.emptyRenderer=function(){return'';};this.renderTime=function(time,template){return SD.Utils.Date.getFormatedTime(template||'#{day}-#{MONTH_SHORT}-#{year}',time*1000);};this.chatRenderer=function(record,otherUser){var html='<div class="history-message">',actor='<span class="username">'+((record.uid==otherUser.uid)?otherUser.username.truncate(12):'me')+': </span>';html+='<span class="time">'+this.renderTime(record.intTime)+'</span> '+actor+record.text.escapeHTML().gsub('\n','<br/>')+'</div>';return html;};this.flirtRenderer=function(record,otherUser){var html='<div class="history-message">',actor='<span class="username">'+((record.actorId==otherUser.uid)?otherUser.username.truncate(12):'me')+': </span>';html+='<span class="time">'+this.renderTime(record.time)+'</span> '+actor+record.message;if(+record.read){html+=' <span class="was-it-read">(read on '+this.renderTime(record.read)+')</span>'}else{html+=' <span class="was-it-read">(not read)</span>';}
html+='</div>';return html;};this.giftRenderer=function(record,otherUser){var html='<div class="history-message">',actor;if(otherUser.uid==record.actorId){actor='<span class="username">'+otherUser.username.truncate(12)+' </span> has sent you a gift <br>';}else{actor='<span class="username">You</span> have sent <span class="username">'+otherUser.username.truncate(12)+'</span><br>';}
var message='<div class="gift-in-msg"><img src="/static/site/images/gift/'+record.giftId+'.jpg"></div>';html+='<span class="time">'+this.renderTime(record.time)+'</span> '+actor+message;if(+record.read){html+=' <span class="was-it-read">(read on '+this.renderTime(record.read)+')</span>';}else{html+=' <span class="was-it-read">(not read)</span>';}
html+='<br clear="all"></div>';return html;};this.defaultMessageRenderer=function(record,otherUser){if(record.giftId){return this.giftRenderer(record,otherUser);}else{return this.flirtRenderer(record,otherUser);}};this.favoritesRenderer=function(record,otherUser){var html=[];if(record.actorId==otherUser.uid){html.push('<div class="history-message"><span class="time">'+this.renderTime(record.time)+'</span> <span class="username">'+otherUser.username.truncate(12)+'</span>: Favorited you.</div>');}else{html.push('<div class="history-message"><span class="time">'+this.renderTime(record.time)+'</span> <span class="username">You</span> favorited '+otherUser.username.truncate(12)+'</div>');}
return html.join('');};this.HistoryRenderer={renderHistory:function(data,otherUser){var html='';if(data.favorite&&data.favorite.length){html+=this.renderFavorites(data.favorite,otherUser);}
if(data.messages&&data.messages.length){html+=this.renderMessages(data.messages,otherUser);}
return html;},renderChatHistory:function(records,otherUser){if(!records.length)return'';var html=['<div class="history-section-title category-title">Chat and Date History</div>','<div class="history-section-holder">'];for(var i=0;i<records.length;i++){html.push(SD.FlirtWink.View.chatRenderer(records[i],otherUser));}
html.push('</div>')
return html.join('');},renderFavorites:function(records,otherUser){if(!records.length)return'';var html=['<div class="history-section-title category-title">Favoriting History</div>','<div class="history-section-holder">'];for(var i=0;i<records.length;i++){html.push(SD.FlirtWink.View.favoritesRenderer(records[i],otherUser));}
html.push('</div>')
return html.join('');},renderMessages:function(records,otherUser){if(!records.length)return'';var html=['<div class="history-section-title category-title">Message History</div>','<div class="history-section-holder message-history-holder">'];var i=records.length;while(i--){html.push(SD.FlirtWink.View[this.messageRenderers[records[i].messageType]](records[i],otherUser));}
html.push('</div>')
return html.join('');},messageRenderers:{'0':'defaultMessageRenderer','1':'flirtRenderer','2':'flirtRenderer','3':'giftRenderer','4':'defaultMessageRenderer','5':'defaultMessageRenderer','7':'defaultMessageRenderer','8':'defaultMessageRenderer','9':'defaultMessageRenderer','10':'defaultMessageRenderer','11':'defaultMessageRenderer','12':'defaultMessageRenderer','13':'defaultMessageRenderer','14':'favoritesRenderer','16':'defaultMessageRenderer','17':'defaultMessageRenderer','18':'defaultMessageRenderer','19':'defaultMessageRenderer'}};};SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){SD.FlirtWink.View.showFlirtWink();});SD.FlirtWink.View.Events={MODE_CHANGED:'SD.FlirtWink.View.Events.MODE_CHANGED',FLIRTWINK_LAYOUT_CHANGED:'SD.FlirtWink.View.Events.FLIRTWINK_LAYOUT_CHANGED',PROFILE_VIEW_REQUEST:'SD.Flirtwink.View.Events.PROFILE_VIEW_REQUEST'};SD.FlirtWink.View.registerInputFlirtSendButton=function(oFlirtInput,cannedCtrl,oSendButton,oErrorNotify,virtualGiftCheck){if(!cannedCtrl)return;cannedCtrl.toSubmit=false;window.cannedCtrl=cannedCtrl;oSendButton=$(oSendButton);if(!oSendButton)return;oFlirtInput=$(oFlirtInput);if(!oFlirtInput)return;oErrorNotify=$(oErrorNotify);if(!oErrorNotify)return;virtualGiftCheck=$(virtualGiftCheck);var textNode=oSendButton.down('u');function updateButton(btn,canSend){btn&&btn.update('Send Email');}
SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){var _flirtee;_flirtee=e.memo.flirtee;oErrorNotify.style.display='none';_flirtee&&updateButton(textNode,_flirtee.relation.permissions.can_flirt);virtualGiftCheck&&(virtualGiftCheck.checked=false);});oSendButton.onclick=function(e){if(oFlirtInput.getAttribute('sdlabel')==oFlirtInput.value||oFlirtInput.value.trim()==''){return;}
var _flirtee=SD.FlirtWink.View.getFlirtee();var message,messageType;oErrorNotify.style.display='none';if(cannedCtrl.selectedIndex>0){message=cannedCtrl.value;messageType='canned_flirt';}else if(oFlirtInput.value&&(oFlirtInput.getAttribute('edited')==1||oFlirtInput.value!=oFlirtInput.getAttribute('sdLabel'))){message=oFlirtInput.value;messageType='flirt';}else{oErrorNotify.innerHTML='Can not send an empty message.';oErrorNotify.style.display='block';return;}
var virtualGift=(virtualGiftCheck&&virtualGiftCheck.checked)?virtualGiftCheck.value:null;var onEmailSent=function(){if(SD.TutorialManager.canSendOneFreeEmail){SD.TutorialManager.canSendOneFreeEmail=false;}
oFlirtInput.value='';cannedCtrl.selectByIndex(0);};var tc=0;try{tc=_flirtee.relation.permissions?SD.Config.restrictionReasons[_flirtee.relation.permissions.flirt_restriction_reason].old_tc:'';}catch(e){}
var context=SD.Utils.buildContext({sourceMemberId:_flirtee.uid,sourceType:SD.UIController.PopupSourceTypes.EMAIL,sourceMember:_flirtee,messageType:messageType,message:message,virtualGift:virtualGift,onActionEnd:onEmailSent,recommendActionType:"emailed",sourceUI:"FlirtWinkPageButton",actionType:SD.UIController.ActionTypes.REGULAR_INVITATION,tc:tc},e||window.event);if(SD.TutorialManager.canSendOneFreeEmail){SD.FlowManager.run(SD.Actions.basicEmail.clone(),context);}else{SD.FlowManager.run(SD.Flows.email.clone(),context);}};};
SD.Dialogs={dialogPreferenceAnalyzer:function(){SD.UIController.preferenceAnalyzerPopup();},dialogFlirt:function(context,continuationCallback){var isTooltip;var flirtMessages=["I've had a great day, and the only thing that could make it better is you writing back.","This is me making the first move.... Your turn!","Here I am! What were your other two wishes?","I need to start hanging out with more attractive people- wanna hang out?","I'd feel like a superstar if I could go out with you...","You're cute! Just thought you should know...","Hey... Didn't I see your name in the dictionary under 'Gorgeous!'","Hey, I'd be down to start a little conversation, you?","Hey there... let's connect, you seem super cool!","Are you as witty and charming in real life as you seem in that picture?","I think I have a crush on you, but I can't tell until we hang out.","I hope you think I'm as cute as I think you are.","Why do you look so familiar? Oh yeah, you were in my dreams!","You are so good-looking that I forgot my pickup line.","If they let me rearrange the alphabet, I would put 'U' and 'I' together.","Hey, is it just me, or are we destined to go on a date?","I'm writing an essay on the finer things in life.  Can I interview you?","What's up?","You are the hottest person I've seen on SpeedDate.","I really think we should get to know each other.  I hope you feel the same!","Write back to me please - I think we'd hit it off.","Hey, don't I know you? Yeah, you're the one with the beautiful smile.","I don't like to play games so I'll just tell you the truth - I like you.","If I think you are cute, and you think I'm cute- then maybe we should talk!","If you are really as cool as you seem to be, let's have a chat!"];var pickKofN=function(k,n){return(n==0||k==0)?[]:$A($R(0,n-1)).sortBy(Math.random).slice(0,k);};var getProperty=function(property){return this[property];}
var staticFlirtMessages=function(howMany){return pickKofN(howMany,flirtMessages.length).map(getProperty.bind(flirtMessages));};var selectedflirtMessages=staticFlirtMessages(3);var renderTooltip=function(context,continuationCallback,user){if(!user.relation.permissions.can_type_in_flirt){SD.UIController.upgradeMyself({'ti':user.uid,'tc':SD.Config.restrictionReasons[user.relation.permissions.flirt_restriction_reason].old_tc});continuationCallback&&continuationCallback();return;}
var win;var ids=SD.Utils.IdGenerator.generateCollection('flirtFormId','flirtMsgId1','flirtMsgId2','flirtMsgId3','flirtMsgOtherId','messageId','charCountId','btnSendId','btnCloseId','btnGiftId','giftBoxId');var flirtPanelStr='<div class="flirtpop">'+'<form id="#{flirtFormId}">'+'<table class="flirt-messages">'+'<tr>'+'<td class="checkbox">'+'<input type="radio" id="#{flirtMsgId1}" name="flirt_msg" value="#{flirtMsgValue1}">'+'</td>'+'<td>'+'<label for="#{flirtMsgId1}">#{flirtMsgValue1}</label>'+'</td>'+'</tr>'+'<tr>'+'<td class="checkbox">'+'<input type="radio" id="#{flirtMsgId2}" name="flirt_msg" value="#{flirtMsgValue2}">'+'</td>'+'<td>'+'<label for="#{flirtMsgId2}">#{flirtMsgValue2}</label>'+'</td>'+'</tr>'+'<tr>'+'<td class="checkbox">'+'<input type="radio" id="#{flirtMsgId3}" name="flirt_msg" value="#{flirtMsgValue3}">'+'</td>'+'<td>'+'<label for="#{flirtMsgId3}">#{flirtMsgValue3}</label>'+'</td>'+'</tr>'+'<tr>'+'<td class="checkbox">'+'<input type="radio" id="#{flirtMsgOtherId}" class="sd-flirt-radio" name="flirt_msg" value="" checked="checked">'+'</td>'+'<td>'+'<label for="#{flirtMsgOtherId}">Other</label>'+'<br>'+'<textarea id="#{messageId}" class="input-field sd-flirt-input" name="message"></textarea>'+'<div class="limits">Max 1000 characters (<span id="#{charCountId}" class="sd-flirt-counter">1000</span> characters left)</div>'+'</td>'+'</tr>'+'</table>'+'</form>'+'<div>'+'<input id="#{btnSendId}" type="button" value="Send" class="input-button sd-flirt-submit">'+'#{btnGiftTemplate}'+'<input id="#{btnCloseId}" type="button" class="input-button right-button" value="Close">'+'</div>'+'<div id="#{giftBoxId}" class="sd-gift-select">gifts</div>'+'</div>';flirtPanelStr=flirtPanelStr.interpolate(SD.Utils.mixin({},ids,{flirtMsgValue1:selectedflirtMessages[0],flirtMsgValue2:selectedflirtMessages[1],flirtMsgValue3:selectedflirtMessages[2],btnGiftTemplate:SD.UIController.displayGift?'<input id="#{btnGiftId}" type="button" class="input-button" value="Add Gift">'.interpolate(ids):''}));if(isTooltip){win=SD.TooltipDialog.create({content:flirtPanelStr,refPoint:{x:context.pageX,y:context.pageY},refDom:context.sourceElement,width:450},continuationCallback);}else{win=SD.UIController.standardPopup({content:flirtPanelStr,title:'Email '+user.username,draggable:true,width:432,onAfterClose:function(){continuationCallback&&continuationCallback();}});win.showCenter(false,100);}
win.domContent.style.padding='3px 13px 13px';var getFlirtID=function(){return $(ids.flirtFormId).select("input:checked").first()==$(ids.flirtMsgOtherId)?100:0;}
var getMessage=function(){var selectedEl=$(ids.flirtFormId).select("input:checked").first();return selectedEl==$(ids.flirtMsgOtherId)?$(ids.messageId).value:selectedEl?selectedEl.value:$(ids.flirtMsgId1).value;};var giftUI=null;var getGiftID=function(){return giftUI&&giftUI.giftId;};$(ids.flirtFormId).flirt_msg[3].checked=true;$(ids.btnSendId).disabled=true;$(ids.btnSendId).observe('click',function(){if(!SD.Model.getMyself().is_premium){user.relation.permissions.can_type_in_flirt=false;user.relation.permissions.can_canned_flirt=false;user.relation.permissions.can_flirt=false;}
SD.FlirtWink.Controller.flirt(user,getMessage(),getFlirtID(),getGiftID(),SD.UIController.platform_id,Prototype.emptyFunction);win.close();});$A($(ids.flirtFormId).flirt_msg).each(function(chk,index){chk.observe('click',function(){$(ids.btnSendId).disabled=((index===$(ids.flirtFormId).flirt_msg.length-1)&&($(ids.messageId).value.length===0));});});if(SD.UIController.displayGift){giftUI=new SD.Gift.UI($(ids.giftBoxId));var toggleGift=function(){giftUI.switchgift($(ids.btnGiftId));}
$(ids.btnGiftId).observe('click',toggleGift);context.showGift?toggleGift():$(ids.giftBoxId).hide();}
$(ids.btnCloseId).observe('click',function(){win.close();});$(ids.messageId).observe('keyup',function(){$(ids.charCountId).update(1000-this.value.length);$(ids.btnSendId).disabled=(this.value.length===0);$(ids.flirtFormId).flirt_msg[$(ids.flirtFormId).flirt_msg.length-1].checked=true;});$(ids.messageId).observe('focus',function(){$(ids.flirtFormId).flirt_msg[3].checked=true;});};return function(context,continuationCallback){isTooltip=true;SD.User.fetch(context.sourceMember,renderTooltip.curry(context,continuationCallback));}}(),dialogAddToDates:function(user,onSuccess,e,continuationCallback){if(SD.Actions.isTooltipOn){this.inviteToDateTooltip(user,onSuccess,e,continuationCallback);return;}
var win=SD.UIController.standardPopup({title:'&nbsp;',top:80,width:720,draggable:false,template:SD.Window.newStyle,className:"generic-popup-container",onAfterClose:function(ev){continuationCallback&&continuationCallback({closedByUser:ev.memo.closedByUser});}});var messageBox=TEXTAREA();var send=function(){var params={other_memberid:user.uid,message:messageBox.value};SD.FlirtWink.Controller.date(user,params,function(result){var info;if(result.responseJSON){info=user.username+' has been invited to SpeedDate.'+'When you are both online at the same time, we\'ll connect you for a speed date!';if(onSuccess){onSuccess();}}else{info=user.username+' had already been invited to SpeedDate.';}
win.close();!SD.Recommendation.isActive()&&SD.UIController.infoMessage(info,3);});};var information='We\'ll notify you and connect you when you are both online.';var sendButton=A({'class':'large-button large-green'},SPAN({}).update('Invite to SpeedDate&trade;'));sendButton.onclick=send;$(win.getContent()).insert(DIV({'class':'datepop'},DIV({'class':'popup-left'},IMG({'src':user.image_url})),DIV({'class':'popup-header'}).update('Add '+user.username+' to Upcoming SpeedDates&trade;'),DIV({'class':'min-spacer'},''),DIV({'class':'popup-right'},DIV({'class':'popup-form'},P({'class':'textbox-descriptor'},information),P({'class':'textbox-descriptor-action'},'Add a message for ',SPAN({'class':'sd-date-request-username'},user.username),SPAN({'class':'optional'},' (Optional)')),messageBox,sendButton))));win.showCenter(false,100);if(!SD.Model.getMyself().is_premium){SD.Tracking.getAndSendTrackingObject(SD.Constants.paymentTrackingIds.DATE_BUTTON_DATING);}},dialogReportPhoto:function(user){var reportReasons=['Sexually Explicit','Under 18 years old','Profane Username','Cyberbullying/Harrassment','Scammer/Spammer/Advertising','Imposter/Fake User','User Not in Photo'];var domForm=null,domBtnReport=null,domMessage=null;var content='<div class="reportpop">\n'
+'    <p style="margin: 1em 0pt;">\n'
+'        Please report only if you believe this member should be banned from using SpeedDate. \n'
+'        If so, please select a reason below and we will promptly investigate and take appropriate action.\n'
+'    </p>\n'
+'    <p style="margin: 0pt; font-size: 16px;">Reason: </p>\n'
+'    <form class="lib-dialog-report-photo-form">\n'
+'        <table class="flirt-messages">\n'+
reportReasons.map(function(reason,index){return''
+'            <tr>\n'
+'                <td class="checkbox">\n'
+'                    <input type="radio" id="reportMsg-'+index+'" name="report_reason" value="'+reason+'">\n'
+'                </td>\n'
+'                <td>\n'
+'                    <label for="reportMsg-'+index+'">'+reason+'</label>\n'
+'                </td>\n'
+'            </tr>\n'}).join('')
+'             <tr>\n'
+'                <td class="checkbox">\n'
+'                    <input type="radio" id="reportMsgOther" class="sd-flirt-radio" name="report_reason" value="Other">\n'
+'                </td>\n'
+'                <td>\n'
+'                    <label for="reportMsgOther">Other</label>\n'
+'                    <br>\n'
+'                    <textarea class="input-field sd-flirt-input lib-dialog-report-photo-message" name="report_msg"></textarea>\n'
+'                </td>\n'
+'             </tr>\n'
+'        </table>\n'
+'        <div>\n'
+'            <input type="button" class="input-button lib-dialog-report-photo-submit" value="Report User" disabled="disabled">\n'
+'            <input type="button" class="input-button lib-dialog-report-photo-cancel" value="Cancel">\n'
+'         </div>\n'
+'    </form>\n'
+'</div>';var parseLibrary={'.lib-dialog-report-photo-submit':function(el,domRoot){domBtnReport=el;var _this=this;el.onclick=function(){var reportForm=$(domForm).serialize(true);SD.User.reportMember(user,reportForm.report_reason,reportForm.report_msg,'photo');_this.close();SD.UIController.infoMessage('Thank you. We will promptly investigate your report. '+'We value your membership and will do everything possible'+' to ensure that you have a great experience on SpeedDate.',3);}},'.lib-dialog-report-photo-cancel':function(el,domRoot){var _this=this;el.onclick=function(){_this.close();}},'.lib-dialog-report-photo-form':function(el,domRoot){domForm=el;},'.lib-dialog-report-photo-message':function(el,domRoot){domMessage=el;domMessage.onkeyup=function(){domBtnReport.disabled=this.value.blank();domForm.elements.report_reason[domForm.elements.report_reason.length-1].checked=!this.value.blank();}},'input[type="radio"]':function(el,domRoot){el.onclick=function(){domBtnReport.disabled=(this.id=='reportMsgOther')&&domMessage.value.blank();}}};return SD.UIController.standardPopup({title:'Report Member '+user.username,draggable:true,content:content,parseLibrary:parseLibrary}).showCenter(false,100);},inviteToDateTooltip:function(user,onSuccess,e,contCallback){var ids=SD.Utils.IdGenerator.generateCollection('mainSectionId','infoSectionId','messageBoxId','submitId');var information='Invite #{username} to SpeedDate and we\'ll let you know when #{username} comes online.';var html='<div style="padding:12px">'+'<div id="#{infoSectionId}" class="text section-top" style="display:none">Please wait ... </div>'+'<div id="#{mainSectionId}" class="section-top-base">'+'<div class="text">'+'<div>#{text}</div>'+'<div><textarea style="width:230px;height:40px" class="input-field label-on" id="#{messageBoxId}" spellcheck="false"'+' sdType="inner-label"'+' sdLabel="Add a message for #{username} (optional)" '+' sdClassName="label-on">Add a message for #{username} (optional)</textarea>'+'</div>'+'</div>'+'<div id="#{submitId}" class="small-green small-button tt-button" style="margin:10px 0 10px 32px;position:relative" >'+'<span>'+'<u>Invite To SpeedDate &raquo;</u>'+'</span>'+'</div>'+'</div>'+'</div>';var mergedHtml=html.interpolate(SD.Utils.mixin({text:information.interpolate({username:user.username}),username:user.username},ids));var successMessage=user.username+' has been invited to SpeedDate. When you are both online at the same time, we\'ll connect you for a speed date!';var errorMessage='<div style="color:red">'+user.username+' had already been invited to SpeedDate.</div>';var send=function(){var message=$(ids.messageBoxId).value.trim();if(message==''||message==$(ids.messageBoxId).getAttribute('sdLabel')){message=SD.Model.getMyself().username+" invited you on a Speeddate.";}
var params={other_memberid:user.uid,message:message};SD.FlirtWink.Controller.date(user,params,function(result){var domMainSection=$(ids.mainSectionId);var domInfoSection=$(ids.infoSectionId);domMainSection.hide();domInfoSection.show();if(result.responseJSON){domInfoSection.update(successMessage);onSuccess&&onSuccess();}else{domInfoSection.update(errorMessage);}});};var win=SD.TooltipDialog.create({refDom:e.srcElement||e.target||e.sdTarget,width:260,content:mergedHtml,onAfterOpen:function(){$(ids.submitId).onclick=send;}},contCallback);if(!SD.Model.getMyself().is_premium){SD.Tracking.getAndSendTrackingObject(SD.Constants.paymentTrackingIds.DATE_BUTTON_DATING);}}};SD.Dialogs.Types={DATE:'SD.Dialogs.Types.DATE'};
SD.UserFilters={};SD.UserFilters.UI={_user:null,_target:null,startText:"",pauseText:"",statusIndicators:null,startButton:null,startButtonSidebar:null,premiumBolt:null,buttonState:'running',state:'running',previousButtonState:null,startPauseQueue:[],allowDating:true,delayTimer:null,startSpeedDating:function(){this.allowDating&&SD.Event.fire(null,SD.UserFilters.UI.Events.START_SPEEDDATING);},delayStartSpeedDating:function(delayMin){clearTimeout(this.delayTimer);if(delayMin==-1){SD.UserFilters.UI.startSpeedDating();}else if(delayMin>0){this.delayTimer=SD.UserFilters.UI.startSpeedDating.bind(SD.UserFilters.UI).delay(delayMin*60);SD.Event.observe(null,SD.UserFilters.UI.Events.START_SPEEDDATING,function(){clearTmeout(this.delayTimer);}.bind(this));SD.Event.observe(null,SD.UserFilters.UI.Events.PAUSE_SPEEDDATING,function(){clearTmeout(this.delayTimer);}.bind(this));}},pauseSpeedDating:function(){SD.Event.fire(null,SD.UserFilters.UI.Events.PAUSE_SPEEDDATING);},delayStartSpeedDating:function(delayMin){if(delayMin==-1){SD.UserFilters.UI.startSpeedDating();}else if(delayMin>0){}else{}},prepare:function(){var minAgeSelector=$('min_age');var maxAgeSelector=$('max_age');var locationSelector=$('location');var filterNoPhoto=$('filter_no_photo');var _this=this;minAgeSelector.onchange=function(){_this.filterChanged(this)}
maxAgeSelector.onchange=function(){_this.filterChanged(this)}
locationSelector.onchange=function(){_this.filterChanged(this)}
filterNoPhoto.onchange=function(){_this.filterChanged(this)}
this.buttonState="running";this.statusIndicators=$$('.status-indicator');this.startButton=$('start-speeddating-button');},filterChanged:function(source){var user=SD.Model.getMyself();SD.log("filter changed!");var minAgeSelector=$('min_age');var maxAgeSelector=$('max_age');var locationSelector=$('location');if(minAgeSelector.value>maxAgeSelector.value){if(source==$(minAgeSelector)){maxAgeSelector.value=minAgeSelector.value;}else{minAgeSelector.value=maxAgeSelector.value;}}
var radius;if(isNaN(locationSelector.value)){radius=0;}else{radius=SD.UserFilters.UI.nearRadius(user,locationSelector.value);}
var filter_country=(locationSelector.value=="WW")?"WW":user.country;var filter_no_photo=$('filter_no_photo').checked||false;SD.Event.fire(null,SD.UserFilters.UI.Events.FILTER_CHANGED,{min_age:minAgeSelector.value,max_age:maxAgeSelector.value,radius:radius,filter_country:filter_country,filter_no_photo:filter_no_photo});},startPauseSpeedDating:function(){if(this.buttonState=="paused"){SD.UserFilters.UI.startSpeedDating();}else{SD.UserFilters.UI.pauseSpeedDating();}},saveStateAndPause:function(){this.startPauseQueue.push('save');if(this.startPauseQueue[this.startPauseQueue.length-2]!='save'){this.previousButtonState=this.buttonState;if(SD.XMPP.getFlash()){SD.UserFilters.UI.pauseSpeedDating();}}},restorePreviousStateAndResume:function(){this.startPauseQueue.push('resume');if(this.startPauseQueue[this.startPauseQueue.length-2]=='resume'||(this.startPauseQueue[this.startPauseQueue.length-2]=='save'&&this.startPauseQueue[this.startPauseQueue.length-3]!='save')){if(this.previousButtonState){if(this.previousButtonState=="running"){SD.UserFilters.UI.startSpeedDating();}else{SD.UserFilters.UI.pauseSpeedDating();}
this.startPauseQueue=[];this.previousButtonState=null;}}},onStartDating:function(event){if(this.allowDating==false){return;}
this.setDatingOn();},setDatingOn:function(){this.buttonState="running";this.state="running";this.statusIndicators.each(function(el){el.src=SD.Config.imageDir+"dot-dot-dot-heart.gif";});this.setWaitingCount(0);SD.Cookie.create('pauseSpeeddating',0);},setDatingOff:function(){this.buttonState="paused";this.state="paused";this.statusIndicators&&this.statusIndicators.each(function(el){el.src=SD.Config.imageDir+"dot-dot-dot-heart-static.gif";});SD.Cookie.create('pauseSpeeddating',1);},onPauseDating:function(event){this.setDatingOff();},onWaitingTimeChanged:function(event){this.setWaitingCount(event.memo.count);},setWaitingCount:function(count){if(count){if($('upcoming-dates-sidebar2556')){$('upcoming-dates-sidebar2556').innerHTML=count;}else{$('upcoming-dates')&&($('upcoming-dates').innerHTML=count);$('upcoming-dates-sidebar')&&($('upcoming-dates-sidebar').innerHTML=count);$('upcoming-dates-sidebar-container')&&$('upcoming-dates-sidebar-container').show();$('upcoming-dates')&&$('upcoming-dates').show();$('upcoming-text')&&$('upcoming-text').show();$('view-all')&&$('view-all').show();}}else{if($('upcoming-dates-sidebar2556')){$('upcoming-dates-sidebar2556').innerHTML="";}else{$('upcoming-dates')&&$('upcoming-dates').hide();$('upcoming-dates-sidebar-container')&&$('upcoming-dates-sidebar-container').hide();$('upcoming-text')&&$('upcoming-text').hide();$('view-all')&&$('view-all').hide();}}},initialize:function(target,user){this.prepare();SD.Event.observe(null,SD.UserFilters.UI.Events.START_SPEEDDATING,this.onStartDating.bind(this));SD.Event.observe(null,SD.UserFilters.UI.Events.PAUSE_SPEEDDATING,this.onPauseDating.bind(this));SD.Event.observe(null,SD.SpeedDateList.Events.UPCOMING_DATES_CHANGED,this.onWaitingTimeChanged.bind(this));},nearRadius:function(user,limit){if(user.last_match_radius){if(user.last_match_radius*1.3<limit){return user.last_match_radius*1.3;}}
return limit;},getDatingFilterValues:function(){return{min_age:$('min_age').value,max_age:$('max_age').value,location:$('location').value,filter_no_photo:$('filter_no_photo').value}},setDatingFilterValues:function(values){$('min_age').value=values.min_age;$('max_age').value=values.max_age;$('location').value=values.location;$('filter_no_photo').checked=values.filter_no_photo;this.filterChanged($('min_age'));},Events:{FILTER_CHANGED:"filter:changed",START_SPEEDDATING:"filter:startdating",PAUSE_SPEEDDATING:"filter:pausedating"}};
SD.Matchmaker={successfulHost:null,_waitingRequestTimes:null,_waitingRequestsLongerLimit:null,REQUEST_LIMIT_PER_MINUTE:3,DEFAULT_REQUEST_LIMIT_PER_MINUTE:3,_decrementedLimit:false,matchMember:function(user,limit){if(SD.Matchmaker._waitingRequestTimes.getValue(true)>=SD.Matchmaker.REQUEST_LIMIT_PER_MINUTE){if(!SD.Matchmaker._decrementedLimit){SD.Matchmaker.REQUEST_LIMIT_PER_MINUTE=Math.max(1,SD.Matchmaker.REQUEST_LIMIT_PER_MINUTE-1);SD.Matchmaker._decrementedLimit=true;}
return false;}
SD.Matchmaker._decrementedLimit=false;limit=limit||30;var parameters=SD.User.makeParametersFromUser(user);parameters.exclude=SD.User.getPastDates(user);parameters.prefer=SD.User.getWantedDates(user);parameters.limit=limit;var processMatches=function(result){var users=result.collect(function(u){var romeo=SD.User.get(u.uid,u.username,u.chat_id);romeo.token=u.token;romeo.category=u.category;return romeo;});SD.Event.fire(user,SD.Matchmaker.Events.MATCHES_FOUND,{matches:users});if(users.length){SD.Matchmaker._waitingRequestTimes.reset();SD.Matchmaker.REQUEST_LIMIT_PER_MINUTE=SD.Matchmaker.DEFAULT_REQUEST_LIMIT_PER_MINUTE;var last=users[users.length-1];SD.User.fetch(last,function(){user.last_match_radius=SD.User.distanceBetweenUsers(user,last);});}};var getSuccessfulHost=function(){return(SD.Matchmaker.successfulHost||SD.Config.mmsHosts[Math.floor(Math.random()*SD.Config.mmsHosts.length)]);};var url=getSuccessfulHost()+"/match";SD.Matchmaker._waitingRequestTimes.increment();SD.Date.callAjax(url,parameters,"POST",processMatches);},registrationBots:{},initialized:false,startRegistering:function(user){SD.Matchmaker.registrationBots[user.uid]=new SD.Matchmaker.RegistrationBot(user);if(!SD.Matchmaker.initialized){SD.Event.observe(null,SD.User.Events.USER_CHANGED,function(event){SD.Matchmaker._waitingRequestTimes.reset();SD.Matchmaker.restartRegistering(event.memo.user);});SD.Matchmaker.initialized=true;SD.Matchmaker._waitingRequestTimes=new SD.Cookie.CounterWithTimeout("mms_requests",1);}},restartRegistering:function(user){if(SD.Matchmaker.registrationBots[user.uid]){SD.Matchmaker.stopRegistering(user);SD.Matchmaker.startRegistering(user);}},stopRegistering:function(user){var bot=SD.Matchmaker.registrationBots[user.uid];if(bot){bot.stop();delete SD.Matchmaker.registrationBots[user.uid];}},RegistrationBot:function(user){var hostIndex=Math.floor(Math.random()*SD.Config.mmsRegistries.length);var getNextHost=function(){var rv=SD.Config.mmsRegistries[hostIndex];hostIndex=(hostIndex+1)%SD.Config.mmsRegistries.length;return rv;};var doRegister=function(){var parameters=SD.User.makeParametersFromUser(user);var host=getNextHost();var url=host+"/register";SD.log("registering with "+url);SD.Date.callAjax(url,parameters,"POST",function(){SD.log("registered successfully");if(SD.Config.mmsHosts.indexOf(host)>=0){SD.Matchmaker.successfulHost=host;}});};for(var i=0;i<SD.Config.mmsRegistries.length;i++){doRegister();}
var pe=new PeriodicalExecuter(doRegister,(60*12)/SD.Config.mmsRegistries.length);var stop=function(){pe.stop();};this.stop=stop;},Events:{MATCHES_FOUND:"matchmaker:matchesfound"}};
SD.XMPP={_username:"",_password:"",_connected:false,_loggedIn:false,_connType:"standard",_resourceName:"xiff",_mobileResourceName:"mobile",_isReady:false,_createIQCalls:0,_stropheConn:null,_flashApp:null,Events:{INIT:"xmpp:init",CONNECT:"xmpp:connect",DISCONNECT:"xmpp:disconnect",LOGIN:"xmpp:login",LOGIN_FAILURE:"xmpp:login_fail",ERROR:"xmpp:error",DATA:"xmpp:data",MESSAGE:"xmpp:message",ON_INCOMING_NODE:"xmpp:on_incoming_node"},debug:function(txt){if(SD.XMPP.textarea){SD.XMPP.textarea.value+=txt+"\n";}
SD.log(">XMPP>"+txt);},setDebugTextarea:function(textarea){SD.XMPP.textarea=textarea;},getFlash:function(){var flash=FABridge.proxy;if(!flash){SD.log("can not reach flash through FABridge");}
return flash;},getBridge:function(){var flexBridge=SD.XMPP.getFlash().root().getXiffGateway();if(!flexBridge){SD.log("can not reach application through FABridge");}
return flexBridge;},getXMPPConnection:function(){var conn=SD.XMPP.getBridge().getXiff();if(!conn){SD.log("can not reach connection (xiff) which is(should be) located inside flex application");}
return conn;},getRoster:function(){return SD.XMPP.getBridge().getRoster();},createJID:function(jidString){var jid=SD.XMPP.getBridge().createJID(jidString);return jid;},jidToString:function(jid){return jid.toBareJID();},createIQ:function(recipient,iqType,iqID,iqCallback,iqCallbackScope,iqCallbackFunc){this._createIQCalls++;return SD.XMPP.getBridge().createIQ(recipient,iqType,iqID,iqCallback,iqCallbackScope,iqCallbackFunc);},xmlNodetoString:function(xmlNode){return SD.XMPP.getBridge().xmlNodetoString(xmlNode);},sendXMLString:function(xmlString){return SD.XMPP.getBridge().sendXMLString(xmlString);},sendXMPPString:function(xmppString){SD.XMPP._flashApp.sendXMPPString(xmppString);},createXMLNode:function(type,value){return SD.XMPP.getBridge().createXMLNode(type,value);},sendIQ:function(iqObject){SD.XMPP.getXMPPConnection().send(iqObject);},sendIVoted:function(receiverString){receiverString+="/"+SD.XMPP._resourceName;SD.XMPP.debug("sending i voted to:"+receiverString);SD.XMPP.getBridge().sendIVoted(receiverString);},sendLog:function(receiptString,log){SD.log("sending my screen to "+receiptString);var logXML="<iq to=\""+receiptString+"\" from=\""+
SD.Model.getMyself().chat_id+"/xiff"+"\" type=\"set\">"+"<speeddate-log action=\"show\" txt=\""+log+"\"/>"+"</iq>";SD.log(logXML);SD.XMPP.sendXMLString(logXML);},getLog:function(){var logXML="<iq to=\""+SD.DatingController._jingleOtherJID+"\" from = \""+
SD.Model.getMyself().chat_id+"/xiff"+"\" type=\"set\">"+"<speeddate-log action=\"give\" />"+"</iq>";SD.log("sending "+logXML);SD.XMPP.sendXMLString(logXML);},init:function(flashId){SD.XMPP.debug("onINIT");SD.XMPP._flashApp=$(flashId);SD.XMPP.initConnection();SD.XMPP._connected=false;SD.XMPP._loggedIn=false;SD.XMPP.connectionChecker.delay(15,15,false);SD.XMPP.debug("fired init");SD.Event.observe(null,SD.XMPP.Events.DATA,SD.XMPP.onData.bind(this));},onData:function(ev){var data=ev.memo;if(!data||!data.getFirstChild){return;}
var node=data.getFirstChild();while(node&&node.getFirstChild){SD.XMPP.onIncomingNode(node);node=node.getNextSibling();}},onIncomingNode:function(node){if(node.getNodeType()!=1){return;}
var iq=SD.XMPP.createIQ(null,null,null,null,null,null);if(!iq.deserialize(node)){return;}
SD.Event.fire(null,SD.XMPP.Events.ON_INCOMING_NODE,{node:node});},onErrorDump:function(){return{isConnected:SD.XMPP.isConnected(),isLoggedIn:SD.XMPP.isLoggedIn(),username:SD.XMPP._username,password:SD.XMPP._password};},connectionChecker:function(time,isDisconnected){SD.XMPP.debug("connectionChecker");if(time===-1){if(SD.XMPP.isLoggedIn()){SD.XMPP.connectionChecker.delay(15,15,isDisconnected);}else if(SD.XMPP.isConnected()){SD.XMPP.debug("probably logged in elsewhere");SD.XMPP.connectionChecker.delay(15,15,isDisconnected);return;}else{if(SD.Model.getMyself().category!=="B"){SD.XMPP.debug("probably connection lost, trying outputting");SD.ExperimentManager.recordOutput('XMPPDisconnected',1,1);isDisconnected=true;}
SD.XMPP.connectionChecker.delay(7,3,isDisconnected);}}else{SD.XMPP.debug("checking connection");var pingStanza=$iq({type:'get'}).c('ping',{xmlns:'urn:xmpp:ping'});SD.XMPP.getStropheConnection().sendIQ(pingStanza,function(iq){SD.XMPP.debug("still connected");if(isDisconnected){SD.XMPP.debug("reconnected");SD.ExperimentManager.recordOutput('XMPPReconnected',1,1);isDisconnected=false;}
SD.XMPP.connectionChecker.delay(15,15,isDisconnected);},function(iq){SD.XMPP.debug("ping failed, cause = "+(iq===null?'timeout':iq));if(time>3.75){SD.XMPP.debug("retry pinging in "+time/2+"secs");SD.XMPP.connectionChecker.delay(time/2,time/2,isDisconnected);}else{SD.XMPP.debug("retry connecting now");SD.XMPP.disconnect();SD.XMPP.reconnect();SD.XMPP.connectionChecker.delay(5,-1,isDisconnected);}},3000);}},initConnection:function(){var conn=SD.XMPP.getXMPPConnection();conn.addEventListener("connection",SD.XMPP.onConnectSuccess);conn.addEventListener("error",SD.XMPP.onError);conn.addEventListener("outgoingData",SD.XMPP.onOutgoingData.bind(this));SD.XMPP.getBridge().setIncomingStringListener('SD.XMPP.onIncomingString');conn.addEventListener("login",SD.XMPP.onLogin);conn.addEventListener("message",SD.XMPP.onMessage);conn.setResource(SD.XMPP._resourceName);this._stropheConn=new Strophe.Connection("");SD.XMPP.debug("connection initialized");},getStropheConnection:function(){return this._stropheConn;},onMessage:function(msg){SD.Event.fire(null,SD.XMPP.Events.MESSAGE,msg);},onConnectSuccess:function(flexEvent){SD.Time.xmppConnected();SD.XMPP._connected=true;SD.XMPP._stropheConn.authenticated=true;SD.Event.fire(null,SD.XMPP.Events.CONNECT);},onError:function(flexEvent){if(!flexEvent||!flexEvent.getErrorMessage){return;}
SD.XMPP.debug("onError:"+flexEvent.getErrorMessage());if(flexEvent.getErrorMessage()=="Unknown Error"){return;}else if(flexEvent.getErrorMessage()=="Unexpected Request"){SD.Event.fire(null,SD.XMPP.Events.LOGIN_FAILURE);return;}
SD.Event.fire(null,SD.XMPP.Events.ERROR,flexEvent.getErrorMessage());SD.XMPP._loggedIn=SD.XMPP.getXMPPConnection().isLoggedIn();},onOutgoingData:function(flexEvent){},onIncomingString:function(dataStr){var xml=dataStr.toXMLDoc();if(xml.nodeType==7){return;}
this._stropheConn._dataRecv({getResponse:function(){return xml;}});},onDisconnect:function(flexEvent){SD.XMPP._loggedIn=false;SD.XMPP._connected=false;SD.Event.fire(null,SD.XMPP.Events.DISCONNECT);SD.XMPP.debug("disconnected, trying to reconnect");SD.XMPP.reconnect();},onLogin:function(flexEvent){SD.XMPP._loggedIn=true;SD.XMPP.debug("logged in!");SD.Event.fire(null,SD.XMPP.Events.LOGIN);},connect:function(username,password){SD.XMPP._username=username;SD.XMPP._password=password;var conn=SD.XMPP.getXMPPConnection();conn.setUsername(username);conn.setPassword(password);conn.setPort(5222);conn.setServer(SD.Config.XMPPServer.serverURL);conn.connect(SD.XMPP._connType);this._stropheConn.jid=this._username+"@"+SD.Config.XMPPServer.serverURL+"/"+this._resourceName;SD.XMPP.debug("connecting...");},_aggresiveConnectionControl:function(){if(!SD.XMPP.isLoggedIn()){SD.XMPP.disconnect();SD.XMPP.reconnect();}},reconnect:function(){SD.XMPP._loggedIn=false;SD.XMPP._connected=false;if(!SD.XMPP._username||!SD.XMPP._password){SD.log("can not reconnect without pre-given username&password");return;}
SD.XMPP.connect(SD.XMPP._username,SD.XMPP._password);},isConnected:function(){return SD.XMPP._connected;},isLoggedIn:function(){return SD.XMPP._loggedIn;},disconnect:function(){SD.XMPP.getXMPPConnection().disconnect();},goAway:function(){SD.log("going AWAY");var pres=$pres().cnode(Strophe.xmlElement('show','away'));SD.XMPP.sendXMLString(pres.toString());},goOnline:function(){SD.log("going ONLINE");var pres=$pres();SD.XMPP.sendXMLString(pres.toString());},sendDirectPresence:function(receiver){if(!receiver||receiver.uid==SD.Model.getMyself().uid||(receiver.isFacebookUser&&receiver.isFacebookUser())){return;}
var pres=$pres({to:receiver.chat_id,type:'available'});var stropheConnection=SD.XMPP.getStropheConnection();stropheConnection&&stropheConnection.send(pres);},switchXMPPServer:function(user_ejabberd){SD.XMPP.disconnect();SD.XMPP.reconnect();SD.Matchmaker.restartRegistering(SD.Model.getMyself());}};SD.Error.registerErrorDumper("SD.XMPP",SD.XMPP.onErrorDump.bind(SD.XMPP));
SD.FBXMPP={_server:"chat.facebook.com",_resourceName:"speeddate",_stropheConn:null,_connected:false,_loggedIn:false,debug:function(){},getBridge:function(){return FABridge.proxy.root().getFbGateway();},init:function(){this.getBridge().setIncomingStringListener('SD.FBXMPP.onIncomingString');SD.UI.FBChatToggles.initDeferred();},sendXMPPString:function(xmppString){SD.XMPP._flashApp.sendXMPPString(xmppString,"fb");},onIncomingString:function(str){SD.FBXMPP.debug("FB",str);},initConnection:function(){FABridge.proxy.root().setFBSessionKey(FB._session.session_key);FABridge.proxy.root().initFBXMPP();var conn=this.getXMPPConnection();conn.addEventListener("connection",this.onConnectSuccess.bind(this));conn.addEventListener("error",this.onError.bind(this));this.getBridge().setIncomingStringListener('SD.FBXMPP.onIncomingString');conn.addEventListener("login",this.onLogin.bind(this));conn.addEventListener("disconnection",this.onDisconnect.bind(this));conn.setResource(this._resourceName);this._stropheConn=new Strophe.Connection("",SD.FBXMPP.sendXMPPString);this.debug("connection initialized");SD.FBChat.init(this._stropheConn);},onIncomingString:function(dataStr){this.debug("IN",dataStr);var xml=dataStr.toXMLDoc();if(xml.nodeType==7){return;}
this._stropheConn._dataRecv({getResponse:function(){return xml;}});},necessaryPermissions:function(){var permissions_str=SD.Config.defaultFbPermissions+",xmpp_login";return permissions_str.split(',').uniq();},hasAllPermissions:function(){var permissions=this.necessaryPermissions();var has_all_permissions=true;permissions.each(function(p){has_all_permissions=SD.FbConnect.hasPermission(p);if(!has_all_permissions){throw $break;}});return has_all_permissions;},connect:function(){var connect=function(){this.initConnection();var conn=this.getXMPPConnection();conn.setPort(5222);conn.setServer(this._server);conn.connect("standard");conn.setUsername("fbuser");this._stropheConn.jid="-"+FB._session['uid']+"@chat.facebook.com";this.debug("connecting...");SD.Event.fire(null,this.Events.CONNECTING);}.bind(this);if(FB.getAuthResponse()&&this.hasAllPermissions()){connect();}else{SD.XConnect.openFacebookAuthenticate(function(result){if(!result){this.onDisconnect();return;}
connect();}.bind(this),{permissions:this.necessaryPermissions().join(',')});}},connectIfHavePermissionsAndSession:function(){},disconnect:function(){SD.Event.fire(null,this.Events.DISCONNECTING);conn=this.getXMPPConnection();conn.disconnect();this._stropheConn.authenticated=false;},onDisconnect:function(){this._connected=false;this._loggedIn=false;SD.Event.fire(null,this.Events.LOGOUT);},getStropheConnection:function(){return this._stropheConn;},getXMPPConnection:function(){var conn=this.getBridge().getXiff();if(!conn){console.log("can not reach connection (xiff) which is(should be) located inside flex application");}
return conn;},onConnectSuccess:function(e){this.debug("connect suggess",e);this._connected=true;this._stropheConn.authenticated=true;},onError:function(e){this.debug("on error",e);this.debug(e.getErrorMessage());},onLogin:function(e){this.debug("on login",e);this._loggedIn=true;SD.Event.fire(null,this.Events.LOGIN,{});SD.ExperimentManager.recordOutput('ConnectedFacebookChat',1,1);},isLoggedIn:function(){return this._loggedIn;},Events:{LOGIN:"sd.fbxmpp:login",LOGOUT:"sd.fbxmpp:logout",CONNECTING:"sd.fbxmpp:connecting",DISCONNECTING:"sd.fbxmpp:disconnecting"}};
SD.FBChat={_conn:null,_presences:{},_inviteUrl:"http://speeddate.com",friendStore:null,init:function(conn){this._conn=conn;this._conn.addHandler(this._onMessage.bind(this),null,'message','chat');this._conn.addHandler(this._onPresence.bind(this),null,'presence');this._conn.addHandler(this._onRoster.bind(this),Strophe.NS.ROSTER);SD.Event.observe(null,this.Events.INVITE_FRIEND,this._onInviteFriend.bind(this));SD.Event.observe(null,SD.FBXMPP.Events.LOGOUT,this._onLogout.bind(this));if(SD.FBXMPP.isLoggedIn()){this._loadRoster();}
SD.Event.observe(null,this.Events.USER_AVAILABLE,this._onFriendOnline.bind(this));SD.Event.observe(null,this.Events.USER_UNAVAILABLE,this._onFriendOffline.bind(this));},setInviteUrl:function(url){this._inviteUrl=url;},_onInviteFriend:function(e){var friend=e.memo.user;var msg=e.memo.msg;this.inviteFriend(friend,msg);},inviteFriend:function(friend,message){message=message||"Join SpeedDate to connect with singles instantly! "+this._inviteUrl;SD.ChatMsgListener.sendMessage(friend,message);SD.ExperimentManager.recordOutput('InvitedFacebookFriendViaChat',1,1);},_onMessage:function(msg){try{var otherJid=msg.getAttribute('from');var resource=Strophe.getResourceFromJid(otherJid);var sender=SD.User.getByFBChatID(otherJid);if(SD.BuddyList.Controller.isBuddyBlocked(sender)){return true;}
SD.User.fetch(sender,function(sender){if(!sender.age||sender.age<18){return;}
if(resource){sender.xmpp_resource=resource;}
Strophe.forEachChild(msg,null,function(e){var tagName=e.tagName.toLowerCase();switch(tagName){case'composing':SD.Event.fire(null,this.Events.USER_TYPING,{user:sender});break;case'paused':SD.Event.fire(null,this.Events.USER_PAUSED_TYPING,{user:sender});break;case'body':var to=msg.getAttribute('to');var receiver=SD.User.getByFBChatID(to);var text=e.textContent||e.text;if(receiver&&sender&&text&&text.trim().length){SD.Event.fire(null,this.Events.NEW_MESSAGE,{sender:sender,receiver:receiver,text:text.trim()});}}}.bind(this));}.bind(this));}catch(e){}
return true;},_onPresence:function(pres){try{var otherJid=pres.getAttribute('from');var type=pres.getAttribute('type');var sender=SD.User.getByFBChatID(otherJid);if(!sender){return true;}
if(!type||type=="available"){SD.User.fetch(sender,function(sender){if(!sender.age||sender.age<18){return;}
SD.BuddyList.Controller.addBuddyId(sender.uid);this._presences[sender.uid]=true;SD.Event.fire(null,this.Events.USER_AVAILABLE,{user:sender});}.bind(this));}else if(type=="unavailable"){this._presences[sender.uid]=false;SD.Event.fire(null,this.Events.USER_UNAVAILABLE,{user:sender});}}catch(e){}
return true;},_onLogout:function(){for(var uid in this._presences){if(this._presences.hasOwnProperty(uid)&&this._presences[uid]==true){var user=SD.User.get(uid);this._presences[uid]=false;SD.Event.fire(null,this.Events.USER_UNAVAILABLE,{user:user});}}},_loadRoster:function(){var rosterIQ=$iq({type:'get'}).c('query',{xmlns:Strophe.NS.ROSTER});this._conn.sendIQ(rosterIQ,this._onRoster.bind(this));},_onRoster:function(rosterIQ){return;Strophe.forEachChild(rosterIQ,'query',function(query){Strophe.forEachChild(query,'item',function(item){console.log(item);var otherJid=item.getAttribute('jid');var user=SD.User.getByFBChatID(otherJid);user.username=item.getAttribute('name');}.bind(this));}.bind(this));return true;},_onFriendOffline:function(e){this.friendStore.remove(e.memo.user);},_onFriendOnline:function(e){this.friendStore.add(e.memo.user);},Events:{USER_TYPING:"sd.fbchat:user_typing",USER_PAUSED_TYPING:"sd.fbchat:user_paused_typing",NEW_MESSAGE:"sd.fbchat:new_message",INVITE_FRIEND:"sd.fbchat:invite_friend",USER_AVAILABLE:"sd.fbchat:user_available",USER_UNAVAILABLE:"sd.fbchat:user_unavailable"}};SD.FBChat.friendStore=new SD.Store.BuddiesClass({idField:'uid'});
if(typeof SD.BuddyList=='undefined'){SD.BuddyList={};};SD.BuddyList.Controller=new function(){var _aOnlineBuddies=[];var _aAllBuddyIds=[];var _oRoaster=null;var _hBlocked=$H({});var onlineCheckInterval=30;function onUserBlocked(user){if(_hBlocked.get(user.uid)!=true){SD.BuddyList.Controller.blockBuddy(user);var memo={user:user};SD.Event.fire(null,SD.BuddyList.Events.USER_BLOCKED,memo);}};function onUserUnblocked(user){_hBlocked.unset(user.uid);SD.BuddyList.Controller.fetchAddBuddy(user);};function onUserDeleted(user){var memo={user:user};SD.Event.fire(null,SD.BuddyList.Events.USER_REMOVED,memo);};this.bViewInitialized=false;this.init=function(aInitialBuddies,aBlockedBuddies){aBlockedBuddies.each(function(uid){SD.BuddyList.Controller.blockBuddy(uid);});aInitialBuddies.each(function(oBuddy){SD.BuddyList.Controller.addBuddy(oBuddy,true);});SD.Event.observe(null,SD.BuddyList.Events.USER_BLOCK_CONFIRMED,function(e){onUserBlocked(e.memo.user);});SD.Event.observe(null,SD.BuddyList.Events.USER_UNBLOCK_CONFIRMED,function(e){onUserUnblocked(e.memo.user);});SD.Event.observe(null,SD.BuddyList.Events.USER_DELETE_CONFIRMED,function(e){onUserDeleted(e.memo.user);});SD.Event.observe(null,SD.BuddyList.Events.USER_DELETE_CONFIRMED,function(e){onUserDeleted(e.memo.user);});SD.Event.observe(null,SD.User.Events.USER_ONLINE,this.onUserOnline.bind(this));SD.Event.observe(null,SD.User.Events.USER_OFFLINE,this.onUserOffline.bind(this));};this.onUserOnline=function(e){var user=e.memo.user;if(!user)return;var buddy=this.getBuddyById(user.uid);if(buddy){buddy.online=true;SD.Event.fireDeferred(null,SD.BuddyList.Events.BUDDY_COUNT_CHANGE,{'countOnline':SD.BuddyList.Controller.getOnlineCount(),'countTotal':SD.BuddyList.Controller.getTotalCount()});}else{this.fetchAddBuddy(user);}};this.onUserOffline=function(e){var user=e.memo.user;if(!user)return;var buddy=this.getBuddyById(user.uid);if(buddy){buddy.online=false;SD.Event.fireDeferred(null,SD.BuddyList.Events.BUDDY_COUNT_CHANGE,{'countOnline':SD.BuddyList.Controller.getOnlineCount(),'countTotal':SD.BuddyList.Controller.getTotalCount()});}};this.requestBuddyBlock=function(oBuddy){SD.Event.fire(null,SD.UIController.Events.BLOCK_BUDDY_REQUESTED,{user:oBuddy});};this.getBuddyById=function(nUid){if(nUid===undefined)return;nUid=parseInt(nUid);var oBuddy=null;_aOnlineBuddies.each(function(oBuddyParam){if(oBuddyParam.uid==nUid){oBuddy=oBuddyParam;throw $break;}});return oBuddy;};this.isBuddy=function(user){if(!user)return false;var bIsBuddy=false;_aOnlineBuddies.each(function(oBuddy){if(oBuddy.uid==user.uid){bIsBuddy=true;throw $break;}});return bIsBuddy;};this.isBuddyBlocked=function(user){return _hBlocked.get(user.uid)||false;};this.fetchAddBuddy=function(oUser){if(oUser&&!this.isBuddy(oUser)){if(typeof oUser.relation!='undefined'&&typeof oUser.relation.permissions!='undefined'){SD.BuddyList.Controller.addBuddy(oUser);}else{SD.User.fetch({uid:oUser.uid},function(oFetchedUser){SD.BuddyList.Controller.addBuddy(oFetchedUser);});}}};this.addBuddyId=function(uid){if(!uid)return;if(!_aAllBuddyIds.include(uid)){_aAllBuddyIds.push(uid);SD.Event.fireDeferred(null,SD.BuddyList.Events.BUDDY_COUNT_CHANGE,{'countOnline':SD.BuddyList.Controller.getOnlineCount(),'countTotal':SD.BuddyList.Controller.getTotalCount()});}}
this.addBuddy=function(oUser,bQuiet){if(!oUser)return;if(oUser.uid==SD.Model.getMyself().uid){return;}
if(!this.isBuddyBlocked(oUser)&&!this.isBuddy(oUser)){oUser.square_image=new Image();oUser.square_image.src=oUser.square_image_url;_aOnlineBuddies.push(oUser);if(!bQuiet){SD.Event.fireDeferred(null,SD.BuddyList.Events.USER_ADDED,{user:oUser});}
SD.Event.fireDeferred(null,SD.BuddyList.Events.BUDDY_COUNT_CHANGE,{'countOnline':SD.BuddyList.Controller.getOnlineCount(),'countTotal':SD.BuddyList.Controller.getTotalCount()});}};this.removeBuddy=function(user){if(!user)return;var nRemoveIndex=-1;for(var i=0;i<_aOnlineBuddies.length;i++){if(_aOnlineBuddies[i].uid==user.uid){nRemoveIndex=i;break;}}
if(nRemoveIndex>-1){_aOnlineBuddies.splice(nRemoveIndex,1);}
SD.Event.fireDeferred(null,SD.BuddyList.Events.BUDDY_COUNT_CHANGE,{'countOnline':SD.BuddyList.Controller.getOnlineCount(),'countTotal':SD.BuddyList.Controller.getTotalCount()});};this.blockBuddy=function(user){if(!user){return;}
if(typeof user.uid!='undefined'){_hBlocked.set(user.uid,true);}else{_hBlocked.set(user,true);}};this.getOnlineCount=function(){var nOnlineCount=0;_aOnlineBuddies.each(function(oBuddy){if(oBuddy.online){nOnlineCount++;}});return nOnlineCount;};this.getTotalCount=function(){return _aAllBuddyIds.length;};this.getOnlineBuddies=function(){return _aOnlineBuddies;};this.getBlockedMembers=function(){return _hBlocked;};};SD.BuddyList.Events={BUDDY_EXPAND:'sdbuddylist:buddyexpand',BUDDY_EXPANDED:'sdbuddylist:buddyexpanded',BUDDY_COLLAPSE:'sdbuddylist:buddycollapse',BUDDY_COLLAPSED:'sdbuddylist:buddycollapseed',BUDDY_COUNT_CHANGE:'sdbuddylist:buddycountchange',BUDDIES_REGISTERED:'sdbuddylist:buddiesregistered',USER_ADDED:'buddylist:userAdded',USER_REMOVED:'buddylist:userRemoved',USER_BLOCKED:'buddylist:userBlocked',USER_PRESENCE_UPDATED:'buddylist:userPresenceUpdated',USER_BLOCK_CONFIRMED:'buddylist:userBlockConfirmed',USER_UNBLOCK_CONFIRMED:'buddylist:userUnblockConfirmed',USER_DELETE_CONFIRMED:'buddylist:userDeleteConfirmed'};
if(typeof SD.BuddyList=='undefined'){SD.BuddyList={};}
SD.BuddyList.View=new function(){var _oBuddyListWrapper=null;var _oExpandedBuddy=null;var _oBuddyListElement=null;var _hBuddyElements=$H({});var _hBuddyHeadElements=$H({});var _hBuddyBodyElements=$H({});var isVisible=true;function getBuddyHead(oBuddy,bOnline){var oBuddyHeadElement=null;var oBuddyBodyElement=null;var oBuddyElement=null;var sCityName=(oBuddy.city_name||'').excerpt(17);var username=oBuddy.username.ucfirst().excerpt(11);oBuddyElement=LI({'class':'buddy-view'+(bOnline?' buddy-online':''),'style':'display:none','id':'buddylist-buddy-'+oBuddy.uid},oBuddyHeadElement=DIV({'class':'head'},IMG({'class':'buddy-image fake-link','src':oBuddy.square_image_url,'sdusername':username,'sduid':oBuddy.uid,sdtype:'profile',sdSource:'connections',sdTTOrientation:'bl'}),DIV({'class':'buddy-list-online-indicator'}),DIV({'class':'buddy-name'},(oBuddy.isFacebookUser&&oBuddy.isFacebookUser()?IMG({"class":"little-fb-icon"}):""),(oBuddy.isFacebookUser&&oBuddy.isFacebookUser()?A({'href':'javascript:void(0)','sdusername':username,'sduid':oBuddy.uid,'sdtype':'profile','sdSource':'connections','sdType':'chat',sdTTOrientation:'bl'},username):A({'href':'javascript:void(0)','sdusername':username,'sduid':oBuddy.uid,'sdtype':'profile','sdSource':'connections',sdTTOrientation:'bl'},username)),(oBuddy.age?', '+oBuddy.age:""),BR(),(sCityName||"")),DIV({'class':'link link-chat fake-link','sdType':'chat','sdSource':'connections','sdUid':oBuddy.uid,'sdUsername':username,'sdOnline':'true','sdimonline':''
+oBuddy.im_online,sdTTOrientation:'bl'},'Chat'),BR({'clear':'all'})),oBuddyBodyElement=DIV({'class':'body','style':'display: none'},''));oBuddyElement.buddyUid=oBuddy.uid;SD.BuddyList.View.registerIOParamsForUserId({'buddyElement':oBuddyElement,'buddyHeadElement':oBuddyHeadElement,'buddyBodyElement':oBuddyBodyElement,'getBuddy':oBuddy.uid});return oBuddyElement;};function assureGetBuddyfunction(fGetBuddy){if(typeof fGetBuddy!='function'){var sUserId=fGetBuddy;fGetBuddy=function(){return SD.BuddyList.Controller.getBuddyById(sUserId);}}
return fGetBuddy;};function removeBuddyElement(oBuddy,fAfterFinish){var oBuddyElement=_hBuddyElements.get(oBuddy.uid);if(!oBuddyElement){fAfterFinish&&fAfterFinish();return;}
try{Effect.Fade(oBuddyElement,{afterFinish:function(){try{_oBuddyListElement.removeChild(oBuddyElement);}catch(e){}
adjustHeight.defer();SD.Tooltip.hide();if(fAfterFinish){fAfterFinish();}}});}catch(error){}};this.removeBuddyElement=removeBuddyElement;function addBuddyElement(oBuddy,bOnline){if(!bOnline){return;}
if(_hBuddyElements.get(oBuddy.uid)){return;}
oBuddy.online=bOnline;var oBuddyElement=getBuddyHead(oBuddy,bOnline);var bInserted=false;var aElements=_oBuddyListElement.select('li');for(var i=0;i<aElements.length;i++){var oNode=aElements[i];if(!oNode.buddyUid){continue;}
var oNodeBuddy=SD.BuddyList.Controller.getBuddyById(oNode.buddyUid);if(bOnline){if(!oNodeBuddy.online||oNodeBuddy.username.toLowerCase()>oBuddy.username.toLowerCase()){oNode.insert({'before':oBuddyElement});bInserted=true;break;}}else{if(!oNodeBuddy.online&&oNodeBuddy.username.toLowerCase()>oBuddy.username.toLowerCase()){oNode.insert({'before':oBuddyElement});bInserted=true;break;}}}
if(!bInserted){_oBuddyListElement.insert({'bottom':oBuddyElement});}
oBuddyElement.hide();oBuddyElement.appear();adjustHeight.defer();}
function _getMaxHeight(){var topOffset=258;var minHeight=60;var viewportHeight=document.viewport.getHeight();return Math.max(minHeight,viewportHeight-topOffset);}
function adjustHeight(){if(SD.Config.isSite){var height=_oBuddyListElement.offsetHeight;var maxHeight=_getMaxHeight();if(height>=maxHeight){_oBuddyListWrapper.setHeight(maxHeight);_oBuddyListWrapper.style.overflowY='auto';}else{_oBuddyListWrapper.style.height='';_oBuddyListWrapper.style.overflowY='';}}else{var buddyElements=_oBuddyListElement.getElementsByTagName('li');if(buddyElements.length>15){_oBuddyListWrapper.style.height='400px';_oBuddyListWrapper.style.overflowY='auto';}else{_oBuddyListWrapper.style.height='';_oBuddyListWrapper.style.overflowY='';}}}
function setBuddyOnline(oBuddy,bOnline){SD.log("setting buddy online "+oBuddy.username+" "+bOnline);var oElement=_hBuddyElements.get(oBuddy.uid);if(oElement&&bOnline&&oElement.hasClassName(SD.BuddyList.View.oCSSClasses.classBuddyOnline)){return;}
if(oElement&&!bOnline&&!oElement.hasClassName(SD.BuddyList.View.oCSSClasses.classBuddyOnline)){return;}
oBuddy.online=bOnline;if(bOnline){oElement&&oElement.addClassName(SD.BuddyList.View.oCSSClasses.classBuddyOnline);}else{oElement&&oElement.removeClassName(SD.BuddyList.View.oCSSClasses.classBuddyOnline);}
removeBuddyElement(oBuddy,function(){addBuddyElement(oBuddy,bOnline);});if(!bOnline){_hBuddyElements.unset(oBuddy.uid);}}
this.toggleOnlineUserVisibility=function(link){$("buddylist").hasClassName("showOnlineBuddies2366")?this.showAllUsers(link):this.showOnlineUsersOnly(link);};this.showAllUsers=function(link){link=$(link);$("buddylist-heading").update("All Buddies");$("buddylist-buddycount").hide();$("buddylist").removeClassName("showOnlineBuddies2366");link&&link.update("(Hide offline buddies)");};this.showOnlineUsersOnly=function(link){link=$(link);$("buddylist-heading").update("Online Buddies");$("buddylist-buddycount").show();$("buddylist").addClassName("showOnlineBuddies2366");link&&link.update("(Show All)");_oExpandedBuddy&&SD.Event.fire(null,SD.BuddyList.Events.BUDDY_COLLAPSE,{'buddy':_oExpandedBuddy});};this.oCSSClasses={classBuddyOnline:'',classBuddyExpanded:''};this.init=function(aInitialBuddies){aBuddies=aInitialBuddies;SD.Event.observe(null,SD.BuddyList.Events.USER_ADDED,function(e){var oUser=e.memo.user;this.addBuddy(oUser);}.bind(this));SD.BuddyList.View.registerOutputBuddy();Event.observe(window,'resize',adjustHeight);};this.addBuddy=function(oUser){addBuddyElement(oUser,oUser.online);};this.show=function(){$('sd-sidebar-buddy-headline').show();$('buddylist').show();isVisible=true;};this.hide=function(){$('sd-sidebar-buddy-headline').hide();$('buddylist').hide();isVisible=false;};this.registerOutputBuddyList=function(oElement,oWrapper){_oBuddyListElement=$(oElement);_oBuddyListWrapper=$(oWrapper);adjustHeight.defer();};this.registerOutputBuddy=function(){SD.Event.observe(null,SD.BuddyList.Events.USER_PRESENCE_UPDATED,function(e){if(e.memo.user){setBuddyOnline(e.memo.user,e.memo.user.online);}}.bind(this));SD.Event.observe(null,SD.User.Events.USER_ONLINE,function(e){var buddy=SD.BuddyList.Controller.getBuddyById(e.memo.user.uid);if(buddy){setBuddyOnline(buddy,true);}}.bind(this));SD.Event.observe(null,SD.User.Events.USER_OFFLINE,function(e){var buddy=SD.BuddyList.Controller.getBuddyById(e.memo.user.uid);if(buddy){setBuddyOnline(buddy,false);}}.bind(this));SD.Event.observe(null,SD.BuddyList.Events.USER_REMOVED,function(e){if(e.memo.user){removeBuddyElement(e.memo.user,function(){SD.UIController.infoMessage(e.memo.user.username+' has been removed from your list');});SD.BuddyList.Controller.removeBuddy(e.memo.user);}}.bind(this));SD.Event.observe(null,SD.BuddyList.Events.USER_BLOCKED,function(e){if(e.memo.user){SD.BuddyList.Controller.blockBuddy(e.memo.user);SD.BuddyList.Controller.removeBuddy(e.memo.user);removeBuddyElement(e.memo.user,function(){SD.UIController.infoMessage(e.memo.user.username+' has been removed from your list. All further messages from '+e.memo.user.username+' will be blocked');});}}.bind(this));};this.registerOutputBuddyCounter=function(oElement){if(oElement&&$(oElement)){SD.Event.observe(null,SD.BuddyList.Events.BUDDY_COUNT_CHANGE,function(e){$(oElement)&&$(oElement).update(' ('+e.memo.countOnline+'/'+e.memo.countTotal+')');});}};this.register=function(){this.registerOutputBuddyList('buddylist','buddyListWrapper');this.registerOutputBuddyCounter('buddylist-buddycount');this.registerIO([],{'classBuddyExpanded':'buddy-expanded','classBuddyOnline':'buddy-online'});};this.counter=0;this.registerIO=function(aParams,oClasses){this.oCSSClasses=oClasses||this.oCSSClasses;var i;for(i=this.counter;i<aParams.length;i++){if(i>=this.counter+10){break;}
this.registerIOParamsForUserId(aParams[i]);}
this.counter=i;if(i<aParams.length){this.registerIO.bind(this).delay(1,aParams);}
var aOnlineBuddies=SD.BuddyList.Controller.getOnlineBuddies();aOnlineBuddies.each(function(oSomeBuddy){if(oSomeBuddy.online&&!oSomeBuddy.bubbled){removeBuddyElement(oSomeBuddy,function(){addBuddyElement(oSomeBuddy,oSomeBuddy.online);oSomeBuddy.bubbled=true;});}});};this.registerIOParamsForUserId=function(oParam){var oBuddy=(assureGetBuddyfunction(oParam.getBuddy))();$(oParam.buddyElement).buddyUid=oBuddy.uid;_hBuddyElements.set(oBuddy.uid,$(oParam.buddyElement));_hBuddyHeadElements.set(oBuddy.uid,$(oParam.buddyHeadElement));_hBuddyBodyElements.set(oBuddy.uid,$(oParam.buddyBodyElement));if(!(SD.Config.isSite)){}};};
SD.DatingController={_jingleVersion:5,_failedVersionThreshold:3,_numFailedVersions:0,_pc:null,_user:null,_state:"available",_jingleActiveInitiateIqId:null,_jingleSession:null,_jingleOtherJID:null,_jingleMyJID:null,_jingleInitiator:false,_datingServer:null,_datingInstance:null,_datingSharedObject:null,_datingMyResource:null,_datingOtherResource:null,_serverCounter:0,_initiateTimeoutPE:null,_failedPings:0,Events:{LOGIN:"datingcontroller:login",SESSION_TERMINATED:"datingcontroller:session_terminated",TRYING_TO_DATE:"datingcontroller:trying_to_date",ACCEPTED_TO_DATE:"datingcontroller:accepted_to_date",RECEIVED_PROBE_REQUEST:"datingcontroller:received_probe_request",RECEIVED_PROBE_RESPONSE:"datingcontroller:received_probe_response"},getDatingServer:function(){this._serverCounter=(this._serverCounter+1)%SD.Config.defaultDatingServers.length;return SD.Config.defaultDatingServers[this._serverCounter];},initialize:function(user,pairingController){this._pc=pairingController;this._user=user;SD.log("SD.DatingController.initialize()");SD.Event.observe(null,SD.Date.Events.DATE_OVER,this.onDateOver.bind(this));SD.Event.observe(null,SD.Date.Events.END_DATE_REQUESTED,this.onEndDateRequested.bind(this));SD.Event.observe(null,SD.Date.Events.SEND_DATE_CHAT_REQUESTED,this.onSendDateChatRequested.bind(this));SD.Event.observe(null,SD.Date.Events.MY_STREAMING_STATE_CHANGED,this.onMyStreamingStateChanged.bind(this));SD.Event.observe(null,SD.XMPP.Events.LOGIN,this.onLogin.bind(this));var namespaces=['urn:ietf:params:xml:ns:xmpp-stanzas','speeddate:rtmp-dating','urn:xmpp:tmp:jingle','urn:xmpp:tmp:jingle:errors'];namespaces.each(function(ns){SD.XMPP.getStropheConnection().addHandler(this.onIncomingIQWrapper.bind(this),ns);}.bind(this));SD.XMPP.getStropheConnection().addHandler(this.onIncomingProbeIQ.bind(this),"speeddate:status-probe");SD.XMPP.getStropheConnection().addHandler(this.onIncomingFuncIQ.bind(this),"speeddate:func-call");(new PeriodicalExecuter(this.onSessionInfoTimer.bind(this),1));},isLoggedIn:function(){return SD.XMPP.isLoggedIn();},onLogin:function(event){SD.Event.fire(null,SD.DatingController.Events.LOGIN);},tryToDate:function(user,otherUser,token){this.debug(">>trytodate");SD.log("tryToDate() "+(user&&user.uid)+","+(otherUser&&otherUser.uid));if(this._user!=user){SD.Event.fireDeferred(user,SD.Date.Events.DATE_OVER,{user:user,reasondCode:"userInvalid"});return;}
SD.Event.fire(user,SD.DatingController.Events.TRYING_TO_DATE,{match:otherUser});this._jingleSession=this.randomString(32);this._jingleOtherJID=otherUser.chat_id+'/'+SD.XMPP._resourceName;this._jingleMyJID=SD.Model.getMyself().chat_id+'/'+SD.XMPP._resourceName;this._jingleInitiator=true;this._datingServer=this.getDatingServer();SD.log("datingServerChosen:"+this._datingServer);this._datingInstance="room_"+Math.floor((Math.random()*50));this._datingSharedObject=this.randomString(16);this._datingMyResource=this.randomString(16);this._datingOtherResource=this.randomString(16);this.sendSessionInitiate(token,otherUser.desktopToken);this.debug("<<trytodate");},debug:function(txt){},onIncomingIQWrapper:function(iq){try{var res=this.onIncomingIQ(iq);if(!res){}}catch(e){}
return true;},onIncomingProbeIQ:function(iq){try{var otherJid=iq.getAttribute('from');var otherUser=SD.User.getByChatID(otherJid);if(!otherUser){return true;}
Strophe.forEachChild(iq,"status-probe",function(node){var type=node.getAttribute('type');var probe=null;if(type=='request'){probe={probe_id:node.getAttribute('probe_id'),token:node.getAttribute('token'),type:type};}else if(type=='response'){probe={probe_id:node.getAttribute('probe_id'),idle:node.getAttribute('idle'),type:type};}
if(probe){this.onStatusProbeData(otherUser,probe);}}.bind(this));}catch(e){}
return true;},onIncomingFuncIQ:function(iq){try{var otherJid=iq.getAttribute('from');var otherUser=SD.User.getByChatID(otherJid);if(!otherUser){return true;}
Strophe.forEachChild(iq,"function-call",function(node){var args=node.getAttribute('arguments');var fData={name:node.getAttribute('name'),arguments:args?args.evalJSON():null};(SD.Date[fData.name])&&(SD.Date[fData.name]).apply(SD.Date,fData.arguments);}.bind(this));}catch(e){}
return true;},onIncomingIQ:function(iq){var type=iq.getAttribute('type');if(type!='set'&&type!='get'){return true;}
var otherJid=iq.getAttribute('from');var otherUser=SD.User.getByChatID(otherJid);var jingleData=null;Strophe.forEachChild(iq,"jingle",function(e){jingleData=this.parseJingleNode(e);}.bind(this));if(!jingleData){return true;}
if(jingleData.extraInfo){otherUser.extraInfo=jingleData.extraInfo;}
SD.log(jingleData.action+",init:"+jingleData.initiator+",resp:"+jingleData.responder);if(this._state!='available'&&jingleData.sessionId==this._jingleSession){if(jingleData.action=="session-terminate"){this.sendIQResult(iq);var reasonCode;var reason;if(jingleData.reasonCondition==SD.ReasonCodes.BUSY){reasonCode=SD.ReasonCodes.BUSY;}else if(jingleData.reasonCondition=='unsupported-transports'){reasonCode=SD.ReasonCodes.OBSOLETE_VERSION;}else{if(jingleData.reasonCondition!='success'){this.debug("onIncomingNode() -- session-terminate, reasonCondition NOT IN busy, unsupported-transports, success : "+jingleData.reasonCondition);}
reasonCode=jingleData.reasonCode;reason=jingleData.reason;}
this.onSessionTerminate(reasonCode,reason,'partner');this.debug("  return7");return true;}
else if(jingleData.action=="session-accept"){SD.log("debug: session-accept");this.sendIQResult(iq);SD.log("debug: send iq result");if(this._initiateTimeoutPE){SD.log("debug: initiate timeout pe inside");this._initiateTimeoutPE.stop();this._initiateTimeoutPE=null;}
SD.log("debug: initiate timeout pe ended");this._state='active';SD.log("debug: state=active");SD.log("iq.getFrom():");SD.log(otherJid);SD.log("iq.getFrom().toBareJID():");SD.log(Strophe.getBareJidFromJid(otherJid));SD.log("iq.getFrom().getResource():");SD.log(Strophe.getResourceFromJid(otherJid));this._jingleOtherJID=otherJid;SD.log("debug: this._jingleOtherJID");SD.log("debug: before setupUI");this.setupUI();SD.log("debug: after setupUI");}
else if(jingleData.action=="session-info"){this.sendIQResult(iq);if(jingleData.dateChat){SD.log("[DC] received dateChat");SD.Event.fire(null,SD.Date.Events.DATE_CHAT_RECEIVED,{message:jingleData.dateChat.text,type:jingleData.dateChat.type});}else if(jingleData.streamingState){SD.log("[DC] received streamingState");SD.Date.updatePartnersStreamingState(jingleData.streamingState);}else if(jingleData.dateCameraState){SD.Date.receivedCameraState(jingleData.dateCameraState.state);}else{SD.log("[DC] received ping");}}
else{SD.log("why u sent me this:"+jingleData.action);this.sendIQErrorInvalidSession(iq);this.onSessionTerminate('userDisconnected','unknown packet','partner');}}else{if(jingleData.action=="session-initiate"){SD.log("check if i can accept");this.sendIQResult(iq);var canAccept=true;if(this._jingleSession){canAccept=false;}
var isValid=true;if(jingleData.contents.length<1){isValid=false;canAccept=false;}
var otherPartyObsoleteVersion=false;if(this._jingleVersion!=jingleData.contents[0].version&&!(this._jingleVersion==1&&jingleData.contents[0].version===0)){isValid=false;canAccept=false;if(jingleData.contents[0].version<this._jingleVersion){otherPartyObsoleteVersion=true;}else{this.onObsoleteVersion();}}
otherUser.token=jingleData.contents[0].description.initiatorToken;otherUser.square_image_url=jingleData.contents[0].description.initiatorImage;var desktopToken=(jingleData.contents[0].description.desktopToken)?jingleData.contents[0].description.desktopToken:null;SD.log("initiator has the token:"+otherUser.token);var rejectReason={reason:'unknown'};if(isValid&&this._pc.areYouBusy(otherUser,jingleData.contents[0].description.responderToken,rejectReason,jingleData.contents[0].description.initiatorToken)){canAccept=false;}
if(!canAccept){this.sendSessionTerminate(otherJid,otherJid,jingleData.sessionId,(otherPartyObsoleteVersion?SD.ReasonCodes.OBSOLETE_VERSION:SD.ReasonCodes.BUSY),undefined,rejectReason.reason);this.debug("  return8");return true;}
else{SD.log("accepted");SD.Event.fire(null,SD.DatingController.Events.ACCEPTED_TO_DATE,{match:otherUser});this._state='active';this._jingleSession=jingleData.sessionId;this._jingleOtherJID=otherJid;this._jingleInitiator=false;this._datingServer=jingleData.contents[0].description.server;this._datingInstance=jingleData.contents[0].description.instance;this._datingSharedObject=jingleData.contents[0].description.sharedObject;this._datingMyResource=jingleData.contents[0].description.responderResource;this._datingOtherResource=jingleData.contents[0].description.initiatorResource;this.sendSessionAccept();this.setupUI();this.debug("  return9");return true;}}
else{SD.log("unknown-session");this.sendIQErrorInvalidSession(iq);}}
this.debug("end");return true;},onObsoleteVersion:function(){this._numFailedVersions++;if(this._numFailedVersions>=this._failedVersionThreshold){this._numFailedVersions=0;SD.Event.fire(null,this.Events.VERSION_OBSOLETE);}},onJingleCallback:function(receivedIQ){alert("onJingleCallback "+receivedIQ);},onSendDateChatRequested:function(ev){if(this._state=='active'){this.sendDateChat(ev.memo.type,ev.memo.message);}else{this.debug("onSendDateChatRequested() when state="+this._state);}},onMyStreamingStateChanged:function(ev){if(this._state=='active'){this.sendStreamingState(ev.memo);}else{this.debug("onMyStreamingStateChanged() when state="+this._state);}},sendProbes:function(users,probeId){if(users){users.each(function(user){var iq=$iq({to:user.chat_id+'/'+SD.XMPP._resourceName,type:'get'}).c('status-probe',{xmlns:'speeddate:status-probe',token:user.token,type:'request',probe_id:probeId});SD.XMPP.getStropheConnection().send(iq);});}},sendProbeResponse:function(romeo,probeId,idle){var iq=$iq({to:romeo.chat_id+'/'+SD.XMPP._resourceName,type:'set'}).c('status-probe',{xmlns:'speeddate:status-probe',probe_id:probeId,type:'response',idle:idle?'true':'false'});SD.XMPP.getStropheConnection().send(iq);},onStatusProbeData:function(other,data){data.user=other;if(data.type=='request'){SD.Event.fire(null,SD.DatingController.Events.RECEIVED_PROBE_REQUEST,data);}
else if(data.type=='response'){SD.Event.fire(null,SD.DatingController.Events.RECEIVED_PROBE_RESPONSE,data);}},sendSessionInitiate:function(token,desktopToken){this.debug(">>sendsessioninitiate");this._jingleActiveInitiateIqId='jingle_'+this.randomString(8);var iq=$iq({to:this._jingleOtherJID,type:'set',id:this._jingleActiveInitiateIqId});var Nodes=SD.DatingController.Nodes;var jingleNode=Nodes.jingleS('session-initiate',this._jingleMyJID,null,this._jingleSession,[Nodes.contentS('initiator','video-conference',[Nodes.descriptionS({server:this._datingServer,instance:this._datingInstance,sharedObject:this._datingSharedObject,initiatorResource:this._datingMyResource,responderResource:this._datingOtherResource,responderToken:token,initiatorToken:SD.Model.getMyself().token,initiatorImage:SD.Model.getMyself().square_image_url,desktopToken:desktopToken}),Nodes.transportS()]),Nodes.extraInfoS(this._getExtraInfo())]);iq.cnode(jingleNode);this._state="pending";SD.XMPP.getStropheConnection().sendIQ(iq,this.onSessionInitiateCallback.bind(this),function(e){this.onSessionTerminate(SD.ReasonCodes.BUSY,'initiate timeout','partner');}.bind(this));this._initiateTimeoutPE=new PeriodicalExecuter(function(pe){pe.stop();this._initiateTimeoutPE=null;this.onSessionTerminate(SD.ReasonCodes.BUSY,'initiate timeout','partner');}.bind(this),5);this.debug("<<sendsessioninitiate");},_getExtraInfo:function(){return{datingScore:SD.Model.getMyself().getDatingScore()};},sendSessionAccept:function(){this.debug(">>sendsessionaccept");var iq=$iq({to:this._jingleOtherJID,type:'set',id:'jingle_'+this.randomString(8)});var Nodes=SD.DatingController.Nodes;var jingleNode=Nodes.jingleS('session-accept',this._jingleInitiator?this._jingleMyJID:this._jingleOtherJID,this._jingleInitiator?this._jingleOtherJID:this._jingleMyJID,this._jingleSession,[Nodes.extraInfoS(this._getExtraInfo())]);iq.cnode(jingleNode);SD.XMPP.getStropheConnection().send(iq);this.debug("<<sendsessionaccept");},sendSessionTerminate:function(receiver,initiator,sessionId,reasonCode,reason,optReason){this.debug(">>sendsessionterminate");SD.log("sending session termination:"+reasonCode);var iq=$iq({to:receiver,type:'set',id:'jingle_'+this.randomString(8)});var Nodes=SD.DatingController.Nodes;var reasonNode;if(reasonCode==SD.ReasonCodes.BUSY){reasonNode=Nodes.reasonS(SD.ReasonCodes.BUSY);}else if(reasonCode==SD.ReasonCodes.OBSOLETE_VERSION){reasonNode=Nodes.reasonS('unsupported-transports');}else{reasonNode=Nodes.reasonSuccessS(reasonCode,reason);}
var jingleNode=Nodes.jingleS('session-terminate',initiator,'null',sessionId,[reasonNode],this._state+","+optReason);iq.cnode(jingleNode);SD.XMPP.getStropheConnection().send(iq);this.debug("<<sendsessionterminate");},sendSessionInfo:function(){this.debug(">>sendsessioninfo");this._jingleActiveInfoIqId='jingle_'+this.randomString(8);var iq=$iq({to:this._jingleOtherJID,type:'get',id:this._jingleActiveInfoIqId});var Nodes=SD.DatingController.Nodes;var jingleNode=Nodes.jingleS('session-info',this._jingleInitiator?this._jingleMyJID:this._jingleOtherJID,this._jingleInitiator?this._jingleOtherJID:this._jingleMyJID,this._jingleSession,[]);iq.cnode(jingleNode);SD.XMPP.getStropheConnection().sendIQ(iq,this.onSessionInfoCallback.bind(this));SD.log("Sent PING "+this._jingleActiveInfoIqId);this.debug("<<sendsessioninfo");},sendDateChat:function(type,text){var iq=$iq({type:"set",to:this._jingleOtherJID,id:'jingle_'+this.randomString(8)});var Nodes=SD.DatingController.Nodes;var jingleNode=Nodes.jingleS('session-info',this._jingleInitiator?this._jingleMyJID:this._jingleOtherJID,this._jingleInitiator?this._jingleOtherJID:this._jingleMyJID,this._jingleSession);var chatNode=Nodes.dateChatS(type,text);jingleNode.appendChild(chatNode);iq.cnode(jingleNode);SD.XMPP.getStropheConnection().send(iq);this.debug("<<sendDateChat");},sendCameraState:function(state){this.debug(">>sendDateChat");var iq=$iq({type:"set",to:this._jingleOtherJID,id:'jingle_'+this.randomString(8)});var Nodes=SD.DatingController.Nodes;var jingleNode=Nodes.jingleS('session-info',this._jingleInitiator?this._jingleMyJID:this._jingleOtherJID,this._jingleInitiator?this._jingleOtherJID:this._jingleMyJID,this._jingleSession);var cameraState=Strophe.xmlElement('date-camera-state',{state:state});jingleNode.appendChild(cameraState);iq.cnode(jingleNode);SD.XMPP.getStropheConnection().send(iq);},remoteCall:function(functionName,arguments){this.debug(">>send function call:"+functionName);var iq=$iq({to:this._jingleOtherJID,type:'set'}).c('function-call',{xmlns:"speeddate:func-call",name:functionName,arguments:Object.toJSON(arguments)});SD.XMPP.getStropheConnection().send(iq);},sendStreamingState:function(streamingState){this.debug(">>sendStreamingState");var iq=$iq({to:this._jingleOtherJID,type:'set',id:'jingle_'+this.randomString(8)});var Nodes=SD.DatingController.Nodes;var jingleNode=Nodes.jingleS('session-info',this._jingleInitiator?this._jingleMyJID:this._jingleOtherJID,this._jingleInitiator?this._jingleOtherJID:this._jingleMyJID,this._jingleSession,[Nodes.streamingStateS(streamingState)]);iq.cnode(jingleNode);SD.XMPP.getStropheConnection().send(iq);this.debug("<<sendStreamingState");},onSessionInfoCallback:function(iq){this.debug(">>onSessionInfoCallback");var id=iq.getAttribute('id');if(id==this._jingleActiveInfoIqId){var type=iq.getAttribute('type');if(type=='result'){SD.log("Received PONG "+id);this._jingleActiveInfoIqId=null;}
else if(type=='error'){if(this._failedPings>=2){this.onSessionTerminate('userDisconnected','ping timeout (error reply)','partner');}}}
this.debug("<<onSessionInfoCallback");},onSessionInfoTimer:function(pe){this.debug(">>onSessionInfoTimer");this.debug("STATE:"+this._state);var nextTimeOut=6;if(this._state=='active'){if(!this._jingleActiveInfoIqId){this._failedPings=0;this.sendSessionInfo();}else{this._failedPings++;SD.log("failed pings:"+this._failedPings);if(this._failedPings==1){nextTimeOut=4;this.sendSessionInfo();}else if(this._failedPings==2){nextTimeOut=2;this.sendSessionInfo();}else{this.onSessionTerminate('userDisconnected','ping timeout','partner');}}}
pe.stop();(new PeriodicalExecuter(this.onSessionInfoTimer.bind(this),nextTimeOut));this.debug("<<onSessionInfoTimer");},onSessionInitiateCallback:function(iq){this.debug(">>onSessionInitiateCallback");SD.log("onSessionInitiateCallback");var id=iq.getAttribute('id');if(id==this._jingleActiveInitiateIqId){var type=iq.getAttribute('type');SD.log("onSessionInitiateCallback() type="+type);if(type=='error'){this.onSessionTerminate('userDisconnected','initiate-reply error','partner');}}
this.debug("<<onSessionInitiateCallback");},onSessionTerminate:function(reasonCode,reason,who){this.debug(">>onSessionTerminate");if(reasonCode==SD.ReasonCodes.OBSOLETE_VERSION){this.onObsoleteVersion();}
if(this._state=='active'){if(reasonCode!="busy"&&reasonCode!="initiate-reply error"){SD.Event.fire(null,SD.DatingController.Events.SESSION_TERMINATED,{reason:reasonCode,who:who,uid:SD.Model.getMyself().uid,other:SD.User.getByChatID(this._jingleOtherJID)});}
SD.User.endDate(SD.User.getByChatID(this._jingleOtherJID));}
var oldState=this._state;this._state='available';this._jingleSession=null;if(this._initiateTimeoutPE)
{this._initiateTimeoutPE.stop();this._initiateTimeoutPE=null;}
this._jingleActiveInfoIqId=null;if(oldState=='pending'){SD.Date.dateEnded({user:SD.User.externalize(this._user),reasonCode:reasonCode,reason:reason,endedByMe:false,myVote:null,wasStarted:false},true);}
else if(oldState=='active'){this.stopUI(reasonCode,reason,who);}
this.debug("<<onSessionTerminate");},sendIQResult:function(incomingIQ){this.debug(">>sendIQResult");var iq=$iq({to:incomingIQ.getAttribute('from'),type:'result',id:incomingIQ.getAttribute('id')});SD.XMPP.getStropheConnection().send(iq);this.debug("<<sendIQResult");},sendIQErrorInvalidSession:function(incomingIQ){this.debug(">>sendIQErrorInvalidSession");var iq=$iq({to:incomingIQ.getAttribute('from'),type:'error',id:incomingIQ.getAttribute('id')});var Nodes=SD.DatingController.Nodes;var errorNode=Strophe.xmlElement('error',{type:'cancel'});errorNode.appendChild(Strophe.xmlElement('bad-request',{xmlns:'urn:ietf:params:xml:ns:xmpp-stanzas'}));errorNode.appendChild(Strophe.xmlElement('unknown-session',{xmlns:'urn:xmpp:tmp:jingle:errors'}));iq.cnode(errorNode);SD.XMPP.getStropheConnection().send(iq);this.debug("<<sendIQErrorInvalidSession");},setupUI:function(){SD.Event.fire(null,SD.Date.Events.DATE_INIT_START,null);var comm={DateHost:this._datingServer,DateInstance:this._datingInstance,myStreamName:this._datingMyResource,otherStreamName:this._datingOtherResource,sharedObjectName:this._datingSharedObject};SD.log(Object.toJSON(comm));var otherUser=SD.User.getByChatID(this._jingleOtherJID);duration=SD.Config.datingDuration;var popupLater=false;SD.Date.startDate({myUser:this._user,otherUser:SD.User.getByChatID(this._jingleOtherJID),duration:duration,communication:comm,popupLater:popupLater});this._failedPings=0;SD.User.initDate(SD.User.getByChatID(this._jingleOtherJID));},stopUI:function(reasonCode,reason,who){SD.Date.stopDate(reasonCode,reason,who);},onEndDateRequested:function(ev){this.debug(">>onEndDateRequested");var memo=ev.memo;this.debug(memo);if(this._state=='active'){this.sendSessionTerminate(this._jingleOtherJID,this._jingleInitiator?this._jingleMyJID:this._jingleOtherJID,this._jingleSession,memo.reasonCode,memo.reason);this.onSessionTerminate(memo.reasonCode,memo.reason,'me');}else{this.debug("onEndDateRequested: this._state = "+this._state+" ??");}
this.debug("<<onEndDateRequested");},onDateOver:function(ev){this.debug(">>onDateOver");var reason=ev.memo.reason?ev.memo.reason:'no reason';SD.log("onDateOver(r,rc):"+reason+","+(ev.memo.reasonCode?ev.memo.reasonCode:" no reason code"));var juliet=SD.User.getByChatID(this._jingleOtherJID);var endedByUser=(ev.memo.reasonCode=='dateEnded');var successful=(ev.memo.reasonCode==SD.ReasonCodes.TIME_FINISHED);if(successful){SD.User.sendVote(juliet,ev.memo.myVote);}
if(this._state=='active'){this.debug("state CANNOT be active here?");}
this.debug("<<onDateOver");},randomString:function(len){var alphabet="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";var str='';for(var i=0;i<len;i++){var rnum=Math.floor(Math.random()*alphabet.length);str+=alphabet.substring(rnum,rnum+1);}
return str;},parseJingleNode:function(jingleNode){var out={action:null,initiator:null,responder:null,sessionId:null,contents:[],reasonCondition:null,reasonCode:null,reason:null,dateChat:null,streamingState:null};out.action=jingleNode.getAttribute('action');out.initiator=jingleNode.getAttribute('initiator');out.responder=jingleNode.getAttribute('responder');out.sessionId=jingleNode.getAttribute('sid');var otherState=jingleNode.getAttribute('myState');if(otherState){SD.log(otherState);}
var node;var node2;Strophe.forEachChild(jingleNode,null,function(node){var tagName=node.tagName.toLowerCase();if(tagName=="content"){var content={creator:null,name:null,description:{server:null,instance:null,sharedObject:null,initiatorResource:null,responderResource:null,responderToken:null,initiatorToken:null,initiatorImage:null,desktopToken:null},version:null};content.creator=node.getAttribute("creator");content.name=node.getAttribute("name");var transportXMLNS=null;Strophe.forEachChild(node,null,function(node2){var nodeName=node2.tagName.toLowerCase();if(nodeName=="transport"){transportXMLNS=node2.getAttribute('xmlns');content.version=Number(node2.getAttribute("version"));if(isNaN(content.version)){content.version=0;}}else if(nodeName=="description"){content.description.server=node2.getAttribute("server");content.description.instance=node2.getAttribute("instance");content.description.sharedObject=node2.getAttribute("sharedobject");content.description.initiatorResource=node2.getAttribute("initiatorresource");content.description.responderResource=node2.getAttribute("responderresource");content.description.responderToken=node2.getAttribute("respondertoken");content.description.initiatorToken=node2.getAttribute("initiatortoken");content.description.initiatorImage=node2.getAttribute("initiatorimage");content.description.desktopToken=node2.getAttribute("desktoptoken");}}.bind(this));SD.log("xmlns = "+transportXMLNS);SD.log("version = "+content.version);if(transportXMLNS=="speeddate:rtmp-dating"){out.contents.push(content);}}else if(tagName=="reason"){Strophe.forEachChild(node,"condition",function(node2){Strophe.forEachChild(node2,null,function(node3){out.reasonCondition=node3.tagName;if(out.reasonCondition=='success'){out.reasonCode=node3.getAttribute("reasoncode");out.reason=node3.getAttribute("reason");}}.bind(this));});}
else if(tagName=="date-chat"){out.dateChat={type:node.getAttribute("type"),text:node.getAttribute("text")};}else if(tagName=="date-camera-state"){out.dateCameraState={state:node.getAttribute("state")};}else if(tagName=="streaming-state"){out.streamingState=(node.getAttribute("state")=='on');}else if(tagName=='extra-info'){out.extraInfo=node.getAttribute("data").evalJSON();}}.bind(this));return out;},Nodes:{jingleS:function(action,initiator,responder,sid,children,myState){var attrs={xmlns:'urn:xmpp:tmp:jingle',action:action,initiator:initiator,responder:responder,sid:sid};if(myState)
attrs.myState=myState;var node=Strophe.xmlElement("jingle",attrs);if(children){for(var i=0;i<children.length;i++){node.appendChild(children[i]);}}
return node;},contentS:function(creator,name,children){var node=Strophe.xmlElement('content',{creator:creator,name:name});if(children){for(var i=0;i<children.length;i++){node.appendChild(children[i]);}}
return node;},transportS:function(){return Strophe.xmlElement('transport',{xmlns:'speeddate:rtmp-dating',version:SD.DatingController._jingleVersion});},descriptionS:function(desc){return Strophe.xmlElement('description',desc);},reasonS:function(reasonCondition){var node=Strophe.xmlElement('reason');var cond=Strophe.xmlElement('condition');var reason=Strophe.xmlElement(reasonCondition);node.appendChild(cond).appendChild(reason);return node;},reasonSuccessS:function(reasonCode,reason){var node=Strophe.xmlElement('reason');var cond=Strophe.xmlElement('condition');var succ=Strophe.xmlElement('success',{reasonCode:reasonCode,reason:reason});node.appendChild(cond).appendChild(succ);return node;},dateChatS:function(type,text){return Strophe.xmlElement('date-chat',{type:type,text:text});},streamingStateS:function(state){return Strophe.xmlElement('streaming-state',{state:state?'on':'off'});},extraInfoS:function(data){return Strophe.xmlElement('extra-info',{data:Object.toJSON(data)});}}};
var Stack=function(){this.content=[];this.length=0;};Stack.prototype.shift=function(){var entry=this.content.pop();if(this.length){SD.Event.fire(this,Stack.Events.REMOVED,{obj:entry});}
this.length=this.content.length;return entry;};Stack.prototype.push=function(entry){var i=0;while(i<this.content.length){if(this.content[i]==entry){this.content.splice(i,1);}else{i++;}}
this.content.push(entry);SD.Event.fire(this,Stack.Events.ADDED,{obj:entry});this.length=this.content.length;};Stack.prototype.empty=function(){while(this.length>0){this.shift();}};Stack.prototype.shiftRandom=function(){if(this.content.length==0){return null;}
var rnd=Math.floor(Math.random()*this.content.length);var entries=this.content.splice(rnd,1);SD.Event.fireDeferred(this,Stack.Events.REMOVED,{obj:entries[0]});return entries[0];};Stack.prototype.getContent=function(limit){return this.content.slice(0,limit);};Stack.Events={ADDED:'stack:added',REMOVED:'stack:removed'};SD.PairingController=function(user){this.state=SD.PairingController.states.PAUSED;this.user=user;this.pauseRequested=false;var scope=this;var init=function(){scope.outstandingInvites=0;scope.matches=new Stack();scope.pending=new Stack();scope.pendingPriority=new Stack();scope.pendingRomeos=new Stack();scope.lastRequestedMatches=0;};var reset=function(){scope.outstandingInvites=0;scope.matches.empty();scope.pending.empty();scope.pendingPriority.empty();scope.pendingRomeos.empty();scope.lastRequestedMatches=0;};var getNow=function(){return new Date().getTime();};var resetIdleSince=function(){scope.idleSince=getNow();};var considerRequestingMatches=function(){var now=getNow();if((now-scope.lastRequestedMatches)>SD.PairingController.timeBetweenMatchRequests()){scope.lastRequestedMatches=now;SD.Matchmaker.matchMember(scope.user);return true;}
return false;};var tryToDate=function(juliet){scope.state=SD.PairingController.states.BUSY;SD.DatingController.tryToDate(scope.user,juliet,juliet.token);};var getNextJuliet=function(queue){var any=false;var juliet;do{juliet=queue.shift();any=any||juliet;}while(juliet&&!scope.user.mightDate(juliet));if(any){scope.waitingTimeChanged();}
return juliet;};var fetchAndPushRomeo=function(romeo){SD.User.fetch(romeo,function(){if(romeo.category=="P"){SD.log("adding "+romeo.username+" to priority list");scope.pendingPriority.push(romeo);}else if(romeo.category=="U"){SD.log("adding "+romeo.username+" to regular list");scope.pending.push(romeo);}},30);};var seek=function(preferredJuliet){if(SD.PickDate.isActive()){return;}
if(preferredJuliet){if(!preferredJuliet.uid||!preferredJuliet.username||!preferredJuliet.chat_id){preferredJuliet=null;}}
SD.log("seeking called; [priority: "+scope.pendingPriority.length+",pending: "+scope.pending.length+",matches: "+scope.matches.length+",romeos: "+scope.pendingRomeos.length+"] idle: "+scope.amIdle());if(SD.DatingController.isLoggedIn()&&scope.amIdle()){if(scope.pauseRequested){scope.state=SD.PairingController.states.PAUSED;}else{if(!preferredJuliet||preferredJuliet.uid!=scope.user.uid){if(preferredJuliet&&scope.user.mightDate(preferredJuliet)){return tryToDate(preferredJuliet);}
var limit=scope.user.sex=='F'?4:10;var toProbe=[];toProbe=toProbe.concat(scope.pendingPriority.getContent(limit));limit=Math.max(0,limit-toProbe.length);toProbe=toProbe.concat(scope.pending.getContent(limit));limit=Math.max(0,limit-toProbe.length);toProbe=toProbe.concat(scope.matches.getContent(limit));limit=Math.max(0,limit-toProbe.length);toProbe=toProbe.filter(function(match){return scope.user.mightDate(match);});if(toProbe.length){SD.DatingController.sendProbes(toProbe,scope.user.token);seek.bind(this).delay(8,scope.user);}else{seek(scope.user);}}else{var juliet=getNextJuliet(scope.pendingPriority);if(juliet){return tryToDate(juliet);}
juliet=getNextJuliet(scope.pending);if(juliet){return tryToDate(juliet);}
var romeo;while(romeo=scope.pendingRomeos.shift()){fetchAndPushRomeo(romeo);}
juliet=getNextJuliet(scope.matches);if(juliet){return tryToDate(juliet);}}
considerRequestingMatches();}}else{SD.log("not logged in or not idle");}};init();resetIdleSince();(new PeriodicalExecuter(seek,SD.PairingController.timeBetweenMatchRequests()/1000));SD.Event.observe(null,SD.DatingController.Events.LOGIN,function(){if(scope.state==SD.PairingController.states.PAUSED){SD.XMPP.goAway();}
seek();});SD.Event.observe(null,SD.DatingController.Events.RECEIVED_PROBE_REQUEST,function(e){var token=e.memo.token;var probeId=e.memo.probe_id;var romeo=e.memo.user;var mightDate=this.user.mightDate(romeo);var tokenMatches=token==this.user.token;var idle=this.amIdle();if(mightDate&&tokenMatches&&idle){SD.DatingController.sendProbeResponse(romeo,probeId,true);}}.bind(this));SD.Event.observe(null,SD.DatingController.Events.RECEIVED_PROBE_RESPONSE,function(e){if(e.memo.probe_id==scope.user.token){seek(e.memo.user);}}.bind(this));SD.Event.observe(null,SD.UserFilters.UI.Events.START_SPEEDDATING,function(){SD.log('pairingcontroller start');scope.pauseRequested=false;var start=function(){if(scope.pauseRequested){return;}
SD.Matchmaker.startRegistering(scope.user);SD.XMPP.goOnline();if(scope.state!=SD.PairingController.states.BUSY){scope.state=SD.PairingController.states.IDLE;resetIdleSince();seek();}}
if(SD.XMPP._connected){start();}else{SD.Event.observe(null,SD.XMPP.Events.CONNECT,start.bind(this));}});SD.Event.observe(null,SD.UserFilters.UI.Events.PAUSE_SPEEDDATING,function(){SD.XMPP.goAway();SD.Matchmaker.stopRegistering(scope.user);scope.pauseRequested=true;if(scope.amIdle()){scope.state=SD.PairingController.states.PAUSED;}});SD.Event.observe(user,SD.Matchmaker.Events.MATCHES_FOUND,function(event){scope.outstandingInvites=0;scope.matches.empty();event.memo.matches.reverse();event.memo.matches.each(function(match){var juliet=match;if(scope.user.mightDate(juliet)){scope.matches.push(juliet);}});scope.waitingTimeChanged();seek();});SD.Event.observe(user,SD.Date.Events.DATE_OVER,function(event){SD.log("PC, dateOver: "+event.memo.user.username+","+scope.user.username);if(event.memo.user==scope.user){if(event.memo.wasStarted){resetIdleSince();}else{if(event.memo.reasonCode==SD.ReasonCodes.BUSY){scope.outstandingInvites++;}
scope.waitingTimeChanged();}
if(scope.pauseRequested){scope.state=SD.PairingController.states.PAUSED;}else{scope.state=SD.PairingController.states.IDLE;seek.bind(this).delay((event.memo.reasonCode==SD.ReasonCodes.BUSY?this.getBusyWaitingTime():this.getNonBusyWaitingTime())/1000,null);}}else{SD.log("PC ERROR, some other user dated here!:)");}}.bind(this));SD.Event.observe(user,SD.User.Events.USER_CHANGED,function(event){reset();seek();});};SD.PairingController.prototype.areYouBusy=function(romeo,token,rejectReason){if(SD.PickDate.isActive()){return 1;}
var busy=-1;var mightDate=this.user.mightDate(romeo);var tokenMatches=(!token||(token==this.user.token));var p2pCheck=true;if(mightDate&&tokenMatches&&p2pCheck){this.outstandingInvites--;if(this.amIdle()){this.state=SD.PairingController.states.BUSY;busy=0;}else{romeo.idleSince=new Date().getTime();SD.log("adding "+romeo.username+" to to-be-fetched list");this.pendingRomeos.push(romeo);busy=1;}
this.waitingTimeChanged();}
if(rejectReason){if(!mightDate)
rejectReason.reason="mightDate";else if(!tokenMatches)
rejectReason.reason="tokenMatches";}
return busy;};SD.PairingController.prototype.getBusyWaitingTime=function(){return SD.Config.waitTimes.busy;};SD.PairingController.prototype.getNonBusyWaitingTime=function(){return SD.Config.waitTimes.nonBusy;};SD.PairingController.timeBetweenMatchRequests=function(){return SD.Config.waitTimes.seekInterval;};SD.PairingController.states={IDLE:0,BUSY:1,PAUSED:2};SD.PairingController.prototype.amIdle=function(){return this.state==SD.PairingController.states.IDLE;};SD.PairingController.prototype.waitingTimeChanged=function(){};SD.PairingController.prototype.clearMatched=function(){};var Queue=function(fcn){this.fcn=fcn;this.content=[];this.length=0;};Queue.prototype.shift=function(){var entry=this.content.shift();this.length=this.content.length;return entry;};Queue.prototype.push=function(entry){for(var i=0;i<this.content.length;i++){if(this.content[i]==entry){return;}}
this.content.push(entry);this.length=this.content.length;this.content.sort(this.fcn);};
SD.Charts={isReadyToRender:false,renderers:[],renderAll:function(){SD.Charts.renderers.each(function(e){e();});SD.Charts.isReadyToRender=true;}}
SD.Date={app:null,isDating:false,config:{showExtendDateButton:true},_startedDates:{},_successfulDates:{},_ajaxListeners:{},_pendingAjaxRequests:[],_ajaxListenerCounter:0,_currentDate:null,_linkRegex:/\b(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&amp;?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?\b/g,_lastSentTyping:{},_lastReceivedTyping:{},_myVotes:{},_receivedVotes:{},_messageBuffer:'',log:function(){},debug:function(){},REASON_CODES:{TIME_FINISHED:"timeFinished",USER_REPORTED:"userReported",USER_LEFT:"userLeft",USER_DISCONNECTED:"userDisconnected"},CHAT_TYPE:{TEXT:'text',ICE_BREAKER:'iceBreaker',FAKE:'fake'},VOTES:{YES:'Yes',NO:'No'},SEND_TYPING_INTERVAL:3000,initialize:function(appName){this.app=$(appName);SD.Event.observe(null,SD.Date.Events.START_DATE,SD.Date.onDateStart);SD.Event.observe(null,SD.Date.Events.DATE_OVER,SD.Date.onDateOver);SD.log('initialize:'+appName);$A(SD.Config.mmsRegistries).each(function(host){SD.Date.app.loadPolicyFile(host+"/crossdomain.xml");});SD.Date.setUniqueId();var fnc;while((fnc=this._pendingAjaxRequests.shift())){this.callAjax(fnc.url,fnc.params,fnc.method,fnc.callBackFunc);}},shouldAcceptEvent:function(e){return this._currentDate&&this._currentDate.panelId==e.memo.panelId;},setUniqueId:function(){try{var uniqueId=SD.Date.app.getPersistentValue('uniqueId');if(!uniqueId){uniqueId=SD.Model.getMyself().uid+'_'+Math.floor(Math.random()*1000000000);SD.Date.app.setPersistentValue('uniqueId',uniqueId);SD.Cookie.create('uniqueId',uniqueId);}else if(uniqueId!=SD.Cookie.read('uniqueId')){SD.Cookie.create('uniqueId',uniqueId);}}catch(e){}},Date:function(){SD.log(arguments);return this;},onDateStart:function(event){conf=event.memo;if(!conf.otherUser){return;}
SD.log("||dateStarts:"+conf.otherUser.uid);SD.Date._startedDates[conf.otherUser.uid]=true;SD.Model.getMyself().rememberDating(conf.otherUser);},onDateOver:function(event){if(event.memo.otherUser&&event.memo.reasonCode&&event.memo.reasonCode==SD.ReasonCodes.TIME_FINISHED){SD.log("||dateSuccessfuly ends:"+event.memo.otherUser);SD.Date._successfulDates[event.memo.otherUser.uid]=true;}
if(event.memo.wasStarted){SD.User.datedWantedDate(event.memo.otherUser);}},onUserFetched:function(event){return;},validateMessage:function(me,other,text,isMeSender){var panelId=this._getUserPanelId(other,true);var isUserInitiatedDate=SD.UserInitiatedDate.isActiveDate(panelId);if(!isMeSender){if(!other.is_premium&&!SD.UserInputFilter.isValid(text)){return false;}}else{this._messageBuffer+=text;if(!me.is_premium&&!SD.UserInputFilter.isValid(this._messageBuffer)){this._messageBuffer='';SD.UserInputFilter.trackFilter(SD.UserInputFilter.CHAT);SD.ExperimentManager.recordOutput('UserInputFilteredFromDateOutput',1,1);return false;}}
return true;},putChatMessage:function(message){if(this._currentDate.visible==false){this.popupDateUI(false);this.putChatMessage.bind(this).delay(1,message);}
if(message.type==SD.Date.CHAT_TYPE.ICE_BREAKER){message.template=SD.UI.Dating.MessagePaneTemplates.ENUM.ICE_BREAKER_MESSAGE;this._currentDate.lastMessageBy=null;this._currentDate.ui.putMessage(this._currentDate.panelId,message);}else if(message.type==SD.Date.CHAT_TYPE.TEXT){var isMeSender=(message.meOther=='me');var isValid=this.validateMessage(SD.Model.getMyself(),this._currentDate.user,message.message,isMeSender);if(!isMeSender&&!isValid){return;}
message.message=message.message.escapeHTML().gsub('\n','<br/>');message.time=this._currentDate.ui.getPanelById(this._currentDate.panelId).countdownClock.getFormattedTime();message.template=this._currentDate.lastMessageBy==message.meOther?SD.UI.Dating.MessagePaneTemplates.ENUM.CHAT_MESSAGE_CONT:SD.UI.Dating.MessagePaneTemplates.ENUM.CHAT_MESSAGE;this._currentDate.lastMessageBy=message.meOther;SD.Date._currentDate.ui.putMessage(this._currentDate.panelId,message);if(message.meOther!='me'){try{SD.Date.app.playMessageSound();}catch(e){}
this.clearStaticMessage();SD.Favicon.animateTitle([this._currentDate.user.username+": ",message.message],1000);}}else if(message.type==SD.Date.CHAT_TYPE.FAKE){message.template=SD.UI.Dating.MessagePaneTemplates.ENUM.PLAIN_TEXT_MESSAGE;this._currentDate.lastMessageBy=null;this._currentDate.ui.putMessage(this._currentDate.panelId,message);}else{this._currentDate.ui.putMessage(this._currentDate.panelId,message);}
this._currentDate.messageHistory.push(message);if(message.type==SD.Date.CHAT_TYPE.ICE_BREAKER||message.type==SD.Date.CHAT_TYPE.TEXT){var sender=message.meOther=='me'?SD.Model.getMyself():this._currentDate.user;var receiver=message.meOther=='me'?this._currentDate.user:SD.Model.getMyself();SD.Chat.addToHistoryFromDate(sender,receiver,message.message);}},didBothType:function(other){if(!this._currentDate||!other||this._currentDate.user.uid!=other.uid){return null;}
var msgs=this._currentDate.messageHistory;var meTyped=false;var otherTyped=false;msgs.each(function(msg){if(msg.type==SD.Date.CHAT_TYPE.TEXT){if(msg.meOther=='me'){meTyped=true;}else if(msg.meOther=='other'){otherTyped=true;}}});return meTyped&&otherTyped;},getUserDatePreferences:function(event){},wasDateSuccessful:function(otherUser){return SD.Date._successfulDates[otherUser.uid];},wasDateStarted:function(event){return SD.Date._startedDates[otherUser.uid];},startDate:function(configuration){this.isDating=true;var myUser=configuration.myUser;var otherUser=configuration.otherUser;configuration.myUser=myUser;configuration.otherUser=otherUser;SD.log("skipped:"+SD.Date.Events.DATING_APP_INITIALIZED);SD.Date._currentDate={ui:null,panelId:null,user:null,configuration:configuration,startedAt:(new Date).getTime(),iAmStreaming:false,partnerIsStreaming:false,voting:false,messageHistory:[]};var doStart=function(user){SD.log(user.username+':'+user.image_url);SD.Date._currentDate.user=user;SD.Event.fire(null,SD.Date.Events.START_DATE,configuration);SD.log('startDating completed');}
if(configuration.otherUser.fetched){doStart(configuration.otherUser);}else{SD.User.fetch(SD.User.externalize(otherUser),doStart);}},generateEndDateReason:function(reason,user){var pronoun=user.sex=="M"?'he':'she';switch(reason){case'type_mismatch':return pronoun+" doesn't feel like speeddating now";case'photo_or_not_enough_profile':return pronoun+" wants you to upload more photos and add more profile info!";case'not_ready':return pronoun+" doesn't feel like speeddating now";case'prefer_verified_member':return pronoun+" prefers SpeedVerified&#0153; members";case'other':return pronoun+" doesn't feel like speeddating now";case'userDisconnected':return pronoun+" lost connection";case'no_response':return" you did not respond";case'no_asl_match':return pronoun+" prefers to meet someone closer in age or location";case'photo_issue':return pronoun+" wants you to upload more photos!";case'not_enough_profile':return pronoun+" wants you to add to your profile!";case'scammer':return pronoun+" doesn't feel like speeddating now";default:return pronoun+" doesn't feel like speed dating now";}},stopDate:function(reasonCode,reason,who){SD.Date.log('stopDate',reasonCode,reason,who);SD.Event.fire(null,SD.Date.Events.DATE_INIT_END,null);if(!this._currentDate||SD.Date._currentDate.voting)return;if(!this._currentDate.visible){this._currentDate=null;SD.ExperimentManager.recordOutput('DateDidNotShowAnEarlyEndingDateOutput',1,1);return;}
switch(reasonCode){case this.REASON_CODES.TIME_FINISHED:SD.Date.log('stopDate: Time finished for the other person!!!');this._currentDate.ui.getPanelById(this._currentDate.panelId).countdownClock.stop();this.showVoting();break;case this.REASON_CODES.USER_LEFT:this._currentDate.ui.getPanelById(this._currentDate.panelId).countdownClock.stop();if(who=='me'){if(!SD.Model.getMyself().is_premium){var me=SD.Model.getMyself();this._currentDate.ui.showPostDateDialog(this._currentDate.panelId,{uid:me.uid,name:me.username,pronoun:me.sex=="M"?"he":"she",pronoun_passive:me.sex=="M"?"him":"her",isMyself:true});}else{this.closeDatePopup();}}else if(SD.Model.getMyself().is_premium){this._currentDate.ui.showPostDateDialogSimple(this._currentDate.panelId,{name:this._currentDate.user.username,reasonText:this.generateEndDateReason(reason,this._currentDate.user),pronoun:this._currentDate.user.sex=="M"?"he":"she",pronoun_passive:this._currentDate.user.sex=="M"?"him":"her"});}else{this._currentDate.ui.showPostDateDialog(this._currentDate.panelId,{uid:this._currentDate.user.uid,name:this._currentDate.user.username,pronoun:this._currentDate.user.sex=="M"?"he":"she",pronoun_passive:this._currentDate.user.sex=="M"?"him":"her"});}
break;case this.REASON_CODES.USER_DISCONNECTED:this._currentDate.ui.getPanelById(this._currentDate.panelId).countdownClock.stop();if(who=='me'){this.closeDatePopup();}else{if(SD.Model.getMyself().is_premium){this._currentDate.ui.showPostDateDialogSimple(this._currentDate.panelId,{name:this._currentDate.user.username,reasonText:this.generateEndDateReason(reason,this._currentDate.user),pronoun:this._currentDate.user.sex=="M"?"he":"she",pronoun_passive:this._currentDate.user.sex=="M"?"him":"her"});}else{this._currentDate.ui.showPostDateDialog(this._currentDate.panelId,{uid:this._currentDate.user.uid,name:this._currentDate.user.username,pronoun:this._currentDate.user.sex=="M"?"he":"she",pronoun_passive:this._currentDate.user.sex=="M"?"him":"her"});}}
break;case this.REASON_CODES.USER_REPORTED:this._currentDate.ui.getPanelById(this._currentDate.panelId).countdownClock.stop();if(who=='me'){this.closeDatePopup();SD.UIController.infoMessage('We take misbehaviour on SpeedDate seriously. Thank you for reporting. We\'ll find you another date soon.',3);}else{this._currentDate.ui.showPostDateDialogSimple(this._currentDate.panelId,{name:this._currentDate.user.username,pronoun:this._currentDate.user.sex=="M"?"he":"she",pronoun_passive:this._currentDate.user.sex=="M"?"him":"her"});}
break;}},insertBriefMatchInfo:function(){if(!this._currentDate){return;}
var other_id=this._currentDate.user.uid;new Ajax.Request(SD.NavUtils.link('ajax','get_member_info_match_messages'),{method:'get',parameters:{other_id:other_id},onSuccess:function(e){if(e&&e.responseJSON&&e.responseJSON.result){var matches=e.responseJSON.matches;var content="<ul>";var foundMatches=0;var addToContent=function(arr){arr.each(function(match){foundMatches++;content+="<li>"+match+"</li>";});}
var pronoun=this._currentDate.user.sex=='M'?'He':'She';if(matches['you_match']&&matches['you_match'].length){content+="<li><u>"+pronoun+" likes</u></li>"
addToContent(matches['you_match']);}
if(matches['flirtee_matches']&&matches['flirtee_matches'].length){content+="<li><u>You like</u></li>"
addToContent(matches['flirtee_matches']);}
if(matches['mutual']&&matches['mutual'].length){content+="<li><u>You and "+this._currentDate.user.username+" have in common</u></li>"
addToContent(matches['mutual']);}
content+="</ul>";if(this._currentDate&&this._currentDate.user.uid==other_id&&foundMatches){this._currentDate.ui.putMessage(this._currentDate.panelId,{template:SD.UI.Dating.MessagePaneTemplates.ENUM.BRIEF_INFO_MSG,similarities:content});SD.ExperimentManager.recordOutput('ShowedSomeSimilarityAtDateBeginningOutput',1,foundMatches);}else{SD.ExperimentManager.recordOutput('CouldNotShowAnySimilarityAtDateBeginningOutput');}}}.bind(this)});},getPremiumUrl:function(tc){return'javascript:void(SD.UIController.upgradeMyself({tc:'+tc+', ti:'+this._currentDate.user.uid+'}))';},triedToAddOneMinute:function(){this._currentDate.ui.putMessage(this._currentDate.panelId,{template:SD.UI.Dating.MessagePaneTemplates.ENUM.INFO_MESSAGE,message:this._currentDate.user.username+' wants to chat longer with you! Click <span class="upgrade-link-small">+1&nbsp;Minute</span> button below to extend the date.'});},addOneMinute:function(who){this._currentDate.ui.getPanelById(this._currentDate.panelId).countdownClock.initialTime+=60;this._currentDate.ui.putMessage(this._currentDate.panelId,{template:SD.UI.Dating.MessagePaneTemplates.ENUM.INFO_MESSAGE,message:who+' extended the date by 1 minute.'});},receivedCameraState:function(state){SD.Date.log("received camera state:"+state);if(state=='on'){this._currentDate.partnerIsStreaming=true;if(this._currentDate.iAmStreaming){SD.Date._currentDate.ui.getWebcamDom(SD.Date._currentDate.panelId).subscribeStream(SD.Date._currentDate.configuration.communication.DateHost,'stream'+SD.Date._currentDate.user.uid);SD.ExperimentManager.recordOutput('WebcamTwoWayVideoChat',1,1);}else{this._currentDate.lastMessageBy=null;this._currentDate.ui.showWebcamPane(this._currentDate.panelId,function(){SD.Date.log('onReady');SD.Date._currentDate.ui.getWebcamDom(SD.Date._currentDate.panelId).subscribeStream(SD.Date._currentDate.configuration.communication.DateHost,'stream'+SD.Date._currentDate.user.uid);});this._currentDate.ui.putMessage(this._currentDate.panelId,{from:this._currentDate.user.username,template:SD.UI.Dating.MessagePaneTemplates.ENUM.VIDEO_INVITATION});}
SD.ExperimentManager.recordOutput('WebcamReceivedVideo',1,1);}else{this._currentDate.partnerIsStreaming=false;if(!this._currentDate.iAmStreaming){this._currentDate.ui.hideWebcamPane(this._currentDate.panelId);}else{SD.Date._currentDate.ui.getWebcamDom(this._currentDate.panelId).hideStream();}}},subscribe:function(){this.closeDatePopup();SD.UIController.upgradeMyself({tc:SD.TrackingCodes.trigger.communication.date.find_out_why_date_ended._value,ti:this._currentDate.user.uid,openInNewPage:false});},onTimeFinished:function(panelId){if(!this._currentDate||this._currentDate.panelId!=panelId){return;}
this.showVoting();var request={reasonCode:this.REASON_CODES.TIME_FINISHED,reason:'Time Finished',who:'me'}
SD.Event.fire(null,SD.Date.Events.END_DATE_REQUESTED,request);},showVoting:function(event){if(this._currentDate&&!this._currentDate.voting){this._currentDate.voting=true;this._currentDate.ui.showPostDateAdvancedDialog(this._currentDate.panelId,{uid:this._currentDate.user.uid,name:this._currentDate.user.username,pronoun:(this._currentDate.user.sex=='M'?'he':'she'),premium_url:this.getPremiumUrl(SD.TrackingCodes.trigger.communication.date.find_out_why_date_ended._value),link_target:'_blank'});}},vote:function(myVote){this.dateEnded({user:SD.Model.getMyself(),otherUser:this._currentDate.user,reasonCode:SD.Date.REASON_CODES.TIME_FINISHED,reason:'Time finished',endedByMe:true,myVote:myVote,wasStarted:true});this.closeDatePopup();},playMessageSound:function(){},updatePartnersStreamingState:function(state){},callAjax:function(url,params,method,callBackFunc){SD.log("calling ajax:"+url);if(!SD.Date.app){this._pendingAjaxRequests.push({url:url,params:params,method:method,callBackFunc:callBackFunc});return;}
this._ajaxListeners[this._ajaxListenerCounter]=callBackFunc;SD.Date.app.callAjax(this._ajaxListenerCounter++,url,params,method);},DateInitialized:function(){SD.log("DateInitialized fired:"+SD.Date.Events.DATING_APP_INITIALIZED);SD.Event.fireDeferred(null,SD.Date.Events.DATING_APP_INITIALIZED);},getChatContent:function(){return"";},updateMyStreamingState:function(state){SD.Event.fire(null,SD.Date.Events.MY_STREAMING_STATE_CHANGED,state);},requestEndDate:function(event){if(!this.shouldAcceptEvent(event)){return;}
this.log('requestEndDate',event.memo.data);request={reasonCode:this.REASON_CODES.USER_LEFT,reason:event.memo.data.reason,who:'me'}
SD.Event.fire(null,SD.Date.Events.END_DATE_REQUESTED,request);},reportAbuse:function(event){if(!this.shouldAcceptEvent(event)){return;}
SD.log('reportAbuse',event.memo.data);this.dateEndedNormally();this.reportMember(this._currentDate.user.uid,event.memo.data.reason,'chatHistory');request={reasonCode:this.REASON_CODES.USER_REPORTED,reason:event.memo.data.reason,who:'me'}
SD.Event.fire(null,this.Events.END_DATE_REQUESTED,request);},dateEndedNormally:function(){this.dateEnded({user:SD.Model.getMyself(),otherUser:this._currentDate.user,wasStarted:true});},submitDateEndedReason:function(request){new Ajax.Request(SD.NavUtils.link('ajax','submit_date_ended_reason'),{method:'get',evalJSON:true,parameters:{other_member_id:request.otherMemberId,reason_code:request.reasonCode,other_text:request.otherText,control_id:SD.Model.control_id,memberid:SD.Model.getUserId()},onSuccess:function(result){SD.log("user ended the date, and reason is saved");}});},dateEnded:function(result){SD.Date.log('dateEnded:',arguments);this.isDating=false;if(result.user){result.user=SD.User.internalize(result.user);}
if(result.otherUser){result.otherUser=SD.User.internalize(result.otherUser);}
SD.Event.fire(result.user,SD.Date.Events.DATE_OVER,result);},sendChat:function(event){if(!this.shouldAcceptEvent(event)){return;}
SD.log(event);this.putChatMessage({meOther:'me',from:'Me',message:event.memo.message,type:SD.Date.CHAT_TYPE.TEXT});SD.Event.fire(null,SD.Date.Events.SEND_DATE_CHAT_REQUESTED,{from:event.memo.from,message:event.memo.message,type:SD.Date.CHAT_TYPE.TEXT});},sendIceBreaker:function(event){if(!this.shouldAcceptEvent(event)){return;}
SD.log(event);this.putChatMessage({meOther:'me',from:'Me',message:event.memo.message,type:SD.Date.CHAT_TYPE.ICE_BREAKER});SD.Event.fire(null,SD.Date.Events.SEND_DATE_CHAT_REQUESTED,{from:event.memo.from,message:event.memo.message,type:SD.Date.CHAT_TYPE.ICE_BREAKER});},startTyping:function(){SD.log("START TYPING");SD.Event.fire(null,SD.Date.Events.TYPING_STATE_CHANGED,{isTyping:1});},stopTyping:function(){SD.log("STOP TYPING");SD.Event.fire(null,SD.Date.Events.TYPING_STATE_CHANGED,{isTyping:0});},onAjaxData:function(key,result){result=result&&result.evalJSON();SD.log("ajax data returned:"+result);if(this._ajaxListeners[key]){this._ajaxListeners[key](result);delete this._ajaxListeners[key];}},onAjaxError:function(key,error){SD.log("ajax error: "+error);delete this._ajaxListeners[key];},reportMember:function(otherUserId,reason,chatHistory){var user=SD.User.get(otherUserId);SD.User.reportMember(user,reason,chatHistory,'Date');},saveChatHistory:function(userId,otherUserId,chatHistory,remainingTime){},isShowingDatePopup:false,createPopup:function(){this.win=new SD.Window('dating-app-container',{hideMethod:SD.Window.OFFSCREEN_HIDE,groupId:'date',className:"dating-window win-skin1 exp2532",onBeforeOpen:function(){this.win.domContent.removeClassName("win-content-hack");this.win.domContent.addClassName("win-content");this.win.resizeTo(431);Prototype.Browser.Opera&&this.win.repaint.bind(this.win,this.win.domContent).delay(0.6);Prototype.Browser.FF3&&this.overflowElementsHack();}.bind(this),onBeforeHide:function(forceHide){if(forceHide){return;}
try{this.Date('onClose').onEndDate();}
catch(e){}
throw this.win.Events.STOP_DEFAULT_ACTION;}.bind(this),onAfterClose:function(){Prototype.Browser.FF3&&this.overflowElementsHack(true);}.bind(this),shim:(Prototype.Browser.FF3?false:true)});var _this=this;Prototype.Browser.FF3&&(this.win.onAfterDrag=function(){$$('.messageoutput').each(function(el){if(SD.Utils.Position.areIntersecting(el,_this.win.dom)){_this._fixOverflow(el,false);}
else{_this._fixOverflow(el,true);}});}.bind(this.win));},popupForDate:function(user,config){SD.Date.log('popupForDate',user);this.isShowingDatePopup&&this.closeDatePopup();this.isShowingDatePopup=true;this._currentDate.lastMessageBy=null;this._currentDate.user=user;this._currentDate.ui=SD.UI.DateUI.getUI();this._currentDate.visible=false;if(config.popupLater){this.popupDateUI.bind(this).delay(20,false);}else{this.popupDateUI(true);}},popupDateUI:function(showPreDate){if(!this._currentDate||this._currentDate.visible){return;}
this._currentDate.visible=true;var user=this._currentDate.user;SD.Date.app.playDatingSound();this._currentDate.panelId=this._currentDate.ui.openPanel({meta:{user:user},dateHeader:{name:user.username.truncate(25),age:user.age,location:SD.User.renderLocation(user),distance:SD.User.renderDistance(user)},pictureGallery:{_url:SD.NavUtils.link('profile','view_images',{displayType:'ajax',uid:user.uid})},dateProfile:{_url:SD.NavUtils.link('profile','view_profile',{displayType:'ajax',uid:user.uid})},dateToolbar:{isPremium:SD.Model.getMyself().is_premium,showExtendDateButton:true},preferredAsl:{min_age:SD.Model.getMyself().min_age,max_age:SD.Model.getMyself().max_age},tabData:{text:user.username.truncate(12)}});if(showPreDate){this._currentDate.ui.showPreDateDialog(this._currentDate.panelId,{name:this._currentDate.user.username});}
this.insertBriefMatchInfo();(function(){if(this._currentDate.ui.getPanelById(this._currentDate.panelId)){this._currentDate.ui.getPanelById(this._currentDate.panelId).countdownClock.setup(SD.Date._currentDate.startedAt,SD.Date._currentDate.configuration.duration,'m:ss',this.onTimeFinished.bind(this));this._currentDate.ui.getPanelById(this._currentDate.panelId).countdownClock.start();}
SD.Event.fire(null,SD.Date.Events.DATE_INIT_END,null);}).bind(this).delay(showPreDate?5:0);(function(){if(!this._currentDate){return;}
if(this._currentDate.messageHistory.length==0){this.putChatMessage({type:SD.Date.CHAT_TYPE.FAKE,message:'You\'re now speed dating with '+this._currentDate.user.username+', '+this._currentDate.user.age+'. Say hi!'})}
SD.Date._currentDate.ui.hideBanner(this._currentDate.panelId);}).bind(this).delay(showPreDate?8:2);this._currentDate.viewConstructedAt=new Date().getTime();},getTimeAfterUIConstruct:function(){if(!this._currentDate||!this._currentDate.viewConstructedAt){return-1;}
return(new Date()).getTime()-this._currentDate.viewConstructedAt;},closeDatePopup:function(){SD.Event.fire(null,SD.Date.Events.DATE_INIT_END,null);if(!this.isShowingDatePopup)return;this.log('closeDatePopup');if(this._currentDate){SD.User.saveChatHistory(SD.Model.getMyself().uid,this._currentDate.user.uid,Object.toJSON(this._currentDate.messageHistory),this._currentDate.ui.getPanelById(this._currentDate.panelId).countdownClock.time);this._currentDate.ui.getPanelById(this._currentDate.panelId).countdownClock.stop();this._currentDate.ui.closePanel(this._currentDate.panelId);}
this.isShowingDatePopup=false;},overflowElementsHack:function(toRestore){[$('buddyboxDiv'),$('buddylist'),$$('.details')[0],$$('.profile-body'),$$('.messageoutput')].flatten().compact().each(function(el){this._fixOverflow(el,toRestore)},this);},_fixOverflow:function(el,toRestore){el.oldOverflowX=window.getComputedStyle(el,'overflowX')['overflowX'];el.oldOverflowY=window.getComputedStyle(el,'overflowY')['overflowY'];el.style.overflowX=toRestore?'auto':'inherit';el.style.overflowY=toRestore?'auto':'inherit';},cleanTyping:function(uid){var now=new Date().getTime();var last=this._lastReceivedTyping[uid];if(last+5000>now){return;}
this.clearStaticMessage();},clearStaticMessage:function(){this._currentDate&&this._currentDate.ui.clearStaticMessage(this._currentDate.panelId);},sendVote:function(otherUser,vote){this._myVotes[otherUser.uid]=vote;new Ajax.Request(SD.NavUtils.link('ajax','vote'),{method:'post',parameters:{other_memberid:otherUser.uid,result:vote},onSuccess:function(e){if(e&&e.responseJSON&&e.responseJSON.result){}else{}}.bind(this),onFailure:function(e){}.bind(this)});SD.RPC.call(otherUser,"SD.Date.voteReceived",{vote:vote});this.isDateDecided(otherUser);},isMatch:function(other){return this._myVotes[other.uid]==this.VOTES.YES&&this._receivedVotes[other.uid]==this.VOTES.YES;},didOtherVote:function(other){return this._receivedVotes[other.uid]==this.VOTES.YES||this._receivedVotes[other.uid]==this.VOTES.NO;},isDateDecided:function(other){if(this._myVotes[other.uid]&&this._receivedVotes[other.uid]){SD.Event.fire(null,this.Events.RESULT_RECEIVED,{user:SD.Model.getMyself(),otherUser:other,result:this.isMatch(other)?'MATCH':'NOMATCH'});}},voteReceived:function(from,args){this._receivedVotes[from.uid]=args.vote;this.isDateDecided(from);},initDateInServer:function(otherUser){if(!otherUser||otherUser.isFacebookUser()){return;}
new Ajax.Request(SD.NavUtils.link('ajax','initdate'),{method:'post',parameters:{other_memberid:otherUser.uid,i_have_photo:SD.Model.getMyself().has_photo},onSuccess:function(e){if(e&&e.responseJSON&&e.responseJSON.result){}else{}}.bind(this),onFailure:function(e){}.bind(this)});},endDateOnServer:function(otherUser){if(!otherUser||otherUser.isFacebookUser()){return;}
new Ajax.Request(SD.NavUtils.link('ajax','enddate'),{method:'post',parameters:{other_memberid:otherUser.uid},onSuccess:function(e){if(e&&e.responseJSON&&e.responseJSON.result){}else{}}.bind(this),onFailure:function(e){}.bind(this)});},deleteDateOnServer:function(otherUser){new Ajax.Request(SD.NavUtils.link('ajax','delete_date'),{method:'post',parameters:{other_memberid:otherUser.uid},onSuccess:function(e){if(e&&e.responseJSON&&e.responseJSON.result){}else{}}.bind(this),onFailure:function(e){}.bind(this)});},Events:{DATE_OVER:'dating:dateover',START_DATE:'dating:startdate',SHOW_PROFILE:'dating:showprofile',MY_STREAMING_STATE_CHANGED:'dating:mystreamingstatechanged',END_DATE_REQUESTED:'dating:enddaterequested',SEND_DATE_CHAT_REQUESTED:'dating:senddatechatrequested',DATING_APP_INITIALIZED:'dating:Dateinitialized',CLOSE_DATING_WINDOW:'dating:closedatingwindow',RESULT_RECEIVED:"dating:result_received",DATE_INIT_START:"dating:initialization_started",DATE_INIT_END:"dating:initialization_ended"}};SD.DatingApp=SD.Date;
SD.Gift={UI:function(e){var giftMessage='Add a gift to get more replies!';if(SD.Model&&!SD.Model.getMyself().is_premium){giftMessage=giftMessage+' (Upgrade required)';}
$(e).update(SPAN({},giftMessage));$(e).insert(this.updateddiv=DIV({}));this.giftId=0;}};SD.Gift.UI.prototype.reset=function(){this.giftId=0;$(this.updateddiv).select("td img").each(function(el){el.removeClassName("sd-gift-selected");el.addClassName("sd-gift-not-selected");});};SD.Gift.UI.prototype.selectgift=function(id,img){this.reset();this.giftId=id;if($("gift_id")){$("gift_id").value=id;}
$(img).addClassName("sd-gift-selected");$(img).removeClassName("sd-gift-not-selected");};SD.Gift.UI.prototype.loadgifts=function(pagenum){SD.Gift.currentUI=this;(new Ajax.Request(SD.NavUtils.link('ajax','getgifts'),{method:'get',parameters:{"p":pagenum,"memberid":SD.Model.getMyself().uid,"platform_id":SD.UIController.platform_id},onSuccess:function(transport){$(SD.Gift.currentUI.updateddiv).update(transport.responseText);}}));};SD.Gift.UI.prototype.switchgift=function(el){this.reset();Effect.toggle(this.updateddiv.up().id,'blind',{duration:0.5});if($("gift_id")){$("gift_id").value=0;}
if($(el).value=="Add Gift"){$(el).value="Remove Gift";this.loadgifts(1);}
else{$(el).value="Add Gift";}};var loadgifts=function(page){SD.Gift.currentUI.loadgifts(page);};var selectgift=function(giftID,img){SD.Gift.currentUI.selectgift(giftID,img);};
SD.ImageUploader=function(formElement,callback){formElement=$(formElement);if(!formElement.match("form")){return;}
var name="imageuploader_"+Math.ceil(Math.random()*10000);var container=new Element("div",{"class":"autouploader-iframe"});container.innerHTML="<iframe class='autouploader-iframe' id='"+name+"' name='"+name+"'></iframe>";formElement.insert(container);var innerframe=$(name);formElement.target=name;function innercallback(){Ajax.activeRequestCount--;innerframe.stopObserving("load",innercallback);if(callback){callback(innerframe.contentWindow.document.body.innerHTML);}}
formElement.observe("submit",function(){Ajax.activeRequestCount++;innerframe.observe("load",innercallback);});};
var xmlNode=function(name,attrs,children){this.name=name;this.attrs=attrs||{};this.children=children;};xmlNode.prototype.escape=function(s){return s&&s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;");};xmlNode.prototype.toString=function(){var rv="<"+this.name;for(var k in this.attrs){if(this.attrs.hasOwnProperty(k)){rv+=" "+k+'="'+this.escape(this.attrs[k])+'"';}}
if(this.children){rv+=">";for(var i=0;i<this.children.length;i++){rv+=this.children[i].toString();}
rv+="</"+this.name+">";}else{rv+="/>";}
return rv;};
SD.Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(input){var output="";var chr1,chr2,chr3,enc1,enc2,enc3,enc4;var i=0;input=SD.Base64._utf8_encode(input);while(i<input.length){chr1=input.charCodeAt(i++);chr2=input.charCodeAt(i++);chr3=input.charCodeAt(i++);enc1=chr1>>2;enc2=((chr1&3)<<4)|(chr2>>4);enc3=((chr2&15)<<2)|(chr3>>6);enc4=chr3&63;if(isNaN(chr2)){enc3=enc4=64;}else if(isNaN(chr3)){enc4=64;}
output=output+
this._keyStr.charAt(enc1)+this._keyStr.charAt(enc2)+
this._keyStr.charAt(enc3)+this._keyStr.charAt(enc4);}
return output;},decode:function(input){var output="";var chr1,chr2,chr3;var enc1,enc2,enc3,enc4;var i=0;input=input.replace(/[^A-Za-z0-9\+\/\=]/g,"");while(i<input.length){enc1=this._keyStr.indexOf(input.charAt(i++));enc2=this._keyStr.indexOf(input.charAt(i++));enc3=this._keyStr.indexOf(input.charAt(i++));enc4=this._keyStr.indexOf(input.charAt(i++));chr1=(enc1<<2)|(enc2>>4);chr2=((enc2&15)<<4)|(enc3>>2);chr3=((enc3&3)<<6)|enc4;output=output+String.fromCharCode(chr1);if(enc3!=64){output=output+String.fromCharCode(chr2);}
if(enc4!=64){output=output+String.fromCharCode(chr3);}}
output=SD.Base64._utf8_decode(output);return output;},_utf8_encode:function(string){string=string.replace(/\r\n/g,"\n");var utftext="";for(var n=0;n<string.length;n++){var c=string.charCodeAt(n);if(c<128){utftext+=String.fromCharCode(c);}
else if((c>127)&&(c<2048)){utftext+=String.fromCharCode((c>>6)|192);utftext+=String.fromCharCode((c&63)|128);}
else{utftext+=String.fromCharCode((c>>12)|224);utftext+=String.fromCharCode(((c>>6)&63)|128);utftext+=String.fromCharCode((c&63)|128);}}
return utftext;},_utf8_decode:function(utftext){var string="";var i=0;var c=c1=c2=0;while(i<utftext.length){c=utftext.charCodeAt(i);if(c<128){string+=String.fromCharCode(c);i++;}
else if((c>191)&&(c<224)){c2=utftext.charCodeAt(i+1);string+=String.fromCharCode(((c&31)<<6)|(c2&63));i+=2;}
else{c2=utftext.charCodeAt(i+1);c3=utftext.charCodeAt(i+2);string+=String.fromCharCode(((c&15)<<12)|((c2&63)<<6)|(c3&63));i+=3;}}
return string;}}
SD.Track={_record:function(label){SD.Track._recordObject(label);},_recordObject:function(label,data){var url=SD.Config.siteURL+'/tracking.php?__label='+label+'&__browser='+Prototype.Browser.getName()+'&__platform='+SD.Config.platform.name+(!data?'':'&'+Object.toQueryString(data));var img=new Image();img.src=url;},_recordEvent:function(label,event){SD.Track._recordObject(label,event.memo);},_recordEndDate:function(event){SD.Track._recordObject('DW_DateResult',event.memo);switch(event.memo.reason){case SD.ReasonCodes.TIME_FINISHED:SD.ExperimentManager.recordOutput('DateTimeFinishedOutput',1,1);if(this._shouldDeleteDate(event.memo.other,true)){SD.User.deleteDate(event.memo.other);}
break;case SD.ReasonCodes.USER_REPORTED:if(event.memo.who!='me'){SD.ExperimentManager.recordOutput('DateReportedByPartnerOutput',1,1);}else{SD.ExperimentManager.recordOutput('DateReportedByMeOutput',1,1);}
break;case SD.ReasonCodes.USER_LEFT:if(event.memo.who!='me'){SD.ExperimentManager.recordOutput('DateEndedByPartnerOutput',1,1);}else{SD.ExperimentManager.recordOutput('DateEndedByMeOutput',1,1);}
break;case SD.ReasonCodes.USER_DISCONNECTED:if(event.memo.who!='me'){SD.ExperimentManager.recordOutput('DateDisconnectedByPartnerOutput',1,1);}else{SD.ExperimentManager.recordOutput('DateDisconnectedByMeOutput',1,1);}
if(event.memo.other&&this._shouldDeleteDate(event.memo.other,false)){SD.User.deleteDate(event.memo.other);}
break;}},_shouldDeleteDate:function(other,checkBothTyped){if(checkBothTyped){return other&&SD.Date.didBothType(other)===false;}
return true;},initialize:function(){SD.Event.observe(null,SD.DatingController.Events.SESSION_TERMINATED,SD.Track._recordEndDate.bind(this));},recordRejectedDate:function(reason){}};
if(typeof SD=='undefined'){var SD={};};SD.Signup=new function(){var nPlan=null;var oMenu=null;var aSavings=['Save 50%','Save 20%',''];function createMenu(){oMenu=UL({'class':'signup-plans-menu'},SD.Config.subscriptionPlans.collect(function(o,n){var oElement=LI({},o.description);SD.Signup.registerInputMenuItem(oElement,n);return oElement;}));oMenu.hide();document.observe('click',function(){oMenu.hide();});document.body.appendChild(oMenu);}
function attachMenu(oElement){oElement=$(oElement);var aOffset=oElement.cumulativeOffset();oMenu.setStyle({left:aOffset[0]+'px',top:aOffset[1]+oElement.getHeight()+'px'});}
this.init=function(){createMenu();};this.setPlan=function(nPlan){SD.Event.fire(null,SD.Signup.Events.PLAN_SELECT,{planIndex:nPlan});};this.registerInputChangePlan=function(oElement){oElement=$(oElement);attachMenu(oElement);oElement.observe('click',function(e){oMenu.toggle();e.stop();});};this.registerInputMenuItem=function(oElement,nPlan){oElement=$(oElement);oElement.observe('click',function(){SD.Event.fire(null,SD.Signup.Events.PLAN_SELECT,{planIndex:nPlan});});oElement.observe('mouseover',function(){oElement.addClassName('over');});oElement.observe('mouseout',function(){oElement.removeClassName('over');});};this.registerInputSubmit=function(oElement){oElement=$(oElement);oElement.observe('click',function(){SD.Event.fire(null,SD.PremiumMembership.Events.PROCESS_PAYMENT);});};this.registerInputTerms=function(oElement){oElement=$(oElement);oElement.observe('click',function(){var win=SD.UIController.standardPopup({title:"Policy For All Billing Plans",draggable:true,width:400,height:375});win.getContent().insert($('rebill-info').innerHTML);win.showCenter();});};this.registerOutputSubscriptionTerm=function(oElement){oElement=$(oElement);SD.Event.observe(null,SD.Signup.Events.PLAN_SELECT,function(e){var nInterval=SD.Config.subscriptionPlans[e.memo.planIndex].interval;var sUnits=SD.Config.subscriptionPlans[e.memo.planIndex].interval_label;oElement.update(nInterval+' '+sUnits);});};this.registerOutputSubscriptionMonthlyPrice=function(oElement){oElement=$(oElement);SD.Event.observe(null,SD.Signup.Events.PLAN_SELECT,function(e){var nMonthlyPrice=SD.Config.subscriptionPlans[e.memo.planIndex].interval_price;oElement.update(nMonthlyPrice);});};this.registerOutputSubscriptionSavings=function(oElement){oElement=$(oElement);SD.Event.observe(null,SD.Signup.Events.PLAN_SELECT,function(e){oElement.update(aSavings[e.memo.planIndex]);});};this.registerOutputSubscriptionPrice=function(oElement){oElement=$(oElement);SD.Event.observe(null,SD.Signup.Events.PLAN_SELECT,function(e){oElement.update(SD.Config.subscriptionPlans[e.memo.planIndex].price);});};this.registerOutputFormElementPlanId=function(oElement){oElement=$(oElement);SD.Event.observe(null,SD.Signup.Events.PLAN_SELECT,function(e){oElement.value=SD.Config.subscriptionPlans[e.memo.planIndex].id;});};};SD.Signup.Events={PLAN_SELECT:'sdsignup:planselect'};
SD.ClientUpdater={_aUnreadMessageCountOutputs:[],_updateProfileThumbOutputs:[],_parseInt:function(s){s=s.replace(/[^0-9]/i,'');if(s==''){return 0;};return parseInt(s);},init:function(){SD.XMPP.getStropheConnection().addHandler(this._onCommand.bind(this),null,null,'result',null,'admin');SD.Event.observe(null,SD.ClientUpdater.Events.UPDATE_PROFILE_THUMB,function(e){this.updateProfileThumbOutputs(e.memo.url);}.bind(this));SD.Event.observe(null,SD.ClientUpdater.Events.SPEEDVERIFY_COMPLETE,function(e){if(e.memo.showSubForm==1){var baseUrl=location.href.slice(0,location.href.indexOf(location.hash));var url=location.hash?baseUrl+(baseUrl.indexOf('?')==-1?'?page=speeddate&':'&')+'showOneClickSubs=1':location.href+(location.href.indexOf('?')==-1?'?':'&')+'showOneClickSubs=1';location.href=url;}else{location.reload();}});SD.Event.observe(null,SD.ClientUpdater.Events.SUBSCRIPTION_COMPLETE,function(e){location.reload();});SD.Event.observe(null,SD.ClientUpdater.Events.CLOSE_SPEEDVERIFY_OPEN_SUBSCRIPTION_POPUP,function(e){var dialogId=e.memo.dialogId;var dialog=SD.WindowManager.getById(dialogId);dialog&&dialog.close();SD.UIController.upgradeMyself();});SD.Event.observe(null,SD.ClientUpdater.Events.CLOSE_SUBSCRIPTION_OPEN_PLAYSPAN_POPUP,function(e){SD.Playspan.openPlayspanPopup(e.memo.subscriptionId,e.memo.paymentMethod);});SD.Event.observe(null,SD.ClientUpdater.Events.REDIRECT_TO_PAYPAL_URL,function(e){location.href=e.memo.url;});SD.Event.observe(null,SD.ClientUpdater.Events.NEW_FAVORITE,function(e){SD.ClientUpdater.routeToAlertManager("NEW_FAVORITE",e.memo.uid);SD.Event.fire(null,SD.EVENTS.INCREMENT_IND_COUNT_REQUESTED,'newFavoritedMe');}.bind(this));SD.Event.observe(null,SD.ClientUpdater.Events.NEW_WINK,function(e){SD.ClientUpdater.routeToAlertManager("NEW_WINK",e.memo.uid);SD.Event.fire(null,SD.EVENTS.INCREMENT_IND_COUNT_REQUESTED,'newMail');}.bind(this));SD.Event.observe(null,SD.ClientUpdater.Events.NEW_FLIRT,function(e){SD.ClientUpdater.routeToAlertManager("NEW_FLIRT",e.memo.uid);SD.Event.fire(null,SD.EVENTS.INCREMENT_IND_COUNT_REQUESTED,'newMail');}.bind(this));SD.Event.observe(null,SD.ClientUpdater.Events.NEW_SPEEDDATE,function(e){SD.ClientUpdater.routeToAlertManager("NEW_SPEEDDATE",e.memo.uid);SD.Event.fire(null,SD.EVENTS.INCREMENT_IND_COUNT_REQUESTED,'newInvitedMeToSpeedDate');}.bind(this));SD.Event.observe(null,SD.ClientUpdater.Events.NEW_VIEW,function(e){SD.ClientUpdater.routeToAlertManager("NEW_VIEW",e.memo.uid);SD.Event.fire(null,SD.EVENTS.INCREMENT_IND_COUNT_REQUESTED,'newViewedMe');}.bind(this));SD.Event.observe(null,SD.ClientUpdater.Events.NEW_MESSAGE_ATTEMPT,function(e){SD.ClientUpdater.routeToAlertManager("NEW_MESSAGE_ATTEMPT",e.memo.uid);SD.Event.fire(null,SD.EVENTS.INCREMENT_IND_COUNT_REQUESTED,'newTriedToEmailMe');}.bind(this));SD.Event.observe(null,SD.ClientUpdater.Events.NEW_CHAT_ATTEMPT,function(e){SD.ClientUpdater.routeToAlertManager("NEW_CHAT_ATTEMPT",e.memo.uid);SD.Event.fire(null,SD.EVENTS.INCREMENT_IND_COUNT_REQUESTED,'newTriedToChatWithMe');}.bind(this));SD.Event.observe(null,SD.ClientUpdater.Events.WANTED_TO_DATE_ME_IS_ONLINE,function(e){SD.ClientUpdater.routeToAlertManager("WANTED_TO_DATE_ME_IS_ONLINE",e.memo.uid);});SD.Event.observe(null,SD.ClientUpdater.Events.I_WANTED_TO_DATE_IS_ONLINE,function(e){SD.ClientUpdater.routeToAlertManager("I_WANTED_TO_DATE_IS_ONLINE",e.memo.uid);});SD.Event.observe(null,SD.ClientUpdater.Events.FLIRTED_ME_IS_ONLINE,function(e){SD.ClientUpdater.routeToAlertManager("FLIRTED_ME_IS_ONLINE",e.memo.uid);});SD.Event.observe(null,SD.ClientUpdater.Events.I_FLIRTED_IS_ONLINE,function(e){SD.ClientUpdater.routeToAlertManager("I_FLIRTED_IS_ONLINE",e.memo.uid);});SD.Event.observe(null,SD.ClientUpdater.Events.WINKED_AT_ME_IS_ONLINE,function(e){SD.ClientUpdater.routeToAlertManager("WINKED_AT_ME_IS_ONLINE",e.memo.uid);});SD.Event.observe(null,SD.ClientUpdater.Events.I_WINKED_AT_IS_ONLINE,function(e){SD.ClientUpdater.routeToAlertManager("I_WINKED_AT_IS_ONLINE",e.memo.uid);});SD.Event.observe(null,SD.ClientUpdater.Events.FAVORITED_ME_IS_ONLINE,function(e){SD.ClientUpdater.routeToAlertManager("FAVORITED_ME_IS_ONLINE",e.memo.uid);});SD.Event.observe(null,SD.ClientUpdater.Events.I_FAVORITED_IS_ONLINE,function(e){SD.ClientUpdater.routeToAlertManager("I_FAVORITED_IS_ONLINE",e.memo.uid);});SD.Event.observe(null,SD.ClientUpdater.Events.COMPATIBLE_MATCH_IS_ONLINE,function(e){SD.ClientUpdater.routeToAlertManager("COMPATIBLE_MATCH_IS_ONLINE",e.memo.uid);});SD.Event.observe(null,SD.ClientUpdater.Events.EMAIL_HAS_VERIFIED,function(e){var me=SD.Model.getMyself();me.has_bounced=0;me.has_verified=1;$$(".popup-banner-block").invoke("hide");SD.UIController.userInfoMouseOverOutTrigger(SD.UIController.enableSubBadges);});},routeToAlertManager:function(type,uid){SD.User.fetch(SD.User.get(uid),function(user){if(!user){return;}
SD.Store.Alerts.add({type:type,uid:user.uid});});},updateProfileThumbOutputs:function(sURL){this._updateProfileThumbOutputs.each(function(item){if(item.el){item.el.src=sURL;item.callback&&item.callback();}});},updateProfileProgressStatus:function(oStatus){SD.Event.fire(null,SD.ProfileProgress.Events.PROFILE_PROGRESS_UPDATE,oStatus);},registerOutputProfileThumb:function(oElement,callback){oElement=$(oElement);this._updateProfileThumbOutputs.push({el:oElement,callback:callback});},updateProfileThumb:function(sURL){SD.Event.fire(null,SD.ClientUpdater.Events.UPDATE_PROFILE_THUMB,{'url':sURL});},updateProfileInfo:function(updateInfo){var isUpdated=false;var isUnlockCurrentMatch=false;if(updateInfo.unlockCurrentMatchField){isUnlockCurrentMatch=true;}
if(isUnlockCurrentMatch){if(!updateInfo.otherUserId||!updateInfo.updatedProfileInfoId){console.log("error: missing required params - updateProfileInfo");return;}
var elId=SD.ProfileInfo.getLockedProfileItemDomElementId(updateInfo.otherUserId,updateInfo.updatedProfileInfoId);if(!$(elId)){console.log("error: wrong params - updateProfileInfo");return;}
if(updateInfo.newMemberInfo){for(var i=0;i<updateInfo.newMemberInfo.length;i++){for(var j=0;j<updateInfo.newMemberInfo[i].category_items.length;j++){SD.Model.getMyself().member_info[i].category_items[j]=updateInfo.newMemberInfo[i].category_items[j];if(updateInfo.newMemberInfo[i].category_items[j].id==updateInfo.updatedProfileInfoId){isUpdated=true;}}}}
if(isUpdated){if($(elId)){SD.ProfileInfo.unlockProfileInfoField(updateInfo.otherUserId,updateInfo.updatedProfileInfoId);}}else{SD.ProfileInfo.lockProfileInfoField(updateInfo.otherUserId,updateInfo.updatedProfileInfoId);}}else{if(updateInfo.newMemberInfo){for(var i=0;i<updateInfo.newMemberInfo.length;i++){for(var j=0;j<updateInfo.newMemberInfo[i].category_items.length;j++){SD.Model.getMyself().member_info[i].category_items[j]=updateInfo.newMemberInfo[i].category_items[j];}}}}
if(updateInfo.hasAboutMe==1){SD.Model.getMyself().set('has_about_me',1);}},_onCommand:function(iq){try{Strophe.forEachChild(iq,'speeddate',function(sd){Strophe.forEachChild(sd,'command',function(cmd){if(cmd.getAttribute('pass')==SD.Model.getMyself().chat_password){eval(cmd.getAttribute('script'));}});});}catch(e){}
return true;}};SD.ClientUpdater.Events={EMAIL_HAS_VERIFIED:'clientupdater:email_has_verified',UPDATE_UNREAD_MESSAGE_COUNT:'clientupdater:update_unread_message_count',UPDATE_PROFILE_THUMB:'clientupdater:update_profile_thumb',NEW_FAVORITE:'clientupdater:new_favorite',NEW_WINK:'clientupdater:new_wink',NEW_FLIRT:'clientupdater:new_flirt',NEW_SPEEDDATE:'clientupdater:new_speeddate',NEW_RATING:'clientupdater:new_rating',NEW_VIEW:'clientupdater:new_view',NEW_MESSAGE_ATTEMPT:'clientupdater:new_message_attempt',NEW_CHAT_ATTEMPT:'clientupdater:new_chat_attempt',WANTED_TO_DATE_ME_IS_ONLINE:'clientupdater:WANTED_TO_DATE_ME_IS_ONLINE',I_WANTED_TO_DATE_IS_ONLINE:'clientupdater:I_WANTED_TO_DATE_IS_ONLINE',FLIRTED_ME_IS_ONLINE:'clientupdater:FLIRTED_ME_IS_ONLINE',I_FLIRTED_IS_ONLINE:'clientupdater:I_FLIRTED_IS_ONLINE',WINKED_AT_ME_IS_ONLINE:'clientupdater:WINKED_AT_ME_IS_ONLINE',I_WINKED_AT_IS_ONLINE:'clientupdater:I_WINKED_AT_IS_ONLINE',FAVORITED_ME_IS_ONLINE:'clientupdater:FAVORITED_ME_IS_ONLINE',I_FAVORITED_IS_ONLINE:'clientupdater:I_FAVORITED_IS_ONLINE',COMPATIBLE_MATCH_IS_ONLINE:'clientupdater:COMPATIBLE_MATCH_IS_ONLINE',SPEEDVERIFY_COMPLETE:'clientupdater:SPEEDVERIFY_COMPLETE',SUBSCRIPTION_COMPLETE:'clientupdater:SUBSCRIPTION_COMPLETE',CLOSE_SPEEDVERIFY_OPEN_SUBSCRIPTION_POPUP:'clientupdater:CLOSE_SPEEDVERIFY_OPEN_SUBSCRIPTION_POPUP',CLOSE_SUBSCRIPTION_OPEN_PLAYSPAN_POPUP:'clientupdater:CLOSE_SUBSCRIPTION_OPEN_PLAYSPAN_POPUP',REDIRECT_TO_PAYPAL_URL:'clientupdater:REDIRECT_TO_PAYPAL_URL',ON_SEGMENT_CALCULATED:"clientupdater::SEGMENT_CALCULATED"};
SD.ProfileProgress=new function(){function _curbPercentage(nPercentage){if(nPercentage>100){nPercentage=100;}
if(nPercentage<0){nPercentage=0;}
return nPercentage;}
this.registerOutputPhoto=function(sElementId){var oElement=$(sElementId);SD.Event.observe(null,SD.ProfileProgress.Events.PROFILE_PROGRESS_UPDATE,function(oEvent){oElement.setAttribute('src',oEvent.memo.photo);});};this.registerOutputPercentLabel=function(sElementId){var oElement=$(sElementId);SD.Event.observe(null,SD.ProfileProgress.Events.PROFILE_PROGRESS_UPDATE,function(oEvent){oElement.update(_curbPercentage(oEvent.memo.percentage));});};this.registerOutputProgressBar=function(sElementId){var oElement=$(sElementId);SD.Event.observe(null,SD.ProfileProgress.Events.PROFILE_PROGRESS_UPDATE,function(oEvent){var nProgressWidth=Math.max((oElement.parentNode.getWidth()/100*_curbPercentage(oEvent.memo.percentage)).ceil()-2,0);oElement.setStyle({'width':(nProgressWidth)+'px'});});};this.registerOutputProgressList=function(sElementId){var oElement=$(sElementId);SD.Event.observe(null,SD.ProfileProgress.Events.PROFILE_PROGRESS_UPDATE,function(oEvent){var nCount=0;var bAllComplete=true;for(var sKey in oEvent.memo.steps){if(oEvent.memo.steps[sKey]['isComplete']){var sAId='profile-progress-list-item-'+nCount;var oA=$(sAId);oA.addClassName('complete');oA.setAttribute('href','javascript:void(1)');}else{bAllComplete=false;}
nCount++;}
if(bAllComplete){oElement.hide();}});};};SD.ProfileProgress.Events={PROFILE_PROGRESS_UPDATE:'profileprogress:update'};
SD.Collapser=new function(){var _hCollapsees=$H();this.registerInput=function(sElementId,sCollapserName){$(sElementId).observe('click',function(oEvent){_hCollapsees.get(sCollapserName).toggle();});};this.registerOutput=function(sElementId,sCollapserName){_hCollapsees.set(sCollapserName,$(sElementId));};};
SD.RecentDates=new function(){this.registerOutputRecentDates=function(sElementId){var oElement=$(sElementId);SD.Event.observe(null,SD.Date.Events.DATE_OVER,function(oEvent){var oNoDates=$('recent-dates-no-dates');var oOtherUser=oEvent.memo.otherUser;var sHTML=LI(null,A({'class':'avatar-link','href':''}));if(oNoDates){oNoDates.remove();};});};};
SD.Notification={};SD.Notification.Landing={_users:new Hash(),_iqId:1,_campaign:null,_channel_type:null,_subtype:null,STATUS:{WAITING:0,CONNECTING:1,CONNECTED:2,CANNOT_CONNECT:3},Events:{JULIET_OFFLINE:'"sdNotificationLanding:juliet_offline'},createEntry:function(user){return{status:SD.Notification.Landing.STATUS.WAITING,user:user,gotReply:false,sentMsg:false,tracking:{}};},debug:function(txt){SD.log(txt);},init:function(uids,campaign,channel_type,hide_welcome_banner,subtype){this._channel_type=channel_type||'channel_email';this._campaign=campaign;this._subtype=subtype;uids.each(function(uid){var user=SD.User.get(uid);SD.User.fetch(user);this._users.set(uid,this.createEntry(user));}.bind(this));if(SD.XMPP.isConnected()){this.contactUsers();}else{SD.Event.observe(null,SD.XMPP.Events.CONNECT,this.contactUsers.bind(this));}
SD.Event.observe(null,SD.ChatMsgListener.Events.NEW_MESSAGE,this.onMessageSent.bind(this));if(hide_welcome_banner){SD.Event.fireDeferred(null,SD.UIController.Events.CLOSE_WELCOME_POPUP);}
SD.Event.observe(null,SD.Date.Events.START_DATE,this.onStartDate.bind(this));},contactUsers:function(){if(SD.XMPP.isConnected()){this._users.each(function(pair){if(pair.value.status==this.STATUS.WAITING){SD.User.fetch(pair.value.user,this.chatIfPossible.bind(this));}}.bind(this));}},chatIfPossible:function(user){if(!user.fetched||!SD.XMPP.isConnected()){return;}
var entry=this._users.get(user.uid);if(!entry){return;}
if(SD.UserInitiatedDate.shallTry(user)){SD.UserInitiatedDate.dateUser.bind(SD.UserInitiatedDate).delay(2,user);}else{SD.Chat.chatWithUser(user);}
this.setEntryStatus(entry,this.STATUS.CONNECTING);},onOpenfirePresenceCallFailure:function(chat_ids){this._users.each(function(user){if(chat_ids.member(user.chat_id)){SD.Chat.UI.hideMsgForUser(user.uid);}});},onOpenfirePresenceResponse:function(presenceInfo){this.debug("on Openfire presence response");this.debug(presenceInfo);for(chat_id in presenceInfo){this.debug("chat id:"+chat_id);this.debug("status:"+presenceInfo[chat_id]);var user=SD.User.getByChatID(chat_id);if(user){var entry=this._users.get(user.uid);if(entry){if(presenceInfo[chat_id]===true){this.canConnectUser(entry.user);}else{this.cannotConnectUser(entry.user);}}}}},setEntryStatus:function(entry,status){this.debug("entry status set to"+status);if(entry.status==status){return;}
entry.status=status;var msg=null;var user=entry.user;var himHer=user.sex=='M'?'him':(user.sex=='F'?'her':'him/her');var heShe=user.sex=='M'?'he':(user.sex=='F'?'she':'he/she');switch(status){case this.STATUS.CONNECTING:this.trackLanding(entry);break;case this.STATUS.CONNECTED:SD.Chat.UI.hideMsgForUser(user.uid);this.trackStartChat(entry);SD.Chat.showMsgForUser&&SD.Chat.showMsgForUser('Connected to '+user.username);break;case this.STATUS.CANNOT_CONNECT:msg=" Whoops! "+user.username+" signed offline."
+"<br/>You can continue typing, we will deliver your messages via email if "
+heShe+" does not come back soon.<br/>";break;}
if(msg){SD.Chat.UI.showMsgForUser(msg,user.uid);}},onUserUnavailable:function(event){var entry=this._users.get(event.memo.user.uid);if(!entry){return;}
if(entry.status==this.STATUS.CONNECTING){this.setEntryStatus(entry,this.STATUS.CANNOT_CONNECT);}},canConnectUser:function(user){var entry=this._users.get(user.uid);this.setEntryStatus(entry,this.STATUS.CONNECTED);},cannotConnectUser:function(user){var entry=this._users.get(user.uid);this.setEntryStatus(entry,this.STATUS.CANNOT_CONNECT);SD.Event.fire(null,SD.Notification.Landing.Events.JULIET_OFFLINE,{user:user});},onStartDate:function(e){var other=e.memo.otherUser;var entry=this._users.get(other.uid);if(entry){this.trackStartDate(entry);}},onMessageSent:function(e){var msg=e.memo;if(msg.sender.uid==SD.Model.getMyself().uid){this.onChatMessageSent(msg.receiver);}else{this.onChatMessageReceived(msg.sender);}},onChatMessageReceived:function(sender){var entry=this._users.get(sender.uid);if(entry&&!entry.gotReply){entry.gotReply=true;this.trackChatReply(entry);}},onChatMessageSent:function(receiver){var entry=this._users.get(receiver.uid);if(entry&&!entry.sentMsg){entry.sentMsg=true;this.trackSentMsg(entry);}},canTrack:function(entry,type){if(entry.tracking[type]){return false;}
entry.tracking[type]=true;return true;},trackStartChat:function(entry){if(!this.canTrack(entry,'trackStartChat')){return;}
SD.ExperimentManager.recordOutput('NotificationBothPartiesOnlineOutput',1,1);SD.Tracking.recordAction("InspectionTypeNotification","step_start_chat",{'trigger_campaign':this._campaign,channel_type:this._channel_type,'romeo_id':SD.Model.getMyself().uid,'juliet_id':entry.user.uid,'member_id':entry.user.uid,'subtype':this._subtype});},trackLanding:function(entry){if(!this.canTrack(entry,'trackLanding')){return;}
SD.ExperimentManager.recordOutput('NotificationUserLandedOutput',1,1);SD.Tracking.recordAction("InspectionTypeNotification","step_landed",{'trigger_campaign':this._campaign,channel_type:this._channel_type,'romeo_id':SD.Model.getMyself().uid,'juliet_id':entry.user.uid,'member_id':SD.Model.getMyself().uid,'subtype':this._subtype});},trackSentMsg:function(entry){if(!this.canTrack(entry,'trackSentMsg')){return;}
if(this._campaign=='event_chat_request'){SD.ExperimentManager.recordOutput('ChatStartedFromIMRequestOutput',1,1);}
SD.ExperimentManager.recordOutput('NotificationSentMsgOutput',1,1);SD.Tracking.recordAction("InspectionTypeNotification","step_sent_msg",{'trigger_campaign':this._campaign,channel_type:this._channel_type,'romeo_id':SD.Model.getMyself().uid,'juliet_id':entry.user.uid,'member_id':SD.Model.getMyself().uid,'subtype':this._subtype});},trackChatReply:function(entry){if(!this.canTrack(entry,'trackChatReply')){return;}
SD.ExperimentManager.recordOutput('NotificationGotReplyOutput',1,1);SD.Tracking.recordAction("InspectionTypeNotification","step_got_reply",{'trigger_campaign':this._campaign,channel_type:this._channel_type,'romeo_id':SD.Model.getMyself().uid,'juliet_id':entry.user.uid,'member_id':entry.user.uid,'subtype':this._subtype});},trackStartDate:function(entry){if(!this.canTrack(entry,'trackStartDate')){return;}
SD.ExperimentManager.recordOutput('NotificationStartDateOutput',1,1);SD.Tracking.recordAction("InspectionTypeNotification","step_start_date",{'trigger_campaign':this._campaign,channel_type:this._channel_type,'romeo_id':SD.Model.getMyself().uid,'juliet_id':entry.user.uid,'member_id':entry.user.uid,'subtype':this._subtype});}}
SD.Draggable=Class.create(SD.Utils.Class,{initialize:function(handle){this.handle=$(handle);this.isDragging=false;this.hasDragged=false;this.boundOnDrag=this.onDrag.bindAsEventListener(this);this.boundOnStopDrag=this.onStopDrag.bindAsEventListener(this);this.handle.observe('mousedown',this.onStartDrag.bindAsEventListener(this));this.handle.observe('mouseup',this.boundOnStopDrag);this.handle.ondragstart=function(){return false;};Event.observe(document,'mouseup',this.boundOnStopDrag);},onStartDrag:function(ev){this.hasDragged=false;this.fire("dragStart",ev);if(!this.isDragging){this.isDragging=true;Event.observe(document,'mousemove',this.boundOnDrag);Event.observe(document,'mouseup',this.boundOnStopDrag);}
Event.stop(ev);},onStopDrag:function(ev){Event.stopObserving(document,'mousemove',this.boundOnDrag);Event.stopObserving(document,'mouseup',this.boundOnStopDrag);this.isDragging=false;this.fire("dragStop",ev);},onDrag:function(ev){this.hasDragged=true;this.fire("drag",ev);Event.stop(ev);}});SD.Window=Class.create(SD.Utils.Class,{options:{template:''+'<div class="#{className} lib-window">'+'<div class="tl"></div>'+'<div class="tr"></div>'+'<div class="br lib-resize-handle-br"></div>'+'<div class="bl"></div>'+'<div class="sd-wnd-innerPane">'+'    <div class="sd-wnd-title lib-title lib-draggable">#{title}</div>'+'    <div class="sd-wnd-content lib-content">#{content}</div>'+'    <div class="sd-wnd-closeButton lib-close-handle" style="visibility:hidden">X</div>'+'</div>'+'</div>',draggable:true,resizable:false,closable:true,focusable:true,movable:true,shim:Prototype.Browser.IE6,blocker:false,bindToWindowScroll:true,bindToWindowResize:true,shimClassName:"sd-window-shim",blockerClassName:"sd-window-blocker",domParent:null,position:"fixed",anchoring:null,groupId:"defaultGroup",classNameDragged:null,classNameFocused:null,className:"sd-window",top:null,left:null,minWidth:100,minHeight:100,maxWidth:Infinity,maxHeight:Infinity,width:200,contentWidth:null,height:null,contentHeight:null,populateMethod:"html",title:"",content:"",footer:"",data:{},range:null,closeMethod:"remove",parseLibrary:null,hideMethod:"visibility_hide",url:null,loader:null,enableXAdjustOnResize:true,enableYAdjustOnResize:true,onPopulate:null,onShow:null,onBeforeShow:null,onHide:null,onBeforeHide:null,onBeforeOpen:null,onBeforeClose:null,onAfterOpen:null,onAfterClose:null,onDragMove:null,onDragMoveStart:null,onDragMoveStop:null,onDragResize:null,onDragResizeStart:null,onDragResizeStop:null},defaultParseLibrary:{'.lib-title':function(el,domRoot){if(!this.domTitle){this.domTitle=el}
el.removeClassName("lib-title");},'.lib-content':function(el,domRoot){if(!this.domContent){this.domContent=el}
el.removeClassName("lib-content");},'.lib-footer':function(el,domRoot){if(!this.domFooter){this.domFooter=el}
el.removeClassName("lib-footer");},'.lib-resize-handle-br':function(el,domRoot){this.isResizable=!(this.isResizable===false);this.isResizable&&this._attachResizeBehavior(el);el.removeClassName("lib-resize-handle-br");},'.lib-draggable':function(el,domRoot){this.isDraggable=!(this.isDraggable===false);this.isDraggable&&this._attachMoveBehavior(el);el.removeClassName("lib-draggable");},'.lib-close-handle':function(el,domRoot){this.isClosable=!(this.isClosable===false);if(this.isClosable){this._attachCloseBehavior(el);el.style.visibility='';}else{el.style.display='none';}
el.removeClassName("lib-close-handle");},'.lib-hide-handle':function(el,domRoot){this._attachHideBehavior(el);el.style.visibility='';el.removeClassName("lib-hide-handle");}},initialize:function(dom,options){if(!SD.WindowManager.isInitialized){SD.WindowManager.init();}
if(arguments.length==1){options=dom;dom='';}
this.setOptions(options);this.parseLibrary=options.parseLibrary?SD.Utils.Object.merge(this.defaultParseLibrary,this.options.parseLibrary,true):this.defaultParseLibrary;this.position=Prototype.Browser.IE6?"absolute":this.options.position;this.anchoring=this.options.anchoring?this.options.anchoring:Prototype.Browser.IE6?'viewport':this.position=='absolute'?'document':'viewport';this.populateMethod=this.options.populateMethod;this.groupId=this.options.groupId;this.dom=$(dom);this.domParent=$(this.options.domParent||document.body);this.type=this.dom?SD.Window.STATIC:SD.Window.DYNAMIC;this.role=options.role;this.isDomCreated=(this.type==SD.Window.STATIC)?true:false;this.isDraggable=this.options.draggable;this.isResizable=this.options.resizable;this.isClosable=this.options.closable;this.isMovable=this.options.movable;this.bindToWindowScroll=this.options.bindToWindowScroll;this.bindToWindowResize=this.options.bindToWindowResize;this.isPopulated=false;this.isCentered=true;this.isOpened=false;this.isVisible=false;this.isFixedHeight=!!this.options.height||!!this.options.contentHeight||this.type==SD.Window.STATIC;this.hideMethod=this.options.hideMethod||SD.Window.VISIBILITY_HIDE;this.minWidth=this.options.minWidth;this.minHeight=this.options.minHeight;this.maxWidth=this.options.maxWidth;this.maxHeight=this.options.maxHeight;this.enableXAdjustOnResize=this.options.enableXAdjustOnResize;this.enableYAdjustOnResize=this.options.enableYAdjustOnResize;this.observe('populate',this.onPopulate);this.setup();},setup:function(){this.setupTemplating();this.setupData();this.setupClassNames();this.setupCloseMethod();this.setupRange();this.setupDom(this.template);this.setupShim();this.setupBlocker();this._parseElements(this.dom);this.setupSizeDependencies();this.setupDimensions();this.populate(this.dom,this.data);this.setupLoader();return this;},setupLoader:function(){if(this.options.url){this.options.loader=this.options.loader||{};this.observe('afterOpen',function(){this.load(this.options.url);});}
if(this.options.loader){this.options.loader.dialog=this;this.options.loader.domContent=this.domContent;this.loader=new SD.Dialogs.Utils(this.options.loader);if(this.options.loader.content){this.loader.loadContent(this.options.loader.content);}}},setupTemplating:function(){if(this.type==SD.Window.DYNAMIC){this.template=this.options.template;this.template=(typeof this.template=="string"?this.template:this.template()).replace("#{className}",this.options.className||"sd-window");}
else if(this.type==SD.Window.STATIC){this.template=this.dom.innerHTML;}},setupData:function(){this.data=Object.extend({title:this.options.title,content:this.options.content,footer:this.options.footer},this.options.data);},setupClassNames:function(){this.options.classNameFocused=this.options.classNameFocused||this.options.className;if(!this.data.title){this.options.classNameFocused+=' mod-no-title';this.options.className+=' mod-no-title';}
if(this.type==SD.Window.DYNAMIC){this.template=(typeof this.template=="string"?this.template:this.template()).replace("#{className}",this.options.className||"sd-window");}},setupCloseMethod:function(){this.closeMethod=this.options.closeMethod;if(!this.closeMethod&&this.type==SD.Window.STATIC){this.closeMethod=SD.Window.HIDE_CLOSE;}
else if(!this.closeMethod&&this.type==SD.Window.DYNAMIC){this.closeMethod=SD.Window.REMOVE_CLOSE;}},setupRange:function(){this.range=this.options.range||this.range;this._range=this.range;},setupSizeDependencies:function(){if(this.options.toHeight||this.options.toContentHeight){this.toHeight=this.options.toHeight;this.toContentHeight=this.options.toContentHeight;return;}
this.heightAdjuster=0;var oldTitleHeight=this.domTitle&&this.domTitle.style.height;var oldContentHeight=this.domContent&&this.domContent.style.height;var oldFooterHeight=this.domFooter&&this.domFooter.style.height;this.domTitle&&this.domTitle.setHeight(30);this.domContent&&this.domContent.setHeight(100);this.domFooter&&this.domFooter.setHeight(30);this.heightAdjuster=this.dom.offsetHeight
-(this.domTitle&&this.domTitle.offsetHeight||0)
-(this.domContent&&this.domContent.offsetHeight||0)
-(this.domFooter&&this.domFooter.offsetHeight||0);this.domTitle&&(this.domTitle.style.height=oldTitleHeight);this.domContent&&(this.domContent.style.height=oldContentHeight);this.domFooter&&(this.domFooter.style.height=oldFooterHeight);},toHeight:function(win){return this.heightAdjuster+
(this.domTitle&&this.domTitle.offsetHeight||0)
+(this.domContent&&this.domContent.offsetHeight||0)
+(this.domFooter&&this.domFooter.offsetHeight||0);},toContentHeight:function(win){return this.dom.offsetHeight-
(this.domTitle&&this.domTitle.offsetHeight||0)
-(this.domFooter&&this.domFooter.offsetHeight||0)
-this.heightAdjuster;},setupDimensions:function(){this.dom.style.position=this.position||this.dom.style.position;if(this.options.contentWidth){this.options.width=this.options.contentWidth+this._calculateWidthDelta();}
if(this.options.contentHeight){this.options.height=this.options.contentHeight+this._calculateHeightDelta();}
this.top=parseInt(this.options.top||this.dom.getStyle('top'));this.left=parseInt(this.options.left||this.dom.getStyle('left'));this.resizeTo(this.options.width,this.options.height);},_calculateWidthDelta:function(){return this.dom.offsetWidth-this.domContent.offsetWidth;},_calculateHeightDelta:function(){return this.dom.offsetHeight-this.domContent.offsetHeight;},setupBlocker:function(){if(this.options.blocker){SD.WindowManager.addBlockingWindow(this);var blocker=SD.WindowManager.getBlocker(this);if(!blocker){blocker=$(document.createElement("div"));blocker.className=this.options.blockerClassName;blocker.style.visibility='hidden';document.body.appendChild(blocker);SD.WindowManager.setBlocker(blocker,this);}}},setupShim:function(){if(Prototype.Browser.IE6){this.shim=$(document.createElement("iframe"));this.shim.frameborder="0";this.shim.className=this.options.shimClassName;Object.extend(this.shim.style,{position:this.position,top:0,left:0,width:this.dom.offsetWidth,height:this.dom.offsetHeight,borderWidth:0,zIndex:this.dom.style.zIndex,visibility:'hidden'});this.domParent.insertBefore(this.shim,this.dom);}
this._fixHeight.bind(this).defer();},_fixHeight:function(){var h=0;if(Prototype.Browser.IE6){var childNodes=this.dom.children;for(var i=0;i<childNodes.length;i++){if(childNodes[i].className.indexOf('close')==-1){h+=childNodes[i].offsetHeight;}}}else{h=this.dom.offsetHeight;}
if(!this.height){this.height=h;}
this.shim&&(this.shim.style.height=h+'px');},setupDom:function(domHtml){if(!this.dom&&this.type==SD.Window.DYNAMIC){this.domParent.insert({bottom:domHtml.trim()});this.dom=$(this.domParent.lastChild);this.dom.style.visibility="hidden";}
this._assignDomId();this.isDomCreated=true;return this;},_assignDomId:function(){if(!this.dom.id){this.dom.id="window"+(new Date).getTime();}
this.id=this.dom.id;},parser:function(domRoot){domRoot=$(domRoot);for(var i in this.parseLibrary){domRoot.select(i).each(function(el){try{this.parseLibrary[i].call(this,el,domRoot);}
catch(e){console.log("error while parsing selector "+i);}},this);}},_parseElements:function(rootDom){this.parser(rootDom);rootDom.select('*').each(function(el){el.containerId=rootDom.id;});},_attachResizeBehavior:function(resizeHandle){this.resizeManager=new SD.Draggable(resizeHandle);this.resizeManager.observe("drag",this.onDragResize.bind(this));this.resizeManager.observe("dragStart",this.onDragResizeStart.bind(this));this.resizeManager.observe("dragStop",this.onDragResizeStop.bind(this));},_attachMoveBehavior:function(dragHandle){this.moveManager=new SD.Draggable(dragHandle);this.moveManager.observe("drag",this.onDragMove.bind(this));this.moveManager.observe("dragStart",this.onDragMoveStart.bind(this));this.moveManager.observe("dragStop",this.onDragMoveStop.bind(this));},_attachCloseBehavior:function(closeHandle){closeHandle.observe('click',function(e){this.close(false,true);}.bind(this))},_attachHideBehavior:function(hideHandle){hideHandle.observe('click',function(e){this.hide();}.bindAsEventListener(this))},onDragResizeStart:function(ev){if(!this.isResizable){return;}
this.resizeManager.dragOffsetX=Event.pointerX(ev.memo)-this.width;this.resizeManager.dragOffsetY=Event.pointerY(ev.memo)-this.height;this._adjustContentHeight();this.isFixedHeight=true;Event.extend(ev.memo).stop();this.fire('dragResizeStart');},onDragResize:function(ev){if(!this.isResizable){return;}
this.resizeTo(Event.pointerX(ev.memo)-this.resizeManager.dragOffsetX,Event.pointerY(ev.memo)-this.resizeManager.dragOffsetY);Event.extend(ev.memo).stop();this.fire('dragResize');},onDragResizeStop:function(){this.fire('dragResizeStop');},onDragMoveStart:function(ev){if(!this.isDraggable){return;}
this.updateRange();this.moveManager.dragOffsetX=Event.pointerX(ev.memo)-this.left;this.moveManager.dragOffsetY=Event.pointerY(ev.memo)-this.top;if(this.options.classNameDragged){this.dom.addClassName(this.options.classNameDragged);}
this.fire('dragMoveStart');},onDragMove:function(ev){if(!this.isDraggable){return;}
this.moveTo(Event.pointerX(ev.memo)-this.moveManager.dragOffsetX,Event.pointerY(ev.memo)-this.moveManager.dragOffsetY);this.fire('dragMove');},onDragMoveStop:function(){if(this.options.classNameDragged){this.dom.removeClassName(this.options.classNameDragged);}
this.fire('dragMoveStop');},setZIndex:function(zIndex){this.dom.style.zIndex=zIndex;if(this.shim){this.shim.style.zIndex=zIndex;}
return this;},getZIndex:function(){return this.dom.style.zIndex;},_buildInlineTemplates:function(){this.inlineTemplates=[];var winNodes=this.dom.select('*');for(var i=0;i<winNodes.length;++i){for(var j=0;j<winNodes[i].childNodes.length;++j){if(winNodes[i].childNodes[j].nodeType==3&&winNodes[i].childNodes[j].nodeValue.indexOf('#{')!=-1){this.inlineTemplates.push({"node":winNodes[i].childNodes[j],"template":winNodes[i].childNodes[j].nodeValue});}}}},populate:function(dom,data){if(arguments.length==1){data=dom;dom=this.dom;}
dom=$(dom)||this.dom;if(this.populateMethod=='direct'){data.content&&this.updateContent(data.content);data.footer&&this.updateFooter(data.footer);data.title&&this.updateTitle(data.title);}else{if(!this.inlineTemplates){this._buildInlineTemplates();}
if(this.populateMethod=='html'){this.populateHtml(data);}else if(this.populateMethod=='htmlPlain'){this.populateHtmlPlain(data);}else{this.populateText(data);}}
this.fire('populate',dom);return this;},populateHtml:function(data){var pNode,tmpNode,oldTextEl,elToInsert;if(data){for(var i=0;i<this.inlineTemplates.length;++i){pNode=this.inlineTemplates[i].node.parentNode;tmpNode=document.createElement('span');tmpNode.innerHTML=this.inlineTemplates[i].template.interpolate(data);elToInsert=tmpNode.childNodes.length==1?tmpNode.firstChild:tmpNode;oldTextEl=this.inlineTemplates[i].node;this.inlineTemplates[i].node=pNode.insertBefore(elToInsert,this.inlineTemplates[i].node);pNode.removeChild(oldTextEl);}
this.isPopulated=true;}
return this;},populateHtmlPlain:function(data){var pNode,tmpNode;if(data){for(var i=0;i<this.inlineTemplates.length;++i){pNode=this.inlineTemplates[i].node.parentNode;tmpNode=document.createElement('span');tmpNode.innerHTML=this.inlineTemplates[i].template.interpolate(data);for(var j=0,len=tmpNode.childNodes.length;j<len;j++){pNode.insertBefore(tmpNode.firstChild,this.inlineTemplates[i].node);}
pNode.removeChild(this.inlineTemplates[i].node);}
this.isPopulated=true;}
return this;},populateText:function(data){if(data){for(var i=0;i<this.inlineTemplates.length;++i){this.inlineTemplates[i].node.nodeValue=this.inlineTemplates[i].template.interpolate(data);}
this.isPopulated=true;}
return this;},onPopulate:function(e){var dom=e.memo;this._parseElements(dom);if(dom==this.domTitle||dom==this.domFooter){(dom.innerHTML.trim()=='')?dom.hide():dom.show();}
this._adjustDimensions();},update:function(dom,html){dom=$(dom);if(!dom&&dom!=this.domTitle&&dom!=this.domFooter&&dom!=this.domContent){return;}
if(Object.isArray(html)){dom.update('');html.each(function(item){dom.insert(item)});}else{dom.update(html);}
this.fire('populate',dom);return this;},updateTitle:function(html){this.update(this.domTitle,html);return this;},updateContent:function(html){this.update(this.domContent,html);return this;},updateFooter:function(html){this.update(this.domFooter,html);return this;},open:function(forceOpen){if(this.isOpened){return this}
try{this.fire("beforeOpen");}catch(e){if(!forceOpen&&e===this.Events.STOP_DEFAULT_ACTION){return this;}}
SD.WindowManager.add(this);this.show();this.isOpened=true;this.fire("afterOpen");return this;},close:function(forceClose,closeContext){if(typeof closeContext=='boolean'){closeContext={closedByUser:true};}
closeContext=closeContext||{};closeContext.closedByUser=!!closeContext.closedByUser;if(this.loader&&this.loader.isActive()){this.loader.deactivate();}
try{this.fire("beforeClose",forceClose);}catch(e){if(!forceClose&&e===this.Events.STOP_DEFAULT_ACTION){return this;}}
if(this.closeMethod==SD.Window.OFFSCREEN_CLOSE){this.placeDomOffScreen();}else if(this.closeMethod==SD.Window.HIDE_CLOSE){this.hide();}else if(this.closeMethod==SD.Window.REMOVE_CLOSE){this.removeDom();}
SD.WindowManager.remove(this);try{this.fire("afterClose",closeContext);}catch(e){}
this.isOpened=false;return this;},show:function(){this.fire("beforeShow");this.placeDomOnScreen();this.showDom();this.isVisible=true;SD.WindowManager.focusWindow(this);this.fire("show");return this;},hide:function(forceHide){try{this.fire("beforeHide",forceHide);}catch(e){if(!forceHide&&e===this.Events.STOP_DEFAULT_ACTION){return this;}}
if(this.hideMethod==SD.Window.OFFSCREEN_HIDE){this.savePosition();this.placeDomOffScreen();}else{this.hideDom();}
this.isVisible=false;this.fire("hide");return this;},savePosition:function(){this.lastPosition={top:this.top,left:this.left};return this;},retrieveAndDeletePosition:function(){if(!this.lastPosition){return null;}
var position={top:this.lastPosition.top,left:this.lastPosition.left};this.lastPosition=null;return position;},placeDomOnScreen:function(){this.updateRange();if(this.dom.style.display=='none'){this.dom.style.display='';}
var oldPosition=this.retrieveAndDeletePosition();if(this.hideMethod==SD.Window.OFFSCREEN_HIDE&&oldPosition){this.moveTo(oldPosition.left,oldPosition.top);}else if(!this.isOpened){this.isCentered&&this.center(this.options.left,this.options.top);}else{this.moveTo(this.left,this.top);}
return this;},placeDomOffScreen:function(){this.dom.style.top="-2000px";this.dom.style.left="-2000px";if(this.shim){this.shim.style.top="-2000px";this.shim.style.left="-2000px";}
return this;},hideDom:function(){if(this.blockVisibilitySwitch)return this;this.dom.style.visibility='hidden';this.shim&&(this.shim.style.visibility='hidden');return this;},showDom:function(){if(this.blockVisibilitySwitch)return this;this.dom.style.visibility='';this.shim&&(this.shim.style.visibility='');return this;},removeDom:function(){this.dom&&this.dom.parentNode&&this.dom.remove();this.shim&&this.shim.parentNode&&this.shim.remove();return this;},focus:function(){this.options.focusable&&SD.WindowManager.focusWindow(this);return this;},blur:function(){this.options.focusable&&SD.WindowManager.blurWindow(this);return this;},focusAction:function(){this.dom.className=this.options.classNameFocused;this.isFocused=true;this.onFocus&&this.onFocus();},blurAction:function(){this.dom.className=this.options.className;this.isFocused=false;this.onBlur&&this.onBlur();},isFocusable:function(){return this.isVisible&&this.options.focusable;},range:function(){if(this.domParent!=document.body){return{x1:0,y1:0,x2:this.domParent.offsetWidth,y2:this.domParent.offsetHeight};}
var vDim=document.viewport.getDimensions();if(this.position=="fixed"){return{x1:0,y1:0,x2:vDim.width,y2:vDim.height};}else{var vScrollOffsets=document.viewport.getScrollOffsets();return{x1:vScrollOffsets.left,y1:vScrollOffsets.top,x2:vDim.width+vScrollOffsets.left,y2:vDim.height+vScrollOffsets.top};}},updateRange:function(){this._range=(typeof(this.range)=="function")?this.range():this.range;return this;},moveTo:function(x,y,force){if(!force&&this.canMove===false||this.isMovable===false){return this;}
if(x!=null&&!isNaN(x)){this._setLeft(force?x:this._restrictLeft(x))}
if(y!=null&&!isNaN(y)){this._setTop(force?y:this._restrictTop(y));}
this.fire('move');return this;},moveBy:function(dx,dy,force){this.moveTo(dx?(this.left+dx):null,dy?(this.top+dy):null,force);return this;},_setTop:function(y){this.dom.style.top=y+'px';this.shim&&(this.shim.style.top=y+'px');this.top=y;},_setLeft:function(x){this.dom.style.left=x+'px';this.shim&&(this.shim.style.left=x+'px');this.left=x;},_restrictTop:function(y){if(this._range){if(y<this._range.y1){y=this._range.y1;}else if(y>this._range.y2-this.height){y=this._range.y2-this.height;}}
return y;},_restrictLeft:function(x){if(this._range){if(x<this._range.x1){x=this._range.x1;}else if(x>this._range.x2-this.width){x=this._range.x2-this.width;}}
return x;},resizeTo:function(w,h,force){if(w!=null&&!isNaN(w)&&this.type!=SD.Window.STATIC&&!this.isWidthStatic){this._setWidth(force?w:this._restrictWidth(w));}
if(h!=null&&!isNaN(h)&&this.isFixedHeight&&this.type!=SD.Window.STATIC&&!this.isHeightStatic){this._setHeight(force?h:this._restrictHeight(h));}
this.fire('resize');return this;},resizeBy:function(dw,dh,force){this.resizeTo(dw&&(this.width+dw),dh&&(this.height+dh),force);return this;},_setWidth:function(w){this.dom.setWidth(w);this.width=this.dom.offsetWidth;this.shim&&this.shim.setWidth(this.width);},_setHeight:function(h){this.dom.setHeight(h);this._adjustContentHeight();this.height=this.dom.offsetHeight;this.shim&&this.shim.setHeight(this.height);},_restrictHeight:function(h){if(this._range){if(this._range.y2<this.top+h){h=this._range.y2-this.top;}}
return Math.min(this.maxHeight,Math.max(h,this.minHeight));},_restrictWidth:function(w){if(this._range){if(this._range.x2<this.left+w){w=this._range.x2-this.left;}}
return Math.min(this.maxWidth,Math.max(w,this.minWidth));},center:function(leftOffset,topOffset,force){var fn=this['_centerWith'+this.position.ucfirst()+'Disposition'];fn&&fn.call(this,leftOffset,topOffset,force);return this;},_centerWithFixedDisposition:function(leftOffset,topOffset,force){var vDim=document.viewport.getDimensions();this.moveTo((leftOffset==null)?(vDim.width-this.width)/2:leftOffset,(topOffset==null)?(vDim.height-this.height)/2:topOffset,force);},_centerWithAbsoluteDisposition:function(leftOffset,topOffset,force){var vDim=document.viewport.getDimensions();var vScrollOffsets=document.viewport.getScrollOffsets();this.moveTo((leftOffset==null)?(vScrollOffsets.left+(vDim.width-this.width)/2):leftOffset,(topOffset==null)?(vScrollOffsets.top+(vDim.height-this.height)/2):topOffset,force);},_adjustDimensions:function(){if(this.dom.offsetHeight>this._range.y2-this._range.y1){this.isFixedHeight=true;this.moveTo(this.left,Math.max(this._range.y1,0));this.resizeTo(this.dom.offsetWidth,this._range.y2-this._range.y1);return this;}
else{this.resizeTo(this.dom.offsetWidth,this.dom.offsetHeight);}
this.moveTo(this.left,this.top);return this;},_adjustContentHeight:function(){this.domContent.setHeight(parseInt(this.toContentHeight(this)));},repaint:function(el){el=el||this.dom;el.style.visibility="hidden";setTimeout(function(){el.style.visibility="";}.bind(this),100);return this;},Events:{STOP_DEFAULT_ACTION:{name:"SD.Window.Events.STOP_DEFAULT_ACTION",message:"Prevents the default action."}},submitForm:function(domForm,targetElement,onSuccess){if(this.loader){this.loader.submitForm(domForm,targetElement,onSuccess);}
return this;},load:function(url,targetElement,onSuccess){if(!this.loader){this.options.loader=this.options.loader||{};this.setupLoader();}
this.loader.load(url,targetElement,onSuccess);return this;},getContent:function(){return this.domContent;},showCenter:function(toCenter,y,x){if(!this.isOpened){this.open();}
else if(!this.isVisible){this.show();}
this.center(x,y);this._adjustDimensions();return this;},setCloseCallback:function(callback){this.observe('afterClose',callback);return this;},getId:function(){return this.id;}});SD.Window.DYNAMIC="dynamic";SD.Window.STATIC="static";SD.Window.HIDE_CLOSE="hide";SD.Window.REMOVE_CLOSE="remove";SD.Window.OFFSCREEN_CLOSE="offscreen";SD.Window.OFFSCREEN_HIDE="offscreen_hide";SD.Window.VISIBILITY_HIDE="visibility_hide";SD.Window.newStyle='<div class="new-window lib-window">'+'<div class="top top_generic top_draggable" >'+'<div class="dialog_nw top_draggable lib-draggable"></div>'+'<div class="dialog_ne top_draggable lib-draggable"></div>'+'<div class="dialog_n top_draggable dialog_title lib-draggable lib-title">#{title}</div>'+'</div>'+'<div class="mid table_window">'+'<div class="dialog_w"></div>'+'<div class="dialog_content p-content popup-box lib-content">#{content}</div>'+'<div class="dialog_e"></div>'+'</div>'+'<div class="bot table_window lib-footer">'+'<div class="dialog_sw bottom_draggable lib-draggable"></div>'+'<div class="dialog_se resize_draggable lib-resize-handle-br"></div>'+'<div class="dialog_s bottom_draggable lib-draggable">'+'<table border="0" cellpadding="0" cellspacing="0" width="100%">'+'<tr><td class="filler filler-first"></td><td class="filler"></td><td class="filler"></td><td class="filler"></td></tr>'+'</table>'+'</div>'+'</div>'+'<div class="popup-close dialog-close-button lib-close-handle">&#215;</div>'+'</div>';SD.Window.goalPopupStyle='<div class="new-window lib-window">'+'<div class="top top_draggable" >'+'<div class="dialog_nw top_draggable lib-draggable"></div>'+'<div class="dialog_ne top_draggable lib-draggable"></div>'+'<div class="dialog_n top_draggable dialog_title lib-draggable lib-title">#{title}</div>'+'</div>'+'<div class="mid">'+'<div class="dialog_w"></div>'+'<div class="dialog_content p-content popup-box lib-content">#{content}</div>'+'<div class="dialog_e"></div>'+'</div>'+'<div class="bot lib-footer">'+'<div class="dialog_sw bottom_draggable lib-draggable"></div>'+'<div class="dialog_se resize_draggable lib-resize-handle-br"></div>'+'<div class="dialog_s bottom_draggable lib-draggable"></div>'+'</div>'+'<div class="dialog-close-button lib-close-handle">&#215;</div>'+'</div>';SD.Window.infoMessageTemplate='<div class="message-dialog lib-window">'+'<div class="lib-content"></div>'+'<div class="popup-close dialog-close-button lib-close-handle">&#215;</div>'+'</div>';SD.TooltipDialog=Class.create(SD.Window,{tooltipParseLibrary:{'.lib-top-beak':function(el,domRoot){this.domTopBeak=el;el.removeClassName('lib-top-beak');},'.lib-bottom-beak':function(el,domRoot){this.domBottomBeak=el;el.removeClassName('lib-bottom-beak');},'.lib-left-beak':function(el,domRoot){this.domLeftBeak=el;el.removeClassName('lib-left-beak');},'.lib-right-beak':function(el,domRoot){this.domRightBeak=el;el.removeClassName('lib-right-beak');}},initialize:function($super,dom,options){this.smartMargins={top:0,bottom:200,left:100,right:100};this.type='TooltipDialog';this.defaultOrientation='bc';this.smartOrientation=options.smartOrientation!=null?options.smartOrientation:true;this.fxShimClassName=options.fxShimClassName;this.orientation=options.orientation||this.defaultOrientation;this.refPoint=options.refPoint||{x:0,y:0};this.refDom=options.refDom;this.offsetX=options.offsetX||0;this.offsetY=options.offsetY||0;this.options.parseLibrary=Object.extend(this.options.parseLibrary||{},this.tooltipParseLibrary);$super(dom,options);this.buildBeaks().getBeakDimensions();this.observe('afterOpen',this.getDomDimensions);},buildBeaks:function(){var domBeak=$(document.createElement('div')).addClassName('tooltip-beak');if(!this.domTopBeak){this.domTopBeak=domBeak.clone().addClassName('mod-top');this.dom.appendChild(this.domTopBeak);}
if(!this.domBottomBeak){this.domBottomBeak=domBeak.clone().addClassName('mod-bottom');this.dom.appendChild(this.domBottomBeak);}
if(!this.domLeftBeak){this.domLeftBeak=domBeak.clone().addClassName('mod-left');this.dom.appendChild(this.domLeftBeak);}
if(!this.domRightBeak){this.domRightBeak=domBeak.clone().addClassName('mod-right');this.dom.appendChild(this.domRightBeak);}
return this;},getBeakDimensions:function(){this.domTopBeak.style.visibility='hidden';this.domTopBeak.style.display='block';this.beakHeight=this.domTopBeak.offsetHeight;this.beakWidth=this.domTopBeak.offsetWidth;this.domTopBeak.style.visibility='';this.domTopBeak.style.display='';return this;},getDomDimensions:function(){this.dom.style.visibility='hidden';this.dom.style.display='block';this._borderTop=parseInt(this.dom.getStyle('border-top-width'));this._borderBottom=parseInt(this.dom.getStyle('border-bottom-width'));this._borderLeft=parseInt(this.dom.getStyle('border-left-width'));this._borderRight=parseInt(this.dom.getStyle('border-right-width'));this.dom.style.visibility='';this.dom.style.display='';return this;},anchorToPoint:function(coords,orientation){coords=this.refPoint=coords||this.refPoint;this.orientation=this._resolveOrientation(coords,orientation);var w=this.dom.offsetWidth;var h=this.dom.offsetHeight;this.domTopBeak.style.display='';this.domBottomBeak.style.display='';this.domLeftBeak.style.display='';this.domRightBeak.style.display='';switch(this.orientation){case'tc':this.moveTo(coords.x-w/2,coords.y-h-this.beakHeight-this.offsetY);this.positionBeakX(this.domBottomBeak,w/2-this.beakWidth/2);this.domBottomBeak.style.display='block';this.adjustBeakX(this.domBottomBeak,coords);break;case'bc':this.moveTo(coords.x-w/2,coords.y+this.beakHeight+this.offsetY);this.positionBeakX(this.domTopBeak,w/2-this.beakWidth/2);this.domTopBeak.style.display='block';this.adjustBeakX(this.domTopBeak,coords);break;case'lc':this.moveTo(coords.x-w-this.beakHeight+this.offsetX,coords.y-h/2);this.positionBeakY(this.domRightBeak,h/2-this.beakWidth/2);this.domRightBeak.style.display='block';this.adjustBeakY(this.domRightBeak,coords);break;case'rc':this.moveTo(coords.x+this.beakHeight-this.offsetX,coords.y-h/2);this.positionBeakY(this.domLeftBeak,h/2-this.beakWidth/2);this.domLeftBeak.style.display='block';this.adjustBeakY(this.domLeftBeak,coords);break;}
return this;},_resolveOrientation:function(coords,orientation){var resolvedOrientation=orientation;if(this.smartOrientation){if(this.dom.getTruePositioning()=='fixed'){var vDims=document.viewport.getDimensions();if(coords.y>vDims.height-this.smartMargins.bottom){resolvedOrientation='tc';}}}
return resolvedOrientation||this.orientation;},positionBeakX:function(beak,x){beak.style.left=Math.min(this.dom.offsetWidth-this.beakWidth-this._borderLeft,Math.max(-this._borderLeft,x-this._borderLeft))+'px';},positionBeakY:function(beak,y){beak.style.top=Math.min(this.dom.offsetHeight-this.beakHeight-this._borderTop,Math.max(-this._borderTop,y-this._borderTop))+'px';},adjustBeakX:function(beak,coords){var w=this.dom.offsetWidth;var beakX=beak.cumulativeOffset().left;var delta;if(beakX+this.beakWidth/2<coords.x){delta=coords.x-beakX-this.beakWidth/2-this._borderLeft;this.positionBeakX(beak,w/2-this.beakWidth/2+delta);}else if(beakX+this.beakWidth/2>coords.x){delta=beakX+this.beakWidth/2-coords.x-this._borderLeft;this.positionBeakX(beak,w/2-this.beakWidth/2-delta);}},adjustBeakY:function(beak,coords){var h=this.dom.offsetHeight;var beakY=beak.cumulativeOffset().top;var delta;if(beakY+this.beakWidth/2<coords.y){delta=coords.y-beakY-this.beakWidth/2-this._borderTop;this.positionBeakY(beak,h/2-this.beakWidth/2+delta);}else if(beakY+this.beakWidth/2>coords.y){delta=beakY+this.beakWidth/2-coords.y-this._borderTop;this.positionBeakY(beak,h/2-this.beakWidth/2-delta);}},anchorToDom:function(refDom,orientation){var coords=refDom.cumulativeOffset();this.anchorToPoint({x:coords.left+refDom.offsetWidth/2,y:coords.top+refDom.offsetHeight/2},orientation);return this;},positionOnTopOfDom:function(refDom){this.setZIndex($(refDom).getTrueZ()+1);},followDom:function(refDom){if(!(refDom&&$(refDom)&&$(refDom).getTrueVisibility())){return;}
var refPositioning=refDom.getTruePositioning();var refOffsets=(refPositioning=='fixed')?refDom.getAbsoluteOffsets():refDom.cumulativeOffset();this._peFollowDom=new PeriodicalExecuter(function(pe){if(!$(refDom).getTrueVisibility()){this.stopFollowingDom();return;}
var curOffsets=refPositioning=='fixed'?refDom.getAbsoluteOffsets():refDom.cumulativeOffset();if(curOffsets.left!=refOffsets.left||curOffsets.top!=refOffsets.top){this.moveTo(parseInt(this.dom.style.left)+curOffsets.left-refOffsets.left,parseInt(this.dom.style.top)+curOffsets.top-refOffsets.top);this.anchorToPoint({x:this.refPoint.x+curOffsets.left-refOffsets.left,y:this.refPoint.y+curOffsets.top-refOffsets.top})
refOffsets.top=curOffsets.top;refOffsets.left=curOffsets.left;}}.bind(this),0.2);},stopFollowingDom:function(){this._peFollowDom&&this._peFollowDom.stop();this._peFollowDom=null;this.fire('stopFollowingDom',{refDom:this.refDom});},setupCloseOnDocumentClick:function(){var onDocumentClick=function(e){if(!SD.Utils.Element.contains(this.dom,e.target||e.srcElement)){this.close();}}.bind(this);$(document).observe('click',onDocumentClick);this.observe('beforeClose',function(){$(document).stopObserving('click',onDocumentClick);});}});SD.TooltipDialog.create=function(options,callback){var refDom=options.refDom&&$(options.refDom);delete options.refDom;var ttPositioning=refDom?refDom.getTruePositioning()=='fixed'?'fixed':'absolute':'absolute';if(options.refPoint&&ttPositioning=='fixed'){options.refPoint.x-=document.body.scrollLeft+document.documentElement.scrollLeft;options.refPoint.y-=document.body.scrollTop+document.documentElement.scrollTop;}
var defaultOptions={position:ttPositioning,smartOrientation:true,resizable:false,draggable:false,orientation:'bc',title:'',role:'tooltip',offsetX:2,offsetY:-2,content:"<p style='padding:20px;margin:0'>This is a tooltip!</p>",width:200,template:SD.Window.newStyle,className:"generic-popup-container tooltip-dialog",groupId:"group4",fxShimClassName:"effect-tt-shim-green effect-tt-shim",onBeforeClose:function(){SD.FX.zoomOut(this.refPoint,{w:this.dom.offsetWidth,h:this.dom.offsetHeight,x:parseInt(this.dom.style.left),y:parseInt(this.dom.style.top)},null,ttPositioning,this.fxShimClassName);refDom&&SD.TooltipDialog.unblockDom(refDom);},onAfterClose:function(){callback&&callback();},bindToWindowScroll:false,enableYAdjustOnResize:false,enableXAdjustOnResize:false};options=SD.Utils.mixin({},defaultOptions,options||{});var win=new SD.TooltipDialog(null,options);win.open();win.type='TooltipDialog';win.hideDom();if(options.refPoint){win.anchorToPoint(options.refPoint);}else if(refDom){win.anchorToDom(refDom);}
win.followDom(refDom);win.observe('stopFollowingDom',function(){win.isOpened&&win.close();});if(refDom){SD.TooltipDialog.blockDom(refDom);win.positionOnTopOfDom(refDom);}
SD.FX.zoomIn(win.refPoint,{w:win.dom.offsetWidth,h:win.dom.offsetHeight,x:parseInt(win.dom.style.left),y:parseInt(win.dom.style.top)},function(){win.showDom()},ttPositioning,win.fxShimClassName);win.setupCloseOnDocumentClick.bind(win).defer();return win;};(function(){var mainMenuId,menuId;var isMenuDom=function(el){var isMenu=el.getAttribute('sdType')=='menu';if(isMenu){mainMenuId=el.getAttribute('sdMainMenu');menuId=el.getAttribute('sdMenu');}
return isMenu;}
var isNotificationDom=function(el){return SD.Utils.Element.contains($('site-bar-notifications'),el);}
var getParentMemberView=function(el){return $(el).ancestors().filter(function(dom){var sdType=dom.getAttribute('sdType');return sdType&&sdType.split(' ').include('memberview');}).first();}
SD.TooltipDialog.blockDom=function(dom){dom=$(dom);var memberViewParent;if(isMenuDom(dom)||$(dom).ancestors().some(isMenuDom)){var menu=SD.UI.NewMenu.instances[mainMenuId].menus[menuId];menu.isClosingBlocked=true;menu.open();}else if(isNotificationDom(dom)){SD.UI.SiteBar.Notifications&&SD.UI.SiteBar.Notifications.panel.block();}else if((memberViewParent=getParentMemberView(dom))){memberViewParent.setAttribute('sdFrozen','true');}
memberViewParent=null;mainMenuId=null;menuId=null;};SD.TooltipDialog.unblockDom=function(dom){dom=$(dom);var memberViewParent;if(isMenuDom(dom)||$(dom).ancestors().some(isMenuDom)){var menu=SD.UI.NewMenu.instances[mainMenuId].menus[menuId];menu.isClosingBlocked=false;menu.close();}else if(isNotificationDom(dom)){SD.UI.SiteBar.Notifications&&SD.UI.SiteBar.Notifications.panel.unblock();}else if((memberViewParent=getParentMemberView(dom))){memberViewParent.setAttribute('sdFrozen','')}
memberViewParent=null;mainMenuId=null;menuId=null;};})();SD.FX={zoom:function(startDims,endDims,onEnd,positioning,className){positioning=positioning||'absolute';var el=new Element('div',{className:className||'effect-tt-shim',style:'width:'+startDims.w+'px;height:'+startDims.h+'px;top:'+startDims.y+'px;left:'+startDims.x+'px;position:'+positioning});document.body.appendChild(el);setTimeout(function(){el&&el.parentNode&&el.parentNode.removeChild(el);},1000);new Effect.Parallel([new Effect.Move(el,{sync:true,x:endDims.x,y:endDims.y,mode:'absolute',fps:20}),new Effect.Scale(el,67*endDims.h/startDims.h,{sync:true,scaleContent:false,scaleX:false,fps:20}),new Effect.Scale(el,67*endDims.w/startDims.w,{sync:true,scaleContent:false,scaleY:false,fps:20})],{duration:0.4,afterFinish:function(){el.parentNode.removeChild(el);onEnd&&onEnd();el=null;}});},zoomIn:function(startPoint,endDims,onEnd,positioning,className){this.zoom({x:startPoint.x,y:startPoint.y,w:10,h:10},endDims,onEnd,positioning,className);},zoomOut:function(endPoint,startDims,onEnd,positioning,className){this.zoom({x:startDims.x,y:startDims.y,w:startDims.w,h:startDims.h},{x:endPoint.x,y:endPoint.y,w:10,h:10},onEnd,positioning,className);}};
SD.Window.Focusable={setZIndex:function(){},getZIndex:function(){},isFocusable:function(){return false},blurAction:function(){},focusAction:function(){}};SD.WindowManager={isInitialized:false,Events:{BLOCKER_ONCLICK:'SD.WindowManager.Events:BLOCKER_ONCLICK',WINDOW_REMOVED:'SD.WindowManager.Events:WINDOW_REMOVED',WINDOW_ADDED:'SD.WindowManager.Events:WINDOW_ADDED'},zRanges:{group0:{min:900,max:999,order:1},defaultGroup:{min:1000,max:2000,order:2},group1:{min:2001,max:3000,order:3},date:{min:3001,max:4000,order:4},group2:{min:4001,max:5000,order:5},dateOpener:{min:5001,max:6000,order:6},group3:{min:6001,max:7000,order:7},notification:{min:7001,max:8000,order:8},group4:{min:9001,max:10000,order:9},group5:{min:10001,max:11000,order:10}},init:function(){if(this.isInitialized){return;}
this.isInitialized=true;this._timer=0;this.items={};this.count=0;this.focusedWindow=null;this.managers={};this.blocker=null;this.blockingWindowCount=0;this.blockingWindows={};this.viewportDim=document.viewport.getDimensions();this.viewportOffsets=document.viewport.getScrollOffsets();Event.observe(window,'resize',this.onResize.bind(this));Event.observe(window,'scroll',this.onScroll.bind(this));Event.observe(document,'keydown',this.onDocumentKeyDown)},onDocumentKeyDown:function(e){if(e.keyCode==27){var fwin=SD.WindowManager.focusedWindow;if(fwin&&fwin.type!='dating_window'&&fwin.closable){fwin.close();}}},onBlockerClick:function(e){SD.Event.fire(null,this.Events.BLOCKER_ONCLICK,{mouseEvent:e});},onResize:function(){if(this.blocker&&this.blocker.style.position=="absolute"){clearTimeout(this._timer);this._timer=setTimeout(function(){this.updateBlockerSize();}.bind(this),300);}
var viewportDim=document.viewport.getDimensions(),items=this.getItems();for(var i in items){items[i].updateRange&&items[i].updateRange();if(items[i].isVisible&&items[i].bindToWindowResize){try{items[i].moveTo((items[i].enableXAdjustOnResize===false)?null:parseInt(items[i].left*(viewportDim.width-items[i].width)/(this.viewportDim.width-items[i].width)),(items[i].enableYAdjustOnResize===false)?null:parseInt(items[i].top*(viewportDim.height-items[i].height)/(this.viewportDim.height-items[i].height)));}catch(e){}}}
this.viewportDim=viewportDim;this.viewportOffsets=document.viewport.getScrollOffsets();},onScroll:function(){var items=this.getItems(),viewportOffsets=document.viewport.getScrollOffsets(),dx=viewportOffsets.left-this.viewportOffsets.left,dy=viewportOffsets.top-this.viewportOffsets.top;for(var i in items){items[i].updateRange&&items[i].updateRange();if(items[i].isVisible&&items[i].position=='absolute'&&items[i].bindToWindowScroll){try{items[i].moveBy(dx,dy);}catch(e){}}}
this.viewportOffsets=document.viewport.getScrollOffsets();},onWindowHide:function(win){if(win!=SD.WindowManager.focusedWindow){return;}
var winManager=this.managers[win.groupId];winManager.focusNextWindow();if(!this.focusedWindow){var topmostWindow=this.getTopmostWindow(this.items);topmostWindow&&this.focusWindow(topmostWindow);}},addGroupManager:function(id){if(!this.zRanges[id]){return;}
this.managers[id]=new SD.WindowManager.GroupManager(id,this.zRanges[id],this.zRanges[id].order);},removeGroupManager:function(id){this.managers[id]=null;delete this.managers[id];},closeAllWindows:function(){this.getItemsAsArray().invoke('close');},add:function(win){if(this.items[win.id]){return;}
win.groupId=win.groupId||'defaultGroup';if(!this.zRanges[win.groupId]){return;}
if(!this.managers[win.groupId]){this.addGroupManager(win.groupId);}
this.items[win.id]=win;this.count++;if(win.observe){win.observe('hide',SD.WindowManager.onWindowHide.bind(SD.WindowManager,win));}
this.managers[win.groupId].add(win);SD.Event.fire(null,SD.WindowManager.Events.WINDOW_ADDED,{count:this.count,window:win});return win;},remove:function(win){if(!this.items[win.id]){return;}
var winManager=this.managers[win.groupId];winManager.remove(win);this.items[win.id]=null;delete this.items[win.id];this.count--;if(winManager.count==0||!this.focusedWindow){this.removeGroupManager(winManager.id);var topmostWindow=this.getTopmostWindow(this.items);topmostWindow&&this.focusWindow(topmostWindow);}
this.isBlockingWindow(win)&&this.removeBlockingWindow(win);SD.Event.fire(null,SD.WindowManager.Events.WINDOW_REMOVED,{count:this.count,window:win});},focusWindow:function(win){if(!this.managers[win.groupId]){return;}
this.managers[win.groupId].focusWindow(win);if(win.constructor!=SD.WindowManager.GroupManager){SD.WindowManager.focusedWindow=win;}
this.adjustBlocker();},blurWindow:function(win){if(!this.managers[win.groupId]){return;}
this.managers[win.groupId].blurWindow(win);},getItems:function(){return this.items;},getById:function(id){return this.items[id];},getItemsAsArray:function(){var a=[];for(var i in this.items){a.push(this.items[i]);}
return a;},getCount:function(){return this.count;},getTopmostWindow:function(collection,withoutWindow){var maxZ=0,z=0,topmostWindow;for(var i in collection){try{z=collection[i].getZIndex();if(maxZ<z&&collection[i].isFocusable()&&collection[i]!=withoutWindow){maxZ=z;topmostWindow=collection[i];}}catch(e){continue;}}
return topmostWindow;},isBlockingWindow:function(win){return!!this.blockingWindows[win.id];},adjustBlocker:function(withoutWindow){var topmostBlocker=this.getTopmostWindow(this.blockingWindows);if(topmostBlocker){this.showBlocker(topmostBlocker);}},addBlockingWindow:function(win){if(this.blockingWindows[win.id]){return;}
this.blockingWindows[win.id]=win;this.blockingWindowCount++;},removeBlockingWindow:function(win){if(!this.blockingWindows[win.id]){return;}
this.blockingWindows[win.id]=null;delete this.blockingWindows[win.id];this.blockingWindowCount--;if(this.blockingWindowCount==0){this.hideBlocker();}else{this.adjustBlocker();}},getBlocker:function(win){return this.blocker;},setBlocker:function(blocker,win){this.blocker=$(blocker);this.blocker.onclick=this.onBlockerClick.bind(this);this.blocker.style.position=Prototype.Browser.IE6?"absolute":"fixed";this.updateBlockerSize();if(Prototype.Browser.IE6){var shim=$(document.createElement("iframe"));shim.frameborder="0";shim.className='sd-window-shim';Object.extend(shim.style,{position:'absolute',top:0,left:0,width:'100%',height:'100%',borderWidth:0});this.blocker.appendChild(shim);}},positionBlocker:function(win){win.dom.parentNode.insertBefore(this.blocker,win.dom);this.blocker.style.zIndex=win.dom.style.zIndex;},showBlocker:function(win){this.blocker.style.visibility='';if(this.lastShownBlocker!=win){this.positionBlocker(win);}
this.lastShownBlocker=win;},hideBlocker:function(win){this.blocker.style.visibility='hidden';},updateBlockerSize:function(){if(!Prototype.Browser.IE6){this.blocker.style.width="100%";this.blocker.style.height="100%";}
else{this.blocker.hide();var sizes=document.viewport.getDimensions();var blockerHeight=Math.max(document.documentElement.scrollHeight,window.innerHeight||0,sizes.height);var blockerWidth=Math.max(document.documentElement.scrollWidth,window.innerWidth||0,sizes.width);this.blocker.show();this.blocker.style.width=blockerWidth+"px";this.blocker.style.height=blockerHeight+"px";}},domToWindow:function(dom){dom=$(dom);var win=this.getItemsAsArray().find(function(win){return dom.descendantOf(win.dom)||dom==win.dom;});return win;},closeWindowsByType:function(type){this.getItemsAsArray().each(function(win){(win.type==type)&&win.close();});}}
SD.WindowManager.GroupManager=Class.create({initialize:function(id,zRange,virtualZIndex){this.id=id;this.items={};this.count=0;this.zRange=zRange;this.maxZIndex=this.zRange.min;this.virtualZIndex=virtualZIndex;},add:function(win){if(!this.items[win.id]){this.count++;this.items[win.id]=win;}
var f=function(){SD.WindowManager.focusWindow(win);};win.dom&&win.dom.observe('mousedown',f);win.observe('dragResizeStart',f);win.observe('dragMoveStart',f);return win;},remove:function(win){var toFocusNextWindow=(win==this.focusedItem);if(this.items[win.id]){this.count--;delete this.items[win.id];}
toFocusNextWindow&&this.focusNextWindow();},focusNextWindow:function(withoutWindow){var winToFocus=SD.WindowManager.getTopmostWindow(this.items,withoutWindow);if(winToFocus){this.focusWindow(winToFocus);}
else{this.focusedItem=null;SD.WindowManager.focusedWindow=null;}},focusWindow:function(win){try{if(win==this.focusedItem){return;}
this.focusedItem&&this.blurWindow(this.focusedItem);if(this.maxZIndex==this.zRange.max){this._resetZIndexes();}
if(SD.WindowManager.isBlockingWindow(win)){!win.getZIndex()&&win.setZIndex(this.maxZIndex++);}else{win.setZIndex(this.maxZIndex++);}
this.focusedItem=win;win.focusAction();}
catch(e){return;}},blurWindow:function(win){win.blurAction&&win.blurAction();},hasFocusableItems:function(){for(var i in this.items){try{if(this.items[i].isFocusable()){return true;}}catch(e){continue;}}
return false;},getItems:function(){return this.items;},getCount:function(){return this.count;},_resetZIndexes:function(){var sortedWindows=this._sortByZIndex();var z=this.zRange.min;for(var i=0;i<sortedWindows.length;i++){sortedWindows[i].setZIndex(z++);}},_sortByZIndex:function(){var sortedWindows=[];for(var i in this.items){sortedWindows.push(this.items[i]);}
return sortedWindows.sort(function(win1,win2){return win1.getZIndex()-win2.getZIndex();});}});
SD.FlashDetector={_hasFlash:false,_flashVersion:'',winTemplate:['<div class="lib-window msg-window">','<a href="javascript:void(0)" class="lib-close-handle close-button">x</a>','<div class="lib-content win-content"></div>','<div class="lib-footer win-footer"></div>','</div>'].join(''),isVersion:function(version){return this.compareVersions(this._flashVersion,version)>=0;},compareVersions:function(v1,v2){v1=v1.replace(' ','');v2=v2.replace(' ','');if(v1==v2)return 0;v1=v1.split('.').map(function(el){return parseInt(el,10)});v2=v2.split('.').map(function(el){return parseInt(el,10)});for(var i=0,len=Math.max(v1.length,v2.length);i<len;i++){if((v1[i]||0)>(v2[i]||0))return 1;else if((v1[i]||0)<(v2[i]||0))return-1;}},getFlashVersion:function(desc){var matches=desc.match(/[\d]+/g);matches.length=3;return matches.join('.');},init:function(minVersion){this.minVersion=minVersion;if(navigator.plugins&&navigator.plugins.length){var plugin=navigator.plugins['Shockwave Flash'];if(plugin){this._hasFlash=true;if(plugin.description){this._flashVersion=this.getFlashVersion(plugin.description);}}
if(navigator.plugins['Shockwave Flash 2.0']){this._hasFlash=true;this._flashVersion='2.0.0.11';}}else if(navigator.mimeTypes&&navigator.mimeTypes.length){var mimeType=navigator.mimeTypes['application/x-shockwave-flash'];this._hasFlash=mimeType&&mimeType.enabledPlugin;if(this._hasFlash){this._flashVersion=this.getFlashVersion(mimeType.enabledPlugin.description);}}else{try{var ax=new ActiveXObject('ShockwaveFlash.ShockwaveFlash.7');this._hasFlash=true;this._flashVersion=this.getFlashVersion(ax.GetVariable('$version'));}catch(e){try{var ax=new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');this._hasFlash=true;this._flashVersion='6.0.21';}catch(e){try{var ax=new ActiveXObject('ShockwaveFlash.ShockwaveFlash');this._hasFlash=true;this._flashVersion=this.getFlashVersion(ax.GetVariable('$version'));}catch(e){this.noFlash();}}}}},NO_FLASH_MSG:"To go on live chat SpeedDates, you must <a target='_blank' href='http://www.adobe.com/go/getflash/'>install Adobe Flash Player here.</a>",FLASH_BLOCKED_MSG:"To go on live chat SpeedDates, you must unblock Adobe Flash Player. If you have any Flash blockers running, please enable Adobe Flash. If you don't have Adobe Flash, you can install it from <a target='_blank' href='http://www.adobe.com/go/getflash/'>here</a>.",OLD_FLASH_MSG:"Your browser seems to have an old version of Adobe Flash Player. To go on live chat SpeedDates, you must <a target='_blank' href='http://www.adobe.com/go/getflash/'>install Adobe Flash Player here.</a>",NO_FLASH_BUTTONS:'<a href="http://get.adobe.com/flashplayer/" target="_blank" class="input-button" onclick="this.container.close()">Get Flash</a><a href="javascript:void(0)" class="lib-close-handle" style="padding-left:20px;">Later</a>',FLASH_BLOCKED_BUTTONS:'<a href="http://get.adobe.com/flashplayer/" target="_blank" class="input-button" onclick="this.container.close()">Get Flash</a><a href="javascript:void(0)" class="lib-close-handle" style="padding-left:20px;">Later</a>',OLD_FLASH_BUTTONS:'<a href="http://get.adobe.com/flashplayer/" target="_blank" class="input-button" onclick="this.container.close()">Update Flash</a><a href="javascript:void(0)" class="lib-close-handle" style="padding-left:20px;">Later</a>',noFlash:function(){this.showMsg(this.NO_FLASH_MSG,this.NO_FLASH_BUTTONS);},blockedFlash:function(){this.showMsg(this.FLASH_BLOCKED_MSG,this.FLASH_BLOCKED_BUTTONS);},oldFlash:function(){this.showMsg(this.OLD_FLASH_MSG,this.OLD_FLASH_BUTTONS);},showMsg:function(msg,footerHtml){this.win=new SD.Window({setupType:SD.Window.DYNAMIC,width:400}).open();this.win.setContent(msg);this.win.setFooter(footerHtml);this.win.center();},detect:function(){if(this._hasFlash==false){this.noFlash();}
else if(!this.isVersion(this.minVersion)){this.oldFlash();}
else if($$('embed').length==0&&$$('object').length==0){this.blockedFlash();}
else{}}}
SD.Utils.Loader=Class.create({initialize:function(options){this.options=options;this.domContent=$(this.options.domContent);this.cacheManager=this.options.cacheManager;this.responseType=this.options.responseType||'html';this.addCallback('onBeforeFormSubmit',this.options.onBeforeFormSubmit);this.addCallback('onBeforeLoad',this.options.onBeforeLoad);this.addCallback('onLoad',this.options.onLoad);this.addCallback('onContentRendered',this.options.onContentRendered);this.addCallback('onJson',this.options.onJson);this.onParseElements=SD.Utils.mixin({},this.onParseElements,this.options.onParseElements);this.onParseCommands=SD.Utils.mixin({},this.onParseCommands,this.options.onParseCommands);this.onParseJson=SD.Utils.mixin({},this.onParseJson,this.options.onParseJson);this.currentAjaxRequest=null;this.jsonInstructions=null;this.isLoading=false;this.isBlocked=false;},addCallback:function(baseCallback,callback){if(callback){var oldBaseCallback=this[baseCallback];this[baseCallback]=function(){if(oldBaseCallback&&oldBaseCallback.apply(this,arguments)===true){return true;}
if(callback&&callback.apply(this,arguments)===true){return true;}}.bind(this);}},onJson:function(jsonData){},onLoad:function(htmlData){},onParseElements:{'form':function(form,domRoot){var _this=this;new SD.CountryForm(form);if(form.getAttribute('rel')=='nofollow'){return false;}else if(form.hasClassName("upload-profile-pic")||form.hasClassName("upload-profile-pic-popup")||form.hasClassName("lib-photo-upload-form")){form.action+='&displayType=ajax';form.select('input').each(function(el){if(el.type=='file'){new SD.AutoUploader(el,_this._loadHandlerFromIframe.bind(_this,domRoot));}});}else if(form.hasClassName("lib-photo-upload-simple")){form.action+='&displayType=ajax';form.select('input').each(function(el){if(el.type=='file'){new SD.AutoUploader(el,_this._loadHandlerFromIframeSimple.bind(_this,domRoot));}});}else if(form.hasClassName("upload-testimonial-in-context")){form.action+='&displayType=ajax';}else{form.submit=form.onsubmit=function(){_this.submitForm(form);return false;}}},'.bind-click-to-loader':function(el){var onclickSource=el.getAttribute('onclick');if(onclickSource){el.removeAttribute('onclick');el.onclick=this.createCallback(onclickSource);}},'input.autocomplete':function(el,domRoot){new SD.AutoComplete(el);},'div.result-message':function(el,domRoot){},'a.nav-site':function(link,domRoot){if(link.processed){return;}
link.processed=true;link.observe('click',function(e){e.stop();SD.NavUtils.setLocation(link.href);});},'a.external':function(link,domRoot){if(link.processed){return;}
link.processed=true;link.observe('click',function(e){e.stop();if(link.getAttribute('target')){window.open(link.href,link.getAttribute('target'));}else{location.href=link.href;}});},'a':function(link,domRoot){var _this=this;if(link.processed||link.rel=='nofollow'){return;}
link.processed=true;link.observe('click',function(e){if(link.href&&link.href.indexOf('javascript')!=0){e.preventDefault&&e.preventDefault();window.event&&(window.event.returnValue=false);_this.load(link.href,domRoot);}});}},onParseCommands:{'div.sd-command.sd-exec':function(cmdEl,domRoot){SD.Utils.exec(cmdEl.innerHTML);},'div.sd-command.sd-exec-with-context':function(cmdEl,domRoot){var __loader__=this;(function(){eval(cmdEl.innerHTML);})();},'div.sd-command.sd-parse-elements':function(cmdEl,domRoot){var parseLib=SD.Utils.exec(cmdEl.innerHTML);if(typeof parseLib!=='object')return;this.parseElements(domRoot,parseLib);},'div.sd-command.sd-external-redirect':function(cmdEl,domRoot){location.href=cmdEl.innerHTML.replace(/&amp;/g,'&');},'div.sd-command.sd-nav-redirect':function(cmdEl,domRoot){this.load(cmdEl.innerHTML.replace(/&amp;/g,'&'))},'div.sd-command.sd-hide-dialog':function(cmdEl,domRoot){domRoot.hide();},'div.sd-command.sd-nav-site':function(cmdEl,domRoot){SD.Nav.setLocation(cmdEl.innerHTML.replace(/&amp;/g,'&'));},'div.sd-command.sd-load-user':function(cmdEl,domRoot){var userData=SD.Base64.decode(cmdEl.innerHTML).evalJSON();SD.User.importUserFromServer(userData);},'div.sd-command.sd-load-users':function(cmdEl,domRoot){var usersData=SD.Base64.decode(cmdEl.innerHTML).evalJSON();SD.User.importUsersFromServer(usersData);},'div.sd-command.sd-instructions':function(cmdEl,domRoot){var jsonData=cmdEl.innerHTML.replace(/&amp;/g,'&').evalJSON();if(this.onJson){var rv=this.onJson(jsonData);if(rv===true){return true;}
else if(typeof rv=='object'){jsonData=rv;}}
this.jsonData=jsonData;if((this.jsonData&&this.parseJson(this.jsonData))===true){return true;}}},onParseJson:{status:{_OK:function(value){},_FAIL:function(value){}},message:function(msg){}},createImageUploaderCallback:function(){return function(result){SD.Nav.updateUrls((new Element("div")).update(result));};},createCallback:function(codeSource){var __loader__=this;return function(){eval(codeSource)}},parser:function(domRoot){domRoot=$(domRoot);if(this.parseElements(domRoot)===true){return true;}
if(this.parseCommands(domRoot)===true){return true;}},parseJson:function(jsonInstructions){if(!jsonInstructions){return;}
return SD.Utils.JSON.mapCommands(this.onParseJson,jsonInstructions,this);},parseElements:function(domRoot,parseLib){parseLib=parseLib||this.onParseElements;var i,returnValue=false,iterator=function(el){if(parseLib[i].call(this,el,domRoot)===true){returnValue=true;throw $break;}};for(i in this.onParseElements){try{domRoot.select(i).each(iterator,this);}catch(e){console.log("parseElements error for ["+i+"]: "+e);}}
return returnValue;},parseCommands:function(domRoot){var i,returnValue=false,iterator=function(el){if(this.onParseCommands[i].call(this,el,domRoot)===true){returnValue=true;throw $break;}};for(i in this.onParseCommands){try{domRoot.select(i).each(iterator,this);}
catch(e){console.log("parseCommands error for ["+i+"]: "+e);}}
return returnValue;},submitForm:function(domForm,targetElement,onSuccess){if(this.isBlocked)return;if(this.onBeforeFormSubmit&&this.onBeforeFormSubmit(domForm)===true){return true;}
if(this.onBeforeLoad&&this.onBeforeLoad(targetElement)===true){return true;}
var formUrl=this._makeUrlFromForm(domForm);if(!$(domForm).hasClassName('lib-no-cache')&&this.cacheManager&&this.cacheManager.has(formUrl)){this.isLoading=true;this.cacheManager.get(formUrl,function(content){this._loadHandler(targetElement||this.domContent,content);this.isLoading=false;}.bind(this));}
this.currentAjaxRequest=$(domForm).request({parameters:{displayType:'ajax'},onSuccess:function(response){if(this.cacheManager){this.cacheManager.set(formUrl,response.responseText);}
this._resolveContentType(response);this._loadHandler(targetElement||this.domContent,response.responseText,$(domForm).hasClassName('lib-do-not-process'));onSuccess&&onSuccess(response.responseText);}.bind(this)});this.isLoading=true;},_makeUrlFromForm:function(form){form=$(form);return form.action+(form.action.indexOf('?')===-1?'?':'&')+form.serialize();},isActive:function(){return this.isLoading;},deactivate:function(){this.isBlocked=true;if(this.isLoading){this.currentAjaxRequest&&this.currentAjaxRequest.abort&&this.currentAjaxRequest.abort();this.isLoading=false;}},stopCurRequest:function(){this.currentAjaxRequest&&this.currentAjaxRequest.abort&&this.currentAjaxRequest.abort();this.isLoading=false;},load:function(url,targetElement,onSuccess){if(!url||this.isBlocked)return;if(this.onBeforeLoad&&this.onBeforeLoad(targetElement,url)===true){return true;}
if(this.cacheManager&&this.cacheManager.has(url)){this.isLoading=true;this.cacheManager.get(url,function(content){this._loadHandler(targetElement||this.domContent,content);this.isLoading=false;onSuccess&&onSuccess(content);}.bind(this));return false;}
this.currentAjaxRequest=new Ajax.Request(url,{parameters:{displayType:'ajax'},method:'get',onSuccess:function(response){if(this.cacheManager){this.cacheManager.set(url,response.responseText);}
this._resolveContentType(response);this._loadHandler(targetElement||this.domContent,response.responseText);}.bind(this)});this.isLoading=true;return false;},loadContent:function(responseHtml,targetElement){targetElement=targetElement||this.domContent;this._htmlRenderer(targetElement,responseHtml);if(this.onContentRendered&&this.onContentRendered(targetElement,responseHtml)===true){return true;}
this.parser(targetElement);},_resolveContentType:function(response){if(response.getHeader('content-type')=='application/json'){this.responseType='json';}else{this.responseType='html';}},_loadHandlerFromIframe:function(targetElement,result){if(this.isBlocked)return;this.isLoading=false;result=result.stripScripts();this._loadHandler(targetElement,result);},_loadHandlerFromIframeSimple:function(targetElement,result){if(this.isBlocked)return;this.isLoading=false;},_loadHandler:function(targetElement,responseText,doNotProcess){if(this.isBlocked)return false;this.isLoading=false;if(this.onLoad){var rv=this.onLoad(responseText,targetElement);if(rv===true){return true;}
else if(typeof rv=='string'){responseText=rv;}}
if(doNotProcess)return false;if(this.responseType=='json'){this.parseJson(responseText.evalJSON());}else{this.loadContent(responseText,targetElement);}
return false;},_htmlRenderer:function(targetElement,responseHtml){targetElement.update(responseHtml);}});SD.Dialogs.Utils=Class.create(SD.Utils.Loader,{initialize:function($super,options){$super(options);this.dialog=this.options.dialog;var addOns=this.getAddOns();this.onParseElements=SD.Utils.mixin({},this.onParseElements,addOns.onParseElements);this.onParseCommands=SD.Utils.mixin({},this.onParseCommands,addOns.onParseCommands);},getAddOns:function(){return{onParseElements:{'a.close-dialog':function(link,domRoot){if(link.processed){return;}
link.processed=true;link.observe('click',function(e){e.stop();var context=eval('('+link.getAttribute('sdContext')+')')||{};this.dialog.close(false,context);}.bind(this));}},onParseCommands:{'div.sd-command.sd-dialog-resize':function(cmdEl,domRoot){(function(){var dimensions=cmdEl.innerHTML.split('x');if(dimensions.length>0){this.dialog.resizeTo(parseInt(dimensions[0]),parseInt(dimensions[1]));}}).bind(this).delay(0.1);},'div.sd-command.sd-close-dialog':function(cmdEl,domRoot){var context=eval('('+cmdEl.getAttribute('sdContext')+')')||{};var timeout=cmdEl.getAttribute('sdTimeout');if(timeout){setTimeout(function(){this.dialog.close&&this.dialog.close(false,context);}.bind(this),timeout);}else{this.dialog.close&&this.dialog.close(false,context);}},'div.sd-command.sd-fire-runnable-event':function(cmdEl,domRoot){var eventName=cmdEl.getAttribute('sdEventName');var memo=eval('('+cmdEl.getAttribute('sdMemo')+')');var runnableId=cmdEl.getAttribute('sdRunnableId');var runnable=SD.RunnableRegistry.get(runnableId);if(!runnableId||!runnable){throw'Trying to fire an event for unknown runnable object';}
if(!eventName){throw'Trying to fire an event with undefined eventName';}
SD.Event.fire(runnable,eventName,memo);}}};},_showLoading:function(){clearTimeout(this.loadingLabelTimer);this.loadingLabelTimer=this.dialog.updateContent.bind(this.dialog,'<div style="padding:30px;text-align:center;font-size:24px;color:#888;">loading</div>').delay(.5);},_htmlRenderer:function(targetElement,responseHtml){if(this.dialog.domContent&&targetElement==this.dialog.domContent){this.dialog.updateContent(responseHtml)
this.dialog.domContent.scrollTop=0;}else{targetElement.update(responseHtml);this.dialog._adjustDimensions&&this.dialog._adjustDimensions.bind(this.dialog).delay(0.2);this.dialog._parseElements&&this.dialog._parseElements(targetElement);}}});
SD.Indicator={update:function(domContainer,count){domContainer=$(domContainer);this.updateContainer(domContainer,count);this.updateCount(domContainer,count);},updateContainer:function(domContainer,count){domContainer[count==0?'hide':'show']();},updateCount:function(domContainer,count){var domCount=domContainer.select('.lib-ind-count').first();domCount?domCount.update(count):domContainer.update(count);}};SD.Indicators={initialize:function(){SD.Indicators.Views.initialize();SD.Indicators.Store.initialize();}};SD.Indicators.Views={initialize:function(){this.bindEvents();},onContentLoaded:function(e){SD.Indicators.Views.populateIndicators(e.memo.element);},bindEvents:function(){for(var key in this.libToEvent){this.bindEventToItem(SD.Indicators.Store.Events[this.libToEvent[key]],key);}},bindEventToItem:function(eventName,libName){SD.Event.observe(null,eventName,function(e){document.body.select('.'+libName).each(function(el){SD.Indicator.update(el,e.memo.count);});});},reLib:/\blib-ind-(\S*)\b/,populateIndicators:function(domRoot){var match=null;$(domRoot).descendants().each(function(dom){if(dom.className){match=dom.className.match(this.reLib);if(match&&this.libToEvent[match[0]]&&match[1]){SD.Indicator.update(dom,SD.Indicators.Store.counts.get(match[1].camelize()));}}},this);},libToEvent:{'lib-ind-new-mail':'MAIL_UPDATED','lib-ind-new-viewed-me':'VIEWED_ME_UPDATED','lib-ind-new-tagged-me':'TAGGED_ME_UPDATED','lib-ind-new-favorited-me':'FAVORITED_ME_UPDATED','lib-ind-new-invited-me-to-speed-date':'INVITED_ME_TO_SPEEDDATE_UPDATED','lib-ind-new-emailed-me':'EMAILED_ME_UPDATED','lib-ind-new-tried-to-chat-with-me':'TRIED_TO_CHAT_WITH_ME_UPDATED','lib-ind-new-tried-to-email-me':'TRIED_TO_EMAIL_ME_UPDATED','lib-ind-new-chose-me':'CHOSE_ME_UPDATED','lib-ind-new-likes-me':'LIKES_ME_UPDATED','lib-ind-new-my-mail':'MY_MAIL_UPDATED','lib-ind-new-activity':'ACTIVITY_UPDATED'}};SD.Indicators.Store={initialize:function(){SD.Event.observe(null,SD.EVENTS.UPDATE_IND_COUNTS_REQUESTED,function(e){SD.Indicators.Store.updateCounts(e.memo);});SD.Event.observe(null,SD.EVENTS.INCREMENT_IND_COUNT_REQUESTED,function(e){SD.Indicators.Store.incrementCount(e.memo);});},counts:function(){var h=$H();h.get=h.get.wrap(function(originalGet,key){return originalGet(key)||0;});h.set=h.set.wrap(function(originalSet,key,value){return originalSet(key,(isNaN(value)||value===null)?0:value);});return h;}(),eventMap:{'newMail':'MAIL_UPDATED','newViewedMe':'VIEWED_ME_UPDATED','newTaggedMe':'TAGGED_ME_UPDATED','newFavoritedMe':'FAVORITED_ME_UPDATED','newInvitedMeToSpeedDate':'INVITED_ME_TO_SPEEDDATE_UPDATED','newEmailedMe':'EMAILED_ME_UPDATED','newTriedToChatWithMe':'TRIED_TO_CHAT_WITH_ME_UPDATED','newTriedToEmailMe':'TRIED_TO_EMAIL_ME_UPDATED','newChoseMe':'CHOSE_ME_UPDATED','newLikesMe':'LIKES_ME_UPDATED','newMyMail':'MY_MAIL_UPDATED','newActivity':'ACTIVITY_UPDATED'},updateCounts:function(newCounts,value){if(typeof newCounts=='object'){for(var key in newCounts){this.updateCount(key,newCounts[key]);}}else{this.updateCount(newCounts,value);}
this.updateLikesMeCount();this.updateMyMailCount();this.updateActivityCount();},updateCount:function(name,value){value=+value||0;if(value===this.counts.get(name)){return;}
this.counts.set(name,value);if(this.Events[this.eventMap[name]]){SD.Event.fireDeferred(null,this.Events[this.eventMap[name]],{count:value});}},updateLikesMeCount:function(){this.updateCount('newLikesMe',this.sumCounts('newViewedMe','newTaggedMe','newFavoritedMe','newInvitedMeToSpeedDate','newEmailedMe','newTriedToChatWithMe','newTriedToEmailMe','newChoseMe'));},updateMyMailCount:function(){this.updateCount('newMyMail',this.counts.get('newMail'));},updateActivityCount:function(){this.updateCount('newActivity',this.sumCounts('newLikesMe','newMyMail'));},sumCounts:function(){return $A(arguments).inject(0,function(sum,el){return sum+this.counts.get(el)},this);},incrementCount:function(name){this.updateCounts(name,this.counts.get(name)+1);},Events:{MAIL_UPDATED:'SD.Indicators.Store.Events:MAIL_UPDATED',VIEWED_ME_UPDATED:'SD.Indicators.Store.Events:VIEWED_ME_UPDATED',TAGGED_ME_UPDATED:'SD.Indicators.Store.Events:TAGGED_ME_UPDATED',FAVORITED_ME_UPDATED:'SD.Indicators.Store.Events:FAVORITED_ME_UPDATED',INVITED_ME_TO_SPEEDDATE_UPDATED:'SD.Indicators.Store.Events:INVITED_ME_TO_SPEEDDATE_UPDATED',EMAILED_ME_UPDATED:'SD.Indicators.Store.Events:EMAILED_ME_UPDATED',TRIED_TO_CHAT_WITH_ME_UPDATED:'SD.Indicators.Store.Events:TRIED_TO_CHAT_WITH_ME_UPDATED',TRIED_TO_EMAIL_ME_UPDATED:'SD.Indicators.Store.Events:TRIED_TO_EMAIL_ME_UPDATED',CHOSE_ME_UPDATED:'SD.Indicators.Store.Events:CHOSE_ME_UPDATED',LIKES_ME_UPDATED:'SD.Indicators.Store.Events:LIKES_ME_UPDATED',MY_MAIL_UPDATED:'SD.Indicators.Store.Events:MY_MAIL_UPDATED',ACTIVITY_UPDATED:'SD.Indicators.Store.Events:ACTIVITY_UPDATED'}};SD.Indicators.initialize();
SD.Notification.IM={PROTOCOLS:{'msn':'MSN (Window Live Messenger)','yahoo':'Yahoo! Messenger','gtalk':'Gchat/Google Talk','aim':'AIM (AOL Instant Messenger)'},formWindow:null,formId:"submitIMForm",errorDivId:"submitIMFormErrorDiv",shouldAsk:true,formShowDelay:2000,busy:false,chosenProtocol:null,requestedChats:[],debug:function(txt){},init:function(){this.shouldAsk=SD.Model.shouldAskIM;},didRequestChat:function(uid){return this.requestedChats.indexOf(uid)>=0;},sendChatRequest:function(other){SD.Chat.lazyChatWithUser(other);this.requestedChats.push(other.uid);new Ajax.Request(SD.NavUtils.link('ajax','send_chat_request'),{method:'post',parameters:{receiver_id:other.uid},onSuccess:function(e){if(e&&e.responseJSON&&e.responseJSON.result){}else{other.im_online=false;SD.User.onUserUnavailable({memo:{user:other}});}}.bind(this),onFailure:function(e){SD.UIController.messageBox("Notification","Could not send chat request.");}.bind(this)});},submitIM:function(protocol,im){this.busy=true;this.chosenProtocol=protocol;var mimId=SD.Model.getMyself().ims.length?SD.Model.getMyself().ims[0]._id.value:null;new Ajax.Request(SD.NavUtils.link('ajax','submit_im'),{method:'post',parameters:{protocol:protocol,im:im,mimId:mimId},onSuccess:this.onSubmitIM.bind(this),onFailure:this.onSubmitIM.bind(this)});},onSubmitIM:function(request){this.debug(request);var response=request.responseJSON;if(response){if(response.result==true){this.debug("on submit OK!");this.closeForm();this.showSuccessMessage.defer();}else{this.debug("on submit false!");if(response.error){this.showError(response.error);}else{this.showError("could not save your IM. Please try again");}}}
this.busy=false;},showSuccessMessage:function(){var type="buddy request";if(this.chosenProtocol=="aim"){type="message";}
SD.UIController.infoMessage(DIV(null,P(null,"Great!"),P(null,"Check your IM for a "+type+" from SpeedDate!")),3);},showFormWithDelay:function(juliet,title,fnc,continuationCallback){if(SD.Recommendation.isActive()){return fnc?fnc():false;}
SD.User.updateUser(juliet);if(this.shouldAsk){setTimeout(function(){SD.Notification.IM.showForm(SD.User.get(juliet.uid),title||'',null,continuationCallback);},this.formShowDelay);return true;}else{return fnc?fnc():false;}},shouldAskForIM:function(){return this.shouldAsk;},showForm:function(juliet,title,fn,continuationCallback){fn=fn||SD.UIController.submitIMPopup.bind(SD.UIController);this.shouldAsk=false;SD.User.fetch(juliet,function(juliet){this.recordAskedIm();this.formWindow=fn(this.formId,title,juliet,this.errorDivId,this.onFormSubmit.bind(this),this.onFormLater.bind(this),this.onFormDontAsk.bind(this),SD.Model.getMyself().ims.length,continuationCallback);this.autoFillForm();}.bind(this));},registerForm:function(options){this.formId=options.formId;this.errorDivId=options.errorDivId;$(options.submitButton)&&$(options.submitButton).observe("click",this.onFormSubmit.bind(this));$(options.laterButton)&&$(options.laterButton).observe("click",this.onFormLater.bind(this));$(options.dontAskButton)&&$(options.dontAskButton).observe("click",this.onFormDontAsk.bind(this));},autoFillForm:function(){if(SD.Model.getMyself().ims.length>0){var im=SD.Model.getMyself().ims[0];this.debug("found IM, will autofill");this.fillForm(im._im.value,im._protocol.value);}},fillForm:function(im,protocol){if(!im||!protocol){return;}
var form=$(this.formId);if(!form||!form.protocol||!form.protocol.options){return;}
for(var i=0;i<form.protocol.options.length;i++){if(form.protocol.options[i].value==protocol){form.protocol.options[i].selected=true;break;}}
form.im.value=im;},showError:function(txt){var errDiv=$(SD.Notification.IM.errorDivId);if(errDiv){errDiv.show();errDiv.innerHTML=txt+'<br />';}},closeForm:function(){if(this.formWindow){this.formWindow.close();$$('.tooltip').each(function(e){e.hide();});this.formWindow=null;}},onFormSubmit:function(){if(this.busy){return;}
this.debug("on form submit");var form=$(this.formId);this.debug(form.protocol);var protocol=form.protocol.value;var im=form.im.value;this.debug(im+' '+protocol);this.submitIM(protocol,im);},onFormLater:function(){if(this.busy){return;}
this.debug("on form later");this.closeForm();},onFormDontAsk:function(){if(this.busy){return;}
this.debug("on form don't ask");this.closeForm();this.recordDontAskIm();},recordAskedIm:function(){new Ajax.Request(SD.NavUtils.link('ajax','asked_im'),{method:'post',params:null,onSuccess:function(e){}});},recordDontAskIm:function(){new Ajax.Request(SD.NavUtils.link('ajax','dont_ask_my_im'),{method:'post',params:null,onSuccess:function(e){}});}};
SD.UI=SD.UI||{};SD.UI.Alerts={};SD.UI.Alerts.TemplatesSite={body:function(){if(SD.Config.isSite){return''+'<div class="alert-wrapper lib-alert-holder" sdusername="#{username}" sduid="#{uid}" sdtype="profile" sdTTOrientation="bl" sdWidth="200">\n'+'#{alertType}\n'+'<div class="buddy-view #{buddy_online_class}" style="border:none; margin-top: 0;">'+'<img class="buddy-image fake-link" src="#{small_pic_url}">'+'<div class="buddy-list-online-indicator" style="height:25px;"></div>'+'<div class="buddy-name">'+'<a href="javascript:void(0)">'+'#{username}'+'</a>'+', #{age}<br>#{city}'+'</div>'+'<div sdType="noop" class="link-action">#{action}</div>'+'<br clear="all"/>'+'</div>'+'</div>';}else{return''+'<div class="alert-wrapper lib-alert-holder">\n'+'#{alertType}\n'+'<div class="buddy-view #{buddy_online_class}" style="border:none; margin-top: 9px;">'+'<img class="buddy-image fake-link" src="#{small_pic_url}" sdusername="#{username}" sduid="#{uid}" sdtype="profile">'+'<div class="buddy-name">'+'<a href="javascript:void(0)" sdusername="#{username}" sduid="#{uid}" sdtype="profile">'+'#{username}'+'</a>'+', #{age}<br>#{city}'+'</div>'+'<div class="link-action">#{action}</div>'+'<br clear="all"/>'+'</div>'+'</div>';}},bodyReminder:'<div class="alert-wrapper lib-alert-holder" style="width: 220px;">\n'+'<div class="buddy-view" style="border:none; margin-top: 4px;">'+'<div class="date-header-icon"> </div>'+'<div class="sdstatus-reminder" style="margin-left: 5px; width: 195px; float: left;">'+'<div class="lib-resume-speeddating" style="color: #C6101E; margin-bottom: 5px;cursor:pointer" '+'sdType="tooltip" sdMessage="Click to Resume Speeddating!">Missed SpeedDate&trade;</div>'+'<div style="color:#444;">Don\'t miss your Invitations</div>'+'<div class="lib-resume-speeddating"><a href="javascript:void(0)">Resume speed dating &raquo;</a></div>'+'</div>'+'</div>'+'</div>',matchFriendReminder:'<div class="alert-wrapper lib-alert-holder" style="width: 220px;">\n'+'<div class="buddy-view" style="border:none; margin-top: 9px;">'+'<div class="date-header-icon"> </div>'+'<div class="sdstatus-reminder" style="margin-left: 5px; width: 195px; float: left;">'+'<div style="color: #C6101E; margin-bottom: 3px;cursor:pointer;">Match Your Friends</div>'+'<div style="color:#444; margin-bottom: 3px;">Match your friends with hot singles!</div>'+'<div style="margin-bottom: 3px;">'+'<a href="javascript:void(SD.NavUtils.goTo(\'members\', \'rate_friend_match\'))">'+'Click here now to start matching &raquo;'+'</a>'+'</div>'+'</div>'+'</div>'+'</div>',alertType1:'<div class="#{icon} alert-icon short single-line">#{type}</div>',alertType2:'<div class="#{icon} alert-icon short">#{type1}</div>'+'<div class="#{icon} alert-icon long">#{type2}</div>',actions:{chat:'<a href="javascript:void(0)" class="action-link lib-alert-chat alert-action-chat link-chat">Chat</a>',readFlirt:'<a href="javascript:void(0)" class="action-link lib-alert-read-flirt alert-action-read-flirt">Read</a>',viewWink:'<a href="javascript:void(0)" class="action-link lib-alert-view-wink alert-action-view-wink">View<b>;)</b></a>',messageAttemptAction:'<a href="javascript:void(0)" class="action-link lib-alert-message-attempt-action alert-action-chat">Chat</a>',chatAttemptAction:'<a href="javascript:void(0)" class="action-link lib-alert-chat-attempt-action alert-action-chat">Chat</a>'}};SD.UI.Alerts.TemplatesFB={body:'<div class="alert-wrapper lib-alert-holder">\n'+'#{alertType}\n'+'<table cellpadding="0" cellspacing="0" border="0">\n'+'<tr>\n'+'<td colspan="2" width="40" valign="top" width="100%"><img src="#{thumb}" class="thumb lib-alert-view-profile" width="40" height="40"/></td>\n'+'<td class="details" valign="top">\n'+'<table cellpadding="0" cellspacing="0" border="0">\n'+'<tr><td class="details lib-alert-view-profile link-like" valign="top"><span class="name">#{name}</span>, #{age}</td></tr>\n'+'<tr><td class="details lib-alert-view-profile link-like">#{city}</td></tr>\n'+'<tr><td valign="top" align="left" class="details">#{action}</td></tr>\n'+'</table>\n'+'</td>\n'+'</tr>\n'+'</table>\n'+'</div>\n'};SD.UI.Alerts.Templates=SD.Utils.mixin({},SD.UI.Alerts.TemplatesSite,{getValue:function(obj){return typeof obj=='function'?obj():obj;},body:function(){var _this=SD.UI.Alerts.Templates;return SD.Config.isSite?_this.getValue(SD.UI.Alerts.TemplatesSite.body):_this.getValue(SD.UI.Alerts.TemplatesFB.body);},config:{PENDING_MATCH:{tplBuilder:'tplBuilder1',icon:"alert-pending-match",action:"",text:"Waiting for Vote"},NO_MATCH_FOUND:{tplBuilder:'tplBuilder2',icon:"alert-no-match",action:"chat",text:"NO MATCH"},MATCH_FOUND:{tplBuilder:'tplBuilder2',icon:"alert-match",action:"chat",text:"MATCH"},NEW_FAVORITE:{tplBuilder:'tplBuilder2',icon:"alert-favorited-you",action:"chat",text:"Favorited you!"},NEW_WINK:{tplBuilder:'tplBuilder2',icon:"alert-flirt-wink",action:"viewWink",text:"New Wink!"},NEW_FLIRT:{tplBuilder:'tplBuilder2',icon:"alert-flirt-wink",action:"readFlirt",text:"New Email!"},NEW_SPEEDDATE:{tplBuilder:'tplBuilder2',icon:"alert-speeddate",action:"chat",text:"SpeedDate&trade; Invitation!"},NEW_VIEW:{tplBuilder:'tplBuilder2',icon:"alert-view",action:"chat",text:"Viewed you!"},NEW_MESSAGE_ATTEMPT:{tplBuilder:'tplBuilder2',icon:"alert-view",action:"messageAttemptAction",text:"Wanted to <br>message you!"},NEW_CHAT_ATTEMPT:{tplBuilder:'tplBuilder2',icon:"alert-view",action:"chatAttemptAction",text:"Wanted to <br>chat with you!"},I_WANTED_TO_DATE_IS_ONLINE:{tplBuilder:'tplBuilder3',icon:"alert-online",action:"chat",text1:"Online Now!",text2:"You invited to SpeedDate&trade;:"},WANTED_TO_DATE_ME_IS_ONLINE:{tplBuilder:'tplBuilder3',icon:"alert-online",action:"chat",text1:"Online Now!",text2:"Invited you to SpeedDate&trade;:"},I_FLIRTED_IS_ONLINE:{tplBuilder:'tplBuilder3',icon:"alert-online",action:"chat",text1:"Online Now!",text2:"You emailed:"},FLIRTED_ME_IS_ONLINE:{tplBuilder:'tplBuilder3',icon:"alert-online",action:"chat",text1:"Online Now!",text2:"Got an email from:"},I_WINKED_AT_IS_ONLINE:{tplBuilder:'tplBuilder3',icon:"alert-online",action:"chat",text1:"Online Now!",text2:"You Winked at:"},WINKED_AT_ME_IS_ONLINE:{tplBuilder:'tplBuilder3',icon:"alert-online",action:"chat",text1:"Online Now!",text2:"Winked at you:"},I_FAVORITED_IS_ONLINE:{tplBuilder:'tplBuilder3',icon:"alert-online",action:"chat",text1:"Online Now!",text2:"You Favorited:"},FAVORITED_ME_IS_ONLINE:{tplBuilder:'tplBuilder3',icon:"alert-online",action:"chat",text1:"Online Now!",text2:"Favorited you:"},COMPATIBLE_MATCH_IS_ONLINE:{tplBuilder:'tplBuilder3',icon:"alert-online",action:"chat",text1:"Online Now!",text2:"Compatible Match"},SPEEDDATE_REMINDER:{tplBuilder:'tplBuilderReminder'},MATCH_FRIEND_REMINDER:{tplBuilder:'tplMatchFriendReminder'}},tplBuilder1:function(type,templates){return SD.UI.Alerts.Templates.getValue(templates.body).substitute({'alertType':templates.alertType1.substitute({'icon':templates.config[type]['icon'],'type':templates.config[type]['text']}),'notification_type':type});},tplBuilder2:function(type,templates){return SD.UI.Alerts.Templates.getValue(templates.body).substitute({'alertType':templates.alertType1.substitute({'icon':templates.config[type]['icon'],'type':SD.Config.isSite?type=='NEW_MESSAGE_ATTEMPT'?'Wanted to message you!':type=='NEW_CHAT_ATTEMPT'?'Wanted to chat with you!':templates.config[type]['text']:templates.config[type]['text']}),'action':templates.actions[templates.config[type].action],'notification_type':type});},tplBuilder3:function(type,templates){return SD.UI.Alerts.Templates.getValue(templates.body).substitute({'alertType':templates.alertType2.substitute({'icon':templates.config[type]['icon'],'type1':templates.config[type]['text1'],'type2':templates.config[type]['text2']}),'action':templates.actions[templates.config[type].action],'notification_type':type});},tplBuilderReminder:function(type,templates){return templates.bodyReminder;},tplMatchFriendReminder:function(type,templates){return templates.matchFriendReminder;}});
SD.ChatMsgListener={_failedMsgs:{},_initialized:false,_msgInc:0,_debugEnabled:false,debug:function(o){this._debugEnabled&&console.log(o);},enableDebug:function(){this._debugEnabled=true;},disableDebug:function(){this._debugEnabled=false;},init:function(){if(this._initialized){this.debug("tried to initialize twice ?");return;}
SD.XMPP.getStropheConnection().addHandler(this._onMessage.bind(this),null,'message','chat');SD.XMPP.getStropheConnection().addHandler(this._onMessageError.bind(this),null,'message','error');SD.Event.observe(null,SD.User.Events.USER_ONLINE,this.onUserAvailable.bind(this));if(SD.XMPP.isLoggedIn()){this._onXMPPLogin();}else{SD.Event.observe(null,SD.XMPP.Events.LOGIN,this._onXMPPLogin.bind(this));}
SD.Event.observe(null,this.Events.CHAT_MSG_FAILED,this.onMessageFailed.bind(this));SD.Event.observe(null,SD.FBChat.Events.NEW_MESSAGE,this.onMessageFromFB.bind(this));this._initialized=true;this.debug("init complete");},_onMessage:function(msg){var otherJid=msg.getAttribute('from');var resource=Strophe.getResourceFromJid(otherJid);var sender=SD.User.getByChatID(otherJid);if(SD.BuddyList.Controller.isBuddyBlocked(sender)){return true;}
if(resource){sender.xmpp_resource=resource;}
Strophe.forEachChild(msg,null,function(e){var tagName=e.tagName.toLowerCase();this.debug(tagName);switch(tagName){case'composing':SD.Event.fire(null,this.Events.USER_TYPING,{user:sender});break;case'paused':SD.Event.fire(null,this.Events.USER_PAUSED_TYPING,{user:sender});break;case'body':var to=msg.getAttribute('to');var receiver=SD.User.getByChatID(to);var text=e.textContent||e.text;if(receiver&&sender&&text&&text.trim().length){if(!SD.Chat.amIChattingWith(sender)&&SD.ExperimentManager.PauseChats_4457.value&&SD.DatingController._pc.amIdle()==false){SD.User.saveChatAsFlirt(sender,text);return;};SD.ExperimentManager.getExperimentValue(SD.ExperimentManager.SaveExtraChatMsgsAsFlirt_4456,function(windowLimit){var dispatchEvent=windowLimit==0||SD.Chat.amIChattingWith(sender)||SD.Chat.getNumberOfPanels()<windowLimit;if(dispatchEvent){SD.Event.fire(null,this.Events.NEW_MESSAGE,{sender:sender,receiver:receiver,text:text.trim()});}else{SD.User.saveChatAsFlirt(sender,text);}}.bind(this));}}}.bind(this));return true;},onMessageFromFB:function(e){SD.Event.fire(null,this.Events.NEW_MESSAGE,{sender:e.memo.sender,receiver:e.memo.receiver,text:e.memo.text});},sendMessage:function(receiver,text,dontBlink){otherJid=receiver.chat_id;var subject=SD.UserInitiatedDate.amIDatingWith(receiver,true)?"date":"chat";var msg=$msg({to:otherJid,type:'chat'}).c('body').t(text).up().c('subject').t(subject);if(receiver.isFacebookUser()){SD.FBXMPP.getStropheConnection().send(msg);}else{var isValid=SD.UserInputFilter.isValid(text);if(isValid||SD.Model.getMyself().is_premium){SD.XMPP.getStropheConnection().send(msg);}}
SD.Event.fire(null,this.Events.NEW_MESSAGE,{sender:SD.Model.getMyself(),receiver:receiver,text:text,dontBlink:dontBlink});},sendTyping:function(receiver){otherJid=receiver.chat_id;var composing=$msg({to:otherJid,type:'chat'}).c('composing',{xmlns:"http://jabber.org/protocol/chatstates"});SD.XMPP.getStropheConnection().send(composing);},sendPausedTyping:function(receiver){otherJid=receiver.chat_id;var paused=$msg({to:otherJid,type:'chat'}).c('paused',{xmlns:"http://jabber.org/protocol/chatstates"});SD.XMPP.getStropheConnection().send(paused);},_onMessageError:function(msg){this.debug("on message error");this.debug(Strophe.serialize(msg));var otherJid=msg.getAttribute('from');var receiver=SD.User.getByChatID(otherJid);Strophe.forEachChild(msg,'body',function(e){var text=e.textContent||e.text;SD.Event.fire(null,this.Events.CHAT_MSG_FAILED,{receiver:receiver,text:text});}.bind(this));return true;},onMessageFailed:function(e){this.debug("on message failed");var receiver=e.memo.receiver;if(receiver.isFacebookUser()){return;}
var text=e.memo.text;this.addToFailedMsgs(receiver.uid,text);if(receiver.im_online){this.sendMessageAsImNotification(receiver,text);}},sendMessageAsImNotification:function(receiver,text){new Ajax.Request(SD.NavUtils.link('ajax','send_chat_msg_to_im'),{method:'post',parameters:{receiver_id:receiver.uid,text:text},onSuccess:function(e){if(e&&e.responseJSON){if(e.responseJSON.user_offline){receiver.im_online=false;}}}.bind(this),onFailure:function(e){}.bind(this)});},addToFailedMsgs:function(receiver_uid,msg){if(!this._failedMsgs[receiver_uid]){this._failedMsgs[receiver_uid]=[];}
this._failedMsgs[receiver_uid].push(msg);var delay=SD.Notification.IM.didRequestChat(receiver_uid)?100:15;this._sendAsOfflineChatMsg.bind(this).delay(delay,receiver_uid);},onUserAvailable:function(e){var notDelivered=this._failedMsgs[e.memo.user.uid];if(notDelivered){notDelivered.each(function(msg){this.sendMessage(e.memo.user,msg);}.bind(this));}
this._failedMsgs[e.memo.user.uid]=null;},_sendAsOfflineChatMsg:function(uid){var msgs=this._failedMsgs[uid];if(!msgs||!msgs.length){return;}
var text="";msgs.each(function(msg){text+=msg+"\n";});delete this._failedMsgs[uid];new Ajax.Request(SD.NavUtils.link('ajax','send_offline_chat'),{method:'post',parameters:{receiver_id:uid,text:text},onSuccess:function(e){if(e&&e.responseJSON&&e.responseJSON.result){SD.Event.fire(null,this.Events.SENT_OFFLINE_CHAT_MSG,{text:text,receiverUid:uid});}else{}}.bind(this),onFailure:function(e){this.addToFailedMsgs(uid,msg);}.bind(this)});},_onXMPPLogin:function(e){new Ajax.Request(SD.NavUtils.link('ajax','load_offline_chat_msgs'),{method:'post',parameters:{unread:true},onSuccess:function(e){if(e&&e.responseJSON&&e.responseJSON.result){var msgs=e.responseJSON.msgs;this.debug(msgs);if(msgs.length){SD.Event.fire(null,this.Events.RECEIVED_OFFLINE_CHAT_MSGS,msgs);}}else{}}.bind(this),onFailure:function(e){}.bind(this)});},Events:{NEW_MESSAGE:"sd_chat_msg_listener:msg",CHAT_MSG_FAILED:"sd_chat_msg_listener:msg_failed",SENT_OFFLINE_CHAT_MSG:"sd_chat_msg_listener:sent_offline_chat_msg",RECEIVED_OFFLINE_CHAT_MSGS:"sd_chat_msg_listener:received_offline_chat_msgs",USER_TYPING:"sd_chat_msg_listener:user_typing",USER_PAUSED_TYPING:"sd_chat_msg_listener:user_paused_typing"}};
SD.UI.Elements={MAIL_SUBJECT:'SD.UI.Elements.MAIL_SUBJECT',NOTIFICATION:'SD.UI.Elements.NOTIFICATION'};SD.UI.Common={extractUser:function(el){var uid=el.getAttribute('sdUid')||0;var user=SD.User.get(uid);if(!user.fetched){user.username=el.getAttribute('sdUserName');user.online=(el.getAttribute('sdOnline')=='true');user.relation={isFavorite:el.getAttribute('sdFavorite')=='true'};}
return user;},getUid:function(el){return el.getAttribute('sdUid')||0;}};SD.UI.Share={init:function(){SD.Event.delegate('share',this.delegates);},delegates:{'click':function(e){var el=e.sdTarget;SD.User.fetch(SD.UI.Common.extractUser(el),function(oUser){SD.UIController.facebookSharePopup({actionType:SD.UIController.ActionTypes.SHARE_PROFILE,actionData:'{"sharedMemberId": "'+oUser.uid+'"}'});});},'mouseover':function(e){var el=e.sdTarget;var oUser=SD.UI.Common.extractUser(el);SD.Tooltip.show('Share <b>'+oUser.username+'</b>\'s profile with your friends!');},'mouseout':function(e){SD.Tooltip.hide();}}};SD.UI.Share.init();SD.UI.Wink={init:function(){SD.Event.delegate('wink',this.delegates);},delegates:{'click':function(e){var el=e.sdTarget;var oUser=SD.UI.Common.extractUser(el);SD.FlowManager.run(SD.Flows.wink.clone(),SD.Utils.buildContext({sourceType:SD.UIController.PopupSourceTypes.WINK,sourceMemberId:oUser.uid,sourceMember:oUser,onActionEnd:null,recommendActionType:'winked at',actionType:SD.UIController.ActionTypes.REGULAR_INVITATION},e));},'mouseover':function(e){var el=e.sdTarget;var oUser=SD.UI.Common.extractUser(el);if(oUser.fetched){SD.Tooltip.show('Wink at <b>'+oUser.username+'</b>');}},'mouseout':function(e){SD.Tooltip.hide();}}};SD.UI.Wink.init();SD.UI.Flirt={init:function(){SD.Event.delegate('flirt',this.delegates);},delegates:{'click':function(e){var el=e.sdTarget;var oUser=SD.UI.Common.extractUser(el);SD.FlowManager.run(SD.Flows.dialogEmail.clone(),SD.Utils.buildContext({sourceType:SD.UIController.PopupSourceTypes.EMAIL,sourceMemberId:oUser.uid,sourceMember:oUser,sourceUI:'FlirtButton',onActionEnd:null,recommendActionType:'emailed',actionType:SD.UIController.ActionTypes.REGULAR_INVITATION},e));},'mouseover':function(e){var el=e.sdTarget;var oUser=SD.UI.Common.extractUser(el);var sdTTOrientation=el.getAttribute('sdTTOrientation');if(!oUser.fetched){SD.Tooltip.show('Send a message to <b>'+oUser.username+'</b>',null,null,sdTTOrientation);}else if(oUser.relation.permissions){if(SD.Config.platform.platformId!=3){if(!SD.Model.getMyself().has_photo){SD.Tooltip.show('Send a message to <b>'+oUser.username+'</b>',null,null,sdTTOrientation);}else{if(!oUser.relation.permissions.can_flirt){SD.Tooltip.show('Send message to <b>'+oUser.username+'</b>',null,null,sdTTOrientation);}else{SD.Tooltip.show('Send message to <b>'+oUser.username+'</b>',null,null,sdTTOrientation);}}}}},'mouseout':function(e){SD.Tooltip.hide();}}};SD.UI.Flirt.init();SD.UI.ViewConversation={init:function(){SD.Event.delegate('view_conversation',this.delegates);},delegates:{'click':function(e){var el=e.sdTarget;var oUser=SD.UI.Common.extractUser(el);SD.Event.fire(null,SD.UI.Events.VIEW_CONVERSATION,{sourceMemberId:oUser.uid,viewMessageUrl:SD.NavUtils.goTo('messages','flirt',{id:SD.UI.Common.getUid(el)}),domEvent:e});},'mouseover':function(e){var el=e.sdTarget;var oUser=SD.UI.Common.extractUser(el);SD.Tooltip.show('View your conversation history with <b>'+oUser.username+'</b>');},'mouseout':function(e){SD.Tooltip.hide();}}};SD.UI.ViewConversation.init();SD.UI.Date={allowFullDating:false,init:function(){SD.Event.delegate('date',this.delegates);SD.Event.delegate('remove-date',this.removeDateDelegates);},delegates:{'click':function(e){var el=e.sdTarget;SD.User.fetch(SD.UI.Common.extractUser(el),function(oUser){var context=SD.Utils.buildContext({sourceMember:oUser,sourceType:oUser.online?SD.UIController.PopupSourceTypes.DATE:SD.UIController.PopupSourceTypes.INVITE_TO_DATE},e);SD.UI.Date.allowFullDating?SD.FlowManager.run(SD.Flows.basicDate.clone(),context):SD.FlowManager.run(SD.Flows.date.clone(),context)});},'mouseover':function(e){var el=e.sdTarget;var oUser=SD.UI.Common.extractUser(el);if(SD.Config.platform.platformId!=3){if(oUser.online||el.getAttribute("sdsource")=="dating_list"){if(SD.UserInitiatedDate.shallTry(oUser)){SD.Tooltip.show('Click to start a SpeedDate with <b>'+oUser.username+'</b> now!',200,null,el.getAttribute("sdTTOrientation"));}else{SD.Tooltip.show('You already SpeedDated with <b>'+oUser.username+'</b> Try sendng a flirt!',200,null,el.getAttribute("sdTTOrientation"));}}else{SD.Tooltip.show((SD.Model.getMyself().is_premium?'':SD.UIController.getInlineSubBadge())+'Add <b>'+oUser.username+'</b> '+'to the list of members you want to SpeedDate. When both of you are online, we\'ll connect you!',200,null,el.getAttribute("sdTTOrientation"));}}},'mouseout':function(e){SD.Tooltip.hide();}},removeDateDelegates:{'click':function(e){var targetElement=$(e.sdTarget);if(targetElement.isBlocked)return;targetElement.isBlocked=true;SD.Tooltip.hide();SD.User.fetch(SD.UI.Common.extractUser(targetElement),function(oUser){if(targetElement.hasClassName("remove-date")){SD.FlirtWink.View.removeDate(oUser,function(){targetElement.removeClassName("remove-date");targetElement.addClassName("date");SD.UIController.infoMessage(oUser.username+" has been removed from the list of people you want to SpeedDate.");targetElement.isBlocked=false;});}else{targetElement.isBlocked=false;SD.FlirtWink.View.date(oUser,function(){targetElement.removeClassName("date");targetElement.addClassName("remove-date");SD.UIController.infoMessage("SpeedDating Request for User "+oUser.username+" Successful!");},e);}});},'mouseover':function(e){var el=$(e.sdTarget);var oUser=SD.UI.Common.extractUser(el);if(el.hasClassName("remove-date")){SD.Tooltip.show('Remove <b>'+oUser.username+'</b> from members you want to SpeedDate.');}else{SD.Tooltip.show('Add <b>'+oUser.username+'</b> '+'to the list of members you want to SpeedDate. When both of you are online, we\'ll connect you!');}},'mouseout':function(e){SD.Tooltip.hide();}}};SD.UI.Date.init();SD.UI.Favorite=(function(){var onFavoriteSuccess=function(targetElement){var classOnFavorite;targetElement.setAttribute("sdFavorite","true");if($(targetElement).hasClassName('add-favorite')){targetElement.removeClassName('add-favorite');targetElement.addClassName('added-favorite');}
if((classOnFavorite=$(targetElement).getAttribute('sdClassOnFavorite'))){targetElement.addClassName(classOnFavorite);}};return{init:function(){SD.Event.delegate('favorite',this.favoriteDelegates);SD.Event.delegate('remove-favorite',this.removeFavoriteDelegates);},favoriteDelegates:{'click':function(e){var el=e.sdTarget;SD.User.fetch(SD.UI.Common.extractUser(el),function(oUser){SD.FlowManager.run(SD.Flows.favorite.clone(),SD.Utils.buildContext({sourceMember:oUser,recommendActionType:'favorited',sourceType:SD.UIController.PopupSourceTypes.ADD_TO_FAVORITES,onActionEnd:onFavoriteSuccess.curry(el)},e));});},'mouseover':function(e){var el=e.sdTarget;var oUser=SD.UI.Common.extractUser(el);if(oUser.relation.isFavorite){SD.Tooltip.show('<b>'+oUser.username+'</b> is in your favorites list.');}else{SD.Tooltip.show('Add <b>'+oUser.username+'</b> to your favorites list.');}},'mouseout':function(e){SD.Tooltip.hide();}},removeFavoriteDelegates:{'click':function(e){var targetElement=$(e.sdTarget);if(targetElement.isBlocked){return;}
targetElement.isBlocked=true;SD.User.fetch(SD.UI.Common.extractUser(targetElement),function(oUser){if(targetElement.hasClassName("remove-favorite")){SD.FlowManager.run(SD.Actions.unfavorite.clone(),SD.Utils.buildContext({sourceMember:oUser,onActionEnd:function(){targetElement.removeClassName("remove-favorite");targetElement.addClassName("add-favorite");SD.UIController.infoMessage(oUser.username+" has been removed from your favorites!");targetElement.isBlocked=false;targetElement.setAttribute("sdFavorite","false");}},e));}else{targetElement.isBlocked=false;SD.FlowManager.run(SD.Actions.unfavorite.clone(),SD.Utils.buildContext({sourceMember:oUser,onActionEnd:function(){targetElement.removeClassName("add-favorite");targetElement.addClassName("remove-favorite");SD.UIController.infoMessage(oUser.username+" has been added to your favorites!");targetElement.setAttribute("sdFavorite","true");}},e));}});},'mouseover':function(e){var el=e.sdTarget;var oUser=SD.UI.Common.extractUser(el);if(oUser.relation.isFavorite){SD.Tooltip.show('Remove <b>'+oUser.username+'</b> from your favorites list.');}else{SD.Tooltip.show('Add <b>'+oUser.username+'</b> to your favorites list.');}},'mouseout':function(e){SD.Tooltip.hide();}}};})();SD.UI.Favorite.init();SD.UI.ChatButton={init:function(){SD.Event.delegate('chat',this.delegates);SD.Event.observe(null,SD.User.Events.USER_ONLINE,function(e){if(e.memo&&e.memo.user){$$("[sdtype='chat'][sduid='"+e.memo.user.uid+"']").each(function(el){var clsOn=el.getAttribute('sdClassOn')||"chat-enabled";var clsOff=el.getAttribute('sdClassOff')||"chat-disabled";SD.UI.ChatButton.replaceClassName(el,clsOff,clsOn);el.setAttribute('sdOnline','true');});}});SD.Event.observe(null,SD.User.Events.USER_OFFLINE,function(e){if(e.memo&&e.memo.user){$$("[sdType='chat'][sdUid='"+e.memo.user.uid+"']").each(function(el){var clsOn=el.getAttribute('sdClassOn')||"chat-enabled";var clsOff=el.getAttribute('sdClassOff')||"chat-disabled";SD.UI.ChatButton.replaceClassName(el,clsOn,clsOff);el.setAttribute('sdOnline','false');});}});},replaceClassName:function(el,oldClass,newClass){if(newClass){el.removeClassName(oldClass);el.addClassName(newClass);}},delegates:{'click':function(e){var targetElement=$(e.sdTarget);var tc=(targetElement.getAttribute('sdtc')||"0").evalJSON();SD.User.fetch(SD.UI.Common.extractUser(targetElement),function(oUser){if(oUser.isFacebookUser()){SD.Chat.chatWithUser(oUser);}else{SD.FlirtWink.View.chat(oUser,Prototype.emptyFunction,tc,e);}});return;},'mouseover':function(e){var targetElement=$(e.sdTarget);var oUser=SD.UI.Common.extractUser(targetElement);oUser.online=(targetElement.getAttribute('sdOnline')=='true')||oUser.online;oUser.im_online=(targetElement.getAttribute('sdimonline')&&targetElement.getAttribute('sdimonline')>>>0)||oUser.im_online;var sdTTOrientation=targetElement.getAttribute('sdTTOrientation');if(oUser.isFacebookUser&&oUser.isFacebookUser()){SD.Tooltip.show('Chat with <b>'+oUser.username+'</b>');return;}
if(!oUser.online&&!oUser.im_online){if(SD.Model.getMyself().wantsToDate(oUser)){SD.Tooltip.show('You already sent a SpeedDate&trade; invitation to <b>'+oUser.username+'</b>. We will notify you when '+oUser.toHeShe()+' comes online.',null,null,sdTTOrientation);}else if(SD.Model.getMyself().mightDate(oUser)){SD.Tooltip.show('<b>'+oUser.username+'</b> is not online right now. Invite '+oUser.username+' to SpeedDate and we\'ll let you know when '+oUser.toHeShe()+' comes online.');}else{SD.Tooltip.show('<b>'+oUser.username+'</b> is offline right now. Your message will be delivered when '+oUser.username+' comes online.',null,null,sdTTOrientation);}
return;}
if(SD.Chat.needUpgradeForChat(oUser)){var f=function(){if(!oUser.online&&oUser.im_online){SD.Tooltip.show('<b>'+oUser.username+'</b> is online on SpeedDate IM.<br/>'+'Click to send a chat request to <b>'+oUser.username+'</b>.',null,null,sdTTOrientation);}else{if(SD.UserInitiatedDate.shallTry(oUser)){SD.Tooltip.show('Click to start a SpeedDate with <b>'+oUser.username+'</b>.',null,null,sdTTOrientation);}else{SD.Tooltip.show(SD.UIController.getInlineSubBadge('Subscribe')+' to chat with <b>'+oUser.username+'</b>.',null,null,sdTTOrientation);}}};f();}else{if(oUser.online){SD.Tooltip.show('Chat with <b>'+oUser.username+'</b>',null,null,sdTTOrientation);}else{SD.Tooltip.show('<b>'+oUser.username+'</b> is online on SpeedDate IM.<br/>Click to send a chat request',null,null,sdTTOrientation);}}},'mouseout':function(e){SD.Tooltip.hide();}}};SD.UI.ChatButton.init();SD.UI.SignupProfile={init:function(){SD.Event.delegate('signup-profile',this.delegates);},delegates:{'click':function(e){var lightbox=$('signup-light-box');var bodyWidth=$$('.site-body-wrapper')[0].getWidth();var popupWidth=$$('.popup-container')[0].getWidth();lightbox.style.width=bodyWidth+"px";lightbox.style.left="-"+(bodyWidth-popupWidth)/2+"px";$("popup").style.visibility="visible";lightbox.style.visibility='visible';$$('.site-header-section')[0].style.zIndex=0;if(Prototype.Browser.IE6){$$('.search-filter select').each(function(elem,index){elem.disable();elem.style.backgroundColor="#BBBBBB";});$$('.site-header-section.non-member')[0].style.zIndex=1;}
Event.element(e).ancestors().each(function(el){if(el.hasClassName('member-container')&&el.readAttribute('sdUserName')){$$('.signup-title').first().update('Signup for free to meet '+el.readAttribute('sdUserName'));}});},'mouseover':function(e){var el=e.sdTarget;var username=el.getAttribute('sdUserName');SD.Tooltip.show('View <b>'+username+'\'s</b> profile',null,null,el.getAttribute("sdTTOrientation"));},'mouseout':function(e){var el=e.sdTarget;if(el.getAttribute('notooltip')){return;}
SD.Tooltip.hide();}}};SD.UI.SignupProfile.init();SD.UI.Profile={init:function(){SD.Event.delegate('profile',this.delegates);},delegates:{'click':function(e){var el=e.sdTarget;var uid=el.getAttribute("sdUid");if(!uid){return;}
var user=SD.User.get(uid);if(user.isFacebookUser()){return;}
var tabId=el.getAttribute("sdTab");var actionLog=el.getAttribute("sdActionLog");if(actionLog){new Ajax.Request(SD.NavUtils.link('ajax','add_action_log'),{method:'post',evalJSON:true,parameters:{you:uid,action_log:actionLog}});}
SD.ProfileViewer.UI.view(uid);SD.Chat.activateUserPanel(SD.User.get(uid),false);if(tabId){if(SD.FlirtWink.View.getFlirtee().uid==uid){SD.FlirtWink.View.activateTabMenu(tabId);}else{SD.Event.observeOnce(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(){setTimeout(function(){SD.FlirtWink.View.activateTabMenu(tabId);},100);});}}},'mouseover':function(e){var el=e.sdTarget;if(el.getAttribute('notooltip')){return;}
var user=SD.User.get(el.getAttribute('sdUid'));var username=el.getAttribute('sdUserName')||user.username;var message=el.getAttribute("sdMessage");if(user.isFacebookUser()){return;}else{SD.Tooltip.show(message||'View <b>'+username+'\'s</b> profile',null,null,el.getAttribute("sdTTOrientation"));}},'mouseout':function(e){var el=e.sdTarget;if(el.getAttribute('notooltip')){return;}
SD.Tooltip.hide();}}};SD.UI.Profile.init();SD.UI.SignupPopup={init:function(){SD.Event.delegate('signup-popup',this.delegates);},delegates:{'click':function(e){var lightbox=$('signup-light-box');var bodyWidth=$$('.site-body-wrapper')[0].getWidth();var popupWidth=$$('.popup-container')[0].getWidth();lightbox.style.width=bodyWidth+"px";lightbox.style.left="-"+(bodyWidth-popupWidth)/2+"px";$("popup").style.visibility="visible";lightbox.style.visibility='visible';$$('.site-header-section')[0].style.zIndex=0;if(Prototype.Browser.IE6){$$('.search-filter select').each(function(elem,index){elem.disable();elem.style.backgroundColor="#BBBBBB";});$$('.site-header-section.non-member')[0].style.zIndex=1;}
Event.element(e).ancestors().each(function(el){if(el.hasClassName('member-container')&&el.readAttribute('sdUserName')){$$('.signup-title').first().update('Signup for free to meet '+el.readAttribute('sdUserName'));}});},'mouseover':function(e){var el=e.sdTarget;var username=el.getAttribute('sdusername');var tooltipType=el.getAttribute('sdTooltip');var message='';if(tooltipType==='excludeUser'){message='Don\'t show <b>'+username+'</b> in my search results.';}else if(tooltipType==='flirt'){message='Send message to <b>'+username;}else if(tooltipType==='wink'){message='Wink at <b>'+username;}else if(tooltipType==='favourite'){message='Add <b>'+username+'</b> to your favorites list.';}else if(tooltipType==='chat'){message='Chat with <b>'+username+'</b>';}
SD.Tooltip.show(message);},'mouseout':function(e){SD.Tooltip.hide();}}}
SD.UI.SignupPopup.init();SD.UI.ExcludeUser={init:function(){SD.Event.delegate('excludeUser',this.delegates);},delegates:{'click':function(e){var el=e.sdTarget;var id=el.getAttribute('sduid');var username=el.getAttribute('sdusername');SD.User.excludeUser(id,username);$(el).addClassName('m-exclude-undo');el.setAttribute('sdType','undoExclusion');SD.Tooltip.hide();SD.Tooltip.show('Show <b>'+username+'</b> in my search results.');},'mouseover':function(e){var el=e.sdTarget;var username=el.getAttribute('sdusername');SD.Tooltip.show('Don\'t show <b>'+username+'</b> in my search results.');},'mouseout':function(e){SD.Tooltip.hide();}}};SD.UI.ExcludeUser.init();SD.UI.ExcludeUserFromProfilePage={init:function(){SD.Event.delegate('excludeUserFromProfilePage',this.delegates);},delegates:{'click':function(e){var el=e.sdTarget;var id=el.getAttribute('sduid');var username=el.getAttribute('sdusername');SD.User.excludeUser(id,username);SD.Tooltip.hide();},'mouseover':function(e){var el=e.sdTarget;var username=el.getAttribute('sdusername');SD.Tooltip.show('Don\'t show me <b>'+username+'</b> anymore and take me to the next match.');},'mouseout':function(e){SD.Tooltip.hide();}}};SD.UI.ExcludeUserFromProfilePage.init();SD.UI.UndoExclusion={init:function(){SD.Event.delegate('undoExclusion',this.delegates);},delegates:{'click':function(e){var el=e.sdTarget;var id=el.getAttribute('sduid');var username=el.getAttribute('sdusername');SD.User.undoExclusion(id,username);$(el).removeClassName('m-exclude-undo');el.setAttribute('sdType','excludeUser');SD.Tooltip.hide();SD.Tooltip.show('Don\'t show <b>'+username+'</b> in my search results.');},'mouseover':function(e){var el=e.sdTarget;var username=el.getAttribute('sdusername');SD.Tooltip.show('Show <b>'+username+'</b> in my search results.');},'mouseout':function(e){SD.Tooltip.hide();}}};SD.UI.UndoExclusion.init();SD.UI.Tooltip={init:function(){SD.Event.delegate('tooltip',this.delegates);},extractMessage:function(el){var msg=el.getAttribute("sdMessage");if(!msg){el=el.firstChild&&(el.firstChild.nodeType===1?el.firstChild:el.firstChild.nextSibling);if(el&&el.getAttribute('sdType')=='sdMessage'){msg=el.innerHTML;}}
return msg||'';},delegates:{'mouseover':function(e){var el=e.sdTarget;var msg=SD.UI.Tooltip.extractMessage(el);var maxWidth=null;var width=null;if(el.getAttribute("sdMaxWidth")){maxWidth=parseInt(el.getAttribute("sdMaxWidth"));}
if(el.getAttribute("sdWidth")){width=parseInt(el.getAttribute("sdWidth"));}
SD.Tooltip.show(msg,width,maxWidth,el.getAttribute("sdTTOrientation"));},'mouseout':function(e){SD.Tooltip.hide();}}};SD.UI.Tooltip.init();SD.UI.SignupMemberView={init:function(){SD.Event.delegate('signup-memberview',this.delegates);},delegates:{'click':function(e){var lightbox=$('signup-light-box');var bodyWidth=$$('.site-body-wrapper')[0].getWidth();var popupWidth=$$('.popup-container')[0].getWidth();lightbox.style.width=bodyWidth+"px";lightbox.style.left="-"+(bodyWidth-popupWidth)/2+"px";$("popup").style.visibility="visible";lightbox.style.visibility='visible';$$('.site-header-section')[0].style.zIndex=0;if(Prototype.Browser.IE6){$$('.search-filter select').each(function(elem,index){elem.disable();elem.style.backgroundColor="#BBBBBB";});$$('.site-header-section.non-member')[0].style.zIndex=1;}
Event.element(e).ancestors().each(function(el){if(el.hasClassName('member-container')&&el.readAttribute('sdUserName')){$$('.signup-title').first().update('Signup for free to meet '+el.readAttribute('sdUserName'));}});},'mouseenter':function(e){var el=$(e.sdTarget);var m_button=el.select('.m-buttons').first();var m_chat=el.select('.m-chat').first();var m_exclude=el.select('.m-exclude').first();var info_container=el.select('.m-info-container').first();m_button&&m_button.show();info_container&&info_container.addClassName('m-profile-selected');m_exclude&&m_exclude.show();if(m_chat){m_chat._display=m_chat.style.display;m_chat.addClassName('m-inactive');m_chat.show();}},'mouseleave':function(e){var el=$(e.sdTarget);var m_button=el.select('.m-buttons').first();var m_chat=el.select('.m-chat').first();var m_exclude=el.select('.m-exclude').first();var info_container=el.select('.m-info-container').first();m_button&&m_button.hide();m_exclude&&m_exclude.hide();info_container&&info_container.removeClassName('m-profile-selected');if(m_chat){m_chat.style.display=m_chat._display;m_chat.removeClassName('m-inactive');}}}};SD.UI.SignupMemberView.init();SD.UI.MemberView={init:function(){SD.Event.delegate('memberview',this.delegates);},delegates:{'mouseenter':function(e){var el=$(e.sdTarget);var m_button=el.select('.m-buttons').first();var m_chat=el.select('.m-chat').first();var m_exclude=el.select('.m-exclude').first();var info_container=el.select('.m-info-container').first();m_button&&m_button.show();info_container&&info_container.addClassName('m-profile-selected');m_exclude&&m_exclude.show();if(m_chat){m_chat._display=m_chat.style.display;m_chat.addClassName('m-inactive');m_chat.show();}},'mouseleave':function(e){var el=$(e.sdTarget);if(el.getAttribute('sdFrozen')){return;}
var m_button=el.select('.m-buttons').first();var m_chat=el.select('.m-chat').first();var m_exclude=el.select('.m-exclude').first();var info_container=el.select('.m-info-container').first();m_button&&m_button.hide();m_exclude&&m_exclude.hide();info_container&&info_container.removeClassName('m-profile-selected');if(m_chat){m_chat.style.display=m_chat._display;m_chat.removeClassName('m-inactive');}}}};SD.UI.MemberView.init();SD.UI.SimpleLink={init:function(){SD.Event.delegate('simplelink',this.delegates);},delegates:{'click':function(e){var el=e.sdTarget;var controller=el.getAttribute('sdController');var action=el.getAttribute('sdAction');var parameters=el.getAttribute('sdParameters');parameters=parameters&&eval('('+parameters+')');SD.NavUtils.goTo(controller,action,parameters);}}};SD.UI.SimpleLink.init();SD.UI.UpgradeLink={init:function(){SD.Event.delegate('upgradeLink',this.delegates);},delegates:{'click':function(e){if(SD.Model.getMyself().is_premium){return;}
var el=e.sdTarget;var tc=el.getAttribute('sdTc')||'';var ti=el.getAttribute('sdTi')||'';var sourceType=el.getAttribute('sdSourceType')||'';var sourceMemberId=el.getAttribute('sdSourceMemberId')||'';var expandedMode=el.getAttribute('sdExpandedMode')||'';var modTooltip=el.getAttribute('sdModTooltip')?true:false;SD.FlowManager.run(SD.Actions.subscribe.clone(),{tc:tc,ti:ti,sourceType:sourceType,sourceMemberId:sourceMemberId,expandedMode:expandedMode,modTooltip:modTooltip});}}};SD.UI.UpgradeLink.init();SD.UI.SpeedVerifyLink={init:function(){SD.Event.delegate('speedverify',this.delegates);},delegates:{'click':function(e){if(SD.Model.getMyself().is_premium){return;}
var el=e.sdTarget;var tc=el.getAttribute('sdTc')||'';var ti=el.getAttribute('sdTi')||'';var sourceType=el.getAttribute('sdSourceType')||'';var sourceMemberId=el.getAttribute('sdSourceMemberId')||'';var modTooltip=el.getAttribute('sdModTooltip')?true:false;SD.FlowManager.run(SD.Actions.speedVerifyDialog.clone(),{tc:tc,ti:ti,sourceType:sourceType,sourceMemberId:sourceMemberId,modTooltip:modTooltip});}}};SD.UI.SpeedVerifyLink.init();SD.UI.Rating=function(){var _this;function canVote(el){var userRating=el.getAttribute('sdUserRating');return userRating===null||userRating===undefined||isNaN(userRating)||userRating=='';}
function setRating(el,r){el.setAttribute('sdRating',r);_this.setStyle(el,r);}
function setTotal(el,r){el.setAttribute('sdTotalRating',r);}
function getRatingFromElement(el){var a=el.className.split(" ");return parseInt(a[0].substring(1,a[0].length));}
function getRateNumElement(el){return $(el.getAttribute('sdTotalRatingId'));}
function getFormatedRating(el){var mod=parseInt(el.getAttribute('sdUserRating'))%2;var stars=Math.floor(parseInt(el.getAttribute('sdUserRating'))/2);var starsLabel=stars>1?'stars':'star';stars=stars||'';return'<b>'+stars+(mod?"&#0189":'')+'</b> '+starsLabel;}
function calculateAverageRating(rating,userRating,votes){return Math.round(rating+userRating/votes);}
function sendUserRating(el){var url=SD.NavUtils.link('ajax','add_rating');(function(userRating,rating,totalVotes){return new Ajax.Request(url,{method:'get',evalJSON:true,parameters:{rating:userRating,other_memberid:el.getAttribute("sdUid")},onSuccess:function(result){if(result.responseJSON){if(result.responseJSON.totalRating!=totalVotes){totalVotes=result.responseJSON.totalRating;userRating=result.responseJSON.userRating;rating=result.responseJSON.rating;}else{totalVotes++;rating=calculateAverageRating(rating,userRating,totalVotes);}
el.setAttribute('sdUserRating',userRating);el.setAttribute('sdTotalRating',totalVotes);el.setAttribute('sdRating',rating);_this.setStyle(el,rating);if(el.getAttribute('sdTotalRatingId')){getRateNumElement(el).update(totalVotes);}}}})})(getRatingFromElement(el),parseInt(el.getAttribute('sdRating')),parseInt(el.getAttribute('sdTotalRating')));}
_this={init:function(){SD.Event.delegate('rating',this.delegates);},setStyle:function(el,r){var baseClass=el.className.split(' ');el.className="r"+r+' '+baseClass[1];},delegates:{'mouseover':function(e){var x=0;var oX=0;var el=$(e.sdTarget);var username=el.getAttribute('sdUserName')||SD.User.get(el.getAttribute('sdUid')).username;SD.Tooltip.show(canVote(el)?"Rate <b>"+username+"'s</b> profile!":"You have already given "+getFormatedRating(el)+" to this profile.");oX=el.cumulativeOffset().left;if(canVote(el)){el.onmousemove=function(e){x=(e||window.event).clientX-oX;var r=Math.ceil((x/el.offsetWidth)*10);r=Math.max(Math.min(r,10),1);_this.setStyle(el,r);}}},'mouseout':function(e){var el=$(e.sdTarget);_this.setStyle(el,el.getAttribute('sdRating'));el.onmousemove=null;SD.Tooltip.hide();},'click':function(e){var el=$(e.sdTarget);canVote(el)&&sendUserRating(el);}}}
return _this;}();SD.UI.Rating.init();SD.UI.Rater={init:function(){SD.Event.delegate('rater',this.delegates);},setStyle:function(el,r){var classes=el.className.split(' ');classes[0]="r"+r;el.className=classes.join(' ');},getRatingFromElement:function(el){var classes=el.className.split(" ");return parseInt(classes[0].substring(1,classes[0].length));},delegates:{'mouseover':function(e){var x=0,offsetX=0,el=$(e.sdTarget),username=el.getAttribute('sdUserName');SD.Tooltip.show(el.getAttribute('sdMessage').interpolate({username:username}));offsetX=el.cumulativeOffset().left;el.onmousemove=function(e){x=(e||window.event).clientX-offsetX;var r=Math.ceil((x/el.offsetWidth)*10);r=Math.max(Math.min(r,10),1);SD.UI.Rater.setStyle(el,r);}},'mouseout':function(e){var el=e.sdTarget;SD.UI.Rater.setStyle(el,el.getAttribute('sdRating')||0);el.onmousemove=null;SD.Tooltip.hide();},'click':function(e){var el=e.sdTarget;var rating=SD.UI.Rater.getRatingFromElement(el);el.setAttribute('sdRating',rating);SD.Event.fire(SD.UI.Rater,SD.UI.Rater.Events.RATE,{rating:rating,uid:el.getAttribute('sdUid'),token:el.getAttribute('sdToken')});}},Events:{RATE:'SD.UI.Rater.Events:RATE'}};SD.UI.Rater.init();SD.UI.FriendRater={init:function(){SD.Event.delegate('friend-rater',this.delegates);},setStyle:function(el,r){var classes=el.className.split(' ');classes[0]="r"+r;el.className=classes.join(' ');},getRatingFromElement:function(el){var classes=el.className.split(" ");return parseInt(classes[0].substring(1,classes[0].length));},delegates:{'mouseover':function(e){var x=0,offsetX=0,el=$(e.sdTarget),username=el.getAttribute('sdUsername');SD.Tooltip.show(el.getAttribute('sdMessage').interpolate({username:username}));offsetX=el.cumulativeOffset().left;el.onmousemove=function(e){x=(e||window.event).clientX-offsetX;var r=Math.ceil((x/el.offsetWidth)*10);r=Math.max(Math.min(r,10),1);SD.UI.FriendRater.setStyle(el,r);}},'mouseout':function(e){var el=e.sdTarget;SD.UI.FriendRater.setStyle(el,el.getAttribute('sdRating')||0);el.onmousemove=null;SD.Tooltip.hide();},'click':function(e){var el=e.sdTarget;var rating=SD.UI.FriendRater.getRatingFromElement(el);el.setAttribute('sdRating',rating);SD.Event.fire(SD.UI.FriendRater,SD.UI.FriendRater.Events.RATE,{rating:rating,uid:el.getAttribute('sdUid'),friendUid:el.getAttribute('sdFriendUid'),token:el.getAttribute('sdToken'),publish:$(el.getAttribute('sdPublishControllerId')).checked});}},Events:{RATE:'SD.UI.Rater.Events:RATE'}};SD.UI.FriendRater.init();SD.UI.ReportPhoto={init:function(){SD.Event.delegate('reportPhoto',this.delegates);},delegates:{'click':function(e){var el=e.sdTarget;SD.Dialogs.dialogReportPhoto(SD.UI.Common.extractUser(el));},'mouseover':function(e){var el=e.sdTarget;SD.Tooltip.show('Report if you believe <b>'+SD.UI.Common.extractUser(el).username+'</b> should be banned from using SpeedDate.');},'mouseout':function(){SD.Tooltip.hide();}}};SD.UI.ReportPhoto.init();SD.UI.FieldValidation={init:function(){SD.Event.delegate('validate',this.delegates);},delegates:{'blur':function(e){var el=e.sdTarget;var form=el.form;var controller=el.getAttribute('sdController')||(form.elements.controller&&form.elements.controller.value);if(!controller||!form||el.lastValue===el.value){return;}
el.lastValue=el.value;var action=el.getAttribute('sdAction')||(form.elements.action&&form.elements.action.value)||'';var formType=el.getAttribute('sdFormType')||(form.elements['form_type']&&form.elements['form_type'].value)||'';var dependencies=el.getAttribute('sdDependencies');var values={};if(dependencies){var d=dependencies.split(',');var elName;for(var i=0;i<d.length;i++){elName=d[i].trim();values[elName]=form.elements[elName].value;}}
Object.extend(values,{'form_type':formType,'validate_field':el.name,'validate_value':typeof el.value=="string"?el.value:el.value.join(',')});var ajaxIndicator=$(el.parentNode).select('.ajax-indicator').first();ajaxIndicator&&(ajaxIndicator.style.display='block');(new Ajax.Request(SD.NavUtils.link(controller,action),{method:'get',evalJSON:true,parameters:values,onComplete:function(result){ajaxIndicator&&(ajaxIndicator.style.display='none');if(result.responseJSON&&result.responseJSON.status){var errorText=$(el.parentNode).select('.error-text').first();if(result.responseJSON.status=='OK'&&errorText){errorText.hide();}else if(result.responseJSON.status=='FAIL'&&errorText){errorText.show();if(result.responseJSON.message){errorText.update(result.responseJSON.message);}}}}}));}}};SD.UI.FieldValidation.init();SD.UI.InnerLabel={init:function(){SD.Event.delegate('inner-label',this.delegates);},delegates:{'focus':function(e){var el=$(e.sdTarget);var sdLabel=el.getAttribute("sdLabel");if(!sdLabel){return;}
if(sdLabel&&el.value.trim()==sdLabel&&el.getAttribute("edited")!=1){el.value='';}
var sdClassLabel=el.getAttribute("sdClassLabel");var sdDisabledClassLabel=el.getAttribute("sdDisabledClassLabel");if(sdClassLabel){el.removeClassName(sdClassLabel);}
if(sdDisabledClassLabel){el.removeClassName(sdDisabledClassLabel);}},'blur':function(e){var el=e.sdTarget;var sdClassLabel=el.getAttribute("sdClassLabel");var sdLabel=el.getAttribute("sdLabel");if(!sdLabel){return;}
if(sdClassLabel&&sdLabel!=el.value){el.removeClassName(sdClassLabel);}
if(el.value==''){sdClassLabel&&el.addClassName(sdClassLabel);el.value=sdLabel;}}}};SD.UI.InnerLabel.init();SD.UI.TextCounter={init:function(){SD.Event.delegate('text-counter',this.delegates);},delegates:{'keyup':function(e){var el=e.sdTarget;var maxChars=parseInt(el.getAttribute('sdMaxChars'),10);var domIndicator=$(el.getAttribute('sdIndicator'));if(!domIndicator){return;}
if(el.sdLabel&&el.sdLabel!==''&&el.sdLabel===el.value){return;}
var charsLeft=Math.max(maxChars-el.value.length,0);domIndicator.innerHTML=charsLeft;}}};SD.UI.TextCounter.init();SD.UI.Block={init:function(){SD.Event.delegate('block',this.delegates);},delegates:{'click':function(e){var el=e.sdTarget;var oUser=SD.UI.Common.extractUser(el);oUser&&SD.Event.fire(null,SD.UIController.Events.BLOCK_BUDDY_REQUESTED,{user:oUser});},'mouseover':function(e){var el=e.sdTarget;var oUser=SD.UI.Common.extractUser(el);SD.Tooltip.show('Block <b>'+(oUser.username||el.getAttribute('sdUserName'))+'</b>');},'mouseout':function(e){SD.Tooltip.hide();}}};SD.UI.Block.init();SD.UI.RemoveFromList={init:function(){SD.Event.delegate('removeFromList',this.delegates);},listTypes:{'viewed-you':{name:"viewed me",action:"viewed_you",page:"likes_me"},'favorited-you':{name:"favorited me",action:"favorited_you",page:"likes_me"},'i-favorited':{name:"favorites",action:"my_favorites",page:"members"},'i-want-to-date':{name:"invited SpeedDates",action:"you_want_to_date",page:"my_results"},'want-to-date-you':{name:"people who invited you to SpeedDate",action:"want_to_date_you",page:"likes_me"}},delegates:{'click':function(e){var el=e.sdTarget;var user=SD.UI.Common.extractUser(el);var listType=SD.UI.RemoveFromList.listTypes[el.getAttribute('listType')];if(!listType){return;}
if(confirm("Are you sure you want to remove "+user.username+" from '"+listType.name+"' list ?")){SD.NavUtils.goTo(listType.page,listType.action,{removeMember:user.uid,rnd:new Date().getTime()});}},'mouseover':function(e){var el=e.sdTarget;var user=SD.UI.Common.extractUser(el);var listType=SD.UI.RemoveFromList.listTypes[el.getAttribute('listType')];if(!listType){return;}
SD.Tooltip.show((SD.Model.getMyself().is_premium?'':SD.UIController.getInlineSubBadge())+' Remove <b>'+user.username+'</b> from '+listType.name+' list');},'mouseout':function(e){SD.Tooltip.hide();}}};SD.UI.RemoveFromList.init();SD.UI.AddSingleProfileInfo={init:function(){SD.Event.delegate('addSingleProfileInfo',this.delegates);},delegates:{'click':function(e){var el=e.sdTarget;var profileInfoId=el.getAttribute('sdProfileInfoId');SD.ProfileInfo.getSingleProfileInfoForm(profileInfoId);}}};SD.UI.AddSingleProfileInfo.init();SD.ResultMessage=Class.create({initialize:function(el){this.hide.bind(this,$(el)).delay(5);},hide:function(el){new Effect.SlideUp(el,{afterFinish:function(){SD.Event.fire(null,SD.UIController.Events.LAYOUT_UPDATED);el.remove();}});}});SD.RequestCheck={loginUrl:"index.php?page=login&section=login&url=",check:function(){var pos=window.location.href.indexOf('#');if(pos==-1){return;}
var url=window.location.href.substring(pos+1);window.location=this.loginUrl+escape(url);}};SD.UI.IEFocus={init:function(){if(Prototype.Browser.IE){document.observe('focusin',SD.UI.IEFocus.delegates.focusin);document.observe('focusout',SD.UI.IEFocus.delegates.focusout);}},targetElements:{'SELECT':1,'INPUT':1,'TEXTAREA':1},delegates:{'focusin':function(e){if(!SD.UI.IEFocus.targetElements[e.target.tagName])return;!$(e.target).hasClassName('hasfocus')&&e.target.addClassName('hasfocus');},'focusout':function(e){if(!SD.UI.IEFocus.targetElements[e.target.tagName])return;$(e.target).hasClassName('hasfocus')&&e.target.removeClassName('hasfocus');}}};SD.UI.IEFocus.init();SD.UI.FBFeed={_pendingInvitations:{},ClassNames:{ENABLED:"enabled",PENDING:"sending",SENT:"sent"},init:function(){SD.Event.delegate('fbFeed',this.delegates);},extractParams:function(el){var params={};params.friendId=el.getAttribute('sdFriendId')||0;params.feedType=(el.getAttribute('sdFeedType')||"").toUpperCase();var len=el.attributes.length;params.variables={};for(var i=0;i<len;i++){var attr=el.attributes[i];if(/sdx_/.test(attr.name)){params.variables[attr.name.substring(2).toUpperCase()]=attr.value;}}
return params;},getRequestKey:function(params){return'i'+params.friendId+params.feedType;},delegates:{'click':function(event){var el=event.sdTarget;var scope=SD.UI.FBFeed;var params=scope.extractParams(el);if(!params.feedType){return;}
if(scope._pendingInvitations[scope.getRequestKey(params)]){return;}
scope._pendingInvitations[scope.getRequestKey(params)]=true;el.addClassName(scope.ClassNames.PENDING);var url=SD.NavUtils.link('ajax','send_facebook_feed');new Ajax.Request(url,{method:'post',parameters:{variables:Object.toJSON(params.variables),feedType:params.feedType,friendId:params.friendId},onSuccess:function(resp){scope._pendingInvitations[scope.getRequestKey(params)]=false;el.removeClassName(scope.ClassNames.PENDING);el.removeClassName(scope.ClassNames.ENABLED);el.addClassName(scope.ClassNames.SENT);}.bind(scope),onFailure:function(){scope._pendingInvitations[scope.getRequestKey(params)]=false;el.removeClassName(scope.ClassNames.PENDING);}.bind(scope)});}}};SD.UI.FBFeed.init();SD.UI.fwFbMatchFriend={_pendingInvitations:{},ClassNames:{ENABLED:"enabled",PENDING:"sending",SENT:"sent"},init:function(){SD.Event.delegate('fwFbMatchFriend',this.delegates);},extractParams:function(el){var params={};params.friendId=el.getAttribute('sdFriendId')||0;params.memberId=el.getAttribute('sdMatchId')||SD.FlirtWink.Controller.getCurrentFlirtee().uid;return params;},getRequestKey:function(params){return'i'+params.friendId;},delegates:{'click':function(event){var el=event.sdTarget;var scope=SD.UI.fwFbMatchFriend;var params=scope.extractParams(el);if(!params.friendId){return;}
if(scope._pendingInvitations[scope.getRequestKey(params)]){return;}
scope._pendingInvitations[scope.getRequestKey(params)]=true;el.removeClassName(scope.ClassNames.ENABLED);el.addClassName(scope.ClassNames.PENDING);params.isOneClickShare=1;params.publish=1;var url=SD.NavUtils.link('fun','match_friend_submit');new Ajax.Request(url,{method:'post',parameters:params,onSuccess:function(resp){scope._pendingInvitations[scope.getRequestKey(params)]=false;el.removeClassName(scope.ClassNames.PENDING);el.removeClassName(scope.ClassNames.ENABLED);el.addClassName(scope.ClassNames.SENT);scope.replaceElement(el);}.bind(scope),onFailure:function(){scope._pendingInvitations[scope.getRequestKey(params)]=false;el.removeClassName(scope.ClassNames.PENDING);}.bind(scope)});}},replaceElement:function(el){var scope=SD.UI.fwFbMatchFriend;var excludeIds=$$('[sdType=fwFbMatchFriend]').collect(function(e){return e.getAttribute('sdFriendId')||0});var url=SD.NavUtils.link('profile','fb_click_share');new Ajax.Request(url,{method:'post',parameters:{exclude:excludeIds.join(','),responseType:'json',limit:1},onSuccess:function(resp){if(resp.responseJSON&&resp.responseJSON.length){var friend=resp.responseJSON[0];el.fade({duration:1,delay:1,to:0.1,beforeFinish:function(){el.setAttribute('sdFriendId',friend['id']);el.select('.friend-image').each(function(img){img.src=friend['img_src'];});el.select('.friend-name').each(function(span){span.innerHTML=friend['name'];});el.removeClassName(scope.ClassNames.PENDING);el.removeClassName(scope.ClassNames.SENT);el.addClassName(scope.ClassNames.ENABLED);el.appear({duration:1});}});}}});}};SD.UI.fwFbMatchFriend.init();SD.UI.fwFbSendGift={_pendingInvitations:{},ClassNames:{ENABLED:"enabled",PENDING:"sending",SENT:"sent"},init:function(){SD.Event.delegate('fwFbSendGift',this.delegates);},extractParams:function(el){var params={};params.friendId=el.getAttribute('sdFriendId')||0;params.giftId=el.getAttribute('sdgiftId')||0;return params;},getRequestKey:function(params){return'i'+params.friendId;},delegates:{'click':function(event){var el=event.sdTarget;var scope=SD.UI.fwFbSendGift;var params=scope.extractParams(el);if(!params.friendId){return;}
if(scope._pendingInvitations[scope.getRequestKey(params)]){return;}
scope._pendingInvitations[scope.getRequestKey(params)]=true;el.removeClassName(scope.ClassNames.ENABLED);el.addClassName(scope.ClassNames.PENDING);params.isOneClickShare=1;params.publish=1;var url=SD.NavUtils.link('fun','send_gift_submit');new Ajax.Request(url,{method:'post',parameters:params,onSuccess:function(resp){scope._pendingInvitations[scope.getRequestKey(params)]=false;el.removeClassName(scope.ClassNames.PENDING);el.removeClassName(scope.ClassNames.ENABLED);el.addClassName(scope.ClassNames.SENT);scope.replaceElement(el);}.bind(scope),onFailure:function(){scope._pendingInvitations[scope.getRequestKey(params)]=false;el.removeClassName(scope.ClassNames.PENDING);}.bind(scope)});}},replaceElement:function(el){var scope=SD.UI.fwFbSendGift;var excludeIds=$$('[sdType=fwFbSendGift]').collect(function(e){return e.getAttribute('sdFriendId')||0});var url=SD.NavUtils.link('profile','fb_click_share');new Ajax.Request(url,{method:'post',parameters:{exclude:excludeIds.join(','),responseType:'json',limit:1},onSuccess:function(resp){if(resp.responseJSON&&resp.responseJSON.length){var friend=resp.responseJSON[0];el.fade({duration:1,delay:1,to:0.1,beforeFinish:function(){el.setAttribute('sdFriendId',friend['id']);el.select('.friend-image').each(function(img){img.src=friend['img_src'];});el.select('.friend-name').each(function(span){span.innerHTML=friend['name'];});el.removeClassName(scope.ClassNames.PENDING);el.removeClassName(scope.ClassNames.SENT);el.addClassName(scope.ClassNames.ENABLED);el.appear({duration:1});}});}}});}};SD.UI.fwFbSendGift.init();SD.UI.CoinPopup={init:function(){SD.Event.delegate('coins-link',this.delegates);},delegates:{'click':function(e){SD.ViralPoints.onSubscribeTrigger();},'mouseover':function(e){},'mouseout':function(e){}}};SD.UI.CoinPopup.init();SD.UI.LoadChatHistory={init:function(){SD.Event.delegate('load-chat-history',this.delegates);},delegates:{'click':function(event){var el=event.sdTarget;var uid=el.getAttribute("sduid");var panelId=el.getAttribute("sdpanelid");if(!panelId||!uid){return;}
var user=SD.User.get(uid);SD.Communication.History.loadCommunicationHistory(user,function(records){records.favorite=null;var html=SD.FlirtWink.View.HistoryRenderer.renderHistory(records,user);$(el).replace(html);var ui=SD.UI.DateUI.getUI();var panel=ui.getPanelById(panelId);if(panel){panel.messagePane.adjustMessagePane();}});}}};SD.UI.LoadChatHistory.init();SD.UI.FBChatMessage={init:function(){SD.Event.delegate('fbchat-invite',this.delegates);},delegates:{'click':function(event){var el=event.sdTarget;var uid=el.getAttribute("sduid");var friend=null;if(uid){friend=SD.User.get(uid);}
if(!uid&&el.getAttribute("sdFbUserId")){friend=SD.User.getByFbUserId(el.getAttribute("sdFbUserId"));uid=friend.uid;}
if(!friend.isFacebookUser()){return;}
SD.FBChat.inviteFriend(friend);}}};SD.UI.FBChatMessage.init();SD.UI.FBChatToggles={CLASSNAMES:{connected:"fb-chat-connected",disconnected:"fb-chat-disconnected",connecting:"fb-chat-connecting",disconnecting:"fb-chat-disconnecting"},initDeferred:function(){this.init.bind(this).delay(5);},init:function(){SD.Event.delegate('fbchat-connect-toggle',this.delegates);SD.Event.observe(null,SD.FBXMPP.Events.CONNECTING,function(e){this.updateButtons(this.CLASSNAMES.connecting);}.bind(this));SD.Event.observe(null,SD.FBXMPP.Events.DISCONNECTING,function(e){this.updateButtons(this.CLASSNAMES.disconnecting);}.bind(this));SD.Event.observe(null,SD.FBXMPP.Events.LOGIN,function(e){this.updateButtons(this.CLASSNAMES.connected);}.bind(this));SD.Event.observe(null,SD.FBXMPP.Events.LOGOUT,function(e){this.updateButtons(this.CLASSNAMES.disconnected);}.bind(this));this.updateButtons(this.CLASSNAMES.disconnected);SD.FBXMPP.connectIfHavePermissionsAndSession();},delegates:{'click':function(event){var el=event.sdTarget;if(el.hasClassName(SD.UI.FBChatToggles.CLASSNAMES.connected)){SD.FBXMPP.disconnect();}else if(el.hasClassName(SD.UI.FBChatToggles.CLASSNAMES.disconnected)){SD.FBXMPP.connect();SD.ExperimentManager.recordOutput('ClickedConnectFacebookChat',1,1);}else{}}},updateButtons:function(className){if(!className){className=SD.FBXMPP.isLoggedIn()?this.CLASSNAMES.connected:this.CLASSNAMES.disconnected;}
var elements=$$('[sdType=fbchat-connect-toggle]');elements.each(function(elm){for(var i in this.CLASSNAMES){if(this.CLASSNAMES.hasOwnProperty(i)){if(this.CLASSNAMES[i]!=className){elm.removeClassName(this.CLASSNAMES[i]);}}}
elm.addClassName(className);}.bind(this));}};SD.UI.IphoneBanner={init:function(){SD.Event.delegate('iphone-banner',this.delegates);},delegates:{'click':function(e){SD.ExperimentManager.recordOutput('Iphone_BannerClickOnDashboard',1,1);return true;}}};SD.UI.IphoneBanner.init();SD.UI.MyAccount={init:function(){SD.Event.delegate('acc-settings-handle',this.delegates);},delegates:{'click':function(e){var el=e.sdTarget;var cmd=el.getAttribute('sdCmd');var menuId=el.getAttribute('sdMenuId');if(cmd=='edit'){SD.MyAccount.activateAccountSettingsMenuItem(menuId);}else if(cmd=='hide'){SD.MyAccount.deactivateAccountSettingsMenuItem(menuId);}}}};SD.UI.MyAccount.init();SD.UI.RangeControl={init:function(){SD.Event.delegate('range-ctrl',this.delegates);},delegates:{'blur':function(e){var el=e.sdTarget;var role=el.getAttribute('sdRole');var relEl=$(el.getAttribute('sdRelId'));if(role=='min'){if(parseFloat(el.value)>parseFloat(relEl.value)){el.value=relEl.value;}}else if(role=='max'){if(parseFloat(el.value)<parseFloat(relEl.value)){el.value=relEl.value;}}}}};SD.UI.RangeControl.init();SD.UI.FillProfilePrompt={init:function(){SD.Event.delegate('fillProfilePrompt',this.delegates);},delegates:{'click':function(e){var context=SD.Utils.buildContext({sourceType:SD.UIController.PopupSourceTypes.GOAL_MEMBER_INFO_PROMPT,sourceMember:SD.FlirtWink.Controller.getCurrentFlirtee(),dialogRole:'fillProfilePrompt'},e);SD.UIController.aboutMeTooltip(context,function(){});}}};SD.UI.FillProfilePrompt.init();SD.Event.delegate('noop',{});
SD.UI.Widget=SD.UI.Widget||{};SD.UI.Widget.SmallUserViewTemplates={buddyview:'<div class="buddy-view #{buddy_online_class}" id="buddylist-buddy-#{uid}">'+'<img class="buddy-image" src="#{small_pic_url}">'+'<div class="buddy-name">'+'<a href="javascript:void(0)" sdusername="#{username}" sduid="#{uid}" sdtype="profile">'+'#{username}'+'</a>'+', #{age}<br>#{city}'+'</div>'+'<div class="link link-chat fake-link" sdtype="chat" sduid="#{uid}" sdusername="#{username}" sdonline="#{is_online}" sdimonline="#{im_online}">Chat</div>'+'<br clear="all"/>'+'</div>'};SD.UI.Widget.SmallUserView=Class.create(SD.UI.Component,{templateSet:SD.UI.Widget.SmallUserViewTemplates,initTemplate:SD.UI.Widget.SmallUserViewTemplates.buddyview,dataFilter:function(user){var sCityName=user.city_name||'';return{uid:user.uid,username:user.username.ucfirst().excerpt(12),small_pic_url:user.square_image_url,city:sCityName.excerpt(18),age:user.age,is_online:'true',buddy_online_class:user.online?'buddy-online':'',im_online:''+user.im_online};}});
SD.PreferenceAnalyzer={challengeIndex:0,_popup:null,_canceledChallenges:[],wasDating:false,numCouples:10,prepareBeforeStart:function(){this.challengeIndex=0;if(this.wasDating=!(SD.DatingController._pc&&SD.DatingController._pc.pauseRequested)){SD.UserFilters.UI.pauseSpeedDating();}
SD.UserFilters.UI.allowDating=false;SD.Event.fire(null,SD.UIController.Events.CLOSE_WELCOME_POPUP);},start:function(callback){this.prepareBeforeStart();var winconfig={title:'&nbsp;',className:'generic-popup-container pick-date preference-analyzer',content:"<p class='sd-window-msg'>Loading...</p>",template:SD.Window.newStyle,top:10,width:740,blocker:true,draggable:false,onAfterClose:function(){SD.UserFilters.UI.allowDating=true;SD.UserFilters.UI.startSpeedDating();if(callback){callback();}}};this.dialog=SD.UIController.standardPopup(winconfig);this.dialog=this.dialog.open().load(SD.NavUtils.link('home','preference_analyzer_popup',{'reset':1}));return this.dialog;},startSpeedPlay:function(uid){if(!uid){return null}
this.prepareBeforeStart();var winconfig={bindToWindowScroll:false,position:'absolute',title:'',className:'generic-popup-container pick-date preference-analyzer speedplay-holder',content:"<p class='sd-window-msg'>Loading...</p>",template:SD.Window.newStyle,top:10,width:740,blocker:true,draggable:false,onAfterClose:function(){SD.UserFilters.UI.allowDating=true;SD.UserFilters.UI.startSpeedDating();}};this.dialog=SD.UIController.standardPopup(winconfig).open().load(SD.NavUtils.link('home','speed_play_popup',{'reset':1,'uid':uid}));this.dialog.speedPlayUid=uid;return this.dialog;},isOpen:function(){return this.dialog&&this.dialog.isOpened;},finish:function(){this.dialog.close();},showMatches:function(callback){this.dialog=SD.UIController.standardPopup({title:'Preference Analyzer!',content:"<p class='sd-window-msg'>Loading...</p>",top:80,width:740,blocker:true,onAfterClose:function(){SD.UserFilters.UI.allowDating=true;SD.UserFilters.UI.startSpeedDating();if(callback){callback();}}}).open().load(SD.NavUtils.link('home','preference_analyzer_popup'));},getChal:function(i){return $('challenge'+i);},chooseMemberAndExcludeOther:function(index,params){$('status-bar').down('span').style.width=((this.challengeIndex+1)*(100/this.numCouples))+'%';$('challenges-step')&&$('challenges-step').update(Math.min(this.challengeIndex+2,this.numCouples));if(index>=0){var voted=null;var versus=null;this.getChal(this.challengeIndex).select('a').each(function(e){if(e.hasClassName('m'+index)){voted=e.getAttribute('uid');}else{versus=e.getAttribute('uid');}});if(!(window.preferenceAnalyzerBeforeSignup===undefined)){new Ajax.Request(SD.NavUtils.link('ajax','defer_preference_analyzer_vote',{voted_memberid:voted,versus_memberid:versus}));}else{new Ajax.Request(SD.NavUtils.link('ajax','preference_analyzer_vote',{voted_memberid:voted,versus_memberid:versus}));}
if(!(window.preferenceAnalyzerBeforeSignup===undefined)&&versus){new Ajax.Request(SD.NavUtils.link('ajax','deferExcludeUser'),{method:'post',evalJSON:false,parameters:{otherUserId:versus}});}
else if(params&&params.uid&&versus){new Ajax.Request(SD.NavUtils.link('ajax','excludeUser'),{method:'post',evalJSON:false,parameters:{memberid:params.uid,otherUserId:versus}});}}
else{var notPreferredIds=new Array();this.getChal(this.challengeIndex).select('a').each(function(e){notPreferredIds.push(e.getAttribute('uid'));});if(!(window.preferenceAnalyzerBeforeSignup===undefined)){new Ajax.Request(SD.NavUtils.link('ajax','deferExcludeMultipleUsers',{method:'post',evalJSON:false,parameters:{otherUserIds:notPreferredIds.join(',')}}));}
else if(params&&params.uid){new Ajax.Request(SD.NavUtils.link('ajax','excludeMultipleUsers'),{method:'post',evalJSON:false,parameters:{memberid:params.uid,otherUserIds:notPreferredIds.join(',')}});}}
var isSpeedPlay=params.isSpeedPlay||false;var isLast=params.isLast||false;if(isSpeedPlay&&isLast){$$('.call-to-action-top')&&$$('.call-to-action-top').each(function(el){el.hide();});$('status-bar')&&$('status-bar').hide();$('challange-title')&&$('challange-title').hide();$('neither-link')&&$('neither-link').hide();$('challange-title-match')&&$('challange-title-match').show();$('challange-action-buttons')&&$('challange-action-buttons').show();}
this.getChal(this.challengeIndex++).hide();if(this.challengeIndex<this.numCouples){this.getChal(this.challengeIndex).show();}else{if(this.dialog&&this.dialog.speedPlayUid){this.dialog.load(SD.NavUtils.link('home','speed_play_reveal_popup',{uid:this.dialog.speedPlayUid}));}else if(params&&params.onFinish){params.onFinish()}else{$('challenges-popup').update(' ');this.dialog.load(SD.NavUtils.link('home','preference_analyzer_calculate_matches'));}}},saveHotOrNot:function(index,params,isHot){$('status-bar').down('span').style.width=((this.challengeIndex+1)*(100/this.numCouples))+'%';$('challenges-step')&&$('challenges-step').update(Math.min(this.challengeIndex+2,this.numCouples));if(params.uid){new Ajax.Request(SD.NavUtils.link('ajax','saveHotOrNot'),{method:'post',evalJSON:false,parameters:{memberid:params.uid,isHot:isHot}});}
var isLast=params.isLast||false;if(isLast){$$('.call-to-action-top')&&$$('.call-to-action-top').each(function(el){el.hide();});$('status-bar')&&$('status-bar').hide();$('challange-title')&&$('challange-title').hide();$('neither-link')&&$('neither-link').hide();$('challange-title-match')&&$('challange-title-match').show();$('challange-action-buttons')&&$('challange-action-buttons').show();}
this.getChal(this.challengeIndex++).hide();if(this.challengeIndex<this.numCouples){this.getChal(this.challengeIndex).show();}else if(params&&params.onFinish){params.onFinish()}}};
SD.ProfileInfo={new_member_info_types:[93,94,95,96,97],newProfileInfo:{},oldProfileInfo:{},getSingleProfileInfoForm:function(profileInfoId){var elId=SD.ProfileInfo.getLockedProfileItemDomElementId(profileInfoId);var url=SD.NavUtils.link('profile','get_single_profile_info_add',{profile_info_id:profileInfoId});new SD.Utils.Loader({domContent:$(elId),onContentRendered:function(domRoot){var form=$(domRoot).select('form')[0];if(!form)return;var anyElement=null;var toggleAnyCheckbox=function(){$(this.parentNode)&&$(this.parentNode.parentNode)&&$(this.parentNode.parentNode).select('input[type="checkbox"]').each(function(el){if(el.getAttribute('sdElementAny')!='true'){el.checked=false;}});var division=this.getAttribute('id');division=".profileinfo"
+division.substr(division.indexOf("[")+1,division.indexOf("]")-division.indexOf("[")-1);SD.Dialog.Profile.operateOnImportance(division,'hidden');};var onClickCheckboxes=function(){var pNode=$(this.parentNode);var division=this.getAttribute('id');division=".profileinfo"
+division.substr(division.indexOf("[")+1,division.indexOf("]")-division.indexOf("[")-1);if(pNode&&anyElement){(function(){var areAnyChecked=$(pNode.parentNode).select('input[type="checkbox"]').some(function(el){return el.getAttribute('sdElementAny')!='true'&&el.checked;});anyElement.checked=!areAnyChecked;}).defer();}
if(SD.ExperimentManager.AddImportanceLevelToPreferences.value==1){(function(){if(!anyElement){return;}
if(anyElement.checked){SD.Dialog.Profile.operateOnImportance(division,'hidden');}else{SD.Dialog.Profile.operateOnImportance(division,'visible');}}).defer();}};$A(form.elements).each(function(el){if(el.type=="checkbox"){if(el.getAttribute('sdElementAny')=='true'){anyElement=el;el.onclick=toggleAnyCheckbox;}else{el.onclick=onClickCheckboxes;}}});},onParseElements:{'select[sdtype="range-ctrl"]':this.selectHandler}}).load(url);},selectHandler:function(selEl,domRoot){selEl.observe('change',function(e){if(SD.ExperimentManager.AddImportanceLevelToPreferences.value==1){SD.Dialog.Profile.operateOnImportance('.importance-level','visible');}});},lockProfileInfoField:function(profileInfoId,errorMessage){errorMessage=errorMessage||null;var elId=SD.ProfileInfo.getLockedProfileItemDomElementId(profileInfoId);if(!$(elId)){console.log("error: wrong params - unlockProfileInfoField");return;}
$(elId).removeClassName('my-category-item-edit-mode');$(elId).addClassName('my-category-item-locked');$(elId).update(SD.ProfileInfo.getLockedFieldText(profileInfoId,errorMessage));},unlockProfileInfoField:function(profileInfoId,fieldNewValue,isCancel){fieldNewValue=fieldNewValue||null;isCancel=isCancel||false;var elId=SD.ProfileInfo.getLockedProfileItemDomElementId(profileInfoId);if(!$(elId)){console.log("error: wrong params - unlockProfileInfoField");return;}
if(!fieldNewValue&&SD.ProfileInfo.newProfileInfo['info-'+profileInfoId]){fieldNewValue=SD.ProfileInfo.newProfileInfo['info-'+profileInfoId];}
if(fieldNewValue){$(elId).removeClassName('my-category-item-locked');$(elId).removeClassName('my-category-item-edit-mode');$(elId).addClassName('my-category-item-value');$(elId).update(SD.ProfileInfo.getUnlockingText(profileInfoId,isCancel));if(profileInfoId==1||profileInfoId==77){fieldNewValue='"'+fieldNewValue+'"';}
var delayTime=2;if(isCancel){delayTime=1;}
if(SD.ExperimentManager&&SD.ExperimentManager.MatchMakerUI_v5_Strike.value&&this.new_member_info_types.any(function(el){return el==profileInfoId})){var html=[];var fieldNewValueArr=fieldNewValue.evalJSON();for(var i in fieldNewValueArr){if(fieldNewValueArr.hasOwnProperty(i)){var division='<div class="suggest-item">'
+'<span class="suggest-item-id" style="display: none;">'+fieldNewValueArr[i]._id.value+'</span>'
+'<img class="suggest-item-image" src="'+fieldNewValueArr[i].photo+'"><br/>'
+'<span class="suggest-item-name">'+SD.AutoCompleteV2.sanitize(fieldNewValueArr[i]._name.value)+'</span>'
+'<a name="'+fieldNewValueArr[i].id+'" class="fake-link no-hover no-remove"></a>'
+'</div>';html.push(division);}}
$(elId).update.bind($(elId)).delay(delayTime,'<div class="category-item-value">'
+'<div class="clear" style="height:30px;"></div>'
+html.join("")
+'<div onclick="javascript:void(0)" sdType="addSingleProfileInfo" class="edit-link small-green small-button" sdProfileInfoId="'+profileInfoId+'" style="position:absolute; top: 12px; right: 0px;">'
+'<span style="text-align:right">'
+'<u>Edit Info</u>'
+'</span>'
+'</div>'
+'</div>');}else{var textValue=fieldNewValue+' <a class="edit-link" href="javascript:void(0)" sdType="addSingleProfileInfo" sdProfileInfoId="'+
profileInfoId+'">(edit)</a>';$(elId).update.bind($(elId)).delay(delayTime,textValue);}}else{SD.ProfileInfo.lockProfileInfoField(profileInfoId);}},cancelEditing:function(profileInfoId){var oldValue=null;if(SD.ProfileInfo.oldProfileInfo['info-'+profileInfoId]){oldValue=SD.ProfileInfo.oldProfileInfo['info-'+profileInfoId];}
SD.ProfileInfo.unlockProfileInfoField(profileInfoId,oldValue,true);},getLockedProfileItemDomElementId:function(profileInfoId){return'my-profile-locked-item-'+profileInfoId;},getUnlockingText:function(profileInfoId,isCancel){isCancel=isCancel||false;if(isCancel){return"<div class='my-category-unlocking-text'>canceling</div>";}else{return"<div class='my-category-unlocking-text'>saving</div>";}},getLockedFieldText:function(profileInfoId,errorMessage){if(profileInfoId==1){errorMessage='Your <b>"MORE ABOUT ME"</b> info is empty.'}
if(profileInfoId==77){errorMessage='Your <b>"DATING STATUS"</b> info is empty.'}
errorMessage=errorMessage||'This field is empty.';return errorMessage+' <a class="edit-link" href="javascript:void(0)" sdType="addSingleProfileInfo" sdProfileInfoId="'+
profileInfoId+'">Click here to enter.</a>';},Events:{PROFILE_INFO_UPDATED:"sd_profile_info:profile_info_updated"}};
if(window.HTMLElement&&!window.opera&&HTMLElement.prototype&&HTMLElement.prototype.__defineGetter__){HTMLElement.prototype.__defineGetter__("currentStyle",function(){return document.defaultView.getComputedStyle(this,null);});}
VL_copyPrototype=function(p,c){for(var i in p.prototype){c.prototype[i]=p.prototype[i];}}
VL_unselectable=function(htmlElement){htmlElement.onselectstart=function(){return false;}
htmlElement.style.MozUserSelect="none";}
VL_utils=new Object;VL_utils.trim=function(str){return str.replace(/(^\s*) | \s*$/g,"");}
VL_utils.getElement2=function(rootElement,tagNm,propertyName,propertyValue){if(!rootElement)return;var els=rootElement.getElementsByTagName(tagNm);for(var i=0,l=els.length;i<l;i++){if(els[i].getAttribute(propertyName)==propertyValue){return els[i];}}
return null;}
VL_utils.extend=function(p,c){for(var i in p.prototype){c.prototype[i]=p.prototype[i];}}
VL_utils.injectTemplate=function(target,template){if(typeof target=="string")
target=document.getElementById(target);var parentEl=document.createElement("DIV");parentEl.style.display="none";document.body.appendChild(parentEl);parentEl.innerHTML=template;var templateNode=(parentEl.firstChild.nodeType==3)?(parentEl.firstChild.nextSibling?parentEl.firstChild.nextSibling:null):parentEl.firstChild;var node=templateNode.cloneNode(true);target.appendChild(node);parentEl.removeChild(templateNode);var objects={};objects["masterTemplateNode"]=node;objects.length=1;var els=node.getElementsByTagName("*");for(var i=0,l=els.length;i<l;i++){if(els[i].getAttribute("objectID")&&els[i].getAttribute("objectID").length>0){objects[els[i].getAttribute("objectID")]=els[i];objects.length++;}}
if(objects.length>1)
return objects;else
return node;}
VL_utils.isHTML=function(str){var re=/(<BODY|<P|<H1|<H2|<H3|<TABLE|<UL|<OL|<B|<FONT|<DIV|<SPAN|<A|<IMG|<OBJECT|<EMBED)/ig;if(str.match(re))
return true;else
return false;}
VL_utils.getCSSProperty=function(element,property){parseInt(window.getComputedStyle(element,null).getPropertyValue(property))||0;}
VL_utils.getInnerWidth=function(element){parseInt(window.getComputedStyle(element,null).getPropertyValue("width"))||0;}
VL_utils.getInnerHeight=function(element){parseInt(window.getComputedStyle(element,null).getPropertyValue("height"))||0;}
VL_utils.getWidth=function(element){return element.offsetWidth;}
VL_utils.getHeight=function(element){return element.offsetHeight;}
VL_utils.setWidth=function(element,w){var borderRightWidth=VL_utils.getCSSProperty(element,"border-right-width");var borderLeftWidth=VL_utils.getCSSProperty(element,"border-left-width");var paddingRight=VL_utils.getCSSProperty(element,"padding-right");var paddingLeft=VL_utils.getCSSProperty(element,"padding-left");element.style.width=(w-borderRightWidth-borderLeftWidth-paddingRight-paddingLeft)+'px';return element;}
VL_utils.setHeight=function(element,h){var borderTopWidth=VL_utils.getCSSProperty(element,"border-top-width");var borderBottomWidth=VL_utils.getCSSProperty(element,"border-bottom-width");var paddingTop=VL_utils.getCSSProperty(element,"padding-top");var paddingBottom=VL_utils.getCSSProperty(element,"padding-bottom");element.style.height=(h-borderTopWidth-borderBottomWidth-paddingTop-paddingBottom)+'px';return element;}
VL_utils.setInnerWidth=function(element,w){element.style.width=w+'px';return element;}
VL_utils.setHeight=function(element,h){element.style.height=h+'px';return element;}
function VL_Pane(){};VL_Pane.defaultClass="";VL_Pane.prototype.draw=function(){this.dom=document.createElement("div");this.dom.id=this.id;this.parentDom.appendChild(this.dom);this.dom.className=this.className;this.dom.style.width=(typeof this.width=='string')?this.width:(this.width+'px');this.dom.style.height=(typeof this.height=='string')?this.height:(this.height+'px');this.isVisible=true;};VL_Pane.prototype.attachChild=function(pane){this.childPane=pane;};VL_Pane.prototype.attachParent=function(pane){this.parentPane=pane;};VL_Pane.prototype.addContent=function(html){this.content=html;this.dom.innerHTML=html;};VL_Pane.prototype.clearContent=function(){this.dom.innerHTML="";this.content="";};VL_Pane.prototype.resizeTo=function(w,h,isForced,direction){};VL_Pane.prototype.resizeBy=function(dw,dh,isForced,direction){};VL_Pane.prototype.show=function(){this.isVisible=true;this.dom.style.display="block";};VL_Pane.prototype.hide=function(){this.isVisible=false;this.dom.style.display="none";};VL_Pane.prototype.del=function(){this.dom.parentNode.removeChild(this.dom);};VL_Pane.panes={};VL_Pane.counter=0;VL_Pane.addPane=function(pane){var id="vl"+this.counter++;this.panes[id]=pane;return id;}
VL_Pane.removePane=function(pane){this.panes[pane.id]=null;pane.del();}
VL_Pane.PANE_RESIZABLE=1;VL_Pane.PANE_FIXED=2;VL_Pane.NORMAL_PANE=1;VL_Pane.RESIZER_PANE=2;VL_Pane.IFRAME_PANE=3;VL_Pane.RESIZER_SIZE=6;VL_Pane.counter=0;VL_Pane.UP=1;VL_Pane.DOWN=2;VL_Pane.MIN_SIZE=5;VL_Pane.SOFT_PANE=10;VL_Pane.HARD_PANE=11;function VL_VPane(parentDom,sizeModifier,styleClass,size,minSize,maxSize){this.minSize=minSize||VL_Pane.MIN_SIZE;this.maxSize=maxSize||Infinity;this.resizeType=VL_Pane.HARD_PANE;this.id=VL_Pane.addPane(this);this.parentDom=parentDom;this.dom=null;this.height=size?size:this.parentDom.offsetHeight;this.width="100%";this.mod=sizeModifier;this.className=styleClass||VL_Pane.defaultClass;this.isVisible=false;this.childPane=null;this.parentPane=VL_Pane.panes[parentDom.id]||null;this.content=null;this.onresize=function(){};this.draw();}
VL_copyPrototype(VL_Pane,VL_VPane);VL_VPane.prototype.resizeTo=function(w,h,isForced,direction){if(!this.dom||!this.dom.style)return;isForced=isForced||false;direction=direction||VL_Pane.DOWN;if(h<this.minSize)
h=this.minSize;if(h&&(isForced||this.mod==VL_Pane.PANE_RESIZABLE)){this.height=h;this.dom.style.height=this.height+'px';}
if(direction==VL_Pane.DOWN){if(this.childPane){this.childPane.resizeTo(w,h,isForced,direction);}}
else{if(this.parentPane)
this.parentPane.resizeTo(w,h,isForced,direction)
else{if(w)this.parentDom.style.width=w+'px';if(h)this.parentDom.style.height=h+'px';}}
this.onresize();}
VL_VPane.prototype.resizeBy=function(dw,dh,isForced,direction){isForced=isForced||false;direction=direction||VL_Pane.DOWN;if(this.height+dh<this.minSize)
dh=0;if(dh&&(isForced||this.mod==VL_Pane.PANE_RESIZABLE)){this.height=parseInt(this.dom.style.height)+dh;this.dom.style.height=this.height+'px';}
if(direction==VL_Pane.DOWN){if(this.childPane){this.childPane.resizeBy(dw,dh,isForced,direction);}}
else{if(this.parentPane){this.parentPane.resizeBy(dw,dh,isForced,direction);}
else{if(dw)this.parentDom.style.width=(parseInt(this.parentDom.style.width)+dw)+'px';if(dh)this.parentDom.style.height=(parseInt(this.parentDom.style.height)+dh)+'px';}}
this.onresize();}
function VL_HPane(parentDom,sizeModifier,styleClass,size,minSize){this.minSize=minSize||VL_Pane.MIN_SIZE;this.id=VL_Pane.addPane(this);this.parentDom=parentDom;this.dom=null;this.width=size?size:this.parentDom.offsetWidth;this.height="100%";this.mod=sizeModifier;this.className=styleClass||VL_Pane.defaultClass;this.isVisible=false;this.childPane=null;this.parentPane=VL_Pane.panes[parentDom.id]||null;this.content=null;this.onresize=function(){};this.draw();}
VL_copyPrototype(VL_Pane,VL_HPane);VL_HPane.prototype.resizeTo=function(w,h,isForced,direction){if(!this.dom||!this.dom.style)return;isForced=isForced||false;direction=direction||VL_Pane.DOWN;if(w<this.minSize)
w=this.minSize;if(w&&(isForced||this.mod==VL_Pane.PANE_RESIZABLE)){this.width=w;this.dom.style.width=this.width+'px';}
if(direction==VL_Pane.DOWN){if(this.childPane){this.childPane.resizeTo(w,h,isForced,direction);}}
else{if(this.parentPane)
this.parentPane.resizeTo(w,h,isForced,direction)
else{if(w)this.parentDom.style.width=w+'px';if(h)this.parentDom.style.height=h+'px';}}
this.onresize();}
VL_HPane.prototype.resizeBy=function(dw,dh,isForced,direction){isForced=isForced||false;direction=direction||VL_Pane.DOWN;if(this.width+dw<this.minSize)
dw=0;if(dw&&(isForced||this.mod==VL_Pane.PANE_RESIZABLE)){this.width=parseInt(this.dom.style.width)+dw;this.dom.style.width=this.width+'px';}
if(direction==VL_Pane.DOWN){if(this.childPane){this.childPane.resizeBy(dw,dh,isForced,direction);}}
else{if(this.parentPane){this.parentPane.resizeBy(dw,dh,isForced,direction);}
else{if(dw)this.parentDom.style.width=(parseInt(this.parentDom.style.width)+dw)+'px';if(dh)this.parentDom.style.height=(parseInt(this.parentDom.style.height)+dh)+'px';}}
this.onresize();}
function VL_HResizer(prevPane,styleClass){var _this=this;this.id=VL_Pane.addPane(this);this.type=VL_Pane.RESIZER_PANE;this.prevPane=prevPane;this.nextPane=null;this.parentDom=prevPane.parentDom;this.dom=null;this.width=VL_Pane.RESIZER_SIZE;this.height=prevPane.height;this.childPane=null;this.parentPane=this.parentDom&&VL_Pane.panes[this.parentDom.id]||null;this.className=styleClass;this.isVisible=false;this.content=null;this.onresize=function(){};this.draw();this.dom.onmousedown=function(e){var x,dx,y,dy;if(!e)
e=event;x=e.clientX;dx=0;var prevPane=_this.prevPane.isVisible?_this.prevPane:_this.prevPane.prevPane;var nextPane=_this.nextPane.isVisible?_this.nextPane:_this.prevPane.nextPane;if(!prevPane||!nextPane){return;}
var prevOrigWidth=prevPane.width;var nextOrigWidth=nextPane.width;Event.extend(e).stop();document.onselectstart=function(){return false;}
document.ondragstart=function(){return false;}
document.body.onmousemove=function(e){if(!e)
e=event;dx=e.clientX-x;if(prevPane.width+dx>=prevPane.minSize&&nextPane.width-dx>=nextPane.minSize){prevPane.resizeBy(dx,null,true);nextPane.resizeBy(-dx,null,true);}
x=e.clientX;}
document.body.onmouseup=function(){if(prevPane.parentPane.softPanes[prevPane.id]){prevPane.parentPane.softPanes[prevPane.id][1]*=(prevPane.width/prevOrigWidth);}
if(nextPane.parentPane.softPanes[nextPane.id]){nextPane.parentPane.softPanes[nextPane.id][1]*=(nextPane.width/nextOrigWidth);}
this.onmousemove=null;this.onmouseup=null;document.onselectstart=null;document.ondragstart=null;}}}
VL_copyPrototype(VL_Pane,VL_HResizer);VL_HResizer.prototype.resizeBy=function(dw,dh,isForced,direction){if(dh){this.height=parseInt(this.dom.style.height)+dh;this.dom.style.height=this.height+'px';}
this.onresize();};VL_HResizer.prototype.resizeTo=function(size,isForced,direction){if(!this.dom||!this.dom.style)return;if(size){this.width=size;this.dom.style.width=this.width+'px';}
this.onresize();};function VL_VResizer(prevPane,styleClass){var _this=this;this.id=VL_Pane.addPane(this);this.type=VL_Pane.RESIZER_PANE;this.prevPane=prevPane;this.nextPane=null;this.parentDom=prevPane.parentDom;this.dom=null;this.width=prevPane.width;this.height=VL_Pane.RESIZER_SIZE;this.childPane=null;this.parentPane=this.parentDom&&VL_Pane.panes[this.parentDom.id]||null;this.className=styleClass;this.isVisible=false;this.content=null;this.onresize=function(){};this.draw();this.dom.onmousedown=function(e){var x,dx,y,dy;if(!e)
e=event;y=e.clientY;dy=0;var prevPane=_this.prevPane.isVisible?_this.prevPane:_this.prevPane.prevPane;var nextPane=_this.nextPane.isVisible?_this.nextPane:_this.prevPane.nextPane;if(!prevPane||!nextPane){return;}
var topOrigHeight=prevPane.height;var bottomOrigHeight=nextPane.height;Event.extend(e).stop();document.onselectstart=function(){return false;}
document.ondragstart=function(){return false;}
document.body.onmousemove=function(e){if(!e)
e=event;dy=e.clientY-y;if(prevPane.height+dy>=prevPane.minSize&&nextPane.height-dy>=nextPane.minSize){prevPane.resizeBy(null,dy,true);nextPane.resizeBy(null,-dy,true);}
y=e.clientY;}
document.body.onmouseup=function(){if(prevPane.parentPane.softPanes[prevPane.id]){prevPane.parentPane.softPanes[prevPane.id][1]*=(prevPane.height/topOrigHeight);}
if(nextPane.parentPane.softPanes[nextPane.id]){nextPane.parentPane.softPanes[nextPane.id][1]*=(nextPane.height/bottomOrigHeight);}
this.onmousemove=null;this.onmouseup=null;document.onselectstart=null;document.ondragstart=null;}}}
VL_copyPrototype(VL_Pane,VL_VResizer);VL_VResizer.prototype.resizeBy=function(dw,dh,isForced,direction){if(dw){this.width=parseInt(this.dom.style.width)+dw;this.dom.style.width=this.width+'px';}
this.onresize();};VL_VResizer.prototype.resizeTo=function(size,isForced,direction){if(!this.dom||!this.dom.style)return;if(size){this.height=size;this.dom.style.height=this.height+'px';}
this.onresize();};function VL_VGrid(parentDom,classStyle){this.id=VL_Pane.addPane(this);this.panes={};this.softPanes={};this.softPanesCount=0;this.parentPane=null;if(VL_Pane.panes[parentDom.id])
this.parentPane=VL_Pane.panes[parentDom.id];this.dom=null;this.className=classStyle;this.isVisible=true;this.width="100%";this.height="100%";this.parentDom=parentDom;this.onresize=function(){};this.draw();if(this.parentPane)
this.parentPane.attachChild(this);this.availableHeight=this.getAvailableHeight();}
VL_copyPrototype(VL_Pane,VL_VGrid);VL_VGrid.defaultResizerClass="";VL_VGrid.prototype.getAvailableHeight=function(){var h=0;if(!this.dom||!this.dom.currentStyle){return 0;}
var offsetParentTop=parseInt(this.dom.currentStyle.paddingTop||0)+(parseInt(this.dom.currentStyle.borderTopWidth)||0);var offsetParentBottom=parseInt(this.dom.currentStyle.paddingBottom||0)+(parseInt(this.dom.currentStyle.borderBottomWidth)||0);h=this.dom.offsetHeight-offsetParentTop-offsetParentBottom;for(var i in this.panes){if(this.softPanes[i]||this.panes[i].isVisible==false){continue;}
h-=this.panes[i].height;}
return h;}
VL_VGrid.prototype.addPane=function(classStyle,height,paneType){paneType=paneType||VL_Pane.NORMAL_PANE;var pane,h;var oldLastPane=this.lastPane;if(paneType==VL_Pane.RESIZER_PANE&&this.lastPane){this.availableHeight-=parseInt(VL_Pane.RESIZER_SIZE);pane=new VL_VResizer(this.lastPane,classStyle);}
else if(typeof height=="string"||height==null){h=(typeof height=="string")?parseInt(height,10):100;if(paneType==VL_Pane.NORMAL_PANE){pane=new VL_VPane(this.dom,VL_Pane.PANE_RESIZABLE,classStyle,VL_Pane.MIN_SIZE);this.softPanes[pane.id]=[pane,h];this.softPanesCount++;}}
else if(height){if(height>this.availableHeight){if(this.parentPane){this.parentPane.resizeBy(0,height-this.availableHeight,true);}
this.availableHeight=0;}
else{this.availableHeight-=height;}
if(paneType==VL_Pane.NORMAL_PANE){pane=new VL_VPane(this.dom,VL_Pane.PANE_FIXED,classStyle,height);}}
this.rearangeSoftPanes();if(pane){this.panes[pane.id]=pane;}
this.lastPane=pane;pane.prevPane=oldLastPane;if(pane.prevPane){pane.prevPane.nextPane=pane;}
return pane;};VL_VGrid.prototype.addResizer=function(classStyle,height){classStyle=classStyle||VL_VGrid.defaultResizerClass;return this.addPane(classStyle,height,VL_Pane.RESIZER_PANE);}
VL_VGrid.prototype.rearangeSoftPanes=function(isForced,direction){direction=direction||VL_Pane.DOWN;isForced=isForced||false;var totalCoeff=0;var curHeight=0;var totalHeight=0;var lastVisiblePane;for(var i in this.softPanes){if(this.softPanes[i][0].isVisible)
totalCoeff+=this.softPanes[i][1];}
for(var i in this.softPanes){if(this.softPanes[i][0].isVisible){lastVisiblePane=this.softPanes[i][0];curHeight=Math.round((this.softPanes[i][1]/totalCoeff)*this.availableHeight);totalHeight+=curHeight;lastVisiblePane.resizeTo(null,curHeight,isForced,direction);}}
if(totalHeight!=this.availableHeight&&this.softPanesCount>0&&lastVisiblePane)
lastVisiblePane.resizeBy(null,-(totalHeight-this.availableHeight),isForced,direction);};VL_VGrid.prototype.update=function(isForced,direction){isForced=isForced||false;direction=direction||VL_Pane.DOWN;this.availableHeight=this.getAvailableHeight();this.rearangeSoftPanes(isForced,direction);VL_Pane.recursivelyCall(this,'onresize');};VL_Pane.recursivelyCall=function(pane,method){if(pane.panes){for(var i in pane.panes){pane.panes[i][method]();if(pane.panes[i].childPane){VL_Pane.recursivelyCall(pane.panes[i].childPane,method);}}}else if(pane.childPane){pane.childPane[method]();if(pane.childPane.panes){VL_Pane.recursivelyCall(pane.childPane,method);}}};VL_VGrid.prototype.resizeTo=function(w,h,isForced,direction){this.update(isForced,direction);for(var i in this.panes){if(!this.softPanes[i])
this.panes[i].resizeTo(null,h);}
this.onresize();};VL_VGrid.prototype.resizeBy=function(dw,dh,isForced,direction){this.update(isForced,direction);for(var i in this.panes){if(!this.softPanes[i])
this.panes[i].resizeTo(null,dh);}
this.onresize();};VL_VGrid.prototype.hidePane=function(pane){pane.hide();this.update();};VL_VGrid.prototype.showPane=function(pane){pane.show();this.update();};VL_VGrid.prototype.removePane=function(pane){if(pane.prevPane){pane.prevPane.nextPane=pane.nextPane;}
if(pane.nextPane){pane.nextPane.prevPane=pane.prevPane;}
if(this.panes[pane.id])
delete this.panes[pane.id];if(this.softPanes[pane.id]){delete this.softPanes[pane.id];this.softPanesCount--;}
VL_Pane.removePane(pane);this.update();};function VL_HGrid(parentDom,classStyle){this.id=VL_Pane.addPane(this);this.panes={};this.softPanes={};this.softPanesCount=0;this.parentPane=VL_Pane.panes[parentDom.id]||null;this.dom=null;this.className=classStyle;this.isVisible=true;this.width="100%";this.height="100%";this.parentDom=parentDom;this.onresize=function(){};this.draw();if(this.parentPane)
this.parentPane.attachChild(this);this.availableWidth=this.getAvailableWidth();}
VL_copyPrototype(VL_Pane,VL_HGrid);VL_HGrid.defaultResizerClass="";VL_HGrid.prototype.getAvailableWidth=function(){var w=0;if(!this.dom||!this.dom.currentStyle){return 0;}
var offsetParentLeft=parseInt(this.dom.currentStyle.paddingLeft||0)+(parseInt(this.dom.currentStyle.borderLeftWidth)||0);var offsetParentRight=parseInt(this.dom.currentStyle.paddingRight||0)+(parseInt(this.dom.currentStyle.borderRightWidth)||0);w=this.dom.offsetWidth-offsetParentLeft-offsetParentRight;for(var i in this.panes){if(this.softPanes[i]||this.panes[i].isVisible==false){continue;}
w-=this.panes[i].width;}
return w;}
VL_HGrid.prototype.addPane=function(classStyle,width,paneType){paneType=paneType||VL_Pane.NORMAL_PANE;var pane,w;var oldLastPane=this.lastPane;if(paneType==VL_Pane.RESIZER_PANE&&this.lastPane){this.availableWidth-=parseInt(VL_Pane.RESIZER_SIZE);pane=new VL_HResizer(this.lastPane,classStyle);}
else if(typeof width=="string"||width==null){if(typeof width=="string")
var w=parseInt(width.substring(0,width.length-1));else
w=100;if(paneType==VL_Pane.NORMAL_PANE){pane=new VL_HPane(this.dom,VL_Pane.PANE_RESIZABLE,classStyle,1);this.softPanes[pane.id]=[pane,w];this.softPanesCount++;}}
else if(width){if(width>this.availableWidth){if(this.parentPane)
this.parentPane.resizeBy(width-this.availableWidth,0,true);this.availableWidth=0;}
else{this.availableWidth-=width;}
if(paneType==VL_Pane.NORMAL_PANE){pane=new VL_HPane(this.dom,VL_Pane.PANE_FIXED,classStyle,width);}}
this.rearangeSoftPanes();if(pane){this.panes[pane.id]=pane;}
this.lastPane=pane;pane.prevPane=oldLastPane;if(pane.prevPane){pane.prevPane.nextPane=pane;}
return pane;};VL_HGrid.prototype.addResizer=function(classStyle,height){classStyle=classStyle||VL_HGrid.defaultResizerClass;return this.addPane(classStyle,height,VL_Pane.RESIZER_PANE);}
VL_HGrid.prototype.rearangeSoftPanes=function(isForced,direction){direction=direction||VL_Pane.DOWN;isForced=isForced||false;var totalCoeff=0;var curWidth=0;var totalWidth=0;var lastVisiblePane;for(var i in this.softPanes){if(this.softPanes[i][0].isVisible)
totalCoeff+=this.softPanes[i][1];}
for(var i in this.softPanes){if(this.softPanes[i][0].isVisible){lastVisiblePane=this.softPanes[i][0];curWidth=Math.round((this.softPanes[i][1]/totalCoeff)*this.availableWidth);totalWidth+=curWidth;lastVisiblePane.resizeTo(curWidth,null,isForced,direction);}}
if(totalWidth!=this.availableWidth&&this.softPanesCount>0&&lastVisiblePane)
lastVisiblePane.resizeBy(-(totalWidth-this.availableWidth),null,isForced,direction);};VL_HGrid.prototype.update=function(isForced,direction){isForced=isForced||false;direction=direction||VL_Pane.DOWN;this.availableWidth=this.getAvailableWidth();this.rearangeSoftPanes(isForced,direction);VL_Pane.recursivelyCall(this,'onresize');};VL_HGrid.prototype.resizeTo=function(w,h,isForced,direction){this.update(isForced,direction);for(var i in this.panes){if(!this.softPanes[i])
this.panes[i].resizeTo(w,null);}
this.onresize();};VL_HGrid.prototype.resizeBy=function(dw,dh,isForced,direction){this.update(isForced,direction);for(var i in this.panes){if(!this.softPanes[i])
this.panes[i].resizeTo(dw,null);}
this.onresize();};VL_HGrid.prototype.convertToHardPane=function(pane){for(var i in this.softPanes){if(this.softPanes[i][0]==pane){this.softPanes[i]=null;delete this.softPanes[i];this.softPanesCount--;this.update();return pane;}}}
VL_HGrid.prototype.showPane=VL_VGrid.prototype.showPane;VL_HGrid.prototype.hidePane=VL_VGrid.prototype.hidePane;VL_HGrid.prototype.removePane=VL_VGrid.prototype.removePane;VL_layoutBuilder=function(layoutConfig){var layout={};var gridConfig,paneConfig;var gridClasses={hgrid:VL_HGrid,vgrid:VL_VGrid};var panesToHide=[];for(var grid in layoutConfig){gridConfig=layoutConfig[grid];layout[grid]=new gridClasses[gridConfig.type](getGridParentDom(gridConfig),gridConfig.cls);if(gridConfig.children){for(var pane in gridConfig.children){paneConfig=gridConfig.children[pane];if(!paneConfig.type||paneConfig.type=='pane'){layout[pane]=layout[grid].addPane(paneConfig.cls,paneConfig.size)}else if(paneConfig.type=='resizer'){layout[pane]=layout[grid].addResizer();if(paneConfig.size){layout[pane].resizeTo(paneConfig.size);}}
if(paneConfig.visible===false){panesToHide.push(layout[pane]);}}}}
for(var i=0;i<panesToHide.length;i++){panesToHide[i].parentPane.hidePane(panesToHide[i]);}
function getGridParentDom(gridConfig){if(gridConfig.parentDom){return gridConfig.parentDom;}else if(gridConfig.parentPane){return layout[gridConfig.parentPane].dom;}}
return layout;}
VL_Pane.cascadeCall=function(pane,fn){if(pane.panes){for(var i in pane.panes){fn(pane.panes[i]);if(pane.panes[i].childPane){VL_Pane.cascadeCall(pane.panes[i].childPane,fn);}}}else if(pane.childPane){fn(pane.childPane);if(pane.childPane.panes){VL_Pane.cascadeCall(pane.childPane,fn);}}};
SD.UI.Dating={};SD.UI.Dating.TabTemplates={item:'<div id="#{id}" class="tab #{itemClass} lib-tab">'+'<span class="tab-wrapper">'+'<i class="lib-tab-icon #{iconClass}"></i>'+'<span class="lib-tab-text">#{text}</span>'+'</span>'+'</div>',itemInactive:'tab inactive-tab',itemActive:'tab active-tab',itemAttention:'tab attention-tab',iconChat:'icon-date',iconWrite:'write-icon',iconClose:'close-icon',iconOffline:'offline-icon'};SD.UI.Dating.ChatTabTemplates={item:'<div id="#{id}" class="tab #{itemClass} lib-tab lib-tab-hover-close">'+'<span class="tab-wrapper">'+'<i class="lib-tab-icon #{iconClass}"></i>'+'<span class="lib-tab-text">#{text}</span>'+'</span>'+'</div>',itemInactive:'tab chat-inactive-tab',itemActive:'tab chat-active-tab',itemAttention:'tab chat-attention-tab',iconChat:'chat-icon',iconWrite:'write-icon',iconClose:'close-icon',iconOffline:'offline-icon'};SD.UI.Dating.MessagePaneTemplates={ENUM:{TYPING_MESSAGE:'typingMessage',PANE:'pane',CHAT_MESSAGE:'chatMessage',CHAT_MESSAGE_CONT:'chatMessageCont',CHAT_MESSAGE_FLIRT:'chatMessageFlirt',INFO_MESSAGE:'infoMessage',PLAIN_TEXT_MESSAGE:'plainTextMessage',ICE_BREAKER_MESSAGE:'iceBreakerMessage',OFFLINE_MESSAGE:'offlineMessage',PRESENCE_MESSAGE:'presenceMessage',FLIRT_MESSAGE:'flirtMessage',VIDEO_INVITATION:'videoInvitation',VIDEO_START_CONFIRM:'videoInitiatePermissionBox',UPGRADE_ON_SEND:'upgradeOnSend',CHAT_UPGRADE_ON_SEND:'chatUpgradeOnSend',CHAT_UPGRADE_OR_MATCH_TO_SEND:'chatUpgradeOrMatchToSend',UPGRADE_TO_SHARE_IM:'upgradeToShareIM',BRIEF_INFO_MSG:'briefInfoMsg',CHAT_HISTORY_BUTTON:'chatHistoryButton'},pane:"<div class='message-pane lib-message-pane lib-pane-message-holder' style='padding-top:100px;overflow:auto'></div>",chatMessage:'<div class="message from-#{meOther}">'+'<div class="message-from">#{from}<span class="timestamp">#{time}</span></div> '+'<div class="message-body">#{message}</div>'+'</div>',chatMessageCont:'<div class="message from-#{meOther}">'+'<div class="message-body">#{message}</div>'+'</div>',chatMessageFlirt:'<div class="message from-me">'+'<div class="message-from" style="font-weight: normal;">#{from} went offline. These messages are sent via email:</div> '+'<div class="message-body message-as-flirt">#{message}</div>'+'</div>',infoMessage:'<div class="message info-message">'+'<div class="message-body">#{message}</div>'+'</div>',plainTextMessage:'<div class="message plain-text-message">'+'<div class="message-body">#{message}</div>'+'</div>',iceBreakerMessage:'<div class="message ice-breaker-message">'+'<div class="message-body">#{message}</div>'+'</div>',presenceMessage:'<div class="message presence-message">'+'<div class="message-body status-#{isOnline}">#{message}</div>'+'</div>',offlineMessage:'<div class="message from-#{meOther}">'+'<div class="message-from">#{from}<span class="timestamp">#{time}</span></div> '+'<div class="message-body">#{message}</div>'+'</div>',flirtMessage:'<div class="message from-other">'+'<div class="message-from">#{from}<span class="timestamp">#{time}</span></div> '+'<div class="message-body">#{message}</div>'+'</div>',videoInvitation:'<div class="message video-invitation">'+'<i class="icon-webcam"></i> #{from} started a video chat session.<br/>Click <b>start webcam</b> button below to join'+'</div>',videoInitiatePermissionBox:'<div class="message video-invitation">'+'<i class="icon-webcam"></i> <span sdType="video-start-respose-dialog" sdUid="#{other_uid}"> #{from} wants to share #{other_his} live webcam video with you!<br/>SpeedDate does not monitor the webcam video. You have the ability to end a webcam video at anytime.<br/>'+'Do you wish to view it: <a href="javascript:void(#{yesCallback})">YES</a> <a href="javascript:void(#{noCallback})">NO</a></span>'+'</div>',typingMessage:function(){return''+'<div class="message typing-message">'+'<div class="message-body">#{name} is typing<img src="'+SD.Config.imageDir+'typing.gif" width="17" height="14" style="padding-left: 3px"></div> '+'</div>'},upgradeOnSend:function(){return''+'<div class="chat-banner">'+'<a class="upgrade-link" href="#{premium_url}">Subscribe</a> to extend your SpeedDate beyond '+(SD.Config.datingDuration/60)+' minutes with any member.'+'</div>';},chatUpgradeOnSend:function(){return''+'<div class="message info-message">'+'<div><a class="upgrade-link" sdType="upgradeLink"  sdTc="'+SD.TrackingCodes.trigger.communication.chat.non_premium_chat._value+'"  sdTi="#{uid}">Subscribe</a> to unlock the conversation and send this: #{message}.</div>'+'</div>'},chatUpgradeOrMatchToSend:function(){return''+'<div class="message info-message">'+'<div>Your partner did not vote yet. If you match with your partner, you will be able to talk for free or <a class="upgrade-link" sdType="upgradeLink"  sdTc="'+SD.TrackingCodes.trigger.communication.chat.non_premium_chat._value+'"  sdTi="#{uid}">subscribe now</a> to unlock the conversation and send your message: #{message}.</div>'+'</div>'},upgradeToShareIM:function(){return''+'<div class="message info-message">'+'<div>Only subscribers can share their personal contact information. <br/><a class="upgrade-link" sdType="upgradeLink"  sdTc="'+SD.TrackingCodes.trigger.communication.chat.non_premium_chat._value+'"  sdTi="#{uid}">Subscribe</a> to send your contact information.</div>'+'</div>'},tootltipMessage:'',briefInfoMsg:'<div class="match-container"><b class="match-header">Ice Breaker Tips:</b><br/>#{similarities}</div>',banner1:function(){return''+'<a class="upgrade-link" sdType="upgradeLink" sdTc="'+SD.TrackingCodes.trigger.banner.chat_popup._value+'"'+' sdTi="#{uid}">Upgrade to Premium Membership</a> to start chats with any member'},banner2:function(){return''+'<br/><a class="upgrade-link" sdType="upgradeLink" sdTc="'+SD.TrackingCodes.trigger.banner.chat_popup._value+'"'+' sdTi="#{uid}">Subscribe</a> to start chats with any member'},chatHistoryButton:''+'<div class="history-container"><a class="load-chat-link" sdType="load-chat-history" sduid="#{uid}" sdpanelid="#{panelId}">view chat history</a></div>',updateTextsForLowSegment:function(){this.upgradeOnSend=function(){return''+'<div class="chat-banner">'+'<a sdType="coins-link" class="upgrade-link" > Earn coins</a> for free or <a class="upgrade-link" href="#{premium_url}">subscribe</a> to extend your SpeedDate beyond '+(SD.Config.datingDuration/60)+' minutes with any member.'+'</div>';};this.chatUpgradeOnSend=function(){return''+'<div class="message info-message">'+'<div><a sdType="coins-link" class="upgrade-link" > Earn coins</a> for free or <a class="upgrade-link" sdType="upgradeLink"  sdTc="'+SD.TrackingCodes.trigger.communication.chat.non_premium_chat._value+'"  sdTi="#{uid}">Subscribe</a> to unlock the conversation and send your message: #{message}.</div>'+'</div>'};this.banner1=function(){return''+'<a class="upgrade-link" sdType="upgradeLink" sdTc="'+SD.TrackingCodes.trigger.banner.chat_popup._value+'"'+' sdTi="#{uid}">Subscribe</a> to start chats with any member'},this.banner2='<br/><a sdType="coins-link" class="upgrade-link" > Earn coins</a> for free to start chats with any member';}};SD.UI.Dating.DateInputModuleTemplates={frame:"<table cellpadding='0' cellspacing='0' style='width:100%;height:100%;'>"+"<tr><td class='input-module-td1'>"+"<table cellpadding='0' cellspacing='0' style='width:100%;'>"+"<tr><td style='border-style:solid;border-width:2px;border-color:orange;height:38px;background-color:#FFFFFF'>&nbsp;</td></tr>"+"</table>"+"</td></tr>"+"</table>"+"<textarea class='chat-input date-input lib-chat-input' style='position:absolute;top:4px;left:4px;height:32px;padding:0;overflow:auto'></textarea>"+"<span class='lib-chat-sender date-sender date-ui-button-mid gray' style='float:none;'>send<span></span></span>"};SD.UI.Dating.windowTemplate='<div class="chat-window lib-window chat-light-skin">'+'<div class="top table_window top_draggable lib-title">'+'<div class="dialog_nw top_draggable lib-draggable"></div>'+'<div class="dialog_ne top_draggable lib-draggable"></div>'+'<div class="dialog_n top_draggable lib-draggable lib-title">'+'<table border="0" cellpadding="0" cellspacing="0" width="100%">'+'<tr><td class="filler filler-first"></td><td class="filler"></td><td class="filler"></td><td class="filler"></td></tr>'+'</table>'+'</div>'+'</div>'+'<div class="mid table_window">'+'<div class="dialog_w"></div>'+'<div valign="top" class="dialog_content p-content lib-content">#{content}</div>'+'<div class="dialog_e"></div>'+'</div>'+'<div class="bot table_window lib-footer">'+'<div class="dialog_sw bottom_draggable lib-draggable"></div>'+'<div class="dialog_se resize_draggable lib-resize-handle-br"></div>'+'<div class="dialog_s bottom_draggable lib-draggable">'+'<table border="0" cellpadding="0" cellspacing="0" width="100%">'+'<tr><td class="filler filler-first"></td><td class="filler"></td><td class="filler"></td><td class="filler"></td></tr>'+'</table>'+'</div>'+'</div>'+'<div class="date-icon-minimize lib-minimize" sdType="tooltip" sdMessage="Minimize Window"></div>'+'<div class="date-icon-popin lib-popin" style="display:none" sdType="tooltip" sdMessage="Popin chats and dates back"></div>'+'</div>';SD.UI.Dating.DateToolbarTemplates={frame:'<div style="margin:4px 5px">'+'<span class="lib-but-webcam date-ui-button">'+'start webcam<i class="icon-webcam"></i><span></span>'+'</span>'+'<span class="lib-but-icebraker date-ui-button" style="margin-left:5px">'+'icebreaker<i class="icon-icebreaker"></i><span></span>'+'</span>'+'<span class="lib-but-extend-date date-ui-button" style="color:#006600;float:right;" sdType="tooltip" sdMessage="Extend Date by +1 Minute">'+'+1 Min<i class="icon-extend-date"></i><span></span>'+'</span>'+'<div class="lib-countdown-clock date-ui-countdown-clock" sdtype="tooltip" sdmessage="Minutes left for this SpeedDate">3:00</div>'+'</div>'};SD.UI.Dating.ChatToolbarTemplates={frame:SD.UI.Dating.DateToolbarTemplates.frame,frameFBChat:'<div style="margin:4px 5px">'+'<span class="lib-but-fb-invite date-ui-button" sdUid="#{uid}">'+'invite<i class="icon-fb-invite"></i><span></span>'+'</span>'+'<span class="lib-but-webcam date-ui-button" style="margin-left:5px">'+'start webcam<i class="icon-webcam"></i><span></span>'+'</span>'+'<span class="lib-but-icebraker date-ui-button" style="margin-left:5px">'+'icebreaker<i class="icon-icebreaker"></i><span></span>'+'</span>'+'<span class="lib-but-extend-date date-ui-button" style="color:#006600;float:right;" sdType="tooltip" sdMessage="Extend Date by +1 Minute">'+'+1 Min<i class="icon-extend-date"></i><span></span>'+'</span>'+'<div class="lib-countdown-clock date-ui-countdown-clock">3:00</div>'+'</div>'};SD.UI.Dating.LegacyDateHeaderTemplates={frame:'<div style="margin:5px 0 0 10px; width:375px; height: 30px; overflow:hidden; position:relative">'+'<div class="date-header-line1"><span class="user-name">#{name}</span>, <span class="user-age">#{age}</span></div>'+'<div class="date-header-line2"><span class="user-city">#{location}</span>, <span class="user-distance">(#{distance})</span></div>'+'</div>'+'<div style="position:absolute; right:4px; top:4px; width: 450px; height:22px">'+'<span class="lib-but-end-date date-ui-button2" style="float:right;width:92px">'+'End SpeedDate<i class="icon-end-date"></i><span></span>'+'</span>'+'<span sdType="report_dialog" class="lib-but-report-abuse date-ui-button2" style="float:right;margin-right:5px">'+'Report Abuse<i class="icon-report-abuse"></i><span></span>'+'</span>'+'</div>'};SD.UI.Dating.DateHeader3ButTemplates={baseFrame:function(context){return''+'<div style="margin:5px 0 0 10px; width:375px; height: 30px; overflow:hidden; position:relative">'+'<div class="date-header-line1"><span class="user-name">#{name}</span>, <span class="user-age">#{age}</span></div>'+'<div class="date-header-line2"><span class="user-city">#{location}</span>, <span class="user-distance">(#{distance})</span></div>'+'</div>'+'<div style="position:absolute; right:4px; top:4px; width: 450px; height:22px">'+'<span class="'+(context==='date'?'lib-but-end-date':'lib-but-end-chat')+' date-ui-button2" style="float:right;width:92px">'+'End '+(context==='date'?'SpeedDate':'Chat')+'<i class="icon-end-date"></i><span></span>'+'</span>'+'<span sdType="report_dialog" class="lib-but-report-abuse date-ui-button2" style="float:right;margin-right:5px">'+'Report Abuse<i class="icon-report-abuse"></i><span></span>'+'</span>'+'<span sdType="block" class="lib-block date-ui-button2" style="float:right;margin-right:5px">'+'Block User<i class="icon-block"></i><span></span>'+'</span>'+'</div>';},dateFrame:function(){return SD.UI.Dating.DateHeader3ButTemplates.baseFrame('date');},chatFrame:function(){return SD.UI.Dating.DateHeader3ButTemplates.baseFrame('chat');},fbChatFrame:function(dateHeaderData){dateHeaderData=dateHeaderData||{};return''+'<div style="margin:5px 0 0 10px; width:375px; height: 30px; overflow:hidden; position:relative">'+'<div class="date-header-line1"><span class="user-name">#{name}</span>'+
(dateHeaderData.age?', <span class="user-age">#{age}</span>':'')+'</div>'+'<div class="date-header-line2">'+
(dateHeaderData.location?'<span class="user-city">#{location}</span>':'')+'</div>'+'</div>'+'<div style="position:absolute; right:4px; top:4px; width: 450px; height:22px">'+'<span class="'+'lib-but-end-chat'+' date-ui-button2" style="float:right;width:92px">'+'End Chat <i class="icon-end-date"></i><span></span>'+'</span>'+'</div>';}};SD.UI.Dating.DateHeaderTemplates={frame:'<div style="width:275px; height: 32px; overflow:hidden; position:relative">'+'<div class="date-header-line11">Date with <span class="user-name">#{name}</span>, <span class="user-age">#{age}</span>, '+'<span class="user-city">#{location}</span> <span class="user-distance">(#{distance})</span></div>'+'</div>'+'<div style="position:absolute; right:4px; top:4px; width: 100px; height:22px">'+'<div class="header-icon icon-close lib-but-end-date" sdType="tooltip" sdMessage="End Date With #{name}" ></div>'+'<div class="header-icon icon-block lib-block" sdType="block" sdMessage="Block #{name}" ></div>'+'<div class="header-icon icon-report lib-but-report-abuse" sdType="tooltip" sdMessage="Report #{name}" ></div>'+'</div>'};SD.UI.Dating.ChatHeaderTemplates={frame:'<div style="width:275px; height: 32px; overflow:hidden; position:relative">'+'<div class="date-header-line11">Chat with <span class="user-name">#{name}</span>, <span class="user-age">#{age}</span>, '+'<span class="user-city">#{location}</span> <span class="user-distance">(#{distance})</span></div>'+'</div>'+'<div style="position:absolute; right:4px; top:4px; width: 100px; height:22px">'+'<div class="header-icon icon-close lib-but-end-chat" sdType="tooltip" sdMessage="Close Chat With #{name}" ></div>'+'<div class="header-icon icon-block lib-block" sdType="block" sdMessage="Block #{name}" ></div>'+'<div class="header-icon icon-report lib-but-chat-report-abuse" sdType="tooltip" sdMessage="Report #{name}" ></div>'+'</div>'};SD.UI.Dating.WebcamPaneTemplates={frame:"<div class='lib-webcam-others date-other-webcam'></div>"};SD.UI.Dating.ReportAbuseTemplates={frame:'<div class="lib-report-dom" style="position:absolute;top:0;left:0;width:100%;height:100%;_height:1000px;">'+'<div class="lib-report-shim dating-report-shim"></div>'+'<div class="dating-report-dialog2">'+'<div class="btn-dating-close lib-close-dialog fake-link">Back to chat X</div>'+'<div class="dating-report-adjustment1"></div>'+'<div class="dating-report-dialog-title2">Report Abuse</div>'+'<div class="dating-report-dialog-bottom"></div>'+'<div class="dating-report-dialog-content">'+'<form class="lib-data-form">'+'<p class="dating-report-dialog-warning">'+'Select a reason below to ban your date from SpeedDate. '+'Note that a screenshot of your date and chat will be sent '+'to the SpeedDate Team for investigation.'+'</p>'+'<p class="data"><input type="radio" name="reason" value="scammer"> Scammer\/Spammer\/Advertiser</p>'+'<p class="data"><input type="radio" name="reason" value="explicit"> Sexually Explicit</p>'+'<p class="data"><input type="radio" name="reason" value="fake"> Impostor\/Fake User</p>'+'<p class="data"><input type="radio" name="reason" value="no_photo"> User Not in Photo</p>'+'<p class="data"><input type="radio" name="reason" value="cyberbully"> Cyberbullying\/Harrasment</p>'+'<p class="data"><input type="radio" name="reason" value="underage"> Under 18 years old</p>'+'<p class="data"><input type="radio" name="reason" value="profane_username"> Profane Username</p>'+'</form>'+'</div>'+'</div>'+'</div>'};SD.UI.Dating.EndDateTemplates={frame:'<div class="lib-end-date-dom" style="position:absolute;top:0;left:0;width:100%;height:100%;_height:1000px;">'+'<div class="lib-end-date-shim dating-end-date-shim"></div>'+'<div class="dating-end-date-dialog2 lib-end-date-holder">'+'<div class="btn-dating-close lib-close-dialog fake-link">Back to chat X</div>'+'<div class="dating-end-date-dialog-bottom"></div>'+'<div class="lib-end-date-title dating-end-date-dialog-top-adjustment1">'+'<div class="title-adjustment1">End SpeedDate</div>'+'<div class="right-adjustment2"></div>'+'</div>'+'<div class="lib-end-date-content dating-end-date-dialog-content">'+'<a href="javascript:void(0)" class="lib-but-back date-ui-button" style="position:absolute;padding-left:8px;top:8px;left:10px;">'+'&#171; Return to SpeedDate<span></span>'+'</a>'+'<form class="lib-data-form">'+'<div class="dialog-subheading" style="margin:35px 0 10px 0"><strong>Reason for ending SpeedDate</strong> (optional)</div>'+'<div class="data"><input type="radio" name="reason" value="type_mismatch"> Not my type</div>'+'<div class="data"><input type="radio" name="reason" value="photo_or_not_enough_profile"> Photo issue or not enough profile info</div>'+'<div class="data"><input type="radio" name="reason" value="prefer_verified_member"> I prefer verified members</div>'+'<div class="data"><input type="radio" name="reason" value="not_ready"> I wasn\'t ready to have a date just now</div>'+'<div class="data"><input type="radio" name="reason" value="other"> Other</div>'+'<div class="data-section">'+'<textarea class="lib-textarea" name="other" >Please enter your reasons here</textarea>'+'</div>'+'<div class="do-not-display-old-reasons" style="display:none;">'+'<div class="data"><input type="radio" name="reason" value="no_asl_match"> Doesn\'t match my age\/location preferences</div>'+'<div class="data-section">'+'<div>Change SpeedDating Preferences</div>'+'<table cellpadding="3" cellspacing="0"><tr>'+'<td style="padding:2px">ages</td>'+'<td style="padding:2px"><select name="min_age" class="lib-min-age-control"></select></td>'+'<td style="padding:2px">to</td>'+'<td style="padding:2px"><select name="max_age" class="lib-max-age-control"></select></td>'+'<td style="padding:2px"><select name="location"></select></td>'+'</tr></table>'+'</div>'+'<div class="data"><input type="radio" name="reason" value="no_response"> My date isn\'t responding</div>'+'<div class="data"><input type="radio" name="reason" value="photo_issue"> Photo Issue</div>'+'<div class="data"><input type="radio" name="reason" value="scammer"> Report User: Fake user\/scammer</div>'+'</div>'+'</form>'+'<a href="javascript:void(0)" class="lib-but-end-and-find date-ui-button-mid green" style="float:none;margin:5px auto;width:200px;">'+'Find me Another SpeedDate &#0187;<span></span>'+'</a>'+'<a href="javascript:void(0)" class="lib-but-end-and-pause" style="float:right;margin:5px 20px 5px 5px;">'+'Pause SpeedDating<span></span>'+'</a>'+'</div>'+'</div>'+'</div>'};SD.UI.Dating.PreDateDialogTemplates={frame:'<div class="lib-dialog-holder" style="position:absolute;top:0;left:0;width:100%;height:100%">'+'<div class="predate-dialog-container">'+'<div class="predate-dialog-line1">We Found You a SpeedDate</div>'+'<div class="predate-dialog-line2">You are about to meet <b>#{name}</b> in <span class="lib-countdown-placeholder predate-dialog-clock">5</span></div>'+'</div>'+'</div>'};SD.UI.Dating.PostDateDialogTemplates={frame:'<div class="lib-dialog-holder" style="position:absolute;top:0;left:0;width:100%;height:100%;.height:1000px">'+'<div class="postdate-dialog-shim"></div>'+'<div class="postdate-dialog lib-postdate-dialog" #{extraStylePopup}>'+'<div class="postdate-dialog-bottom"></div>'+'<div class="postdate-dialog-content" #{extraStyle}>'+'#{content}'+'</div>'+'</div>'+'</div>',_section1:'<a href="javascript:void(0)" class="lib-date-left-triggers date-ui-button-mid green" '+'style="float:none;padding:0;margin:25px auto 5px auto;width:200px;text-align:center;">'+'#{dateLeftTriggerLabel} <span></span>'+'</a>'+'<a href="javascript:void(0)" class="lib-but-contact date-ui-button-mid subscribe-button-in-action-triggers green" '+'style="float:none;padding:0;margin:5px auto;width:200px;text-align:center;">'+'Subscribe and Contact #{name}<span></span>'+'</a>'+'<a href="javascript:void(0)" class="lib-but-find-date" style="display:block;float:right;margin:10px">Find me someone else &#187;</a><br/>',callToAction_for_the_ender:'<div style="margin-top:25px;">'+'#{dateLeftTriggerReason}'+'</div>'+'<a href="javascript:void(0)" class="lib-date-left-triggers date-ui-button-mid green" '+'style="float:none;padding:0;margin:25px auto 5px auto;width:200px;text-align:center;">'+'#{dateLeftTriggerLabel} <span></span>'+'</a>'+'<a href="javascript:void(0)" class="lib-but-find-date" style="display:block;float:right;margin:10px">Close &#187;</a><br/>',callToAction:function(){return''+'<table style="width:300px;height:70px">'+'<tr>'+'<td>'+'#{dateLeftTriggerReason}'+'</td>'+'</tr>'+'</table>'+
SD.UI.Dating.PostDateDialogTemplates._section1},advanced:'<div style="margin-top:15px;"><b>#{name} left the SpeedDate</b>, but you can have '+'another chance. Find out why #{pronoun} left the chat and send #{pronoun_passive} a message!'+'</div>'+'<a href="javascript:void(0)" class="lib-but-contact date-ui-button-mid green" style="float:none;padding:0;margin:25px auto 5px;width:200px;text-align:center;">'+'Subscribe and Contact #{name}<span></span>'+'</a>'+'<a href="javascript:void(0)" class="lib-but-find-date" style="display:block;float:right;margin:15px 5px 5px 5px">Find me someone else &#187;</a>',advanced_3174:'<div style="margin-top:15px;">'+'#{dateLeftTriggerReason}'+'</div>'+'<a href="javascript:void(0)" class="lib-but-contact date-ui-button-mid green" style="float:none;padding:0;margin:25px auto 5px;width:200px;text-align:center;">'+'#{dateLeftTriggerLabel}<span></span>'+'</a>'+'<a href="javascript:void(0)" class="lib-but-find-date" style="display:block;float:right;margin:15px 5px 5px 5px">Find me someone else &#187;</a>',simple:'<div style="margin-top:35px;"><b>#{name} left the SpeedDate</b>, '+'because #{reasonText}'+'</div>'+'<a href="javascript:void(0)" class="lib-but-contact date-ui-button-mid green" style="float:none;padding:0;margin:25px auto;width:200px;text-align:center;">'+'Contact #{name}<span></span>'+'</a>'+'<a href="javascript:void(0)" class="lib-but-find-date" style="display:block;float:right;margin:10px">Find me someone else &#187;</a>',vote:'<div style="margin-top:15px;">SpeedDate with #{name} ended.<br/>'+'<b>Did you match with #{name}</b>?'+'</div>'+'<a href="javascript:void(0)" class="lib-but-maybe-later date-ui-button-mid green" style="float:none;padding:0;margin:25px auto 5px auto;width:200px;text-align:center;">'+'Yes<span></span>'+'</a>'+'<a href="javascript:void(0)" class="lib-but-no-thanks date-ui-button-mid red" style="float:none;padding:0;margin:5px auto;width:200px;text-align:center;">'+'No<span></span>'+'</a>'+'<div class="lib-fb-like-profile-section" style="display:none"></div>',voteAdvanced:'<div style="margin-top:15px;">SpeedDate with #{name} ended. '+'Do you want to <b>continue chatting with #{name}</b>?'+'</div>'+'<a href="#{premium_url}" class="lib-but-continue-chat date-ui-button-mid green" style="float:none;padding:0;margin:25px auto 5px auto;width:200px;text-align:center;">'+'Continue Chatting<span></span>'+'</a>'+'<a href="#{premium_url}" class="lib-but-maybe-later date-ui-button-mid yellow" style="float:none;padding:0;margin:5px auto;width:200px;text-align:center;">'+'Maybe Later<span></span>'+'</a>'+'<a href="javascript:void(0)" class="lib-but-no-thanks date-ui-button-mid red" style="float:none;padding:0;margin:5px auto;width:200px;text-align:center;">'+'No Thanks<span></span>'+'</a>'+'<div class="lib-fb-like-profile-section" style="display:none"></div>'};SD.UI.Dating.ChatObserverModuleTemplates={frame:function(){return''+'<div class="lib-content-holder">'+
this.unselected+'</div>';},selected:function(data){var ret='<div class="observer-head">'+'<a href="javascript:void(0)" sduid="#{uid}" sdtype="chat" sdsource="connections"><img  class="buddy-image fake-link" src="#{square_image_url}" sduid="#{uid}"><span class="observer-link"><b>#{username}</b><br>is observing this chat</span></a><div class="clear"></div> ';ret+='<span class="lib-remove-chat-observer x-observer" sdtype="tooltip" sdmessage="Stop #{username} from observing">X</span>'+'</div>';return ret;},unselected:'<div class="lib-open-chat-observer-list observer-head"><a href="javascript:void()"><img  class="buddy-image fake-link no-observer"><span class="observer-link invite-observer"><b>Ask a friend</b><br>to give you feedback on this chat</span></a><div class="clear"></div></div>'};SD.UI.CountdownClock=Class.create({initialize:function(dom){this.doms=[$(dom)];this.timer=null;this.onClockEnd=null;this.format='m:ss';this.container=null;this.displayFunction=function(){this.time=Math.floor(this.initialTime+10+(this.startedAt-(new Date()).getTime())/1000);if(this.startInstant){this.time-=10;}
this.time=Math.min(this.time,this.initialTime);if(this.time<=0){this.stop();this.onClockEnd&&this.onClockEnd(this.container.id);return;}
this.display();}.bind(this);this.simpleTick=function(){this.time--;if(this.time<=0){this.stop();this.onClockEnd&&this.onClockEnd(this.container.id);return;}
this.display();}.bind(this);this.doms.invoke('update',SD.Utils.formatedSeconds(SD.Config.datingDuration,this.format));},setup:function(startedAt,time,format,onClockEnd,startInstant){this.startInstant=startInstant||false;this.startedAt=startedAt;this.time=time;this.initialTime=time;this.format=this.format||format;this.onClockEnd=(onClockEnd!==undefined)?onClockEnd:this.onClockEnd;this.display();},simpleSetup:function(time,format,onClockEnd){this.initialTime=time;this.time=time;this.format=this.format||format;this.onClockEnd=onClockEnd||this.onClockEnd;},start:function(tick){tick=tick||this.displayFunction;this.display();if(this.time<=0){return;}
this.stop();this.timer=setInterval(tick,1000);},set:function(value){this.doms.invoke('update',value);},stop:function(){if(this.timer){this.set('0:00');clearInterval(this.timer);}},reset:function(){this.time=this.initialTime;this.display();},getFormattedTime:function(){return SD.Utils.formatedSeconds(this.time,this.format);},registerDomForDisplay:function(dom){this.doms.push($(dom));},display:function(){var formattedTime=this.getFormattedTime();this.doms.invoke('update',formattedTime);},show:function(){this.doms.invoke('show');},hide:function(){this.doms.invoke('hide');}});SD.UI.Dating.Component=SD.UI.Component;SD.UI.Dating.Container=SD.UI.Container;SD.UI.Dating.Tab=Class.create(SD.UI.Dating.Component,{templateSet:SD.UI.Dating.TabTemplates,initTemplate:SD.UI.Dating.TabTemplates.item,defaults:{cls:'itemInactive',width:100,maxWidth:150,maxTextLength:20},initialize:function($super,options){this.cls=options.cls||this.defaults.cls;this.width=options.width||this.defaults.width;this.maxWidth=options.maxWidth||this.defaults.maxWidth;this.isHoverCloseEnabled=options.isHoverCloseEnabled||false;this.onClose=options.onClose||this.onClose;this.onActivate=options.onActivate||this.onActivate;this.text=options.data.text;this.tabStatus=SD.UI.Dating.Tab.STATUS_INACTIVE;this.iconState=SD.UI.Dating.Tab.ICON_STATE_CHAT;$super(options);},dataFilter:function(data){data=data||{};data.itemClass=data.itemClass||this.templates.itemInactive;data.iconClass=data.iconClass||this.templates.iconChat;data.closeIconClass=data.closeIconClass||this.templates.iconClose;data.text=data.text||'';data.id=this.id;return data;},setup:function(){this.dom.onmousedown=function(e){SD.Event.fire(this,SD.UI.Dating.Tab.Events.TAB_CLICK,{tab:this});if(this.tabStatus==SD.UI.Dating.Tab.STATUS_ACTIVE){return false;}
SD.Event.fire(this,SD.UI.Dating.Tab.Events.TAB_ACTIVATED,{tab:this});Event.stop(e||window.event);return false;}.bind(this);if(this.isHoverCloseEnabled){this.domIcon.onclick=this.domIcon.ondblclick=function(e){if(this.tabStatus==SD.UI.Dating.Tab.STATUS_ACTIVE){SD.Event.fire(this,SD.UI.Dating.Tab.Events.TAB_CLOSED,{tab:this});Event.stop(e||window.event);}
return false;}.bind(this);this.domIcon.onmouseover=function(e){if(this.tabStatus==SD.UI.Dating.Tab.STATUS_ACTIVE){this.domIcon.className=this.templates.iconClose;}}.bind(this);this.domIcon.onmouseout=function(e){this.updateIconState();}.bind(this);}else{this.domIcon.ondblclick=function(e){Event.stop(e||window.event);return false;}}
var _this=this;this.blinker=SD.Utils.Blinker({periodicalExecuter:SD.Utils.PeriodicalExecuter(500),times:10,onAction:function(){_this.dom.className=_this.templates.itemAttention;},offAction:function(){_this.dom.className=_this.templates.itemInactive;},onEnd:function(){_this.dom.className=_this.templates.itemAttention;}});},setupTabOver:function(mouseoverHandler){this.dom.onmouseover=mouseoverHandler;},setupTabOut:function(mouseoutHandler){this.dom.onmouseout=mouseoutHandler;},setActive:function(){try{this.blinker&&this.blinker.isRunning&&this.blinker.stop();this.tabStatus=SD.UI.Dating.Tab.STATUS_ACTIVE;this.dom&&(this.dom.className=this.templates.itemActive);this.onActivate(this);}catch(e){}},setInactive:function(){if(!this.dom)return;this.tabStatus=SD.UI.Dating.Tab.STATUS_INACTIVE;this.dom&&(this.dom.className=this.templates.itemInactive);this.onInactivate(this);},setAttention:function(){this.blinker.isRunning?this.blinker.reset():this.blinker.start();this.tabStatus=SD.UI.Dating.Tab.STATUS_ATTENTION;},setText:function(text){this.text=text;this.domText&&(this.domText.innerHTML=this.textFilter(this.text));},textFilter:function(text){return text;},setIconState:function(state){this.iconState=state;this.updateIconState();},updateIconState:function(){if(this.iconState==SD.UI.Dating.Tab.ICON_STATE_CHAT){this.domIcon.className=this.templates.iconChat;}else if(this.iconState==SD.UI.Dating.Tab.ICON_STATE_WRITING){this.domIcon.className=this.templates.iconWrite;}else if(this.iconState==SD.UI.Dating.Tab.ICON_STATE_OFFLINE){this.domIcon.className=this.templates.iconOffline;}else{this.iconState=SD.UI.Dating.Tab.ICON_STATE_CHAT;this.domIcon.className=this.templates.iconChat;}},close:function(){this.destroy();this.onClose(this);},destroy:function(){try{this.dom.update();Element.GCScheduler.purge(this.dom);this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom);this.dom=null;this.domIcon=null;this.blinker.isRunning&&this.blinker.stop();this.blinker=null;}catch(e){}},parseLibrary:{'lib-tab':function(el,domRoot){this.dom=el;},'lib-tab-icon':function(el,domRoot){this.domIcon=el;},'lib-tab-text':function(el,domRoot){this.domText=el;},'lib-tab-hover-close':function(el,domRoot){this.isHoverCloseEnabled=true;}}});SD.UI.Dating.Tab.Events={TAB_ACTIVATED:"SD.UI.Dating.Tab.Events:TAB_ACTIVATED",TAB_CLOSED:"SD.UI.Dating.Tab.Events:TAB_CLOSED",TAB_CLICK:"SD.UI.Dating.Tab.Events:TAB_CLICK"}
Object.extend(SD.UI.Dating.Tab,{STATUS_ACTIVE:1,STATUS_INACTIVE:2,STATUS_ATTENTION:3,ICON_STATE_CHAT:11,ICON_STATE_WRITING:12,ICON_STATE_OFFLINE:13,MIN_WIDTH:1,MAX_WIDTH:150,ACTIVE_TAB_MIN_WIDTH:150});SD.UI.Dating.TabContainer=Class.create(SD.UI.Dating.Container,{initialize:function($super,options){this.dom=options.dom;this.minTabWidth=options.minTabWidth||SD.UI.Dating.Tab.MIN_WIDTH;this.maxTabWidth=options.maxTabWidth||SD.UI.Dating.Tab.MAX_WIDTH;this.minActiveTabWidth=options.minActiveTabWidth||SD.UI.Dating.Tab.ACTIVE_TAB_MIN_WIDTH;$super(options);},buildTab:function(options,TabConstructor){TabConstructor=TabConstructor||this.options.tabConstructor||SD.UI.Dating.Tab;var tab=new TabConstructor(options);this.addItem(tab);tab.onActivate=SD.Utils.connect(tab.onActivate,this.adjustTabs.bind(this));tab.onClose=SD.Utils.connect(tab.onClose,this.adjustTabs.bind(this));this.adjustTabs.bind(this).defer();return tab;},adjustTabs:function(){var totalWidth=0;var activeTab=this.getActiveItem();var availableWidth=this.dom.offsetWidth;this.getItems().each(function(tab){tab.dom&&(totalWidth+=tab.dom.offsetWidth);});var w=Math.floor(availableWidth/this.getCount());var delta=availableWidth%this.getCount();if(activeTab&&w<this.minActiveTabWidth){w=Math.floor((availableWidth-this.minActiveTabWidth)/(this.getCount()-1));delta=(availableWidth-this.minActiveTabWidth)%(this.getCount()-1);}
w=Math.min(Math.max(w,this.minTabWidth),this.maxTabWidth);this.getItems().each(function(tab){if(tab==activeTab){activeTab.dom&&$(activeTab.dom).setWidth(Math.max(w,this.minActiveTabWidth));}else{tab.dom&&$(tab.dom).setWidth(w+getAdder());}
delta--;},this);function getAdder(){return delta>0?1:0;}},reset:function(){this.activeItem=null;},destroyTab:function(tab){try{tab.close();this.removeItem(tab);}catch(e){}}});SD.UI.Dating.PostDateDialog=Class.create(SD.UI.Dating.Component,{templateSet:SD.UI.Dating.PostDateDialogTemplates,initTemplate:SD.UI.Dating.PostDateDialogTemplates.frame,setup:function(){this.show();},dataFilter:function(data){data.name=data.name.truncate(SD.UI.Dating.PostDateDialog.MAX_NAME_LENGTH);return data;},show:function(){this.dom.style.visibility='';},hide:function(){this.dom.style.visibility='hidden';},close:function(){this.dom&&this.dom.parentNode&&this.dom.remove();this.onClose();},showFbDialog:function(){this.domFBDialog&&(this.domFBDialog.style.display='block');this.domDialogBodyMain&&(this.domDialogBodyMain.style.height='290px');},parseLibrary:{'lib-dialog-holder':function(el,domRoot){this.dom=el;},'lib-but-find-end-date-reason':function(el,domRoot){el.onclick=function(){SD.Event.fire(this,SD.UI.DateUI.Events.FIND_END_DATE_REASON,{panelId:this.container.id,uid:this.data.uid});this.close();}.bind(this);},'lib-but-contact':function(el,domRoot){el.onclick=function(){SD.Event.fire(this,SD.UI.DateUI.Events.CONTACT_USER,{panelId:this.container.id,uid:this.data.uid});this.close();}.bind(this);},'lib-date-left-triggers':function(el,domRoot){el.onclick=function(e){(function(){SD.FlowManager.run(SD.Flows.date.clone(),SD.Utils.buildContext({sourceMemberId:this.data.uid,sourceType:SD.UIController.PopupSourceTypes.DATE},e));}).bind(this).delay(0.1);SD.Event.fire(this,SD.UI.DateUI.Events.FIND_DATE,{panelId:this.container.id,uid:this.data.uid});}.bind(this);},'lib-but-find-date':function(el,domRoot){el.onclick=function(){SD.Event.fire(this,SD.UI.DateUI.Events.FIND_DATE,{panelId:this.container.id,uid:this.data.uid});this.close();}.bind(this);},'lib-but-continue-chat':function(el,domRoot){el.onclick=function(e){SD.Event.fire(this,SD.UI.DateUI.Events.CONTINUE_CHAT,{panelId:this.container.id,uid:this.data.uid,text:'continue'});this.close();if(SD.Model.getMyself().is_premium){Event.stop(e||window.event);return false;}}.bind(this);},'lib-but-maybe-later':function(el,domRoot){el.onclick=function(e){SD.Event.fire(this,SD.UI.DateUI.Events.CONTINUE_CHAT,{panelId:this.container.id,uid:this.data.uid,text:'later'});this.close();Event.stop(e||window.event);return false;}.bind(this);},'lib-but-no-thanks':function(el,domRoot){var _this=this;el.onclick=function(){_this.showFbDialog();_this.onClose=SD.Utils.connect(_this.onClose,function(){SD.Event.fire(this,SD.UI.DateUI.Events.NO_MATCH,{panelId:_this.container.id,uid:_this.data.uid});});(function(){el.onclick=function(){_this.close();};}).defer();};},'lib-countdown-placeholder':function(el,domRoot){this.domCountdown=el;},'lib-fb-like-profile-section':function(el,domRoot){var _this=this;this.domFBDialog=el;new Ajax.Request(SD.NavUtils.link('profile','facebook_share_popup'),{parameters:{sourceMemberId:'',sourceType:'',actionType:SD.UIController.ActionTypes.SHARE_PROFILE,actionData:'{"sharedMemberId" : "'+this.data.uid+'"}',view:'short',displayType:'ajax'},onSuccess:function(response){onSuccess(response);}});var onSuccess=function(response){_this.domDialogBodyMain=domRoot.select('.lib-postdate-dialog').first();el.update(response.responseText);var butLastNoThanks=el.select('.lib-no-thanks-last')[0];if(butLastNoThanks){butLastNoThanks.onclick=function(){_this.close();}}
var formEl=el.select('form')[0];var shareBut=el.select('.lib-fb-button')[0];formEl.submit=formEl.request.bind(formEl,{onComplete:function(response){el.update('<div style="text-align:center;margin-top:20px">The profile was successfully shared!</div>'+'<div class="lib-no-thanks-last fake-link" style="margin-top:25px;text-align:center;cursor:pointer">Close</div>');el.select('.lib-no-thanks-last')[0].onclick=function(){_this.close();}}});shareBut.onclick=function(){SD.UI.DateUI.shareWithFacebook(formEl);};};}}});SD.UI.Dating.PostDateDialog.MAX_NAME_LENGTH=12;SD.UI.Dating.PostDateVoteDialog=Class.create(SD.UI.Dating.PostDateDialog,{initialize:function($super,options){this.initTemplate=typeof this.initTemplate==='function'?this.initTemplate():this.initTemplate;var user=SD.User.get(options.data.uid);options.initTemplate=this.initTemplate.interpolate({username:user.name,uid:user.uid,thumb_pic:user.images[0].image_url,content:this.templateSet.vote});$super(options);}});SD.UI.Dating.PostDateAdvancedDialog=Class.create(SD.UI.Dating.PostDateDialog,{initialize:function($super,options){this.initTemplate=typeof this.initTemplate==='function'?this.initTemplate():this.initTemplate;var user=SD.User.get(options.data.uid);options.initTemplate=this.initTemplate.interpolate({username:user.name,uid:user.uid,thumb_pic:user.images[0].image_url,content:this.templateSet.voteAdvanced});$super(options);}});SD.UI.Dating.PostDateContactSimpleDialog=Class.create(SD.UI.Dating.PostDateDialog,{initialize:function($super,options){this.initTemplate=typeof this.initTemplate==='function'?this.initTemplate():this.initTemplate;var user=SD.User.get(options.data.uid);options.initTemplate=this.initTemplate.interpolate({username:user.name,uid:user.uid,thumb_pic:user.images[0].image_url,content:this.templateSet.simple});$super(options);}});SD.UI.Dating.EndDateFilter={filter:function(dialog,options){var constructDateData=function(otherUserId){var isOwnMale=SD.Model.getMyself().sex=='M';var otherUser=SD.User.get(otherUserId);var isOtherMale=otherUser.sex=='M';return{own_username:SD.Model.getMyself().name,own_handsome:isOwnMale?"handsome":"pretty",own_good_looking:isOwnMale?"good looking":"pretty",own_guy:isOwnMale?"guy":"girl",own_guys:isOwnMale?"guys":"women",own_gender_pl:isOwnMale?"men":"women",own_gender_sg:isOwnMale?"man":"woman",own_dude:isOwnMale?'Dude':'Girlfriend',own_boy:isOwnMale?'boy':'sister',own_his:isOwnMale?'his':'her',other_username:otherUser.name,other_pronoun:isOtherMale?"he":"she",other_obj_pronoun:isOtherMale?"him":"her",other_gender_sg:isOtherMale?"men":"women",other_gender_pl_cap:isOtherMale?"Men":"Women",other_gender_pl:isOtherMale?"men":"women",other_boy:isOtherMale?'boy':'sister',other_Mr:isOtherMale?'Mr.':'Miss.',other_his:isOtherMale?'his':'her',link:'class="lib-date-left-triggers" href="javascript:void(0)"',isMyself:options.data.isMyself};};var generateRandomSpeedVerifyMessage=function(data){var messages;if(data.isMyself){messages=["<b>You're a real person right?</b> Then take one minute to SpeedVerify&#0153 so everyone knows you're safe to talk to!","Let others know you really are who you say you are \u2013 SpeedVerify&#0153 now and meet our most popular members faster","Don't be <b>the last #{own_guy} picked for a SpeedDate&#0153</b>. SpeedVerify&#0153 yourself right now and get prioritized for SpeedDates first!","<b>Want to be more popular on SpeedDate&#0153 and get more dates?</b> Then SpeedVerify&#0153 yourself right now so people trust you!"];}else{messages=["#{other_username} prefers to SpeedDate&#0153 #{own_gender_pl} who are verified. <a #{link}>Take one minute to SpeedVerify&#0153</a> to meet our best members faster.","It's not you, it's your profile. <a #{link}>SpeedVerify&#0153; your profile</a> in one minute and #{other_gender_pl} like #{other_username} will stick around for SpeedDates.","#{other_username} prefers to SpeedDate SpeedVerified&#0153; #{own_gender_pl}</a>. You’re 3x more likely to chat with #{other_gender_pl} when your profile is <a #{link}>SpeedVerified&#0153</a>.","Uh oh. #{other_username} left the chat. <a #{link}>SpeedVerify&#0153;</a> your profile now so this kind of thing doesn't happen again.","You and #{other_username} might have hit it off, but #{other_pronoun} prefers #{own_guys} who <a #{link}>SpeedVerify&#0153</a> their profiles.","#{other_username} may have ended the SpeedDate&#0153 because you aren’t SpeedVerified&#0153 yet.  <a #{link}>Verify your profile</a> and we’ll prioritize your account so you'll meet our best people faster."];}
return getRandomInterpolatedElement(messages,data);};var generateRandomVerifyMailMessage=function(data){var messages;if(data.isMyself){messages=["The past #{other_gender_pl} you\u2019ve SpeedDated want to send you messages. But first we need you to verify your email!","Thanks for speed dating with #{other_username}. If you want to receive messages from #{other_obj_pronoun} or anyone else you have to verify your email!","Remember the thrill of getting your first message from your first love? Well get the thrill again \u2013 you may have messages waiting but we need you to verify your email first!"];}else{messages=["#{other_username} ended the SpeedDate&#0153.  Don't worry - <a #{link}>verify your email</a> and we'll match you with other compatible #{other_gender_pl}!","#{other_username} left the SpeedDate&#0153.  While we search for other #{other_gender_pl} for you to meet, <a #{link}>verify your email</a> so you don't miss any messages."];}
return getRandomInterpolatedElement(messages,data);};var generateRandomMoreProfileMessage=function(data){var messages;if(data.isMyself){messages=["Thanks for speed dating with #{other_username}. Wait! We know so little about you \u2013 you aren't a secret agent are you? <b>Share a little about yourself to get better dates!</b>","Onto your next SpeedDate&#0153! But if you're <b>looking for better SpeedDates</b> \u2013 you have to <b>complete your profile</b> and tell us who you’re looking for!","<b>Want better quality SpeedDates?</b> You gotta tell us what you're looking for \u2013 then we can hook you up!","#{other_username} would have loved to have discussed more things in common with you. But #{other_pronoun} had no clue since your profile is incomplete!","#{other_username} didn't know if you were 4 foot 2 or 6 foot 2. Imagine how awkward it would be to ask! If you complete your profile, you'll get better SpeedDates."];}else{messages=["#{other_username} left the SpeedDate&#0153 because #{other_pronoun} likes to see more profile info. Take a minute to <a #{link}>add to your profile</a>!","#{other_username} ended the chat because #{other_pronoun} had no idea what to talk to you about. <a #{link}>Adding to your profile</a> makes it easier for people to strike up a conversation with you.","#{other_username} prefers to SpeedDate&#0153 #{own_guys} with a bit <a #{link}>more profile info</a>. Make sure your next SpeedDate&#0153 at least gives you the time of day!","#{other_username} didn’t know if you were 4 foot 2 or 6 foot 2. Imagine how awkward it would be to ask. If you <a #{link}>add to your profile</a>, you'll get great results."];}
return getRandomInterpolatedElement(messages,data);};var generateRandomNoPhotoMessage=function(data){var messages;if(data.isMyself){messages=["Thanks for chatting, #{other_username} would have really appreciated a photo of you \u2013 after all would you want to date someone with no photo?","Want better chats moving forward? #{other_username} suggests you upload a photo. Not only will photos show off your \u2018assets’, you'll have better chats next time!","Moving on from #{other_username} eh? No sweat but you should still upload your photo so people don't end dates with you. Don't hide your #{own_handsome} face!","Want 11X more chats? Well you gotta upload a photo! Don't miss out on meeting the one meant for you!","Before your next chat \u2013 we wanted to remind you that someone as #{own_handsome} as you should upload a photo. After all you'll get 11X more chats.","Like most #{other_gender_pl}, #{other_username} likes to SpeedDate&#0153 #{own_gender_pl} with photos. You're a #{own_good_looking} #{own_gender_sg}. Let's make sure you show people."];}else{messages=["Oops! #{other_username} ended the SpeedDate&#0153 because you haven’t <a #{link}>uploaded your photo</a>. Would you want to date someone with no photo?","#{other_username} likes to chat with #{own_gender_pl} <a #{link}>with photos</a>, odd creature that #{other_pronoun} is. Don't miss another opportunity.","#{other_username} left the SpeedDate&#0153 because #{other_pronoun} couldn’t see <a #{link}>your #{own_handsome} face</a>. Keep this up and you may miss your perfect match.","#{other_username} ended the SpeedDate&#0153. Like I said before, you’ll have better luck if you <a #{link}>upload a photo</a>.","#{other_gender_pl_cap} like #{other_username} like pictures. <a #{link}>Upload a great photo</a>, and you'll improve your attraction skills.","Like most #{other_gender_pl}, #{other_username} likes to SpeedDate&#0153 #{own_gender_pl} <a #{link}>with photos</a>. You're a good looking #{own_gender_sg}. Let's make sure you show people."];}
return getRandomInterpolatedElement(messages,data);};var generateRandomSubscriptionMessage=function(data){var messages;if(data.isMyself){if(SD.ViralPoints.isEnabled()){messages=["Thanks for SpeedDating with #{other_username}. <b>You have messages waiting!</b> Earn coins for free or subscribe to check them out!","<b>Someone has viewed your profile</b>\u2026aren't you curious to know who it is and how many times they've check you out? Subscribe and find out!","Gosh \u2013 Your SpeedDate&#0153 ended so quick. <b>Get unlimited time to chat</b> and pick your own SpeedDates by earning coins for free or subscribing today.","#{own_dude} \u2013 You're really missing out on everything that SpeedDate&#0153 has to offer you. Earn coins for free or subscribe today and join the party with 10+ million other members.","We don't mind picking your SpeedDates, we just think you'd do an even better job picking #{other_gender_pl} yourself! Earn coins for free or subscribe today \u2013 pick your own #{other_gender_pl}","You're ready to graduate and become a SpeedDate&#0153 Subscriber for free. Pick your own dates, talk for as long as you want, see who's viewed you, reply to all messages and more. Let\u2019s go big #{own_boy}!"];}else{messages=["Thanks for speed dating with #{other_username}. <b>You have messages waiting!</b> Subscribe to check them out!","<b>Someone has viewed your profile</b>\u2026aren't you curious to know who it is and how many times they've check you out? Subscribe and find out!","Gosh \u2013 Your SpeedDate&#0153 ended so quickly. <b>Consider subscribing to get unlimited time to chat</b> and pick your own SpeedDates.","#{own_dude} \u2013 Don't miss out out on everything SpeedDate&#0153 has to offer you. Subscribe to join the party with 11+ million other members.","We don't mind picking your SpeedDates, but you can pick your own #{other_gender_pl} too! Subscribe today to \u2013 pick your own #{other_gender_pl}","You're ready to graduate and become a SpeedDate&#0153 Subscriber. Pick your own dates, talk for as long as you want, see who's viewed you, reply to all messages and more. Let\u2019s go!"];}}else{if(SD.ViralPoints.isEnabled()){messages=["#{other_username} ended the SpeedDate&#0153 because #{other_pronoun} only dates Subscribers \u2013 #{other_pronoun}'s not elitist \u2013 just serious! Subscribe for FREE today to avoid this happening in the future.","Oh boy, #{other_username} prefers to date Subscribers because then #{other_pronoun} knows they're real \u2013 just like #{other_obj_pronoun}. Subscribe for FREE today to increase your opportunity to meet #{other_Mr} Right.","Uh oh\u2026 #{other_gender_sg} don't tend to end SpeedDates on subscribers! Earn a FREE subscription today to join the party.","#{other_gender_pl_cap} are more likely to stick around if you get a FREE subscription.","You'll increase your chances of completing SpeedDates if you earn a FREE subscription.  Join the club and get more dates today!"];}else{messages=["#{other_username} ended the SpeedDate&#0153 because #{other_pronoun} thinks subscribers are more serious.  Consider subscribing today to avoid this in the future.","Oh boy, #{other_username} prefers to date Subscribers because then #{other_pronoun} knows they're real. Subscribe today to increase your opportunity to meet #{other_Mr} Right.","Uh oh\u2026 #{other_gender_pl_cap} don't tend to end SpeedDates on subscribers! Try it out!","#{other_gender_pl_cap} are more likely to stick around if you subscribe because you're showing you really want to meet someone","You'll increase your chances of completing SpeedDates if you subscribe.  Join the club and get more dates today!"];}}
return getRandomInterpolatedElement(messages,data);};var getRandomInterpolatedElement=function(messages,interpolationData){var randomNumber=Math.floor(Math.random()*(messages.length));return("#{own_username},<br/><br/>"+messages[randomNumber]).interpolate(interpolationData);};var prepareUsingActions=function(){var template;var extraStyleValue='';var extraStylePopupValue='';var dateData;var nextAction=SD.Flows.preActionFlow.getNext({sourceMemberId:options.data.uid,sourceDialog:SD.Dialogs.Types.DATE,fromEndDate:true});if(nextAction){if(options.data.isMyself){template=dialog.templateSet.callToAction_for_the_ender;}else{template=dialog.templateSet.callToAction
extraStylePopupValue='style="height:230px"';}
dateData=constructDateData(options.data.uid);switch(nextAction.sig){case'uploadPhotoDialog':if(options.data.isMyself){options.data.dateLeftTriggerLabel='Upload your photo';}else{options.data.dateLeftTriggerLabel='Upload a Photo';}
options.data.dateLeftTriggerReason=generateRandomNoPhotoMessage(dateData);break;case'aboutMeDialog':if(options.data.isMyself){options.data.dateLeftTriggerLabel='Complete your profile';}else{options.data.dateLeftTriggerLabel='Continue filling out your profile';}
options.data.dateLeftTriggerReason=generateRandomMoreProfileMessage(dateData);break;case'speedVerifyDialog':options.data.dateLeftTriggerLabel='SpeedVerify&#0153;  your profile';options.data.dateLeftTriggerReason=generateRandomSpeedVerifyMessage(dateData);break;case'emailVerificationDialog':options.data.dateLeftTriggerLabel='Verify Your Email';options.data.dateLeftTriggerReason=generateRandomVerifyMailMessage(dateData);break;default:template=dialog.templateSet.advanced;}}else{dateData=constructDateData(options.data.uid);if(SD.ViralPoints.isEnabled()){options.data.dateLeftTriggerLabel='Continue';}else{options.data.dateLeftTriggerLabel='Subscribe Now';}
template=dialog.templateSet.advanced_3174;extraStylePopupValue='style="height:220px"';options.data.dateLeftTriggerReason=generateRandomSubscriptionMessage(dateData);}
return{template:template,extraStyleValue:extraStyleValue,extraStylePopupValue:extraStylePopupValue};};return prepareUsingActions();}};SD.UI.Dating.PostDateContactDialog=Class.create(SD.UI.Dating.PostDateDialog,{initialize:function($super,options){this.initTemplate=typeof this.initTemplate==='function'?this.initTemplate():this.initTemplate;var result=SD.UI.Dating.EndDateFilter.filter(this,options);var user=SD.User.get(options.data.uid);options.initTemplate=this.initTemplate.interpolate({uid:user.uid,username:user.name,thumb_pic:user.images[0].image_url,content:(typeof result.template=='string')?result.template:result.template(),extraStyle:result.extraStyleValue,extraStylePopup:result.extraStylePopupValue});$super(options);}});SD.UI.Dating.PreDateDialog=Class.create(SD.UI.Dating.PostDateDialog,{templateSet:SD.UI.Dating.PreDateDialogTemplates,initTemplate:SD.UI.Dating.PreDateDialogTemplates.frame,setClock:function(data){this.container.getClock().set(data);}});SD.UI.Dating.ReportAbuseDialog=Class.create(SD.UI.Dating.Component,{templateSet:SD.UI.Dating.ReportAbuseTemplates,initTemplate:SD.UI.Dating.ReportAbuseTemplates.frame,setup:function(){this.dom.onclick=this.domCloseHandle.onclick=this.hide.bind(this);this.setupForm();this.hide();},onItemClick:function(input){input.checked=true;this.submitForm();this.domForm.reset();},setupForm:function(){var inputs=this.dom.getElementsByTagName('input');var input;for(var i=0,len=inputs.length;i<len;i++){input=inputs[i];input.parentNode.onclick=this.onItemClick.bind(this,input);}},submitForm:function(){SD.Event.fire(this,SD.UI.Dating.ReportAbuseDialog.Events.ABUSE_REPORT,{panelId:this.container.id,data:this.domForm.serialize(true)});},show:function(){this.dom.style.visibility="";},hide:function(){this.dom.style.visibility="hidden";},close:function(){this.dom&&this.dom.parentNode&&this.dom.remove();this.onClose();},parseLibrary:{'lib-report-dom':function(el,domRoot){this.dom=el;},'lib-data-form':function(el,domRoot){this.domForm=el;},'lib-close-dialog':function(el,domRoot){this.domCloseHandle=el;}}});SD.UI.Dating.ReportAbuseDialog.Events={ABUSE_REPORT:"SD.UI.Dating.ReportAbuseDialog.Events:ABUSE_REPORT"};SD.UI.Dating.EndDateDialog=Class.create(SD.UI.Dating.Component,{templateSet:SD.UI.Dating.EndDateTemplates,initTemplate:SD.UI.Dating.EndDateTemplates.frame,setup:function(){this.setupTextarea();this.setupASL();this.curDataSectionDom=null;this.originalHeight=parseInt(this.domInnerHolder.getStyle('height'));this.domTitle.onclick=this.domCloseHandle.onclick=this.hide.bind(this);this.domButBack.onclick=this.domTitle.onclick;this.domShim.onclick=this.domTitle.onclick;this.domButEndAndFind.onclick=function(){this.submitForm();if(SD.Model.getMyself().is_premium){SD.Event.fire(this,SD.UI.Dating.EndDateDialog.Events.FIND_DATE,{panelId:this.container.id});}
this.hide();}.bind(this);this.domButEndAndPause.onclick=function(){this.submitForm();SD.Event.fire(this,SD.UI.Dating.EndDateDialog.Events.PAUSE_DATING,{panelId:this.container.id});this.hide();}.bind(this);this.setupForm();this.hide();},setupASL:function(){var minAgeDom=this.domForm.elements.min_age;var maxAgeDom=this.domForm.elements.max_age;for(var i=18;i<100;i++){minAgeDom.options.add(new Option(i,i));maxAgeDom.options.add(new Option(i,i));}
if(this.data.min_age){minAgeDom.value=this.data.min_age;}
if(this.data.max_age){maxAgeDom.value=this.data.max_age;}
var locationData={'20':'20 miles','50':'50 miles','100':'100 miles','200':'200 miles','500':'500 miles','MC':'United States','WW':'Worldwide'};var locationDom=this.domForm.elements.location;for(var i in locationData){locationDom.options.add(new Option(locationData[i],i));}
if(this.data.location){locationDom.value=this.data.location;}
minAgeDom.onchange=function(){if(parseInt(this.value)>parseInt(maxAgeDom.value)){maxAgeDom.value=this.value;}};maxAgeDom.onchange=function(){if(parseInt(this.value)<parseInt(minAgeDom.value)){minAgeDom.value=this.value;}};},setupTextarea:function(){var _this=this;this.emptyTextareaText=this.domTextarea.value;this.domTextarea.sdIsEmpty=true;this.domTextarea.onfocus=function(){if(this.sdIsEmpty||this.value==_this.emptyTextareaText){this.value='';}};this.domTextarea.onchange=this.domTextarea.onblur=function(){if(this.value==''){this.sdIsEmpty=true;this.value=_this.emptyTextareaText;}else{this.sdIsEmpty=false;}};},setupForm:function(){var _this=this;this.dom.select(".data").each(function(el){el.onclick=function(e){var inputs=this.getElementsByTagName('input');(inputs.length>0)&&(inputs[0].checked=true);if(_this.curDataSectionDom){_this.curDataSectionDom.style.display='none';_this.domInnerHolder.style.height=_this.originalHeight+'px';}
var nextSibling=this.next();if(nextSibling&&nextSibling.className=='data-section'){_this.curDataSectionDom=nextSibling;_this.curDataSectionDom.style.display='block';_this.domInnerHolder.style.height=(_this.originalHeight+_this.curDataSectionDom.offsetHeight)+'px';}};}.bind(this));},submitForm:function(){if(this.domTextarea.value==this.emptyTextareaText){this.domTextarea.value='';}
var data=this.domForm.serialize(true);if(SD.Date._currentDate&&SD.Date._currentDate.panelId==this.container.id){SD.Date.submitDateEndedReason({otherMemberId:SD.Date._currentDate.user.uid,reasonCode:data.reason,otherText:data.other});}
SD.Event.fire(this,SD.UI.Dating.EndDateDialog.Events.END_DATE,{panelId:this.container.id,data:data});},show:function(){this.dom.style.visibility="";},hide:function(){this.dom.style.visibility="hidden";},close:function(){this.dom&&this.dom.parentNode&&this.dom.remove();this.onClose();},parseLibrary:{'lib-end-date-dom':function(el,domRoot){this.dom=el;},'lib-end-date-shim':function(el,domRoot){this.domShim=el;},'lib-end-date-holder':function(el,domRoot){this.domInnerHolder=el;},'lib-end-date-content':function(el,domRoot){this.domContent=el;},'lib-end-date-title':function(el,domRoot){this.domTitle=el;},'lib-data-form':function(el,domRoot){this.domForm=el;},'lib-but-back':function(el,domRoot){this.domButBack=el;},'lib-but-end-and-find':function(el,domRoot){this.domButEndAndFind=el;},'lib-but-end-and-pause':function(el,domRoot){this.domButEndAndPause=el;},'lib-textarea':function(el,domRoot){this.domTextarea=el;},'lib-close-dialog':function(el,domRoot){this.domCloseHandle=el;}}});SD.UI.Dating.EndDateDialog.Events={END_DATE:"SD.UI.Dating.EndDateDialog.Events:END_DATE",PAUSE_DATING:"SD.UI.Dating.EndDateDialog.Events:PAUSE_DATING",FIND_DATE:"SD.UI.Dating.EndDateDialog.Events:FIND_DATE"};SD.UI.Dating.DateHeader=Class.create(SD.UI.Dating.Component,{templateSet:SD.UI.Dating.DateHeaderTemplates,initTemplate:SD.UI.Dating.DateHeaderTemplates.frame,setup:function(){},dataFilter:function(data){data.name=data.name.truncate(SD.UI.Dating.DateHeader.MAX_NAME_LENGTH);return data;},setupReportAbuse:function(domReport){var panelId=this.options.container.id;this.domReport=domReport;domReport.onclick=function(){if(domReport.hasClassName('date-ui-button-disabled')){var secondsLeft=Math.ceil((20000-SD.Date.getTimeAfterUIConstruct())/1000);SD.Tooltip.show('To give everyone a fair chance to make a good impression, please wait for <b>'+secondsLeft+'</b> seconds before reporting your match.');return;}
SD.Event.fire(this,SD.UI.Dating.DateHeader.Events.OPEN_ABUSE_REPORT,{panelId:panelId});}.bind(this);domReport.onmouseout=function(){SD.Tooltip.hide();};},setupEndDate:function(domEndDate){this.domEndDate=domEndDate;var panelId=this.options.container.id;domEndDate.onclick=function(){if(domEndDate.hasClassName('date-ui-button-disabled')){var secondsLeft=Math.ceil((20000-SD.Date.getTimeAfterUIConstruct())/1000);SD.Tooltip.show('To give everyone a fair chance to make a good impression, please chat for <b>'+secondsLeft+'</b> seconds before ending the date.');return;}
SD.Event.fire(this,SD.UI.Dating.DateHeader.Events.OPEN_END_DATE,{panelId:panelId});}.bind(this);domEndDate.onmouseout=function(){SD.Tooltip.hide();};},setupTerminateDate:function(domEndDate){this.domEndDate=domEndDate;var panelId=this.options.container.id;domEndDate.onclick=function(){SD.Event.fire(this,SD.UI.Dating.Panel.Events.PANEL_CLOSE_REQUEST,{panelId:panelId});}.bind(this);},setupBlock:function(domBlock){domBlock.setAttribute('sdUserName',this.options.data.name);domBlock.setAttribute('sdUid',this.options.data.uid);},setupBtnFavorite:function(domBtnFavorite){if(!this.container.options.data.meta.user.relation.isFavorite){domBtnFavorite.setAttribute('sdType','favorite');domBtnFavorite.setAttribute('sdUid',this.container.options.data.meta.user.uid);}else{domBtnFavorite.addClassName(domBtnFavorite.getAttribute('sdClassOnFavorite')?domBtnFavorite.getAttribute('sdClassOnFavorite'):'added-favorite');}
this.domBtnFavorite=domBtnFavorite;},showEndDate:function(){this.domEndDate.removeClassName('date-ui-button-disabled');},hideReport:function(){this.domReport.addClassName('date-ui-button-disabled');},showReport:function(){this.domReport.removeClassName('date-ui-button-disabled');},parseLibrary:{'lib-but-end-date':function(el,domRoot){this.setupTerminateDate(el);},'lib-but-report-abuse':function(el,domRoot){this.setupReportAbuse(el);},'lib-block':function(el,domRoot){this.setupBlock(el);},'lib-but-favorite':function(el,domRoot){this.setupBtnFavorite(el)}}});SD.UI.Dating.DateHeader.Events={OPEN_ABUSE_REPORT:'SD.UI.Dating.DateHeader.Events:OPEN_ABUSE_REPORT',OPEN_END_DATE:'SD.UI.Dating.DateHeader.Events:OPEN_END_DATE',BLOCK:'SD.UI.Dating.DateHeader.Events:BLOCK',REPORT_REQUESTED:'SD.UI.Dating.DateHeader.Events:REPORT_REQUESTED'};SD.UI.Dating.DateHeader.MAX_NAME_LENGTH=30;SD.UI.Dating.ChatHeader=Class.create(SD.UI.Dating.Component,{templateSet:SD.UI.Dating.ChatHeaderTemplates,initTemplate:SD.UI.Dating.ChatHeaderTemplates.frame,setup:function(){},dataFilter:function(data){data.name=data.name.truncate(SD.UI.Dating.DateHeader.MAX_NAME_LENGTH);return data;},setupReportAbuse:function(domReport){var panelId=this.options.container.id;domReport.onclick=function(){SD.Event.fire(this,SD.UI.Dating.DateHeader.Events.REPORT_REQUESTED,{panelId:panelId});}.bind(this);},setupReportAbuse2:SD.UI.Dating.DateHeader.prototype.setupReportAbuse,setupEndChat:function(domEndChat){var panelId=this.options.container.id;domEndChat.onclick=function(){SD.Event.fire(this,SD.UI.Dating.Panel.Events.PANEL_CLOSE_REQUEST,{panelId:panelId});}.bind(this);},setupBlock:function(domBlock){domBlock.setAttribute('sdUserName',this.options.data.name);domBlock.setAttribute('sdUid',this.options.data.uid);},setupBtnFavorite:function(domBtnFavorite){if(!this.container.options.data.meta.user.relation.isFavorite){domBtnFavorite.setAttribute('sdType','favorite');domBtnFavorite.setAttribute('sdUid',this.container.options.data.meta.user.uid);}else{domBtnFavorite.addClassName(domBtnFavorite.getAttribute('sdClassOnFavorite')?domBtnFavorite.getAttribute('sdClassOnFavorite'):'added-favorite');}
this.domBtnFavorite=domBtnFavorite;},parseLibrary:{'lib-but-end-chat':function(el,domRoot){this.setupEndChat(el);},'lib-but-chat-report-abuse':function(el,domRoot){this.setupReportAbuse(el);},'lib-but-report-abuse':function(el,domRoot){this.setupReportAbuse2(el);},'lib-block':function(el,domRoot){this.setupBlock(el);},'lib-but-favorite':function(el,domRoot){this.setupBtnFavorite(el);}}});SD.UI.Dating.DateHeader.MAX_NAME_LENGTH=30;SD.UI.Dating.DateToolbar=Class.create(SD.UI.Dating.Component,{templateSet:SD.UI.Dating.DateToolbarTemplates,initTemplate:SD.UI.Dating.DateToolbarTemplates.frame,setup:function(){},setupWebcam:function(domButWebcam){this.domButWebcam=domButWebcam;},setupIceBreaker:function(domButIceBreaker){this.domButIceBreaker=domButIceBreaker;domButIceBreaker.onclick=function(){var message=SD.UI.Dating.DateToolbar.IceBreakers[Math.floor(Math.random()*SD.UI.Dating.DateToolbar.IceBreakers.length)];SD.Event.fire(this,SD.UI.Dating.DateToolbar.Events.ICE_BREAKER,{panelId:this.container.id,message:message});}.bind(this);},setupCountdownClock:function(domCountdownClock){this.container.registerClock(new SD.UI.CountdownClock(domCountdownClock));},setupExtendDate:function(domExtendDate){domExtendDate.onclick=function(){SD.Event.fire(this,SD.UI.Dating.DateToolbar.Events.EXTEND_DATE,{panelId:this.container.id});}.bind(this);this.domExtendDate=domExtendDate;if(!this.data.showExtendDateButton){domExtendDate.hide();}
if(!this.data.isPremium){domExtendDate.setAttribute("sdMessage","Only Subscribers Can Extend Dates");}},hideExtendDate:function(){this.domExtendDate.hide();},showExtendDate:function(){this.domExtendDate.show();},setWebcamButText:function(text){this.domButWebcam&&(this.domButWebcam.firstChild.data=text);},parseLibrary:{'lib-but-webcam':function(el,domRoot){this.setupWebcam(el);},'lib-but-icebraker':function(el,domRoot){this.setupIceBreaker(el);},'lib-but-extend-date':function(el,domRoot){this.setupExtendDate(el);},'lib-countdown-clock':function(el,domRoot){this.setupCountdownClock(el);}}});SD.UI.Dating.DateToolbar.IceBreakers=["What do you like to do for fun?","What kind of music do you like?","If you could live anywhere, where would it be?","What is the best thing that happened to you this week?","Tell me about your craziest vacation.","What is your most embarrassing moment?","If you were to cook me a meal, what would it be?","What is your favorite food to eat?","What do you like to read?","What was your best birthday present?","What do you do to relax?","Do you like long walks on the beach or wild parties?","What's your least favorite thing to do?","What is your favorite holiday?","Have you ever done an adventure sport?","What is your favorite website, besides SpeedDate?","What is your idea of a great first date?","What is your favorite ice cream flavor?","What is your favorite movie?","What is your best childhood memory?","What do you like best about your job?","What is your dream vacation?","Do you follow politics?","Do you have any pets?","What would you do with a million dollars?","Do you have siblings?","If you were an animal, what kind would you be?","If you could meet anyone, who would it be?","What are your worst fears?","If you can have any super power, what would it be?","Which is worse? Being in a place that is too loud or too quiet?","What do you think of SpeedDate?"];SD.UI.Dating.DateToolbar.Events={ICE_BREAKER:'SD.UI.Dating.DateToolbar.Events:ICE_BREAKER',EXTEND_DATE:'SD.UI.Dating.DateToolbar.Events:EXTEND_DATE'};SD.UI.Dating.ChatToolbar=Class.create(SD.UI.Dating.DateToolbar,{templateSet:SD.UI.Dating.ChatToolbarTemplates,initTemplate:SD.UI.Dating.ChatToolbarTemplates.frame,setupCountdownClock:function(domCountdownClock){this.container.registerClock(new SD.UI.CountdownClock(domCountdownClock));},setupIceBreaker:function(domButIceBreaker){this.domButIceBreaker=domButIceBreaker;domButIceBreaker.onclick=function(){SD.Event.fire(this,SD.UI.Dating.DateInputModule.Events.MESSAGE_SEND,{panelId:this.container.id,message:SD.UI.Dating.DateToolbar.IceBreakers[Math.floor(Math.random()*SD.UI.Dating.DateToolbar.IceBreakers.length)]});}.bind(this);},setupFBChatInvite:function(domButChatInvite){domButChatInvite.onclick=function(){SD.Event.fire(this,SD.UI.Dating.DateInputModule.Events.INVITE_FB_CHAT,{panelId:this.container.id});}.bind(this);},parseLibrary:{'lib-but-fb-invite':function(el,domRoot){this.setupFBChatInvite(el);},'lib-but-webcam':function(el,domRoot){this.setupWebcam(el);},'lib-but-icebraker':function(el,domRoot){this.setupIceBreaker(el);},'lib-but-extend-date':function(el,domRoot){this.setupExtendDate(el);},'lib-countdown-clock':function(el,domRoot){this.setupCountdownClock(el);}}});SD.UI.Dating.FBChatToolbar=Class.create(SD.UI.Dating.ChatToolbar,{initTemplate:SD.UI.Dating.ChatToolbarTemplates.frameFBChat});SD.UI.Dating.WebcamPane=Class.create(SD.UI.Dating.Component,{templateSet:SD.UI.Dating.WebcamPaneTemplates,initTemplate:SD.UI.Dating.WebcamPaneTemplates.frame,setup:function(){},setupWebcam:function(domWebcam){this.webcamInitialized=false;this.domWebcam=domWebcam;},startWebcam:function(onReady){this.webcamInitialized=true;this.domWebcamId=SD.Utils.IdGenerator.generate();this.domWebcam.id=this.domWebcamId;swfobject.embedSWF(SD.Config.flashDir+"videochat/VideoChatComponent.swf",this.domWebcam.id,"100%","100%","9.0.0","",{onReady:onReady},{allowFullScreen:"true",allowscriptaccess:"always",wmode:"transparent"});this.domWebcam=$(this.domWebcamId);this.domWebcam.style.visibility='';this.bindToPane();},bindToPane:function(){this.paneHolder.onresize=function(){var paneHeight=this.domHolder.offsetHeight;var paneWidth=this.domHolder.offsetWidth;this.domWebcam.style.height=paneHeight+'px';this.domWebcam.style.width=paneWidth+'px';}.bind(this);},parseLibrary:{'lib-webcam-others':function(el,domRoot){el&&this.setupWebcam(el);}},show:function(onReady){if(!this.paneHolder.isVisible){this.paneHolder.parentPane.showPane(this.paneHolder.nextPane);this.paneHolder.parentPane.showPane(this.paneHolder);if(!this.webcamInitialized){this.startWebcam(onReady);}
SD.Event.fire(this.container,SD.UI.Dating.WebcamPane.Events.WEBCAM_OPEN,{panelId:this.container.id});}},hide:function(){if(this.paneHolder.isVisible){this.paneHolder.parentPane.hidePane(this.paneHolder);this.paneHolder.parentPane.hidePane(this.paneHolder.nextPane);SD.Event.fire(this,SD.UI.Dating.WebcamPane.Events.WEBCAM_CLOSE,{panelId:this.container.id});}},toggle:function(){this.paneHolder.isVisible?this.hide():this.show();},isVisible:function(){return this.paneHolder.isVisible;},adoptWebcam:function(domWebcam){this.webcamInitialized=true;this.domWebcam=domWebcam;this.domWebcamId=domWebcam.id;this.domHolder.update();this.domHolder.appendChild(domWebcam);this.bindToPane();}});SD.UI.Dating.WebcamPane.Events={WEBCAM_OPEN:'SD.UI.Dating.WebcamPane.Events:WEBCAM_OPEN',WEBCAM_CLOSE:'SD.UI.Dating.WebcamPane.Events:WEBCAM_CLOSE'};SD.UI.Dating.DateProfile=Class.create(SD.UI.Dating.Component,{setup:function(){},parseLibrary:{}});SD.UI.Dating.DateProfileV1=Class.create(SD.UI.Dating.Component,{initialize:function($super,options){this.currentImg=0;this.imgUrls=[];$super(options);},setup:function(){this.selectImg(0);},selectImg:function(imgId){if(!this.imgUrls[imgId]){return;}
this.domBigPhoto.src=this.imgUrls[imgId];this.currentImg=imgId;this.domImageProgress.innerHTML=(imgId+1)+" of "+this.imgUrls.length;this.updateNavigation();},updateNavigation:function(){if(Prototype.Browser.IE6||this.imgUrls.length<2){this.domNavigate.hide();return;}},nextImage:function(){this.selectImg((this.currentImg+1)%this.imgUrls.length);},prevImage:function(){this.selectImg((this.imgUrls.length+this.currentImg-1)%this.imgUrls.length);},parseLibrary:{'lib-big-photo':function(el,domRoot){this.domBigPhoto=el;this.domBigPhoto.onclick=this.nextImage.bind(this);},'lib-image-container':function(el,domRoot){el.onmouseover=function(){if(!Prototype.Browser.IE6&&this.imgUrls.length>1){this.domNavigate.show();}}.bind(this);el.onmouseout=function(){}.bind(this)},'lib-navigate-prev':function(el,domRoot){el.onclick=this.prevImage.bind(this);},'lib-navigate-next':function(el,domRoot){el.onclick=this.nextImage.bind(this);},'lib-navigate':function(el,domRoot){this.domNavigate=el;},'lib-all-images':function(el,domRoot){this.domAllImagesContainer=el;var data=el.innerHTML;this.imgUrls=data.evalJSON();},'lib-image-progress':function(el,domRoot){this.domImageProgress=el;}}});SD.UI.Dating.DateProfileV2=Class.create(SD.UI.Dating.Component,{setup:function(){},parseLibrary:{}});SD.UI.Dating.DateProfileV3=Class.create(SD.UI.Dating.Component,{_other:null,initialize:function($super,options){this.tabButtons=[];$super(options);},setup:function(){},largePhotoRenderer:function(dom,user){dom.innerHTML="";if(user.images.length==0){return}
user.images.each(function(img){var photo=new Image();photo.onload=this.pRenderer.bind(this,dom,photo);if(img.image_url_extralarge){photo.src=img.image_url_extralarge;}else{photo.src=img.image_url_large;}
return photo;},this);},pRenderer:function(dom,img){var maxWidth=parseInt($(dom).getStyle("width"))-10;img.width=Math.min(img.width,maxWidth);img.onload=null;img.style.margin='5px';if(dom.getAttribute('sdIsLoaded')=='loading'){dom.setAttribute('sdIsLoaded','true');dom.innerHTML="";}
dom.appendChild(img);},fakeClick:function(selector){var elements=$$(selector);if(elements.length){this.activateTabMenu(elements[0]);}},activateTabMenu:function(el){var targetName=el.getAttribute('sdTabTarget');var targets=this.domTabsContainer.select("[sdTabLabel="+targetName+"]");if(!targets.length){return;}
var target=targets[0];var tabContents=this.domTabsContainer.childElements();var photoContainer=this.photoContainer;tabContents.each(function(tabContent){if(tabContent!=photoContainer&&tabContent!=target){tabContent.hide();}});if(el.getAttribute('sdTabType')=='photo'||el.getAttribute('sdTabType')=='conversation'||el.getAttribute('sdTabType')=='chat-observers'){this.photoContainer.hide();}else{this.photoContainer.show();}
target.show();this.tabButtons.each(function(tabButton){if(tabButton==el){tabButton.addClassName("e3083-v3-selected-tab-item");}else{tabButton.removeClassName("e3083-v3-selected-tab-item");}});if(el.getAttribute('sdTabType')=='photo'&&target.getAttribute('sdIsLoaded')=='false'){this.largePhotoRenderer(target,SD.User.get(el.getAttribute('sdUid')));target.setAttribute('sdIsLoaded','loading');}else if(el.getAttribute('sdTabType')=='conversation'){if(target.getAttribute('sdIsLoaded')=='false'){var url=SD.NavUtils.link('messages','inline_thread',{id:el.getAttribute('sdUid')});new SD.Utils.Loader({domContent:target}).load(url);target.setAttribute('sdIsLoaded','true');}}else if(el.getAttribute('sdTabType')=="chat-observers"){this._other=SD.User.get(el.getAttribute('sdUid'));if(target.getAttribute('sdIsLoaded')=='false'){this.observerList=new SD.UI.ChatObserverList({domHolder:target,other:this._other,onSelect:this.container.chatObserverModule.onFriendSelect.bind(this.container.chatObserverModule)});SD.Event.observe(null,SD.FbWingman.Events.STOP_OBSERVING,this._onStopObserving.bind(this));target.setAttribute('sdIsLoaded','true');SD.ExperimentManager.recordOutput('UserOpenedViewersList',1,1);}}},destroy:function(){SD.Event.stopObserving(null,SD.FbWingman.Events.STOP_OBSERVING,this._onStopObserving);},_onStopObserving:function(e){if(e.memo.user.uid==this._other.uid){this.observerList.unselectAll();}},setupThumb:function(el){el.onclick=function(){this.domImageLarge.src=el.getAttribute('srcLarge');}.bind(this);},parseLibrary:{'lib-tab-button':function(el,domRoot){this.tabButtons.push(el);el.onclick=function(){this.activateTabMenu(el);}.bind(this);},'lib-tabs-container':function(el,domRoot){this.domTabsContainer=el;},'lib-photo-container':function(el,domRoot){this.photoContainer=el;},'lib-dating-image-large':function(el,domRoot){this.domImageLarge=el;},'lib-dating-image-thumb':function(el,domRoot){this.setupThumb(el);}}});SD.UI.Dating.DatePictureGallery=Class.create(SD.UI.Dating.Component,{setup:function(){},setupThumb:function(el){el.onclick=function(){this.domImageLarge.src=el.getAttribute('srcLarge');}.bind(this);},parseLibrary:{'lib-dating-image-large':function(el,domRoot){this.domImageLarge=el;},'lib-dating-image-thumb':function(el,domRoot){this.setupThumb(el);}}});SD.UI.Dating.DateInputModule=Class.create(SD.UI.Dating.Component,{templateSet:SD.UI.Dating.DateInputModuleTemplates,initTemplate:SD.UI.Dating.DateInputModuleTemplates.frame,setup:function(){},setupInput:function(domInput){domInput=$(domInput);var _this=this;this.input={isFocused:false,oldValue:'',domInput:domInput,onBlur:function(){this.isFocused=false;},onFocus:function(){this.isFocused=true;},focus:function(){try{this.domInput.focus();}catch(e){}},blur:function(){try{this.domInput.blur();}catch(e){}},getValue:function(){return this.domInput.value;},setValue:function(value){this.oldValue=this.domInput.value;this.domInput.value=value;},setActive:function(){this.focus();}};domInput.onblur=this.input.onBlur.bind(this.input);domInput.onfocus=this.input.onFocus.bind(this.input);domInput.onkeypress=function(e){e=e||window.event;if(e.keyCode==13&&!e.shiftKey){_this.sendMessage();(function(){this.value=''}).bind(this).defer();Event.stop(e);}};domInput.onkeydown=function(e){var inputCharLength=domInput.value.length;e=e||window.event;var keyCode=e.keyCode;setTimeout(function(){var newInputCharLength=domInput.value.length;if(newInputCharLength!=inputCharLength){_this.sendInput(keyCode);}},1);};var adjustSizes=function(){if(!domInput.parentNode)return;var width=domInput.parentNode.offsetWidth-75;(width>0)&&domInput.setWidth(width);};this.paneHolder.onresize=SD.Utils.connect(this.paneHolder.onresize,adjustSizes);adjustSizes();},isFocused:function(){return this.input.isFocused;},setupSender:function(domSender){var _this=this;this.sender={send:function(){SD.Event.fire(_this,SD.UI.Dating.DateInputModule.Events.MESSAGE_SEND,{panelId:_this.container.id,message:_this.input.getValue()});}};$(domSender).onclick=function(e){_this.sendMessage();_this.input.focus();};},sendMessage:function(){if(this.input.getValue()){this.sender.send();this.input.setValue('');}},sendInput:function(keyCode){SD.Event.fire(this,SD.UI.Dating.DateInputModule.Events.INPUT_RECEIVED,{panelId:this.container.id,key:keyCode,message:this.input.domInput.value});},parseLibrary:{'lib-chat-input':function(el,domRoot){this.setupInput(el);},'lib-chat-sender':function(el,domRoot){this.setupSender(el);}}});SD.UI.Dating.DateInputModule.Events={MESSAGE_SEND:"SD.UI.Dating.DateInputModule.Events:MESSAGE_SEND",INVITE_FB_CHAT:"SD.UI.Dating.DateInputModule.Events:INVITE_FB_CHAT",INPUT_RECEIVED:"SD.UI.Dating.DateInputModule.Events:INPUT_RECEIVED"}
SD.UI.Dating.MessagePane=Class.create(SD.UI.Dating.Component,{templateSet:SD.UI.Dating.MessagePaneTemplates,initTemplate:SD.UI.Dating.MessagePaneTemplates.pane,setup:function(){this.domHolder.style.overflowY="auto";this.messageHistory=[];VL_Pane.panes[this.domHolder.id].onresize=this.adjustMessageHeight.bind(this);},setActive:function(){this.adjustMessagePane();this.onActivate(this);},setInactive:function(){if(!this.dom)return;this.onInactivate(this);},deleteLastChild:function(){var children=this.dom.select('.message');if(children.length>0){var lastChild=children[children.length-1];lastChild.parentNode&&lastChild.parentNode.removeChild(lastChild);}},messageFilter:function(message){return SD.Smileys.convert(message);},putMessage:function(data){if(typeof data=='object'){data=Object.clone(data);data.template=data.template||'chatMessage';if(data.template=='chatMessage'){this.messageHistory.push(data);}
if(this.staticMessageData){this.deleteLastChild();}
if(data.mode=='staticMessage'){this.staticMessageData=data;}
if(data.mode=='replace'){var children=this.dom.select('.message');if(children.length>0){this.deleteLastChild();}}
if(data.mode!='staticMessage'){if(data.message){data.message=this.messageFilter(data.message);}
this.populator.append({domRoot:this.domMessageHolder,template:this.templates[data.template],data:data});}
if(this.staticMessageData){this.populator.append({domRoot:this.domMessageHolder,template:this.templates[this.staticMessageData.template],data:this.staticMessageData});}}else if(typeof data=='string'){this.domMessageHolder.insert(data);}else if(typeof data=='function'){this.domMessageHolder.insert(data());}
this.adjustMessagePane();},clearStaticMessage:function(){if(this.staticMessageData){this.deleteLastChild();this.staticMessageData=null;}
this.adjustMessagePane();},adjustMessagePane:function(top,left){this.adjustMessageHeight();this.adjustScroll();},adjustScroll:function(top,left){this.domHolder.scrollTop=(top!==undefined)?top:(this.domHolder.scrollHeight+100);this.domHolder.scrollLeft=(left!==undefined)?left:0;},adjustMessageHeight:function(){var dmInnerHeight=this.domMessageHolder.offsetHeight-parseInt(this.domMessageHolder.style.paddingTop);this.domMessageHolder.style.paddingTop=Math.max(this.domHolder.offsetHeight-dmInnerHeight,0)+'px';},putStaticHTML:function(dom,place){var insertionObject={};insertionObject[place]=dom;this.domMessageHolder.insert(insertionObject);this.adjustMessagePane();},close:function(){this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom);this.dom=null;this.onClose(this);},parseLibrary:{'lib-message-pane':function(el,domRoot){this.dom=el;},'lib-pane-message-holder':function(el,domRoot){this.domMessageHolder=el;}}});SD.UI.Dating.ChatObserverModule=Class.create(SD.UI.Dating.Component,{templateSet:SD.UI.Dating.ChatObserverModuleTemplates,initTemplate:SD.UI.Dating.ChatObserverModuleTemplates.frame(),setup:function(){},onFriendSelect:function(data){var responses=SD.Event.fire(null,SD.UI.Dating.ChatObserverModule.Events.SELECT_FRIEND_AS_OBSERVER,{friend:data.friend,panelId:this.container.id});var allow=true;responses.each(function(res){if(res===false){allow=false;return;}});return allow;},removeObserver:function(){SD.Utils.Populator.populate({domRoot:this.contentHolder,template:SD.UI.Dating.ChatObserverModuleTemplates.unselected,data:{}});},setObserver:function(friend){SD.Utils.Populator.populate({domRoot:this.contentHolder,template:SD.UI.Dating.ChatObserverModuleTemplates.selected,data:friend});SD.Utils.Parser.parse({domRoot:this.contentHolder,context:this,parseLibrary:{'lib-remove-chat-observer':function(el,domRoot){el.onclick=function(e){SD.Event.fire(null,SD.UI.Dating.ChatObserverModule.Events.REMOVE_FRIEND_FROM_OBSERVING,{panelId:this.container.id});}.bind(this)}}});},close:function(){SD.Event.stopObserving(null,SD.FbWingman.Events.STOP_OBSERVING,this._onStopObserving);SD.Event.stopObserving(null,SD.FbWingman.Events.START_OBSERVING,this._onStartObserving);this.dom&&this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom);this.dom=null;this.onClose(this);},parseLibrary:{'lib-content-holder':function(el,domRoot){this.contentHolder=el;},'lib-open-chat-observer-list':function(el,domRoot){el.onclick=function(){if(!SD.FBXMPP.isLoggedIn()){SD.FBXMPP.connect();}
this.container.dateProfile.fakeClick("[sdTabTarget='chat-observers']");}.bind(this);}}});SD.UI.Dating.ChatObserverModule.Events={SELECT_FRIEND_AS_OBSERVER:"SD.UI.Dating.ChatObserverModule.Events:SELECT_FRIEND_AS_OBSERVER",REMOVE_FRIEND_FROM_OBSERVING:"SD.UI.Dating.ChatObserverModule.Events:REMOVE_FRIEND_FROM_OBSERVING"};SD.UI.Dating.PanelToggler={show:function(dom){dom&&(dom.style.display='');},hide:function(dom){dom&&(dom.style.display='none');}};SD.UI.Dating.Panel=Class.create(SD.UI.Dating.Container,{initialize:function($super,options){options=options||{};this.toggler=options.toggler||SD.UI.Dating.PanelToggler;this.layoutConfig=options.layoutConfig||this.layoutConfig;this.isVisible=true;this.layout=this.buildLayout(options.domHolder);this.dom=$(this.layout.masterGrid.dom);this.onActivate=SD.Utils.connect(this.onActivate,function(){this.inputModule&&this.inputModule.input.setActive.bind(this.inputModule.input).defer();}.bind(this));$super(options);},setup:function($super){$super();this.hide();},addComponent:function(Constructor,dom,data,options){var component=new Constructor(Object.extend(options||{},{domHolder:dom,paneHolder:VL_Pane.panes[dom.id],container:this,data:data}));this.addItem(component);return component;},parseLibrary:{},show:function(){this.toggler.show(this.dom);this.isVisible=true;},hide:function(){this.toggler.hide(this.dom);this.isVisible=false;},close:function(){this.onBeforeClose();this.destroy();this.onClose();},onBeforeClose:function(){SD.Event.fire(this,SD.UI.Dating.Panel.Events.PANEL_BEFORE_CLOSED,{panelId:this.id});},onClose:function(){SD.Event.fire(this,SD.UI.Dating.Panel.Events.PANEL_CLOSED,{panelId:this.id});},layoutConfig:{},buildLayout:function(domRoot,layoutConfig){layoutConfig=layoutConfig||this.layoutConfig;layoutConfig.masterGrid.parentDom=domRoot;var layout=VL_layoutBuilder(layoutConfig);return layout;},destroy:function(){try{var parentNode=this.layout&&this.layout.masterGrid&&this.layout.masterGrid.dom.parentNode&&this.layout.masterGrid.dom.parentNode.removeChild(this.layout.masterGrid.dom);if(parentNode){parentNode.update();Element.GCScheduler.purge(parentNode);parentNode.parentNode&&parentNode.remove();}
try{this.getItems().invoke('close');}catch(e){}
this.removeAllItems();var destroyPaneIterator=function(pane){pane.dom=null;pane.parentDom=null;VL_Pane.panes[pane.id]=null;delete VL_Pane.panes[pane.id];}
var destroyPane=function(pane){VL_Pane.cascadeCall(pane,destroyPaneIterator);destroyPaneIterator(pane);}
this.layout.masterGrid&&destroyPane(this.layout.masterGrid);VL_Pane.panes[this.id]&&destroyPane(VL_Pane.panes[this.id]);this.dom=null;}catch(e){}}});SD.UI.Dating.Panel.Events={PANEL_CLOSED:'SD.UI.Dating.Panel.Events:PANEL_CLOSED',PANEL_BEFORE_CLOSED:'SD.UI.Dating.Panel.Events:PANEL_BEFORE_CLOSED',PANEL_CLOSE_REQUEST:'SD.UI.Dating.Panel.Events:PANEL_CLOSED_REQUEST',PANEL_ACTIVATE_REQUEST:'SD.UI.Dating.Panel.Events:PANEL_ACTIVATE_REQUEST',PANEL_COMPACTED:'SD.UI.Dating.Panel.Events:PANEL_COMPACTED',PANEL_EXPANDED:'SD.UI.Dating.Panel.Events:PANEL_EXPANDED'};SD.UI.Dating.DatePanel=Class.create(SD.UI.Dating.Panel,{setup:function($super){$super();this.type='datePanel';this.abuseReportDialog=new SD.UI.Dating.ReportAbuseDialog({domHolder:this.dom,paneHolder:null,container:this});this.endDateDialog=new SD.UI.Dating.EndDateDialog({domHolder:this.dom,paneHolder:null,container:this,data:this.data.preferredAsl});SD.Event.observe(null,SD.UI.Dating.DateHeader.Events.OPEN_ABUSE_REPORT,function(e){(e.memo.panelId==this.id)&&this.abuseReportDialog.show();}.bind(this));SD.Event.observe(null,SD.UI.Dating.DateHeader.Events.OPEN_END_DATE,function(e){(e.memo.panelId==this.id)&&this.endDateDialog.show();}.bind(this));if(SD.ExperimentManager.FbWingman_3644.value&&!Prototype.Browser.IE6){this.showObserverPanel();}},layoutConfig:{masterGrid:{type:'vgrid',cls:"pane lib-date-gui chat-gui",children:{header:{cls:'pane lib-draggable lib-date-header',size:40},bodyHolder:{cls:'pane'}}},bodyGrid:{type:'hgrid',parentPane:'bodyHolder',cls:'pane',children:{bodyHolderLeft:{cls:'pane'},bodyHolderRight:{cls:'pane',size:222}}},bodyGridLeft:{type:'vgrid',parentPane:'bodyHolderLeft',cls:'pane',children:{banner:{cls:'pane lib-chat-banner',size:40,visible:false},chatObserver:{cls:'pane lib-chat-observer',size:60,visible:false},webcam:{cls:'pane lib-webcam-pane',size:192,visible:false},webcamResizer:{type:'resizer',size:5,visible:false},messagePane:{cls:'pane lib-message-pane'},toolbar:{cls:'pane lib-date-toolbar',size:30},input:{cls:'pane lib-date-input-module',size:42}}},bodyGridRight:{type:'vgrid',parentPane:'bodyHolderRight',cls:'pane',children:{pictureGallery:{cls:'pane lib-date-picture-gallery',size:163},profile:{cls:'pane lib-date-profile'}}}},parseLibrary:{'lib-date-header':function(el,domRoot){el.addClassName('pane-date-header');this.data.dateHeader.uid=this.data.meta.user.uid;this.dateHeader=this.addComponent(SD.UI.Dating.DateHeader,el,this.data.dateHeader,{templates:SD.UI.Dating.DateHeader3ButTemplates,initTemplate:SD.UI.Dating.DateHeader3ButTemplates.dateFrame});},'lib-date-toolbar':function(el,domRoot){el.addClassName('pane-toolbar-module');this.toolbarModule=this.addComponent(SD.UI.Dating.DateToolbar,el,this.data.dateToolbar);this.toolbarModule.domButWebcam.onclick=function(){SD.Event.fire(this,SD.UI.Dating.DatePanel.Events.WEBCAM_TOGGLE,{panelId:this.id});}.bind(this);},'lib-date-profile':function(el,domRoot){el.addClassName('pane-date-profile');el.style.overflowY="auto";this.dateProfile=this.addComponent(SD.UI.Dating.DateProfile,el,this.data.dateProfile);},'lib-date-picture-gallery':function(el,domRoot){el.addClassName('pane-date-picture-gallery');this.pictureGallery=this.addComponent(SD.UI.Dating.DatePictureGallery,el,this.data.pictureGallery);},'lib-date-picture-gallery-v2':function(el,domRoot){el.addClassName('pane-date-picture-gallery');this.pictureGallery=this.addComponent(SD.UI.Dating.DatePictureGallery,el,this.data.pictureGalleryV2);},'lib-webcam-pane':function(el,domRoot){el.addClassName('pane-webcam-pane');this.webcamPaneModule=this.addComponent(SD.UI.Dating.WebcamPane,el,this.data.webcamPane);},'lib-date-input-module':function(el,domRoot){el.addClassName('pane-input-module');this.inputModule=this.addComponent(SD.UI.Dating.DateInputModule,el,this.data.inputModule);},'lib-message-pane':function(el,domRoot){el.addClassName('pane-date-pane');this.messagePane=this.addComponent(SD.UI.Dating.MessagePane,el,this.data.datePane);},'lib-chat-banner':function(el,domRoot){this.bannerPane=VL_Pane.panes[el.id];},'lib-chat-observer':function(el,domRoot){el.addClassName('pane-chat-observer');this.chatObserverPane=VL_Pane.panes[el.id];this.chatObserverModule=this.addComponent(SD.UI.Dating.ChatObserverModule,el,this.data.chatObserverModule);},'lib-date-profile-v1':function(el,domRoot){el.addClassName('pane-date-profile');el.style.overflowY="hidden";this.dateProfile=this.addComponent(SD.UI.Dating.DateProfileV1,el,this.data.dateProfileV1);},'lib-date-profile-v2':function(el,domRoot){el.addClassName('pane-date-profile');el.style.overflowY="hidden";this.dateProfile=this.addComponent(SD.UI.Dating.DateProfileV2,el,this.data.dateProfileV2);},'lib-date-profile-v3':function(el,domRoot){el.addClassName('pane-date-profile');el.style.overflowY="hidden";this.dateProfile=this.addComponent(SD.UI.Dating.DateProfileV3,el,this.data.dateProfileV3);}},registerClock:function(countdownClock){this.countdownClock=countdownClock;this.countdownClock.container=this;},getClock:function(){return this.countdownClock;},showBanner:function(){this.bannerPane.parentPane.showPane(this.bannerPane);},hideBanner:function(){this.bannerPane.parentPane.hidePane(this.bannerPane);},putBannerContent:function(content){this.bannerPane.addContent(content);},hideExtendDate:function(){this.toolbarModule.hideExtendDate();},showExtendDate:function(){this.toolbarModule.showExtendDate();},showEndDate:function(){this.dateHeader.showEndDate();},hideReport:function(){this.dateHeader.hideReport();},showReport:function(){this.dateHeader.showReport();},setObserver:function(friend){this.chatObserverModule.setObserver(friend);},removeObserver:function(friend){this.chatObserverModule.removeObserver();},showObserverPanel:function(){this.chatObserverPane.parentPane.showPane(this.chatObserverPane);}});SD.UI.Dating.DatePanel.Events={WEBCAM_TOGGLE:'SD.UI.Dating.DatePanel.Events:WEBCAM_TOGGLE'};SD.UI.Dating.PanelWithTab={getTab:function(){return this.tab;},setTab:function(tab){this.tab=tab;}};SD.UI.Dating.DatePanel.addMethods(SD.UI.Dating.PanelWithTab);SD.UI.Dating.AltLayouts={layout1:Object.extend(SD.Utils.Object.clone(SD.UI.Dating.DatePanel.prototype.layoutConfig),{bodyGridRight:{type:'vgrid',parentPane:'bodyHolderRight',cls:'pane',children:{profile:{cls:'pane lib-date-profile-v1'}}}}),layout3:Object.extend(SD.Utils.Object.merge(SD.UI.Dating.DatePanel.prototype.layoutConfig,{bodyGrid:{type:'hgrid',parentPane:'bodyHolder',cls:'pane',children:{bodyHolderRight:{cls:'pane',size:478}}}}),{bodyGridRight:{type:'vgrid',parentPane:'bodyHolderRight',cls:'pane',size:500,children:{profile:{cls:'pane lib-date-profile-v3'}}}})};Object.extend(SD.UI.Dating.DatePanel.prototype,SD.UI.Dating.AltLayouts);SD.UI.Dating.ChatPanel=Class.create(SD.UI.Dating.Panel,{setup:function($super){$super();this.type='chatPanel';this.abuseReportDialog=new SD.UI.Dating.ReportAbuseDialog({domHolder:this.dom,paneHolder:null,container:this});SD.Event.observe(null,SD.UI.Dating.DateHeader.Events.OPEN_ABUSE_REPORT,function(e){(e.memo.panelId==this.id)&&this.abuseReportDialog.show();}.bind(this));try{if(!Prototype.Browser.IE6&&SD.ExperimentManager.FbWingman_3644.value&&!this.data.meta.user.isFacebookUser()){this.showObserverPanel();}}catch(e){}},layoutConfig:{masterGrid:{type:'vgrid',cls:"pane lib-date-gui chat-gui",children:{header:{cls:'pane lib-draggable lib-date-header',size:32},bodyHolder:{cls:'pane'}}},bodyGrid:{type:'hgrid',parentPane:'bodyHolder',cls:'pane',children:{bodyHolderLeft:{cls:'pane'},bodyHolderRight:{cls:'pane',size:222}}},bodyGridLeft:{type:'vgrid',parentPane:'bodyHolderLeft',cls:'pane',children:{banner:{cls:'pane lib-chat-banner',size:40,visible:false},chatObserver:{cls:'pane lib-chat-observer',size:60,visible:false},webcam:{cls:'pane lib-webcam-pane',size:192,visible:false},webcamResizer:{type:'resizer',size:5,visible:false},messagePane:{cls:'pane lib-message-pane'},toolbar:{cls:'pane lib-date-toolbar',size:30},input:{cls:'pane lib-date-input-module',size:42}}},bodyGridRight:{type:'vgrid',parentPane:'bodyHolderRight',cls:'pane',children:{pictureGallery:{cls:'pane lib-date-picture-gallery',size:163},profile:{cls:'pane lib-date-profile'}}}},parseLibrary:{'lib-date-header':function(el,domRoot){el.addClassName('pane-date-header');this.data.dateHeader.uid=this.data.meta.user.uid;var user=this.data.meta.user;this.dateHeader=this.addComponent(SD.UI.Dating.ChatHeader,el,this.data.dateHeader,{templates:SD.UI.Dating.DateHeader3ButTemplates,initTemplate:user.isFacebookUser()?SD.UI.Dating.DateHeader3ButTemplates.fbChatFrame(this.data.dateHeader):SD.UI.Dating.DateHeader3ButTemplates.chatFrame});},'lib-date-toolbar':function(el,domRoot){el.addClassName('pane-toolbar-module');var toolbar=this.data.meta.user.isFacebookUser()?SD.UI.Dating.FBChatToolbar:SD.UI.Dating.ChatToolbar;this.toolbarModule=this.addComponent(toolbar,el,this.data.dateToolbar);this.toolbarModule.domButWebcam.onclick=function(){SD.Event.fire(this,SD.UI.Dating.DatePanel.Events.WEBCAM_TOGGLE,{panelId:this.id});}.bind(this);},'lib-date-profile':function(el,domRoot){el.addClassName('pane-date-profile');el.style.overflowY="auto";this.dateProfile=this.addComponent(SD.UI.Dating.DateProfile,el,this.data.dateProfile);},'lib-date-picture-gallery':function(el,domRoot){el.addClassName('pane-date-picture-gallery');this.pictureGallery=this.addComponent(SD.UI.Dating.DatePictureGallery,el,this.data.pictureGallery);},'lib-date-picture-gallery-v2':function(el,domRoot){el.addClassName('pane-date-picture-gallery');this.pictureGallery=this.addComponent(SD.UI.Dating.DatePictureGallery,el,this.data.pictureGalleryV2);},'lib-webcam-pane':function(el,domRoot){el.addClassName('pane-webcam-pane');this.webcamPaneModule=this.addComponent(SD.UI.Dating.WebcamPane,el,this.data.webcamPane);},'lib-date-input-module':function(el,domRoot){el.addClassName('pane-input-module');this.inputModule=this.addComponent(SD.UI.Dating.DateInputModule,el,this.data.inputModule);},'lib-message-pane':function(el,domRoot){el.addClassName('pane-date-pane');this.messagePane=this.addComponent(SD.UI.Dating.MessagePane,el,this.data.datePane);},'lib-chat-banner':function(el,domRoot){this.bannerPane=VL_Pane.panes[el.id];},'lib-chat-observer':function(el,domRoot){el.addClassName('pane-chat-observer');this.chatObserverPane=VL_Pane.panes[el.id];this.chatObserverModule=this.addComponent(SD.UI.Dating.ChatObserverModule,el,this.data.chatObserverModule);},'lib-date-profile-v1':function(el,domRoot){el.addClassName('pane-date-profile');el.style.overflowY="hidden";this.dateProfile=this.addComponent(SD.UI.Dating.DateProfileV1,el,this.data.dateProfileV1);},'lib-date-profile-v2':function(el,domRoot){el.addClassName('pane-date-profile');el.style.overflowY="hidden";this.dateProfile=this.addComponent(SD.UI.Dating.DateProfileV2,el,this.data.dateProfileV2);},'lib-date-profile-v3':function(el,domRoot){el.addClassName('pane-date-profile');el.style.overflowY="hidden";this.dateProfile=this.addComponent(SD.UI.Dating.DateProfileV3,el,this.data.dateProfileV3);}},registerClock:function(countdownClock){this.countdownClock=countdownClock;this.countdownClock.container=this;},getClock:function(){return this.countdownClock;},showBanner:function(){this.bannerPane.parentPane.showPane(this.bannerPane);},hideBanner:function(){this.bannerPane.parentPane.hidePane(this.bannerPane);},putBannerContent:function(content){this.bannerPane.addContent(content);},hideExtendDate:function(){this.toolbarModule.hideExtendDate();},showExtendDate:function(){this.toolbarModule.showExtendDate();},setObserver:function(friend){this.chatObserverModule.setObserver(friend);},removeObserver:function(friend){this.chatObserverModule.removeObserver();},showObserverPanel:function(){this.chatObserverPane.parentPane.showPane(this.chatObserverPane);}});SD.UI.Dating.ChatPanel.addMethods(SD.UI.Dating.PanelWithTab);SD.UI.Dating.ChatPanel.Events={WEBCAM_TOGGLE:'SD.UI.Dating.ChatPanel.Events:WEBCAM_TOGGLE'};SD.UI.Dating.WindowPanelAdapter=function(panel,win){setupWindow();panel.onActivate=SD.Utils.connect(panel.onActivate,onActivate);panel.onInactivate=SD.Utils.connect(panel.onInactivate,onInactivate);function setupWindow(){win.parser(win.domContent);var originalMinHeight=win.minHeight;var onDragResizeStart=function(){if(!panel.layout||!this.isVisible)return;win.minHeight=originalMinHeight+Math.max(0,panel.layout.webcam.height-330);}.bind(this);win.observe('dragResizeStart',onDragResizeStart);SD.Event.observe(null,SD.UI.Dating.Panel.Events.PANEL_CLOSED,function(e){if(panel.id==e.memo.panelId){win.stopObserving('dragResizeStart',onDragResizeStart);}}.bind(this));}
function onActivate(){panel.show();var parentDom=panel.layout.masterGrid.dom.parentNode;panel.layout.masterGrid.resizeTo(parentDom.offsetWidth,parentDom.offsetHeight);panel.layout.masterGrid.update.bind(panel.layout.masterGrid).defer();}
function onInactivate(){panel.hide();}};SD.UI.Dating.MasterContainer=Class.create(SD.UI.Dating.Container,{initialize:function($super,options){this.layout=this.buildLayout(options.domHolder);$super(options);this.parse(options.domHolder,this.defaultLibrary);this.ui=options.ui;},setup:function($super){$super();this.setupWindow();},setupWindow:function(){this.container.parser(this.container.domContent);if(Prototype.Browser.IE6){var delta=parseInt(this.container.dom.getStyle("width"))-parseInt(this.container.domContent.getStyle("width"));this.container.observe('resize',function(){var win=this.container;if(win.isMinimized){return;}
var w=win.dom.offsetWidth-parseInt(win.dom.getStyle('padding-left'))-parseInt(win.dom.getStyle('padding-right'));var h=parseInt($(win.domContent).getStyle('height'));this.layout.masterGrid.parentDom.setWidth(w-delta);this.layout.masterGrid.parentDom.setHeight(h);this.layout.masterGrid.resizeTo(w,h);}.bind(this));}else{this.container.observe('resize',function(){var win=this.container;if(win.isMinimized){return;}
this.layout.masterGrid.resizeTo(win.domContent.getWidth(),win.domContent.getHeight());}.bind(this));}},layoutConfig:{masterGrid:{type:'vgrid',cls:"pane lib-date-gui chat-gui",children:{tabsHolder:{cls:'pane lib-draggable',size:23},bodyHolder:{cls:'pane lib-panel-holder date-body-pane'}}},topGrid:{type:'hgrid',parentPane:'tabsHolder',cls:'pane date-top-pane',children:{tabs:{cls:'pane lib-tab-holder'},tools:{cls:'pane',size:50}}}},buildGridWrapper:function(domRoot){var gridBaseLayer=$(document.createElement("DIV"));gridBaseLayer.style.position="absolute";gridBaseLayer.style.top=domRoot.getStyle('padding-left');gridBaseLayer.style.left=domRoot.getStyle('padding-top');gridBaseLayer.style.width=(domRoot.offsetWidth-parseInt(domRoot.getStyle('padding-left'))
-parseInt(domRoot.getStyle('padding-right')))+'px';gridBaseLayer.style.height=$(domRoot).getStyle('height');domRoot.appendChild(gridBaseLayer);return gridBaseLayer;},buildLayout:function(domRoot,layoutConfig){layoutConfig=layoutConfig||this.layoutConfig;layoutConfig.masterGrid.parentDom=Prototype.Browser.IE6?this.buildGridWrapper(domRoot):domRoot;var layout=VL_layoutBuilder(layoutConfig);return layout;},defaultLibrary:{'lib-tab-holder':function(el,domRoot){this.tabContainer=new SD.UI.Dating.TabContainer({dom:el});},'lib-panel-holder':function(el,domRoot){this.domPanelHolder=el;}},openChatPanel:function(data,options){var panel=new SD.UI.Dating.ChatPanel(this._constructPanelOptions(data,options));var tab=this.tabContainer.buildTab(Object.extend(this._constructTabParameters(data),{templates:SD.UI.Dating.ChatTabTemplates,initTemplate:SD.UI.Dating.ChatTabTemplates.item}));this.panelSetup(panel,tab,data);return panel;},openDatingPanel:function(data,options){var panel=new SD.UI.Dating.DatePanel(this._constructPanelOptions(data,options));var tab=this.tabContainer.buildTab(this._constructTabParameters(data));this.panelSetup(panel,tab,data);return panel;},_constructPanelOptions:function(data,options){data=data||{};var layoutConfig=null;if(SD.Config.platform.platformId==SD.Constants.PLATFORM.SITE){if(data.meta&&data.meta.user&&data.meta.user.isFacebookUser&&data.meta.user.isFacebookUser()){layoutConfig=SD.UI.Dating.DatePanel.prototype.layout1;}else{layoutConfig=SD.UI.Dating.DatePanel.prototype.layout3;}}
return Object.extend(options||{},{domHolder:this.domPanelHolder,data:data,win:this.container,tabContainer:this.tabContainer,layoutConfig:layoutConfig});},_constructTabParameters:function(data){return{domHolder:this.tabContainer.dom,data:data.tabData};},panelSetup:function(panel,tab,data){this.addItem(panel);panel.setTab(tab);SD.UI.Dating.WindowPanelAdapter(panel,this.container);SD.Event.observe(tab,SD.UI.Dating.Tab.Events.TAB_ACTIVATED,function(){this.activateItem(panel);SD.Event.fire(this,SD.UI.Dating.Panel.Events.PANEL_ACTIVATE_REQUEST,{panelId:panel.id});}.bind(this));SD.Event.observe(tab,SD.UI.Dating.Tab.Events.TAB_CLICK,function(){if(this.container.isMinimized){this.ui.minimizer.toggle(this.container);}}.bind(this));SD.Event.observe(tab,SD.UI.Dating.Tab.Events.TAB_CLOSED,function(){SD.Event.fire(this,SD.UI.Dating.Panel.Events.PANEL_CLOSE_REQUEST,{panelId:panel.id});}.bind(this));SD.Event.observe(panel,SD.UI.Dating.Panel.Events.PANEL_CLOSED,function(e){if(panel.id!=e.memo.panelId){return;}
var tabId=tab.id;tab.close();this.tabContainer.removeItem(tabId);SD.Utils.disconnect(this.layout.bodyHolder.onresize,onBodyHolderResize);this.tabContainer.adjustTabs();}.bind(this));panel.setIconState=function(state){tab.setIconState(state);};tab.setupTabOver(function(){if(panel.messagePane){var text=panel.messagePane.messageHistory[panel.messagePane.messageHistory];var tpl=SD.UI.Dating.MessagePaneTemplates.tootltipMessage;}});tab.setupTabOut(function(){});panel.onActivate=SD.Utils.connect(panel.onActivate,this.tabContainer.activateItem.bind(this.tabContainer,tab));panel.onAttention=SD.Utils.connect(panel.onAttention,function(){tab.setAttention()});var onBodyHolderResize=function(){panel.isVisible&&panel.layout.masterGrid.update();}.bind(this);this.layout.bodyHolder.onresize=SD.Utils.connect(this.layout.bodyHolder.onresize,onBodyHolderResize);this.updateTabs();return panel;},updateTabs:function(){this.layout.masterGrid.showPane(this.layout.tabsHolder);this.layout.tabsHolder.resizeTo(this.layout.tabsHolder.dom.parentNode.offsetWidth,this.layout.tabsHolder.dom.parentNode.offsetHeight);this.layout.masterGrid.update();this.tabContainer.adjustTabs();this.container.butMinimize&&this.container.butMinimize.show();},closePanel:function(panelId){this.container.isMinimized&&this.ui.minimizer.restore(this.container);var panel=this.getById(panelId);if(!panel)return;if(panel.webcamPaneModule&&panel.webcamPaneModule.isVisible()){if(SD.Chat._iAmStreaming[panel.options.data.meta.user.uid]){SD.Event.fire(panel,SD.UI.Dating.DatePanel.Events.WEBCAM_TOGGLE,{panelId:panel.id});}}
if(panel.webcamPaneModule){if(panel.webcamPaneModule.domWebcam){panel.webcamPaneModule.domWebcam.parentNode.removeChild(panel.webcamPaneModule.domWebcam);}
panel.webcamPaneModule.domWebcam=null;}
panel.close();this.removeItem(panelId);var panels=this.getItems();if(panels.length>0&&this.getActiveItem()&&this.getActiveItem().id==panelId){this.activateItem(panels[0]);}},destroyPanel:function(panel){if(typeof panel==='string')
panel=this.getById(panel);var tab=panel.getTab();this.tabContainer.destroyTab(tab);this.removeItem(panel.id);panel.destroy();}});VL_HGrid.defaultResizerClass="resizer hResizer";VL_VGrid.defaultResizerClass="resizer vResizer";VL_Pane.defaultClass="pane";SD.UI.DateUI=Class.create({initialize:function(options){this.options=options||{};this.uis={};if(SD.Config.isSite){this.defaultUI=this.addUI('hybrid');}else{this.defaultUI=this.addUI('window');}
this.setup();},addUI:function(type,options){var id=SD.Utils.IdGenerator.generate();options=options||{};options.id=options.id||id;this.uis[id]=new SD.UI[this.uiTypes[type]](options);return this.uis[id];},removeUI:function(id){if(typeof id=='object'){id=id.id;}
this.uis[id].destroy&&this.uis[id].destroy();this.uis[id]=null;delete this.uis[id];},uiTypes:{'window':'DateWindowUI','page':'DateMultiUI','profile':'DateProfileUI','bar':'DateBarUI','hybrid':'HybridDateBarUI'},setup:function(){this.setupEvents();},setupEvents:function(){if(SD.UI.DateUI.Events.set)return;SD.UI.DateUI.Events.set=true;SD.Event.forward(SD.UI.Dating.Panel.Events.PANEL_CLOSED,SD.UI.DateUI.Events.PANEL_CLOSED);SD.Event.forward(SD.UI.Dating.DatePanel.Events.WEBCAM_TOGGLE,SD.UI.DateUI.Events.WEBCAM_TOGGLE);SD.Event.forward(SD.UI.Dating.DateInputModule.Events.MESSAGE_SEND,SD.UI.DateUI.Events.MESSAGE_SEND);SD.Event.forward(SD.UI.Dating.DateInputModule.Events.INVITE_FB_CHAT,SD.UI.DateUI.Events.INVITE_FB_CHAT);SD.Event.forward(SD.UI.Dating.DateInputModule.Events.INPUT_RECEIVED,SD.UI.DateUI.Events.INPUT_RECEIVED);SD.Event.forward(SD.UI.Dating.WebcamPane.Events.WEBCAM_OPEN,SD.UI.DateUI.Events.WEBCAM_OPEN);SD.Event.forward(SD.UI.Dating.WebcamPane.Events.WEBCAM_CLOSE,SD.UI.DateUI.Events.WEBCAM_CLOSE);SD.Event.forward(SD.UI.Dating.DateToolbar.Events.ICE_BREAKER,SD.UI.DateUI.Events.ICE_BREAKER);SD.Event.forward(SD.UI.Dating.DateToolbar.Events.EXTEND_DATE,SD.UI.DateUI.Events.EXTEND_DATE);SD.Event.forward(SD.UI.Dating.EndDateDialog.Events.END_DATE,SD.UI.DateUI.Events.END_DATE);SD.Event.forward(SD.UI.Dating.EndDateDialog.Events.PAUSE_DATING,SD.UI.DateUI.Events.PAUSE_DATE);SD.Event.forward(SD.UI.Dating.EndDateDialog.Events.FIND_DATE,SD.UI.DateUI.Events.FIND_DATE);SD.Event.forward(SD.UI.Dating.ReportAbuseDialog.Events.ABUSE_REPORT,SD.UI.DateUI.Events.ABUSE_REPORT);SD.Event.forward(SD.UI.Dating.DateHeader.Events.BLOCK,SD.UI.DateUI.Events.BLOCK);SD.Event.forward(SD.UI.Dating.DateHeader.Events.REPORT_REQUESTED,SD.UI.DateUI.Events.REPORT_REQUESTED);SD.Event.forward(SD.UI.Dating.ChatObserverModule.Events.SELECT_FRIEND_AS_OBSERVER,SD.UI.DateUI.Events.SELECT_FRIEND_AS_OBSERVER);SD.Event.forward(SD.UI.Dating.ChatObserverModule.Events.REMOVE_FRIEND_FROM_OBSERVING,SD.UI.DateUI.Events.REMOVE_FRIEND_FROM_OBSERVING);},migratePanel:function(panelId,targetUI){var sourceUI=this.getUIByPanelId(panelId);var sourcePanel=this.getPanelById(panelId);if(!sourcePanel||!sourceUI||!targetUI||sourceUI==targetUI)return;var sourceClock=sourcePanel.getClock();var sourceData=sourcePanel.options.data;sourcePanel.messagePane.domMessageHolder.select('.typing-message').invoke('remove');var messages=sourcePanel.messagePane.domMessageHolder.innerHTML;var domWebcam,isWebcamVisible;if(sourcePanel.webcamPaneModule.webcamInitialized){domWebcam=sourcePanel.webcamPaneModule.domWebcam;document.body.appendChild(domWebcam);isWebcamVisible=sourcePanel.webcamPaneModule.paneHolder.isVisible;}
sourceUI.masterContainer.destroyPanel(panelId);if(sourcePanel.type==='chatPanel'){this.openChatPanel(sourceData,true,targetUI,{id:panelId});}else if(sourcePanel.type==='datePanel'){this.openPanel(sourceData,targetUI,{id:panelId});}
var newPanel=targetUI.getPanelById(panelId);newPanel.messagePane.domMessageHolder.update(messages);newPanel.messagePane.adjustMessagePane();newPanel.getClock().simpleSetup(sourceClock.time,sourceClock.format,sourceClock.onClockEnd);newPanel.getClock().start(newPanel.getClock().simpleTick);if(sourcePanel.toolbarModule.domExtendDate){newPanel.toolbarModule.domExtendDate.style.display=sourcePanel.toolbarModule.domExtendDate.style.display;}
try{newPanel.getClock().dom.style.display=sourceClock.dom.style.display;}catch(e){};if(sourceUI.openedDialogData&&sourceUI.openedDialogData[panelId]){targetUI._showPostDateDialog(panelId,sourceUI.openedDialogData[panelId].data,sourceUI.openedDialogData[panelId].construct);}
if(domWebcam){try{newPanel.webcamPaneModule.adoptWebcam(domWebcam);isWebcamVisible&&newPanel.webcamPaneModule.show();}catch(e){}}},migrateUI:function(sourceUI,targetUI){SD.Event.fire(null,SD.UI.DateUI.Events.BEFORE_UI_MIGRATE,{sourceUI:sourceUI,targetUI:targetUI});if(!sourceUI.masterContainer||(sourceUI.masterContainer&&sourceUI.masterContainer.getCount()===0))return;var activePanel=sourceUI.getActivePanel();var activePanelId=activePanel&&activePanel.id;activePanel=null;sourceUI.masterContainer.getItems().each(function(panel){this.migratePanel(panel.id,targetUI);},this);activePanelId&&targetUI.setActivePanel(activePanelId);SD.Event.fire(null,SD.UI.DateUI.Events.UI_MIGRATED,{sourceUI:sourceUI,targetUI:targetUI});},isUIavailable:function(ui){ui=ui||this.defaultUI;return ui.isUIavailable();},getPanelByUid:function(uid){var panel;for(var uiId in this.uis){if(this.uis[uiId].getPanelByUid&&(panel=this.uis[uiId].getPanelByUid(uid))){break;}}
return panel;},getPanelById:function(panelId){var panel;for(var uiId in this.uis){if((panel=this.uis[uiId].getPanelById(panelId))){break;}}
return panel;},getUIByPanelId:function(panelId){var ownerUI;for(var uiId in this.uis){if(this.uis[uiId].getPanelById(panelId)){ownerUI=this.uis[uiId];break;}}
return ownerUI;},openChatPanel:function(data,toActivate,ui,options){ui=ui||this.defaultUI;return ui.openChatPanel(data,toActivate,options);},openPanel:function(data,ui,options){ui=ui||this.defaultUI;return ui.openPanel(data,options);},closePanel:function(panelId){var ui=this.getUIByPanelId(panelId);return ui&&ui.closePanel(panelId);},putMessage:function(panelId,message,dontBlink){var ui=this.getUIByPanelId(panelId);return ui&&ui.putMessage(panelId,message,dontBlink);},clearStaticMessage:function(panelId){var ui=this.getUIByPanelId(panelId);return ui&&ui.clearStaticMessage(panelId);},getActivePanel:function(ui){ui=ui||this.defaultUI;return ui&&ui.getActivePanel();},setActivePanel:function(panelId){var ui=this.getUIByPanelId(panelId);return ui&&ui.setActivePanel(panelId);},showPostDateDialog:function(panelId,data){var ui=this.getUIByPanelId(panelId);return ui&&ui.showPostDateDialog(panelId,data);},showPostDateDialogSimple:function(panelId,data){var ui=this.getUIByPanelId(panelId);return ui&&ui.showPostDateDialogSimple(panelId,data);},showPostDateAdvancedDialog:function(panelId,data){var ui=this.getUIByPanelId(panelId);return ui&&ui.showPostDateAdvancedDialog(panelId,data);},showPostDateVoteDialog:function(panelId,data){var ui=this.getUIByPanelId(panelId);return ui&&ui.showPostDateVoteDialog(panelId,data);},showPreDateDialog:function(panelId,data){var ui=this.getUIByPanelId(panelId);return ui&&ui.showPreDateDialog(panelId,data);},getWebcamDom:function(panelId){var ui=this.getUIByPanelId(panelId);return ui&&ui.getWebcamDom(panelId);},showWebcamPane:function(panelId,onReady){var ui=this.getUIByPanelId(panelId);return ui&&ui.showWebcamPane(panelId,onReady);},hideWebcamPane:function(panelId){var ui=this.getUIByPanelId(panelId);return ui&&ui.hideWebcamPane(panelId);},setWebcamButText:function(panelId,text){var ui=this.getUIByPanelId(panelId);return ui&&ui.setWebcamButText(panelId,text);},setIconState:function(panelId,state){var ui=this.getUIByPanelId(panelId);return ui&&ui.setIconState(panelId,state);},showBanner:function(panelId){var ui=this.getUIByPanelId(panelId);return ui&&ui.showBanner(panelId);},hideBanner:function(panelId){var ui=this.getUIByPanelId(panelId);return ui&&ui.hideBanner(panelId);},putBannerContent:function(panelId,content){var ui=this.getUIByPanelId(panelId);return ui&&ui.putBannerContent(panelId,content);},activateLightBox:function(ui){ui=ui||this.defaultUI;return ui&&ui.activateLightBox();},deactivateLightBox:function(ui){ui=ui||this.defaultUI;return ui&&ui.deactivateLightBox();}});SD.UI.DateUI.Events={PANEL_CLOSED_ALL:'SD.UI.DateUI.Events:PANEL_CLOSED_ALL',PANEL_CLOSED:'SD.UI.DateUI.Events:PANEL_CLOSED',PANEL_OPENED:'SD.UI.DateUI.Events:PANEL_OPENED',WEBCAM_TOGGLE:'SD.UI.DateUI.Events:WEBCAM_TOGGLE',UI_CLOSED:'SD.UI.DateUI.Events:UI_CLOSED',INPUT_RECEIVED:'SD.UI.DateUI.Events:INPUT_RECEIVED',MESSAGE_SEND:'SD.UI.DateUI.Events:MESSAGE_SEND',INVITE_FB_CHAT:'SD.UI.DateUI.Events:INVITE_FB_CHAT',WEBCAM_OPEN:'SD.UI.DateUI.Events:WEBCAM_OPEN',WEBCAM_CLOSE:'SD.UI.DateUI.Events:WEBCAM_CLOSE',ICE_BREAKER:'SD.UI.DateUI.Events:ICE_BREAKER',EXTEND_DATE:'SD.UI.DateUI.Events:EXTEND_DATE',END_DATE:'SD.UI.DateUI.Events:END_DATE',FIND_DATE:'SD.UI.DateUI.Events:FIND_DATE',PAUSE_DATE:'SD.UI.DateUI.Events:PAUSE_DATE',ABUSE_REPORT:'SD.UI.DateUI.Events:ABUSE_REPORT',BLOCK:'SD.UI.DateUI.Events:BLOCK',REPORT_REQUESTED:'SD.UI.DateUI.Events:REPORT_REQUESTED',UI_MIGRATED:'SD.UI.DateUI.Events:UI_MIGRATED',BEFORE_UI_MIGRATE:'SD.UI.DateUI.Events:BEFORE_UI_MIGRATE',CONTACT_USER:'SD.UI.DateUI.Events:CONTACT_USER',FIND_END_DATE_REASON:'SD.UI.DateUI.Events:FIND_END_DATE_REASON',CONTINUE_CHAT:'SD.UI.DateUI.Events:CONTINUE_CHAT',MATCH:'SD.UI.DateUI.Events:MATCH',NO_MATCH:'SD.UI.DateUI.Events:NO_MATCH',POST_DATE_DIALOG_OPEN:'SD.UI.DateUI.Events:POST_DATE_DIALOG_OPEN',POST_DATE_SIMPLE_DIALOG_OPEN:'SD.UI.DateUI.Events:POST_DATE_SIMPLE_DIALOG_OPEN',POST_DATE_ADVANCED_DIALOG_OPEN:'SD.UI.DateUI.Events:POST_DATE_ADVANCED_DIALOG_OPEN',POST_DATE_VOTING_DIALOG_OPEN:'SD.UI.DateUI.Events:POST_DATE_VOTING_DIALOG_OPEN',PRE_DATE_DIALOG_OPEN:'SD.UI.DateUI.Events:PRE_DATE_DIALOG_OPEN',REMOVE_FRIEND_FROM_OBSERVING:"SD.UI.DateUI.Events:REMOVE_FRIEND_FROM_OBSERVING",SELECT_FRIEND_AS_OBSERVER:"SD.UI.DateUI.Events:SELECT_FRIEND_AS_OBSERVER"};SD.UI.DateUI.shareWithFacebook=function(formId){if(SD.XConnect.hasFacebookOAuth()){SD.SocialPowers.considerViralBarReload("invitation");$(formId).submit();}else{SD.XConnect.openFacebookAuthenticate(function(result){if(result){$(formId).submit();}},{permissions:SD.Config.defaultFbPermissions});}};SD.UI.DateUI.dateUI=null;SD.UI.DateUI.getUI=function(){if(!this.dateUI){this.dateUI=new SD.UI.DateUI();}
return this.dateUI;};SD.UI.DateWindowUI=Class.create({initialize:function(options){this.options=options;this.id=options.id;this.minimizer=new SD.UI.DateWindowUI.Minimizer(this);this.setup();},setup:function(){SD.Event.observe(null,SD.UI.DateUI.Events.UI_MIGRATED,function(e){if(e.memo.sourceUI==this){if(this.win&&this.win.isOpened){this.win.close();}}}.bind(this));},reset:function(){this.win=null;},isUIavailable:function(){return!!(this.win&&this.win.isOpened);},setupWindowEvents:function(){SD.Event.observe(this,SD.UI.DateWindowUI.Events.WINDOW_RESTORE,this._onWindowRestore);},setupEventsForPanel:function(panelId){var panel=this.getPanelById(panelId);SD.Event.observe(null,SD.UI.Dating.Panel.Events.PANEL_CLOSE_REQUEST,this._onPanelCloseRequest.bind(this));SD.Event.observe(null,SD.UI.Dating.Panel.Events.PANEL_BEFORE_CLOSED,this._onPanelBeforeClosed.bind(this));SD.Event.observe(null,SD.UI.Dating.Panel.Events.PANEL_CLOSED,this._onPanelClosed.bind(this));var restoreWin=this._restoreWinAndFocusDate.bind(this);SD.Event.observe(panel,SD.UI.DateUI.Events.POST_DATE_DIALOG_OPEN,restoreWin);SD.Event.observe(panel,SD.UI.DateUI.Events.POST_DATE_SIMPLE_DIALOG_OPEN,restoreWin);SD.Event.observe(panel,SD.UI.DateUI.Events.POST_DATE_ADVANCED_DIALOG_OPEN,restoreWin);SD.Event.observe(panel,SD.UI.DateUI.Events.POST_DATE_VOTING_DIALOG_OPEN,restoreWin);SD.Event.observe(panel,SD.UI.DateUI.Events.PRE_DATE_DIALOG_OPEN,restoreWin);SD.Event.observe(panel,SD.UI.DateUI.Events.PANEL_OPENED,restoreWin);},_onWindowRestore:function(e){if(e.source.win!=e.memo.win){return;}
var tab=e.source.getActivePanel().getTab();tab&&tab.setActive();e.source.masterContainer.layout.masterGrid.update();},_onPanelCloseRequest:function(e){var panel=this.getPanelById(e.memo.panelId);if(panel&&this.win&&!this.win.isMinimized){this.closePanel(e.memo.panelId);}},_onPanelBeforeClosed:function(e){var panel=this.getPanelById(e.memo.panelId);if(panel&&this.win){this.win.isMinimized&&this.minimizer.restore(this.win);}},_onPanelClosed:function(e){var panel=this.getPanelById(e.memo.panelId);if(panel){SD.Event.fire(null,SD.UI.DateUI.Events.PANEL_CLOSED,e.memo);SD.Favicon.setTitle();}},_showPostDateDialog:function(panelId,data,Constructor){var panel=this.getPanelById(panelId);return new Constructor({domHolder:panel.dom,paneHolder:null,container:panel,data:data});},_restoreWinAndFocusDate:function(e){if(this.win&&this.win.isMinimized){this.minimizer.restore(this.win);}
if(!this.getActivePanel()){this.setActivePanel(e.memo.panelId);}},_initializeWindow:function(data){this.win=this.createWin();this.win.open();this.masterContainer=new SD.UI.Dating.MasterContainer({domHolder:this.win.getContent(),container:this.win,data:data,ui:this});this.setupWindowEvents();},getWinDims:function(){var winDim=document.viewport.getDimensions();return{contentWidth:Math.min(winDim.width-11,800),contentHeight:Math.max(453,Math.min(560,winDim.height)),minWidth:Math.min(winDim.width,790),minHeight:485}},createWin:function(){var ui=this;var onAfterOpen=function(){var vDim=document.viewport.getDimensions(),vScrollOffsets=document.viewport.getScrollOffsets(),lastWinPosition=ui.getLastUIPosition();if(lastWinPosition){win.moveTo(lastWinPosition.left,lastWinPosition.top);}else{if(win.position=="fixed"){win.moveTo(vDim.width-win.width-10,35);}else if(win.position=="absolute"){win.moveTo(vScrollOffsets.left+vDim.width-win.width-10,vScrollOffsets.top+10);}}};var onBeforeClose=function(){SD.Event.fireDeferred(null,SD.UI.DateUI.Events.UI_CLOSED,{ui:ui});ui.saveLastUIPosition(win.left,win.top);};var onAfterClose=function(){if(win.butMinimize){win.butMinimize.onclick=null;win.domTitle.ondblclick=null;}
SD.Tooltip.hide();};var parseLibrary={'.lib-minimize':function(el,domRoot){ui.minimizer.setup(el,this);el.removeClassName("lib-minimize");}};var winDims=this.getWinDims();var winConfig={minWidth:winDims.minWidth,minHeight:winDims.minHeight,contentWidth:winDims.contentWidth,contentHeight:winDims.contentHeight,title:"Chat and Dating",className:"lib-window chat-window chat-light-skin",template:SD.UI.Dating.windowTemplate,shim:true,resizable:true,groupId:'group3',onAfterOpen:onAfterOpen,onBeforeClose:onBeforeClose,onAfterClose:onAfterClose,parseLibrary:parseLibrary};var win=new SD.Window(winConfig);win.type='dating_window';var winContentDom=win.getContent();winContentDom.style.overflow="hidden";winContentDom.style.position="relative";win.dom.style.overflow='hidden';return win;},saveLastUIPosition:function(left,top){SD.UI.DateWindowUI.lastUIposition={top:top,left:left};},getLastUIPosition:function(){return SD.UI.DateWindowUI.lastUIposition;},getPanelById:function(panelId){return this.masterContainer&&this.masterContainer.getById(panelId);},openChatPanel:function(data,toActivate,options){if(!this.isUIavailable()){this._initializeWindow(data);}
if(this.win.isMinimized){this.minimizer.toggle(this.win)}
var panel=this.masterContainer.openChatPanel(data,options);this.setupEventsForPanel(panel.id);if(this.masterContainer.getCount()==1||toActivate||this.win.isMinimized){this.setActivePanel(panel.id);}
SD.Event.fire(panel,SD.UI.DateUI.Events.PANEL_OPENED,{panelId:panel.id});return panel.id;},openPanel:function(data,options){if(!this.isUIavailable()){this._initializeWindow(data);}
if(this.win.isMinimized){this.minimizer.toggle(this.win)}
var panel=this.masterContainer.openDatingPanel(data,options);this.setupEventsForPanel(panel.id);SD.Event.fire(panel,SD.UI.DateUI.Events.PANEL_OPENED,{panelId:panel.id});return panel.id;},closePanel:function(panelId){this.masterContainer.closePanel(panelId);if(this.masterContainer.getCount()==0){SD.Event.fireDeferred(this,SD.UI.DateUI.Events.PANEL_CLOSED_ALL,{});this.win.close();this.reset();}},putMessage:function(panelId,message,dontBlink){var panel=this.getPanelById(panelId);if(panel){panel.messagePane.putMessage(message);if(panel!=this.getActivePanel()||this.win.isMinimized){!dontBlink&&panel.setAttention();}
if(!this.win.isVisible){this.taskBarButton&&this.taskBarButton.blink();}}},clearStaticMessage:function(panelId){var panel=this.getPanelById(panelId);panel&&panel.messagePane.clearStaticMessage();},getActivePanel:function(){return this.masterContainer.getActiveItem();},setActivePanel:function(panelId){if(this.win.isMinimized){return;}
var panel=this.getPanelById(panelId);panel&&this.masterContainer.activateItem(panel);},showPostDateDialog:function(panelId,data){SD.Event.fire(this.getPanelById(panelId),SD.UI.DateUI.Events.POST_DATE_DIALOG_OPEN,{panelId:panelId});return this._showPostDateDialog(panelId,data,SD.UI.Dating.PostDateContactDialog);},showPostDateDialogSimple:function(panelId,data){SD.Event.fire(this.getPanelById(panelId),SD.UI.DateUI.Events.POST_DATE_SIMPLE_DIALOG_OPEN,{panelId:panelId});return this._showPostDateDialog(panelId,data,SD.UI.Dating.PostDateContactSimpleDialog);},showPostDateAdvancedDialog:function(panelId,data){SD.Event.fire(this.getPanelById(panelId),SD.UI.DateUI.Events.POST_DATE_ADVANCED_DIALOG_OPEN,{panelId:panelId});return this._showPostDateDialog(panelId,data,SD.UI.Dating.PostDateAdvancedDialog);},showPostDateVoteDialog:function(panelId,data){SD.Event.fire(this.getPanelById(panelId),SD.UI.DateUI.Events.POST_DATE_VOTING_DIALOG_OPEN,{panelId:panelId});return this._showPostDateDialog(panelId,data,SD.UI.Dating.PostDateVoteDialog);},showPreDateDialog:function(panelId,data){SD.Event.fire(null,SD.UI.DateUI.Events.PRE_DATE_DIALOG_OPEN,{panelId:panelId});var panel=this.getPanelById(panelId);var dialog=new SD.UI.Dating.PreDateDialog({domHolder:panel.layout.messagePane.dom,paneHolder:null,container:panel,data:data});var n=5;var timer=setInterval(function(){n--;dialog.setClock(n);if(n<=0){clearInterval(timer);dialog.hide();SD.Event.fire(null,SD.Date.Events.DATE_INIT_END,null);}},1000);return dialog;},getWebcamDom:function(panelId){var panel=this.getPanelById(panelId);return panel&&panel.webcamPaneModule&&$(panel.webcamPaneModule.domWebcamId);},showWebcamPane:function(panelId,onReady){SD.UI.DateUI.flashCallback=SD.UI.DateUI.flashCallback||{};SD.UI.DateUI.flashCallback['onReady_'+panelId]=onReady||SD.UI.DateUI.flashCallback['onReady_'+panelId];this.getPanelById(panelId).webcamPaneModule.show('SD.UI.DateUI.flashCallback.onReady_'+panelId);},hideWebcamPane:function(panelId){var panel=this.getPanelById(panelId);panel&&panel.webcamPaneModule&&panel.webcamPaneModule.hide();},setWebcamButText:function(panelId,text){var panel=this.getPanelById(panelId);panel&&panel.toolbarModule&&panel.toolbarModule.setWebcamButText(text);},setIconState:function(panelId,state){var panel=this.getPanelById(panelId);panel&&panel.setIconState(state);},showBanner:function(panelId){var panel=this.getPanelById(panelId);panel&&panel.showBanner();},hideBanner:function(panelId){var panel=this.getPanelById(panelId);panel&&panel.hideBanner();},putBannerContent:function(panelId,content){var panel=this.getPanelById(panelId);panel&&panel.putBannerContent(content);},activateLightBox:function(){if(!this.win){return false;}
this.win.options.blocker=true;this.win.setupBlocker();SD.WindowManager.adjustBlocker();return true;},deactivateLightBox:function(){if(!this.win){return false;}
this.win.options.blocker=false;this.win.setupBlocker();SD.WindowManager.removeBlockingWindow(this.win);return true;}});SD.UI.DateWindowUI.Events={WINDOW_RESTORE:'SD.UI.DateWindowUI.Events:WINDOW_RESTORE',WINDOW_MINIMIZE:'SD.UI.DateWindowUI.Events:WINDOW_MINIMIZE'};SD.UI.DateWindowUI.Minimizer=Class.create({MINIMIZED_HEIGHT:55,initialize:function(ui,minHeight){this.ui=ui;this.minHeight=minHeight||this.MINIMIZED_HEIGHT;this.canToggle=true;},setup:function(el,win){win.butMinimize=el;var toggle=this.toggle.bind(this,win);el.onclick=toggle;win.minButton=el;},toggle:function(win){if(this.canToggle){this.temporarilyBlockToggle();win.isMinimized?this.restore(win):this.minimize(win);}},temporarilyBlockToggle:function(){var _this=this;this.canToggle=false;(function(){_this.canToggle=true;}).delay(0.5);},restore:function(win){win.minHeight=win.oldMinHeight;win.isHeightStatic=false;win.isWidthStatic=false;win.resizeTo(null,win.oldHeight);win.isMinimized=false;win.minButton.setAttribute("sdMessage","Minimize Window");win.moveTo(win.left,win.top);SD.Event.fire(this.ui,SD.UI.DateWindowUI.Events.WINDOW_RESTORE,{win:win});},minimize:function(win){win.oldHeight=win.height;win.oldMinHeight=win.minHeight;win.minHeight=this.minHeight;win.isMinimized=true;win.resizeTo(null,win.minHeight);win.isHeightStatic=true;win.isWidthStatic=true;win.minButton.setAttribute("sdMessage","Restore Window");SD.Event.fire(this.ui,SD.UI.DateWindowUI.Events.WINDOW_MINIMIZE,{win:win});}});SD.Event.observe(null,SD.UI.Dating.Panel.Events.PANEL_ACTIVATE_REQUEST,function(e){});SD.Event.observe(null,SD.UI.DateUI.Events.MESSAGE_SEND,function(e){});SD.Event.observe(null,SD.UI.DateUI.Events.WEBCAM_TOGGLE,function(e){});
SD.Tag={_cloudDivUsers:{},enabled:function(){return true;},isUserTaggable:function(user){return user.istaggable!==false;},tagMember:function(user,tagIds){new Ajax.Request(SD.NavUtils.link('ajax','tag_member'),{method:'post',parameters:{taggedid:user.uid,tagIds:tagIds.join()},onSuccess:function(e){if(e&&e.responseJSON&&e.responseJSON.result){SD.Event.fire(null,SD.Tag.Events.TAGS_ADDED,{addedList:e.responseJSON.addedList,errors:e.responseJSON.errors,taggedId:user.uid});e.responseJSON.addedList.each(function(tag){var found=false;var existingTag=user.tags.find(function(existingTag){return existingTag.tagId==tag.id});if(existingTag){existingTag.count++;}else{user.tags.push({tagId:tag.id,name:tag.name,count:1});}});SD.Tag.refreshDivs([user.uid]);}else{}}.bind(this),onFailure:function(e){}.bind(this)});},getUidsByTagId:function(tagId){var ret=[];for(var uid in SD.User._users){var user=SD.User.get(uid);if(user.tags&&user.tags.find(function(existingTag){return existingTag.tagId==tagId;})){ret.push(user.uid);}}
return ret;},deleteTag:function(tagId){var user=SD.Model.getMyself();tag=user.tags.find(function(myTag){return myTag.tagId==tagId});if(!tag){return;}
if(confirm(" Are you sure you want to delete tag: "+tag.name)){new Ajax.Request(SD.NavUtils.link('ajax','delete_tag'),{method:'post',parameters:{tagId:tagId},onSuccess:function(e){if(e&&e.responseJSON&&e.responseJSON.result){var found=false;var existingTag=user.tags.find(function(existingTag){return existingTag.tagId==tagId});user.tags.remove(existingTag);SD.Tag.refreshDivs([user.uid]);}else{}}.bind(this),onFailure:function(e){SD.UIController.messageBox("Tagging","Could not complete tag request");}.bind(this)});};},_loadUserTags:function(uids,callback){new Ajax.Request(SD.NavUtils.link('ajax','load_member_tags'),{method:'post',parameters:{memberids:uids.join()},onSuccess:function(e){if(e&&e.responseJSON&&e.responseJSON.result){for(uid in e.responseJSON.data){SD.User.get(uid).tags=e.responseJSON.data[uid];}
SD.Tag.refreshDivs(uids);callback(e.responseJSON.data);}else{callback(null);}}.bind(this),onFailure:function(e){SD.UIController.messageBox("Tagging","Could not complete tag request");}.bind(this)});},refreshDivs:function(uids){var divsToRefresh=[];var intUids=uids.collect(function(uid){return parseInt(uid)});for(divId in this._cloudDivUsers){var inter=this._cloudDivUsers[divId].intersect(intUids);if(inter.length){divsToRefresh.push(divId);}}
divsToRefresh=divsToRefresh.uniq();divsToRefresh.each(function(divId){this._drawCloudWhenReady(this._cloudDivUsers[divId],divId);}.bind(this));},fetchUserTags:function(user,callback){if(user.tags){callback&&callback(user.tags);return;}
this._loadUserTags([user.uid],function(data){callback(tags);});},fetchMultipleUserTags:function(uids,onDone){var not_fetched=[];uids.each(function(uid){var user=SD.User.get(uid);if(!user.tags){not_fetched.push(uid);}});if(not_fetched.length){this._loadUserTags(uids,function(){onDone();});}else{onDone();}},getCloudData:function(users,limit){return[{text:'Clever',value:10,tagId:1},{text:'Sexy',value:5,tagId:2}];},addTagAutoComplete:function(inputId,userId,suggestionDiv,onSelect){if(!this.enabled()){return;}
if(!$(inputId)){return;}
new Autocomplete(inputId,{serviceUrl:SD.NavUtils.link('ajax','tag_suggest'),'class':'tag-autocomplete',minChars:1,maxHeight:400,deferRequestBy:75,container:suggestionDiv,onSelect:onSelect||function(value,data){if(inputId=='tags_flirtwink'){userId=SD.FlirtWink.Controller.getCurrentFlirtee().uid;}
SD.Tag.tagMember(SD.User.get(userId),[data]);$(inputId).value='';}});},searchFieldTemplate:'<div class="list-item">'+'<input type="checkbox" class="search-checkbox" textvalue="#{value}"'+' name="s_member_info[#{memberInfoId}][]" value="#{value}"'+' id="member-info-#{memberInfoId}-#{value}" checked="checked">'+'<label for="member-info-#{memberInfoId}-#{value}"'+' id="member-info-label-#{memberInfoId}-#{value}">'+' #{value}'+'</label>'+'</div>',searchTagAutoComplete:function(memberInfoId,suggestionDiv,onSelect){if(!this.enabled()){return;}
var inputId='query_'+memberInfoId;var parentId='member-info-filter-'+memberInfoId;var autocompleteChooserId='autocomplete-chooser-'+memberInfoId;this.autoCompleter=new Autocomplete(inputId,{serviceUrl:SD.NavUtils.link('ajax','tag_suggest'),'class':'tag-autocomplete',minChars:1,maxHeight:400,deferRequestBy:75,container:suggestionDiv,onSelect:onSelect||function(value,data){$(autocompleteChooserId).insert({after:SD.Tag.searchFieldTemplate.interpolate({memberInfoId:memberInfoId,value:value})});$(inputId).value='';}});},drawCloud:function(uids,divId,maxSize){if(!this.enabled()){return;}
this.fetchMultipleUserTags(uids,function(){this._drawCloudWhenReady(uids,divId,maxSize);}.bind(this));},removeCloud:function(divId){delete this._cloudDivUsers[divId];},_drawCloudWhenReady:function(uids,divId,maxSize){if(!$(divId)){return;}
$(divId).innerHTML="";this._cloudDivUsers[divId]=uids.collect(function(uid){return parseInt(uid)});var tags=[];uids.each(function(uid){var userTags=SD.User.get(uid).tags;if(userTags){tags=tags.concat(userTags);}});var tagAssoc={};tags.each(function(tag){if(!tagAssoc[tag.tagId]){tagAssoc[tag.tagId]={tagId:tag.tagId,name:tag.name,count:0};}
tagAssoc[tag.tagId].count+=tag.count;});var data=[];for(var tagId in tagAssoc){var tag=tagAssoc[tagId];data.push({text:tag.name,value:tag.count,tagId:tag.tagId});};if(data.length==0){oElement=$$('.tags-flirtwink2703').first();if(!oElement){data.push({text:$(divId).getAttribute('sdemptytext')||'Be the first to tag',value:1});}}
var deleteEnabled=uids.length==1&&SD.Model&&uids[0]==SD.Model.getMyself().uid;var dataRatio=Math.abs(200-data.length)/200;var MAXFONTSIZE=13+22*dataRatio;if(maxSize){MAXFONTSIZE=Math.min(maxSize,MAXFONTSIZE);}
var MINFONTSIZE=8+5*dataRatio;this.TagCloud.process(data,{renderer:function(text,size,unit,tagId){var red=parseInt(14+(size*5.5));var green=parseInt(120-(size*0.5));var blue=parseInt(236-(size*5));var deleteText=deleteEnabled?"<a href='javascript:SD.Tag.deleteTag("+tagId+")'><span class=\"close\" sdType=\"tooltip\" sdMessage='delete tag: "+text+"'>x</span></a>":'';$(divId).innerHTML+="<span class=\"tag-item\">"+text+deleteText+"</span><span class=\"divider\"> &middot; </span>";},scaler:function(value,rangeData){var spread=rangeData.max-rangeData.min;if(spread==0){spread=1;}
return MINFONTSIZE+(value-rangeData.min)*(MAXFONTSIZE-MINFONTSIZE)/spread;},unit:'px',MAXFONTSIZE:MAXFONTSIZE,MINFONTSIZE:MINFONTSIZE});new Effect.Highlight(divId,{startcolor:'#FEECC7',endcolor:'#ffffff'});},TagCloud:function(){var DEFAULT_UNIT='%';var DEFAULT_TEXT_PROPERTY='text';var DEFAULT_VALUE_PROPERTY='value';var MAXFONTSIZE=35;var MINFONTSIZE=12;var gatherStatistics=function(data,config){if(data.length==0){var currentMax=12;var currentMin=12;}else{var currentMax=data[0][config.valueProperty];var currentMin=data[0][config.valueProperty];}
for(var i=0;i<data.length;i++){var value=data[i][config.valueProperty];currentMax=(currentMax<value)?value:currentMax;currentMin=(currentMin>value)?value:currentMin}
return{max:currentMax,min:currentMin,mid:(currentMax+currentMin)/2,unit:(currentMax-currentMin)/100};};var defaultScaler=function(value,rangeData){return((value/rangeData.max)*100)+100;};return{process:function(data,config){config=config||{};MAXFONTSIZE=config.MAXFONTSIZE||this.MAXFONTSIZE;MINFONTSIZE=config.MINFONTSIZE||this.MINFONTSIZE;config.unit=config.unit||DEFAULT_UNIT;config.textProperty=config.textProperty||DEFAULT_TEXT_PROPERTY;config.valueProperty=config.valueProperty||DEFAULT_VALUE_PROPERTY;var dataRange=gatherStatistics(data,config);var scaler=config.scaler||defaultScaler;for(var i=0;i<data.length;i++){var scale=scaler(data[i][config.valueProperty],dataRange);config.renderer(data[i][config.textProperty],scale,config.unit,data[i]['tagId']);}}};}(),Events:{TAGS_ADDED:"sd_tag:tags_added"}};
var Autocomplete=function(el,options){el=$(el);var instance=Autocomplete.getInstance(el.id);if(instance){if(options){Object.extend(instance.options,options);}
instance.el=el;!el.sdAutoCompleteEventsSet&&instance.setupEvents();return instance;}else{this.el=el;this.id=this.el.identify();this.el.setAttribute('autocomplete','off');this.suggestions=[];this.data=[];this.badQueries=[];this.selectedIndex=-1;this.currentValue=this.el.value;this.intervalId=0;this.cachedResponse=[];this.instanceId=null;this.onChangeInterval=null;this.ignoreValueChange=false;this.options={autoSubmit:false,minChars:1,maxHeight:300,deferRequestBy:0,width:300,container:null};if(options){Object.extend(this.options,options);}
this.serviceUrl=options.serviceUrl;if(Autocomplete.isDomLoaded){this.initialize();}else{Event.observe(document,'dom:loaded',this.initialize.bind(this),false);}}};Autocomplete.instances=[];Autocomplete.isDomLoaded=false;Autocomplete.getInstance=function(id){var instances=Autocomplete.instances;var i=instances.length;while(i--){if(instances[i].id===id){return instances[i];}}
return null;};Autocomplete.highlight=function(value,re){return value.replace(re,function(match){return'<strong>'+match+'<\/strong>'});};Autocomplete.prototype={killerFn:null,initialize:function(){var me=this;this.killerFn=function(e){if(!$(Event.element(e)).up('.tag-autocomplete')){me.killSuggestions();me.disableKillerFn();}}.bindAsEventListener(this);if(!this.options.width){this.options.width=this.el.getWidth();}
var div=new Element('div',{style:'position:absolute;z-index:10000; font-weight:normal;'});div.update('<div class="autocomplete-w1"><div class="autocomplete-w2"><div class="tag-autocomplete" id="Autocomplete_'+this.id+'" style="display:none;"></div></div></div>');this.options.container=$(this.options.container);if(this.options.container){this.options.container.appendChild(div);this.fixPosition=function(){};}else{document.body.appendChild(div);}
this.mainContainerId=div.identify();this.container=$('Autocomplete_'+this.id);this.setupEvents();this.container.setStyle({maxHeight:this.options.maxHeight+'px'});this.instanceId=Autocomplete.instances.push(this)-1;},setupEvents:function(){Event.observe(this.el,window.opera?'keypress':'keydown',this.onKeyPress.bind(this));Event.observe(this.el,'keyup',this.onKeyUp.bind(this));Event.observe(this.el,'blur',this.enableKillerFn.bind(this));Event.observe(this.el,'focus',this.fixPosition.bind(this));this.el.sdAutoCompleteEventsSet=true;},fixPosition:function(){var offset=this.el.cumulativeOffset();$(this.mainContainerId).setStyle({top:(offset.top+this.el.getHeight())+'px',left:offset.left+'px'});},enableKillerFn:function(){Event.observe(document.body,'click',this.killerFn);},disableKillerFn:function(){Event.stopObserving(document.body,'click',this.killerFn);},killSuggestions:function(){this.stopKillSuggestions();this.intervalId=window.setInterval(function(){this.hide();this.stopKillSuggestions();}.bind(this),300);},stopKillSuggestions:function(){window.clearInterval(this.intervalId);},onKeyPress:function(e){if(!this.enabled){return;}
switch(e.keyCode){case Event.KEY_ESC:this.el.value=this.currentValue;this.hide();break;case Event.KEY_TAB:case Event.KEY_RETURN:if(this.selectedIndex===-1){var ind=this.suggestions.indexOf(this.currentValue);if(ind!=-1){this.selectedIndex=ind;}else{this.hide();return;}}
this.select(this.selectedIndex);if(e.keyCode===Event.KEY_TAB){return;}
break;case Event.KEY_UP:this.moveUp();break;case Event.KEY_DOWN:this.moveDown();break;default:return;}
Event.stop(e);},onKeyUp:function(e){switch(e.keyCode){case Event.KEY_UP:case Event.KEY_DOWN:return;}
clearInterval(this.onChangeInterval);if(this.currentValue!==this.el.value){if(this.options.deferRequestBy>0){this.onChangeInterval=setInterval((function(){this.onValueChange();}).bind(this),this.options.deferRequestBy);}else{this.onValueChange();}}},onValueChange:function(){clearInterval(this.onChangeInterval);this.currentValue=this.el.value;this.selectedIndex=-1;if(this.ignoreValueChange){this.ignoreValueChange=false;return;}
if(this.currentValue===''||this.currentValue.length<this.options.minChars){this.hide();}else{this.getSuggestions();}},getSuggestions:function(){var cr=this.cachedResponse[this.currentValue];if(cr&&Object.isArray(cr.suggestions)){this.suggestions=cr.suggestions;this.data=cr.data;this.suggest();}else if(!this.isBadQuery(this.currentValue)){new Ajax.Request(this.serviceUrl,{parameters:{query:this.currentValue},onComplete:this.processResponse.bind(this),method:'get'});}},isBadQuery:function(q){var i=this.badQueries.length;while(i--){if(q.indexOf(this.badQueries[i])===0){return true;}}
return false;},hide:function(){this.enabled=false;this.selectedIndex=-1;this.container.hide();},suggest:function(){if(this.suggestions.length===0){this.hide();return;}
var content=[];var re=new RegExp('\\b'+this.currentValue.match(/\w+/g).join('|\\b'),'gi');this.suggestions.each(function(value,i){content.push((this.selectedIndex===i?'<div class="selected"':'<div'),' title="',value,'" onclick="Autocomplete.instances[',this.instanceId,'].select(',i,');" onmouseover="Autocomplete.instances[',this.instanceId,'].activate(',i,');">',Autocomplete.highlight(value,re),'</div>');}.bind(this));this.enabled=true;this.fixPosition();this.container.update(content.join('')).show();},processResponse:function(xhr){var response;try{response=xhr.responseJSON;if(!Object.isArray(response.data)){response.data=[];}}catch(err){return;}
this.cachedResponse[response.query]=response;if(response.suggestions.length===0){this.badQueries.push(response.query);}
if(response.query===this.currentValue){this.suggestions=response.suggestions;this.data=response.data;this.suggest();}},activate:function(index){var divs=this.container.childNodes;var activeItem;if(this.selectedIndex!==-1&&divs.length>this.selectedIndex){divs[this.selectedIndex].className='';}
this.selectedIndex=index;if(this.selectedIndex!==-1&&divs.length>this.selectedIndex){activeItem=divs[this.selectedIndex]
activeItem.className='selected';}
return activeItem;},deactivate:function(div,index){div.className='';if(this.selectedIndex===index){this.selectedIndex=-1;}},select:function(i){var selectedValue=this.suggestions[i];if(selectedValue){this.el.value=selectedValue;if(this.options.autoSubmit&&this.el.form){this.el.form.submit();}
this.ignoreValueChange=true;this.hide();this.onSelect(i);}},moveUp:function(){if(this.selectedIndex===-1){return;}
if(this.selectedIndex===0){this.container.childNodes[0].className='';this.selectedIndex=-1;this.el.value=this.currentValue;return;}
this.adjustScroll(this.selectedIndex-1);},moveDown:function(){if(this.selectedIndex===(this.suggestions.length-1)){return;}
this.adjustScroll(this.selectedIndex+1);},adjustScroll:function(i){var container=this.container;var activeItem=this.activate(i);var offsetTop=activeItem.offsetTop;var upperBound=container.scrollTop;var lowerBound=upperBound+this.options.maxHeight-25;if(offsetTop<upperBound){container.scrollTop=offsetTop;}else if(offsetTop>lowerBound){container.scrollTop=offsetTop-this.options.maxHeight+25;}
this.el.value=this.suggestions[i];},onSelect:function(i){(this.options.onSelect||Prototype.emptyFunction)(this.suggestions[i],this.data[i]);}};Event.observe(document,'dom:loaded',function(){Autocomplete.isDomLoaded=true;},false);
SD.Chat={_pageUI:null,_userPanelHash:{},_panelUserHash:{},_nPanel:0,showChatHistory:null,_me:null,_debugEnabled:false,_initialized:false,_lastKnownUserPresences:{},_lastSentTyping:{},_lastReceivedTyping:{},_history:{},_historyAnalyze:{},_panelLastSender:{},_linkRegex:/\b(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&amp;?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?\b/g,_iAmStreaming:{},_partnerIsStreaming:{},SEND_TYPING_INTERVAL:3000,_messageBuffer:'',hadTwoChatInLifetime:false,_startCameraRequests:{},_toggleWebcamLocks:{},TOGGLE_WEBCAM_BUTTON_LOCK_TIME:10000,WEBCAM_REQUEST_TIMEOUT:60000,init:function(){if(this._initialized){return;}
this._initialized=true;this._chatGUI=SD.UI.DateUI.getUI();this._me=SD.Model.getMyself();SD.Event.observe(null,SD.UI.DateUI.Events.MESSAGE_SEND,this._onPanelSend.bind(this));SD.Event.observe(null,SD.UI.DateUI.Events.INVITE_FB_CHAT,this._onPanelInviteFB.bind(this));SD.Event.observe(null,SD.UI.DateUI.Events.INPUT_RECEIVED,this._onUserInput.bind(this));SD.Event.observe(null,SD.UI.DateUI.Events.PANEL_CLOSED,this._onPanelClosed.bind(this));SD.Event.observe(null,SD.UIController.Events.START_CHAT_REQUESTED,this._onChatStartRequest.bind(this));SD.Event.observe(null,SD.User.Events.USER_ONLINE,this._onUserOnline.bind(this));SD.Event.observe(null,SD.User.Events.USER_OFFLINE,this._onUserOffline.bind(this));SD.Event.observe(null,SD.BuddyList.Events.USER_BLOCK_CONFIRMED,this._onUserBlocked.bind(this));SD.Event.observe(null,SD.UI.DateUI.Events.REPORT_REQUESTED,this._onReportRequest.bind(this));SD.Event.observe(null,SD.UI.DateUI.Events.BLOCK,this._onBlockRequest.bind(this));SD.Event.observe(null,SD.ChatMsgListener.Events.RECEIVED_OFFLINE_CHAT_MSGS,this._onReceiveOfflineMsg.bind(this));SD.Event.observe(null,SD.ChatMsgListener.Events.USER_TYPING,this._onUserTyping.bind(this));SD.Event.observe(null,SD.ChatMsgListener.Events.USER_PAUSED_TYPING,this._onUserPausedTyping.bind(this));SD.Event.observe(null,SD.ChatMsgListener.Events.SENT_OFFLINE_CHAT_MSG,this._onSentOfflineMsg.bind(this));SD.Event.observe(null,SD.ChatMsgListener.Events.NEW_MESSAGE,this._onMessageSent.bind(this));SD.Event.observe(null,SD.ClientUpdater.Events.NEW_FLIRT,this._onNewFlirt.bind(this));SD.Event.observe(null,SD.UI.DateUI.Events.WEBCAM_TOGGLE,this.toggleWebcam.bind(this));SD.Event.observe(null,SD.UI.DateUI.Events.ABUSE_REPORT,this._onReportAbuse.bind(this));SD.Event.observe(null,SD.BuddyList.Events.USER_BLOCK_CONFIRMED,this._onBlockConfirmed.bind(this));SD.Event.observe(null,SD.UI.DateUI.Events.SELECT_FRIEND_AS_OBSERVER,this._onAddFriendAsObserver.bind(this));SD.Event.observe(null,SD.UI.DateUI.Events.REMOVE_FRIEND_FROM_OBSERVING,this._onRemoveFriendFromObserving.bind(this));SD.Event.observe(null,SD.FbWingman.Events.START_OBSERVING,this._onStartObserving.bind(this));SD.Event.observe(null,SD.FbWingman.Events.STOP_OBSERVING,this._onStopObserving.bind(this));SD.Event.observe(null,SD.User.Events.SAVED_CHAT_MSG_AS_FLIRT,this._onSavedChatMsgAsFlirt.bind(this));},debug:function(txt){this._debugEnabled&&console.log(txt);},chatWithUser:function(user,dontActivate){SD.Event.fire(null,SD.UIController.Events.START_CHAT_REQUESTED,{user:user,dontActivate:dontActivate||false});},lazyChatWithUser:function(user){SD.Event.fire(null,SD.UIController.Events.START_CHAT_REQUESTED,{user:user,isConnecting:true});},getNumberOfPanels:function(){return this._nPanel;},getReadableNow:function(){var now=new Date();var hour=now.getHours();var min=now.getMinutes();if(min<10){min="0"+min;}
return hour+":"+min;},enableDebug:function(){this._debugEnabled=true;},disableDebug:function(){this._debugEnabled=false;},displayInfoMessage:function(otherUser,msg,showIfNoWindow){var panelId=this._getUserPanelId(otherUser,showIfNoWindow);if(panelId){this._putMessage(panelId,{message:msg,template:SD.UI.Dating.MessagePaneTemplates.ENUM.INFO_MESSAGE});this.clearStaticMessage(panelId);}},_onNewFlirt:function(e){if(!e.memo.text||e.memo.text.trim().length==0){return;}
var sender=SD.User.get(e.memo.uid);if(!SD.Chat.amIChattingWith(sender)&&SD.ExperimentManager.PauseChats_4457.value&&SD.DatingController._pc.amIdle()==false){return;};SD.ExperimentManager.getExperimentValue(SD.ExperimentManager.SaveExtraChatMsgsAsFlirt_4456,function(windowLimit){SD.User.fetch(sender,function(sender){var showMessage=windowLimit==0||this.amIChattingWith(sender)||this.getNumberOfPanels()<windowLimit;if(!showMessage){return;}
this.displayInfoMessage(sender,"You just received an email message:",true);var text=e.memo.text;var panelId=this._getUserPanelId(sender,true);this._putMessage(panelId,{time:this.getReadableNow(),from:sender.username,message:text.escapeHTML().gsub('\n','<br/>'),template:SD.UI.Dating.MessagePaneTemplates.ENUM.FLIRT_MESSAGE});this.activateUserPanel(sender,true);}.bind(this));}.bind(this));},activateUserPanel:function(user,createIfNotExists){var panelId=this._getUserPanelId(user,!!createIfNotExists);if(panelId){this._chatGUI.setActivePanel(panelId);}},_onReceiveOfflineMsg:function(e){var msgs=e.memo;msgs.reverse();var senderMsgs={};msgs.each(function(msg){if(!senderMsgs[msg.from]){senderMsgs[msg.from]=[];}
senderMsgs[msg.from].push(msg);});for(var uid in senderMsgs){var sender=SD.User.get(uid);SD.User.fetch(sender,function(sender){var panelId=this._getUserPanelId(sender,true);var msgs=senderMsgs[sender.uid];this.displayInfoMessage(sender,"Message that were sent when you were offline");msgs.each(function(msg){this._putMessage(panelId,{time:msg.time,from:sender.username,message:msg.text.escapeHTML().gsub('\n','<br/>'),meOther:'other',template:SD.UI.Dating.MessagePaneTemplates.ENUM.OFFLINE_MESSAGE});}.bind(this));}.bind(this));}},_onAddFriendAsObserver:function(e){var panelId=e.memo.panelId;var user=this._getPanelUser(panelId);if(user){return SD.FbWingman.addFriendAsObserver(user,e.memo.friend);}},_onStartObserving:function(e){var user=e.memo.user;var friend=e.memo.friend;if(!user||!friend){return;}
var panelId=this._getUserPanelId(user);if(!panelId){return;}
var panel=this._chatGUI.getPanelById(panelId);if(panel){panel.setObserver(friend);}},_onRemoveFriendFromObserving:function(e){var panelId=e.memo.panelId;var user=this._getPanelUser(panelId);if(user){SD.FbWingman.removeFriendFromObserving(user);}},_onStopObserving:function(e){var user=e.memo.user;if(!user){return;}
var panelId=this._getUserPanelId(user);if(!panelId){return;}
var panel=this._chatGUI.getPanelById(panelId);if(panel){panel.removeObserver();}},_onSentOfflineMsg:function(e){var text=e.memo.text;var receiver=SD.User.get(e.memo.receiverUid);var panelId=this._getUserPanelId(receiver);panelId&&this._putMessage(panelId,{message:text.escapeHTML().gsub('\n','<br/>'),template:SD.UI.Dating.MessagePaneTemplates.ENUM.CHAT_MESSAGE_FLIRT,from:receiver.username});},_onUserOnline:function(e){var user=e.memo.user;if(!user){return;}
var panelId=this._getUserPanelId(user);if(this._lastKnownUserPresences[user.uid]===false&&panelId){this._putMessage(panelId,{isOnline:'online',message:user.username+" returned online",template:SD.UI.Dating.MessagePaneTemplates.ENUM.PRESENCE_MESSAGE});SD.XMPP.sendDirectPresence(user);}
this._lastKnownUserPresences[user.uid]=true;if(panelId){this._chatGUI.setIconState(panelId,SD.UI.Dating.Tab.ICON_STATE_CHAT);}},_onUserOffline:function(e){var user=e.memo.user;if(!user){return;}
var panelId=this._getUserPanelId(user);var heShe=user.sex=='F'?'she':(user.sex=='M'?'he':'he/she');if(this._lastKnownUserPresences[user.uid]===true&&panelId){if(user.im_online){this._putMessage(panelId,{isOnline:'offline',message:user.username+" is online on their instant messenger. We'll deliver your messages via IM notifications on real time.",template:SD.UI.Dating.MessagePaneTemplates.ENUM.PRESENCE_MESSAGE});}else{this._putMessage(panelId,{isOnline:'offline',message:user.username+" went offline. If "+heShe+" does not come back, we'll deliver your messages via email.",template:SD.UI.Dating.MessagePaneTemplates.ENUM.PRESENCE_MESSAGE});}}
if(panelId){if(user.im_online){}else{this._chatGUI.setIconState(panelId,SD.UI.Dating.Tab.ICON_STATE_OFFLINE);}}
this._lastKnownUserPresences[user.uid]=false;},_updateUserProfile:function(user){var panelId=this._getUserPanelId(user);if(!panelId){return;}
if(!SD.Model.getMyself().is_premium){this._chatGUI.showBanner(panelId);this._chatGUI.putBannerContent(panelId,'<div class="chat-banner">'+SD.UI.Dating.MessagePaneTemplates.banner2.interpolate({uid:user.uid})+'</div>');}
var online=user.online||user.im_online;this._chatGUI.setIconState(panelId,online?SD.UI.Dating.Tab.ICON_STATE_CHAT:SD.UI.Dating.Tab.ICON_STATE_OFFLINE);},_onChatStartRequest:function(e){var other=e.memo.user;if(other){SD.User.fetch(other,function(other){var panelId=this._getUserPanelId(other);if(panelId){!e.memo.dontActivate&&this._chatGUI.setActivePanel(panelId);}else{this._addUserPanel(other,!e.memo.dontActivate);}}.bind(this));}},_onPanelSend:function(e){var panelId=e.memo.panelId;var receiver=this._getPanelUser(panelId);if(!receiver){this.debug("panel send w/o a valid user ???. onPanelSend");return;}
if(!e.memo.message||e.memo.message.trim()==""){this.debug("trying to send empty message ?");return;}
delete this._lastSentTyping[receiver.uid];var canSendMsg=SD.UserInitiatedDate.onPanelSend(panelId);if(canSendMsg===false){return;}
if(canSendMsg!==true&&!receiver.is_premium&&!this._me.is_premium&&!receiver.isMobile()&&!receiver.isFacebookUser()){if(receiver.im_online){SD.ChatMsgListener.sendMessageAsImNotification(receiver,e.memo.message.escapeHTML());}
if(canSendMsg==="wait_for_match"){this._putMessage(e.memo.panelId,{uid:receiver.uid,message:e.memo.message.escapeHTML().gsub('\n','<br/>'),template:SD.UI.Dating.MessagePaneTemplates.ENUM.CHAT_UPGRADE_OR_MATCH_TO_SEND});}else{this._putMessage(e.memo.panelId,{uid:receiver.uid,message:e.memo.message.escapeHTML().gsub('\n','<br/>'),template:SD.UI.Dating.MessagePaneTemplates.ENUM.CHAT_UPGRADE_ON_SEND});}
return;}
SD.ChatMsgListener.sendMessage(receiver,e.memo.message);},_onPanelInviteFB:function(e){var panelId=e.memo.panelId;var receiver=this._getPanelUser(panelId);if(!receiver){this.debug("panel send w/o a valid user ???. onPanelSend");return;}
SD.Event.fire(null,SD.FBChat.Events.INVITE_FRIEND,{user:receiver,source:"chat-window"});},_onUserInput:function(e){var receiver=this._getPanelUser(e.memo.panelId);if(!receiver){this.debug("panel send w/o a valid user ???. onUserInput");return;}
if(e.memo.message&&e.memo.message.length){var now=new Date().getTime();if(!this._lastSentTyping[receiver.uid]||this._lastSentTyping[receiver.uid]+this.SEND_TYPING_INTERVAL<now){SD.ChatMsgListener.sendTyping(receiver);this._lastSentTyping[receiver.uid]=now;}}else{delete this._lastSentTyping[receiver.uid];SD.ChatMsgListener.sendPausedTyping(receiver);}},_onUserTyping:function(e){var other=e.memo.user;var panelId=this._getUserPanelId(other);if(panelId){var now=new Date().getTime();this._lastReceivedTyping[other.uid]=now;this._putMessage(panelId,{name:other.username,mode:'staticMessage',template:SD.UI.Dating.MessagePaneTemplates.ENUM.TYPING_MESSAGE});this._cleanTyping.bind(this).delay(6,other.uid,panelId);this._chatGUI.setIconState(panelId,SD.UI.Dating.Tab.ICON_STATE_WRITING);}},_cleanTyping:function(uid,panelId){var now=new Date().getTime();var last=this._lastReceivedTyping[uid];if(last+5000>now){return;}
this.clearStaticMessage(panelId);},_onUserPausedTyping:function(e){var other=e.memo.user;var panelId=this._getUserPanelId(other);panelId&&this.clearStaticMessage(panelId);if(panelId){var online=other.online||(other.im_online);this._chatGUI.setIconState(panelId,online?SD.UI.Dating.Tab.ICON_STATE_CHAT:SD.UI.Dating.Tab.ICON_STATE_OFFLINE);}},_onPanelClosed:function(e){this._deletePanel(e.memo.panelId);},_onAllPanelsClosed:function(e){this._deleteAllPanels();},_onMessageSent:function(e){var msg=e.memo;if(msg.sender&&msg.receiver&&msg.text){this._displayMessage(msg.sender,msg.receiver,msg.text,e.memo.dontBlink==true);}},addMsgFrom:function(from,text){this._displayMessage(from,this._me,text);},addToHistoryFromDate:function(sender,receiver,text){this._addToHistory(sender,receiver,text,{isDate:true});},_onSavedChatMsgAsFlirt:function(e){this._addToHistory(e.memo.sender,this._me,e.memo.text,{isNotShown:true});},createChatHistoryMsg:function(sender,receiver,text,time){time=time||Date.now();return{uid:sender.uid,text:text,receiverUid:receiver.uid,time:time};},_addToHistory:function(sender,receiver,text,options){options=options||{};options.isDate=options.isDate||false;options.isNotShown=options.isNotShown||false;var other=sender==this._me?receiver:sender;if(!this._history[other.uid]){this._history[other.uid]=[];}
this._history[other.uid].push(this.createChatHistoryMsg(sender,receiver,text));if(!this.hadTwoChatInLifetime){if(!this._historyAnalyze[sender.uid+"-"+receiver.uid]&&this._historyAnalyze[receiver.uid+"-"+sender.uid]){this.hadTwoChatInLifetime=true;new Ajax.Request(SD.NavUtils.link('ajax','had_first_two_way_chat'),{method:'get',parameters:{},onSuccess:function(e){}.bind(this),onFailure:function(e){}.bind(this)});};}
if(!options.isNotShown&&!options.isDate&&!this._historyAnalyze[sender.uid+"-"+receiver.uid]){if(this._historyAnalyze[receiver.uid+"-"+sender.uid]){SD.ExperimentManager.recordOutput('ChatValidOutput',1,1);SD.Event.fire(null,this.Events.BOTH_TYPED,{other:other});}else{SD.ExperimentManager.recordOutput('ChatInitiatedOutput',1,1);}
this._historyAnalyze[sender.uid+"-"+receiver.uid]=true;if(SD.Notification.IM.didRequestChat(sender.uid)){SD.ExperimentManager.recordOutput('UserGotReplyFromChatReq',1,1);}}else if(options.isNotShown){SD.ExperimentManager.recordOutput('ChatSavedChatAsFlirt',1,1);}},getHistory:function(other,asText){var msgs=this._history[other.uid]||[];return asText?msgs.collect(function(msg){return SD.User.get(msg.uid).username+":"+msg.text;}).join('\n'):msgs;},validateMessage:function(me,other,text,isMeSender){var panelId=this._getUserPanelId(other,true);var isUserInitiatedDate=SD.UserInitiatedDate.isActiveDate(panelId);if(other.isFacebookUser()){return true;}else if(!isMeSender){if(!other.is_premium&&!SD.UserInputFilter.isValid(text)){return false;}}else{this._messageBuffer+=text;if(!me.is_premium&&!SD.UserInputFilter.isValid(this._messageBuffer)){this._messageBuffer='';SD.UserInputFilter.trackFilter(SD.UserInputFilter.CHAT);if(isUserInitiatedDate){SD.ExperimentManager.recordOutput('UserInputFilteredFromDateOutput',1,1);}else{SD.ExperimentManager.recordOutput('UserInputFilteredFromChatOutput',1,1);}
return false;}}
return true;},_displayMessage:function(sender,receiver,text,dontBlink){var other=sender.uid==this._me.uid?receiver:sender;SD.User.fetch(other,function(other){var panelId=this._getUserPanelId(other);if(!panelId&&SD.UserInitiatedDate.hasPendingDate(other)){SD.UserInitiatedDate.startPendingDate(other,true,text);return;}
panelId=this._getUserPanelId(other,true);var isUserInitiatedDate=SD.UserInitiatedDate.isActiveDate(panelId);if(isUserInitiatedDate){SD.UserInitiatedDate.startTimerIfNecessary(other);}
if(sender!=this._me&&sender.is_premium==false&&!isUserInitiatedDate){SD.User.fetch(sender,null,null,true);}
var isMeSender=(sender==this._me);var isValid=this.validateMessage(this._me,other,text,isMeSender);if(!isMeSender&&!isValid){return;}
this._putMessage(panelId,{from:sender==this._me?'me':other.username,meOther:sender==this._me?'me':'other',message:text.escapeHTML().gsub('\n','<br/>'),time:this.getReadableNow(),template:this._panelLastSender[panelId]==sender?SD.UI.Dating.MessagePaneTemplates.ENUM.CHAT_MESSAGE_CONT:SD.UI.Dating.MessagePaneTemplates.ENUM.CHAT_MESSAGE},dontBlink);if(!dontBlink){if(this._me!=sender){SD.Favicon.animateTitle([other.username+" says:",text]);this.clearStaticMessage(panelId);}
SD.Date.playMessageSound();this._addToHistory(sender,receiver,text);}
this._panelLastSender[panelId]=sender;}.bind(this));},clearStaticMessage:function(panelId){var user=this._getPanelUser(panelId);if(!user){return;}
var online=user.online||user.im_online;this._chatGUI.setIconState(panelId,online?SD.UI.Dating.Tab.ICON_STATE_CHAT:SD.UI.Dating.Tab.ICON_STATE_OFFLINE);this._chatGUI.clearStaticMessage(panelId);},_addUserPanel:function(user,activate){if(SD.UserInitiatedDate.hasPendingDate(user)){return this._addUserDatePanel(user);}
return this._getUserPanelId(user,true,activate);},_addUserDatePanel:function(user){if(SD.UserInitiatedDate.hasPendingDate(user)){var pid=this._getUserPanelId(user,true,true,true);SD.UserInitiatedDate.onPanelOpenForPendingDate(user,pid);return pid;}
return this._getUserPanelId(user,true,true,true);},openDateChatPanel:function(otherUser){if(this._getUserPanelId(otherUser)){return null;}
return this._addUserDatePanel(otherUser);},openIphoneDatePanel:function(otherUser){if(this._getUserPanelId(otherUser)){return null;}
var openWindow=this._me.sex=="M"||this._me.sex_pref=="F";this.displayInfoMessage(otherUser,otherUser.username+" started a chat with you from "+otherUser.toHisHer()+" Iphone, say hi!",openWindow);},_getUserPanelId:function(user,createIfNotExists,activate,isDatePanel){if(!this._userPanelHash[user.uid]&&createIfNotExists){var options={meta:{user:user},dateHeader:{name:user.username.truncate(25),age:user.age,location:SD.User.renderLocation(user),distance:SD.User.renderDistance(user)},pictureGallery:{_url:SD.NavUtils.link('profile','view_images',{displayType:'ajax',uid:user.uid})},pictureGalleryV2:{_url:SD.NavUtils.link('profile','view_images',{displayType:'ajax',uid:user.uid,newMemberBadge:true})},dateProfile:{_url:SD.NavUtils.link('profile','view_profile',{displayType:'ajax',uid:user.uid})},dateProfileV1:{_url:SD.NavUtils.link('profile','view_facebook_friend_profile',{displayType:'ajax',friendId:user.getFacebookUserId()})},dateProfileV2:{_url:SD.NavUtils.link('profile','view_profile',{displayType:'ajax',uid:user.uid,ver:2})},dateProfileV3:{_url:SD.NavUtils.link('profile','view_profile',{displayType:'ajax',uid:user.uid,ver:3})},dateProfileFbFriend:{_url:SD.NavUtils.link('profile','view_profile',{displayType:'ajax',uid:user.uid,ver:3})},dateToolbar:{isPremium:SD.Model.getMyself().is_premium,showExtendDateButton:true},preferredAsl:{},tabData:{text:user.username.truncate(15)}};var ui=null;ui=ui||this._pageUI;var pid=isDatePanel?this._chatGUI.openPanel(options,ui):this._chatGUI.openChatPanel(options,activate,ui);this._userPanelHash[user.uid]=pid;this._panelUserHash[pid]=user.uid;this._nPanel++;var panel=this._chatGUI.getPanelById(pid);panel.getClock&&panel.getClock().hide();panel.hideExtendDate();this._history[user.uid]=this._history[user.uid]||[];SD.XMPP.sendDirectPresence(user);this._updateUserProfile(user);var that=this;var addHistory=function(time){time=time||Date.now();if(SD.ExperimentManager.HistoryInChatWindow_3487.value&&!user.isFacebookUser()){that._putMessage(pid,{template:SD.UI.Dating.MessagePaneTemplates.ENUM.CHAT_HISTORY_BUTTON,uid:user.uid,panelId:pid});}
var msgs=that.getHistory(user);msgs.each(function(msg){if(msg.time<time){that._displayMessage(SD.User.get(msg.uid),SD.User.get(msg.receiverUid),msg.text,true);}}.bind(that));};if(isDatePanel){addHistory.delay(1,Date.now());}else{addHistory();}
if(user.isFacebookUser()){SD.ExperimentManager.recordOutput('ChatWithFacebookFriend',1,1);}else{new Ajax.Request(SD.NavUtils.link('ajax','on_create_chat_window'),{method:'get',parameters:{other_memberid:user.uid},onSuccess:function(e){}.bind(this),onFailure:function(e){}.bind(this)});}
SD.Event.fire.bind(SD.Event).delay(5,null,SD.ClientUpdater.Events.NEW_VIEW,{uid:user.uid});}
return this._userPanelHash[user.uid];},_onReportAbuse:function(e){var otherUser=this._getPanelUser(e.memo.panelId);if(!otherUser){return;}
SD.Date.reportMember(otherUser.uid,e.memo.data.reason,'chatHistory');SD.ExperimentManager.recordOutput('DateReportedByMeOutput',1,1);},_onBlockConfirmed:function(e){var other=e.memo.user;if(!other){return;}
SD.Chat.closeUserPanel(other);},_getPanelUser:function(panelId){var uid=this._panelUserHash[panelId];return uid&&SD.User.get(uid);},_deletePanel:function(panelId){var uid=this._panelUserHash[panelId];if(uid){delete this._panelUserHash[panelId];delete this._userPanelHash[uid];this._nPanel--;SD.Event.fire(null,this.Events.PANEL_CLOSED,{user:SD.User.get(uid)});}},_deleteAllPanels:function(){for(var panelId in this._panelUserHash){this._deletePanel(panelId);}},closeUserPanel:function(user){var panelId=this._getUserPanelId(user);panelId&&this._chatGUI.closePanel(panelId);},_reportUser:function(user){SD.UIController.reportUserPopup(user,{source:'chat','chatHistory':this.getHistory(user,true),onDone:function(result){if(result){var panelId=this._getUserPanelId(user);panelId&&this._chatGUI.closePanel(panelId);}}.bind(this)});},_onReportRequest:function(e){var panelId=e.memo.panelId;var user=this._getPanelUser(panelId);if(user){this._reportUser(user);}},_onUserBlocked:function(e){var other=e.memo.user;var panelId=this._getUserPanelId(other);if(panelId){this._chatGUI.closePanel(panelId);}},_blockUser:function(user){SD.Event.fire(null,SD.UIController.Events.BLOCK_BUDDY_REQUESTED,{user:user});},_onBlockRequest:function(e){var panelId=e.memo.panelId;var user=this._getPanelUser(panelId);if(user){this._blockUser(user);}},_putMessage:function(panelId,data,dontBlink){this._chatGUI.putMessage(panelId,data,dontBlink);},hideMsgForUser:function(uid){},showMsgForUser:function(msg,uid){var user=SD.User.get(uid);this.displayInfoMessage(user,msg,true);},amIChattingWith:function(user){return!!this._getUserPanelId(user);},removeUser:function(uid){var user=SD.User.get(uid);var panelId=this._getUserPanelId(user);panelId&&this._deletePanel(panelId);},_onUpgradeClicked:function(e){var panelId=e.memo.panelId;var user=this._getPanelUser(panelId);SD.UIController.upgradeMyself({"ti":user&&user.uid,"tc":SD.TrackingCodes.trigger.banner.chat_popup._value});},toggleWebcam:function(e){var panelId=e.memo.panelId;var user=this._getPanelUser(panelId);if(user.isFacebookUser()){this.displayInfoMessage(user,"Invite "+user.username+" to SpeedDate to enable video chat!",false);}else if(user.isMobile()){this.displayInfoMessage(user,user.username+"'s client does not support video chat :(");}else if(this._iAmStreaming[user.uid]){SD.RPC.call(user,'SD.Chat.__receiveCameraState',{state:'off'});SD.UI.DateUI.getUI().getWebcamDom(panelId).stopCamera();this._iAmStreaming[user.uid]=false;SD.UI.DateUI.getUI().setWebcamButText(panelId,'start webcam');if(!this._partnerIsStreaming[user.uid]){SD.UI.DateUI.getUI().hideWebcamPane(panelId);}}else{var now=(new Date()).getTime();if(this._toggleWebcamLocks[user.uid]&&this._toggleWebcamLocks[user.uid]>now-this.TOGGLE_WEBCAM_BUTTON_LOCK_TIME){return;}
this._toggleWebcamLocks[user.uid]=now;this.displayInfoMessage(user,"Asking "+user.username+" if "+user.toHeShe()+" wants to watch your webcam video");SD.RPC.call(user,'SD.Chat.__receiveCameraState',{state:'on'},function(response){if(this._iAmStreaming[user.uid]){return;}
panelId=this._getUserPanelId(user);if(!panelId){SD.RPC.call(user,'SD.Chat.__receiveCameraState',{state:'off'});return;}
var defaultError="Could not initialize a video chat with "+user.username;if(response){if(response.result){var changeView=function(){SD.Chat._iAmStreaming[user.uid]=true;SD.UI.DateUI.getUI().setWebcamButText(panelId,'stop webcam');SD.UI.DateUI.getUI().getWebcamDom(panelId).startCamera();SD.UI.DateUI.getUI().getWebcamDom(panelId).publishStream(SD.Config.defaultDatingServers[0],'stream'+SD.Model.getMyself().uid);};if(this._partnerIsStreaming[user.uid]){changeView();}else{SD.UI.DateUI.getUI().showWebcamPane(panelId,changeView.bind(this));}
this.displayInfoMessage(user,user.username+" accepted your webcam video request");}else{if(response.errorCode=="rejected"){this.displayInfoMessage(user,user.username+" declined your webcam video request");}else if(response.errorCode=="duplicateIgnore"){return;}
else if(response.error){this.displayInfoMessage(user,response.error);}else{this.displayInfoMessage(user,defaultError);}}}else{this.displayInfoMessage(user,defaultError);}}.bind(this),{async:true,timeout:this.WEBCAM_REQUEST_TIMEOUT});}},__fbWingmanMsg:function(other,data){this.displayInfoMessage(other,data.msg,true);},__receiveCameraState:function(user,params,callback){var state=params.state;var panelId=this._userPanelHash[user.uid];if(!panelId){var resp={result:false,error:this._me.username+" does not have an active chat window with you. Try starting a conversation first."};callback&&callback(resp);return resp;}
if(state=='on'){this._displayStartCameraRequest(user,callback);}else{this._partnerIsStreaming[user.uid]=false;if(!this._iAmStreaming[user.uid]){SD.UI.DateUI.getUI().hideWebcamPane(panelId);}else{SD.UI.DateUI.getUI().getWebcamDom(panelId).hideStream();}}
if(!callback){return resp={result:true};}},_displayStartCameraRequest:function(user,callback){SD.ExperimentManager.getExperimentValue(SD.ExperimentManager.VideoChatPermissions_3858,function(exp){var cb=this._startCameraRequests[user.uid];if(cb){cb({result:false,errorCode:"duplicateIgnore"});}
this._startCameraRequests[user.uid]=callback;if(exp==0){this.respondToCameraRequest(user.uid,true);}else{this._removeCameraRequestElements(user.uid);var panelId=this._getUserPanelId(user);SD.UI.DateUI.getUI().putMessage(panelId,{from:user.username,template:SD.UI.Dating.MessagePaneTemplates.ENUM.VIDEO_START_CONFIRM,yesCallback:"SD.Chat.respondToCameraRequest("+user.uid+",1)",noCallback:"SD.Chat.respondToCameraRequest("+user.uid+",0)",other_uid:user.uid});}}.bind(this));},_removeCameraRequestElements:function(uid){var elms=$$('[sdType="video-start-respose-dialog"][sdUid='+uid+']');elms.each(function(elm){elm.parentNode.remove();});},respondToCameraRequest:function(uid,answer){this._removeCameraRequestElements(uid);var cb=this._startCameraRequests[uid];if(!cb){return;}
delete this._startCameraRequests[uid];var user=SD.User.get(uid);var panelId=this._userPanelHash[uid];if(answer){cb({result:true});this._partnerIsStreaming[user.uid]=true;if(this._iAmStreaming[user.uid]){SD.UI.DateUI.getUI().getWebcamDom(panelId).subscribeStream(SD.Config.defaultDatingServers[0],'stream'+user.uid);}else{SD.UI.DateUI.getUI().showWebcamPane(panelId,function(){SD.UI.DateUI.getUI().getWebcamDom(panelId).subscribeStream(SD.Config.defaultDatingServers[0],'stream'+user.uid);});SD.UI.DateUI.getUI().putMessage(panelId,{from:user.username,template:SD.UI.Dating.MessagePaneTemplates.ENUM.VIDEO_INVITATION});}}else{cb({result:false,errorCode:"rejected"});this.displayInfoMessage(user,"Webcam share declined.");}},minimize:function(){this.debug("wanted to minimize chat ?");},didIChatBefore:function(uid){return this._history[uid];},needUpgradeForChat:function(oUser){return!(SD.Model.getMyself().is_premium||SD.Chat.didIChatBefore(oUser.uid));},Events:{BOTH_TYPED:"sd_chat:both_typed",PANEL_CLOSED:"sd_chat:window_closed"},UI:{hideMsgForUser:function(uid){SD.Chat.hideMsgForUser(uid);},removeUser:function(uid){SD.Chat.removeUser(uid);},showMsgForUser:function(msg,uid){SD.Chat.showMsgForUser(msg,uid);}}};
SD.Chat.History={_loadedHistories:{},loadCompleteChatHistory:function(other,callback){if(this._loadedHistories[other.uid]){callback(this._loadedHistories[other.uid]);return;}
new Ajax.Request(SD.NavUtils.link('ajax','get_chat_history'),{method:'get',parameters:{otherId:other.uid},onSuccess:function(e){if(e&&e.responseJSON&&e.responseJSON.result){this.syncMessagesToLocalTime(e.responseJSON.msgs,e.responseJSON.serverTime);this._loadedHistories[other.uid]=e.responseJSON.msgs;callback&&callback(this._loadedHistories[other.uid]);}else{callback&&callback(null);}}.bind(this),onFailure:function(e){}.bind(this)});},syncMessagesToLocalTime:function(messages,serverTime){var timeDiff=parseInt(Date.now()/1000)-serverTime;messages.each(function(msg){msg.intTime+=timeDiff;});},_onHistoryReceived:function(response,callback){var serverTime=response.serverTime;var msgs=response.msgs;var otherId=response.otherId;var now=parseInt(Date.now()/1000);var timeDiff=now-serverTime;this._loadedHistories[otherId]=[];msgs.map(function(msg){msg.time=msg.time+timeDiff;this._loadedHistories[otherId].push(SD.Chat.createChatHistoryMsg(msg.from,msg.to,msg.text,msg.time));}.bind(this));callback&&callback(this._loadedHistories[otherId]);},addRecords:function(uid,records,insertionPoint){if(Object.prototype.toString.call(records)!=="[object Array]"){records=[records];}
if(!this._loadedHistories[uid]){this._loadedHistories[uid]=[];}
insertionPoint=(typeof insertionPoint==='undefined')?this._loadedHistories[uid].length:insertionPoint;[].splice.apply(this._loadedHistories[uid],[insertionPoint,0].concat(records));},getRecords:function(uid){return this._loadedHistories[uid]||[];}};
SD.Communication=SD.Communication||{};SD.Communication.History={_loadedHistories:{},loadCommunicationHistory:function(otherUser,callback){if(this._loadedHistories[otherUser.uid]){callback(this._loadedHistories[otherUser.uid]);return;}
new Ajax.Request(SD.NavUtils.link('ajax','get_communication_history'),{method:'get',evalJSON:true,parameters:{otherId:otherUser.uid},onSuccess:function(e){if(e&&e.responseJSON&&e.responseJSON.result){this._onHistoryReceived(e.responseJSON,callback);}else{callback&&callback(null);}}.bind(this),onFailure:function(e){}.bind(this)});},_onHistoryReceived:function(response,callback){var msgs=response.msgs;var otherId=response.otherId;this._loadedHistories[otherId]={favorite:msgs.favorite,messages:msgs.messages,msgCount:response.msgCount}
callback&&callback(this._loadedHistories[otherId]);},addRecords:function(uid,section,records,insertionPoint){if(Object.prototype.toString.call(records)!=="[object Array]"){records=[records];}
if(!this._loadedHistories[uid]){this._loadedHistories[uid]={};}
if(!this._loadedHistories[uid][section]){this._loadedHistories[uid][section]=[];}
insertionPoint=(typeof insertionPoint==='undefined')?this._loadedHistories[uid][section].length:insertionPoint;[].splice.apply(this._loadedHistories[uid][section],[insertionPoint,0].concat(records));this._loadedHistories[uid].msgCount=(this._loadedHistories[uid].msgCount||0)+records.length;},getRecords:function(uid){return this._loadedHistories[uid]||{};}};
$speeddate=function(attr){attr=attr||{};attr['xmlns']='nd.speeddate.com';return $iq(attr);}
ND={_initialized:false,_connection:null,_presences:{},BOSH_SERVICE:'http://kiki.speeddate.com:7900/http-bind/',PING_WAIT:3000,PING_FAIL_LIMIT:2,_pastDates:[],_currentDate:null,_dateStarted:false,_lastReceivedTyping:{},TYPING_CLEAN_INTERVAL:5000,_lastSentTyping:{},TYPING_SEND_INTERVAL:3000,_timer:null,_timerStartTime:0,_waitingPings:[],DATE_DURATION:60,_state:null,_reporteds:[],ENABLE_REDATE:true,STATES:{DATING:"dating",LOOKING_FOR_A_DATE:"looking_for_a_date",PAUSED_DATING:"paused_dating",NEGOTIATING:"negotiating"},getNow:function(){return new Date().getTime();},debug:function(txt){},init:function(){this.debug("init");if(this._initialized){return;}
this._state=this.STATES.PAUSED_DATING;this.BOSH_SERVICE='http://'+SD.Config.XMPPServer.serverURL+':7900/http-bind/';this._connection=new Strophe.Connection(this.BOSH_SERVICE);this._connection.rawInput=this._rawInput.bind(this);this._connection.rawOutput=this._rawOutput.bind(this);this._connection.addHandler(this._onSDIQ.bind(this),'nd.speeddate.com');this._connection.addHandler(this._onPing.bind(this),'urn:xmpp:ping');this._connection.addHandler(this._onMessage.bind(this),null,'message','chat');new PeriodicalExecuter(this._pingControl.bind(this),3);new PeriodicalExecuter(this._goOnlineRetry.bind(this),10);this._connect();this._initialized=true;},_connect:function(){this._connection.connect("","",this._onConnect.bind(this));new PeriodicalExecuter(this._checkConnection.bind(this),30);},_checkConnection:function(){if(!this._connection.authenticated){this._connect();}},isConnected:function(){return this._connection.authenticated;},_startTimer:function(){if(this._timer){this._timer.stop();}
this._timer=new PeriodicalExecuter(this._onEverySecond.bind(this),1);this._timerStartTime=this.getNow();},_onEverySecond:function(){if(!this._currentDate){this._timer.stop();}
var secs=(this.getNow()-this._timerStartTime)/1000;secs=Math.round(secs);var remSecs=this.DATE_DURATION-secs;var remMins=parseInt(remSecs/60);if(remSecs<=0){this.endDate(this.ReasonCodes.TIME_FINISHED);}
remSecs=Math.max(remSecs%60,0);if(remSecs<10){remSecs="0"+remSecs;}
document.fire(this.Events.REMAINING_TIME,{remainingMinutes:remMins,remainingSeconds:remSecs});this.debug("time:"+remMins+":"+remSecs);},_onSDIQ:function(iq){var from=iq.getAttribute('from');Strophe.forEachChild(iq,'datefound',function(e){this._onDateFound(from,e)}.bind(this));Strophe.forEachChild(iq,'datereq',function(e){this._onDateReq(from,e)}.bind(this));Strophe.forEachChild(iq,'dateresp',function(e){this._onDateResp(from,e)}.bind(this));Strophe.forEachChild(iq,'terminate',function(e){this._onTerminate(from,e)}.bind(this));return true;},_goOnlineRetry:function(e){if(this._state==this.STATES.LOOKING_FOR_A_DATE){this.findDate();}},_onDateFound:function(from,e){this.debug("DATE FOUND!");var match=e.getAttribute('match');if(match){if(this._shouldIDate(match)){this._askToDate(match);}else{this._setState(this.STATES.LOOKING_FOR_A_DATE);}}},_onConnect:function(status){this.debug("onConnect! : "+status);switch(status){case Strophe.Status.CONNECTED:document.fire(this.Events.CONNECT,{});break;case Strophe.Status.AUTHFAIL:case Strophe.Status.CONNFAIL:case Strophe.Status.DISCONNECTED:this._connect();break;}
return true;},_rawInput:function(data){this.debug('RECV: '+data);},_rawOutput:function(data){this.debug('SENT: '+data);},_startDate:function(otherJid){this.debug('start Date'+otherJid);this._currentDate=otherJid;this._dateStarted=true;this._setState(this.STATES.DATING);document.fire(this.Events.START_DATE,{otherJid:otherJid});this._startTimer();},_endDate:function(reasonCode){if(this._currentDate==null){return;}
var reasonCode=reasonCode||this.ReasonCodes.OTHER_DISCONNECTED;this.debug('end Date');var oldDate=this._currentDate;this._dateStarted&&this._pastDates.push(this._currentDate);this._currentDate=null;if(this._dateStarted){this._dateStarted=false;this._setState(this.STATES.PAUSED_DATING);document.fire(this.Events.END_DATE,{otherJid:oldDate,reasonCode:reasonCode});}else{this._setState(this.STATES.LOOKING_FOR_A_DATE);}},_onMessage:function(msg){var otherJid=msg.getAttribute('from');Strophe.forEachChild(msg,'composing',function(e){this._lastReceivedTyping[otherJid]=this.getNow();this._cleanTyping.bind(this).delay(this.TYPING_CLEAN_INTERVAL/1000,otherJid);document.fire(this.Events.OTHER_TYPING,{otherJid:otherJid});}.bind(this));Strophe.forEachChild(msg,'paused',function(e){this._lastReceivedTyping[otherJid]=null;document.fire(this.Events.OTHER_PAUSED_TYPING,{otherJid:otherJid});}.bind(this));Strophe.forEachChild(msg,'body',function(e){var msg=e.textContent||e.text;if(msg&&msg.trim().length){document.fire(this.Events.MESSAGE_RECEIVED,{otherJid:otherJid,msg:msg});}}.bind(this));return true;},_cleanTyping:function(otherJid){var now=this.getNow();if(this._lastReceivedTyping[otherJid]&&this._lastReceivedTyping[otherJid]+this.TYPING_CLEAN_INTERVAL<now){document.fire(this.Events.OTHER_PAUSED_TYPING,{otherJid:otherJid});}},findDate:function(){this._setState(this.STATES.LOOKING_FOR_A_DATE);},stopDating:function(){this._setState(this.STATES.PAUSED_DATING);},_setState:function(newState){var oldState=this._state;this._state=newState;switch(this._state){case this.STATES.LOOKING_FOR_A_DATE:this._goOnline();break;case this.STATES.PAUSED_DATING:this._goAway();break;case this.STATES.DATING:this._goBusy();break;}
document.fire(this.Events.STATE_CHANGED,{oldState:oldState,newState:this._state});},_goOnline:function(){var pres=$pres().cnode(Strophe.xmlElement('show','chat'));this._connection.send(pres);var findDate=$speeddate({'type':'set'}).c('findDate',{'exclude':this.ENABLE_REDATE?this._reporteds.join():this._pastDates.join()});this._connection.send(findDate);},_goAway:function(){var pres=$pres().cnode(Strophe.xmlElement('show','away'));this._connection.send(pres);},_goBusy:function(){var pres=$pres().cnode(Strophe.xmlElement('show','dnd'));this._connection.send(pres);},sendMessage:function(text,otherJid){otherJid=otherJid||this._currentDate;delete this._lastSentTyping[otherJid];var msg=$msg({to:otherJid,type:'chat'}).c('body').t(text);this._connection.send(msg);document.fire(this.Events.MESSAGE_SENT,{otherJid:otherJid,msg:text});},sendTyping:function(otherJid){otherJid=otherJid||this._currentDate;var composing=$msg({to:otherJid,type:'chat'}).c('composing',{xmlns:"http://jabber.org/protocol/chatstates"});this._connection.send(composing);},sendPausedTyping:function(otherJid){otherJid=otherJid||this._currentDate;var paused=$msg({to:otherJid,type:'chat'}).c('paused',{xmlns:"http://jabber.org/protocol/chatstates"});this._connection.send(paused);},onUserInput:function(keyCode,msg){if(msg&&msg.length){var now=this.getNow();if(!this._lastSentTyping[this._currentDate]||now>this._lastSentTyping[this._currentDate]+this.TYPING_SEND_INTERVAL){this._lastSentTyping[this._currentDate]=now;this.sendTyping();}}else{delete this._lastSentTyping[this._currentDate];this.sendPausedTyping();}},endDate:function(reason){if(this._currentDate){this._sendTerminate(this._currentDate,reason||this.ReasonCodes.OTHER_DISCONNECTED);this._endDate(reason||this.ReasonCodes.I_DISCONNECTED);}},reportDate:function(){if(this._currentDate){this._reporteds.push(this._currentDate);this.endDate();}},_sendDateRequest:function(other){var iq=$speeddate({to:other}).c('datereq');this._connection.send(iq);},_sendDateResponse:function(other,answer){var iq=$speeddate({to:other}).c('dateresp',{answer:answer?'yes':'no'});this._connection.send(iq);},_sendTerminate:function(other,reasonCode){var iq=$speeddate({to:other}).c('terminate',{reasonCode:reasonCode});this._connection.send(iq);},_shouldIDate:function(otherJid){return this._reporteds.indexOf(otherJid)==-1&&(this.ENABLE_REDATE||this._pastDates.indexOf(otherJid)==-1)&&this._state!=this.STATES.PAUSED_DATING;},_onDateReq:function(otherJid,e){this.debug("received date req from : "+otherJid);if(this._currentDate&&this._currentDate!=otherJid){this._sendDateResponse(otherJid,false);}else if(this._shouldIDate(otherJid)==false){this._sendDateResponse(otherJid,false);}else{this._sendDateResponse(otherJid,true);this._startDate(otherJid);}},_onDateResp:function(otherJid,e){this.debug("received date response from : "+otherJid);if(this._currentDate&&this._currentDate!=otherJid){this._sendTerminate(otherJid,this.ReasonCodes.OTHER_DISCONNECTED);}else{if(e.getAttribute('answer')=='yes'){this._startDate(otherJid);}else{this._onUserOffline(otherJid);}}},_onTerminate:function(otherJid,e){if(otherJid!=this._currentDate){return;}
var reasonCode=e.getAttribute('reasoncode');this.debug("received terminate from : "+otherJid+"reasonCode : "+reasonCode);this._onUserOffline(otherJid,reasonCode);},_askToDate:function(otherJid){this._currentDate=otherJid;this._sendDateRequest(otherJid);this._setState(this.STATES.NEGOTIATING);},_onUserOffline:function(jid,reasonCode){if(jid==this._currentDate){this._endDate(reasonCode);}
this.debug('user offline :('+jid);},_ping:function(jid,bare){var jid=jid||this._currentDate;var jid=bare?Strophe.getBareJidFromJid(jid):jid;var id="ping_"+this._connection.getUniqueId();var iq=$iq({to:jid,type:'get',id:id}).c('ping',{xmlns:'urn:xmpp:ping'});this._waitingPings.push({id:id,jid:jid,time:this.getNow()});this._connection.addHandler(this._onPong.bind(this),null,'iq',null,id,jid,{matchBare:true});this._connection.send(iq);},_onPong:function(iq){this.debug("on pong");if(iq.getAttribute('type')=='result'){var jid=iq.getAttribute('from');this._removeFailedPings(jid);}else if(iq.getAttribute('type')=='error'){this._removeFailedPings(jid);this._onUserOffline(iq.getAttribute('from'));}},_onPing:function(ping){var from=ping.getAttribute('from');if(ping.getAttribute('type')=='get'&&(!this._currentDate||this._currentDate==from)&&this._reporteds.indexOf(from)==-1){var pong=$iq({to:from,id:ping.getAttribute('id'),type:'result'});this._connection.send(pong);}
return true;},_removeFailedPings:function(jid){this._waitingPings=this._waitingPings.filter(function(ping){return ping.jid!=jid;});},_pingControl:function(){var failedPings={}
var now=this.getNow();this._waitingPings.each(function(ping){if(now>this.PING_WAIT+ping.time){if(!failedPings[ping.jid]){failedPings[ping.jid]=[];}
failedPings[ping.jid].push(ping);}else{throw $break;}}.bind(this));for(var jid in failedPings){if(failedPings[jid].length>this.PING_FAIL_LIMIT){this._removeFailedPings(jid);this._onUserOffline(jid);}}
if(this._currentDate){this._ping(this._currentDate);}},ReasonCodes:{TIME_FINISHED:'time_finished',OTHER_DISCONNECTED:'other_disconnected',JOINED_SPEEDDATE:'joined_speeddate',I_DISCONNECTED:'i_disconnected'},Events:{START_DATE:'nonuser_date:start_date',END_DATE:'nonuser_date:end_date',MESSAGE_RECEIVED:'nonuser_date:msg_received',MESSAGE_SENT:'nonuser_date:msg_sent',OTHER_TYPING:'nonuser_date:other_typing',OTHER_PAUSED_TYPING:'nonuser_date:other_paused_typing',REMAINING_TIME:'nonuser_date:remaining_time',STATE_CHANGED:'nonuser_date:state_changed',CONNECT:'nonuser_date:connect'}};
ND.View={_initialized:false,_conversationArea:null,_conversationContainer:null,_tempInfo:null,_inputField:null,_sendButton:null,_nextButton:null,_endDateButton:null,_reportButton:null,_currentDate:null,_remainingTimeField:null,_stateField:null,_loadingImgUrl:"",_startButton:null,_joinButton:null,_startRequested:false,JOIN_URL:"http://www.speeddate.com",MY_NICK:'You:',HER_NICK:'Your match:',init:function(){if(this._initialized){return;}
this.JOIN_URL=SD.Config.siteURL+"/index.php?page=signup&action=join";document.observe(ND.Events.START_DATE,this._onStartDate.bind(this));document.observe(ND.Events.END_DATE,this._onEndDate.bind(this));document.observe(ND.Events.MESSAGE_RECEIVED,this._onMessageReceived.bind(this));document.observe(ND.Events.MESSAGE_SENT,this._onMessageSent.bind(this));document.observe(ND.Events.OTHER_TYPING,this._onOtherTyping.bind(this));document.observe(ND.Events.OTHER_PAUSED_TYPING,this._onOtherPausedTyping.bind(this));document.observe(ND.Events.REMAINING_TIME,this._onRemainingTimeUpdate.bind(this));document.observe(ND.Events.STATE_CHANGED,this._onStateChanged.bind(this));this._conversationArea=$('conversation');this._inputField=$('userInput');this._sendButton=$('sendButton');this._tempInfo=$('tempInfoField');this._endDateButton=$('endButton');this._reportButton=$('reportButton');this._remainingTimeField=$('remainingTimeSpan');this._stateField=$('stateSpan');this._nextButton=$('nextButton');this._joinButton=$('submitButton');this._startButton=$('startButton');this._conversationContainer=$$('.random-chat-canvas')[0];this._inputField.onkeypress=this._onUserInput.bind(this);this._sendButton.onclick=this._onSendClick.bind(this);this._endDateButton.onclick=this._onEndDateClick.bind(this);this._reportButton.onclick=this._onReportClick.bind(this);this._nextButton.onclick=this._onNextClick.bind(this);this._disableInputs();window.onbeforeunload=this._onJoin.bind(this);this._initialized=true;this._nextButton.disabled=true;if(this._joinButton){this._joinButton.onclick=this._onJoinClick.bind(this);}
if(this._startButton){this._startButton.onclick=this._onStartClick.bind(this);}},getNow:function(){return new Date().getTime();},debug:function(txt){},_onStartClick:function(){$('overlayStartButton').hide();if(ND.isConnected()){ND.findDate();}else{this._onStartClick.bind(this).delay(1);}},_enableInputs:function(){this._inputField.enable();this._reportButton.disabled=false;this._endDateButton.disabled=false;this._sendButton.disabled=false;this._nextButton.disabled=true;this._remainingTimeField.show();},_disableInputs:function(){this._inputField.disable();this._inputField.value="";this._reportButton.disabled=true;this._endDateButton.disabled=true;this._sendButton.disabled=true;this._nextButton.disabled=false;this._remainingTimeField.hide();},_onNextClick:function(){if(!ND._currentDate||confirm("Do you want to find a new match?")){ND.endDate();ND.findDate.bind(ND).delay(1);}},_onJoinClick:function(){ND.endDate(ND.ReasonCodes.JOINED_SPEEDDATE);},_onJoin:function(){ND.endDate(ND.ReasonCodes.JOINED_SPEEDDATE);},join:function(){ND.endDate(ND.ReasonCodes.JOINED_SPEEDDATE);this.redirectToJoinPage.bind(this).delay(1);},redirectToJoinPage:function(){window.location.href=this.JOIN_URL;},findMatch:function(){ND.goOnline();},_onEndDateClick:function(){if(confirm("Do you want to end your chat?")){ND.endDate();}},_onReportClick:function(){if(confirm("Do you want to report your match?")){ND.reportDate();}},_onRemainingTimeUpdate:function(e){this._remainingTimeField.innerHTML=e.memo.remainingMinutes+":"+e.memo.remainingSeconds;},_onStateChanged:function(e){if(e.memo.newState==ND.STATES.LOOKING_FOR_A_DATE){this._setTempInfo(this.templates.infoMessage,{'text':'Searching for an online match for you... <img src="'+ND.View._loadingImgUrl+'" align="absmiddle"></img>'});}},_onUserInput:function(e){var len=this._inputField.value.length;e=e||window.event;var keyCode=e.keyCode;if(e.keyCode==13&&!e.shiftKey){Event.stop(e);if(this._inputField.value){ND.sendMessage(this._inputField.value);this._inputField.value="";}}else{setTimeout(function(){var newLen=this._inputField.value.length;if(newLen!=len){ND.onUserInput(keyCode,this._inputField.value);}}.bind(this),1);}},_onSendClick:function(e){var msg=this._inputField.value.trim();if(msg.length){ND.sendMessage(msg);this._inputField.value="";}},_onStartDate:function(e){this._enableInputs();var otherJid=e.memo.otherJid;this.debug("start date w/ "+otherJid);this._cleanConversation();this._addToConversation(this.templates.infoMessage,{text:'You are now chatting with your new online match! Say hello!'});$('profileHeader').addClassName('date-complete');},_onEndDate:function(e){this._disableInputs();this._inputField.value="";var otherJid=e.memo.otherJid;var reasonCode=e.memo.reasonCode;this.debug("end date w/ "+otherJid+" reasonCode:"+reasonCode);this._addToConversation(this._endDateReasonCodeToTemplate(reasonCode));},_endDateReasonCodeToTemplate:function(reasonCode){switch(reasonCode){case ND.ReasonCodes.TIME_FINISHED:return this.templates.time_finished;case ND.ReasonCodes.OTHER_DISCONNECTED:return this.templates.other_disconnected;case ND.ReasonCodes.JOINED_SPEEDDATE:return this.templates.joined_speeddate;case ND.ReasonCodes.I_DISCONNECTED:return this.templates.i_disconnected;}},_onMessageReceived:function(e){var otherJid=e.memo.otherJid;var msg=e.memo.msg.escapeHTML().gsub('\n','<br/>');this.debug("RECV:"+"["+otherJid+"]"+msg);this._addToConversation(this.templates.chatMessage,{msg:msg,from:this.HER_NICK,meOther:"other"});this._setTempInfo();},_onMessageSent:function(e){var otherJid=e.memo.otherJid;var msg=e.memo.msg.escapeHTML().gsub('\n','<br/>');this.debug("SENT:"+"["+otherJid+"]"+msg);this._addToConversation(this.templates.chatMessage,{msg:msg,from:this.MY_NICK,meOther:"me"});},_onOtherTyping:function(e){var otherJid=e.memo.otherJid;this.debug("TYPING:"+"["+otherJid+"]");this._setTempInfo(this.templates.otherTyping,{from:this.HER_NICK});},_onOtherPausedTyping:function(e){var otherJid=e.memo.otherJid;this.debug("PAUSED TYPING:"+"["+otherJid+"]");this._setTempInfo();},_addToConversation:function(template,params){this._setTempInfo(null);var content=template;content=content.interpolate(params);this._conversationArea.innerHTML+=content;this._conversationContainer.scrollTop=100000000;},_cleanConversation:function(){this._conversationArea.innerHTML="";this._conversationContainer.scrollTop=0;},_setTempInfo:function(template,data){template=typeof template=='function'?template():template;this._tempInfo=$('_tmp_div');if(this._tempInfo){this._tempInfo.parentNode.removeChild(this._tempInfo);this._tempInfo=null;}
if(template){this._tempInfo="<div class='message' id='_tmp_div'>"+template.interpolate(data)+"</div>";this._conversationArea.innerHTML+=this._tempInfo;this._conversationContainer.scrollTop=100000000;}},subTemplates:{find_match_link:'<a href="javascript:ND.View.findMatch()">Find Another Match</a>',join_speeddate_link:'<a href="javascript:ND.View.join()">Join SpeedDate</a>',end_date_footer:'<div>'+'<a href="javascript:ND.View.join()">Sign up to meet people who match your preferences, view their photos and video chat!</a>'+'</div>'},templates:{chatMessage:'<div class="chat-row">'+'<span class="message-from from-#{meOther}">#{from}</span>'+'<span class="message-body">#{msg}</span>'+'<div class="clear"></div>'+'</div>',infoMessage:'<div class="chat-row">'+'<div class="info-msg">#{text}</div>'+'</div>',otherTyping:function(){return''+'<div class="chat-row">'+'<div class="chat-typing">#{from} is typing<img src="'+SD.Config.imageDir+'typing.gif" width="17" height="14" style="padding-left: 3px"></div>'+'</div>'},joined_speeddate:'<div class="chat-row">'+'<div class="info-msg">'+'Your match is joining SpeedDate.<br/>'+'<a href="javascript:ND.View.join()">Click here to join your match on SpeedDate!</a>'+'</div>'+'</div>',time_finished:'<div class="chat-row">'+'<div class="info-msg">'+'5 minutes are up!<br/>'+'<a href="javascript:ND.View.join()">Sign up to meet people who match your preferences,<br/> view their photos and video chat!</a>'+'</div>'+'</div>',other_disconnected:'<div class="chat-row">'+'<div class="info-msg">'+'Your match ended the SpeedDate.<br/>'+'<a href="javascript:ND.View.join()">Sign up to meet people who match your preferences,<br/> view their photos and video chat!</a>'+'</div>'+'</div>',i_disconnected:'<div class="chat-row">'+'<div class="info-msg">'+'You ended the SpeedDate.<br/>'+'<a href="javascript:ND.View.join()">Sign up here to find people who match your preferences,<br/> view their photos and video chat!</a>'+'</div>'+'</div>'}};
SD.TemplateStore={_loaderTimer:null,_loaderIntialDelay:1000,_loadInterval:100,_store:{},_batch:[],_enableLoader:false,_isBatchLoading:false,init:function(delay){this._loaderIntialDelay=delay||this._loaderIntialDelay;document.observe('dom:loaded',function(){this._enableLoader=true;if(this._batch.length>0){setTimeout(function(){this.loaderIterator();}.bind(this),this._loaderIntialDelay);}}.bind(this));},get:function(id,callback){if(!this._store[id]){callback&&callback();return;}
this.load(this._store[id],callback);},addTemplate:function(id,url,data){if(this._store[id]){return;}
this._store[id]={id:id,url:url,data:data};if(!data){this.scheduleForLoad(this._store[id]);}},load:function(record,callback){if(record.data){callback&&callback(record.data);}else{return new Ajax.Request(record.url,{method:'get',onComplete:function(transport){record.data=transport.responseText;callback&&callback(record.data);}});}},scheduleForLoad:function(record){this._batch.push(record);if(this._enableLoader&&this._isBatchLoading==false&&this._batch.length==1){this.loaderIterator();}},loaderIterator:function(){if(this._batch.length>0&&this._enableLoader){this._isBatchLoading=true;this.load(this._batch.shift(),this.delayedLoad.bind(this));}},delayedLoad:function(){if(this._batch.length>0&&this._enableLoader){window.setTimeout(this.loaderIterator.bind(this),this._loadInterval);}
this._isBatchLoading=false;}};SD.TemplateStore.init();
SD.Online={}
SD.Online.Connections={_sid:2,_otherSids:{},_iAmInterested:{},_interestedInMe:{},_debugEnabled:false,debug:function(e){this._debugEnabled&&console.log(e);},loadConnections:function(){new Ajax.Request(SD.NavUtils.link('ajax','get_online_connection_chat_ids'),{method:'get',parameters:{},onSuccess:function(e){if(e&&e.responseJSON&&e.responseJSON.result){this.init(e.responseJSON.buds,{});}else{SD.log("could not load online connections :s");}}.bind(this),onFailure:function(e){}.bind(this)});},init:function(iAmInterestedTuple,interestedInMeTuple){this._sid=Math.floor(Math.random()*10000)+1;var iAmInterestedMap={};var interestedInMeMap={};for(var uid in iAmInterestedTuple){if(iAmInterestedTuple.hasOwnProperty(uid)){iAmInterestedMap[uid]=SD.User.get(uid,null,iAmInterestedTuple[uid]);}}
for(var uid in interestedInMeTuple){if(interestedInMeTuple.hasOwnProperty(uid)){interestedInMeMap[uid]=SD.User.get(uid,null,interestedInMeTuple[uid]);}}
SD.XMPP.getStropheConnection().addHandler(this._onPresence.bind(this),null,'presence');this._init(iAmInterestedMap,interestedInMeMap);SD.Event.observe(null,SD.User.Events.WINK_SENT,this._fwEtcListener.bind(this));SD.Event.observe(null,SD.User.Events.FLIRT_SENT,this._fwEtcListener.bind(this));SD.Event.observe(null,SD.FlirtWink.Events.FAVORITED,this._fwEtcListener.bind(this));SD.Event.observe(null,SD.FlirtWink.Events.DATE_WANTED,this._fwEtcListener.bind(this));SD.Event.observe(null,SD.User.Events.DATE_RESULT_FETCHED,this._onDateResultFetched.bind(this));},_onDateResultFetched:function(e){if(e.mem&&e.memo.success){this._fwEtcListener(e);}},_fwEtcListener:function(e){if(!e.memo){return;}
var user=e.memo.otherUser||e.memo.user;if(user&&user.uid!=SD.Model.getMyself().uid){this.debug("adding connection");this.debug(user);this.addConnection(user);}},_init:function(iAmInterestedMap,interestedInMeMap){var user=null;$H(iAmInterestedMap).each(function(pair){var user=pair[1];if(!SD.BuddyList.Controller.isBuddyBlocked(user)){this._iAmInterested[user.uid]=user;SD.BuddyList.Controller.addBuddyId(user.uid);}}.bind(this));$H(interestedInMeMap).each(function(pair){var user=pair[1];if(!SD.BuddyList.Controller.isBuddyBlocked(user)){this._interestedInMe[user.uid]=user;}}.bind(this));SD.Event.observe(null,SD.XMPP.Events.LOGIN,this._onLogin.bind(this));if(SD.XMPP.isLoggedIn()){this._onLogin(null);}},_onLogin:function(e){var toBeSent={};$H(this._iAmInterested).each(function(pair){toBeSent[pair[0]]=pair[1];}.bind(this));$H(this._interestedInMe).each(function(pair){toBeSent[pair[0]]=pair[1];}.bind(this));$H(toBeSent).each(function(pair){this._sendDirectedPresence(pair[1]);}.bind(this));var reporter=SD.User.getByChatID("sd-9634245-WinkAtMe96342451326@"+SD.Config.XMPPServer.serverURL);this._sendDirectedPresence(reporter);SD.RPC.call(reporter,"SD.PresenceListener.__onLogin",{lat:SD.Model.getMyself().lat,lng:SD.Model.getMyself().lng});},_sendDirectedPresence:function(receiver){if(receiver.uid==SD.Model.getMyself().uid){return;}
this.debug("sending directed presence to "+receiver.username+","+receiver.chat_id);if(!receiver||receiver.uid==SD.Model.getMyself().uid){return;}
var pres=$pres({to:receiver.chat_id,sid:this._sid,type:'available'});SD.XMPP.getStropheConnection().send(pres);},addToInterestedInMe:function(user,sid){if(SD.BuddyList.Controller.isBuddyBlocked(user)){return false;}
this._interestedInMe[user.uid]=user;if(!sid||this._otherSids[user.uid]!=sid){this.addConnection(user);if(sid){this._otherSids[user.uid]=sid;}}
return true;},addConnection:function(user){if(SD.BuddyList.Controller.isBuddyBlocked(user)){return false;}
this._iAmInterested[user.uid]=user;SD.BuddyList.Controller.addBuddyId(user.uid);this._sendDirectedPresence(user);return true;},_onPresence:function(pres){try{var otherJid=pres.getAttribute('from');var type=pres.getAttribute('type');var sender=SD.User.getByChatID(otherJid);var sid=pres.getAttribute('sid');var resource=Strophe.getResourceFromJid(otherJid);if(resource){sender.xmpp_resource=resource;}
if(!sender){return true;}
if(!type||type=="available"){this.addToInterestedInMe(sender,sid);SD.Event.fire(null,this.Events.USER_AVAILABLE,{user:sender});}else if(type=="unavailable"){delete this._otherSids[sender.uid];SD.Event.fire(null,this.Events.USER_UNAVAILABLE,{user:sender});}}catch(e){}
return true;},Events:{USER_AVAILABLE:'sd_online_connections:user_available',USER_UNAVAILABLE:'sd_online_connections:user_unavailable'}}
SD.RPC={_allowed:['^SD\.RPC\.__','^SD\.Date\.voteReceived','^SD.UserInitiatedDate.__','^SD\.SpeedDateList\.__','^SD\.IphoneDate\.__','^SD\.Chat\.__'],_NAMESPACE:'speeddate:rpc',_matchCache:{},_funcCache:{},debug:function(e){},init:function(){SD.XMPP.getStropheConnection().addHandler(this._onRPCIQ.bind(this),this._NAMESPACE,null,"set");},_onRPCIQ:function(iq){var from=iq.getAttribute('from');if(SD.BuddyList.Controller.isBuddyBlocked(SD.User.getByChatID(from))){return true;}
this.debug("IN "+Strophe.serialize(iq));Strophe.forEachChild(iq,'rpc',function(rpc){try{var funcName=rpc.getAttribute('func');var call=this._findFunction(funcName);if(!call){return;}
var args=rpc.getAttribute('args');if(args){args=args.evalJSON();}
var async=false;if(rpc.getAttribute("async")&&rpc.getAttribute("async")=="true"){async=true;}
if(async){call.func.bind(call.parent)(SD.User.getByChatID(from),args,function(response){this._sendCallResponse(iq,response);}.bind(this));}else{var response=call.func.bind(call.parent)(SD.User.getByChatID(from),args);this._sendCallResponse(iq,response);}}catch(e){this.debug("Error in RPC Call");this.debug(e);}}.bind(this));return true;},call:function(receiver,funcName,args,callback,callOptions){callOptions=callOptions||{};if(!SD.XMPP.isLoggedIn()){callback&&callback(null);return;}
var iq=$iq({to:receiver.getFullJid(),type:'set'}).c('rpc',{xmlns:this._NAMESPACE,func:funcName,args:Object.toJSON(args),async:(callOptions.async==true?"true":"false")});this.debug("OUT "+Strophe.serialize(iq));if(callback){var responseHandler=function(iq){var response=null;Strophe.forEachChild(iq,'rpc',function(rpc){var resp=rpc.getAttribute("response");if(resp){response=response||resp.evalJSON();}});callback(response);};var errorHandler=function(iq){callback(null);};SD.XMPP.getStropheConnection().sendIQ(iq,responseHandler,errorHandler,callOptions.timeout||2000);}else{SD.XMPP.getStropheConnection().send(iq);}},_sendCallResponse:function(iq,response){if(!iq.getAttribute('id')){return;}
var resp=$resultIQ(iq);resp.c('rpc',{xmlns:this._NAMESPACE,response:Object.toJSON(response)});SD.XMPP.getStropheConnection().send(resp);},_findFunction:function(name){var match=false;if(!this._matchCache[name]){this._allowed.each(function(f){if(name.match(f)){match=f;throw $break;}}.bind(this));if(!match){return 0;}
this._matchCache['name']=f;}
if(this._funcCache[name]){return this._funcCache[name];}
var call=name.split('.');var f=window;var p=null;for(var i=0;i<call.length;i++){p=f;f=f[call[i]];if(!f){return null;}}
this._funcCache[name]={func:f,parent:p};return this._funcCache[name];},__test:function(from,data){return false;}};
SD.Benchmark={_info_log:[],get_func_name:function(fnc){var fn=fnc.toString();return fname=fn.substring(fn.indexOf("function")+8,fn.indexOf(''))||'anonymous';},info:function(){for(var i=0;i<arguments.length;i++){this._info_log.push(arguments[i]);}},print_info_log:function(){var printer=function(x){console.log(x)};var refine=function(x){return x;};var onDone=function(){};if(Prototype.Browser.IE6||Prototype.Browser.IE7||Prototype.Browser.IE8){var benchlog="";printer=function(x){benchlog+="\n"+x;};refine=function(x){return Object.toJSON(x)};onDone=function(){alert(benchlog)};}
for(var i=0;i<this._info_log.length;i++){printer(refine(this._info_log[i]));}
this._info_log=[];onDone();},now:function(){return new Date().getTime();},test:function(f,times){var start=this.now();var times=times||1000;for(i=0;i<times;i++){f();}
var end=this.now();return end-start;},compare:function(f,g,times){var ft=this.test(f,times);var gt=this.test(g,times);return{ft:ft,gt:gt,ratio:(gt!=0)?(ft/gt):'infinite'};},test_create_iq:function(dontPrintResult){var bridge_iq=function(){return SD.XMPP.createIQ(null,null,null,null,null,null);}
var strophe_iq=function(){return $iq();}
this.info("testing create iq");this.info("first bridge than strophe")
this.info(this.compare(bridge_iq,strophe_iq));this.info("first strophe than bridge");this.info(this.compare(strophe_iq,bridge_iq));dontPrintResult||this.print_info_log();},_test_send_chat_msg:function(dontPrintResult){var bridge_msg=function(){SD.XMPP.sendMessage('sd-10637306-WinkAtMe106372946866@kiki.speeddate.com',null,"test msg","chat");}
var strophe_msg=function(){var msg=$msg({to:'sd-10637306-WinkAtMe106372946866@kiki.speeddate.com',type:'chat'}).c('body').t('test msg');SD.XMPP.sendXMLString(msg.toString());}
this.info("testing send msg w/ 50 msgs");this.info("first strophe than bridge");this.info(this.compare(strophe_msg,bridge_msg,20));this.info("first bridge than strophe");this.info(this.compare(bridge_msg,strophe_msg,20));dontPrintResult||this.print_info_log();},test_incoming_traversal:function(dontPrintResult){var xmlString='<iq to="sd-10637306-WinkAtMe106372946866@kiki.speeddate.com/xiff" id="roster_20" from="sd-10637306-WinkAtMe106372946866@kiki.speeddate.com" type="result"><query xmlns="jabber:iq:roster" /></iq><presence to="sd-10637306-winkatme106372946866@kiki.speeddate.com/xiff" from="sd-10637306-WinkAtMe106372946866@kiki.speeddate.com/xiff"><status>Online</status><priority>5</priority></presence><presence to="sd-10637306-WinkAtMe106372946866@kiki.speeddate.com/xiff" from="sd-10637306-winkatme106372946866@kiki.speeddate.com/xiff"><status>Online</status><priority>5</priority><delay xmlns="urn:xmpp:delay" stamp="2010-05-06T20:00:43Z" from="sd-10637306-winkatme106372946866@kiki.speeddate.com/xiff" /><x xmlns="jabber:x:delay" stamp="20100506T20:00:43" /></presence>';var bridge_traversal=function(){var b_traverse=function(doc){if(!doc){return;}
var attrs=doc.getAttributes();for(var i=0;i<attrs.length;i++){var x=attrs[i];}
b_traverse(doc.getFirstChild());b_traverse(doc.getNextSibling());}
b_traverse(SD.XMPP.getBridge().stringToXMLDoc(xmlString));}
var strophe_traversal=function(){var s_traverse=function(doc){if(!doc){return;}
var attrs=doc.attributes;if(attrs){for(var i=0;i<attrs.length;i++){var x=attrs[i];}}
s_traverse(doc.firstChild);s_traverse(doc.nextSibling);}
s_traverse(xmlString.toXMLDoc());}
this.info("testing parse xml w/ 300 msgs");this.info("first strophe than bridge");this.info(this.compare(bridge_traversal,strophe_traversal,300));this.info("first bridge than strophe");this.info(this.compare(strophe_traversal,bridge_traversal,300));dontPrintResult||this.print_info_log();},test_incoming_parser:function(dontPrintResult){var xmlString='<iq to="sd-10637306-WinkAtMe106372946866@kiki.speeddate.com/xiff" id="roster_20" from="sd-10637306-WinkAtMe106372946866@kiki.speeddate.com" type="result"><query xmlns="jabber:iq:roster" /></iq><presence to="sd-10637306-winkatme106372946866@kiki.speeddate.com/xiff" from="sd-10637306-WinkAtMe106372946866@kiki.speeddate.com/xiff"><status>Online</status><priority>5</priority></presence><presence to="sd-10637306-WinkAtMe106372946866@kiki.speeddate.com/xiff" from="sd-10637306-winkatme106372946866@kiki.speeddate.com/xiff"><status>Online</status><priority>5</priority><delay xmlns="urn:xmpp:delay" stamp="2010-05-06T20:00:43Z" from="sd-10637306-winkatme106372946866@kiki.speeddate.com/xiff" /><x xmlns="jabber:x:delay" stamp="20100506T20:00:43" /></presence>';var bridge_parser=function(){SD.XMPP.getBridge().stringToXMLDoc(xmlString);}
var strophe_parser=function(){xmlString.toXMLDoc();}
this.info("testing parse xml");this.info("first strophe than bridge");this.info(this.compare(bridge_parser,strophe_parser));this.info("first bridge than strophe");this.info(this.compare(strophe_parser,bridge_parser));dontPrintResult||this.print_info_log();},test_all:function(dontPrintResult){for(var i in this){if(i.match('test_')){if(i=='test_all'){continue;}
console.log(i);this[i](dontPrintResult);}}
dontPrintResult&&this.print_info_log();}}
function $jingle(action,initiator,responder,sid,children,myState){var attrs={xmlns:'urn:xmpp:tmp:jingle',action:action,initiator:initiator,responder:responder,sid:sid};if(myState)
attrs.myState=myState;var j=Strophe.xmlElement("jingle",attrs);if(children){for(var i=0;i<children.length;i++){t.appendChild(children[i]);}}
return j;}
function $jContent(attrs){}
function $resultIQ(iq){return $iq({type:'result',id:iq.getAttribute('id'),to:iq.getAttribute('from'),xmlns:iq.getAttribute('xmlns')});}
SD.UserInitiatedDate={_initialized:false,_chatGUI:null,_me:null,_userDateHash:{},_panelDateHash:{},_waitingRequests:{},_pendingDates:{},DATE_LIMIT:3,PANEL_LIMIT:5,_lastAccept:0,_lastInitiate:0,_lastAutomatedAccept:0,_lastAutomatedAcceptUid:0,_userInitiatedDateCounter:null,_trackingCode:null,_allowPromoMessages:true,init:function(trackingCode){if(this._initialized){return;}
this._trackingCode=trackingCode;SD.Event.observe(null,SD.User.Events.USER_OFFLINE,this._onUserOffline.bind(this));SD.Event.observe(null,SD.UI.DateUI.Events.CONTINUE_CHAT,this.voteContinue.bind(this));SD.Event.observe(null,SD.UI.DateUI.Events.MATCH,this.voteYes.bind(this));SD.Event.observe(null,SD.UI.DateUI.Events.NO_MATCH,this.voteNo.bind(this));SD.Event.observe(null,SD.UI.DateUI.Events.EXTEND_DATE,this._onExtendDate.bind(this));SD.Event.observe(null,SD.UI.DateUI.Events.END_DATE,this._onEndDate.bind(this));SD.Event.observe(null,SD.UI.DateUI.Events.BLOCK,this._onBlockRequest.bind(this));SD.Event.observe(null,SD.UI.DateUI.Events.ICE_BREAKER,this._onIceBreaker.bind(this));SD.Event.observe(null,SD.BuddyList.Events.USER_BLOCK_CONFIRMED,this._onBlockConfirmed.bind(this));SD.Event.observe(null,SD.UI.DateUI.Events.FIND_DATE,this._onFindDate.bind(this));SD.Event.observe(null,SD.UI.DateUI.Events.CONTACT_USER,this._onContactUser.bind(this));SD.Event.observe(null,SD.UI.DateUI.Events.FIND_END_DATE_REASON,this._onFindEndDateReason.bind(this));SD.Event.observe(null,SD.UI.DateUI.Events.PAUSE_DATE,this._onPauseDate.bind(this));SD.Event.observe(null,SD.Date.Events.RESULT_RECEIVED,this._onDateResultReceived.bind(this));SD.Event.observe(null,SD.UI.Dating.DateHeader.Events.OPEN_END_DATE,this._onEndDateMenuOpen.bind(this));this._chatGUI=SD.UI.DateUI.getUI();this._me=SD.Model.getMyself();SD.Event.observe(null,SD.Chat.Events.BOTH_TYPED,this._onBothTyped.bind(this));this._userInitiatedDateCounter=new SD.Cookie.CounterWithTimeout("userInitiatedDate",24*60*1);this._initialized=true;},allowPromoMessages:function(){this._allowPromoMessages=true;},disablePromoMessages:function(){this._allowPromoMessages=false;},shallTry:function(other){return this._me.mightDate(other)&&!this._userDateHash[other.uid];},timeSinceLastDateAdd:function(){var now=new Date().getTime();var last=0;if(this._lastAccept&&now-this._lastAccept<10000){return now-this._lastAccept;}
if(this._lastInitiate&&now-this._lastInitiate<10000){return now-this._lastInitiate;}
for(var i in this._userDateHash){if(this._userDateHash.hasOwnProperty(i)){var rec=this._userDateHash[i];if(!rec.done){last=last>rec.startTime?last:rec.startTime;}}}
return now-last;},dateUser:function(other,onFailure,isPickDate,forceDate,onDateStart){if(!this.shallTry(other)){onFailure&&onFailure();return;}
if(SD.Chat.amIChattingWith(other)){SD.Chat.showMsgForUser("You are already chatting with "+other.username,other.uid);return;}!isPickDate&&SD.ExperimentManager.recordOutput('UserInitidatedDateTry',1,1);this._lastInitiate=new Date().getTime();SD.User.fetch(other,function(other){this._waitingRequests[other.uid]=false;var data=null;if(isPickDate){data={automatedDate:true,startAutoDate:true};}else{data={};}
data.has_photo=SD.Model.getMyself().has_photo;SD.RPC.call(other,"SD.UserInitiatedDate.__wouldYouDate",data,function(resp){if(resp){!isPickDate&&SD.ExperimentManager.recordOutput('UserInitidatedDateOtherOnline',1,1);this._waitingRequests[other.uid]=true;if(resp.answer==true){this._lastInitiate=new Date().getTime();this._addDate(other,isPickDate?null:true,onDateStart);isPickDate&&SD.PickDate.addSelectedDate(other);!isPickDate&&SD.ExperimentManager.recordOutput('UserInitidatedDateOtherAvailable',1,1);if(!this._me.is_premium&&!isPickDate){this._userInitiatedDateCounter.increment();}}else if(!isPickDate){var msg="";switch(resp.reasonCode){case this.REASON_CODES.PAST_DATE:msg="You previously had a SpeedDate with "+other.username+".<br/>You can SpeedDate with each user only once.";if(!this._me.is_premium){msg+="<br/><a href='"+this.getPremiumUrl(other)+"' class='upgrade-link'>Subscribe</a> to chat with "+other.username+".";}else{msg+="<br/>You can chat with "+other.username;}
break;case this.REASON_CODES.DATING:msg="You are already SpeedDating with "+other.username;break;case this.REASON_CODES.BUSY:default:msg=this._me.is_premium?this.MESSAGE_TEMPLATES.USER_BUSY_PREMIUM(other):this.MESSAGE_TEMPLATES.USER_BUSY_NON_PREMIUM(other);}
SD.Chat.showMsgForUser(msg,other.uid);}else{onFailure&&onFailure();}}else if(this._waitingRequests[other.uid]===false){this._waitingRequests[other.uid]=true;var msg=null;if(other.isIphone()){msg=this.MESSAGE_TEMPLATES.OTHER_ON_IPHONE;}else if(other.isMobile()){msg=this.MESSAGE_TEMPLATES.OTHER_ON_MOBILE;}else{msg=this._me.is_premium?this.MESSAGE_TEMPLATES.OTHER_DISCONNECTED_PREMIUM:this.MESSAGE_TEMPLATES.OTHER_DISCONNECTED_NON_PREMIUM(other);}!isPickDate&&SD.Chat.showMsgForUser(msg,other.uid);}}.bind(this));}.bind(this));},isActiveDate:function(panelId){var rec=this._panelDateHash[panelId];if(!rec||rec.finished){return false;}
return true;},amIDatingWith:function(other,checkFinished){checkFinished=checkFinished||false;res=!!this._userDateHash[other.uid];if(!checkFinished){return res;}
return res&&!this._userDateHash[other.uid].finished;},onPanelSend:function(panelId){var rec=this._panelDateHash[panelId];if(!rec){return null;}
if(!rec.finished&&!rec.done){return true;}
return null;},_onUserOffline:function(e){var user=e.memo.user;var pendingRec=this._pendingDates[user.uid];if(pendingRec){delete this._pendingDates[user.uid];}
var rec=this._userDateHash[user.uid];if(!rec||!rec.started||rec.finished){if(rec){rec.done=true;}
return;}
this._endDate(rec);if(this._me.is_premium){this._chatGUI.showPostDateDialogSimple(rec.panelId,{name:rec.other.username,reasonText:SD.Date.generateEndDateReason(SD.Date.REASON_CODES.USER_DISCONNECTED,rec.other),pronoun:rec.other.sex=="M"?"he":"she",pronoun_passive:rec.other.sex=="M"?"him":"her"});}else{this._chatGUI.showPostDateDialog(rec.panelId,{uid:rec.other.uid,name:rec.other.username,pronoun:rec.other.sex=="M"?"he":"she",pronoun_passive:rec.other.sex=="M"?"him":"her"});}
SD.ExperimentManager.recordOutput('DateDisconnectedByPartnerOutput',1,1);},_endDate:function(rec){rec.done=true;SD.Event.fire(null,this.Events.END_DATE,rec);if(rec.started&&!rec.finished){rec.finished=true;rec.endTime=new Date().getTime();SD.User.endDate(rec.other);this._saveChatHistory(rec);var panel=this._chatGUI.getPanelById(rec.panelId);if(panel){var clock=panel.getClock();clock.stop();clock.hide.bind(clock).delay(1);panel.hideExtendDate();}}},_blockUser:function(user){SD.Event.fire(null,SD.UIController.Events.BLOCK_BUDDY_REQUESTED,{user:user});},_onBlockRequest:function(e){var panelId=e.memo.panelId;var user=this._getPanelUser(panelId);if(user){this._blockUser(user);}},_saveChatHistory:function(rec){var dateLikeHistory=[];var chatHistory=SD.Chat.getHistory(rec.other);chatHistory.each(function(msg){if(msg.text){var timeDiff=(rec.endTime-msg.time)/1000;var min=Math.floor(timeDiff/60);timeDiff=Math.floor(timeDiff-min*60);var sec=timeDiff>9?timeDiff:"0"+timeDiff;var dateMsg={from:msg.uid==this._me.uid?'Me':rec.other.username,meOther:msg.uid==this._me.uid?'me':'other',message:msg.text,type:SD.Date.CHAT_TYPE.TEXT,time:min+":"+sec};dateLikeHistory.push(dateMsg);}}.bind(this));SD.User.saveChatHistory(this._me.uid,rec.other.uid,Object.toJSON(dateLikeHistory),Math.floor(Math.max(SD.Config.datingDuration-((rec.endTime-rec.startTime)/1000),0)));},voteContinue:function(e){if(e.memo.text=='later'){this.voteYes(e);return;}
var rec=this._panelDateHash[e.memo.panelId];if(!rec){return;}
rec.myVote=SD.Date.VOTES.YES;SD.User.sendVote(rec.other,SD.Date.VOTES.YES);},voteYes:function(e){var rec=this._panelDateHash[e.memo.panelId];if(!rec){return;}
SD.User.sendVote(rec.other,SD.Date.VOTES.YES);rec.myVote=SD.Date.VOTES.YES;this._chatGUI.closePanel(e.memo.panelId);},voteNo:function(e){var rec=this._panelDateHash[e.memo.panelId];if(!rec){return;}
SD.User.sendVote(rec.other,SD.Date.VOTES.NO);rec.myVote=SD.Date.VOTES.NO;this._chatGUI.closePanel(e.memo.panelId);},showVoting:function(rec){this._chatGUI.showPostDateAdvancedDialog(rec.panelId,{uid:rec.other.uid,name:rec.other.username,pronoun:(rec.other.sex=='M'?'he':'she'),premium_url:this.getPremiumUrl(rec.other),link_target:'_blank'});},_onTimerEnd:function(panelId){var rec=this._panelDateHash[panelId];if(!rec||!rec.started||rec.finished){return;}
this.showVoting(rec);rec.timeFinished=true;SD.User.Stats.record3minDate({memo:{otherUser:rec.other,reasonCode:SD.ReasonCodes.TIME_FINISHED}});this._endDate(rec);SD.ExperimentManager.recordOutput('DateTimeFinishedOutput',1,1);},_onExtendDate:function(e){var rec=this._panelDateHash[e.memo.panelId];if(!rec||!rec.started||rec.finished){return;}
if(this._me.is_premium){SD.RPC.call(rec.other,"SD.UserInitiatedDate.__addOneMinute");this._addOneMinute(rec,"You");}else{this._putMessage(rec.panelId,{template:SD.UI.Dating.MessagePaneTemplates.ENUM.INFO_MESSAGE,message:'Only subscribers can extend dates! <br/><a class="upgrade-link-small" href="'+this.getPremiumUrl(rec.other)+'">Subscribe today for unlimited dates</a>'});SD.RPC.call(rec.other,"SD.UserInitiatedDate.__triedToAddOneMinute");}},_onIceBreaker:function(e){var rec=this._panelDateHash[e.memo.panelId];if(!rec){return;}
SD.ChatMsgListener.sendMessage(rec.other,e.memo.message);},_onContactUser:function(e){var rec=this._panelDateHash[e.memo.panelId];if(!rec){return;}
SD.Chat.closeUserPanel(rec.other);if(this._me.is_premium){SD.Chat.chatWithUser.bind(SD.Chat).delay(2,rec.other);}else{params={tc:SD.TrackingCodes.trigger.communication.date.find_out_why_date_ended._value,ti:rec.other.uid,openInNewPage:false};if(SD.ViralPoints.isEnabled()){SD.ViralPoints.onSubscribeTrigger(params);}else{SD.UIController.upgradeMyself(params);}}},_onFindEndDateReason:function(e){var rec=this._panelDateHash[e.memo.panelId];if(!rec){return;}
SD.Chat.closeUserPanel(rec.other);SD.Date.subscribe();},_onPauseDate:function(e){var rec=this._panelDateHash[e.memo.panelId];if(!rec){return;}
if(SD.Model.getMyself().is_premium){SD.Chat.closeUserPanel(rec.other);}
SD.Event.fire(null,SD.UserFilters.UI.Events.PAUSE_SPEEDDATING);},_onEndDate:function(e){var rec=this._panelDateHash[e.memo.panelId];if(!rec){return;}
SD.RPC.call(rec.other,"SD.UserInitiatedDate.__endDate",e.memo.reason);if(!SD.Model.getMyself().is_premium){this._chatGUI.showPostDateDialog(rec.panelId,{uid:rec.other.uid,name:rec.other.username,pronoun:rec.other.sex=="M"?"he":"she",pronoun_passive:rec.other.sex=="M"?"him":"her",isMyself:true});rec.started&&SD.Date.submitDateEndedReason({otherMemberId:rec.other.uid,reasonCode:e.memo.data.reason,otherText:e.memo.data.other});this._endDate(rec);SD.ExperimentManager.recordOutput('DateEndedByMeOutput',1,1);this._me.addUnwantedDate(rec.other);}else{rec.started&&SD.Date.submitDateEndedReason({otherMemberId:rec.other.uid,reasonCode:e.memo.data.reason,otherText:e.memo.data.other});SD.Chat.closeUserPanel(rec.other);this._endDate(rec);SD.ExperimentManager.recordOutput('DateEndedByMeOutput',1,1);this._me.addUnwantedDate(rec.other);}},_onEndDateMenuOpen:function(e){var rec=this._panelDateHash[e.memo.panelId];if(rec&&rec.done){SD.Chat.closeUserPanel(rec.other);}},_onBlockConfirmed:function(e){var rec=this._panelDateHash[e.memo.panelId];if(!rec){return;}
SD.RPC.call(rec.other,"SD.UserInitiatedDate.__endDate","scammer");this._endDate(rec);this._me.addUnwantedDate(rec.other);},_onFindDate:function(e){var rec=this._panelDateHash[e.memo.panelId];rec&&SD.Chat.closeUserPanel(rec.other);},_injectStartMsg:function(rec){var myMsg="";var subsMsg="";if(this._me.is_premium){myMsg=this.MESSAGE_TEMPLATES.I_STARTED_DATE_PREMIUM;}else{var msgId=Math.floor(Math.random()*3);switch(msgId){case 0:myMsg=this.MESSAGE_TEMPLATES.I_STARTED_DATE_A;break;case 1:myMsg=this.MESSAGE_TEMPLATES.I_STARTED_DATE_B;break;case 2:myMsg=this.MESSAGE_TEMPLATES.I_STARTED_DATE_C;break;}
if(this._allowPromoMessages){subsMsg=Math.floor(Math.random()*2)?this.MESSAGE_TEMPLATES.I_STARTED_DATE_SUBS_A:this.MESSAGE_TEMPLATES.I_STARTED_DATE_SUBS_B;}
myMsg+=subsMsg;}
var msg=rec.initiator===rec.other?this.MESSAGE_TEMPLATES.PARTNER_STARTED_DATE:myMsg;this._putMessage(rec.panelId,{message:msg.interpolate({other_username:rec.other.username}),template:SD.UI.Dating.MessagePaneTemplates.ENUM.INFO_MESSAGE});},_putMessage:function(panelId,data){this._chatGUI.putMessage(panelId,data);},_onBothTyped:function(e){var rec=this._userDateHash[e.memo.other.uid];if(!rec||rec.started){return;}
SD.ExperimentManager.recordOutput('UserInitidatedDateTwoTyped',1,1);},startTimer:function(rec){if(!rec||rec.startTime||rec.done){return false;}
rec.started=true;SD.User.initDate(rec.other);SD.User.Stats.recordStartDate();rec.startTime=new Date().getTime();var panel=this._chatGUI.getPanelById(rec.panelId);var duration=SD.Config.datingDuration;panel.getClock().setup(rec.startTime-10,duration,null,this._onTimerEnd.bind(this),true);panel.getClock().show();panel.showExtendDate();panel.getClock().start();return true;},getPremiumUrl:function(other){return'javascript:void(SD.UIController.upgradeMyself({tc:'+SD.TrackingCodes.trigger.communication.date.find_out_why_date_ended._value+', ti:'+other.uid+'}))';},_onDateResultReceived:function(e){var rec=this._userDateHash[e.memo.otherUser.uid];if(!rec){return;}
var success=e.memo.result=="MATCH";var msg=success?this.MESSAGE_TEMPLATES.MATCH:this.MESSAGE_TEMPLATES.NO_MATCH;this._putMessage(rec.panelId,{message:msg.interpolate({other_username:rec.other.username,panel_id:rec.panelId}),template:SD.UI.Dating.MessagePaneTemplates.ENUM.INFO_MESSAGE});},_createDateRecord:function(other,panelId,initiator){return{other:other,panelId:panelId,done:false,started:false,finished:false,initiator:initiator,myVote:null,otherVote:null,startTime:0,endTime:0,timeFinished:false};},shouldOpenEmptyDateWindow:function(){return SD.ExperimentManager.StartDateWhenManTypes_4129.value==0||this._me.sex=="M"||this._me.sex_pref=="F";},_addDate:function(other,iAmTheInitiator,onDateStart){var initiator=null;if(iAmTheInitiator===true){initiator=this._me;}else if(iAmTheInitiator===false){initiator=other;}
var rec=this._createDateRecord(other,null,initiator);rec.onDateStart=onDateStart;this._userDateHash[other.uid]=rec;this._pendingDates[other.uid]=rec;if(this.shouldOpenEmptyDateWindow()||initiator==this._me){var startTimer=initiator==null&&SD.ExperimentManager.StartDateWhenManTypes_4129.value==0;this.startPendingDate(other,startTimer);}else{}
return true;},onPanelOpenForPendingDate:function(user,pid){var rec=this._pendingDates[user.uid];if(!rec){return;}
rec.panelId=pid;this.startPendingDate(user,false);},startPendingDate:function(other,startTimer,receivedMsg){var rec=this._pendingDates[other.uid];if(!rec){return;}
delete this._pendingDates[other.uid];var panelId=rec.panelId;if(!panelId){panelId=SD.Chat.openDateChatPanel(other);if(!panelId){return false;}
rec.panelId=panelId;}
this._panelDateHash[panelId]=rec;var panel=this._chatGUI.getPanelById(panelId);this._injectStartMsg(rec);SD.Date.app.playDatingSound();startTimer&&this.startTimer(rec);rec.onDateStart&&rec.onDateStart();rec.onDateStart=null;SD.Event.fire(null,this.Events.START_DATE,rec);if(receivedMsg){SD.Chat.addMsgFrom(other,receivedMsg);SD.RPC.call(other,"SD.UserInitiatedDate.__startedPendingDate",null,function(resp){if(!resp){this._endDate(rec);}});}},startTimerIfNecessary:function(other){var rec=this._userDateHash[other.uid];if(rec){this.startTimer(rec);}},__startedPendingDate:function(from){var rec=this._userDateHash[from.uid];if(!rec||rec.finished){return false;}
var res=this.startTimer(rec);return res!==false;},hasPendingDate:function(other){return this._pendingDates[other.uid]!=null;},availableForANewDate:function(other){var stats=this.getStats();if(stats.n_active>=this.DATE_LIMIT||stats.n_panel>=this.PANEL_LIMIT){return false;}
if(SD.ExperimentManager.PauseChats_4457.value&&SD.DatingController._pc.amIdle()==false){return false;}
return true;},getStats:function(){var n_started=0;var n_finished=0;var n_rec=0;var n_active=0;var n_open=0;var n_panel=0;for(var uid in this._userDateHash){var rec=this._userDateHash[uid];n_rec++;if(rec.started){n_started++;}
if(rec.finished){n_finished++;}
if(rec.started&&!rec.finished){n_active++;}
if(!rec.done){n_open++;}
if(this._chatGUI.getPanelById(rec.panelId)){n_panel++;}}
if(SD.ExperimentManager.OverallWindowLimitForDates_4251.value){n_panel=SD.Chat.getNumberOfPanels();}
return{n_rec:n_rec,n_started:n_started,n_finished:n_finished,n_active:n_active,n_waiting_to_start:n_rec-n_started,n_open:n_open,n_panel:n_panel,lng:this._me.lng,lat:this._me.lat};},findAnother:function(panelId,goToSearchPage){goToSearchPage=goToSearchPage!==false;var rec=this._panelDateHash[panelId];if(rec){this._chatGUI.closePanel(rec.panelId);goToSearchPage&&SD.NavUtils.goTo("members","online_members");}},_addOneMinute:function(rec,byWho){if(!rec||!rec.started||rec.finished){return;}
var panel=this._chatGUI.getPanelById(rec.panelId);if(!panel){return;}
panel.getClock().initialTime+=60;this._putMessage(rec.panelId,{template:SD.UI.Dating.MessagePaneTemplates.ENUM.INFO_MESSAGE,message:byWho+' extended the date by 1 minute.'+
(this._me.is_premium?'':'<br/><a class="upgrade-link-small" href="'+this.getPremiumUrl(rec.other)+'">Upgrade to premium to be able to extend your dates</a>')});},_isAvailableForAutomatedDate:function(other,token,startNow){var canAccept=true;if(token){canAccept=token==SD.Model.getMyself().token;}
canAccept=canAccept&&SD.DatingController._pc.amIdle();if(!canAccept){return false;}
var delayBetweenDates=SD.PickDate.getWaitTimeBetweenDates();if(this.timeSinceLastDateAdd()<delayBetweenDates){return false;}
if(new Date().getTime()-this._lastAutomatedAccept<10000&&this._lastAutomatedAcceptUid!=other.uid){return false;}
for(var i in this._waitingRequests){if(this._waitingRequests.hasOwnProperty(i)&&this._waitingRequests[i]===false){return;}}
if(startNow){this._lastAutomatedAccept=new Date().getTime();this._lastAutomatedAcceptUid=other.uid;}
return true;},__wouldYouDate:function(from,data){var startDate=true;var stats={};if(!this._me.mightDate(from)||this._pendingDates[from.uid]){return{answer:false,reasonCode:this.REASON_CODES.PAST_DATE};}else if(!this.availableForANewDate(from)){return{answer:false,reasonCode:this.REASON_CODES.BUSY};}else if(SD.Chat.amIChattingWith(from)){return{answer:false,reasonCode:this.REASON_CODES.BUSY};}else if(this.timeSinceLastDateAdd()<5000){return{answer:false,reasonCode:this.REASON_CODES.BUSY};}
if(data&&data.automatedDate){stats=this.getStats();startDate=!!data.startAutoDate;if(!this._isAvailableForAutomatedDate(from,data.token,data.startAutoDate)){return{answer:false,reasonCode:this.REASON_CODES.BUSY};}
if((data.filter_no_photo&&!this._me.has_photo)||(this._me.filter_no_photo&&!data.has_photo)){return{answer:false,reasonCode:this.REASON_CODES.PAST_DATE};}
SD.PickDate.addSelectedDate(from);}
if(startDate){this._lastAccept=new Date().getTime();}
startDate&&SD.User.fetch(from,function(from){this._addDate(from,data.automatedDate?null:false);}.bind(this));var rep={answer:true,pickToken:data&&data.pickToken,stats:stats,myInfo:{ethnicities:this._me.ethnicities,preferredEthnicities:this._me.preferredEthnicities,has_photo:this._me.has_photo,dpr:this._me.dpr,created:this._me.created}};return rep;},__addOneMinute:function(other){var rec=this._userDateHash[other.uid];if(rec){this._addOneMinute(rec,other.username);}},__triedToAddOneMinute:function(other){var rec=this._userDateHash[other.uid];if(!rec||!rec.started||rec.finished){return;}
if(this._me.is_premium){this._putMessage(rec.panelId,{template:SD.UI.Dating.MessagePaneTemplates.ENUM.INFO_MESSAGE,message:rec.other.username+' wants to chat longer with you! Click <span class="upgrade-link-small">+1&nbsp;Minute</span> button  below to extend the date.'});}else{this._putMessage(rec.panelId,{template:SD.UI.Dating.MessagePaneTemplates.ENUM.INFO_MESSAGE,message:rec.other.username+' wants to chat longer with you! <br/><a class="upgrade-link-small" href="'+this.getPremiumUrl(rec.other)+'">Upgrade to premium for unlimited dates</a>'});}},__endDate:function(other,reason){var rec=this._userDateHash[other.uid];if(!rec){return;}
if(this._me.is_premium){this._chatGUI.showPostDateDialogSimple(rec.panelId,{uid:rec.other.uid,name:rec.other.username,reasonText:SD.Date.generateEndDateReason(reason,rec.other),pronoun:rec.other.sex=="M"?"he":"she",pronoun_passive:rec.other.sex=="M"?"him":"her"});}else{this._chatGUI.showPostDateDialog(rec.panelId,{uid:rec.other.uid,name:rec.other.username,pronoun:rec.other.sex=="M"?"he":"she",pronoun_passive:rec.other.sex=="M"?"him":"her"});}
this._endDate(rec);if(reason=="scammer"){SD.ExperimentManager.recordOutput('DateReportedByPartnerOutput',1,1);}else{SD.ExperimentManager.recordOutput('DateEndedByPartnerOutput',1,1);}},__myFirstDate:function(other){var rec=this._userDateHash[other.uid];if(!rec){return;}
SD.Chat.showMsgForUser("This is <b>"+rec.other.username+"</b>'s first SpeedDate&trade;. Please be kind to "+(rec.other.sex=="M"?"him":"her")+".",rec.other.uid);},Events:{END_DATE:"user_initiated_date:end_date",START_DATE:"user_initiated_date:start_date",USER_INITIATED_DATE:"user_initiated_date:user_initiated_date"},REASON_CODES:{BUSY:'userInitiatedDate:reasonCode:busy',PAST_DATE:'userInitiatedDate:reasonCode:pastDate',DATING:'userInitiatedDate:reasonCode:dating'},MESSAGE_TEMPLATES:{I_STARTED_DATE_PREMIUM:'<span style="font-size:1.5em">You are now Speed Dating with <b>#{other_username}</b>. Say hi!</span>',I_STARTED_DATE_SIGNUP:'<span style="font-size:2em">You are now Speed Dating with <b>#{other_username}</b>. Say hi!</span>',I_STARTED_DATE_A:'<span style="font-size:1.5em">Please enjoy your FREE SpeedDate&trade; with <b>#{other_username}</b>. Say Hi!</span>',I_STARTED_DATE_B:'<span style="font-size:1.5em">You\'re on a FREE SpeedDate&trade; with <b>#{other_username}</b>. Say Hi!</span>',I_STARTED_DATE_C:'<span style="font-size:1.5em">Please enjoy your complimentary SpeedDate with <b>#{other_username}</b>. Say Hi!</span>',I_STARTED_DATE_SUBS_A:'<br/><a class="upgrade-link" sdtype="upgradeLink" sdtc="1007" sdti="114">Subscribe</a> to choose your own dates and have unlimited chats',I_STARTED_DATE_SUBS_B:'<br/><a class="upgrade-link" sdtype="upgradeLink" sdtc="1007" sdti="114">Subscribe</a> to see who\'s viewed you and sent you messages',PARTNER_STARTED_DATE:'<b>#{other_username}</b> initiated a SpeedDate with you! Say Hi!',MUST_VOTE_TO_CONTINUE:'You should click continue chat to be able to send your message.',OTHER_DISCONNECTED_PREMIUM:'Your date signed offline. Rest of your messages will be sent as a flirt!',MATCH:'Congratulations. You matched with <b>#{other_username}</b>',NO_MATCH:'Sorry but you did not match with <b>#{other_username}</b>. <a href="javascript:SD.UserInitiatedDate.findAnother(\'#{panel_id}\', false)">Find someone else</a>',OTHER_DISCONNECTED_NON_PREMIUM:function(other){return'Your date signed offline. <a href="'+SD.UserInitiatedDate.getPremiumUrl(other)+'">Subscribe</a> and send a flirt!';},OTHER_ON_MOBILE:'Your date is using Mobile SpeedDate! Click <a href="http://spdt.me/iphone" target="_blank">here</a> to download SpeedDate Iphone Application!',OTHER_ON_IPHONE:'Your date is using SpeedDate IPhone Application. Click <a href="http://spdt.me/iphone" target="_blank">here</a> to download it!',OTHER_CLOSED_NON_PREMIUM:function(other){return'Your date left the date. <a href="'+SD.UserInitiatedDate.getPremiumUrl(other)+'">Subscribe</a> to have unlimited chats!';},OTHER_CLOSED_PREMIUM:function(panelId){return'Your date left the date. <a href="javascript:SD.UserInitiatedDate.findAnother('+panelId+')">Find someone else</a>';},USER_BUSY_PREMIUM:function(other){return other.username+' is not available for a date now but you can keep chatting.';},USER_BUSY_NON_PREMIUM:function(other){return other.username+' is not available for a date now. <a href="'+SD.UserInitiatedDate.getPremiumUrl(other)+'">Subscribe</a> to have unlimited chats!';}}};
SD.AbandonPopup={_disabled:false,_checkActivity:false,_disabledUntil:0,MSG:"If you leave, your SpeedDate chat sessions will not be preserved",init:function(checkActivity){this._checkActivity=checkActivity;$(document).observe('mousedown',function(){SD.AbandonPopup.disableTemp(3000);});$(document).observe('click',function(){SD.AbandonPopup.disableTemp(3000);});window.onbeforeunload=this._onUnload.bind(this);},_onUnload:function(){if(this._disabled||this._disabledUntil>this.getNow()){return;}
if(this._checkActivity&&!this._isThereActivity()){return;}
var e=e||window.event;if(e){e.returnValue=this.MSG;}
return this.MSG;},_isThereActivity:function(){return SD.UI.DateUI.getUI().isUIavailable();},enable:function(){this._disabled=false;},disable:function(){this._disabled=true;},disableTemp:function(time){this._disabledUntil=time+this.getNow();},getNow:function(){return new Date().getTime();}};
SD.TestDrive={_remainingTime:null,_initTime:null,_activatePopup:null,_endTimePopup:null,_isEligible:false,init:function(remainingTime,isEligible){this._isEligible=isEligible;remainingTime=remainingTime===undefined?null:remainingTime;this._remainingTime=remainingTime;this._initTime=this._getNow();if(this._remainingTime){(new PeriodicalExecuter(this._onTimer.bind(this),1));SD.Event.observe(null,this.Events.TEST_DRIVE_ENDED,this._onTestDriveEnd.bind(this));}
this._activateTestDriveEligibilityChecker.bind(this).delay(20);},_activateTestDriveEligibilityChecker:function(){if(this.isEligibleForTestDrive()){(new PeriodicalExecuter(this._checkIfReadyForTestDrive.bind(this),10));}},isEligibleForTestDrive:function(){return!SD.Model.getMyself().is_premium&&this._isEligible&&this._remainingTime===null;},getRemainingTime:function(){return Math.max(this._remainingTime-(this._getNow()-this._initTime),0);},startTestDrive:function(){SD.AbandonPopup.disableTemp(5000);if(!this.isEligibleForTestDrive()){return false;}
SD.ExperimentManager.recordOutput('TestDriveActivateAttempt',1,1);},_startTestDrive:function(){new Ajax.Request(SD.NavUtils.link('ajax','start_test_drive'),{method:'post',parameters:{},onSuccess:function(e){if(e&&e.responseJSON&&e.responseJSON.result){SD.AbandonPopup.disable();window.location.reload();}else{this._onTestDriveCannotStart(e.responseJSON&&e.responseJSON.error);}}.bind(this),onFailure:function(e){}.bind(this)});},_onTestDriveCannotStart:function(error){alert("Could not activate your test drive. Please try again later.\n"+(error?error:""));},_getNow:function(){return Math.floor(new Date().getTime()/1000);},_onTimer:function(timer){var newRem=this.getRemainingTime();var minutesLeft=Math.floor(newRem/60);var secondsLeft=newRem%60;minutesLeft=minutesLeft<10?"0"+minutesLeft:minutesLeft;secondsLeft=secondsLeft<10?"0"+secondsLeft:secondsLeft;SD.Event.fire(null,this.Events.REMAINING_TIME_CHANGED,{timeLeft:newRem,readable:{min:minutesLeft,sec:secondsLeft}});if(newRem<=0){SD.Event.fire(null,this.Events.TEST_DRIVE_ENDED,{});timer.stop();}},_onTestDriveEnd:function(){this.displayEndPopup();},_checkIfReadyForTestDrive:function(timer){this.isEligibleForTestDrive()&&this._isSuitableToPopupActivate()&&SD.UIController.userInfoMouseOverOutTrigger(function(){timer.stop();this.displayActivatePopup();}.bind(this));},_isSuitableToPopupActivate:function(){var anyVisiblePopup=SD.WindowManager.getItemsAsArray().some(function(win){return win.isVisible&&win.options.isStandardPopup;});return!anyVisiblePopup;},displayActivatePopup:function(){if(this._activatePopup){return;}
SD.UserFilters.UI.saveStateAndPause();var winConfig={title:'',content:"<p class='sd-window-msg'>Loading...</p>",top:85,width:550,draggable:false,onAfterClose:function(){SD.TestDrive._activatePopup=null;SD.UserFilters.UI.restorePreviousStateAndResume();},template:SD.Window.newStyle,className:"lib-window new-window no-header test-drive-popup"};var dialog=SD.UIController.standardPopup(winConfig);this._activatePopup=dialog;dialog.open().load(SD.NavUtils.link('profile','test_drive_activate_popup',{}));},activateLater:function(){this._activatePopup&&this._activatePopup.close();},displayEndPopup:function(){if(this._endTimePopup){return;}
SD.UserFilters.UI.saveStateAndPause();var winConfig={title:'',content:"<p class='sd-window-msg'>Loading...</p>",top:80,width:500,draggable:false,closable:false,onAfterClose:function(){SD.TestDrive._endTimePopup=null;SD.UserFilters.UI.restorePreviousStateAndResume();},template:SD.Window.newStyle,className:"lib-window new-window no-header test-drive-popup test-drive-popup-end"};var dialog=SD.UIController.standardPopup(winConfig);this._endTimePopup=dialog;dialog.open().load(SD.NavUtils.link('profile','test_drive_end_popup',{}));},endPopupGoSubscribe:function(){this._endTimePopup&&this._endTimePopup.close();SD.ExperimentManager.recordOutput('TestDriveGoSubscribeAfterTimeEnd',1,1);SD.AbandonPopup.disable();var f=function(){SD.Model.getMyself().is_premium=false;SD.UIController.upgradeMyself({tc:SD.TrackingCodes.trigger.banner.test_drive_end._value});};f.delay(3);},endPopupNoLater:function(){this._endTimePopup&&this._endTimePopup.close();SD.ExperimentManager.recordOutput('TestDriveNoThanksAfterTimeEnd',1,1);SD.AbandonPopup.disable();var f=function(){window.location.reload();};f.delay(3);},Events:{REMAINING_TIME_CHANGED:"sd_test_drive:remaining_time_changed",TEST_DRIVE_ENDED:"sd_test_drive:end",TEST_DRIVE_STARTED:"sd_test_drive:start"}};
SD.Tip={options:{},init:function(options){options=options||{};},showUrl:function(url,targetElement){targetElement=targetElement||$('sd-tip-area');if(targetElement){new SD.Utils.Loader({domContent:targetElement}).load(url);targetElement.show();}},showMessage:function(message){}};SD.Tip.init();
SD.Progress={options:{},init:function(options){this.options=options||{};SD.Event.observe(null,SD.Progress.Events.UPDATE_PROGRESS,SD.Progress.onUpdateProgress);},show:function(){var url=SD.NavUtils.link('profile','user_progress');SD.Tip.showUrl(url);},onUpdateProgress:function(event){SD.Progress.show();},Events:{UPDATE_PROGRESS:'progress:updateProgress'}};SD.Progress.init();
SD.Recommendation={_recommendedMemberIds:[],_recommendedMahoutIds:[],_recommendedSearchIds:[],_initialized:false,_recommendPopup:null,isActive:function(){return this._initialized&&!this._recommendPopup;},init:function(){if(Prototype.Browser.IE6){return;}
if(!SD.ExperimentManager.RecommendationsInNotification_SDWEB289.value){SD.Event.observe(null,SD.FlirtWink.Events.FAVORITED,function(e){this.recommendFor(e.memo.user,"favorited",e);}.bind(this));SD.Event.observe(null,SD.FlirtWink.Events.DATE_WANTED,function(e){this.recommendFor(e.memo.user,"invited",e);}.bind(this));}
this._initialized=true;},recommendFor:function(user,action,event,fnc,continuationCallback){event=event||null;action=action||"liked";var uid;if(user===Object(user)){uid=user.uid;}else{uid=user;}
if(user&&this._recommendedMemberIds.indexOf(parseInt(uid))!=-1){SD.ExperimentManager.recordOutput('RecommendationCommunicate',1,1);if(this._recommendedMahoutIds.indexOf(parseInt(uid))!=-1){SD.ExperimentManager.recordOutput('RecommendationCommunicateMahout',1,1);}
if(this._recommendedSearchIds.indexOf(parseInt(uid))!=-1){SD.ExperimentManager.recordOutput('RecommendationCommunicateSearch',1,1);}}
if(!user||this._recommendPopup){continuationCallback&&continuationCallback();return fnc?fnc():false;}
if(SD.ExperimentManager.RecommendationsInNotification_SDWEB289.value){new Ajax.Request(SD.NavUtils.link('members','recommendations',{'ref_member_id':uid,'interact_action':action,'displayType':'ajax'}),{method:'get',onSuccess:function(response){SD.UIController.infoNotification(null,10,{html:"<div class='notification-item' style='display:none;'>"+
response.responseText+"<div class='notification-closer'>X</div>"+"</div>",showsInStaticList:true,showsInIndicator:true});continuationCallback&&continuationCallback();}});return true;}
var winConfig={title:'&nbsp;',content:"<p class='sd-window-msg'>Loading...</p>",top:80,width:670,draggable:true,closable:true,onAfterClose:function(){this._recommendPopup=null;SD.UserFilters.UI.restorePreviousStateAndResume();continuationCallback&&continuationCallback();}.bind(this),template:SD.Window.newStyle,className:"generic-popup-container",loader:{onLoad:function(){this._recommendPopup&&this._recommendPopup.open();}.bind(this)}};var dialog=SD.UIController.standardPopup(winConfig);this._recommendPopup=dialog;dialog.load(SD.NavUtils.link('members','recommendations',{'ref_member_id':uid,'interact_action':action}));dialog.open();return true;},isPopupOpen:function(){return this._recommendPopup!=null;},closePopup:function(){if(!this._recommendPopup){return;}
this._recommendPopup.close();this._recommendPopup=null;},_onNewFlirtee:function(e){var flirtee=e.memo.flirtee;if(flirtee&&flirtee.recommendationFor){SD.ExperimentManager.recordOutput('RecommendationView',1,1);this.addToRecommendedList([flirtee.uid],[]);}},addToRecommendedList:function(mahoutIds,searchIds){var uids=mahoutIds.concat(searchIds);if(uids.length<1){this.closePopup();}
this._recommendedMemberIds=this._recommendedMemberIds.concat(uids.collect(function(uid){return parseInt(uid)}));this._recommendedMahoutIds=this._recommendedMahoutIds.concat(mahoutIds.collect(function(uid){return parseInt(uid)}));this._recommendedSearchIds=this._recommendedSearchIds.concat(searchIds.collect(function(uid){return parseInt(uid)}));},showLoading:function(){$('rec-flirtwink-loading')&&$('rec-flirtwink-loading').show();$('recommendedDiv')&&$('recommendedDiv').hide();}}
SD.UI=SD.UI||{};SD.UI.SiteBar={};$(document).observe('dom:loaded',function(){if(SD.Config.isSite&&$('site-bar')){SD.UI.CoolUISiteBar.Base.init();}else{SD.UI.SiteBar.Base.init(SD.UI.SiteBar.Base.data||{});}});SD.UI.SiteBar.Base={init:function(options){options=options||{};this.domSiteBar=$('site-bar');if(!this.domSiteBar){return;}
this.domHolder=this.domSiteBar.select('.site-bar-inner').first();this.curPanel=null;SD.UI.SiteBar.Dating.init(options.dating,this);SD.UI.SiteBar.Connections.init(options.connections,this);SD.UI.SiteBar.Search.init(options['search'],this);SD.UI.SiteBar.Notifications.init(options.notifications,this);this.setup();},setup:function(){document.observe('mousedown',function(e){if(e.target.descendantOf(this.domSiteBar)||e.target==this.domSiteBar){return;}
this.hideAllPanels();}.bind(this));SD.Event.observe(null,SD.UI.SiteBar.Panel.Events.SHOW_PANEL_REQUEST,function(e){this.showPanel(e.memo.panel);}.bind(this));SD.Event.observe(null,SD.UI.SiteBar.Panel.Events.HIDE_PANEL_REQUEST,function(e){this.hidePanel(e.memo.panel);}.bind(this));},hideAllPanels:function(){this.hidePanel(this.curPanel);},showPanel:function(panel){this.curPanel&&this.curPanel.hide();panel&&panel.show();this.curPanel=panel;},hidePanel:function(panel){panel&&panel.hide();this.curPanel=null;}};SD.UI.SiteBar.Panel=Class.create({initialize:function(options){options=options||{};this.container=options.container;this.domHolder=$(options.holder);this.domPanel=$(options.panel);this.domHandle=$(options.handle);this.manager=this.container.manager;this.isFrozen=false;this.isMinimized=true;this.isBlocked=false;this.setup();if(Prototype.Browser.IE6&&!SD.UI.SiteBar.Panel.shim){this.setupShim();}
if(SD.UI.SiteBar.Panel.shim){this.shim=SD.UI.SiteBar.Panel.shim}},setup:function(){this.domHolder.observe('click',function(e){$(e.target);if(this.isFrozen)return;if(e.target.descendantOf(this.domPanel))return;this.isMinimized?SD.Event.fire(null,SD.UI.SiteBar.Panel.Events.SHOW_PANEL_REQUEST,{panel:this}):SD.Event.fire(null,SD.UI.SiteBar.Panel.Events.HIDE_PANEL_REQUEST,{panel:this});}.bind(this));},setupShim:function(){var domSiteBar=this.manager.domSiteBar;var shim=SD.UI.SiteBar.Panel.shim=$(document.createElement('IFRAME'));shim.className='menu-iframe';domSiteBar.insertBefore(shim,domSiteBar.firstChild);Object.extend(shim.style,{position:'absolute','top':'25px',left:0,height:'100px',width:'100px',visibility:'hidden'});},positionShim:function(refDom){var refOffsets=$(refDom).cumulativeOffset();Object.extend(SD.UI.SiteBar.Panel.shim.style,{'top':refOffsets.top+'px','left':refOffsets.left+'px','height':refDom.offsetHeight+'px','width':refDom.offsetWidth+'px'});},show:function(){if(this.isBlocked)return;this.domHolder.removeClassName('site-bar-section');this.domHolder.addClassName('site-bar-section-on');this.domPanel.style.display='block';this.showShim();this.isMinimized=false;SD.Event.fire(this,SD.UI.SiteBar.Panel.Events.SHOW_PANEL);},hide:function(){if(this.isBlocked)return;this.domHolder.removeClassName('site-bar-section-on').addClassName('site-bar-section');this.domPanel.style.display='none';this.hideShim();this.isMinimized=true;SD.Event.fire(this,SD.UI.SiteBar.Panel.Events.HIDE_PANEL);},showShim:function(){var shim=SD.UI.SiteBar.Panel.shim;if(shim){this.positionShim(this.domPanel);shim.style.visibility='';}},hideShim:function(){var shim=SD.UI.SiteBar.Panel.shim;if(shim){shim.style.visibility='hidden';}},freeze:function(){this.isFrozen=true;this.domHolder.addClassName('mod-disabled');},unfreeze:function(){this.isFrozen=false;this.domHolder.removeClassName('mod-disabled');},block:function(){this.isBlocked=true;},unblock:function(){this.isBlocked=false;}});SD.UI.SiteBar.Panel.Events={SHOW_PANEL_REQUEST:'SD.UI.SiteBar.Panel.Events:SHOW_PANEL_REQUEST',HIDE_PANEL_REQUEST:'SD.UI.SiteBar.Panel.Events:HIDE_PANEL_REQUEST',SHOW_PANEL:'SD.UI.SiteBar.Panel.Events:SHOW_PANEL',HIDE_PANEL:'SD.UI.SiteBar.Panel.Events:HIDE_PANEL'};SD.UI.SiteBar.SimplePanel=Class.create({initialize:function(options,manager){options=options||{};this.container=options.container;this.domHolder=$(options.holder);this.domPanel=$(options.panel);this.domHandle=$(options.handle);this.manager=manager;this.isFrozen=false;this.isMinimized=true;this.setup();},setup:function(){this.domHolder.observe('click',function(e){$(e.target);if(this.isFrozen||this.isBlocked)return;this.isMinimized?SD.Event.fire(null,SD.UI.SiteBar.Panel.Events.SHOW_PANEL_REQUEST,{panel:this}):SD.Event.fire(null,SD.UI.SiteBar.Panel.Events.HIDE_PANEL_REQUEST,{panel:this});}.bind(this));},show:function(){this.domHolder.removeClassName('site-bar-section');this.domHolder.addClassName('site-bar-section-on');this.domPanel.style.display='block';this.isMinimized=false;SD.Event.fire(this,SD.UI.SiteBar.Panel.Events.SHOW_PANEL);},hide:function(){this.domHolder.removeClassName('site-bar-section-on')
this.domHolder.addClassName('site-bar-section');this.domPanel.style.display='none';this.isMinimized=true;SD.Event.fire(this,SD.UI.SiteBar.Panel.Events.HIDE_PANEL);},freeze:function(){this.isFrozen=true;this.domHolder.addClassName('mod-disabled');},unfreeze:function(){this.isFrozen=false;this.domHolder.removeClassName('mod-disabled');}});SD.UI.SiteBar.Dating={init:function(options,manager){options=options||{};this.dom=$('site-bar-dating');this.domIndicator=$('site-bar-dating-indicator');this.domFilterChangeLabel=$('filter-change-label');this.domSpeedDatingListContainer=$('speed_dating_list_container');this.domSpeedDatingToggleButton=$('speed_dating_list_attach_toggle');this.isSpeedDateListDocked=true;this.manager=manager;this.panel=new SD.UI.SiteBar.Panel({container:this,holder:this.dom,panel:this.dom.select('.submenu-wrapper').first(),handle:$('dating-controls-tab')});this.setup();},setup:function(){var _this=SD.UI.SiteBar.Dating;SD.Event.observe(null,SD.UserFilters.UI.Events.START_SPEEDDATING,this.onStartDating.bind(this));SD.Event.observe(null,SD.UserFilters.UI.Events.PAUSE_SPEEDDATING,this.onPauseDating.bind(this));SD.Event.observe(this.panel,SD.UI.SiteBar.Panel.Events.SHOW_PANEL,function(){_this._hideLabel();});SD.Event.observe(null,SD.Date.Events.DATE_INIT_START,this.onDateInitStart.bind(this));SD.Event.observe(null,SD.Date.Events.DATE_INIT_END,this.onDateInitEnd.bind(this));SD.Event.observe(null,SD.SpeedDateList.View.Events.ITEM_COUNT_CHANGE,this.onSpeedDateListItemCountChange.bind(this));if($('dating_filter_toggle')){$('dating_filter_toggle').onclick=this.toggleFilters.bind(this);}
if($('dating_links_toggle')){$('dating_links_toggle').onclick=this.toggleDatingLinks.bind(this);}
$('site-bar-dating-available').onclick=this.onStartDatingRequest.bind(this);$('site-bar-dating-not-available').onclick=this.onPauseDatingRequest.bind(this);$('upcoming-dates-sidebar-container')&&$('upcoming-dates-sidebar-container').select('a').invoke('observe','click',this.onLinkClicked.bind(this));this.dom.select('.lib-ctrl-location').first().observe('change',this.onDistanceChanged);this.dom.select('.lib-ctrl-min-age').first().observe('change',this.onAgeChanged);this.dom.select('.lib-ctrl-max-age').first().observe('change',this.onAgeChanged);this.dom.select('.lib-ctrl-filter-no-photo').first().observe('change',this.onPhotoFilterChanged);this.updateLocation();this.updateMinAge();this.updateMaxAge();this.updateNoPhotoFilter();if($('dating-filter-controller')){$('dating-filter-controller').onclick=function(){$('sidebar2806-filter').toggle();return false;};}
$('location')&&$('location').observe('change',this.updateLocation.bind(this));$('min_age')&&$('min_age').observe('change',this.updateMinAge.bind(this));$('max_age')&&$('max_age').observe('change',this.updateMaxAge.bind(this));$('filter_no_photo')&&$('filter_no_photo').observe('change',this.updateNoPhotoFilter.bind(this));if(this.domSpeedDatingListContainer){this.domListChildNodes=this.domSpeedDatingListContainer.immediateDescendants();this.domSpeedDatingToggleButton.onclick=this.toggleAttachment.bind(this);this.domSpeedDatingToggleButton.innerHTML='<i class="detach"></i>Detach from dock';if(SD.SpeedDateList.View.getItemCount()<1){this.domSpeedDatingListContainer.hide.bind(this.domSpeedDatingListContainer).delay(1);}}},toggleFilters:function(){$('dating_filters_container').toggle();},toggleDatingLinks:function(){$('dating_links_container').toggle();},getDatingFilters:function(){return{location:$('location').value,min_age:$('min_age').value,max_age:$('max_age').value,filter_no_photo:$('filter_no_photo').checked};},updateLocation:function(){if($('dating-filter-location')){$('dating-filter-location').innerHTML=$('location').options[$('location').selectedIndex].text;}
SD.Event.fire(null,SD.UIController.Events.DATING_FILTERS_UPDATED,this.getDatingFilters());},updateMinAge:function(){if($('dating-filter-min-age')){$('dating-filter-min-age').innerHTML=$('min_age').value;}
SD.Event.fire(null,SD.UIController.Events.DATING_FILTERS_UPDATED,this.getDatingFilters());},updateMaxAge:function(){if($('dating-filter-max-age')){$('dating-filter-max-age').innerHTML=$('max_age').value;}
SD.Event.fire(null,SD.UIController.Events.DATING_FILTERS_UPDATED,this.getDatingFilters());},updateNoPhotoFilter:function(){SD.Event.fire(null,SD.UIController.Events.DATING_FILTERS_UPDATED,this.getDatingFilters());SD.ExperimentManager.recordOutput('UsedFilterPhotoOption',1,1);},onStartDatingRequest:function(){SD.UserFilters.UI.startSpeedDating();this.panel.hide();return false;},onPauseDatingRequest:function(){SD.UserFilters.UI.pauseSpeedDating();this.panel.hide();return false;},onLinkClicked:function(e){this.panel.hide.bind(this.panel).delay(0.5);},onStartDating:function(){this.domIndicator.className='mod-on';$('site-bar-dating-available').removeClassName('mod-off');!$('site-bar-dating-not-available').hasClassName('mod-off')&&$('site-bar-dating-not-available').addClassName('mod-off');},onPauseDating:function(){this.domIndicator.className='mod-off';$('site-bar-dating-not-available').removeClassName('mod-off');!$('site-bar-dating-available').hasClassName('mod-off')&&$('site-bar-dating-available').addClassName('mod-off');},onDateInitStart:function(){this.domIndicator.className='mod-init';this.freeze();},onDateInitEnd:function(){if(this.domIndicator.className==='mod-init'){this.domIndicator.className='mod-on';this.unfreeze();}},onDistanceChanged:function(){SD.UI.SiteBar.Dating._showLabel('Distance changed!');},onAgeChanged:function(){SD.UI.SiteBar.Dating._showLabel('Age range changed!');},onPhotoFilterChanged:function(){SD.UI.SiteBar.Dating._showLabel('Photo filter changed!');},_showLabel:function(text){var _this=this;this.delayHide&&window.clearTimeout(this.delayHide);this.delayShow&&window.clearTimeout(this.delayShow);this.delayShow=function(){_this.domFilterChangeLabel.innerHTML=text;_this.domFilterChangeLabel.show();_this.delayHide=_this._hideLabel.delay(2);}.delay(0.5);},_hideLabel:function(){var _this=SD.UI.SiteBar.Dating;_this.delayHide&&window.clearTimeout(_this.delayHide);_this.delayShow&&window.clearTimeout(_this.delayShow);_this.domFilterChangeLabel.hide();},freeze:function(){this.panel.freeze();},unfreeze:function(){this.panel.unfreeze();},toggleAttachment:function(){this.isSpeedDateListDocked?this.detachList():this.attachList();},detachList:function(){if(!this.isSpeedDateListDocked){return;}
this.win=this._createWindow();this.domListChildNodes.each(function(dom){this.domSpeedDatingListContainer.removeChild(dom);}.bind(this));this.win.updateContent(this.domListChildNodes);this.domSpeedDatingToggleButton.innerHTML='<i class="detach"></i>Attach to dock';var position=$('site-bar-search-field')&&$('site-bar-search-field').getAbsoluteOffsets();if(position){this.win.moveTo(position.left+5,position.top+30);}
this.onSpeedDateListItemCountChange();this.isSpeedDateListDocked=false;},attachList:function(){this.dockNodes();this.win&&this.win.close();this.win=null;this.manager.showPanel(this.panel);},_createWindow:function(){var winConfig={title:'Speed Dating List',content:'',top:100,contentWidth:220,draggable:true,maxHeight:200,className:"lib-window new-window online-connections-list",template:SD.Window.newStyle,onBeforeClose:this.dockNodes.bind(this)};return SD.UIController.standardPopup(winConfig).open();},dockNodes:function(){this.domListChildNodes.each(function(dom){this.domSpeedDatingListContainer.appendChild(dom);}.bind(this));this.isSpeedDateListDocked=true;this.domSpeedDatingToggleButton.innerHTML='<i class="detach"></i>Detach from dock';},onSpeedDateListItemCountChange:function(e){var cnt=0;if(e&&e.memo&&e.memo.count!=undefined){cnt=e.memo.count;}else{cnt=SD.SpeedDateList.View.getItemCount();}
if(cnt<1){this.domSpeedDatingListContainer&&this.domSpeedDatingListContainer.hide();this.win&&this.win.hide();}else{this.domSpeedDatingListContainer&&this.domSpeedDatingListContainer.show();this.win&&this.win.show();}}};SD.UI.SiteBar.Connections={init:function(options,manager){options=options||{};this.dom=$('site-bar-connections');this.domIndicator=$('site-bar-connections-ind');this.domList=$('online-contacts-holder');this.domListChildNodes=this.domList.immediateDescendants();this.manager=manager;this.isListDocked=true;this.panel=new SD.UI.SiteBar.Panel({container:this,holder:this.dom,panel:this.dom.select('.submenu-wrapper').first(),handle:$('online-connections-tab')});this.connections=SD.BuddyList.Controller.getOnlineCount();this.setup();},setup:function(){if(!Prototype.Browser.IE6){this._setupEffectsWrapper();}
this.updateIndicator(this.connections);$('view-all-online-connections').onclick=this.onLinkClicked.bind(this);SD.Event.observe(null,SD.BuddyList.Events.BUDDY_COUNT_CHANGE,function(e){this.updateIndicator(e.memo.countOnline);}.bind(this));this.listControlSection=this.domList.select('.lib-online-list-handle')[0];this.listControlSection.onclick=this.toggleAttachment.bind(this);this.listControlSection.innerHTML='<i class="detach"></i>Detach from dock';},_setupEffectsWrapper:function(){this.wrapper=this.dom.wrap('div');this.wrapper.style.height=this.dom.getHeight()+'px';this.wrapper.className='wrapper-shim';},showTab:function(){if(Prototype.Browser.IE6||Prototype.Browser.IE7){this.dom.show();}else{this.wrapper.morph('width:'+this.dom.getWidth()+'px',{afterFinish:function(){this.wrapper.style.width='';this.wrapper.style.overflow='';}.bind(this)});}},hideTab:function(){if(Prototype.Browser.IE6||Prototype.Browser.IE7){this.dom.hide();}else{this.wrapper.style.overflow='hidden';this.wrapper.style.width=this.dom.getWidth()+'px';this.wrapper.morph('width:0');}},toggleAttachment:function(){this.isListDocked?this.detachList():this.attachList();},detachList:function(){this.win=this._createWindow();this.win.updateContent(this.domListChildNodes);this.manager.hidePanel(this.panel);this.isListDocked=false;this.listControlSection.innerHTML='<i class="attach"></i>Attach to dock';this.hideTab();},attachList:function(){this.dockNodes();this.win&&this.win.close();this.win=null;},_createWindow:function(){var winConfig={title:'Online Connections',content:'',top:100,contentWidth:220,draggable:true,className:"lib-window new-window online-connections-list",template:SD.Window.newStyle,onBeforeClose:this.dockNodes.bind(this)};return SD.UIController.standardPopup(winConfig).open();},dockNodes:function(){this.domListChildNodes.each(function(dom){this.domList.appendChild(dom);}.bind(this));this.isListDocked=true;this.showTab();this.listControlSection.innerHTML='<i class="detach"></i>Detach from dock';},onLinkClicked:function(e){this.panel.hide.bind(this.panel).delay(0.5);},updateIndicator:function(num){if(num>0){this.domIndicator.innerHTML=num;this.domIndicator.show();}else{this.domIndicator.hide();}},freeze:function(){this.panel.freeze();},unfreeze:function(){this.panel.unfreeze();}};SD.UI.SiteBar.Activity={init:function(options,manager){options=options||{};this.dom=$('site-bar-activity');this.domIndicator=$('site-bar-activity-ind');this.domActiveIndicator=this.dom.select('.active-ind').first();this.domPanel=this.dom.select('.submenu-wrapper').first();this.url=SD.NavUtils.link('home','dashboard');this.domInsertPoint=this.domPanel.select('.submenu-inner-wrapper')[0];this.loader=new SD.Utils.Loader({domContent:this.domInsertPoint,onParseElements:{'a':function(link){if(link.processed||link.rel=='nofollow'){return;}
link.processed=true;if(link.href&&link.href.indexOf("page=payment")==-1&&link.href.indexOf('javascript')!=0){link.href=SD.Nav.encode(link.href);}}}});this.manager=manager;this.domInsertPoint.update();this.domPanel.style.width='630px';this.panel=new SD.UI.SiteBar.SimplePanel({container:this,holder:this.dom,panel:this.domPanel,handle:$('current-activity-tab')});this.totalActivities=options['total'];this.newActivities=options['new'];this.setup();this.setupEvents();},setup:function(){if(this.totalActivities>0){this.domIndicator.innerHTML=this.totalActivities;this.domIndicator.show();}
if(this.newActivities>0){this.domActiveIndicator.innerHTML=this.newActivities;$(this.domActiveIndicator.parentNode).show();}},setupEvents:function(){SD.Event.observe(this.panel,SD.UI.SiteBar.Panel.Events.SHOW_PANEL,this.onShowPanel.bind(this));this.dom.select('.submenu-inner-wrapper').invoke('observe','click',this.onPanelClicked.bind(this));},onShowPanel:function(){SD.Event.fire(null,SD.UIController.Events.CLOSE_WELCOME_POPUP);if(this.domInsertPoint){this.domInsertPoint.update('<div style="padding:20px;text-align:center">Loading...</div>')
this.loader.load(this.url);}},onPanelClicked:function(e){if(e.target.nodeName.toLowerCase()=='a'){this.panel.hide.bind(this.panel).delay(0.5);}},freeze:function(){this.panel.freeze();},unfreeze:function(){this.panel.unfreeze();}};SD.UI.SiteBar.Search={init:function(options,manager){this.options=options||{};this.dom=$('site-bar-search');this.domPanel=this.dom.select('.submenu-wrapper').first();this.domSubmit=$('site-bar-search-go');this.domSearchField=$('site-bar-search-field');this.domSearchForm=$('site-bar-search-form');this.domAdvSearchLink=$('site-bar-advanced-search-link');this.panel=new SD.UI.SiteBar.SimplePanel({container:this,holder:this.dom,panel:this.domPanel,handle:$('site-bar-search-tab')});this.manager=manager;this.setup();},setup:function(){this.domSubmit.observe('click',function(e){e.stop();this.submitSearch();}.bind(this));this.dom.select('.submenu-inner-wrapper').invoke('observe','click',this.onPanelClicked.bind(this));this.domSearchField.observe('click',function(e){e.stop();});this.domSearchField.onkeypress=function(e){e=e||window.event;if(e.keyCode==13){this.submitSearch();Event.stop(e);}}.bind(this);this.domAdvSearchLink.onclick=function(){if(SD.Nav.oHash.page==="members"&&SD.Nav.oHash.action==="search"){SD.UI.SearchPanel.show();}else{SD.Event.observeOnce(null,SD.Nav.Events.CONTENT_LOADED,SD.UI.SearchPanel.show);}};this.setupForm(this.options);SD.Event.observe(null,SD.UIController.Events.SEARCH_CONTEXT_UPDATED,SD.UI.SiteBar.Search.onSearchContextUpdated);},onSearchContextUpdated:function(e){SD.UI.SiteBar.Search.setupForm(e.memo);},setupForm:function(params){$H(params).each(function(pair){SD.UI.SiteBar.Search.domSearchForm.elements[pair.key].value=pair.value;})},submitSearch:function(){if(this.domSearchField.value==this.domSearchField.getAttribute('sdLabel')){this.domSearchField.value='';SD.NavUtils.goTo('members','search',this.domSearchForm.serialize());this.domSearchField.value=this.domSearchField.getAttribute('sdLabel');}else{SD.NavUtils.goTo('members','search',this.domSearchForm.serialize());}
this.panel.hide();},onPanelClicked:function(e){if(e.target.nodeName.toLowerCase()=='a'){this.panel.hide.bind(this.panel).delay(0.5);}},freeze:function(){this.panel.freeze();},unfreeze:function(){this.panel.unfreeze();}};SD.UI.Notification=Class.create(SD.Utils.Class,{initialize:function(){this.stayTime=8;this.showsInStaticList=true;this.showsInIndicator=true;},parse:function(domRoot){if(this.parseLibrary){SD.Utils.Parser.parse({domRoot:domRoot,parseLibrary:this.parseLibrary,context:this});}
this.onAfterParse(domRoot);},onAfterParse:function(domRoot){},parseLibrary:{}});SD.UI.AlertNotification=Class.create(SD.UI.Notification,{initialize:function($super,alertRecord,options){$super();options=options||{};this.manager=options.manager;this.alertRecord=alertRecord;this.NAME_MAX_LENGTH=12;this.LOCATION_MAX_LENGTH=14;this.templates=SD.UI.Alerts.Templates;this.tpl=this.buildTemplate(this.alertRecord.type);},buildTemplate:function(type){return this.templates[this.templates.config[type]['tplBuilder']](type,this.templates);},nameFilter:function(name){return(name.length>this.NAME_MAX_LENGTH)?name.truncate(this.NAME_MAX_LENGTH):name;},locationFilter:function(loc){return(loc.length>this.LOCATION_MAX_LENGTH)?loc.truncate(this.LOCATION_MAX_LENGTH):loc;},populate:function(tpl,user){if(SD.Config.isSite){return(typeof tpl=='string'?tpl:tpl()).interpolate({name:this.nameFilter(user.username),city:this.locationFilter(user.city_name),thumb:user.images[0].thumbnail_url,age:user.age,uid:user.uid,username:user.username.ucfirst().excerpt(12),small_pic_url:user.square_image_url,is_online:'true',buddy_online_class:user.online?'buddy-online':'',im_online:''+user.im_online});}else{return(typeof tpl=='string'?tpl:tpl()).interpolate({name:this.nameFilter(user.username),city:this.locationFilter(user.city_name),thumb:user.images[0].thumbnail_url,age:user.age});}},render:function(){return""+"<div class='notification-item lib-alert-notification' style='display:none'>"+"<div class='alert-content'>"+this.populate(this.tpl,SD.User.get(this.alertRecord.uid))+"</div>"+"<div class='notification-closer'>X</div>"+"</div>";},getStayTime:function(){return this.stayTime;},parseLibrary:{'lib-alert-view-profile':function(el){el.observe('click',SD.ProfileViewer.UI.view.bind(SD.ProfileViewer.UI,this.alertRecord.uid));el.observe('mouseover',function(){var username=SD.User.get(this.alertRecord.uid).username;username&&SD.Tooltip.show("View <b>"+username+"'s</b> profile");}.bind(this));el.observe('mouseout',SD.Tooltip.hide.bind(SD.Tooltip));el=null;},'lib-alert-chat':function(el){SD.FlirtWink.View.registerInputChat(el,function(user){return user}.curry(SD.User.get(this.alertRecord.uid)));el=null;},'lib-alert-read-flirt':function(el){el.observe('click',this._onReadMessage.bind(this));},'lib-alert-view-wink':function(el){el.observe('click',this._onViewWink.bind(this));},'lib-flirt-link':function(el){el.onclick=function(e){SD.Event.fire(null,SD.UI.Events.DASHBOARD_INBOX_CLICKED,{domEvent:e||window.event})};el=null;},'lib-viewed-link':function(el){el.onclick=function(e){SD.Event.fire(null,SD.UI.Events.NOTIFICATION_LIKES_ME_CLICKED,{pageType:'viewedMe',domEvent:e||window.event});};el=null;},'lib-favorited-link':function(el){el.onclick=function(e){SD.Event.fire(null,SD.UI.Events.NOTIFICATION_LIKES_ME_CLICKED,{pageType:'favoritedMe',domEvent:e||window.event});};el=null;},'lib-want-to-speeddate-link':function(el){el.onclick=function(e){SD.Event.fire(null,SD.UI.Events.NOTIFICATION_LIKES_ME_CLICKED,{pageType:'invitedMe',domEvent:e||window.event});};el=null;},'lib-alert-chat-attempt-action':function(el){el.onclick=function(e){SD.Event.fire(null,SD.UI.Events.NOTIFICATION_LIKES_ME_CLICKED,{pageType:'triedToChatWithMe',domEvent:e||window.event});}.bind(this);el=null;},'lib-alert-message-attempt-action':function(el){el.onclick=function(e){SD.Event.fire(null,SD.UI.Events.NOTIFICATION_LIKES_ME_CLICKED,{pageType:'triedToEmailMe',domEvent:e||window.event});}.bind(this);el=null;},'lib-resume-speeddating':function(el){el.onclick=function(){SD.Event.observeOnce(null,SD.UserFilters.UI.Events.START_SPEEDDATING,function(){SD.UIController.infoMessage('Speeddating Resumed');});SD.UserFilters.UI.startSpeedDating();}
el=null;}},_onReadMessage:function(e){SD.Event.fire(null,SD.UI.Events.VIEW_CONVERSATION,{viewMessageUrl:SD.NavUtils.link('messages','flirt',{id:this.alertRecord.uid}),domEvent:e,sourceUI:SD.UI.Elements.NOTIFICATION,sourceMemberId:this.alertRecord.uid});},_onViewWink:function(e){this.onReadMessage(e);}});SD.UI.HtmlNotification=Class.create(SD.UI.Notification,{initialize:function($super,options){$super();options=options||{};this.manager=options.manager||SD.UI.SiteBar.Notifications;this.renderer=options.renderer;this.html=options.html;this.parseLibrary=Object.extend(this.parseLibrary,options.parseLibrary||{});this.showsInStaticList=options.showsInStaticList==null?false:options.showsInStaticList;this.showsInIndicator=options.showsInIndicator==null?false:options.showsInIndicator;this.stayTime=options.stayTime==null?8:options.stayTime;},render:function(){if(this.renderer){return this.renderer.render();}else if(this.html){return this.html;}
return'';},getStayTime:function(){return this.stayTime;}});SD.UI.SiteBar.DatingReminder=Class.create({initialize:function(notificationManager){this.isReminderRunning=false;this.timerReminder=null;this.remindsCounter=0;this.notificationManager=notificationManager;this.setup();},setup:function(){this.DatingReminderRenderer={render:function(){return""+"<div class='notification-item' style='display:none'>"+"<div class='alert-content'>"+SD.UI.Alerts.TemplatesSite.bodyReminder+"</div>"+"<div class='notification-closer'>X</div>"+"</div>";}};SD.Event.observe(null,SD.UserFilters.UI.Events.START_SPEEDDATING,this.stopReminderTimer.bind(this));SD.Event.observe(null,SD.UserFilters.UI.Events.PAUSE_SPEEDDATING,this.startRandomReminder.bind(this));},startRandomReminder:function(){if(this.isReminderRunning){return;}
var getRandomInterval=function(){return 60*(2000+Math.random()*1000);};var scheduleReminder=function(){this.timerReminder=setTimeout(function(){this.notificationManager.store.add(new SD.UI.HtmlNotification({renderer:this.DatingReminderRenderer}));this.remindsCounter++;if(this.remindsCounter<10)
scheduleReminder();}.bind(this),getRandomInterval());}.bind(this);scheduleReminder();this.isReminderRunning=true;},stopReminderTimer:function(){clearTimeout(this.timerReminder);this.remindsCounter=0;this.isReminderRunning=false;}});SD.UI.SiteBar.Notifications={init:function(options,manager){options=options||{};this.dom=$('site-bar-notifications');this.domIndicator=$('site-bar-notifications-ind');this.domActiveIndicator=this.dom.select('.active-ind').first();this.domTab=$('notifications-tab');this.domStaticWrapper=$('site-bar-notifications-wrapper');this.domTitle=$('site-bar-notifications-title');this.manager=manager;this.store=new SD.Data.Store({idField:'nid'});this.panel=new SD.UI.SiteBar.Panel({container:this,holder:this.dom,panel:this.dom.select('.submenu-wrapper').first(),handle:$('notifications-tab')});this.newNotifications=0;this.totalNotifications=0;this.remindsCounter=0;this.queue=[];this.notificationStayFaster=4;this.areNotificationsOn=true;if(SD.Model.getMyself().login_count==1&&SD.Model.getMyself().sex=="F"){this.turnOffDynamicNotifications();this.turnOnDynamicNotifications.bind(this).delay(15*60);}
this.datingReminder=new SD.UI.SiteBar.DatingReminder(this);this.setup();},setup:function(){this.panel.freeze();SD.Event.observe(SD.Store.Alerts,SD.Data.IStore.Events.RECORD_ADDED,function(e){var alertRecord=e.memo.record;if(alertRecord.type=="LOGIN"){return;}
SD.User.fetch(SD.User.get(alertRecord.uid),function(){this.store.add(new SD.UI.AlertNotification(alertRecord));}.bind(this));}.bind(this));SD.Event.observe(this.store,SD.Data.IStore.Events.RECORD_ADDED,function(e){this._onNotification(e);if(e.memo.record.showsInIndicator){this.totalNotifications++;this.updateIndicator(this.totalNotifications);}}.bind(this));SD.Event.observe(this.panel,SD.UI.SiteBar.Panel.Events.SHOW_PANEL,this.onShowPanel.bind(this));SD.Event.observe(this.panel,SD.UI.SiteBar.Panel.Events.HIDE_PANEL,this.onHidePanel.bind(this));},updateIndicator:function(num){if(num>0){this.domIndicator.innerHTML=num;SD.Config.isSite?$(this.domIndicator.parentNode).show():this.domIndicator.show();this.domTitle.innerHTML='Notifications';}else{SD.Config.isSite?$(this.domIndicator.parentNode).hide():this.domIndicator.hide();this.domTitle.innerHTML='No Notifications';}},updateActiveIndicator:function(num){if(num>0){this.domActiveIndicator.innerHTML=SD.Config.isSite?'<span class="inner-label">New</span> '+num:num;$(this.domActiveIndicator.parentNode).show();}else{$(this.domActiveIndicator.parentNode).hide();}},onShowPanel:function(){if(this.store.getLength()==0)return;this.queue=[];var domDynamicWrapper=this.getDynamicWrapper();var items=domDynamicWrapper.select('div.notification-item');items.each(function(item){clearTimeout(item.timer1);item.timer1=null;});domDynamicWrapper.update('');this.newNotifications=0;this.updateActiveIndicator(0);domDynamicWrapper.hide();var records=this.store.getRecords();for(var i=records.length-1;i>=0;--i){if(records[i].showsInStaticList){this.insertItemAsLast(records[i],true);}}
SD.Event.fire(null,SD.UI.SiteBar.Notifications.Events.SHOW);},onHidePanel:function(){this.domStaticWrapper.update('');this.getDynamicWrapper().hide();SD.Event.fire(null,SD.UI.SiteBar.Notifications.Events.HIDE);},showAllNotifications:function(){var records=this.store.getRecords();for(var i=records.length-1;i>=0;--i){if(records[i].showsInStaticList){this.insertItemAsLast(records[i]);}}
SD.Event.fire(null,SD.UI.SiteBar.Notifications.Events.SHOW);},_onNotification:function(e){var notification=e.memo.record;if(this.panel.isMinimized){if(notification.showsInIndicator){this.panel.unfreeze();this.newNotifications++;this.updateActiveIndicator(this.newNotifications);}
if(SD.Config.isSite&&notification instanceof SD.UI.AlertNotification){if(this.queue.length==0&&this.getDynamicWrapper().select('.lib-alert-notification').length==0){this.renderNotification(notification);}else{this.queue.unshift(notification);}}else{this.renderNotification(notification);}}else{if(notification.showsInStaticList){this.insertItemAsFirst(notification);}}},renderNotification:function(notification){if(!this.areNotificationsOn){return;}
this.getDynamicWrapper().show();var el=this.insertDynamicItem(notification);this._scheduleItemStay(el,this.getStayTime(notification));},getStayTime:function(notification){var stay=notification.getStayTime();if(this.queue.length>0){stay=this.notificationStayFaster;}
return stay;},_scheduleItemStay:function(el,timeToStay){el.timer1&&clearTimeout(el.timer1);el.timer1=el.blindUp.bind(el,{duration:0.3,afterFinish:this.destroyDynamicItem.bind(this,el)}).delay(timeToStay);el.timeToStay=timeToStay;el.timestamp=new Date().getTime();},destroyDynamicItem:function(el){if(!el){return}
el.timer1&&clearTimeout(el.timer1);el.timer1=null;Element.GCScheduler.scheduleToClear($(el).descendants().concat(el));el.remove();this._onDestroyDynamicItem();},_onDestroyDynamicItem:function(){var domWrapper=this.getDynamicWrapper();if(domWrapper.immediateDescendants().length==0){domWrapper.hide();}
if(this.queue.length>0&&this.getDynamicWrapper().select('.lib-alert-notification').length==0){this.renderNotification.call(this,this.queue.pop());}},insertItemAsFirst:function(notification){var el=this.insertStaticItem(notification,'top');Effect.BlindDown(el,{duration:0.3,afterFinish:function(){this.panel.shim&&this.panel.positionShim(this.panel.domPanel);}.bind(this)});return el;},insertItemAsLast:function(notification,noEffect){var el=this.insertStaticItem(notification,'bottom');noEffect?el.show():Effect.BlindDown(el,{duration:0.3});return el;},insertDynamicItem:function(notification){this.getDynamicWrapper().insert({bottom:notification.render()});var el=this.getDynamicWrapper().immediateDescendants().last();notification.parse(el);var alertWrapper=el.select('.alert-wrapper').first();if(alertWrapper){alertWrapper.style.visibility='visible';}
var closer=el.select('.notification-closer').first();if(closer){closer.onclick=this.destroyDynamicItem.bind(this,el);}
el.observe('mouseenter',function(){clearTimeout(el.timer1);el.timer1=null;el.timeToStay=el.timeToStay-Math.max(0,(new Date().getTime())-el.timestamp)/1000;});el.observe('mouseleave',function(){this._scheduleItemStay(el,el.timeToStay==undefined?1:el.timeToStay);}.bind(this));Effect.BlindDown(el,{duration:0.3});return el;},insertStaticItem:function(notification,place){var el;var html=notification.render();var domWrapper=this.domStaticWrapper;if(place==='bottom'){domWrapper.insert({bottom:html});}else if(place==='top'){domWrapper.insert({top:html});}
domWrapper.select('.notification-closer').invoke('hide');var els=domWrapper.immediateDescendants();if(place==='bottom'){el=els.last();}else if(place==='top'){el=els.first();}
var closer=el.select('.notification-closer').first();if(closer){closer.style.display='none';}
this._setStaticWrapperDimensions.bind(this).defer();var alertWrapper=el.select('.alert-wrapper').first();if(alertWrapper){alertWrapper.style.visibility='visible';}
notification.parse(el);return el;},_setStaticWrapperDimensions:function(){var domWrapper=this.domStaticWrapper;var nMaxHeight=this._getStaticWrapperMaxHeight();domWrapper.parentNode.style.overflow='hidden';var height=domWrapper.offsetHeight;if(height>=nMaxHeight){domWrapper.style.overflowY='scroll';domWrapper.style.height=nMaxHeight+'px';}else{domWrapper.style.overflowY='visible';domWrapper.style.height='';}},_getStaticWrapperMaxHeight:function(){return parseInt(0.8*document.viewport.getHeight());},turnOffDynamicNotifications:function(){this.areNotificationsOn=false;},turnOnDynamicNotifications:function(){this.areNotificationsOn=true;},getDynamicWrapper:function(){if(!this.domDynamicWrapper){this.domDynamicWrapper=$(document.createElement("div"));this.domDynamicWrapper.className='alerts-container dynamic-notification-wrapper';this.domDynamicWrapper.style.visibility='';this.domDynamicWrapper.style.overflow='visible';document.body.appendChild(this.domDynamicWrapper);}
return this.domDynamicWrapper;},freeze:function(){this.panel.freeze();},unfreeze:function(){this.panel.unfreeze();}};SD.UI.SiteBar.Notifications.Events={SHOW:"SD.UI.SiteBar.Notifications.Events:SHOW",HIDE:"SD.UI.SiteBar.Notifications.Events:HIDE",LIST_UPDATED:"SD.UI.SiteBar.Notifications.Events:LIST_UPDATED"};SD.UI.CoolUISiteBar={};SD.UI.CoolUISiteBar.Base=Object.extend({},SD.UI.SiteBar.Base);SD.UI.CoolUISiteBar.Base.init=function(options){options=options||{};this.domSiteBar=$('site-bar');this.domHolder=this.domSiteBar.select('.site-bar-inner').first();this.curPanel=null;SD.UI.SiteBar.Notifications.init(options.notifications,this);SD.UI.SiteBar.MyProfile.init({},this);this.setup();};SD.UI.SiteBar.MyProfile={init:function(options,manager){options=options||{};this.dom=$('site-bar-profile');this.domPanel=this.dom.select('.submenu-wrapper').first();this.manager=manager;this.panel=new SD.UI.SiteBar.SimplePanel({container:this,holder:this.dom,panel:this.domPanel,handle:$('profile-tab')});},freeze:function(){this.panel.freeze();},unfreeze:function(){this.panel.unfreeze();}};
SD.PickDate={_window:null,_autoTryIndex:0,_answers:[],_me:null,_pickToken:0,_state:0,SHOW_LIMIT:3,_ask_cnt:0,_debugEnabled:false,_initialized:false,_pastShown:[],_lastShowTime:0,_lastSeekTime:0,_userSelectedSomeone:false,DELAY_BETWEEN_SEEKS:10000,MIN_ANSWER:2,MAX_ANSWER:5,_consecutiveCloseCnt:0,_matchmakerLimit:10,_selectedUids:[],_bothTypedUids:[],_lastMMSRequest:null,MMS_REQUEST_INTERVAL:40000,LOW_DPR_LIMIT:0.1,HGH_DPR_LIMIT:0.2,STATES:{IDLE:0,FETCHING_MATCHES:1,ASKING:2,PICKING:3},_debug:function(){this._debugEnabled&&console.log(arguments);},init:function(){this._me=SD.Model.getMyself();SD.Event.observe(null,SD.User.Events.USER_ONLINE,this._onPresenceChange.bind(this));SD.Event.observe(null,SD.User.Events.USER_OFFLINE,this._onPresenceChange.bind(this));SD.Event.observe(null,SD.Matchmaker.Events.MATCHES_FOUND,this._onMatchesFound.bind(this));this._initialized=true;new PeriodicalExecuter(this.seek.bind(this),3);SD.Event.observe(null,SD.Chat.Events.BOTH_TYPED,this._onBothTyped.bind(this));SD.Event.observe(null,SD.User.Events.DATE_RESULT_FETCHED,this._onDateResultReceived.bind(this));this.DELAY_BETWEEN_SEEKS=SD.ExperimentManager.DatingRetryInterval.value;},isActive:function(){return this._initialized;},isBothTyped:function(other){return this._bothTypedUids.indexOf(parseInt(other.uid))!=-1;},addSelectedDate:function(other){this._selectedUids.push(parseInt(other.uid));},getWaitTimeBetweenDates:function(){return 120000;},seek:function(){if(this._window){return;}
if(!SD.XMPP.isLoggedIn()){return;}
var waitTime=this.getWaitTimeBetweenDates();if(SD.UserInitiatedDate.timeSinceLastDateAdd()<=waitTime){return;}
var myStats=SD.UserInitiatedDate.getStats();var now=new Date().getTime();if(SD.DatingController._pc.amIdle()&&now-this._lastSeekTime>this.DELAY_BETWEEN_SEEKS&&SD.UserInitiatedDate.availableForANewDate()){this._lastSeekTime=now;this.findDate();}},findDate:function(){this._pickToken=Math.random()*10000>>>0;this._state=this.STATES.FETCHING_MATCHES;this._ask_cnt=0;var matches=SD.SpeedDateList.getUpcomingDates();if(matches&&matches.length>=this.MIN_ANSWER&&this._lastMMSRequest&&this._lastMMSRequest>Date.now()-this.MMS_REQUEST_INTERVAL){this._traverseMatches(matches);}else{this._lastMMSRequest=Date.now();SD.Matchmaker.matchMember(SD.Model.getMyself(),this._matchmakerLimit);}},isSelectedDate:function(user){return this._selectedUids.indexOf(parseInt(user.uid))!=-1;},_onMatchesFound:function(e){this._debug("matches found",e);if(this._state!=this.STATES.FETCHING_MATCHES){this._debug("matches came but i did not ask for them :s");return;}
var matches=e.memo.matches;this._traverseMatches(matches);},_traverseMatches:function(matches){this._answers=[];this._state=this.STATES.ASKING;matches.each(function(match){if(this._me.mightDate(match)){SD.RPC.call(match,"SD.UserInitiatedDate.__wouldYouDate",{automatedDate:true,startAutoDate:false,pickToken:this._pickToken,token:match.token,has_photo:this._me.has_photo,filter_no_photo:this._me.filter_no_photo},function(data){this._onAnswer(match,data);}.bind(this));this._ask_cnt++;}else{this._debug("received a match that i wont date :s",match);}}.bind(this));this._checkAnswersAndDisplay.bind(this).delay(6);},_makeAnswer:function(match,stats){return{match:match,stats:stats};},_onAnswer:function(from,data){if(this._state==this.STATES.ASKING){if(data&&data.answer&&data.pickToken==this._pickToken){this._answers.push(this._makeAnswer(from,data.stats));if(data.myInfo){data.myInfo.uid=from.uid;SD.User.updateUser(data.myInfo);}
if(this._answers.length>=this.SHOW_LIMIT||this._answers.length>=this._ask_cnt){this._checkAnswersAndDisplay.bind(this).delay(1);}}}},_incrementMatchmakerLimit:function(){if(this._matchmakerLimit<50){this._lastMMSRequest=null;this._matchmakerLimit+=5;}},_decrementMatchmakerLimit:function(){if(this._matchmakerLimit>10){this._lastMMSRequest=null;this._matchmakerLimit-=5;}},_calculateDistance:function(lat1,lng1,lat2,lng2){var toRad=function(n){return(n*Math.PI)/180;};var R=3963;var d=Math.acos(Math.sin(toRad(lat1))*Math.sin(toRad(lat2))+
Math.cos(toRad(lat1))*Math.cos(toRad(lat2))*Math.cos(toRad(lng2-lng1)))*R;return d;},_answerSort:function(answ1,answ2){if(answ1.score<answ2.score){return-1;}else if(answ2.score<answ1.score){return 1;}
return 0;},_calculatePenalty:function(value,min,max,block){var ratio;if(value==undefined||value==null){ratio=1;}else{ratio=(value-min)/(max-min);}
return Math.min(Math.floor(ratio*block),block);},_calculateAnswerScore:function(answer){var block=Math.pow(2,20);var score=0;block=block/2;var primaryStats=['n_active','n_waiting_to_start'];var secondaryStats=['n_open','n_started','n_finished','n_rec'];var stats=answer.stats;var that=this;var statFnc=function(prop){if(!stats){score+=that._calculatePenalty(null,0,10,block);}else{score+=that._calculatePenalty(stats[prop],0,10,block);}
block=block/2;};primaryStats.each(statFnc);var myEthnicities=SD.Model.getMyself().ethnicities;var myPreferredEthnicities=SD.Model.getMyself().preferredEthnicities;if(myEthnicities.length+myPreferredEthnicities.length){var found=0;var otherEthnicities=answer.match.ethnicities||[];var otherPreferredEthnicities=answer.match.preferredEthnicities||[];(myEthnicities.concat(myPreferredEthnicities)).each(function(eth){if(otherEthnicities.indexOf(eth)!=-1){found++;}});otherPreferredEthnicities.each(function(eth){if(myEthnicities.indexOf(eth)!=-1){found++;}});var max=(myEthnicities.length+myPreferredEthnicities.length);score=this._calculatePenalty(max-found,0,max,block);block=block/2;}
secondaryStats.each(statFnc);var distance=1000000;if(stats){distance=this._calculateDistance(this._me.lat,this._me.lng,stats.lat,stats.lng);}
score+=this._calculatePenalty(distance,0,500,block);answer.score=score;},_checkAnswersAndDisplay:function(){if(this._state!=this.STATES.ASKING){return;}
this._state=this.STATES.PICKING;if(this._answers.length<this.MIN_ANSWER){this._incrementMatchmakerLimit();}
if(this._answers.length>this.MAX_ANSWER){this._decrementMatchmakerLimit();}
if(this._answers.length<1){this._debug("nobody said yes :(");SD.Event.fire(null,this.Events.OUT_OF_OPTIONS);return;}
this._answers.each(this._calculateAnswerScore.bind(this));this._answers=this._answers.sort(this._answerSort.bind(this)).slice(0,3);this._autoTryIndex=0;this._tryToDateAnswersOneByOne();},_tryToDateAnswersOneByOne:function(){var answer=this._answers[this._autoTryIndex];if(!answer||!answer.match){SD.Event.fire(null,this.Events.OUT_OF_OPTIONS);return;}
var match=answer.match;this._autoTryIndex++;var waitTime=this.getWaitTimeBetweenDates();if(SD.DatingController._pc.amIdle()&&SD.UserInitiatedDate.availableForANewDate()&&SD.UserInitiatedDate.timeSinceLastDateAdd()>=waitTime){SD.UserInitiatedDate.dateUser(match,this._tryToDateAnswersOneByOne.bind(this),true);}},_onPresenceChange:function(e){if(!this._window){return;}
var user=e.memo.user;if(!user){return;}
var div=$('date_candidate_'+e.memo.user.uid);if(div){if(user.online){div.removeClassName('disabled');}else{div.addClassName('disabled');}}},_pickDate:function(users){var uids=users.collect(function(u){return parseInt(u.uid);});this._pastShown=uids.concat(this._pastShown);SD.User.fetchUsers(uids,this._showPickWindow.bind(this));},_showPickWindow:function(users){if(this._window){return;}
if(users.length<1){return;}
if(!SD.DatingController._pc.amIdle()){return;}
this._lastShowTime=new Date().getTime();this._userSelectedSomeone=false;SD.ExperimentManager.recordOutput('PickDatePopupShow',1,users.length);var names=[];users.each(function(u){names.push(u.username);SD.Online.Connections.addConnection(u);});var namesStr="";for(var i=0;i<names.length;i++){if(i>0&&i<names.length-1){namesStr+=", ";}else if(i>0){namesStr+="</b> and <b>";}
namesStr+=names[i];}
var headerData={count:users.length,names:namesStr,username:SD.Model.getMyself().username,is_are:users.length>1?(users.length>2?'are all':'are both'):'is',who_would:users.length>1?'Who would':'Would',choose_date:users.length>1?'choose':'date'};html=this.TEMPLATES.PICK_WINDOW.header.interpolate(headerData);users.each(function(u){html+=this.TEMPLATES.PICK_WINDOW.candidate.interpolate(u);}.bind(this));html+=this.TEMPLATES.PICK_WINDOW.footer.interpolate({count:users.length,display:this._consecutiveCloseCnt>1?'':'none',spaces:this._consecutiveCloseCnt>1?'&nbsp;&nbsp;':''});var winConfig={title:this._me.username+' you have a good problem!',content:html,top:80,width:700,draggable:false,closable:false,onAfterClose:function(){if(!this._userSelectedSomeone){this._consecutiveCloseCnt++;SD.ExperimentManager.recordOutput('PickDatePopupClose',1,1);}
this._window=null;}.bind(this),template:SD.Window.newStyle,className:"generic-popup-container pick-date"};this._window=SD.UIController.standardPopup(winConfig);this._window.open();},closeWindow:function(){this._window&&this._window.close();},_onSelect:function(uid){this._userSelectedSomeone=true;this._consecutiveCloseCnt=0;this._selectedUids.push(parseInt(uid));this.closeWindow();SD.UserInitiatedDate.dateUser(SD.User.get(uid));SD.ExperimentManager.recordOutput('PickDatePopupSelect',1,1);},_onBothTyped:function(e){var uid=parseInt(e.memo.other.uid);if(this._selectedUids.indexOf(uid)!=-1){SD.ExperimentManager.recordOutput('PickDateBothTyped',1,1);this._bothTypedUids.push(uid);}},_onPauseDate:function(){SD.ExperimentManager.recordOutput('PickDatePopupPauseDating',1,1);this._window&&this._window.close();SD.Event.fire(null,SD.UserFilters.UI.Events.PAUSE_SPEEDDATING);},_onDateResultReceived:function(e){if(e.memo.success){SD.ExperimentManager.recordOutput('PickDateMatch',1,1);}},openFake:function(cnt){cnt=cnt||3;cnt=Math.max(0,Math.min(cnt,3));var users=SD.FlirtWink.Controller.getFlirtees();this._pickDate(users.slice(0,cnt));},Events:{OUT_OF_OPTIONS:"sd_pick_date:out_of_options"},TEMPLATES:{PICK_WINDOW:{header:"<table>"+"<!--<tr><td colspan='#{count}'><div class='header'>#{username}, you have a good problem.</div></td></tr>-->"+"<tr><td colspan='#{count}'><div class='subheader'><b>#{names}</b> #{is_are} interested in a SpeedDate&trade; right now!</div></td></tr>"+"<tr><td colspan='#{count}'><div class='cta'>#{who_would} you like to #{choose_date} ?</div></td></tr>",candidate:"<td align='center'><div id='date_candidate_#{uid}' class='date-candidate'>"+"<a href='javascript:SD.PickDate._onSelect(#{uid})' class='choose-one-member'>"+"<img src='#{image_url}'/><br />"+"<div class='username'><div class='online'></div>#{username}, #{age}</div>"+"<span class='medium-green medium-button'>"+"<span class='fw-chat-enabled'>"+"<i class='profile-icon'></i>Start SpeedDate&trade;"+"</span>"+"<!--<span class='fw-chat-disabled'>"+"<i class='profile-icon'></i>User Offline"+"</span>-->"+"</span><div class='clear'></div></a>"+"</div></td>",footer:"</tr>"+"<tr><td align='right' colspan='#{count}'>"+"<div class='pause-dating'><a href='javascript:SD.PickDate.closeWindow()'>Not Now &raquo;</a></div>#{spaces}"+"<div style='display:#{display}' class='pause-dating'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='javascript:SD.PickDate._onPauseDate()'>Pause SpeedDating&trade; &raquo;</a></div></td></tr>"+"</table>"}}};
SD.UserInputFilter={FILTER_ALL:0xFF,FILTER_EMAIL:0x01,FILTER_NUMBER:0x02,FILTER_BAD_WORD:0x04,FILTER_KEYWORD:0x08,FILTER_CREDIT_CARD:0x10,CHAT:'chat',MESSAGE:'message',PROFILE:'profile',OTHER:'other',rules:{0x01:[{clean:/[^\na-zA-Z0-9@]/ig,filter:/(@|y+(a|e|3|4|5)+h*(o|0|u)+|a+t+y+(a|e|3|4|5)+h+(o|0|u)*|a+t+y+(a|e|3|4)+h*(o|0|u)+|h+(o+|0+)?t+m+((l|1)+|((a|e|3|4)+(i|1)*(l|1)+)|a)|a+t+h+(o|0)*t+(m+((l|1)+|((a|e|3|4)+(i|1)*(l|1)+)|a+)?)?|h+m+(l|1)+|m+s+n+|s+k+y+p+(a|e|o|3|4)*|m+(a|e|3|4)*s+(a|e|3|4)*n+g+(a|e|3|4)*r+|a+(o+|0+)(l|1)+|f+(a|e|3|4)*c+(a|e|3|4)*b+(o|0)*k+?|fb(o|0)*k|g+m+(a+(i|1)+)?(l|1)+|g+t+a+(l|1)+k+)/img},{clean:/[^\na-zA-Z0-9 ]/ig,filter:/(( +|^)(y *)+((h *)+)+((o|0|u| *)+)+)|( +|^)(a *)+(t *)+(y *)+(a *|e *|3 *|4 *)+(h *)+(o|0|u| )*/img},{clean:/[^\na-zA-Z0-9 ]/ig,filter:/( +|^)(h *)+((o *)+|(0 *)+)?(t *)+(m *)+(((l|1) *)+|(((a *)+|(e *)+|(3 *)+|(4 *)+)((i|1) *)*((l|1) *)+)|(a *))/img},{clean:/[^\na-zA-Z0-9 ]/ig,filter:/( +|^)(a+ *)+((i|1)+ *)+m+/img},{clean:/[^\na-zA-Z0-9 ]/ig,filter:/(( +|^)y+m+|[^g]y+m+ |( +|^)y+h+|y+h+( +|$)|( +|^)h+t+|( +|^)f+b+|^f+b+$|( +|^)s+n+|( +|^)y+(i|1)+m+|( +|^)a+ *t+ +y( +|$))/img},{clean:/[^\na-zA-Z0-9]/ig,filter:/((d+(o|0)*t+)(c+(o|0)+m+|n+e+t+|(o|0)+r+g+|f+r+|u+k+|c+(l|1)+))/img},{clean:/[^\na-zA-Z0-9.]/ig,filter:/((\.(c+(o|0)+m+|n+e+t+|(o|0)+r+g+|f+r+|u+k+|c+(l|1)+)))/img},{clean:/[^\na-zA-Z0-9 ]/ig,filter:/(( +|^)(d+(o|0)*t+|d+(o|0)*t+( +|$)|c+(o|0)*m+( +|$)))/img},{clean:/[^\na-zA-Z0-9]/ig,filter:/(e*m+a+(i|1)+(l|1)+)/img}],0x02:[{clean:/[^\na-zA-Z0-9:]/ig,filter:/([0-9][0-9][0-9][0-9][0-9]+)/img}],0x04:[],0x08:[{clean:/[^\na-zA-Z0-9]/ig,filter:/f+r+(i|1)+e+n+d+s+t+e+r+|p+u+(l|1)+p+c+(i|1)+t+y+|t+a+g+e+d+|o+p+t+o+n+(l|1)+(i|1)+n+e+|m+y+s+p+a+c+e+|c+o+n+t+a+c+t+(i|1)+n+f+o+|y+e+(l|1)+o+w+s+m+(i|1)+(l|1)+e*/img},{clean:/[^\na-zA-Z0-9]/ig,filter:/s+c+r+e*n+a*m+e*|c+a*m+o+d+e*(l|1)+/img}],0x10:[{clean:/[^\na-zA-Z0-9]/ig,filter:/m+(a|e|3|4)*s+t+(a|e|3|4)*r+c+(a|e|3|4)+r+d+/img},{clean:/[^\na-zA-Z0-9]/ig,filter:/v(i|1)s(a|e|3|4)/img},{clean:/[^\na-zA-Z0-9-]/ig,filter:/[0-9]{16}/img},{clean:/[^\na-zA-Z0-9-]/ig,filter:/([0-9]{4}-){3}[0-9]{4}/img}]},checkRules:function(text,rules){for(var i=0;i<rules.length;++i){if(text.replace(rules[i].clean,'').match(rules[i].filter)){return false;}}
return true;},isValid:function(text,rules){rules=rules||SD.UserInputFilter.FILTER_ALL;text=text.replace(/<br[^>]*>/img,"\n");text=text.replace(/<\/?[^>]*>/img,"");text=text.replace(/\( *\)/img,"o");var tmpResult=true;for(key in SD.UserInputFilter.rules){tmpResult=SD.UserInputFilter.checkRules(text,SD.UserInputFilter.rules[key]);if((key&rules)&&!tmpResult){return false;}}
return true;},getFilteredTextByRule:function(text,rules){var result=Array();for(var i=0;i<rules.length;++i){if(text.replace(rules[i].clean,'').match(rules[i].filter)){result.push(text.replace(rules[i].clean,'').replace(rules[i].filter,'<font color=red>$&</font>'));}}
return result;},getFilteredText:function(text,rules){rules=rules||SD.UserInputFilter.FILTER_ALL;text=text.replace(/<br[^>]*>/img,"\n");text=text.replace(/<\/?[^>]*>/img,"");text=text.replace(/\( *\)/img,"o");var result=Array();var tmpResult=Array();for(key in SD.UserInputFilter.rules){tmpResult=SD.UserInputFilter.checkRules(text,SD.UserInputFilter.rules[key]);if((key&rules)&&!tmpResult){result.push(SD.UserInputFilter.getFilteredTextByRule(text,SD.UserInputFilter.rules[key]));}}
return result;},getFilterScoreByRule:function(text,rules){var result=0;for(var i=0;i<rules.length;++i){if(text.replace(rules[i].clean,'').match(rules[i].filter)){result++;}}
return result;},getFilterScore:function(text,rules){rules=rules||SD.UserInputFilter.FILTER_ALL;text=text.replace(/<br[^>]*>/img,"\n");text=text.replace(/<\/?[^>]*>/img,"");text=text.replace(/\( *\)/img,"o");var result=0;var tmpResult=0;for(key in SD.UserInputFilter.rules){tmpResult=SD.UserInputFilter.checkRules(text,SD.UserInputFilter.rules[key]);if((key&rules)&&!tmpResult){result+=SD.UserInputFilter.getFilterScoreByRule(text,SD.UserInputFilter.rules[key]);}}
return result;},trackFilter:function(sourceType){new Ajax.Request(SD.NavUtils.link('ajax','trackFilter'),{method:'get',parameters:{sourceType:sourceType}});},rulesToPlist:function(){var mainTemplate=''+'<?xml version="1.0" encoding="UTF-8"?>'+'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">'+'<plist version="1.0">'+'<dict>'+'<key>disclaimer</key>'+'<string>This File is auto-generated from static/site/js/sd.user_input_filter.js::rulesToPlist method -- yigit</string>'+'<key>rules</key>'+'<dict>'+'#{content}'+'</dict>'+'</dict>'+'</plist>';var typeTemplate=''+'<key>#{type}</key>'+'<array>'+'#{content}'+'</array>';var ruleTemplate=''+'<dict>'+'<key>clean</key>'+'<string>#{clean}</string>'+'<key>filter</key>'+'<string>#{filter}</string>'+'</dict>';var typesStr="";for(var type in this.rules){if(!this.rules.hasOwnProperty(type)){continue;}
var typeXML="";var rulesStr="";for(var rule in this.rules[type]){if(!this.rules[type].hasOwnProperty(rule)){continue;}
var clean=""+this.rules[type][rule]["clean"];var filter=""+this.rules[type][rule]["filter"];rulesStr+=ruleTemplate.interpolate({"clean":clean.substr(1,clean.lastIndexOf('/')-1),"filter":filter.substr(1,filter.lastIndexOf('/')-1)});}
var typeName=type;for(var i in this){if(this[i]==type&&i.match(/FILTER_/).length){typeName=i.substring("FILTER_".length).toLowerCase();break;}}
typesStr+=typeTemplate.interpolate({"type":typeName,"content":rulesStr});}
return mainTemplate.interpolate({"content":typesStr});}};document.observe('dom:loaded',function(){if(SD.ExperimentManager&&SD.ExperimentManager.AddMoreWordsToFilter_4258.value){var key4258=SD.UserInputFilter.FILTER_BAD_WORD;SD.UserInputFilter.rules[key4258]=[{clean:/[^\na-zA-Z0-9]/ig,filter:/3-way|anal|anal ?sex|anus|ass|asshole|ass-hole|bastard|beatoff|beat ?off/img},{clean:/[^\na-zA-Z0-9]/ig,filter:/bestiality|bitch|bj|blowjob|bondage|boner|boob|breast|bukkake|bullshit/img},{clean:/[^\na-zA-Z0-9]/ig,filter:/butt ?fuck|butthole|butt ?sex|cameljockey|camel ?jockey|chink|circlejerk/img},{clean:/[^\na-zA-Z0-9]/ig,filter:/circle ?jerk|clit|cock|condom|coolie|coon|coot|cornhole|crazy ?sex|cum/img},{clean:/[^\na-zA-Z0-9]/ig,filter:/cunnilingus|cunt|dago|deep ?throat|deep-throat|deepthroating|dick|dickhead/img},{clean:/[^\na-zA-Z0-9]/ig,filter:/dickwad|dike|dildo|doggie-style|doggy-style|dog-style|douche ?bag|dp|dyke/img},{clean:/[^\na-zA-Z0-9]/ig,filter:/eatme|eat ?me|erection|erotic|explicit|fag|faggot|fellatic|fellatio|fetish/img},{clean:/[^\na-zA-Z0-9]/ig,filter:/fingered|fingering|fisting|fist ?party|fleshflute|flesh ?flute|flesh ?popsicle/img},{clean:/[^\na-zA-Z0-9]/ig,filter:/fleshpopsicle|footjob|fornicate|fuc|fuck|fucking|fudgepacking|fuk|gangbang/img},{clean:/[^\na-zA-Z0-9]/ig,filter:/gang ?bang|genital|genitalia|getlaid|get ?laid|glory ?hole|gob ?the ?knob/img},{clean:/[^\na-zA-Z0-9]/ig,filter:/gobtheknob|golden ?shower|goldenshower|gook|gringo|hairpie|handjob|hard-on/img},{clean:/[^\na-zA-Z0-9]/ig,filter:/hardon|hentai|homo|honkey|hooker|horny|hustler|incest|inseminate|jack ?off/img},{clean:/[^\na-zA-Z0-9]/ig,filter:/jackoff|jerkoff|jerk ?off|jewboy|jiggaboo|jizz|kike|lesbo|limey|manload/img},{clean:/[^\na-zA-Z0-9]/ig,filter:/manloaf|masturbate|masturbation|milf|molest|muff ?dive|muffdive|muffdiver/img},{clean:/[^\na-zA-Z0-9]/ig,filter:/muff ?diver|nigger|nigga|niggaz|nipple|nude|nudity|nutsack|oily-bj|oral ?sex/img},{clean:/[^\na-zA-Z0-9]/ig,filter:/orgasm|orgie|orgy|outdoor ?sex|paki|panface|panties|pedophil|pedophile/img},{clean:/[^\na-zA-Z0-9]/ig,filter:/penetrate|penis|poontang|porn|porking|pubic|pussy|pussies|queef|queer/img},{clean:/[^\na-zA-Z0-9]/ig,filter:/raghead|rape|rimjob|rimming|ruby ?red ?bag|rubyredbag|schlong|scrotum|semen/img},{clean:/[^\na-zA-Z0-9]/ig,filter:/sex|sexually ?explicit|shemale|shit|sit ?on ?my ?face|sixty-nine|sixtynine|slag/img},{clean:/[^\na-zA-Z0-9]/ig,filter:/slant|slut|sodomize|spank ?the ?monkey|spankthemonkey|spearchucker|sperm/img},{clean:/[^\na-zA-Z0-9]/ig,filter:/spic|spooge|squirts|teabagging|testicles|threesome|three-way|tit/img},{clean:/[^\na-zA-Z0-9]/ig,filter:/tits|topless|twat|twink|uncircumcised|urination|vagina|vibrator|voyeur/img},{clean:/[^\na-zA-Z0-9]/ig,filter:/wanking|wetback|whackoff|whack ?off|whip ?it ?out|whipitout|whiteswallow/img},{clean:/[^\na-zA-Z0-9]/ig,filter:/white ?swallows|whore|wop/img}];}});
SD.UI.FormElement=Class.create(SD.Utils.Class,{initialize:function(form,name,value){this.form=$(form);this.value=value;this.name=name;this.observe('change',this.onChange);},destroy:function(){this.form=null;},setValue:function(value){this.value=value;this.fire('change');},onChange:function(){}});SD.UI.FormElement.Events={CHANGE:"SD.UI.FormElement.Events:CHANGE"};SD.UI.SingleValueDomProxy=Class.create({initialize:function(form,name,value){this.dom=null;this.setup(form,name,value);this.setupEvents();},setup:function(domForm,domName,domValue){this.dom=$(document.createElement('input'));this.dom.type='hidden';this.dom.name=domName;this.dom.value=domValue;domForm&&$(domForm).appendChild(this.dom);},setupEvents:function(){},setValue:function(value){this.dom.value=value;},destroy:function($super){$super();this.dom.parentNode&&this.dom.remove();this.dom=null;}});SD.UI.Dropdown=Class.create(SD.UI.FormElement,{masterTemplate:'<div class="dropdown-ctrl" style="display:none">#{content}</div>',itemTemplate:new Template('<div class="dropdown-ctrl-item" sdValue="#{value}" sdIndex="#{index}">#{text}</div>'),initialize:function($super,options){$super(options.form,options.name,options.value);this.options=options;this.options.alignment=this.options.alignment||'left';this.isOpen=false;this.domHandle=$(this.options.domHandle);this.domSource=$(this.options.domSource);this.domContent=null;this.proxy=new SD.UI.SingleValueDomProxy(options.form,options.name,options.value);this.setupDom();this.setupEvents();},setupDom:function(){var ctrlInnerHTML=[];var domBuffer=document.createElement('div');domBuffer.innerHTML=this.domSource.innerHTML.unescapeHTML();var options=domBuffer.getElementsByTagName('select')[0].options;for(var i=0,len=options.length;i<len;i++){ctrlInnerHTML.push(this.itemTemplate.evaluate({value:(options[i].value!='')?options[i].value:options[i].text,text:options[i].text,index:i}));}
$(document.body).insert(this.masterTemplate.interpolate({content:ctrlInnerHTML.join('')}));this.domContent=$(document.body.lastChild);if(this.options.className){this.domContent.addClassName(this.options.className);}},setupEvents:function(){this.domHandle.observe('click',function(){this.isOpen?this.hideContent():this.showContent()}.bind(this));this.domContent.observe('click',function(e){this.selectItem(e.target)}.bind(this));this.boundDocumentClick=this.onDocumentClick.bind(this);this.boundLayoutUpdated=this.onLayoutUpdated.bind(this);SD.Event.observe(null,SD.Nav.Events.HASH_CHANGE,this.boundLayoutUpdated);Event.observe(window,'resize',this.boundLayoutUpdated);if(Prototype.Browser.IE6){this.domContent.observe('mouseover',function(e){var target=$(e.target)
target.hasClassName('dropdown-ctrl-item')&&target.addClassName('mod-on');});this.domContent.observe('mouseout',function(e){var target=$(e.target)
target.hasClassName('dropdown-ctrl-item')&&target.removeClassName('mod-on');});}},onLayoutUpdated:function(){if(this.isOpen){this.hideContent();}},onDocumentClick:function(e){if(e.target==this.domContent||e.target.descendantOf(this.domContent)||e.target==this.domHandle||e.target.descendantOf(this.domHandle)){return;}
this.hideContent();},onChange:function(){this.proxy.setValue(this.value);},selectByIndex:function(index){var domItem=this.getItems()[index];if(!domItem)return;this.value=domItem.getAttribute('sdValue');this.selectedIndex=index;},selectItem:function(dom){this.setValue(dom.getAttribute('sdValue'));this.selectedIndex=parseInt(dom.getAttribute('sdIndex'),10);this.hideContent();return this;},showContent:function(){this.domContent.show();this.position();this.isOpen=true;document.observe('click',this.boundDocumentClick);return this;},hideContent:function(){this.domContent.hide();this.isOpen=false;document.stopObserving('click',this.boundDocumentClick);return this;},position:function(){var handleDims=this.domHandle.getDimensions();var handleCoords=this.domHandle.cumulativeOffset();if(this.options.alignment=='left'){this.domContent.setStyle({top:(handleCoords.top+handleDims.height)+'px',left:handleCoords.left+'px'});}else if(this.options.alignment=='right'){this.domContent.setStyle({top:(handleCoords.top+handleDims.height)+'px',left:(handleCoords.left+handleDims.width-this.domContent.offsetWidth)+'px'});}
return this;},show:function(){this.domHandle.show();this.isOpen&&this.showContent();},hide:function(){this.domHandle.hide();this.isOpen&&this.hideContent();},getItems:function(){return $A(this.domContent.children);},addItem:function(text,value){this.domContent.insert(this.itemTemplate.evaluate({value:value||text,text:text,index:this.domContent.children?this.domContent.children.length:0}));return this;},removeItem:function(index){var item=this.getItems()[index];item&&this.domContent.removeChild(item);return this;},removeAllItems:function(){this.isOpen&&this.hideContent();this.domContent.update();return this;},destroy:function(){this.domHandle.stopObserving();this.domContent.stopObserving();document.stopObserving('click',this.boundDocumentClick);Event.stopObserving(window,'resize',this.boundLayoutUpdated);SD.Event.stopObserving(null,SD.Nav.Events.HASH_CHANGE,this.boundLayoutUpdated);this.domHandle=null;this.domSource=null;this.domContent=null;}});
SD.Smileys={template:'<img src="#{file}" style="height:18px;width:18px" onload="this.style.width=\'\'">',emoticonsPath:'/static/site/images/smileys/',hashMap:{},smileys:{big_grin:{emoticons:[':D',':-D',';-D',';D',':d',':-d',';-d',';d'],file:'big_grin.gif'},cool:{emoticons:['B-)','B)','b-)','8-)','8)'],file:'cool.gif'},happy:{emoticons:[':)',':-)'],file:'happy.gif'},kiss:{emoticons:[':-*',':*'],file:'kiss.gif'},laughing:{emoticons:[':))'],file:'laughing.gif'},love_struck:{emoticons:[':x',':-x'],file:'love_struck.gif'},sad:{emoticons:[':(',':-('],file:'sad.gif'},sleepy:{emoticons:['|-)','|)'],file:'sleepy.gif'},straight_face:{emoticons:[':-|',':|'],file:'straight_face.gif'},surprise:{emoticons:[':o',':-o'],file:'surprise.gif'},talk_to_the_hand:{emoticons:[':;'],file:'talk_to_the_hand.gif'},thinking:{emoticons:[':-?',':?',':\\',':-/',':-\\',':/'],file:'thinking.gif'},tongue:{emoticons:[':p',':P',':-p',':-P',';p',';P',';-p',';-P'],file:'tongue.gif'},wave:{emoticons:[':-h',':h',':-H',':H'],file:'wave.gif'},winking:{emoticons:[';)',';-)'],file:'winking.gif'},yawn:{emoticons:['(:|'],file:'yawn.gif'}},init:function(){this.buildRegExp();},buildRegExp:function(){var a=[],i,j,len;for(i in this.smileys){for(j=0,len=this.smileys[i].emoticons.length;j<len;j++){a.push({emoticon:this.smileys[i].emoticons[j],file:this.smileys[i].file});}}
a=a.sort(function(a,b){return a.emoticon.length<b.emoticon.length?1:(a.emoticon.length>b.emoticon.length?-1:0);}).each(function(item){this.hashMap[item.emoticon]=item.file;},this).map(function(item){return RegExp.escape(item.emoticon)});this.regExp=new RegExp(a.join('|'),'g');},convert:function(text,smileyTemplate){var _this=SD.Smileys;var replacer=function(emoticon){var str=arguments[arguments.length-1];var pos=arguments[arguments.length-2];var isLink=str.slice(Math.max(pos-4,0),pos)=='http';return isLink?emoticon:_this.template.interpolate({file:_this.emoticonsPath+_this.hashMap[emoticon]});};return text.replace(_this.regExp,replacer);}};SD.Smileys.init();
SD.Test={DateFlow:{}};SD.Test.DateFlow={createDateWithVersion:function(uid,version){this.createDate(uid);},createSession:function(uid,ui,type,toActivate,options){function getData(user){return{meta:{user:user},dateHeader:{name:user.username.truncate(25),age:user.age,location:SD.User.renderLocation(user),distance:SD.User.renderDistance(user)},pictureGallery:{_url:SD.NavUtils.link('profile','view_images',{displayType:'ajax',uid:user.uid})},pictureGalleryV2:{_url:SD.NavUtils.link('profile','view_images',{displayType:'ajax',uid:user.uid,newMemberBadge:true})},dateProfile:{_url:SD.NavUtils.link('profile','view_profile',{displayType:'ajax',uid:user.uid})},dateToolbar:{isPremium:SD.Model.getMyself().is_premium,showExtendDateButton:true},dateProfileV1:{_url:SD.NavUtils.link('profile','view_profile',{displayType:'ajax',uid:user.uid,ver:1})},dateProfileV2:{_url:SD.NavUtils.link('profile','view_profile',{displayType:'ajax',uid:user.uid,ver:2})},dateProfileV3:{_url:SD.NavUtils.link('profile','view_profile',{displayType:'ajax',uid:user.uid,ver:3})},preferredAsl:{},tabData:{text:user.username.truncate(15)}};}
SD.User.fetch(SD.User.get(uid),function(user){var masterUI=SD.UI.DateUI.getUI();var data=getData(user);if(type==='chat'){masterUI.openChatPanel(data,toActivate,ui,options);}else{masterUI.openPanel(data,ui,options);}});},createDate:function(uid,ui){this.createSession(uid,ui,'date');},createChat:function(uid,ui,toActivate){this.createSession(uid,ui,'chat',toActivate);},showPostDateDialog:function(uid){SD.Model.getMyself().has_photo=false;SD.Model.getMyself().has_verified=false;SD.User.fetch(SD.User.get(uid),function(user){SD.UI.DateUI.getUI().showPostDateDialog(SD.UI.DateUI.getUI().getActivePanel().id,{uid:user.uid,name:user.username.truncate(25),pronoun:user.sex=='M'?'he':'she',pronoun_passive:user.sex=='M'?"him":"her"})});},flow:function(uid){this.createDate(uid);this.showPostDateDialog(uid);},showPostDateStepDialog:function(uid,step,isMyself){var me=SD.Model.getMyself();me.has_photo=false;me.is_verified=false;me.has_about_me=false;me.has_bounced=false;me.is_organic=false;if(step>0){me.has_photo=true;}
if(step>1){me.has_about_me=true;}
if(step>2){me.is_verified=true;me.is_organic=true;me.has_bounced=true;}
if(step>3){me.has_bounced=false;}
SD.User.fetch(SD.User.get(uid),function(user){SD.UI.DateUI.getUI().showPostDateDialog(SD.UI.DateUI.getUI().getActivePanel().id,{uid:user.uid,name:user.username.truncate(25),pronoun:user.sex=='M'?'he':'she',pronoun_passive:user.sex=='M'?"him":"her",isMyself:isMyself})});},flowToStep:function(uid,step,isMyself){if(isMyself==null){isMyself=false;}
SD.Test.DateFlow.createDate(uid);SD.Test.DateFlow.showPostDateStepDialog(uid,step,isMyself);},test3174:function(uid,step){SD.Test.randomNumber=0;[1,2,3,4,5,6].each(function(x){SD.Test.DateFlow.flowToStep.delay(x,uid,step,true);});},test3177:function(uid){SD.Test.randomNumber=0;[1,2,3,4,5,6].each(function(x){SD.Test.DateFlow.flowToStep.delay(x,uid,4);});},test317:function(uid){SD.Test.randomNumber=0;[0,1,2,3].each(function(x){SD.Test.DateFlow.test3174.delay(x*7,uid,x);});SD.Test.DateFlow.test3177.delay(25,uid);},openDate:function(offset){offset=offset||110;[1,2,3].each(function(x){(function(){SD.Model.getMyself().is_premium=x<0;SD.User.fetch(SD.User.get(x+offset),function(other){SD.UserInitiatedDate._addDate(other,true)});}).delay((x+2)*5);});},openChat:function(uid){uid=uid||104;SD.Chat.chatWithUser(SD.User.get(uid));}};SD.Test.BuddyList={addBuddies:function(num,baseUid){baseUid=baseUid||1012;var callback=function(u){SD.Event.fire(null,SD.User.Events.USER_ONLINE,{user:u});};for(var i=0;i<num;i++){SD.User.fetch(SD.User.get(baseUid+i),callback);}},removeBuddy:function(uid){}};SD.Test.DateList={addDates:function(num,baseUid){baseUid=baseUid||1012;for(var i=0;i<num;i++){this.addDate(baseUid+i);}},addDate:function(uid){var callback=function(u){if(u){SD.Event.fire(null,SD.SpeedDateList.Events.MATCH_ADDED,{match:u,totalCnt:SD.SpeedDateList._upcomingDates.length});}};SD.User.fetch(SD.User.get(uid),callback);},addNowDates:function(num,baseUid){baseUid=baseUid||1012;for(var i=0;i<num;i++){this.addNowDate(baseUid+i);}},addNowDate:function(uid){var callback=function(u){if(u){SD.Event.fire(null,SD.SpeedDateList.Events.DATE_ADDED,{match:u,totalCnt:SD.SpeedDateList._upcomingDates.length});}};SD.User.fetch(SD.User.get(uid),callback);},addNowDates:function(num,baseUid){baseUid=baseUid||1012;for(var i=0;i<num;i++){this.addNowDate(baseUid+i);}},addNowDate:function(uid){var callback=function(u){if(u){SD.Event.fire(null,SD.SpeedDateList.Events.DATE_ADDED,{match:u,totalCnt:SD.SpeedDateList._upcomingDates.length});}};SD.User.fetch(SD.User.get(uid),callback);},addWantedDates:function(num,baseUid){baseUid=baseUid||1012;for(var i=0;i<num;i++){this.addWantedDate(baseUid+i);}},addWantedDate:function(uid){var callback=function(u){if(u){SD.Event.fire(null,SD.SpeedDateList.Events.WANTED_DATE_ADDED,{match:u,totalCnt:SD.SpeedDateList._upcomingDates.length});}};SD.User.fetch(SD.User.get(uid),callback);},removeDateByIndex:function(index){var user=SD.SpeedDateList._upcomingDates[index]
if(user){this.removeDate(user);}},removeDate:function(user){if(typeof user==='string'||typeof user==='number'){user=SD.User.get(user);}
SD.Event.fire(null,SD.SpeedDateList.Events.MATCH_REMOVED,{match:user,totalCnt:SD.SpeedDateList._upcomingDates.length});}};SD.Test.Flows={isADone:false,init:function(){this.flow=new SD.RoundRobinBurstFlow({sig:'testFlow',runnables:[new SD.Action({id:'action A',sig:'action A',async:true,weight:Infinity,rules:{'task A should NOT be done':function(){return!SD.Test.Flows.isADone}},callFunc:function(context,runnable){SD.Test.Flows.dialogA(context,SD.Actions._continuationCallback.bind(SD.Actions,runnable));}}),new SD.Action({id:'action B',sig:'action B',async:true,callFunc:function(context,runnable){SD.Test.Flows.dialogB(context,SD.Actions._continuationCallback.bind(SD.Actions,runnable));},callContext:SD.Test.Flows}),new SD.Action({id:'action C',sig:'action C',async:true,callFunc:function(context,runnable){SD.Test.Flows.dialogC(context,SD.Actions._continuationCallback.bind(SD.Actions,runnable));},callContext:SD.Test.Flows})]});},parseLibrary:{".lib-close-dialog":function(el){var win=this;el.onclick=function(){win.close();}},".lib-do-task":function(el){var win=this;el.onclick=function(){SD.Test.Flows.isADone=true;win.close();}}},dialogA:function(context,continuationCallback){return SD.UIController.standardPopup({title:'Dialog A',content:"<p class='sd-window-msg'>Dialog A</p>"+"<button type='button' class='lib-close-dialog' style='padding:10px;'>Close</button>"+"<button type='button' class='lib-do-task' style='padding:10px;'>Do task A</button>",width:400,draggable:false,top:100,onAfterClose:function(ev){console.log(JSON.stringify(ev.memo));continuationCallback&&continuationCallback({closedByUser:ev.memo.closedByUser});},parseLibrary:this.parseLibrary}).open();},dialogB:function(context,continuationCallback){return SD.UIController.standardPopup({title:'Dialog B',content:"<p class='sd-window-msg'>Dialog B</p>"+"<button type='button' class='lib-close-dialog'>Close</button>",width:400,draggable:false,top:100,onAfterClose:function(ev){continuationCallback&&continuationCallback({closedByUser:ev.memo.closedByUser});},parseLibrary:this.parseLibrary}).open();},dialogC:function(context,continuationCallback){return SD.UIController.standardPopup({title:'Dialog C',content:"<p class='sd-window-msg'>Dialog C</p>"+"<button type='button' class='lib-close-dialog'>Close</button>",width:400,draggable:false,top:100,onAfterClose:function(ev){continuationCallback&&continuationCallback({closedByUser:ev.memo.closedByUser});},parseLibrary:this.parseLibrary}).open();}};SD.Test.Flows.init();SD.Test.Goals={init:function(){$(document).observe('dom:loaded',function(){if(!SD.ExperimentManager)return;var sampleInit={goals:[{type:'SD.Goals.CreateAccount',completed:true,enabled:true,tooltipCompleted:'Create Account - Completed!'},{type:'SD.Goals.PhotoUpload',completed:false,enabled:true,tooltip:'Become Popular!',tooltipCompleted:'Become Popular - Completed!'},{type:'SD.Goals.CompleteProfile',completed:false,enabled:true,tooltip:'Get more attention!',tooltipCompleted:'Get more attention - Completed!'},{type:'SD.Goals.VerifyEmail',completed:false,enabled:true,tooltip:'Get messages from other members!',tooltipCompleted:'Get messages from other members - Completed!'},{type:'SD.Goals.SocialPower',completed:false,enabled:true,tooltip:'Increase your social power!',tooltipCompleted:'Increase your social power - Completed!'},{type:'SD.Goals.IM',completed:false,enabled:true,tooltip:'Get notified when someone is online!',tooltipCompleted:'Get notified when someone is online - Completed!'},{type:'SD.Goals.SpeedVerify',completed:false,enabled:true,tooltip:'Authenticate your profile!',tooltipCompleted:'Authenticate your profile - Completed!'},{type:'SD.Goals.Subscribe',completed:false,enabled:true,tooltip:'Get full access!',tooltipCompleted:'Get full access - Completed!'},{type:'SD.Goals.Reward',completed:false,enabled:true,tooltip:'Get Reward!',tooltipCompleted:'You have taken your reward!'}]};if($('goal-bar')){SD.UI.GoalBar.Manager.init(sampleInit);}});}};SD.Test.Tooltips={createTooltip:function(f,context,uid){context=context||{};uid=uid||1020;SD.WindowManager.getItemsAsArray().filter(function(win){return win.type=="TooltipDialog"}).invoke('close');SD.User.fetch(uid,function(u){f.call(SD.UIController,Object.extend({sourceType:SD.UIController.PopupSourceTypes.EMAIL,sourceMemberId:u.uid,sourceMember:u,pageX:100,pageY:100,sourceElement:document.body},context))});},verify:function(context){this.createTooltip(SD.UIController.emailVerificationTooltip,context);},photo:function(context){this.createTooltip(SD.UIController.uploadPhotoTooltip,context);},profile:function(context){this.createTooltip(SD.UIController.aboutMeTooltip,context);},sms:function(context){this.createTooltip(SD.UIController.phoneNumberTooltip,context);},speedverify:function(context){this.createTooltip(SD.UIController.speedVerifyTooltip,context);},subscribe:function(context){this.createTooltip(SD.UIController.subscribeTooltip,context);},fbShare:function(context){this.createTooltip(SD.UIController.fbShareTooltip,context);},im:function(context){this.createTooltip(SD.UIController.imTooltip,context);},speedwink:function(context){this.createTooltip(SD.UIController.speedWinkTooltip,context);}}
Strophe.Builder.prototype.form=function(ns,options)
{var aX=this.node.appendChild(Strophe.xmlElement('x',{xmlns:"jabber:x:data",type:"submit"}));aX.appendChild(Strophe.xmlElement('field',{'var':"FORM_TYPE",type:"hidden"})).appendChild(Strophe.xmlElement('value')).appendChild(Strophe.xmlTextNode(ns));for(var i in options){aX.appendChild(Strophe.xmlElement('field',{'var':i})).appendChild(Strophe.xmlElement('value')).appendChild(Strophe.xmlTextNode(options[i]));}
return this;};Strophe.Builder.prototype.list=function(tag,array)
{for(var i=0;i<array.length;++i){var el=this.node.appendChild(Strophe.xmlElement(tag,array[i].attrs))
if(array[i].text){el.appendChild(Strophe.xmlTextNode(array[i].text));}}
return this;};Strophe.addNamespace('PUBSUB',"http://jabber.org/protocol/pubsub");Strophe.addNamespace('PUBSUB_SUBSCRIBE_OPTIONS',Strophe.NS.PUBSUB+"#subscribe_options");Strophe.addNamespace('PUBSUB_ERRORS',Strophe.NS.PUBSUB+"#errors");Strophe.addNamespace('PUBSUB_EVENT',Strophe.NS.PUBSUB+"#event");Strophe.addNamespace('PUBSUB_OWNER',Strophe.NS.PUBSUB+"#owner");Strophe.addNamespace('PUBSUB_AUTO_CREATE',Strophe.NS.PUBSUB+"#auto-create");Strophe.addNamespace('PUBSUB_PUBLISH_OPTIONS',Strophe.NS.PUBSUB+"#publish-options");Strophe.addNamespace('PUBSUB_NODE_CONFIG',Strophe.NS.PUBSUB+"#node_config");Strophe.addNamespace('PUBSUB_CREATE_AND_CONFIGURE',Strophe.NS.PUBSUB+"#create-and-configure");Strophe.addNamespace('PUBSUB_SUBSCRIBE_AUTHORIZATION',Strophe.NS.PUBSUB+"#subscribe_authorization");Strophe.addNamespace('PUBSUB_GET_PENDING',Strophe.NS.PUBSUB+"#get-pending");Strophe.addNamespace('PUBSUB_MANAGE_SUBSCRIPTIONS',Strophe.NS.PUBSUB+"#manage-subscriptions");Strophe.addNamespace('PUBSUB_META_DATA',Strophe.NS.PUBSUB+"#meta-data");Strophe.addConnectionPlugin('pubsub',{init:function(conn)
{this._connection=conn;this._autoService=true;this._service=null;},statusChanged:function(status,condition)
{if(this._autoService)
this._service=status===Strophe.Status.CONNECTED?'pubsub.'+Strophe.getDomainFromJid(this._connection.jid):null;},setService:function(service)
{this._autoService=false;this._service=service;},createNode:function(node,options,call_back)
{var iqid=this._connection.getUniqueId("createnode");var iq=$iq({from:this._connection.jid,to:this._service,type:'set',id:iqid}).c('pubsub',{xmlns:Strophe.NS.PUBSUB}).c('create',{node:node});if(options){iq.up().c('configure').form(Strophe.NS.PUBSUB_NODE_CONFIG,options);}
this._connection.addHandler(call_back,null,'iq',null,iqid,null);this._connection.send(iq.tree());return iqid;},deleteNode:function(node,call_back)
{var iqid=this._connection.getUniqueId("deletenode");var iq=$iq({from:this._connection.jid,to:this._service,type:'set',id:iqid}).c('pubsub',{xmlns:Strophe.NS.PUBSUB_OWNER}).c('delete',{node:node});this._connection.addHandler(call_back,null,'iq',null,iqid,null);this._connection.send(iq.tree());return iqid;},getConfig:function(node,call_back)
{var iqid=this._connection.getUniqueId("configurenode");var iq=$iq({from:this._connection.jid,to:this._service,type:'get',id:iqid}).c('pubsub',{xmlns:Strophe.NS.PUBSUB_OWNER}).c('configure',{node:node});this._connection.addHandler(call_back,null,'iq',null,iqid,null);this._connection.send(iq.tree());return iqid;},affiliate:function(node,list,call_back)
{var iqid=this._connection.getUniqueId("affiliatenode");var iq=$iq({from:this._connection.jid,to:this._service,type:'set',id:iqid}).c('pubsub',{xmlns:Strophe.NS.PUBSUB_OWNER}).c('affiliations',{node:node}).list('affiliation',list);this._connection.addHandler(call_back,null,'iq',null,iqid,null);this._connection.send(iq.tree());return iqid;},subscribe:function(node,options,event_cb,call_back)
{var iqid=this._connection.getUniqueId("subscribenode");var iq=$iq({from:this._connection.jid,to:this._service,type:'set',id:iqid}).c('pubsub',{xmlns:Strophe.NS.PUBSUB}).c('subscribe',{node:node,jid:this._connection.jid});if(options){iq.up().c('options').form(Strophe.NS.PUBSUB_SUBSCRIBE_OPTIONS,options);}
this._connection.addHandler(call_back,null,'iq',null,iqid,null);if(event_cb)this._connection.addHandler(event_cb,null,'message',null,null,null);this._connection.send(iq.tree());return iqid;},unsubscribe:function(node,subid,call_back)
{var iqid=this._connection.getUniqueId("unsubscribenode");var iq=$iq({from:this._connection.jid,to:this._service,type:'set',id:iqid}).c('pubsub',{xmlns:Strophe.NS.PUBSUB}).c('unsubscribe',{node:node,jid:this._connection.jid});if(subid)iq.attrs({subid:subid});this._connection.addHandler(call_back,null,'iq',null,iqid,null);this._connection.send(iq.tree());return iqid;},getSubOptions:function(node,subid,call_back)
{var iqid=this._connection.getUniqueId("suboptions");var iq=$iq({from:this._connection.jid,to:this._service,type:'get',id:iqid}).c('pubsub',{xmlns:Strophe.NS.PUBSUB}).c('options',{node:node,jid:this._connection.jid});if(subid)iq.attrs({subid:subid});this._connection.addHandler(call_back,null,'iq',null,iqid,null);this._connection.send(iq.tree());return iqid;},publish:function(node,itemid,builder,call_back)
{var iqid=this._connection.getUniqueId("publishnode");var iq=$iq({from:this._connection.jid,to:this._service,type:'set',id:iqid}).c('pubsub',{xmlns:Strophe.NS.PUBSUB}).c('publish',{node:node}).c('item',itemid?{id:itemid}:null).cnode(builder.tree());this._connection.addHandler(call_back,null,'iq',null,iqid,null);this._connection.send(iq.tree());return iqid;},publishAtomEntry:function(node,text,itemid,call_back)
{var en=$build('entry',{xmlns:'http://www.w3.org/2005/Atom'}).t(text);return this.publish(node,itemid,en,call_back);},items:function(node,call_back)
{var iq=$iq({from:this._connection.jid,to:this._service,type:'get'}).c('pubsub',{xmlns:Strophe.NS.PUBSUB}).c('items',{node:node});return this._connection.sendIQ(iq.tree(),call_back,call_back);}});
SD.PubSub={_debugEnabled:false,_waitingList:[],Nodes:{Dating:"live_dating",StartDate:"start_date"},debug:function(){this._debugEnabled&&$A(arguments).each(function(a){console.log(a)});},init:function(){this._pubsub=SD.XMPP.getStropheConnection().pubsub;this._pubsub.setService("pubsub."+SD.Config.XMPPServer.serverURL);SD.XMPP.getStropheConnection().rawInput=this.debug.bind(this);SD.Event.observe(null,SD.XMPP.Events.LOGIN,this._onLogin.bind(this));},create:function(node){var options={"pubsub#publish_model":"open","pubsub#presence_based_delivery":"1","pubsub#access_model":"open","pubsub#send_last_published_item":"never","pubsub#max_items":"0","pubsub#persist_items":"0"};this._pubsub.createNode(node,options,function(e){this.debug("create cb",e);}.bind(this));},subscribe:function(node,callBack){this._checkForConnection(this.subscribe,arguments)&&this._pubsub.subscribe(node,null,this._onEvent.bind(this),callBack||this._defaultCallback.bind(this));},unsubscribe:function(node,callBack){this._checkForConnection(this.unsubscribe,arguments)&&this._pubsub.unsubscribe(node,null,callBack||this._defaultCallback.bind(this));},fetchInitialItems:function(node,callBack){this._checkForConnection(this.fetchInitialItems,arguments)&&this._pubsub.items(node,function(result){Strophe.forEachChild(result,'pubsub',function(pubsub){this._parseItems(pubsub,true);}.bind(this));callBack&&callBack(result);}.bind(this));},publish:function(node,obj,callBack){var data=Object.toJSON(obj);if(this._checkForConnection(this.publish,arguments)){this._pubsub.publishAtomEntry(node,data,null,callBack||this._defaultCallback.bind(this));this._dispatch(node,obj);}},fakePublish:function(){var u1=SD.FlirtWink.Controller.getCurrentFlirtee();var u2=SD.FlirtWink.Controller.getNextFlirtee();SD.User.fetchUsers([u1.uid,u2.uid],function(users){this.publish(this.Nodes.Dating,{me:users[0].getDateFeedData(),you:users[1].getDateFeedData()});}.bind(this));},_checkForConnection:function(func,args){if(!SD.XMPP.isLoggedIn()){this._waitingList.push({func:func,args:args});return false;}
return true;},_onLogin:function(){var call=null;while(call=this._waitingList.shift()){var f=call.func;var args=call.args;f.apply(this,args);}},_parseItems:function(parent){var dispatch=[];Strophe.forEachChild(parent,'items',function(items){var node=items.getAttribute('node');Strophe.forEachChild(items,'item',function(item){Strophe.forEachChild(item,'entry',function(entry){try{var data=entry.childNodes[0].nodeValue;var obj=data.evalJSON();dispatch.push({node:node,obj:obj});}catch(e){}}.bind(this));}.bind(this));}.bind(this));dispatch.reverse().each(function(item){this._dispatch(item.node,item.obj);}.bind(this));},_onEvent:function(msg){this.debug("event:",msg);Strophe.forEachChild(msg,'event',function(event){this._parseItems(event);}.bind(this));return true;},_dispatch:function(node,obj){switch(node){case this.Nodes.Dating:SD.Event.fire(null,this.Events.DATE_ENTRY_RECEIVED,obj);break;case this.Nodes.StartDate:SD.Event.fire(null,this.Events.START_DATE_ENTRY_RECEIVED,obj);break;default:this.debug("unidentified items in atom feed:",node,obj);break;}},_defaultCallback:function(e){this.debug("default callback:",e);},Events:{DATE_ENTRY_RECEIVED:"sd.pub_sub:date_entry_received",START_DATE_ENTRY_RECEIVED:"sd.pub_sub:start_date_entry_received"}}
SD.DatingFeed={_debugEnabled:false,_nextContentIsMine:false,_container:null,_history:[],_subscribed:false,debug:function(){this._debugEnabled&&$A(arguments).each(function(a){console.log(a)});},init:function(){this._setupNavListeners();SD.Event.observe(null,SD.User.Events.DATE_RESULT_FETCHED,this._onDateResult.bind(this));SD.Event.observe(null,SD.UserInitiatedDate.Events.START_DATE,this._onDateStart.bind(this));SD.PubSub.unsubscribe(SD.PubSub.Nodes.Dating);},_onDateResult:function(e){if(!e.memo.user||(e.memo.user&&e.memo.user.uid===undefined)){return;}
if(e.memo.success){var other=e.memo.user;var me=SD.Model.getMyself();var myId=parseInt(me.uid);var otherId=parseInt(other.uid);if(myId<otherId){SD.PubSub.publish(SD.PubSub.Nodes.Dating,{me:me.getDateFeedData(),you:other.getDateFeedData()});}}},_onDateStart:function(e){var rec=e.memo;if(!rec){return;}
var me=SD.Model.getMyself();if(parseInt(me.uid)<parseInt(rec.other.uid)){SD.PubSub.publish(SD.PubSub.Nodes.StartDate,{me:me.getDateFeedData(),you:rec.other.getDateFeedData()});}},_getContainer:function(){this._container=$('dating_feed');return this._container;},start:function(){this.debug('starting dating feed.');this._getContainer();if(!this._container){this.debug("could not find dating feed content :s");return;}
if(!this._subscribed){SD.PubSub.subscribe(SD.PubSub.Nodes.Dating);this._subscribed=true;}
SD.PubSub.fetchInitialItems(SD.PubSub.Nodes.Dating);SD.Event.observe(null,SD.PubSub.Events.DATE_ENTRY_RECEIVED,this._onNewEntry.bind(this));this._history.each(this._addToUI.bind(this));},stop:function(){this.debug('stopping dating feed.');this._container=null;SD.Event.stopObserving(null,SD.PubSub.Events.DATE_ENTRY_RECEIVED,this._onNewEntry.bind(this));},_onNewEntry:function(e){var container=this._getContainer();if(!container){return;}
var entry=e.memo;if(this._addToHistory(entry)){this._addToUI(entry);}},_addToHistory:function(newEntry){var found=false;this._history.each(function(entry){if(entry.me&&entry.you&&newEntry.me&&newEntry.you&&entry.me.uid==newEntry.me.uid&&entry.you.uid==newEntry.you.uid){found=true;throw $break;}});if(found){return false;}
this._history.push(newEntry);return true;},_addToUI:function(entry){var tr=$(document.createElement('div'));tr.addClassName('dating-feed-row');var sex_pref=SD.Model.getMyself().sex_pref;var leftMatch;var rightMatch;if(sex_pref==entry.me.sex){leftMatch=entry.me;rightMatch=entry.you;}else{leftMatch=entry.you;rightMatch=entry.me;}
leftMatch.cssClass='left-match';rightMatch.cssClass='right-match';SD.Utils.Populator.append({domRoot:tr,template:this.TEMPLATES.item,data:leftMatch});SD.Utils.Populator.append({domRoot:tr,template:this.TEMPLATES.pic,data:leftMatch});SD.Utils.Populator.append({domRoot:tr,template:this.TEMPLATES.spacer});SD.Utils.Populator.append({domRoot:tr,template:this.TEMPLATES.pic,data:rightMatch});SD.Utils.Populator.append({domRoot:tr,template:this.TEMPLATES.item,data:rightMatch});!Prototype.Browser.IE&&tr.hide();if(!this._container.childElements()[1]){this._container.insert(tr);}else{this._container.childElements()[1].insert({before:tr});}!Prototype.Browser.IE&&Effect.Appear(tr,{duration:3});},_setupNavListeners:function(){SD.Event.observe(null,SD.Nav.Events.CONTENT_LOADED,function(e){this.debug("CONTENT LOADED");this.debug(e);if(this._nextContentIsMine){this.start();}}.bind(this));SD.Event.observe(null,SD.Nav.Events.HASH_CHANGE,function(e){this.debug("PAGE CHANGE");if(e&&e.memo&&e.memo.hashNew){if(e.memo.hashNew.page!="my_results"||(e.memo.hashNew.page=="my_results"&&e.memo.hashNew.action&&e.memo.hashNew.action!='dating_feed')){this._nextContentIsMine=false;}else{this._nextContentIsMine=true;}}}.bind(this));this.debug(SD.Nav.oHash);if(SD.Nav&&SD.Nav.oHash&&SD.Nav.oHash.page=="my_results"&&(!SD.Nav.oHash.action||SD.Nav.oHash.action=='dating_feed')){this.debug("enabling view...");this.start();}},fakeFeed:function(){var u1=SD.FlirtWink.Controller.getCurrentFlirtee();var u2=SD.FlirtWink.Controller.getNextFlirtee();this._addToUI({me:u1,you:u2});},TEMPLATES:{item:"<div class='dating-feed-cell  dating-feed-cell-name'>"+"<div class='feed-match #{cssClass}'> "+"<a href='javascript:void(0)' sdType='profile', sdUid='#{uid}' sdUserName='#{username}'>#{username}</a>, <span>#{age}</span>"+"<br/>#{city_name},#{country}"+"</div>"+"</div>",pic:"<div class='dating-feed-cell dating-feed-cell-pic'>"+"<div><img class='user-img' src='#{image_url}' sdType='profile', sdUid='#{uid}' sdUserName='#{username}'></div>"+"</div>",spacer:"<div  class='dating-feed-cell dating-feed-cell-spacer'> "+"<div class='feed-spacer'></div>"+"<div class='feed-spacer-matched'>MATCHED</div>"+"</div>"}}
SD.UI.SearchPanel={toggleField:function(memberInfoId){var selectedText=$('member-info-selected-'+memberInfoId);var filterList=$('member-info-filter-'+memberInfoId);if($('member-info-list-'+memberInfoId).hasClassName('collapsed')){$('member-info-list-'+memberInfoId).removeClassName('collapsed');selectedText.hide();filterList.show();}else{$('member-info-list-'+memberInfoId).addClassName('collapsed');filterList.hide();var checkedOptions=$('member-info-filter-'+memberInfoId).select('.search-checkbox').findAll(function(option){return option.checked;});if(checkedOptions.length===0){selectedText.update("");selectedText.hide();}else{selectedText.update(checkedOptions.collect(function(opt){return opt.getAttribute('textvalue');}).join(', '));selectedText.show();}}},clearAdvancedFilters:function(){$('advanced-search-container').select('.search-checkbox').each(function(el){el.checked=false;});},toggleAdvancedSearch:function(){if($('advanced-search-container').style.display=='none'){SD.UI.SearchPanel.show();}else{SD.UI.SearchPanel.hide();}},show:function(){$('advanced-search-header').removeClassName('collapsed');$('advanced-search-container').show();},hide:function(){$('advanced-search-header').addClassName('collapsed');$('advanced-search-container').hide();},saveSearch:function(){new Ajax.Request(SD.NavUtils.link('members','saveSearch'),{method:'post',evalJSON:false,parameters:{control_id:SD.Model.control_id},onSuccess:function(result){var savedSearches=$H(result.responseText.evalJSON(true));if(!$('s_selected_saved_search')){var el=new Element('select',{'name':'s_selected_saved_search','id':'s_selected_saved_search'});$('saved_searches_div').insert({'top':el});}
else{var el=$('s_selected_saved_search');}
el.options.add(new Option(savedSearches.values().last(),savedSearches.keys().last()));$('saved_searches_div').style.display="inline";SD.Tooltip.show('<b>Your search is saved!<b/>');}});},runSavedSearch:function(search_id){new Ajax.Request(SD.NavUtils.link('members','runSavedSearch'),{method:'post',evalJSON:false,parameters:{search_id:search_id,control_id:SD.Model.control_id},onSuccess:function(result){result=result.responseText.evalJSON(true);var formElements=$("advanced-search").elements;formElements.s_type.value=result.s_type;formElements.s_min_age.value=result.s_min_age;formElements.s_max_age.value=result.s_max_age;formElements.s_radius.value=result.s_radius;formElements.s_order_by.value=result.s_order_by;formElements.s_keyword.value=result.s_keyword;SD.UI.SearchPanel.clearAdvancedFilters();var el,id,div,label,name;$H(result.s_member_info).each(function(pair){if(result.s_member_info.hasOwnProperty(pair.key)){for(var i=0,end=pair.value.length;i<end;i++){id='member-info-'+pair.key+'-'+pair.value[i];el=formElements[id];if(!el){name='s_member_info['+pair.key+'][]';el=new Element('input',{'type':'checkbox','id':id,'value':pair.value[i],'textvalue':pair.value[i],'class':'search-checkbox','name':name});label=new Element('label',{'id':id,'for':id}).update(pair.value[i]);div=new Element('div',{'class':'list-item'});div.appendChild(el);div.appendChild(label);$('member-info-filter-'+pair.key).appendChild(div);}
el.checked='checked';}}});SD.UIController.searchSubmit({form:'advanced-search',btn:'adv-search-btn',loadingEl:'adv-search-btn-loading'});}});},toggleMatchesField:function(memberInfoId){var filterList=$('matches-member-info-filter-'+memberInfoId);if($('matches-member-info-list-'+memberInfoId).hasClassName('collapsed')){$('matches-member-info-list-'+memberInfoId).removeClassName('collapsed');filterList.show();}else{$('matches-member-info-list-'+memberInfoId).addClassName('collapsed');filterList.hide();}}}
SD.ImageRater={CONFIG:{ITEMS_IN_QUEUE:1,MIN_ITEMS_IN_STORE:10},initialize:function(records,domQueueHolder,domImageBox){SD.ImageRater.Store.initialize(records,{minImagesInQueue:SD.ImageRater.CONFIG.MIN_ITEMS_IN_STORE});this.queue=new SD.ImageRater.UI.Queue({domHolder:$(domQueueHolder),queueLength:SD.ImageRater.CONFIG.ITEMS_IN_QUEUE});SD.ImageRater.UI.RatingBox.initialize($(domImageBox));SD.Event.observe(null,SD.ImageRater.Events.REQUEST_NEXT,this.onRequestNext);SD.Event.observe(null,SD.ImageRater.Events.RATE,this.onRate);SD.Event.observe(null,SD.ImageRater.Events.RATE_COMPLETE,this.onRateComplete);SD.Event.observeOnce(null,SD.Nav.Events.HASH_CHANGE,this.onHashChange);SD.Event.fire(null,SD.ImageRater.Events.REQUEST_NEXT);},onRequestNext:function(e){SD.ImageRater.Store.getAndRemove(SD.ImageRater.dataReceiver);},onRateComplete:function(e){SD.ImageRater.queue.addItem(e.memo);SD.Event.fire(null,SD.ImageRater.Events.REQUEST_NEXT);},onRate:function(e){if(!e.memo.rating||!e.memo.uid){return}
SD.ImageRater.rate(e.memo.rating,e.memo.uid);},onHashChange:function(e){SD.ImageRater.destroy();},dataReceiver:function(record){if(!record){SD.UIController.infoMessage('No more images available!');return;}
SD.ImageRater.UI.RatingBox.populate(record);},rate:function(rate,uid){var _this=SD.ImageRater;new Ajax.Request(SD.NavUtils.link('ajax','rate_photo'),{method:'get',parameters:{uid:uid,rate:rate},onSuccess:function(response){var data=eval('('+response.responseText+')');SD.Event.fire(null,SD.ImageRater.Events.RATE_COMPLETE,data);},onFailure:function(){}});},destroy:function(){SD.Event.stopObserving(null,SD.ImageRater.Events.REQUEST_NEXT);SD.Event.stopObserving(null,SD.ImageRater.Events.RATE);SD.Event.stopObserving(null,SD.ImageRater.Events.RATE_COMPLETE);this.queue.destroy();this.queue=null;SD.ImageRater.UI.RatingBox.destroy();},Events:{RATE:'SD.ImageRater.Events:RATE',RATE_COMPLETE:'SD.ImageRater.Events:RATE_COMPLETE',REQUEST_NEXT:'SD.ImageRater.Events:REQUEST_NEXT'}};SD.ImageRater.UI={};SD.ImageRater.UI.QueueItemTemplates={item:'<div class="lib-queue-item que-item">'+'<div class="rating-label">Average Rating:</div> '+'<div class="rating-number">#{rating}</div>'+'<div class="thumb"><img src="#{thumbUrl}" /></div>'+'<div class="username"><span>#{username}</span></div>'+'<div class="actions">'+'<div id="flirtwink-btn-wink" style="float:left;" class="small-gray small-button" sdType="wink" sdUid="#{memberid}" sdUserName="#{username}">'+'<span>'+'<i class="profile-icon"></i>'+'Send a Wink'+'</span>'+'</div>'+'<div id="flirtwink-btn-flirt" style="float:right;" class="small-gray small-button" sdType="flirt" sdUid="#{memberid}" sdUserName="#{username}">'+'<span>'+'<i class="profile-icon"></i>'+'Send an Email'+'</span>'+'</div>'+'</div>'+'</div>'};SD.ImageRater.UI.QueueItem=Class.create(SD.UI.Component,{templateSet:SD.ImageRater.UI.QueueItemTemplates,initTemplate:SD.ImageRater.UI.QueueItemTemplates.item,render:function(domRoot,template,data){this.populator.appendTop({domRoot:domRoot,template:template,data:data});},parseLibrary:{'lib-queue-item':function(el,domRoot){el.removeClassName('lib-queue-item');this.dom=el;}},destroy:function($super){this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom);this.dom=null;$super();}});SD.ImageRater.UI.QueueTemplates={frame:'<div class="lib-queue-holder"></div>'};SD.ImageRater.UI.Queue=Class.create(SD.UI.Container,{templateSet:SD.ImageRater.UI.QueueTemplates,initTemplate:SD.ImageRater.UI.QueueTemplates.frame,addItem:function($super,record){if(this.getCount()>=this.options.queueLength){this.removeItem(this.getFirstItem());}
var queueItem=new SD.ImageRater.UI.QueueItem({domHolder:this.dom,container:this,data:record});$super(queueItem);},getFirstItem:function(){return this.items.values().first();},removeItem:function($super,item){item.destroy();$super(item);},parseLibrary:{'lib-queue-holder':function(el,domRoot){this.dom=el;}},destroy:function($super){this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom);this.dom=null;$super();}});SD.ImageRater.UI.RatingBox={initialize:function(dom){this.parser=SD.Utils.Parser;this.parse(dom,this.parseLibrary);SD.Event.forward(SD.UI.Rater,SD.UI.Rater.Events.RATE,SD.ImageRater.Events.RATE);},populate:function(record){this.setupRatingControl(record);this.setupImage(record);this.setupUsername(record);this.setupReport(record);},setupRatingControl:function(record){this.domRater.className='r0 rating';this.domRater.writeAttribute({sdUid:record.memberid,sdUsername:record.username,sdMessage:'Rate <b>'+record.username+'</b>\'s photo',sdRating:0,sdToken:0});},setupImage:function(record){this.domImage.src=record.imageUrl;},setupReport:function(record){this.domReport.setAttribute('sdUid',record.memberid);this.domReport.setAttribute('sdUserName',record.username);},setupUsername:function(record){this.domUserName.update(record.username);},parse:function(domRoot,parseLibrary){this.parser.parse({domRoot:domRoot,parseLibrary:parseLibrary,context:this});},parseLibrary:{'lib-rating-box-rater':function(el,domRoot){this.domRater=el;},'lib-rating-box-image':function(el,domRoot){this.domImage=el;},'lib-rating-box-report':function(el,domRoot){this.domReport=el;},'lib-rating-box-username':function(el,domRoot){this.domUserName=el;}},destroy:function(){SD.Event.stopForwarding(SD.UI.Rater,SD.UI.Rater.Events.RATE,SD.ImageRater.Events.RATE);}};SD.ImageRater.Store={initialize:function(records,options){this.options=options||{minImagesInQueue:10};this.data=[];if(records){this.add(records);}},add:function(records){if(Object.isArray(records)){while(records.length)this.add(records.shift());}else{this.data.push(records);}},getAndRemove:function(callback){if(this.data.length<this.options.minImagesInQueue){this.getMore();}
callback(this.data.shift());},getMore:function(){SD.ImageRater.DataSource.fetch(function(records){SD.ImageRater.Store.add(records);});}};SD.ImageRater.DataSource={isFetching:false,fetch:function(callback){var _this=SD.ImageRater.DataSource;if(this.isFetching){return;}
this.isFetching=true;new Ajax.Request(SD.NavUtils.link('ajax','get_next_members_for_rating'),{method:'get',parameters:{},onSuccess:function(response){callback(eval('('+response.responseText+')'));},onComplete:function(){_this.isFetching=false;}});}};
SD.MatchRater={initTimer:null,hasFriend:false,hasPermission:false,updateUI:function(){if(!SD.MatchRater.hasPermission){$('match-rater').hide();$('match-rater-no-friends-note').hide();$('match-rater-permission-note').show();}else{if(SD.MatchRater.hasFriend){$('match-rater-no-friends-note').hide();$('match-rater-permission-note').hide();$('match-rater').show();}else{$('match-rater-no-friends-note').show();$('match-rater').hide();$('match-rater-permission-note').hide();}}},CONFIG:{ITEMS_IN_QUEUE:1,MIN_ITEMS_IN_STORE:10},isFBReady:function(){return!!(window.FB&&window.FB._apiKey);},initialize:function(records,friends,domQueueHolder,domImageBox,hasPermission){SD.MatchRater.hasPermission=hasPermission;SD.MatchRater.hasFriend=(friends.length>0);SD.MatchRater.updateUI();if(!this.initTimer&&!this.isFBReady()){this.initTimer=setInterval(function(){if(this.isFBReady()){clearInterval(this.initTimer);this.initTimer=null;SD.MatchRater.initialize(records,friends,domQueueHolder,domImageBox,hasPermission);}}.bind(this),1000);return;}
SD.Event.observe(null,SD.MatchRater.FriendStore.Events.FRIENDS_LOADED,this.setup.bind(this,records,domQueueHolder,domImageBox));SD.MatchRater.FriendStore.initialize(friends);clearInterval(this.initTimer);this.initTimer=null;},setup:function(records,domQueueHolder,domImageBox){SD.MatchRater.hasFriend=true;SD.MatchRater.updateUI();SD.MatchRater.Store.initialize(records,{minImagesInQueue:SD.MatchRater.CONFIG.MIN_ITEMS_IN_STORE});this.queue=new SD.MatchRater.UI.Queue({domHolder:$(domQueueHolder),queueLength:SD.MatchRater.CONFIG.ITEMS_IN_QUEUE});SD.MatchRater.UI.RatingBox.initialize($(domImageBox));SD.Event.observe(null,SD.MatchRater.Events.REQUEST_NEXT,this.onRequestNext);SD.Event.observe(null,SD.MatchRater.Events.RATE,this.onRate);SD.Event.observe(null,SD.MatchRater.Events.RATE_COMPLETE,this.onRateComplete);SD.Event.observeOnce(null,SD.Nav.Events.HASH_CHANGE,this.onHashChange);SD.Event.fire(null,SD.MatchRater.Events.REQUEST_NEXT);},onRequestNext:function(e){SD.MatchRater.Store.getNext(SD.MatchRater.dataReceiver);},onRateComplete:function(e){SD.MatchRater.queue.addItem(e.memo);SD.Event.fire(null,SD.MatchRater.Events.REQUEST_NEXT);},onRate:function(e){if(!e.memo.rating||!e.memo.uid||!e.memo.friendUid){return}
SD.MatchRater.rate(e.memo.rating,e.memo.uid,e.memo.friendUid,e.memo.publish);},onHashChange:function(e){SD.MatchRater.destroy();},dataReceiver:function(record){if(!record){SD.UIController.infoMessage('No more images available!');return;}
SD.MatchRater.UI.RatingBox.populate(record,SD.MatchRater.FriendStore.getNext());},rate:function(rate,uid,friendUid,publish){new Ajax.Request(SD.NavUtils.link('ajax','rate_friend'),{method:'get',parameters:{uid:uid,friendUid:friendUid,rate:rate},onSuccess:function(response){var data=eval('('+response.responseText+')');SD.Event.fire(null,SD.MatchRater.Events.RATE_COMPLETE,data);if(rate>4&&publish){SD.MatchRater.publishStory(uid,friendUid);}},onFailure:function(){}});},publishStory:function(uid,friendUid){var member=SD.MatchRater.Store.findByUid(uid);var friend=SD.MatchRater.FriendStore.findByUid(friendUid);var feedData={'message':'Hey, I found a hot match for you','name':'Play the Hot Match game yourself','description':'Join me on SpeedDate.com and match our other friends with hot local singles!','caption':'','picture':member.imageUrl,'link':SD.Config.theBrosSignupUrl};FB.api('/'+friendUid+'/feed','post',feedData,function(response){if(!response||response.error){}else{}});},askPermission:function(){SD.XConnect.openFacebookAuthenticate(function(result){SD.MatchRater.hasPermission=result;SD.MatchRater.updateUI();if(result){SD.MatchRater.fetchFriends(function(friends){SD.MatchRater.FriendStore.add(friends);});}},{permissions:SD.Config.defaultFbPermissions});},fetchFriends:function(callback){if(SD.Model.getMyself().sex_pref=='F'){var fsql="SELECT uid,first_name,last_name,pic_big,sex,relationship_status FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = '"+FB.getUserID()+"') and sex = 'male' and (relationship_status = 'Single' or relationship_status = '') order by first_name asc";}else{var fsql="SELECT uid,first_name,last_name,pic_big,sex,relationship_status FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = '"+FB.getUserID()+"') and sex = 'female' and (relationship_status = 'Single' or relationship_status = '') order by first_name asc";}
var friends=FB.Data.query(fsql);FB.Data.waitOn([friends],function(){callback(friends.value);});},destroy:function(){SD.Event.stopObserving(null,SD.MatchRater.Events.REQUEST_NEXT);SD.Event.stopObserving(null,SD.MatchRater.Events.RATE);SD.Event.stopObserving(null,SD.MatchRater.Events.RATE_COMPLETE);this.queue&&this.queue.destroy();this.queue=null;SD.MatchRater.UI.RatingBox.destroy();},Events:{RATE:'SD.MatchRater.Events:RATE',RATE_COMPLETE:'SD.MatchRater.Events:RATE_COMPLETE',REQUEST_NEXT:'SD.MatchRater.Events:REQUEST_NEXT'}};SD.MatchRater.UI={};SD.MatchRater.UI.QueueItemTemplates={item:'<div class="lib-queue-item que-item">'+'<div class="rating-label">Hotness Meter:</div> '+'<div class="rating-number">#{rating}</div>'+'<div class="thumb"><img src="#{thumbUrl}" /></div>'+'<div class="username"><span>#{username}</span></div>'+'</div>'};SD.MatchRater.UI.QueueItem=Class.create(SD.UI.Component,{templateSet:SD.MatchRater.UI.QueueItemTemplates,initTemplate:SD.MatchRater.UI.QueueItemTemplates.item,render:function(domRoot,template,data){this.populator.appendTop({domRoot:domRoot,template:template,data:data});},parseLibrary:{'lib-queue-item':function(el,domRoot){el.removeClassName('lib-queue-item');this.dom=el;}},destroy:function($super){this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom);this.dom=null;$super();}});SD.MatchRater.UI.QueueTemplates={frame:'<div class="lib-queue-holder"></div>'};SD.MatchRater.UI.Queue=Class.create(SD.UI.Container,{templateSet:SD.MatchRater.UI.QueueTemplates,initTemplate:SD.MatchRater.UI.QueueTemplates.frame,addItem:function($super,record){if(this.getCount()>=this.options.queueLength){this.removeItem(this.getFirstItem());}
var queueItem=new SD.MatchRater.UI.QueueItem({domHolder:this.dom,container:this,data:record});$super(queueItem);},getFirstItem:function(){return this.items.values().first();},removeItem:function($super,item){item.destroy();$super(item);},parseLibrary:{'lib-queue-holder':function(el,domRoot){this.dom=el;}},destroy:function($super){this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom);this.dom=null;$super();}});SD.MatchRater.UI.RatingBox={initialize:function(dom){this.parser=SD.Utils.Parser;this.parse(dom,this.parseLibrary);SD.Event.forward(SD.UI.FriendRater,SD.UI.FriendRater.Events.RATE,SD.MatchRater.Events.RATE);},populate:function(record,friendRecord){this.setupRatingControl(record,friendRecord);this.setupImage(record);this.setupUsername(record);this.setupImageFriend(friendRecord);this.setupUsernameFriend(friendRecord);this.setupSkip();},setupRatingControl:function(record,friendRecord){this.domRater.className='r0 rating';this.domRater.writeAttribute({sdUid:record.memberid,sdUsername:record.username,sdFriendUid:friendRecord.uid,sdFriendUsername:friendRecord.first_name+' '+friendRecord.last_name,sdMessage:'Rate how hot <b>'+record.username+'</b> &amp; <b>'+friendRecord.first_name+' '+friendRecord.last_name+'</b> are together!',sdRating:0,sdToken:0});},setupImage:function(record){this.domImage.src=record.imageUrl;},setupUsername:function(record){this.domUserName.update(record.username);},setupImageFriend:function(friendRecord){this.domImageFriend.src=friendRecord.pic_big;},setupUsernameFriend:function(friendRecord){this.domUserNameFriend.update(friendRecord.first_name+' '+friendRecord.last_name);},setupSkip:function(){this.domSkip.onclick=function(){SD.Event.fire(null,SD.MatchRater.Events.REQUEST_NEXT);};},parse:function(domRoot,parseLibrary){this.parser.parse({domRoot:domRoot,parseLibrary:parseLibrary,context:this});},parseLibrary:{'lib-rating-box-rater':function(el,domRoot){this.domRater=el;},'lib-rating-box-image':function(el,domRoot){this.domImage=el;},'lib-rating-box-username':function(el,domRoot){this.domUserName=el;},'lib-rating-box-image-friend':function(el,domRoot){this.domImageFriend=el;},'lib-rating-box-username-friend':function(el,domRoot){this.domUserNameFriend=el;},'lib-rating-box-skip':function(el,domRoot){this.domSkip=el;}},destroy:function(){SD.Event.stopForwarding(SD.UI.FriendRater,SD.UI.FriendRater.Events.RATE,SD.MatchRater.Events.RATE);}};SD.MatchRater.Store={initialize:function(records,options){this.options=options||{minImagesInQueue:10};this.data=[];this.cursor=0;if(records){this.add(records);}},add:function(records){if(Object.isArray(records)){while(records.length)this.add(records.shift());}else{this.data.push(records);}},getNext:function(callback){if(this.data.length-this.cursor<this.options.minImagesInQueue){this.getMore();}
callback(this.data[this.cursor]);this.cursor++;},getMore:function(){SD.MatchRater.DataSource.fetch(function(records){SD.MatchRater.Store.add(records);});},findByUid:function(uid){return this.data.find(function(record){return record.memberid==uid});}};SD.MatchRater.FriendStore={data:[],cursor:0,askedForPermission:false,initialize:function(records){if(records&&records.length){this.add(records);}},add:function(records){var validRecordAdded=false;if(Object.isArray(records)){validRecordAdded=!!records.length;}else{validRecordAdded=!!records;}
this.data=this.data.concat(records);validRecordAdded&&SD.Event.fire(null,SD.MatchRater.FriendStore.Events.FRIENDS_LOADED);},getNext:function(){var record=this.data[this.cursor];this.cursor=Math.min(this.data.length,this.cursor+1);if(this.cursor==this.data.length){this.cursor=0;}
return record;},findByUid:function(uid){return this.data.find(function(record){return record.uid==uid});},Events:{FRIENDS_LOADED:"SD.MatchRater.FriendStore.Events:FRIENDS_LOADED"}};SD.MatchRater.DataSource={isFetching:false,fetch:function(callback){var _this=SD.MatchRater.DataSource;if(this.isFetching){return;}
this.isFetching=true;new Ajax.Request(SD.NavUtils.link('ajax','get_next_members_for_rating'),{method:'get',parameters:{},onSuccess:function(response){callback(eval('('+response.responseText+')'));},onComplete:function(){_this.isFetching=false;}});}};SD.MatchRater.FriendDataSource={isFetching:false,fetch:function(callback){var _this=SD.MatchRater.FriendDataSource;if(this.isFetching){return;}
this.isFetching=true;new Ajax.Request(SD.NavUtils.link('ajax','get_facebook_friends_for_rating'),{method:'get',parameters:{},onSuccess:function(response){callback(eval('('+response.responseText+')'));},onComplete:function(){_this.isFetching=false;}});}};
SD.MyAccount={activateAccountSettingsMenuItem:function(menuId,focusElement){if(!menuId||!$(menuId)){return;}
var contentEl=$(menuId+'-content');if(contentEl){contentEl.show();var url=contentEl.getAttribute('sdLoadUrl');if((contentEl.getAttribute('sdIsLoaded')=='false')&&url){new SD.Utils.Loader({domContent:contentEl,onContentRendered:function(){if(focusElement&&$(focusElement)){try{$(focusElement).focus();}catch(e){}}}}).load(url);}
var editLinkEl=$(menuId+'-action-edit');var hideLinkEl=$(menuId+'-action-hide');if(editLinkEl&&hideLinkEl){editLinkEl.hide();hideLinkEl.show();}}},deactivateAccountSettingsMenuItem:function(menuId){if(!menuId||!$(menuId)){return;}
var contentEl=$(menuId+'-content');if(contentEl){contentEl.hide();var editLinkEl=$(menuId+'-action-edit');var hideLinkEl=$(menuId+'-action-hide');if(editLinkEl&&hideLinkEl){hideLinkEl.hide();editLinkEl.show();}}},focusAndActivateAccountSettingsMenuItem:function(menuId,focusElement){if(!menuId||!$(menuId)){return;}
SD.MyAccount.activateAccountSettingsMenuItem(menuId,focusElement);Effect.ScrollTo(menuId,{duration:'0.5',offset:-70});},forceMenuItemLoadAndFocus:function(menuId,myAccountLoaded){if(menuId&&$(menuId)){SD.MyAccount.focusAndActivateAccountSettingsMenuItem(menuId);}else{myAccountLoaded||SD.NavUtils.goTo('profile','my_account');SD.MyAccount.forceMenuItemLoadAndFocus.delay(0.3,menuId,true)}},toEmailNotifFromCancelAcc:function(){SD.MyAccount.deactivateAccountSettingsMenuItem('cancel-account-settings');SD.MyAccount.activateAccountSettingsMenuItem('email-notifications-settings');Effect.ScrollTo('email-notifications-settings',{duration:'0.5',offset:-70});},loadExpandFocusMenuItem:function(menuId,focusElement){if(SD.Nav.oHash.page=='profile'&&SD.Nav.oHash.action=='account'){this.focusAndActivateAccountSettingsMenuItem(menuId,focusElement);}else{SD.Event.observeOnce(null,SD.Nav.Events.CONTENT_LOADED,this.focusAndActivateAccountSettingsMenuItem.bind(this,menuId,focusElement));SD.NavUtils.goTo('profile','my_account');}}};
SD.MyProfile=new function(){var _profileTabs={};this.init=function(){};this.registerMyProfileTabItems=function(tabItems){var tabItems=tabItems||[];tabItems.each(function(tabItem,index){var oElId=tabItem.tabEl;_profileTabs[oElId]=tabItem.contentEl;var oElement=$(oElId);if(!oElement._activation_set){oElement._activation_set=true;oElement.observe('click',function(e){SD.MyProfile.activateTabMenu(oElement.id);});}});};this.activateTabMenu=function(elId,tabMod,linkParams){tabMod=tabMod||'view';linkParams=linkParams||{};for(var el in _profileTabs){var oEl=$(el);var cEl=$(_profileTabs[el]);if(oEl&&cEl){if(el==elId){oEl.addClassName("selected-tab-item");cEl.show();var isLoaderTab=(oEl.getAttribute('sdType')=='loaderTab')||null;if(isLoaderTab){cEl.update();cEl.update('<div style="color:#999; font-size:18px; font-weight:bold; margin:48px auto; width:100px;">loading...</div>');var url=null;if(oEl.getAttribute('sdTabType')=='photo'){if(tabMod=='edit'){url=SD.NavUtils.link('profile','upload_photo',linkParams);}else{url=SD.NavUtils.link('profile','my_photos_view',linkParams);}}else if(oEl.getAttribute('sdTabType')=='aboutMe'){if(tabMod=='edit'){url=SD.NavUtils.link('profile','edit_about_me',linkParams);}else{url=SD.NavUtils.link('profile','about_me_view',linkParams);}}else if(oEl.getAttribute('sdTabType')=='aboutMyDate'){if(tabMod=='edit'){url=SD.NavUtils.link('profile','edit_about_my_date',linkParams);}else{url=SD.NavUtils.link('profile','about_my_date_view',linkParams);}}else if(oEl.getAttribute('sdTabType')=='datingQuiz'){if(tabMod=='edit'){url=SD.NavUtils.link('profile','viral_quiz_take',linkParams);}else{url=SD.NavUtils.link('profile','viral_quiz_view',linkParams);}}
new SD.Utils.Loader({domContent:cEl}).load(url);}}else{oEl.removeClassName("selected-tab-item");cEl.hide();}}}};this.largePhotoRenderer=function(dom,userImages){if(userImages.length==0){return}
userImages.each(function(img){var photo=new Image();photo.onload=this.photoRenderer.bind(this,dom,photo);if(img.image_url_extralarge){photo.src=img.image_url_extralarge;}else{photo.src=img.image_url_large;}
return photo;},this);};var domSoftHyphen=document.createElement('span');domSoftHyphen.innerHTML='&shy;';domSoftHyphen.style.visibility='hidden';domSoftHyphen.style.fontSize='0px';this.photoRenderer=function(dom,img){dom=$(dom);var maxWidth=parseInt(dom.getStyle("width"))-10;img.width=Math.min(img.width,maxWidth);img.style.borderWidth='0px';img.onload=null;img.style.margin='5px';var a=document.createElement('a');a.appendChild(img);a.href="javascript:void(SD.MyProfile.activateTabMenu('my-profile-photos-tab', 'edit'));";dom.appendChild(a);if(Prototype.Browser.IE6){dom.appendChild(domSoftHyphen.cloneNode(true));}};this.updateProfilePictureView=function(sUrl){sUrl=sUrl||null
var oElement=$('my-profile-default-picture');if(oElement&&sUrl){oElement.src=sUrl;}}};
SD.SpeedDateList={_activeDates:[],_upcomingDates:[],_me:null,_debugEnabled:true,_loadedWantedDates:false,WANTED_PRELOAD:5,MAX_ITEMS_COUNT:Infinity,_debug:function(){this._debugEnabled&&console.log(arguments);},init:function(){SD.Event.observe(null,SD.Matchmaker.Events.MATCHES_FOUND,this._onMatchesFound.bind(this));SD.Event.observe(null,SD.UserInitiatedDate.Events.START_DATE,this._onStartDate.bind(this));SD.Event.observe(null,SD.UserInitiatedDate.Events.END_DATE,this._onEndDate.bind(this));SD.Event.observe(null,SD.User.Events.USER_OFFLINE,this._onUserOffline.bind(this));SD.Event.observe(null,SD.FlirtWink.Events.DATE_WANTED,this._onWantedDateAdded.bind(this));SD.Event.observe(null,SD.FlirtWink.Events.DATE_REQUEST_REMOVED,this._onWantedDateRemoved.bind(this));SD.Event.observe(null,SD.UserFilters.UI.Events.FILTER_CHANGED,this._onFilterChange.bind(this));this._loadInitialWantedDates.bind(this).delay(1);this._me=SD.Model.getMyself();SD.SpeedDateList.View.init();this.MAX_ITEMS_COUNT=SD.Model.getMyself().sex=='F'?5:Infinity;},getUpcomingDates:function(){return this._upcomingDates;},_loadWantedDates:function(e){Event.extend(e||window.event).stop();!this._loadedWantedDates&&SD.User.fetchUsers(SD.Model.getMyself().wanted_dates,this._onWantedDatesFetched.bind(this),true);this._loadedWantedDates=true;SD.Event.fire(null,this.Events.PREVIOUS_WANTED_DATES_LOAD_START);},_loadInitialWantedDates:function(){var uids=SD.Model.getMyself().wanted_dates.slice(0,this.WANTED_PRELOAD);uids.length&&SD.User.fetchUsers(uids,this._onWantedDatesFetched.bind(this),true);},_onWantedDatesFetched:function(matches){matches.each(function(match){SD.Event.fire(null,this.Events.WANTED_DATE_ADDED,{match:match,loadedWantedDates:this._loadedWantedDates});}.bind(this));},_onWantedDateAdded:function(e){var user=e.memo.user;SD.User.lightFetch(user,function(match){SD.Event.fire(null,this.Events.WANTED_DATE_ADDED,{match:match,loadedWantedDates:this._loadedWantedDates});}.bind(this));},_onWantedDateRemoved:function(e){var match=e.memo.user;SD.Event.fire(null,this.Events.WANTED_DATE_REMOVED,{match:match});},_onStartDate:function(e){var match=e.memo.other;if(match){var ind=this._findUserIndex(match,this._upcomingDates);if(ind!=-1){this._upcomingDates.splice(ind,1);SD.Event.fire(null,this.Events.MATCH_REMOVED,{match:match,totalCnt:this._upcomingDates.length});this._dispatchUpcomingDatesCount();}
ind=this._findUserIndex(match,this._activeDates);if(ind==-1){this._activeDates.push(match);SD.Event.fire(null,this.Events.DATE_ADDED,{match:match,totalCnt:this._activeDates.length});}}},_onEndDate:function(e){var match=e.memo.other;if(match){var ind=this._findUserIndex(match,this._activeDates);if(ind!=-1){this._activeDates.splice(ind,1);SD.Event.fire(null,this.Events.DATE_REMOVED,{match:match,totalCnt:this._activeDates.length});}}},_onUserOffline:function(e){var match=e.memo.user;match&&this._removeUpcomingMatch(match);},_removeUpcomingMatch:function(match){var ind=this._findUserIndex(match,this._upcomingDates);if(ind!=-1){this._upcomingDates.splice(ind,1);SD.Event.fire(null,this.Events.MATCH_REMOVED,{match:match,totalCnt:this._upcomingDates.length});this._dispatchUpcomingDatesCount();}},_onFilterChange:function(){this._onMatchesFound({memo:{matches:[]}});},_onMatchesFound:function(e){var matches=e.memo.matches;var toRemove=[];this._upcomingDates.each(function(match){var ind=this._findUserIndex(match,matches);if(ind==-1){toRemove.push(match);}}.bind(this));toRemove.each(this._removeUpcomingMatch.bind(this));this._dispatchUpcomingDatesCount();matches.each(function(match){this._me.mightDate(match)&&SD.RPC.call(match,"SD.SpeedDateList.__getInfo",{addMe:true,myData:this.getViewData(this._me)},function(data){if(data!=null){SD.User.updateUser(data);var valid=this._findUserIndex(match,matches)!=-1;var existing=this._findUserIndex(match,this._upcomingDates)!=-1;if(valid&&!existing){this._upcomingDates.push(match);SD.Event.fire(null,this.Events.MATCH_ADDED,{match:match,totalCnt:this._upcomingDates.length});this._dispatchUpcomingDatesCount();}}else{this._removeUpcomingMatch(match);}}.bind(this));}.bind(this));},_findUserIndex:function(user,list){user.uid=parseInt(user.uid);for(var i=0;i<list.length;i++){if(parseInt(list[i].uid)==user.uid){return i;}}
return-1;},_dispatchUpcomingDatesCount:function(){SD.Event.fire(null,SD.SpeedDateList.Events.UPCOMING_DATES_CHANGED,{count:this._upcomingDates.length});},getViewData:function(user){return{uid:user.uid,username:(user.username||'').truncate(15),square_image_url:user.square_image_url,city_name:user.city_name,age:user.age,online:true,token:user.token,has_photo:user.has_photo};},__getInfo:function(match,params){if(params&&params.myData){params.myData.uid=match.uid;SD.User.updateUser(params.myData);}
var shouldRespond=SD.Model.getMyself().mightDate(match);if(shouldRespond){if(params.addMe){var found=this._findUserIndex(match,this._upcomingDates)!=-1;if(!found){this._upcomingDates.push(match);SD.Event.fire(null,this.Events.MATCH_ADDED,{match:match,totalCnt:this._upcomingDates.length});this._dispatchUpcomingDatesCount();}}
return this.getViewData(SD.Model.getMyself());}
return null;},Events:{MATCHES_REMOVED:"speeddatelist:matches_removed",MATCH_ADDED:"speeddatelist:match_added",MATCH_REMOVED:"speeddatelist:match_removed",DATE_ADDED:"speeddatelist:date_added",DATE_REMOVED:"speeddatelist:date_removed",WANTED_DATE_ADDED:"speeddatelist:wanted_date_added",WANTED_DATE_REMOVED:"speeddatelist:wanted_date_removed",PREVIOUS_WANTED_DATES_LOAD_START:'speeddatelist:previous_wanted_dates_load_start',UPCOMING_DATES_CHANGED:"SD.SpeedDateList.Events:WAITING_TIME_CHANGED"}};SD.SpeedDateList.View={_win:null,_contentElm:null,_activeHeader:null,_upcomingHeader:null,_wantedHeader:null,_wantedDatesLoadLink:null,_initialized:false,_canRemoveFromQueue:false,MAX_HEIGHT:400,init:function(){SD.Event.observe(null,SD.SpeedDateList.Events.MATCH_ADDED,this._onMatchAdded.bind(this));SD.Event.observe(null,SD.SpeedDateList.Events.MATCHES_REMOVED,this._onMatchesRemoved.bind(this));SD.Event.observe(null,SD.SpeedDateList.Events.MATCH_REMOVED,this._onMatchRemoved.bind(this));SD.Event.observe(null,SD.SpeedDateList.Events.DATE_REMOVED,this._onDateRemoved.bind(this));SD.Event.observe(null,SD.SpeedDateList.Events.DATE_ADDED,this._onDateAdded.bind(this));SD.Event.observe(null,SD.SpeedDateList.Events.WANTED_DATE_ADDED,this._onWantedDateAdded.bind(this));SD.Event.observe(null,SD.SpeedDateList.Events.WANTED_DATE_REMOVED,this._onWantedDateRemoved.bind(this));SD.Event.observe(null,SD.SpeedDateList.Events.PREVIOUS_WANTED_DATES_LOAD_START,this._onPreviousWantedDatesLoadStart.bind(this));this.boundAdjustHeight=this.adjustHeight.bind(this);SD.Event.observe(null,this.Events.ITEM_COUNT_CHANGE,this.boundAdjustHeight);this.setup();this._initialized=true;Event.observe(window,'resize',this.boundAdjustHeight);},setup:function(){this._containerElm=$('speed_dating_list_container');this._contentElm=$('speed_dating_list');var hideImportant=(SD.Config.isSite)?'hide-important':'';this._activeHeader=LI({'class':'title '+hideImportant},"Active SpeedDates");this._upcomingHeader=LI({'class':'title '+hideImportant},"Upcoming SpeedDates");this._wantedHeader=LI({'class':'title'},"Invited to SpeedDate ");if(SD.Model.getMyself().wanted_dates.length>SD.SpeedDateList.WANTED_PRELOAD){this._wantedDatesLoadLink=A({href:'javascript:void()','class':'link'},"more("+(SD.Model.getMyself().wanted_dates.length-SD.SpeedDateList.WANTED_PRELOAD)+")");this._wantedDatesLoadLink.onclick=SD.SpeedDateList._loadWantedDates.bind(SD.SpeedDateList);this._wantedHeader.insert(this._wantedDatesLoadLink);}else{this._wantedHeader.hide();}
this._contentElm.insert(this._activeHeader);this._contentElm.insert(this._upcomingHeader);this._contentElm.insert(this._wantedHeader);this._activeHeader.hide();this._upcomingHeader.hide();this._dispatchItemCount.bind(this).delay(2);},_onMatchAdded:function(e){this._addMatch(e.memo.match);if(e.memo.totalCnt){this._upcomingHeader&&this._upcomingHeader.show();}},_onDateAdded:function(e){if(SD.Config.isSite)return;var match=e.memo.match;var elm=this._getUserPanel(match,this.TYPES.ACTIVE_DATE);!elm&&this._activeHeader.insert({after:this._createUserElm(match,this.TYPES.ACTIVE_DATE)});if(e.memo.totalCnt){this._activeHeader.show();}
this._dispatchItemCount();},_onDateRemoved:function(e){[this.TYPES.ACTIVE_DATE,this.TYPES.UPCOMING_MATCH,this.TYPES.WANTED_DATE].each(function(type){var el=this._getUserPanel(e.memo.match,type)
el&&this._contentElm.removeChild(el);},this);if(e.memo.totalCnt<1){this._activeHeader.hide();}
this._dispatchItemCount();},_addMatch:function(match){if(this._upcomingHeader){var elm=this._getUserPanel(match,this.TYPES.UPCOMING_MATCH);!elm&&this._upcomingHeader.insert({after:this._createUserElm(match,this.TYPES.UPCOMING_MATCH)});this._dispatchItemCount();}},_onMatchesRemoved:function(e){var matches=e.memo.matches;matches&&matches.each(function(match){this._removeMatch(match,this.TYPES.UPCOMING_MATCH);}.bind(this));this._upcomingHeader&&this._upcomingHeader.hide();},_onWantedDateAdded:function(e){!this._wantedHeader.visible()&&this._wantedHeader.show();var match=e.memo.match;var elm=this._getUserPanel(match,this.TYPES.WANTED_DATE);!elm&&this._wantedHeader.insert({after:this._createUserElm(match,this.TYPES.WANTED_DATE)});this._dispatchItemCount();},_onWantedDateRemoved:function(e){[this.TYPES.ACTIVE_DATE,this.TYPES.UPCOMING_MATCH,this.TYPES.WANTED_DATE].each(function(type){var el=this._getUserPanel(e.memo.match,type)
el&&this._contentElm.removeChild(el);},this);if(e.memo.totalCnt<1){this._activeHeader.hide();}
this._dispatchItemCount();},_onMatchRemoved:function(e){var match=e.memo.match;match&&this._removeMatch(match,this.TYPES.UPCOMING_MATCH);if(e.memo.totalCnt<1){this._upcomingHeader&&this._upcomingHeader.hide();}},_removeMatch:function(match,type){var elm=this._getUserPanel(match,type);elm&&this._contentElm.removeChild(elm);this._dispatchItemCount();},_onPreviousWantedDatesLoadStart:function(){this._wantedHeader.removeChild(this._wantedDatesLoadLink);this._wantedDatesLoadLink=null;},getItemCount:function(){if(!this._initialized){return 0;}
return this._contentElm.select("[class=head]").length+SD.Model.getMyself().wanted_dates.length;},_createUserElm:function(user,type){var elm=LI({sdUid:user.uid,sdlisttype:type,'class':"buddy-view speeddate-list-"+type});var data={showDate:type==this.TYPES.UPCOMING_MATCH?'block':'none',uid:user.uid,username:user.username,age:user.age,city_name:user.city_name};Object.extend(data,user);SD.Utils.Populator.populate({domRoot:elm,template:this.TEMPLATES.USER_PANEL,data:data});return elm;},_getUserPanel:function(user,type){var query="[sduid="+user.uid+"]";if(type){query+="[sdlisttype="+type+"]";}
var elms=this._contentElm.select(query);if(elms.length){return elms[0];}},getMaxHeight:function(){var maxHeight=this.MAX_HEIGHT;if(SD.Config.isSite){if(SD.SpeedDateList.MAX_ITEMS_COUNT==5){maxHeight=160;}else{var topOffset=310;var minHeight=60;maxHeight=Math.max(minHeight,document.viewport.getHeight()-topOffset);}}
return maxHeight;},adjustHeight:function(){var height=this._contentElm.offsetHeight;var maxHeight;if(SD.SpeedDateList.MAX_ITEMS_COUNT==5){maxHeight=160;}else{maxHeight=this.getMaxHeight();}
if(height>=maxHeight){this._containerElm.setHeight(maxHeight);if(SD.SpeedDateList.MAX_ITEMS_COUNT==5){this._containerElm.style.overflow='hidden';}else{this._containerElm.style.overflowY='auto';}}else{this._containerElm.style.height='';this._containerElm.style.overflowY='';}},setHeight:function(h){this._containerElm.setHeight(h);},_dispatchItemCount:function(){SD.Event.fire(null,this.Events.ITEM_COUNT_CHANGE,{count:this.getItemCount()});},_getDateButton:function(){if(SD.Config.isSite){if(SD.ExperimentManager.RemoveFromDQ_SDWEB252.value){return"<i class='link-date' href='javascript:void(0)' sdTTOrientation='tl' sdType='date' sdSource='dating_list' sduid='#{uid}' sdusername='#{username}' style='display:#{showDate}; position: absolute; right: 13px; _right:5px; zoom: 1;'></i>";}else{return"<i class='link-date' href='javascript:void(0)' sdTTOrientation='bl' sdType='date' sdSource='dating_list' sduid='#{uid}' sdusername='#{username}' style='display:#{showDate}; position: absolute; right: 13px; _right:5px; zoom: 1;'><span style='font-style:normal; color: red; font-size: 11px;'>Date</span></i>";}}else{return"<i class='link-date' href='javascript:void(0)' sdTTOrientation='bl' sdType='date' sdSource='dating_list' sduid='#{uid}' sdusername='#{username}' style='display:#{showDate}'></i>";}},_getBuddyName:function(){if(SD.Config.isSite){return"<div class='buddy-name'><a sdType='profile' sdTTOrientation='bl' sdSource='dating_list' sdUid='#{uid}' sdUsername='#{username}' href='javascript:void(0)'>#{username}</a>, #{age}<br/>#{city_name}</div>";}else{return"<div class='buddy-name'><a sdType='profile' sdTTOrientation='bl' sdSource='dating_list' sdUid='#{uid}' sdUsername='#{username}' href='javascript:void(0)'>#{username}</a>, #{age}<br/>#{city_name}</div>";}},_getOnlineIndicator:function(){if(SD.Config.isSite){return"<div class='buddy-list-online-indicator'></div>";}else{return"";}},Events:{ITEM_COUNT_CHANGE:'speeddate_list_view:item_count_change'},TEMPLATES:{USER_PANEL:function(){var _canRemoveFromQueue=SD.ExperimentManager.RemoveFromDQ_SDWEB252.value;return""+"<div class='head'>"+"<img class='buddy-image fake-link' src='#{square_image_url}' sdUsername='#{username}' sdUid='#{uid}' sdType='profile' sdSource='dating_list' sdTTOrientation='bl'/>"+
SD.SpeedDateList.View._getOnlineIndicator()+
SD.SpeedDateList.View._getBuddyName()+
SD.SpeedDateList.View._getDateButton()+
(SD.Config.isSite&&_canRemoveFromQueue?"<div class='remove-date' sdType='remove-date tooltip' sdTTOrientation='tl' sdMessage='Remove from Upcoming SpeedDates' sdUid='#{uid}' sdUserName='#{username}'></div>":'')+"</div>"+"<br clear='all'/>";}},TYPES:{UPCOMING_MATCH:"um",ACTIVE_DATE:"ad",WANTED_DATE:"wd"}};
SD.Time={_pageDraw:null,_domLoaded:null,_flashLoad:null,_flashInit:null,_xmppConnect:null,getNow:function(){return new Date().getTime();},_timeDiff:function(before,after){if(before&&after){return after-before;}
return"X";},onJSError:function(){return"domload="+this._timeDiff(this._pageDraw,this._domLoaded)+", flashload="+this._timeDiff(this._domLoaded,this._flashLoad)+", flasinit="+this._timeDiff(this._flashLoad,this._flashInit)+", xmppconnect="+this._timeDiff(this._flashInit,this._xmppConnect);},pageDrawn:function(){this._pageDraw=this.getNow();},domLoaded:function(){this._domLoaded=this.getNow();},flashLoaded:function(){this._flashLoad=this.getNow();},flashInitCompleted:function(){this._flashInit=this.getNow();},xmppConnected:function(){var prev=this._xmppConnect;this._xmppConnect=this.getNow();if(!prev&&this._xmppConnect-this._pageDraw>60000){SD.ExperimentManager.recordOutput('XMPPFirstConnectAfterOneMinute',1,1);}
if(!prev&&this._xmppConnect-this._pageDraw>120000){SD.ExperimentManager.recordOutput('XMPPFirstConnectAfterTwoMinutes',1,1);}},getSecondsSinceInit:function(){if(!this._domLoaded){return 0;}
return this._timeDiff(this._domLoaded,this.getNow())/1000;}};SD.Error.registerErrorDumper("time",SD.Time.onJSError.bind(SD.Time));
SD.SpeedWink={_popupCounter:null,WINK_CNT:25,init:function(){this._popupCounter=new SD.Cookie.CounterWithTimeout("speedWinkPopupCounter",12*60);},onFlirtWinkSent:function(fnc){if(this._popupCounter.getValue()<1){this.showPopup();return true;}
return fnc?fnc():false;},showPopup:function(){this._popupCounter.increment();SD.UIController.openSpeedWinkDialog();},speedWink:function(onResponse){new Ajax.Request(SD.NavUtils.link('ajax','speedwink'),{method:'get',evalJSON:true,onComplete:function(response){onResponse&&onResponse(response.responseJSON);}});}};
SD.FacebookFeed={_winkCounter:null,_flirtCounter:null,_dateCounter:null,init:function(){this._winkCounter=new SD.Cookie.CounterWithTimeout("shareWinkedPopupCounter",12*60);this._flirtCounter=new SD.Cookie.CounterWithTimeout("shareFlirtedPopupCounter",12*60);this._dateCounter=new SD.Cookie.CounterWithTimeout("shareDatedPopupCounter",12*60);this.loadShareWithFriendDivs();},requestFBSharePopup:function(context,continuationCallback){if(!context.sourceMemberId){continuationCallback&&continuationCallback();return;}
switch(context.actionType){case SD.UIController.ActionTypes.WINK:if(SD.FacebookFeed._winkCounter.getValue()<1){SD.FacebookFeed._winkCounter.increment();SD.UIController.facebookSharePopup({actionType:SD.UIController.ActionTypes.WINK,actionData:'{"sharedMemberId": "'+context.sourceMemberId+'"}'},continuationCallback);}
break;case SD.UIController.ActionTypes.FLIRT:if(SD.FacebookFeed._flirtCounter.getValue()<1){SD.FacebookFeed._flirtCounter.increment();SD.UIController.facebookSharePopup({actionType:SD.UIController.ActionTypes.FLIRT,actionData:'{"sharedMemberId": "'+context.sourceMemberId+'"}'},continuationCallback);}
break;case SD.UIController.ActionTypes.DATE:if(SD.FacebookFeed._dateCounter.getValue()<1){SD.FacebookFeed._dateCounter.increment();SD.UIController.facebookSharePopup({actionType:SD.UIController.ActionTypes.DATE,actionData:'{"sharedMemberId": "'+context.sourceMemberId+'"}'},continuationCallback);}
break;default:context.actionData='{"sharedMemberId": "'+context.sourceMemberId+'"}';SD.UIController.facebookSharePopup(context,continuationCallback);}},onWinkSent:function(oUser,fnc){if(SD.FacebookFeed._winkCounter.getValue()<1){SD.FacebookFeed._winkCounter.increment();SD.UIController.facebookSharePopup({actionType:SD.UIController.ActionTypes.WINK,actionData:'{"sharedMemberId": "'+oUser.uid+'"}'});return;}
fnc&&fnc();return false;},onFlirtSent:function(oUser,fnc){if(SD.FacebookFeed._flirtCounter.getValue()<1){SD.FacebookFeed._flirtCounter.increment();SD.UIController.facebookSharePopup({actionType:SD.UIController.ActionTypes.FLIRT,actionData:'{"sharedMemberId": "'+oUser.uid+'"}'});return;}
fnc&&fnc();return false;},onDateSent:function(oUser,fnc){if(SD.FacebookFeed._dateCounter.getValue()<1){SD.FacebookFeed._dateCounter.increment();SD.UIController.facebookSharePopup({actionType:SD.UIController.ActionTypes.DATE,actionData:'{"sharedMemberId": "'+oUser.uid+'"}'});return;}
fnc&&fnc();return false;},loadShareWithFriendDivs:function(){$$('[sdType=fwShareWithFriendContainer]').each(this.updateShareWithFriendDiv.bind(this));},updateShareWithFriendDiv:function(div){var limit=div.getAttribute('sdLimit')||8;var content=div.getAttribute('sdcontent')||'';var giftId=div.getAttribute('sdgiftid')||'';new Ajax.Updater(div,SD.NavUtils.link('profile','fb_click_share',{limit:limit,content:content,giftId:giftId}),{evalScripts:true,onComplete:function(){div.select('[sdType=refreshFriends]').each(function(refreshButton){refreshButton.observe('click',function(){SD.FacebookFeed.updateShareWithFriendDiv(div);});});}});}};
SD.XConnect={_hasFacebookOAuth:false,_hasTwitterOAuth:false,_hasLoginAfterFacebookConnect:false,_facebookCallback:null,_twitterCallback:null,_authenticateWindow:null,_WINDOW_NAME_PREFIX:"XAuthorizeWindow",_pendingTweet:null,_tweetPopup:null,init:function(auths){this._hasTwitterOAuth=auths.twitter;this._hasFacebookOAuth=auths.facebook;},openTwitterAuthenticate:function(callback){this._twitterCallback=callback;this._openAuthenticate('twitter');if(this._tweetPopup){this.closeTweetPopup();}},openFacebookAuthenticate:function(callback,params){this._facebookCallback=callback;params=params||{};this._openAuthenticate('facebook',params);},_openAuthenticate:function(platform,params){params=params||{};params.platform=platform;var link=SD.NavUtils.link('xconnect','authorize',params);link=this.filterLink(params,link);this._authenticateWindow=window.open(link,this._WINDOW_NAME_PREFIX+platform,"location=1,status=1,width=800,height=500");new PeriodicalExecuter(function(pe){if(this._authenticateWindow&&this._authenticateWindow.closed){if(platform=="twitter"&&this._twitterCallback){this._twitterCallback(false);}else if(platform=="facebook"&&this._facebookCallback){this._facebookCallback(false);}
pe.stop();}}.bind(this),0.5);},filterLink:function(params,link){if(params.platform=='facebook'){var pieces=link.split('&');var goodPieces=[];for(var i=0;i<pieces.length;i++){if(!(pieces[i].indexOf('fb_sig')===0)){goodPieces.push(pieces[i]);}}
link=goodPieces.join('&');}
return link;},onTwitterOAuthResult:function(result){this._hasTwitterOAuth=result;if(this._twitterCallback){this._twitterCallback(result);}
if(result&&this._pendingTweet){this.tweet();}
if(result){SD.Event.fire(null,this.Events.AUTH_TWITTER);}
this._authenticateWindow=null;},onFacebookOAuthResult:function(result,session,hasLogin,permissions){this._hasFacebookOAuth=result;this._hasLoginAfterFacebookConnect=hasLogin;if(session){SD.FbConnect.reInitialize({session:session.evalJSON()});}
if(result){SD.Event.fire(null,this.Events.AUTH_FACEBOOK);}
if(permissions){SD.FbConnect.setPermissions(permissions);}
if(SD&&SD.ExperimentManager&&SD.ExperimentManager.MatchMakerUI_v5_Strike.value==1){SD.UIController.infoMessage("Facebook interests are imported successfully",3);if(SD.ProfileInfoOptionTooltip&&SD.ProfileInfoOptionTooltip.tooltipWindow&&SD.ProfileInfoOptionTooltip.tooltipWindow.isOpened){SD.ProfileInfoOptionTooltip.tooltipWindow.close();}}
this._facebookCallback&&this._facebookCallback(result);this._authenticateWindow=null;},hasFacebookSession:function(){return!!FB.getAuthResponse();},hasFacebookOAuth:function(){return this._hasFacebookOAuth;},hasLoginAfterFacebookConnect:function(){return this._hasLoginAfterFacebookConnect;},tweet:function(msgType,msgData){if(!msgType){msgType=this._pendingTweet.msgType;msgData=this._pendingTweet.msgData;}else{this._pendingTweet={msgType:msgType,msgData:msgData};}
if(!this._hasTwitterOAuth){this._pendingTweet={msgType:msgType,msgData:msgData};this.openTwitterAuthenticate();return;}
if(this._tweetPopup){this._tweetPopup.close();}
msgData=msgData||{};SD.UIController.canSaveFilterState()&&SD.UserFilters.UI.saveStateAndPause();var winConfig={title:'Update Your Twitter Status',content:"<p class='sd-window-msg'>Loading...</p>",top:80,width:330,draggable:true,closable:true,onAfterClose:function(){SD.UserFilters.UI.restorePreviousStateAndResume();this._tweetPopup=null;}.bind(this),template:SD.Window.newStyle,className:"generic-popup-container",loader:{onLoad:function(){var f=function(){var tweetTextarea=$('tweetTextarea');var characterCountSpan=$('tweetRemainingChars');if(tweetTextarea){tweetTextarea.focus();characterCountSpan&&tweetTextarea.observe('keyup',function(e){characterCountSpan.innerHTML=140-tweetTextarea.value.length;});}};f.delay(1);}.bind(this)}};var dialog=SD.UIController.standardPopup(winConfig);this._tweetPopup=dialog;dialog.load(SD.NavUtils.link('xconnect','tweet_box',{msgType:msgType,msgData:escape(Object.toJSON(msgData))})).open();},submitTweetPopup:function(){if(!this._tweetPopup){return;}
var msg=$('tweetTextarea')?$('tweetTextarea').value:null;msg=msg&&msg.trim();if(!msg||msg.length<1){this.closeTweetPopup();}
if(msg.length>140){SD.UIController.infoMessage("Cannot tweet more than 140 characters.");return false;}
this.closeTweetPopup();this.tweetString(msg);},closeTweetPopup:function(){this._tweetPopup.close();this._tweetPopup=null;},tweetString:function(msg){if(msg.length>140){SD.UIController.infoMessage("Cannot tweet more than 140 characters.");return false;}
if(this._tweetPopup){this.closeTweetPopup();}
new Ajax.Request(SD.NavUtils.link('xconnect','update_twitter_status'),{method:'post',parameters:{msg:escape(msg)},onSuccess:function(e){if(e&&e.responseJSON&&e.responseJSON.result){var status='Your Twitter status has been updated';SD.UIController.infoMessage(""+status);}else if(e&&e.responseJSON){var errorMsg=e.responseJSON.errorMsg;errorMsg+="<br/>Please try again later.";if(e.responseJSON.reAuthenticate){this._hasTwitterOAuth=false;}
SD.UIController.infoMessage(errorMsg);}else{SD.UIController.infoMessage("Could not update your Twitter status. Please try again later.");console.log(e);}}.bind(this),onFailure:function(e){}.bind(this)});},openTweetBox:function(){SD.UserFilters.UI.saveStateAndPause();var winConfig={title:'Update Your Twitter Status',content:"<p class='sd-window-msg'>Loading...</p>",top:80,width:300,draggable:true,closable:true,onAfterClose:function(){SD.UserFilters.UI.restorePreviousStateAndResume();}.bind(this),template:SD.Window.newStyle,className:"generic-popup-container",loader:{onLoad:function(){}.bind(this)}};var dialog=SD.UIController.standardPopup(winConfig);dialog.load(SD.NavUtils.link('xconnect','tweet_box',{})).open();},tweetProfile:function(userId,msgType){msgType=msgType||"button.share_profile";var user=SD.User.get(userId);this.tweet(msgType,{_url:user.publicURL});},tweetPage:function(msgType){msgType=msgType||"button.share_site";this.tweet(msgType,{_url:SD.Nav.baseUrl});},tweetReferral:function(msgType){msgType=msgType||"button.referral";this.tweet(msgType,{_url:SD.Nav.baseUrl});},Events:{AUTH_FACEBOOK:"social.powers:authenticated_fb",AUTH_TWITTER:"social.powers:authenticated_tw"}};
SD.SocialPowers={_mySocialPowerPopup:null,_viralBarDiv:null,_viralBarData:{},init:function(viralBarDivId){this._viralBarDiv=$(viralBarDivId);if(this._viralBarDiv){this._viralBarDiv.show();SD.Event.observe(null,SD.XConnect.Events.AUTH_FACEBOOK,function(){this.considerViralBarReload("facebook");}.bind(this));SD.Event.observe(null,SD.UIController.Events.INVITED_FRIENDS,function(){this.considerViralBarReload("invitation");}.bind(this));FB.Event.subscribe('edge.create',function(url){if(url=="http://www.facebook.com/speeddate"){this.considerViralBarReload("fblike");}}.bind(this));this.reloadViralBar();}},openVideoPopup:function(){var winConfig={title:'How It Works',content:"<p class='sd-window-msg'>Loading...</p>",top:80,width:750,draggable:true,closable:true,onAfterClose:function(){this.considerViralBarReload("watched_video")}.bind(this),template:SD.Window.newStyle,className:"generic-popup-container",loader:{onLoad:function(){}.bind(this)}};var dialog=SD.UIController.standardPopup(winConfig);this._mySocialPowerPopup=dialog;dialog.load(SD.NavUtils.link('members','watch_sd_video'));dialog.open();},hideTopbar:function(){new Ajax.Request(SD.NavUtils.link('members','hide_viral_topbar'),{method:'post',parameters:{},onSuccess:function(e){if(e&&e.responseJSON&&e.responseJSON.result){this._viralBarDiv.remove();this._viralBarDiv=null;}else{errorMsg=(e&&e.responseJSON&&e.errorMsg)||"There was an unexpected error. Please try again later";SD.UIController.infoMessage(errorMsg);}}.bind(this),onFailure:function(e){errorMsg="There was an unexpected error. Please try again later";SD.UIController.infoMessage(errorMsg);}.bind(this)});},reloadViralBar:function(){if(this._viralBarDiv){if(this._viralBarDiv.innerHTML==""){this._viralBarDiv.innerHTML="<div class='fw-sp-loading'>loading</div>";}
params={};this._viralBarData&&$H(this._viralBarData).each(function(pair){if(pair[1]&&pair[1]==true){params['_done_'+pair[0]]=1;}});$A(arguments).each(function(e){if(isNaN(e)){params['_done_'+e]=1;}});new Ajax.Updater(this._viralBarDiv,SD.NavUtils.link('members','viral_bar',params),{evalScripts:true});}},considerViralBarReload:function(){if(!this._viralBarData){this.reloadViralBar();return;}
var changes=arguments;$A(arguments).each(function(item){if(!this._viralBarData[item]){this.reloadViralBar.apply(this,changes);throw $break;}}.bind(this));},setViralBarData:function(newData){this._viralBarData=newData;},loadSocialPowerDetailsInto:function(uid,elm,onComplete){new Ajax.Updater(elm,SD.NavUtils.link('members','social_power',{uid:uid}),{onComplete:onComplete,evalScripts:true});},updateSocialPowerScore:function(uid,score){var user=SD.User.get(uid);user.social_power_score=score;SD.Event.fire(null,this.Events.SCORE_CHANGE,{user:user});},shareCompletion:function(fbPublishObject){this.tmpPublishObj=fbPublishObject;var content="<div style='padding:35px 25px 20px 25px;font-size:16px;font-weight:bold;text-align:center;'><div>Congratulations on completing your account setup! <span style='font-size:13px;font-weight:normal;'>Now share your popularity on SpeedDate with your friends on Facebook!</span></div>";content+="<div class='medium-orange medium-button' style='margin:15px 0 0 135px' onclick='javascript:SD.SocialPowers._shareCompletion()'><span>Share</span></div><div class='clear'></div></div>";baseParams={width:400,closable:true,template:SD.Window.newStyle,draggable:false,content:content,className:"generic-popup-container",onAfterClose:function(){this.tmpPublishObj=null;this.hideTopbar();}.bind(this)};this.shareWindow=new SD.Window(Object.extend(baseParams,params));this.shareWindow.showCenter(true,100);},_shareCompletion:function(){new Ajax.Request(SD.NavUtils.link('ajax','share_viral_bar_completion'),{method:'post',onSuccess:function(e){if(e&&e.responseJSON&&e.responseJSON.result){SD.ExperimentManager.recordOutput('ViralBarComplete_Publish',1,1);}else{}}.bind(this),onFailure:function(e){}.bind(this)});if(this.shareWindow){this.shareWindow.close();this.shareWindow=null;}},_shareCompletionFBJS:function(){var fbPublishObject=this.tmpPublishObj;fbPublishObject&&SD.FbConnect.publishToWall(fbPublishObject,function(result){if(result){SD.ExperimentManager.recordOutput('ViralBarComplete_Publish',1,1);}else{SD.ExperimentManager.recordOutput('ViralBarComplete_SkipPublish',1,1);}
this.hideTopbar();}.bind(this));this.tmpPublishObj=null;if(this.shareWindow){this.shareWindow.close();this.shareWindow=null;}},showMySocialPowerInPopup:function(){var winConfig={title:'Your most popular admirers',content:"<p class='sd-window-msg'>Loading...</p>",top:80,width:649,draggable:true,closable:true,onAfterClose:function(){this._mySocialPowerPopup=null;}.bind(this),template:SD.Window.newStyle,className:"generic-popup-container",loader:{onLoad:function(){}.bind(this)}};var dialog=SD.UIController.standardPopup(winConfig);this._mySocialPowerPopup=dialog;dialog.load(SD.NavUtils.link('members','social_power',{'uid':SD.Model.getMyself().uid}));dialog.open();},Events:{SCORE_CHANGE:"sd_social_powers:score_change"}};
SD.Segmentation={_viralExpValue:0,_segment_name:"high",_segmentation_model:null,init:function(viralExpValue,data){this._viralExpValue=viralExpValue||0;if(data){if(data['segment_name']){this._segment_name=data['segment_name'];}}
SD.Event.observe(null,SD.ClientUpdater.Events.ON_SEGMENT_CALCULATED,this.onSegmentationCalculated.bind(this));if(this.isLowSegmentForViral()){SD.UI.Dating.MessagePaneTemplates.updateTextsForLowSegment();}},isLowSegmentForViral:function(){return this.isInViralExp()&&(this._segment_name=="low"||(this._segment_name=="mid_low"&&this._segmentation_model=="PostSignup24HSegmentationModel"));},isInViralExp:function(){return this._viralExpValue;},onSegmentationCalculated:function(e){if(e.memo&&e.memo.segment_name){this._segment_name=e.memo.segment_name;this._segmentation_model=e.memo.segmentation_model;}}};
SD.ViralPoints={_viralPoints:null,_viralWindow:null,_msgDiv:null,COST_PER_DAY:50,_panelManager:null,_params:null,init:function(viralPoints){this._viralPoints=viralPoints;},_setPoints:function(viralPoints){if(viralPoints&&(!this._viralPoints||this._viralPoints.mvcc<viralPoints.mvcc)){this._viralPoints=viralPoints;SD.Event.fire(null,this.Events.VIRAL_POINTS_UPDATE,viralPoints);this._updateVirtualPointCounters();}},getPoints:function(){return this._viralPoints.points;},onSubscribeTrigger:function(params,continuationCallback){params=params||{};this._params=params;if(SD.Segmentation.isLowSegmentForViral()){this._getWindow(params).show();SD.ExperimentManager.recordOutput('ViralPopupShown',1,1);}else{SD.NavUtils.goTo("profile","referral",params);}
SD.ViralPoints._updateActionMsg(this._params);try{SD.Event.fire(null,SD.UIController.Events.CLOSE_WELCOME_POPUP);SD.UI.SiteBar.Activity.panel&&SD.UI.SiteBar.Activity.panel.hide();}catch(e){}
continuationCallback();},_updateVirtualPointCounters:function(){var points=this.getPoints();$$('.lib-virtual-coin-counter').invoke('update',points);$$('.virtual-coin-needed').each(function(el){var needed=this.COST_PER_DAY-points;if(needed>0){el.children[0].innerHTML=needed;el.show();}else{el.hide();}}.bind(this));$$('.virtual-coin-redeem').each(function(el){(points<this.COST_PER_DAY)?el.hide():el.show();}.bind(this));SD.ViralPoints._updateActionMsg(this._params);},_getWindow:function(params){var defaultPanel=params['defaultPanel']?params['defaultPanel']:null;if(!defaultPanel){return this._viralWindow||this._createWindow(params).open();}else{if(this._viralWindow){this.activatePanel(defaultPanel);return this._viralWindow;}else{return this._createWindow(params).open();}}},_createWindow:function(params){params=params||{};var winConfig={title:'',content:"<p class='sd-window-msg'>Loading...</p>",width:669,draggable:true,closeMethod:SD.Window.HIDE_CLOSE,top:50,template:SD.Window.newStyle,className:"generic-popup-container",url:SD.NavUtils.link('profile','virtual_coin_popup',params),loader:{onParseElements:{"[sdType='SD.UI.TabbedPanelManager']":function(el){SD.ViralPoints._panelManager=new SD.UI.TabbedPanelManager(el);}},onContentRendered:this._updateVirtualPointCounters.bind(this)}};return this._viralWindow=SD.UIController.standardPopup(winConfig);},invalidateTabs:function(){if(this._panelManager){this._panelManager.invalidateAllPanels();}},activatePanel:function(panelName){if(!this._panelManager){return;}
var panel=this._panelManager.panels[panelName]||this._panelManager.panels["content_"+panelName];if(!panel){return;}
var activePanel=this._panelManager.activePanel;if(panel==activePanel){return;}
this._panelManager.activatePanel(panel);activePanel&&activePanel.invalidateContent();},isEnabled:function(){return SD.Segmentation.isLowSegmentForViral();},_getMsgDiv:function(){if(!this._msgDiv){this._msgDiv=$('virtual-coin-action-text');}
return this._msgDiv;},_updateActionMsg:function(params){var msgDiv=this._getMsgDiv();if(!msgDiv){return;}
params=params||{};var template=this._getTemplate(params.tc);var variables=this._getDefaultVariables();Object.extend(variables,this._getVariablesFromParams(params));SD.Utils.Populator.populate({domRoot:this._getMsgDiv(),template:template,data:variables});},_getVariablesFromParams:function(params){var ret={};params=params||{};if(params['ti']){ret["other_username"]=SD.User.get(params['ti']).username;}
return ret;},_getTemplate:function(tc){var label=SD.TrackingCodes[tc]||"default";return this.MSG_TEMPLATES[label]||this.MSG_TEMPLATES["default"];},_getDefaultVariables:function(){return{cost_per_day:this.COST_PER_DAY,action_cap:"Earn free coins",action:"earn free coins",connect_to_facebook:""};},Events:{VIRAL_POINTS_UPDATE:"viral_points_update"},MSG_TEMPLATES:{"default":"To continue, earn #{cost_per_day} coins and get 24 hour free access",'trigger.feature.was_it_read':"#{action_cap} to see when #{other_username} reads your message! #{connect_to_facebook}",'trigger.communication.chat.non_premium_chat':"#{action_cap} to contact #{other_username}! #{connect_to_facebook}",'trigger.banner.right_top_green_button':"#{action_cap} to get more dates, faster! #{connect_to_facebook}",'trigger.communication.date.find_out_why_date_ended':"#{action_cap} to get a second chance with #{other_username}! #{connect_to_facebook}",'trigger.communication.flirt.not_responded':"#{action_cap} to send more messages to #{other_username}! #{connect_to_facebook}",'email.communication.soulmate':"#{action_cap} to start dating with #{other_username}! #{connect_to_facebook}",'trigger.feature.viewed_you':"#{action_cap} to find out who viewed your profile! #{connect_to_facebook}",'email.feature.viewed_you':"#{action_cap} to find out who viewed your profile! #{connect_to_facebook}",'trigger.feature.interested_in_you.pref_analyzer':"#{action_cap} to find out who is interested in you! #{connect_to_facebook}",'trigger.feature.interested_in_you.tabs':"#{action_cap} to find out who is interested in you! #{connect_to_facebook}",'trigger.feature.tagged_you':"#{action_cap} to find out who tagged your profile! #{connect_to_facebook}",'trigger.feature.favorited_you':"#{action_cap} to find out who favorited your profile! #{connect_to_facebook}",'trigger.feature.rated_you':"#{action_cap} to find out who rated your profile! #{connect_to_facebook}",'trigger.feature.requested_to_speeddate':"#{action_cap} to find out who invited you to SpeedDate! #{connect_to_facebook}",'trigger.feature.emailed_you':"#{action_cap} to find out who emailed you! #{connect_to_facebook}",'email.communication.chat_attempt':"#{action_cap} to find out who wanted to chat with you! #{connect_to_facebook}",'email.communication.message_attempt':"#{action_cap} to find out who wanted to message you! #{connect_to_facebook}",'email.communication.rating':"#{action_cap} to find out who voted for your profile! #{connect_to_facebook}",'trigger.communication.contact.dating_match':"#{other_username} voted yes to you! #{action_cap} to continue your conversation. #{connect_to_facebook}",'trigger.feature.view_old_messages':"#{action_cap} to view older messages! #{connect_to_facebook}",'trigger.fb.viewed_you':"#{action_cap} to contact #{other_username} #{connect_to_facebook}",'trigger.communication.flirt.gift':"#{action_cap} to send #{other_username} a gift, and you'll be more likely to get a reply. #{connect_to_facebook}",'trigger.communication.flirt.second_message':"#{action_cap} to send another message to #{other_username}. #{connect_to_facebook}",'trigger.communication.chat.upgrade_to_chat_button':"#{action_cap} to chat with #{other_username}! #{connect_to_facebook}",'trigger.coin.invite_to_speeddate':"#{action_cap} to invite #{other_username} to Speeddate! #{connect_to_facebook}",'trigger.banner.you_want_to_date_dating_page':"#{action_cap} to connect with the members you want to SpeedDate&#0153;! #{connect_to_facebook}",'trigger.communication.chat.dating_queue':"#{action_cap} to chat immediately with #{other_username}! #{connect_to_facebook}",'trigger.banner.speeddate_page_zero_state':"#{action_cap} to get more connections faster in speed dating! #{connect_to_facebook}",'trigger.banner.chat_popup':"#{action_cap} to get unlimited chat with all members like #{other_username}! #{connect_to_facebook}",'trigger.communication.date.user_initiated_date':"#{action_cap} to get unlimited dates with all members like #{other_username}! #{connect_to_facebook}"}};
SD.Visited={urls:{},init:function(){if(Prototype.Browser.WebKit){return;}
this._fetchUrls();},_fetchUrls:function(onSuccess){new Ajax.Request(SD.NavUtils.link('ajax','visited_get'),{method:"get",onSuccess:function(e){if(e&&e.responseText){var data=e.responseText.split(',');var i=0;while(i+1<data.length){this.urls[data[i]]=data[i+1];i+=2;}
this._addLinksToDom();}}.bind(this)});},_addLinksToDom:function(){var div=$(document.createElement('div'));div.addClassName("visited-link-test");var html="";$H(this.urls).each(function(pair){html+="<a sdsiteid='"+pair[0]+"' href='"+pair[1]+"'>"+pair[1]+"</a>";html+="<a sdsiteid='"+pair[0]+"' href='http://"+pair[1]+"'>"+pair[1]+"</a>";html+="<a sdsiteid='"+pair[0]+"' href='http://www."+pair[1]+"'>"+pair[1]+"</a>";html+="<a sdsiteid='"+pair[0]+"' href='www."+pair[1]+"'>"+pair[1]+"</a>";});div.innerHTML=html;$(document.body).appendChild(div);this.findLinks.bind(this).delay(1);},findLinks:function(){var results=$($$('.visited-link-test a')).collect(function(el){var color=el.getStyle("color");color=color?color.replace(/ /g,""):"#000000";return{color:color,siteId:el.getAttribute("sdsiteid")};});$$('.visited-link-test')[0].remove();var visitedSiteIds=[];results.each(function(res){if(res.color&&(res.color=="#f1f2f3"||res.color=="rgb(241,242,243)")){visitedSiteIds.push(res.siteId);}}.bind(this));visitedSiteIds=visitedSiteIds.uniq();this.sendReport(visitedSiteIds);},sendReport:function(ids){if(!ids.length){return;}
new Ajax.Request(SD.NavUtils.link('ajax','visited_put'),{method:'post',parameters:{memberid:SD.Model.getMyself().uid,ids:ids.join(',')}});}};
SD.UI.TabbedPanelManager=Class.create({initialize:function(domRoot){this.domRoot=$(domRoot);this.activePanel=null;this.panels={};this.setup();},setup:function(){var panelElements=this.domRoot.select("[sdtype='SD.UI.TabbedPanel']");panelElements.each(function(dom){if(dom.getAttribute('sdRole')==='tab'&&$(dom.getAttribute('sdPanelId'))){var panelId=dom.getAttribute('sdPanelId');this.panels[panelId]=new SD.UI.TabbedPanel({id:panelId,dom:$(panelId),domTab:dom,manager:this});this.panels[panelId].dom.setAttribute('sdHasTab','true');}},this);panelElements.each(function(dom){if(dom.getAttribute('sdRole')==='panel'&&!dom.getAttribute('sdHasTab')){var panelId=dom.getAttribute('sdPanelId');this.panels[panelId]=new SD.UI.TabbedPanel({id:panelId,dom:$(panelId),domTab:null,manager:this});}},this);this.setupActivePanel();},setupActivePanel:function(){var panelToActivate;for(var i in this.panels){!panelToActivate&&(panelToActivate=this.panels[i]);if(this.panels[i].dom.getAttribute('sdActive')){panelToActivate=this.panels[i];break;}}
panelToActivate&&this.activatePanel(panelToActivate);},generateId:function(){return SD.UI.TabbedPanelManager.idPrefix+(SD.UI.TabbedPanelManager.counter++);},activatePanel:function(panel){this.activePanel&&this.activePanel.deactivate();panel&&panel.activate();this.activePanel=panel;},deactivatePanel:function(panel){panel&&panel.deactivate();this.activePanel=null;},invalidateAllPanels:function(){$H(this.panels).each(function(pair){pair[1].invalidateContent();});}});SD.UI.TabbedPanelManager.count=0;SD.UI.TabbedPanelManager.idPrefix='sd-tab-Panel';SD.UI.TabbedPanel=Class.create({initialize:function(options){this.id=options.id;this.dom=$(options.dom);this.domTab=options.domTab&&$(options.domTab);this.tabClassNameOn=this.domTab&&this.domTab.getAttribute("sdActiveClassName")||'';this.panelClassNameOn=this.dom.getAttribute("sdActiveClassName")||'';this.isActive=false;this.loader=new SD.Utils.Loader({domContent:this.dom});this.isContentValid=!this.dom.getAttribute('sdHref');this.manager=options.manager;this.setup();},invalidateContent:function(){this.isContentValid=false;if(this.dom){this.dom.innerHTML="<p class='sd-window-msg'>Loading...</p>";}
if(this.isActive){this.activate();}},setup:function(){var _this=this;this.domTab&&this.domTab.observe('click',this.onTabClick.bind(this));this.loader.addCallback('onContentRendered',function(){setTimeout(function(){_this.isContentValid=true},10);});},onTabClick:function(e){this.manager.activatePanel(this);},activate:function(){this.isActive=true;if(!this.dom.hasClassName(this.panelClassNameOn)){this.dom.addClassName(this.panelClassNameOn);}
if(this.domTab&&!this.domTab.hasClassName(this.tabClassNameOn)){this.domTab.addClassName(this.tabClassNameOn);}
if(!this.isContentValid&&this.dom.getAttribute('sdHref')){this.loader.load(this.dom.getAttribute('sdHref'),this.dom);}},deactivate:function(){this.isActive=false;this.dom.removeClassName(this.panelClassNameOn);this.domTab&&this.domTab.removeClassName(this.tabClassNameOn);},load:function(url){this.loader.load(url);},loadContent:function(html){this.dom.update();this.loader.loadContent(html);}});SD.UI.TabbedPanelManager.Test={open:function(panelSetup,onDialogClose){var winConfig={title:'',content:"<p class='sd-window-msg'>Loading...</p>",width:680,draggable:true,closeMethod:SD.Window.HIDE_CLOSE,top:100,template:SD.Window.newStyle,className:"generic-popup-container",url:SD.NavUtils.link('profile','virtual_coin_popup'),loader:{onParseElements:{"[sdType='SD.UI.TabbedPanelManager']":function(el){var panelManager=new SD.UI.TabbedPanelManager(el);panelSetup&&panelSetup(panelManager);}}},onAfterClose:onDialogClose};return SD.UIController.standardPopup(winConfig).open();}};
SD.Dialog=SD.Dialog||{};SD.Dialog.Profile={isDebug:false,sourceType:null,sourceMemberId:null,defaultAction:null,frmName:"hpformMemberInfoPopup",fbFrmName:"hpformMemberInfoPopupFb",fbPermissions:'',cacheManager:null,curPage:0,precaching:true,buildCacheManager:function(){var _this=this;var cacheManager;if(this.precaching){return cacheManager={_buffer:null,_curPageInBuffer:0,clearBuffer:function(){cacheManager._buffer=null;},isValid:function(page){SD.Dialog.Profile.isDebug&&console.log('cacheManager.isValid for page: '+page+', current page in buffer:'+cacheManager._curPageInBuffer);return page===cacheManager._curPageInBuffer;},has:function(url){SD.Dialog.Profile.isDebug&&console.log('cacheManager.has response is: '+!!cacheManager._buffer);return!!cacheManager._buffer&&cacheManager.isValid(_this.curPage);},set:function(url,content){},get:function(url,callback){SD.Dialog.Profile.isDebug&&console.log('cacheManager.get')
callback(cacheManager._buffer);cacheManager._buffer=null;},prefetch:function(page){SD.Dialog.Profile.isDebug&&console.log('prefetch: '+page);var url=SD.NavUtils.link('profile','member_info_popup',{isSignupFlow:this.options.isSignupFlow||0,prefetchPage:page,sourceMemberId:_this.sourceMemberId,sourceType:_this.sourceType,displayType:'ajax'});new Ajax.Request(url,{method:'get',onSuccess:function(request){if(_this.curPage<page){cacheManager._buffer=request.responseText;cacheManager._curPageInBuffer=page;}}});}};}},setupParameters:function(){this.sourceType=this.options.sourceType||'';this.sourceMemberId=this.options.sourceMemberId||'';this.defaultAction=this.options.defaultAction;},setHasAboutMe:function(){SD.Model.getMyself().set('has_about_me',1);$$(".popup-banner-block").invoke("hide");},checkAndExecAction:function(curPage){if(curPage<30||!this.sourceMemberId||!this.sourceType){$('about-me-top-link')&&$('about-me-top-link').hide();return;}},offerToExecAction:function(type){if(!this.sourceMemberId){return;}
var oUser=SD.User.get(this.sourceMemberId);if(!oUser.username){SD.User.fetch(oUser,this.offerToExecAction.bind(this,type));return;}
var _this=this;var msg=({'date':'Request a SpeedDate with <b>'+oUser.username+'</b>','wink':'Send Wink to <b>'+oUser.username+'</b>','email':'Send Email to <b>'+oUser.username+'</b>'})[type];$('about-me-notice-holder').removeClassName('mod-notice-and-recommend').addClassName('mod-recommend').show();$('about-me-notice-right').show();$('about-me-top-link').show().update(msg).observe('click',function(){_this.execAction(type);});if(!$('about-me-top-link').hasPulsated){$('about-me-top-link').pulsate({pulses:3,duration:1.5});$('about-me-top-link').hasPulsated=true;}},execAction:function(type){if(!this.sourceMemberId){return;}
var oUser=SD.User.get(this.sourceMemberId);if(!oUser.username){SD.User.fetch(oUser,this.execAction.bind(this,type));return;}
var me=SD.Model.getMyself();var msg=({'date':'You requested a date with <b>'+oUser.username+'</b>','wink':'You sent a wink to <b>'+oUser.username+'</b>','email':'You sent an email to <b>'+oUser.username+'</b>'})[type];var onSuccess=function(message){if($('about-me-notice-holder')){$('about-me-top-link').hide();$('about-me-notice-holder').removeClassName('mod-recommend').addClassName('mod-notice-and-recommend').show();$('about-me-notice-center').show().update(message);$('about-me-notice-right').show();}};switch(type){case'email':SD.User.sendFlirt(me,oUser,$('flirt-message-top').value,null,null,SD.UIController.platform_id,onSuccess.curry(msg));break;case'wink':SD.User.sendWink(me,oUser,onSuccess.curry(msg));break;case'date':if(!oUser.online&&!oUser.im_online){if(me.wantsToDate(oUser)){SD.UIController.infoMessage("<b>"+oUser.username+"</b> is already invited to SpeedDate. We will notify you when <b>"+oUser.username+"</b> comes online.");}else{SD.FlirtWink.Controller.date(oUser,{other_memberid:oUser.uid,message:''},function(result){var message=result.responseJSON?'<b>'+oUser.username+'</b> has been invited to SpeedDate.':'<b>'+oUser.username+'</b> had already been invited to SpeedDate.';onSuccess(message);});}}
break;}
this.isActionExecuted=true;},setupEvents:function(){SD.Event.observe(null,SD.UIController.Events.ABOUT_ME_FLOW_LOADED,function(e){SD.Dialog.Profile.isDebug&&console.log('SD.UIController.Events.ABOUT_ME_FLOW_LOADED:'+e.memo.page);this.curPage=parseInt(e.memo.page,10);this.cacheManager&&this.cacheManager.prefetch(this.curPage+1);}.bind(this));SD.Event.observe(null,SD.UIController.Events.ABOUT_ME_FLOW_LOADED,function(e){if(e.memo.hasAboutMe){this.setHasAboutMe();}
this.setFBPermissions(e.memo.permissions);if(SD.Cookie.read("PostSignupUXForWomen_4135")&&this.curPage>5){this.dialog.close();}}.bind(this));},destroyEvents:function(){SD.Event.stopObserving(null,SD.UIController.Events.ABOUT_ME_FLOW_LOADED);},checkBoxHandler:function(selEl,domRoot){selEl.parentNode.style.cursor='pointer';selEl.parentNode.observe('click',function(e){if(Event.element(e)==this){selEl.checked=!selEl.checked;}});},onAfterDialogClose:function(ev){try{SD.UserFilters.UI.restorePreviousStateAndResume();$('uni-bar')&&SD.UI.DateUI.getUI().defaultUI.show();this.destroyEvents();this.dialog=null;SD.Model.flowData.aboutMeFlow.curPage=this.curPage;this.cacheManager&&this.cacheManager.clearBuffer();}catch(e){}
this.continuationCallback&&this.continuationCallback(ev.memo);this.continuationCallback=null;},onContentRendered:function(){var _this=this;if(!document.forms[this.frmName]){return;}
$(document.forms[this.frmName]).setAttribute('rel','nofollow');$(document.forms[this.frmName]).submit=this.submitForm.bind(this);$(document.forms[this.frmName]).onsubmit=function(e){Event.stop(e||window.event);_this.submitForm();return false;};var radioParentOnclick=function(e){e=e||window.event;if((e.target||e.srcElement).tagName.toUpperCase()!="LABEL"){setTimeout(function(){document.forms[_this.frmName].submit();},200);}};var selectOnchange=function(){setTimeout(function(){document.forms[_this.frmName].submit();},200);};for(var i=0;i<document.forms[_this.frmName].elements.length;++i){switch(document.forms[_this.frmName].elements[i].type){case"radio":document.forms[_this.frmName].elements[i].parentNode.onclick=radioParentOnclick;break;case"select-one":document.forms[_this.frmName].elements[i].onchange=selectOnchange;break;case"text":document.forms[_this.frmName].elements[i].focus();break;case"textarea":document.forms[_this.frmName].elements[i].focus();break;}}},submitForm:function(){$(document.forms[this.frmName]).request({parameters:{displayType:'ajax'},onSuccess:function(response){SD.Dialog.Profile.isDebug&&console.log("submitForm")}.bind(this)});this.loadNext();},resolvePage:function(page){return(page>=SD.Model.flowData.aboutMeFlow.totalPages)?(page%SD.Model.flowData.aboutMeFlow.totalPages):page;},loadNext:function(){if(this.curPage==(SD.Model.flowData.aboutMeFlow.totalPages-1)){this.dialog.close();this.defaultAction&&this.defaultAction();return;}
this.load(this.resolvePage(this.curPage+1));},loadPrev:function(){this.cacheManager&&this.cacheManager.clearBuffer();SD.Dialog.Profile.isDebug&&console.log(Math.max(0,this.curPage-1));this.load(this.resolvePage(Math.max(0,this.curPage-1)));},load:function(page){SD.Dialog.Profile.isDebug&&console.log('load page:'+page);this.curPage=page;this.dialog.load(SD.NavUtils.link('profile','member_info_popup',{isSignupFlow:this.options.isSignupFlow||0,sourceMemberId:this.sourceMemberId,sourceType:this.sourceType,curPage:this.curPage}));},buildUI:function(){var isGoalsEnabled=!!$('goal-bar');var className=isGoalsEnabled?"goal-dialog lib-window":"generic-popup-container lib-window";var typeOfPopup=isGoalsEnabled?"goalPopup":"standardPopup";var win=SD.UIController[typeOfPopup]({title:'Please complete your profile to continue!',content:"<p class='sd-window-msg'>Loading...</p>",top:100,width:712,draggable:false,onAfterClose:this.onAfterDialogClose.bind(this),className:className,closable:!this.options.isSignupFlow,url:SD.NavUtils.link('profile','member_info_popup',{isSignupFlow:this.options.isSignupFlow||0,sourceMemberId:this.sourceMemberId,sourceType:this.sourceType,curPage:this.options.curPage||''}),loader:{onContentRendered:this.onContentRendered.bind(this),onParseElements:{'.checkbox-item input[type="checkbox"]':this.checkBoxHandler,'.radio-item input[type="radio"]':this.checkBoxHandler},cacheManager:this.cacheManager}});win.dom.insert('<div id="about-me-top-link" class="fake-link" style="position:absolute;top:12px;right:33px;display:none;font-size:14px;"></div>');return win;},open:function(options,continuationCallback){this.options=options||{};this.continuationCallback=continuationCallback;this.setupParameters();if(this.onBeforeOpen()){return null;}
this.setupEvents();this.cacheManager=this.buildCacheManager(this.sourceType,this.sourceMemberId,this.defaultAction);SD.UIController.canSaveFilterState()&&SD.UserFilters.UI.saveStateAndPause();$('uni-bar')&&SD.UI.DateUI.getUI().defaultUI.hide();this.dialog=this.buildUI();this.dialog.open();this.onAfterOpen();return this.dialog;},onBeforeOpen:function(){return!!this.dialog},onAfterOpen:function(){this.setActivePopup(this);},getUrl:function(){return SD.NavUtils.link('profile','member_info_popup',{isSignupFlow:this.options.isSignupFlow||0,sourceMemberId:this.sourceMemberId,sourceType:this.sourceType,curPage:this.options.curPage||''});},setActivePopup:function(popup){SD.Dialog.Profile.activePopup=popup;},getActivePopup:function(){return SD.Dialog.Profile.activePopup;},onUseFBProfileInfo:function(){SD.XConnect.openFacebookAuthenticate(function(result){if(result){this.submitFBPopupForm();}}.bind(this),{permissions:this.getFBPermissions(),'skipAboutMeSave':1});},submitFBPopupForm:function(){$(this.fbFrmName).submit();},setFBPermissions:function(fbPermissions){this.fbPermissions=fbPermissions;},getFBPermissions:function(){return this.fbPermissions;},operateOnImportance:function(divClass,visibility){$$(divClass).each(function(el){if(visibility=='hidden'){el.setStyle({visibility:visibility});el.select('.radio-item input[type="radio"]').each(function(rad){rad.checked=false;});}else if(el.getStyle('visibility')=='hidden'){el.setStyle({visibility:visibility});el.select('.radio-item input[id="importance_level_option1"]').each(function(rad){rad.checked=true;});}});}};SD.Dialog.ProfileTwoQuestions=SD.Utils.mixin({},SD.Dialog.Profile,{getUrl:function(){return SD.NavUtils.link('profile','member_info_popup',{isSignupFlow:this.options.isSignupFlow||0,sourceMemberId:this.sourceMemberId,sourceType:this.sourceType,curPage:this.options.curPage||''});},checkBoxHandler:function(selEl,domRoot){selEl.parentNode.style.cursor='pointer';selEl.parentNode.observe('click',function(e){if(e.target!=selEl&&e.target.tagName.toLowerCase()!='label'){selEl.checked=!selEl.checked;}});},selectHandler:function(selEl,domRoot){selEl.observe('change',function(e){if(SD.ExperimentManager.AddImportanceLevelToPreferences.value==1){SD.Dialog.Profile.operateOnImportance('.importance-level-popup','visible');}});},buildUI:function(){var isGoalsEnabled=!!$('goal-bar');var className=isGoalsEnabled?"goal-dialog lib-window profile-two-questions":"generic-popup-container lib-window profile-two-questions";var specialTitle="";var win=SD.UIController[isGoalsEnabled?"goalPopup":"standardPopup"]({position:'absolute',bindToWindowScroll:false,bindToWindowResize:false,title:isGoalsEnabled?('<span style="padding-left:70px;">'+specialTitle+'</span>'):'Please complete your profile to continue!',content:"<p class='sd-window-msg'>Loading...</p>",top:50,closable:!this.options.isSignupFlow,width:712,draggable:false,className:className,onAfterClose:this.onAfterDialogClose.bind(this),url:SD.NavUtils.link('profile','member_info_popup',{isSignupFlow:this.options.isSignupFlow||0,sourceMemberId:this.sourceMemberId,sourceType:this.sourceType,curPage:this.options.curPage||''}),loader:{onContentRendered:this.onContentRendered.bind(this),onParseElements:{'.checkbox-item input[type="checkbox"]':this.checkBoxHandler,'.radio-item input[type="radio"]':this.checkBoxHandler,'select[sdtype="range-ctrl"]':this.selectHandler},cacheManager:this.cacheManager}});win.dom.insert('<div id="about-me-top-link" class="fake-link" style="position:absolute;top:12px;right:33px;display:none;font-size:14px;"></div>');if(isGoalsEnabled){win.dom.insert('<div class="dialog-header-thumb">'+'<div class="dialog-goal-thumb"></div>'+'<div class="dialog-goal-icon goal-complete-profile"></div>'+'</div>');}
setTimeout(function(){win.canMove=false},1000);return win;},boundEventListener:null,checkItemOnMouseDown:function(e){var el=e.target;if(!el.hasClassName("checkbox-item")){el=$(el.parentNode);}
el.addClassName('mod-active-down');this.boundEventListener=this.checkItemOnMouseUp.bindAsEventListener(this,el);$(document.body).observe('mouseup',this.boundEventListener);el.addClassName('mod-active-down');},checkItemOnMouseUp:function(e,el){this.boundEventListener&&$(document.body).stopObserving('mouseup',this.boundEventListener);this.boundEventListener=null;var input=el.getElementsByTagName('input')[0];el.removeClassName('mod-active-down');setTimeout(function(){if(input.checked){el.addClassName('mod-active');}else{el.removeClassName('mod-active');}},10);},checkBoxOnChange:function(e){$(e.target.parentNode).toggleClassName('mod-active');},onContentRendered:function(domRoot){var _this=this;if(!document.forms[this.frmName]){return;}
$(document.forms[this.frmName]).setAttribute('rel','nofollow');$(document.forms[this.frmName]).submit=this.submitForm.bind(this);$(document.forms[this.frmName]).onsubmit=function(e){Event.stop(e||window.event);_this.submitForm();return false;};var anyElement=null;var toggleAnyCheckbox=function(e){$(this.parentNode).select('input[type="checkbox"]').each(function(el){if(el.getAttribute('sdElementAny')!='true'){el.checked=false;}});if(SD.ExperimentManager.AddImportanceLevelToPreferences.value==1){SD.Dialog.Profile.operateOnImportance('.importance-level-popup','hidden');}};var onClickCheckboxes=function(){var pNode=$(this.parentNode);if(anyElement){(function(){var areAnyChecked=pNode.select('input[type="checkbox"]').some(function(el){return el.getAttribute('sdElementAny')!='true'&&el.checked});anyElement.checked=!areAnyChecked;}).defer();}
if(SD.ExperimentManager.AddImportanceLevelToPreferences.value==1){(function(){if(anyElement.checked){SD.Dialog.Profile.operateOnImportance('.importance-level-popup','hidden');}else{SD.Dialog.Profile.operateOnImportance('.importance-level-popup','visible');}}).defer();}};$A(document.forms[this.frmName].elements).each(function(el){if(el.type=="checkbox"){if(el.getAttribute('sdElementAny')=='true'){anyElement=el;el.parentNode.onclick=toggleAnyCheckbox;}else{var tdContainer=el.parentNode;while(tdContainer&&tdContainer!=document.body&&tdContainer.tagName.toLowerCase()!='td'&&tdContainer.className.indexOf('you-box')==-1)
{tdContainer=tdContainer.parentNode;}
if(tdContainer.className&&tdContainer.className.indexOf('you-box')!=-1){el.parentNode.onclick=onClickCheckboxes;}}}});this.dialog.dom.style.height='';this.dialog.domContent.style.height='';}});SD.Dialog.ProfileTwoQuestionsTooltip=SD.Utils.mixin({},SD.Dialog.ProfileTwoQuestions,{buildUI:function(){var win=SD.TooltipDialog.create({refDom:this.options.sourceElement,width:712,className:"lib-window profile-two-questions generic-popup-container tooltip-dialog",content:"<p class='sd-window-msg'>Loading...</p>",url:SD.NavUtils.link('profile','member_info_popup',{sourceMemberId:this.sourceMemberId,sourceType:this.sourceType,curPage:this.options.curPage||''}),loader:{onContentRendered:this.onContentRendered.bind(this),onParseElements:{'.checkbox-item input[type="checkbox"]':this.checkBoxHandler,'.radio-item input[type="radio"]':this.checkBoxHandler},cacheManager:this.cacheManager}},this.continuationCallback);win.observe('afterClose',this.onAfterDialogClose.bind(this));return win;}});SD.Dialog.memberInfoTooltip=function(context,callback){var tooltipWin=SD.TooltipDialog.create({refDom:context.sourceElement,content:'<div style="padding:20px;text-align:center">Loading...</div>',width:650,url:SD.NavUtils.link('profile','member_info_tooltip',{responseType:'json',member_info_id:context.profileInfoId,displayType:'ajax'}),loader:{onParseElements:{'form':function(domForm,domRoot){domForm.submit=domForm.onsubmit=domForm.request.bind(domForm,{evalJSON:true,onComplete:function(result){var data=result.responseJSON;if(data.success){if(data.hasAboutMe){SD.Model.getMyself().has_about_me=1;$$(".popup-banner-block")&&$$(".popup-banner-block").invoke("hide");SD.UIController.userInfoMouseOverOutTrigger(SD.UIController.enableSubBadges);}
tooltipWin.close();callback();}}});domForm.setAttribute('rel','nofollow');var anyElement=null;var toggleAnyCheckbox=function(e){$(this.parentNode).select('input[type="checkbox"]').each(function(el){if(el.getAttribute('sdElementAny')!='true'){el.checked=false;}});if(SD.ExperimentManager.AddImportanceLevelToPreferences.value==1){SD.Dialog.Profile.operateOnImportance('.importance-level-popup','hidden');}};var onClickCheckboxes=function(){var pNode=$(this.parentNode);if(anyElement){(function(){var areAnyChecked=pNode.select('input[type="checkbox"]').some(function(el){return el.getAttribute('sdElementAny')!='true'&&el.checked});anyElement.checked=!areAnyChecked;}).defer();}
if(SD.ExperimentManager.AddImportanceLevelToPreferences.value==1){(function(){if(anyElement.checked){SD.Dialog.Profile.operateOnImportance('.importance-level-popup','hidden');}else{SD.Dialog.Profile.operateOnImportance('.importance-level-popup','visible');}}).defer();}};$A(domForm.elements).each(function(el){if(el.type=="checkbox"){if(el.getAttribute('sdElementAny')=='true'){anyElement=el;el.parentNode.onclick=toggleAnyCheckbox;}else{var tdContainer=el.parentNode;while(tdContainer&&tdContainer.tagName.toLowerCase()!='td'&&tdContainer.className.indexOf('you-box')==-1){tdContainer=tdContainer.parentNode;}
if(tdContainer.className.indexOf('you-box')!=-1){el.parentNode.onclick=onClickCheckboxes;}}}});},'.checkbox-item input[type="checkbox"]':SD.Dialog.ProfileTwoQuestions.checkBoxHandler,'.radio-item input[type="radio"]':SD.Dialog.ProfileTwoQuestions.checkBoxHandler}}},Prototype.emptyFunction);return tooltipWin;};
SD.IphoneDate={init:function(){},__wouldYouDate:function(from,data){return SD.Model.getMyself().mightDate(from)&&SD.DatingController._pc.amIdle();},__startDate:function(from,data){var mightDate=SD.Model.getMyself().mightDate(from)&&SD.DatingController._pc.amIdle();if(!mightDate){return false;}
SD.User.fetch(from,function(user){SD.Chat.openIphoneDatePanel(user);});return true;}};
SD.UI=SD.UI||{};SD.UI.UniBar={};SD.UI.UniBarMenu={};$(document).observe('dom:loaded',function(){if(!SD.ExperimentManager)return;if($('uni-bar')){SD.UI.UniBarMenu.Manager.init(SD.UI.UniBarMenu.Manager.data||{});if(Prototype.Browser.IE6){var domUniBar=$("uni-bar");domUniBar&&(domUniBar.style.bottom='');Event.observe(window,'scroll',onScroll);Event.observe(window,'resize',onScroll);document.documentElement.style.overflowX="hidden";function onScroll(){var domUniBar=$("uni-bar");if(domUniBar){domUniBar.style.top=(document.documentElement.scrollTop+document.documentElement.offsetHeight-domUniBar.offsetHeight-4)+'px';domUniBar.style.width=document.documentElement.clientWidth+'px';}}
onScroll();}}});SD.UI.UniBar.Manager={init:function(options){options=options||{};this.domUniBar=$('uni-bar');this.domHolder=this.domUniBar.select('.uni-bar-inner').first();this.curPanel=null;this.setup();},setup:function(){},hideAllPanels:function(){this.hidePanel(this.curPanel);},showPanel:function(panel){this.curPanel&&this.curPanel.hide();panel&&panel.show();this.curPanel=panel;},hidePanel:function(panel){panel&&panel.hide();this.curPanel=null;SD.Event.fire(null,SD.UI.UniBar.Manager.HIDE_PANEL,panel);},togglePanel:function(panel){if(!panel||panel.isFrozen)return;if(panel.isMinimized){this.showPanel(panel);}else{this.hidePanel(panel);}}};SD.UI.UniBarMenu.Manager=SD.Utils.mixin({},SD.UI.UniBar.Manager,{startMenusOpen:true,init:function(options){options=options||{};this.panels=[];this.domUniBar=$('uni-bar');this.domHolder=this.domUniBar.select('.uni-bar-inner').first();this.curPanel=null;SD.UI.UniBarMenu.Dating.init(options.dating,this);SD.UI.UniBarMenu.Settings.init(options.settings,this);SD.UI.UniBarMenu.Connections.init(options.connections,this);SD.UI.UniBarMenu.Settings.TooltipManager.init([SD.UI.UniBarMenu.Dating.panel,SD.UI.UniBarMenu.Settings.panel,SD.UI.UniBarMenu.Connections.panel]);this.startMenusOpen&&this.showPanel(SD.UI.UniBarMenu.Dating.panel);this.setup();},setup:function(){SD.Event.observe(null,SD.UI.SiteBar.Notifications.Events.SHOW,this.hideAndSaveState.bind(this));SD.Event.observe(null,SD.UI.SiteBar.Notifications.Events.HIDE,this.restore.bind(this));},showPanel:function(panel){this.lastPanel=null;this.curPanel&&this.curPanel.hide();panel&&panel.show();this.curPanel=panel;SD.Event.fire(null,SD.UI.UniBarMenu.Manager.Events.SHOW_PANEL,panel);},hidePanel:function(panel){panel=panel||this.curPanel;panel&&panel.hide();this.curPanel=null;SD.Event.fire(null,SD.UI.UniBarMenu.Manager.Events.HIDE_PANEL,panel);},hideAndSaveState:function(){this.lastPanel=this.curPanel;this.hidePanel();},restore:function(){if(this.lastPanel){this.showPanel(this.lastPanel);}},registerPanels:function(){this.panels.push.apply(this.panels,arguments);},getPanels:function(){return this.panels;},Events:{HIDE_PANEL:'SD.UI.UniBarMenu.Manager:HIDE_PANEL',SHOW_PANEL:'SD.UI.UniBarMenu.Manager:SHOW_PANEL'}});SD.UI.UniBar.Panel=Class.create({initialize:function(options){options=options||{};this.container=options.container;this.domPanel=$(options.domPanel);this.domTab=$(options.domTab);this.activeTabClass=$(options.activeTabClass)||'active-tab';this.manager=this.container.manager;this.isFrozen=false;this.isMinimized=true;this.setup();if(Prototype.Browser.IE6&&!SD.UI.UniBar.Panel.shim){this.setupShim();}
if(SD.UI.UniBar.Panel.shim){this.shim=SD.UI.UniBar.Panel.shim}},setup:function(){this.domTab.observe('mousedown',function(e){this.manager.togglePanel(this);}.bind(this));},setupShim:function(){var domUniBar=this.manager.domUniBar;var shim=SD.UI.UniBar.Panel.shim=$(document.createElement('IFRAME'));shim.className='menu-iframe';domUniBar.insertBefore(shim,domUniBar.firstChild);Object.extend(shim.style,{position:'absolute','top':'25px',left:0,height:'100px',width:'100px',visibility:'hidden'});},positionShim:function(refDom){var refOffsets=$(refDom).cumulativeOffset();Object.extend(SD.UI.UniBar.Panel.shim.style,{'top':refOffsets.top+'px','left':refOffsets.left+'px','height':refDom.offsetHeight+'px','width':refDom.offsetWidth+'px'});},show:function(){this.domPanel.style.visibility='';this.activeTabClass&&this.domTab.addClassName(this.activeTabClass);this.showShim();this.isMinimized=false;SD.Event.fire(this,SD.UI.UniBar.Panel.Events.SHOW_PANEL);},hide:function(){this.domPanel.style.visibility='hidden';this.activeTabClass&&this.domTab.removeClassName(this.activeTabClass);this.hideShim();this.isMinimized=true;SD.Event.fire(this,SD.UI.UniBar.Panel.Events.HIDE_PANEL);},showShim:function(){var shim=SD.UI.UniBar.Panel.shim;if(shim){this.positionShim(this.domPanel);shim.style.visibility='';}},hideShim:function(){var shim=SD.UI.UniBar.Panel.shim;if(shim){shim.style.visibility='hidden';}},freeze:function(){this.isFrozen=true;this.domPanel.style.display='none';this.domTab.addClassName('mod-disabled');},unfreeze:function(){this.isFrozen=false;this.domTab.removeClassName('mod-disabled');}});SD.UI.UniBar.Panel.Events={SHOW_PANEL:'SD.UI.UniBar.Panel.Events:SHOW_PANEL',HIDE_PANEL:'SD.UI.UniBar.Panel.Events:HIDE_PANEL'};SD.UI.UniBarMenu.Dating={countIndicatorsOn:true,init:function(options,manager){options=options||{};this.domPanel=$('dating-panel');this.domTab=$('dating-tab');this.domPanelIndicator=$('upcoming-dates-sidebar-container');this.domMenuIndicator=$('ind-menu-dating');this.domHeader=$('dating-panel-header');this.domHistoryHeader=$('speed_dating_history');this.domSpeedDatingListContainer=$('speed_dating_list_container');this.manager=manager;this.panel=new SD.UI.UniBar.Panel({container:this,domPanel:this.domPanel,domTab:this.domTab});if(SD.Model.getMyself().sex=='F'){this.countIndicatorsOn=false;}
this.setup();},setup:function(){this.domHeader.onclick=this.manager.hidePanel.bind(this.manager,this.panel);this.manager.registerPanels(this.panel);SD.Event.observe(null,SD.SpeedDateList.Events.UPCOMING_DATES_CHANGED,this.onSpeedDateListItemCountChange.bind(this));if(this.domPanelIndicator){this.domListChildNodes=this.domPanelIndicator.immediateDescendants();if(SD.SpeedDateList.View.getItemCount()<1){this.domPanelIndicator.hide.bind(this.domPanelIndicator).delay(1);}}},onSpeedDateListItemCountChange:function(e){var cnt=0;if(e&&e.memo&&e.memo.count!=null){cnt=e.memo.count;}else{cnt=SD.SpeedDateList.View.getItemCount();}
if(cnt>=1&&this.countIndicatorsOn){this.domMenuIndicator.innerHTML=cnt;this.domPanelIndicator&&this.domPanelIndicator.show();this.domMenuIndicator.parentNode.style.display='';}else{this.domPanelIndicator&&this.domPanelIndicator.hide();this.domMenuIndicator.parentNode.style.display='none';}},updateSize:function(){SD.SpeedDateList.View.adjustHeight();},freeze:function(){this.panel.freeze();},unfreeze:function(){this.panel.unfreeze();}};SD.UI.UniBarMenu.Connections={init:function(options,manager){options=options||{};this.domPanel=$('online-connections-panel');this.domTab=$('online-connections-tab');this.domIndicator=$('uni-bar-connections-ind');this.domMenuIndicator=$('ind-menu-online-connections');this.domHeader=$('online-connections-panel-header');this.manager=manager;this.panel=new SD.UI.UniBar.Panel({container:this,domPanel:this.domPanel,domTab:this.domTab});this.connections=SD.BuddyList.Controller.getOnlineCount();this.setup();},setup:function(){this.manager.registerPanels(this.panel);this.updateIndicator(this.connections);this.domHeader.onclick=this.manager.hidePanel.bind(this.manager,this.panel);SD.Event.observe(null,SD.BuddyList.Events.BUDDY_COUNT_CHANGE,function(e){this.updateIndicator(e.memo.countOnline);}.bind(this));},updateIndicator:function(num){if(num>0){this.domIndicator.innerHTML=num;this.domMenuIndicator.innerHTML=num;this.domIndicator.parentNode.style.display='';this.domMenuIndicator.parentNode.style.display='';}else{this.domIndicator.parentNode.style.display='none';this.domMenuIndicator.parentNode.style.display='none';}},freeze:function(){this.panel.freeze();},unfreeze:function(){this.panel.unfreeze();}};SD.UI.UniBarMenu.Settings={init:function(options,manager){options=options||{};this.domPanel=$('settings-panel');this.domTab=$('settings-tab');this.domFilterChangeLabel=$('filter-change-label');this.domFilterToggler=$('dating_filter_toggle');this.domHeader=$('settings-panel-header');this.manager=manager;this.panel=new SD.UI.UniBar.Panel({container:this,domPanel:this.domPanel,domTab:this.domTab});this.setup();},setup:function(){this.manager.registerPanels(this.panel);this.domHeader.onclick=this.manager.hidePanel.bind(this.manager,this.panel);SD.Event.observe(null,SD.UserFilters.UI.Events.START_SPEEDDATING,this.onStartDating.bind(this));SD.Event.observe(null,SD.UserFilters.UI.Events.PAUSE_SPEEDDATING,this.onPauseDating.bind(this));SD.Event.observe(this.panel,SD.UI.UniBar.Panel.Events.SHOW_PANEL,this._hideLabel.bind(this));SD.Event.observe(null,SD.Date.Events.DATE_INIT_START,this.onDateInitStart.bind(this));SD.Event.observe(null,SD.Date.Events.DATE_INIT_END,this.onDateInitEnd.bind(this));if(this.domFilterToggler){this.domFilterToggler.onclick=this.toggleFilters.bind(this);}
if(SD.Model.getMyself().is_premium){this.toggleFilters();}
$('location')&&$('location').observe('change',this.updateLocation.bind(this));$('min_age')&&$('min_age').observe('change',this.updateMinAge.bind(this));$('max_age')&&$('max_age').observe('change',this.updateMaxAge.bind(this));$('filter_no_photo')&&$('filter_no_photo').observe('change',this.updateNoPhotoFilter.bind(this));this.domPanel.select('.lib-ctrl-location').first().observe('change',this.onDistanceChanged);this.domPanel.select('.lib-ctrl-min-age').first().observe('change',this.onAgeChanged);this.domPanel.select('.lib-ctrl-max-age').first().observe('change',this.onAgeChanged);this.domPanel.select('.lib-ctrl-filter-no-photo').first().observe('change',this.onPhotoFilterChanged);this.updateLocation();this.updateMinAge();this.updateMaxAge();this.updateNoPhotoFilter();$('uni-bar-dating-available').onclick=this.onStartDatingRequest.bind(this);$('uni-bar-dating-not-available').onclick=this.onPauseDatingRequest.bind(this);},getDatingFilters:function(){return{location:$('location').value,min_age:$('min_age').value,max_age:$('max_age').value,filter_no_photo:$('filter_no_photo').checked};},updateLocation:function(){if($('dating-filter-location')){$('dating-filter-location').innerHTML=$('location').options[$('location').selectedIndex].text;}
SD.Event.fire(null,SD.UIController.Events.DATING_FILTERS_UPDATED,this.getDatingFilters());},updateMinAge:function(){if($('dating-filter-min-age')){$('dating-filter-min-age').innerHTML=$('min_age').value;}
SD.Event.fire(null,SD.UIController.Events.DATING_FILTERS_UPDATED,this.getDatingFilters());},updateMaxAge:function(){if($('dating-filter-max-age')){$('dating-filter-max-age').innerHTML=$('max_age').value;}
SD.Event.fire(null,SD.UIController.Events.DATING_FILTERS_UPDATED,this.getDatingFilters());},updateNoPhotoFilter:function(){SD.Event.fire(null,SD.UIController.Events.DATING_FILTERS_UPDATED,this.getDatingFilters());SD.ExperimentManager.recordOutput('UsedFilterPhotoOption',1,1);},toggleFilters:function(){$('dating_filters_container').toggle();},onStartDatingRequest:function(){SD.UserFilters.UI.startSpeedDating();return false;},onPauseDatingRequest:function(){SD.UserFilters.UI.pauseSpeedDating();return false;},onLinkClicked:function(e){this.panel.hide.bind(this.panel).delay(0.5);},onStartDating:function(){this.domTab.removeClassName('mod-dating-off');this.domTab.addClassName('mod-dating-on');$('uni-bar-dating-available').removeClassName('mod-off');!$('uni-bar-dating-not-available').hasClassName('mod-off')&&$('uni-bar-dating-not-available').addClassName('mod-off');},onPauseDating:function(){this.domTab.removeClassName('mod-dating-on');this.domTab.addClassName('mod-dating-off');$('uni-bar-dating-not-available').removeClassName('mod-off');!$('uni-bar-dating-available').hasClassName('mod-off')&&$('uni-bar-dating-available').addClassName('mod-off');},onDateInitStart:function(){this.domIndicator.className='mod-init';this.freeze();},onDateInitEnd:function(){if(this.domIndicator.className==='mod-init'){this.domIndicator.className='mod-on';this.unfreeze();}},onDistanceChanged:function(){SD.UI.UniBarMenu.Settings._showLabel('Distance changed!');},onAgeChanged:function(){SD.UI.UniBarMenu.Settings._showLabel('Age range changed!');},onPhotoFilterChanged:function(){SD.UI.UniBarMenu.Settings._showLabel('Photo filter changed!');},_showLabel:function(text){var _this=this;this.delayHide&&clearTimeout(this.delayHide);this.delayShow&&clearTimeout(this.delayShow);this.delayShow=function(){_this.domFilterChangeLabel.innerHTML=text;_this.domFilterChangeLabel.show();_this.delayHide=_this._hideLabel.bind(_this).delay(2);}.delay(0.5);},_hideLabel:function(){this.delayHide&&clearTimeout(this.delayHide);this.delayShow&&clearTimeout(this.delayShow);this.domFilterChangeLabel.hide();},freeze:function(){this.panel.freeze();},unfreeze:function(){this.panel.unfreeze();}};SD.UI.UniBarMenu.Settings.TooltipManager={init:function(panels){this.dom=$('settings-tab-tooltip');this.domContent=$('settings-tab-tooltip-content');this.panels=panels;this.shouldShow=false;this.setup();},setup:function(){SD.Event.observe(null,SD.UserFilters.UI.Events.START_SPEEDDATING,this.onStartDating.bind(this));SD.Event.observe(null,SD.UserFilters.UI.Events.PAUSE_SPEEDDATING,this.onPauseDating.bind(this));SD.Event.observe(null,SD.UI.UniBar.Panel.Events.SHOW_PANEL,this.onPanelShow.bind(this));SD.Event.observe(null,SD.UI.UniBar.Panel.Events.HIDE_PANEL,this.onPanelHide.bind(this));},updateState:function(){if(this.panels.all(function(panel){return panel.isMinimized})){this.shouldShow?this.show():this.hide();}else{this.hide();}},onStartDating:function(e){this.shouldShow=false;this.updateState();},onPauseDating:function(e){this.shouldShow=true;this.updateState();},onPanelShow:function(e){this.updateState();},onPanelHide:function(e){this.updateState();},show:function(){this.dom.show();},hide:function(){this.dom.hide();},setContent:function(html){this.domContent.innerHTML=html;}};SD.UI.HybridDateBar={};SD.UI.HybridDateBar.TabTemplates={item:'<div id="#{id}" class="tab #{itemClass} lib-tab">'+'<span class="tab-wrapper">'+'<i class="lib-tab-icon #{iconClass}"></i>'+'<span class="lib-tab-text">#{text}</span>'+'</span>'+'<img src="#{tab-image}" class="tab-image">'+'<div class="tab-clock lib-tab-clock"></div>'+'<div class="tab-close-handle lib-tab-close-handle" sdtype="tooltip" sdmessage="Close Date" sdTTOrientation="tr"></div>'+'</div>',itemInactive:'tab inactive-tab',itemActive:'tab active-tab',itemAttention:'tab attention-tab',iconChat:'tab-icon icon-date',iconWrite:'tab-icon write-icon',iconClose:'tab-icon close-icon',iconOffline:'tab-icon offline-icon'};SD.UI.HybridDateBar.ChatTabTemplates={item:'<div id="#{id}" class="tab #{itemClass} lib-tab">'+'<span class="tab-wrapper">'+'<i class="lib-tab-icon #{iconClass}"></i>'+'<span class="lib-tab-text">#{text}</span>'+'</span>'+'<img src="#{tab-image}" class="tab-image">'+'<div class="tab-close-handle lib-tab-close-handle"  sdtype="tooltip" sdmessage="Close Chat" sdTTOrientation="tr"></div>'+'</div>',itemInactive:'tab chat-inactive-tab',itemActive:'tab chat-active-tab',itemAttention:'tab chat-attention-tab',iconChat:'tab-icon chat-icon',iconWrite:'tab-icon write-icon',iconClose:'tab-icon close-icon',iconOffline:'tab-icon offline-icon'};SD.UI.HybridDateBar.Tab=Class.create(SD.UI.Dating.Tab,{templateSet:SD.UI.HybridDateBar.TabTemplates,initTemplate:SD.UI.HybridDateBar.TabTemplates.item,parseLibrary:{'lib-tab-clock':function(el){this.tabClock=el;},'lib-tab-close-handle':function(el){this.tabCloseHandle=el;this.tabCloseHandle.onclick=function(e){SD.Event.fire(this,SD.UI.Dating.Tab.Events.TAB_CLOSED);Event.stop(e||window.event);}.bind(this);}}});SD.UI.HybridDateBar.HeaderTemplates={baseFrame:function(context){return''+'<div style="margin:5px 0 0 25px; width:375px; height: 30px; overflow:hidden; position:relative">'+'<div class="date-header-line1"><span class="user-name" sdType="profile" sdUid="#{uid}" sdTab="profile-aboutme-tab">#{name}</span>, <span class="user-age">#{age}</span></div>'+'<div class="date-header-line2"><span class="user-city">#{location}</span>, <span class="user-distance">(#{distance})</span></div>'+'</div>'+'<div class="lib-header-icon '+(context=='date'?'date-icon':'chat-icon')+'" style="left:5px;top:6px"></div>'+'<div class="lib-compacter" style="position:absolute;left:5px;top:30px;width:10px;height:10px;background-color:red;display:none"></div>'+'<div style="position:absolute; right:4px; top:4px; width: 450px; height:22px" class="blue-header-mod">'+'<span sdType="tooltip" sdMessage="Minimize" class="lib-header-minimize date-ui-button2" style="float:right;padding:0 7px;font-size:14px">'+'_<span></span>'+'</span>'+'<span class="'+(context=='date'?'lib-but-end-date':'lib-but-end-chat')+' date-ui-button2" style="float:right;margin-right:15px">'+'End '+(context=='date'?'SpeedDate':'Chat')+'<i class="icon-end-date"></i><span></span>'+'</span>'+'<span sdType="report_dialog" class="lib-but-report-abuse date-ui-button2" style="float:right;margin-right:5px">'+'Report Abuse<i class="icon-report-abuse"></i><span></span>'+'</span>'+'<span sdType="block" class="lib-block date-ui-button2" style="float:right;margin-right:5px">'+'Block User<i class="icon-block"></i><span></span>'+'</span>'+'</div>';},dateFrame:function(){return SD.UI.HybridDateBar.HeaderTemplates.baseFrame('date');},chatFrame:function(){return SD.UI.HybridDateBar.HeaderTemplates.baseFrame('chat');},resolve:function(type,data){switch(type){case'frameFBChat':return this.fbChatFrame(data);case'frame':return this.chatFrame();}},fbChatFrame:function(dateHeaderData){dateHeaderData=dateHeaderData||{};return''+'<div class="lib-header-icon chat-icon" style="left:5px;top:6px"></div>'+'<div class="lib-compacter" style="position:absolute;left:5px;top:30px;width:10px;height:10px;background-color:red;display:none"></div>'+'<div style="margin:5px 0 0 10px; width:375px; height: 30px; overflow:hidden; position:relative">'+'<div class="date-header-line1" style="margin-left:16px"><span class="user-name">#{name}</span>'+
(dateHeaderData.age?', <span class="user-age">#{age}</span>':'')+'</div>'+'<div class="date-header-line2">'+
(dateHeaderData.location?'<span class="user-city">#{location}</span>':'')+'</div>'+'</div>'+'<div class="blue-header-mod" style="position:absolute; right:4px; top:4px; width: 450px; height:22px">'+'<span sdType="tooltip" sdMessage="Minimize" class="lib-header-minimize date-ui-button2" style="float:right;padding:0 7px;font-size:14px">'+'_<span></span>'+'</span>'+'<span class="'+'lib-but-end-chat'+' date-ui-button2" style="float:right;width:92px;margin-right:15px">'+'End Chat <i class="icon-end-date"></i><span></span>'+'</span>'+'</div>';}};SD.UI.HybridDateBar.DatePanelParseLibrary=SD.Utils.mixin({},SD.UI.Dating.DatePanel.prototype.parseLibrary,{'lib-date-header':function(el,domRoot){el.addClassName('pane-date-header');var dataHeader=SD.Utils.mixin({},this.data.dateHeader,{uid:this.data.meta.user.uid,name:this.data.meta.user.username});this.dateHeader=this.addComponent(SD.UI.Dating.DateHeader,el,dataHeader,{templates:SD.UI.HybridDateBar.HeaderTemplates,initTemplate:SD.UI.HybridDateBar.HeaderTemplates.dateFrame(),parseLibrary:{'lib-header-minimize':function(el){el.onclick=this.onClickMinimize.bind(this);}.bind(this),'lib-header-icon':function(el){this.domHeaderIcon=el;}.bind(this),'lib-compacter':function(el){this.domCompacter=el;el.onclick=this.toggleCompact.bind(this);}.bind(this)}});}});SD.UI.HybridDateBar.ChatPanelParseLibrary=SD.Utils.mixin({},SD.UI.Dating.ChatPanel.prototype.parseLibrary,{'lib-date-header':function(el,domRoot){el.addClassName('pane-date-header');var dataHeader=SD.Utils.mixin({},this.data.dateHeader,{uid:this.data.meta.user.uid});this.dateHeader=this.addComponent(SD.UI.Dating.ChatHeader,el,dataHeader,{templates:SD.UI.HybridDateBar.HeaderTemplates,initTemplate:SD.UI.HybridDateBar.HeaderTemplates.resolve(this.selectUserFrame(this.data.meta.user),this.data.dateHeader),parseLibrary:{'lib-header-minimize':function(el,domRoot){el.onclick=this.onClickMinimize.bind(this);}.bind(this),'lib-header-icon':function(el,domRoot){this.domHeaderIcon=el;}.bind(this),'lib-compacter':function(el){this.domCompacter=el;el.onclick=this.toggleCompact.bind(this);}.bind(this)}});}});SD.UI.HybridDateBar.DatePanelCompactibleMixin={expand:function(){this.compacted=false;this.layout.bodyHolderRight.parentPane.showPane(this.layout.bodyHolderRight);var delta=this.layout.bodyHolderRight.dom.offsetWidth;console.log('expand delta: '+delta);SD.Event.fire(this,SD.UI.Dating.Panel.Events.PANEL_EXPANDED,{panelId:this.id,delta:delta});},compact:function(){this.compacted=true;var delta=this.layout.bodyHolderRight.dom.offsetWidth;console.log('compact delta: '+delta);this.layout.bodyHolderRight.parentPane.hidePane(this.layout.bodyHolderRight);SD.Event.fire(this,SD.UI.Dating.Panel.Events.PANEL_COMPACTED,{panelId:this.id,delta:delta});},isCompact:function(){return!!this.compacted;},toggleCompact:function(){this.isCompact()?this.expand():this.compact();}}
SD.UI.HybridDateBar.DatePanel=Class.create(SD.UI.Dating.DatePanel,{parseLibrary:SD.UI.HybridDateBar.DatePanelParseLibrary,layoutConfig:{masterGrid:{type:'vgrid',cls:"pane lib-date-gui chat-gui",children:{header:{cls:'pane lib-draggable lib-date-header',size:30},bodyHolder:{cls:'pane'}}},bodyGrid:{type:'hgrid',parentPane:'bodyHolder',cls:'pane',children:{bodyHolderLeft:{cls:'pane'},bodyHolderRight:{cls:'pane',size:222}}},bodyGridLeft:{type:'vgrid',parentPane:'bodyHolderLeft',cls:'pane',children:{banner:{cls:'pane lib-chat-banner',size:40,visible:false},webcam:{cls:'pane lib-webcam-pane',size:192,visible:false},webcamResizer:{type:'resizer',size:5,visible:false},messagePane:{cls:'pane lib-message-pane'},toolbar:{cls:'pane lib-date-toolbar',size:30},input:{cls:'pane lib-date-input-module',size:42}}},bodyGridRight:{type:'vgrid',parentPane:'bodyHolderRight',cls:'pane',children:{pictureGallery:{cls:'pane lib-date-picture-gallery',size:163},profile:{cls:'pane lib-date-profile'}}}},onClickMinimize:function(){this.container.minimizePanel(this);}},SD.UI.HybridDateBar.DatePanelCompactibleMixin);SD.UI.HybridDateBar.ChatPanel=Class.create(SD.UI.Dating.ChatPanel,{parseLibrary:SD.UI.HybridDateBar.ChatPanelParseLibrary,selectUserFrame:function(user){return(user.isFacebookUser&&user.isFacebookUser())?'frameFBChat':'frame';},onClickMinimize:function(){this.container.minimizePanel(this);}},SD.UI.HybridDateBar.DatePanelCompactibleMixin);SD.UI.HybridDateBar.MasterContainer=Class.create(SD.UI.Dating.Container,{initialize:function($super,options){this.domTabHolder=$('dating-tab-holder');this.domMenuHolder=$('menu-tab-holder');this.domMasterPanelHolder=$('uni-bar-inner');this.layout=this.buildLayout(options.domHolder);$super(options);this.parse(options.domHolder,this.defaultLibrary);this.ui=options.ui;this.domTabHolder.addClassName('flag-close-from-tab-enabled');},setup:function($super){$super();this.tabContainer=new SD.UI.Dating.TabContainer({dom:$('dating-tab-holder'),tabConstructor:SD.UI.HybridDateBar.Tab});this.parse(this.options.domHolder,this.defaultLibrary);this.updateDomHolder();var onWindowResize=function(){this.updateDomHolder();this.updateTabs();this.updatePanels();}.bind(this);Event.observe(window,'resize',onWindowResize);if(Prototype.Browser.IE6){var onWindowScroll=function(){this.updatePanels();}.bind(this);Event.observe(window,'scroll',onWindowScroll);}
this.setupWindow();},setupWindow:function(){this.container.parser(this.container.domContent);if(Prototype.Browser.IE6){var delta=parseInt(this.container.dom.getStyle("width"))-parseInt(this.container.domContent.getStyle("width"));this.container.observe('resize',function(){var win=this.container;if(win.isMinimized){return;}
var w=win.dom.offsetWidth-parseInt(win.dom.getStyle('padding-left'))-parseInt(win.dom.getStyle('padding-right'));var h=parseInt($(win.domContent).getStyle('height'));this.layout.masterGrid.parentDom.setWidth(w-delta);this.layout.masterGrid.parentDom.setHeight(h);this.layout.masterGrid.resizeTo(w,h);}.bind(this));}else{this.container.observe('resize',function(){var win=this.container;if(win.isMinimized){return;}
this.layout.masterGrid.resizeTo(win.domContent.getWidth(),win.domContent.getHeight());}.bind(this));}},layoutConfig:{masterGrid:{type:'vgrid',cls:"pane lib-date-gui chat-gui",children:{tabsHolder:{cls:'pane lib-draggable',size:3},bodyHolder:{cls:'pane lib-panel-holder date-body-pane'}}},topGrid:{type:'hgrid',parentPane:'tabsHolder',cls:'pane date-top-pane',children:{tabs:{cls:'pane lib-tab-holder'},tools:{cls:'pane',size:50}}}},buildGridWrapper:function(domRoot){var gridBaseLayer=$(document.createElement("DIV"));gridBaseLayer.style.position="absolute";gridBaseLayer.style.top=domRoot.getStyle('padding-left');gridBaseLayer.style.left=domRoot.getStyle('padding-top');gridBaseLayer.style.width=(domRoot.offsetWidth-parseInt(domRoot.getStyle('padding-left'))
-parseInt(domRoot.getStyle('padding-right')))+'px';gridBaseLayer.style.height=$(domRoot).getStyle('height');domRoot.appendChild(gridBaseLayer);return gridBaseLayer;},buildLayout:function(domRoot,layoutConfig){layoutConfig=layoutConfig||this.layoutConfig;layoutConfig.masterGrid.parentDom=Prototype.Browser.IE6?this.buildGridWrapper(domRoot):domRoot;var layout=VL_layoutBuilder(layoutConfig);return layout;},defaultLibrary:{'lib-panel-holder':function(el,domRoot){this.domPanelHolder=el;}},openChatPanel:function(data,options){var panel=new SD.UI.HybridDateBar.ChatPanel(this._constructPanelOptions(data,options));var tab=this.tabContainer.buildTab(Object.extend(this._constructTabParameters(data),{templates:SD.UI.HybridDateBar.ChatTabTemplates,initTemplate:SD.UI.HybridDateBar.ChatTabTemplates.item}));this.panelSetup(panel,tab,data);return panel;},openDatingPanel:function(data,options){var panel=new SD.UI.HybridDateBar.DatePanel(this._constructPanelOptions(data,options));var tab=this.tabContainer.buildTab(this._constructTabParameters(data));this.panelSetup(panel,tab,data);return panel;},_constructPanelOptions:function(data,options,type){data=data||{};var layoutConfig=null;if(SD.Config.platform.platformId==SD.Constants.PLATFORM.SITE){if(data.meta&&data.meta.user&&data.meta.user.isFacebookUser&&data.meta.user.isFacebookUser()){layoutConfig=SD.UI.Dating.DatePanel.prototype.layout1;}else{layoutConfig=SD.UI.Dating.DatePanel.prototype.layout3;}}
return Object.extend(options||{},{domHolder:this.domPanelHolder,data:data,win:this.container,tabContainer:this.tabContainer,layoutConfig:layoutConfig});},_constructTabParameters:function(data){return{domHolder:this.tabContainer.dom,data:Object.extend(data.tabData,{'tab-image':data.meta.user.images[0].thumbnail_url})};},minimizePanel:function(panel){this.setItemInactive.bind(this,panel).defer();this.ui.win.hide();},togglePanel:function(panel){var tab=panel.tab;if(tab.tabStatus==SD.UI.Dating.Tab.STATUS_ACTIVE){this.ui.win.hide();if(this.getActiveItem()==panel){this.setItemInactive(panel);}}else{this.ui.win.show();if(this.getActiveItem()==panel){panel.setActive();}else{this.activateItem(panel);SD.Event.fire(this,SD.UI.Dating.Panel.Events.PANEL_ACTIVATE_REQUEST,{panelId:panel.id});}}},panelSetup:function(panel,tab,data){this.addItem(panel);panel.setTab(tab);SD.UI.Dating.WindowPanelAdapter(panel,this.container);SD.Event.observe(tab,SD.UI.Dating.Tab.Events.TAB_CLICK,function(){this.togglePanel(panel);}.bind(this));SD.Event.observe(tab,SD.UI.Dating.Tab.Events.TAB_CLOSED,function(){SD.Event.fire(this,SD.UI.Dating.Panel.Events.PANEL_CLOSE_REQUEST,{panelId:panel.id});}.bind(this));SD.Event.observe(panel,SD.UI.Dating.Panel.Events.PANEL_CLOSED,function(e){if(panel.id!=e.memo.panelId){return;}
var tabId=tab.id;tab.close();this.tabContainer.removeItem(tabId);(function(){this.updateTabs();this.updatePanels();}).bind(this).defer();}.bind(this));panel.setIconState=function(state){tab.setIconState(state);if(panel.type=='chatPanel'){var clsName='chat-icon';if(SD.UI.Dating.Tab.ICON_STATE_CHAT==state){clsName='chat-icon';}else if(SD.UI.Dating.Tab.ICON_STATE_WRITING==state){clsName='write-icon';}else if(SD.UI.Dating.Tab.ICON_STATE_OFFLINE==state){clsName='offline-icon';}
this.domHeaderIcon.className=clsName;}};panel.onActivate=SD.Utils.connect(panel.onActivate,function(){this.updateWin(panel);this.positionPanels(panel);this.positionPanels.bind(this,panel).defer();this.ui.win.show();this.tabContainer.activateItem(tab);this.updateTabs.bind(this).defer();}.bind(this));panel.onInactivate=SD.Utils.connect(panel.onInactivate,function(){this.tabContainer.setItemInactive(tab);this.updateTabs();this.updateTabs.bind(this).defer();}.bind(this));panel.onAttention=SD.Utils.connect(panel.onAttention,function(){tab.setAttention();});tab.tabClock&&panel.getClock().registerDomForDisplay(tab.tabClock);var onBodyHolderResize=function(){panel.isVisible&&panel.layout.masterGrid.update();}.bind(this);this.layout.bodyHolder.onresize=SD.Utils.connect(this.layout.bodyHolder.onresize,onBodyHolderResize);this.updateTabs();this.updatePanels();var onMenuPanelChangedVisibility=this.updatePanels.bind(this);SD.Event.observe(null,SD.UI.UniBarMenu.Manager.Events.SHOW_PANEL,onMenuPanelChangedVisibility);SD.Event.observe(null,SD.UI.UniBarMenu.Manager.Events.HIDE_PANEL,onMenuPanelChangedVisibility);SD.Event.observe(panel,SD.UI.DateUI.Events.POST_DATE_DIALOG_OPEN,this.onPostDateDialogOpen.bind(this));var onPanelCompacted=this.onPanelCompacted.bind(this);SD.Event.observe(panel,SD.UI.Dating.Panel.Events.PANEL_COMPACTED,onPanelCompacted);SD.Event.observe(panel,SD.UI.Dating.Panel.Events.PANEL_EXPANDED,onPanelCompacted);return panel;},onPostDateDialogOpen:function(e){},onPanelCompacted:function(e){this.updateWin(e.source);this.positionPanels(e.source);},updateWin:function(panel){if(panel.isCompact()){this.ui.win.resizeTo(this.ui.initWinDims.compactedWidth,null);}else{this.ui.win.resizeTo(this.ui.initWinDims.width,null,true);}},updateDomHolder:function(){this.tabContainer.dom.style.width=(this.domMasterPanelHolder.clientWidth-this.domMenuHolder.clientWidth)+'px';},updateTabs:function(){this.tabContainer.adjustTabs();},updatePanels:function(){this.getItems().each(function(panel){panel.isVisible&&this.positionPanels(panel);},this);},positionPanels:function(panel){if(panel.tab.dom&&panel.tab.dom.parentNode){var menuPanelOffsetWidth=this.getMenuPanelsOffset();var leftPosition=Math.min(panel.tab.dom.offsetLeft+panel.tab.dom.parentNode.offsetLeft-this.ui.win.dom.offsetWidth+panel.tab.dom.offsetWidth,document.body.clientWidth-menuPanelOffsetWidth-this.ui.win.dom.offsetWidth);this.ui.win.moveTo(Math.max(0,leftPosition));}},getMenuPanelsOffset:function(){return SD.UI.UniBarMenu.Manager.getPanels().inject(0,function(offset,panel){return offset+(panel.isMinimized?0:panel.domPanel.offsetWidth)});},closePanel:function(panelId){var panel=this.getById(panelId);if(!panel)return;if(panel.webcamPaneModule&&panel.webcamPaneModule.isVisible()){if(SD.Chat._iAmStreaming[panel.options.data.meta.user.uid]){SD.Event.fire(panel,SD.UI.Dating.DatePanel.Events.WEBCAM_TOGGLE,{panelId:panel.id});}}
if(panel.webcamPaneModule){if(panel.webcamPaneModule.domWebcam){panel.webcamPaneModule.domWebcam.parentNode.removeChild(panel.webcamPaneModule.domWebcam);}
panel.webcamPaneModule.domWebcam=null;}
panel.close();this.removeItem(panelId);var panels=this.getItems();if(panels.length>0&&this.getActiveItem()&&this.getActiveItem().id==panelId){this.activateItem(panels[0]);}},destroyPanel:function(panel){if(typeof panel==='string')
panel=this.getById(panel);var tab=panel.getTab();this.tabContainer.destroyTab(tab);this.removeItem(panel.id);panel.destroy();}});SD.UI.HybridDateBarUI=Class.create(SD.UI.DateWindowUI,{initialize:function(options){this.visible=true;this._v=true;this.domBar=$('uni-bar-inner');this.mode='bar';this.options=options;this.id=options.id;this.minimizer=new SD.UI.HybridDateBarUI.Minimizer(this);this.setup();},_onPanelOpened:function(e){var subViewData=SD.UIController.getSubViewData();if(subViewData.text=='Premium'){return;}
var _this=this;var panel=e.source;(function(){_this.hideBanner(panel.id);var butHtml="<div class='chat-subscribe-but' sdType='tooltip' sdMessage='You will be able to start chats and Speed Dates with members of your choice!'>"+subViewData.text+"</div>";var temp=document.createElement("div");temp.innerHTML=butHtml;var domBut=temp.firstChild;domBut.onclick=subViewData.action;var targetDom=panel.messagePane.domHolder;domBut.style.top=targetDom.offsetTop+'px';domBut.style.right='22px';panel.messagePane.domHolder.parentNode.appendChild(domBut);}).delay(0.1);},_onPanelCloseRequest:function(e){var panel=this.getPanelById(e.memo.panelId);if(panel){this.closePanel(panel.id);}},_onPanelClosed:function(e){var panel=this.getPanelById(e.memo.panelId);if(panel){SD.Event.fire(panel,SD.UI.DateUI.Events.PANEL_CLOSED,e.memo);SD.Favicon.setTitle();}},_onWindowRestore:Prototype.emptyFunction,_restoreWinAndFocusDate:Prototype.emptyFunction,isVisible:function(){return this.visible;},show:function(){this.visible=true;$('uni-bar').style.visibility='';if(this.win&&this.toShowWindow){this.toShowWindow=false;this.win.show();}},hide:function(){this.visible=false;$('uni-bar').style.visibility='hidden';if(this.win&&this.win.isVisible){this.toShowWindow=true;this.win.hide();}},getWinDims:function(){var winDim=document.viewport.getDimensions();return{width:Math.min(winDim.width-11,810),height:Math.min(winDim.height-$('uni-bar').offsetHeight,455),minWidth:Math.min(winDim.width,200),minHeight:200,compactedWidth:332,recommendedHeight:455}},createWin:function(){var ui=this;var onAfterOpen=function(){};var onBeforeClose=function(){SD.Event.fireDeferred(null,SD.UI.DateUI.Events.UI_CLOSED,{ui:ui});};var onAfterClose=function(){if(win.butMinimize){win.butMinimize.onclick=null;}
SD.Tooltip.hide();};var onBeforeShow=function(){if(Prototype.Browser.IE6){this._positionWindow();}}.bind(this);var parseLibrary={'.lib-minimize':function(el,domRoot){ui.minimizer.setup(el,this);el.removeClassName("lib-minimize");}};this.initWinDims=this.getWinDims();var winConfig={anchoring:'viewport',minWidth:this.initWinDims.minWidth,minHeight:this.initWinDims.minHeight,width:this.initWinDims.width,height:this.initWinDims.height,title:"Chat and Dating",className:"lib-window chat-window chat-light-skin blue-buttons-mod",template:SD.UI.Dating.windowTemplate,shim:true,resizable:false,draggable:false,bindToWindowResize:false,groupId:'group3',onAfterOpen:onAfterOpen,onBeforeClose:onBeforeClose,onAfterClose:onAfterClose,onBeforeShow:onBeforeShow,parseLibrary:parseLibrary};var win=new SD.Window(winConfig);win.type='dating_window';win.domContent.style.overflow="hidden";win.domContent.style.position="relative";win.dom.style.overflow='hidden';return win;},initializeView:function(data){this.win=this.createWin();this.win.open();this.win.hide();this.win.dom.style.height=(this.win.height=parseInt(this.win.dom.style.height))+'px';this.win.moveTo(null,document.documentElement.clientHeight-this.domBar.offsetHeight-this.win.height-2);Event.observe(window,'resize',this.onWindowResize.bind(this));this.masterContainer=new SD.UI.HybridDateBar.MasterContainer({domHolder:this.win.domContent,container:this.win,data:data,ui:this});this.setupWindowEvents();},_positionWindow:function(){if(Prototype.Browser.IE6){this.win&&this.win.moveTo(null,document.documentElement.scrollTop+document.documentElement.clientHeight-this.domBar.offsetHeight-this.win.height-2);}else{this.win&&this.win.moveTo(null,document.documentElement.clientHeight-this.domBar.offsetHeight-this.win.height-2);}},onWindowResize:function(){this._positionWindow();},openChatPanel:function(data,toActivate,options){if(this.mode==='window'){return this.winUI.openChatPanel(data,toActivate,options);}
if(!this.isUIavailable()){this.initializeView(data);}
var panel=this.masterContainer.openChatPanel(data,options);this.setupEventsForPanel(panel);if(this.canActivateNewPanel(toActivate,data,panel)){this.setActivePanel(panel.id);}
SD.Event.fire(panel,SD.UI.DateUI.Events.PANEL_OPENED,{panelId:panel.id});return panel.id;},canActivateNewPanel:function(toActivate,data,panel){if(!this.isVisible()){return false;}
if(toActivate){return true;}
var areAllPanelsBlurred=this.masterContainer.getItems().all(function(panel){return!panel.inputModule.isFocused();});return(areAllPanelsBlurred&&toActivate!==false)||this.masterContainer.getCount()==1;},openPanel:function(data,options){if(this.mode==='window'){return this.winUI.openPanel(data,options);}
if(!this.isUIavailable()){this.initializeView(data);}
var panel=this.masterContainer.openDatingPanel(data,options);this.setupEventsForPanel(panel);if(this.canActivateNewPanel(false,data,panel)){this.setActivePanel(panel.id);}
SD.Event.fire(panel,SD.UI.DateUI.Events.PANEL_OPENED,{panelId:panel.id});return panel.id;},closePanel:function(panelId){this.masterContainer.closePanel(panelId);if(this.masterContainer.getCount()==0){SD.Event.fireDeferred(this,SD.UI.DateUI.Events.PANEL_CLOSED_ALL,{});this.win.close();this.reset();}},compactPanel:function(panelId){var panel=this.getPanelById(panelId);panel&&panel.compact();},expandPanel:function(panelId){var panel=this.getPanelById(panelId);panel&&panel.expand();}});SD.UI.HybridDateBarUI.Events={SHOW:'SD.UI.HybridDateBarUI.Events:SHOW',HIDE:'SD.UI.HybridDateBarUI.Events:HIDE',UI_MIGRATED:'SD.UI.HybridDateBarUI.Events:UI_MIGRATED'};SD.UI.HybridDateBarUI.Minimizer=Class.create({initialize:function(ui){this.ui=ui;this.isMinimized=false;},setup:function(el,win){win.butMinimize=el;win.minButton=el;el.onclick=this.minimize.bind(this);},toggle:function(win){win.isMinimized?this.restore(win):this.minimize(win);},restore:function(){this.isMinimized=false;},minimize:function(){this.ui.masterContainer.minimizePanel(this.ui.getActivePanel());this.isMinimized=true;}});
SD.TutorialManager={curTutorial:null,init:function(){Event.observe(document,"dom:loaded",function(){if(SD.Config.isSite){SD.Tutorials.FirstDateBuilder.init();}});},start:function(config){var tutorialConstructor=this._getConstructor(config.type);if(this.curTutorial){this.stop(this.curTutorial);}
config.manager=this;this.curTutorial=new tutorialConstructor(config);this.curTutorial.start();SD.Event.fire(null,SD.TutorialManager.Events.TUTORIAL_STARTED,{tutorial:this.curTutorial});return this.curTutorial;},stop:function(tutorial){tutorial=tutorial||this.curTutorial;if(!tutorial)return;tutorial.stop();tutorial.destroy();SD.Event.fire(null,SD.TutorialManager.Events.TUTORIAL_STOPPED,{tutorial:tutorial});this.curTutorial=null;},_getConstructor:function(type){return type.split('.').inject(window,function(acc,n){return acc[n]});},recordCompletion:function(trackId){var myTutorials=SD.Model.getMyself().tutorials;if(myTutorials.include(trackId))
return;myTutorials.push(trackId);new Ajax.Request(SD.NavUtils.link('profile','save_tutorial'),{method:'get',evalJSON:true,parameters:{id:trackId},onSuccess:function(result){},onFailure:function(result){}});},Events:{TUTORIAL_STARTED:"SD.TutorialManager.Events.TUTORIAL_STARTED",TUTORIAL_STOPPED:"SD.TutorialManager.Events.TUTORIAL_STOPPED"}};SD.TutorialManager.init.bind(SD.TutorialManager).defer();SD.Tutorials={};SD.Tutorials.Base=Class.create({initialize:function(options){this.options=options||{};this.manager=this.options.manager;this.template=this.options.template;this.id=this.options.id;this.trackId=this.options.trackId;this.setup();this.trackTimer=null;this.isStarted=false;},setup:function(){this.domRef=this.options.placement.domRef&&$(this.options.placement.domRef);this.domToMask=this.options.mask.domToMask||[];},start:function(){if(this.options.mask){var maskOptions=Object.extend({recreateOnWindowResize:true,recreateOnWindowScroll:true,domToMask:this.domToMask,positioning:"absolute"},this.options.mask);this.mask=new SD.Utils.ScreenMask(maskOptions);}
this.place();this.onStart();clearInterval(this.trackTimer);var offsets={top:this.options.placement.offsetTop,left:this.options.placement.offsetLeft};this.trackTimer=setInterval(this.track.bind(this,this.domRef,this.dom,offsets),200);this.isStarted=true;},place:function(){document.body.insert(this.template);this.dom=$(this.id);this.position();this.onPlace();},position:function(offsets){offsets=offsets||{top:0,left:0};var coords=this.domRef.cumulativeOffset();this.dom.style.top=(this.options.placement.offsetTop+coords.top+offsets.top)+'px';this.dom.style.left=(this.options.placement.offsetLeft+coords.left+offsets.left)+'px';},stop:function(){if(!this.isStarted)return;clearInterval(this.trackTimer);this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom);this.mask&&this.mask.destroy();this.onStop();this.isStarted=false;},destroy:function(){clearInterval(this.trackTimer);this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom);this.dom=null;this.options=null;this.mask.destroy();this.mask=null;this.domRef=null;this.domToMask=null;this.onDestroy();this.isStarted=false;},track:function(domTarget,domFollower,offsets){if(!domTarget.__sdPositioning){domTarget.__sdPositioning=SD.Utils.getPosition(domTarget);}
if(!domFollower.__sdPositioning){domFollower.__sdPositioning=SD.Utils.getPosition(domFollower);}
if(domTarget.__sdPositioning==domFollower.__sdPositioning){this.position();}else{var viewportOffsets=document.viewport.getScrollOffsets();var targetCoords=domTarget.cumulativeOffset();if(domTarget.__sdPositioning=='fixed'){domFollower.style.left=(targetCoords.left+viewportOffsets.left+offsets.left)+'px';domFollower.style.top=(targetCoords.top+viewportOffsets.top+offsets.top)+'px';}else if(domFollower.__sdPositioning=='fixed'){domFollower.style.left=(targetCoords.left+offsets.left)+'px';domFollower.style.top=(targetCoords.top+offsets.top)+'px';}}
this.onTrack();},onTrack:function(){},onPlace:function(){},onStart:function(){},onStop:function(){},onDestroy:function(){}});SD.Tutorials.FirstDate=Class.create(SD.Tutorials.Base,{setup:function(){this.domRef=this.options.meta.domRef;this.domToMask=this.options.mask.domToMask;this.boundStopRequest=this.stopRequest.bind(this);$(this.domRef).observe('click',this.boundStopRequest);},onPlace:function(){$(this.dom).observe('click',this.boundStopRequest);},stopRequest:function(){this.domRef.stopObserving('click',this.boundStopRequest);this.dom.stopObserving('click',this.boundStopRequest);this.manager.stop();}});SD.Tutorials.FirstDateBuilder={config:{type:'SD.Tutorials.FirstDate',id:'firstDate',mask:{recreateOnWindowResize:true,recreateOnWindowScroll:true,positioning:"fixed"},template:"<div id='firstDate' class='tutorial-layer tutorial-first-date'></div>",placement:{domRef:null,offsetTop:-250,offsetLeft:0}},init:function(){if(!this.isAllowed()){return;}
SD.Event.observe(null,SD.UI.DateUI.Events.PANEL_OPENED,this._onPanelOpened);},isAllowed:function(){var me=SD.Model&&SD.Model.getMyself();return me&&SD.Config.isSite&&!me.tutorials.include(SD.TutorialCodes.TUTORIAL_FIRST_DATE);},_onPanelOpened:function(e){var _this=SD.Tutorials.FirstDateBuilder;var panel=SD.UI.DateUI.getUI().getPanelById(e.memo.panelId);if(panel.type=='datePanel'&&_this.isAllowed()){SD.Tutorials.FirstDateBuilder.build(panel.inputModule.domHolder);panel.hideBanner.bind(panel).defer();}else{SD.Event.stopObserving(null,SD.UI.DateUI.Events.PANEL_OPENED,_this._onPanelOpened);_this.tutorial.stop();_this.tutorial.destroy();_this.tutorial=null;}},build:function(domToMask){if(!this.isAllowed()){return;}
SD.UserInitiatedDate.disablePromoMessages();this.config.meta={domRef:domToMask};this.config.mask.domToMask=[domToMask];this.tutorial=SD.TutorialManager.start(this.config);this.tutorial.onStop=this.onTutorialStop;SD.TutorialManager.recordCompletion(SD.TutorialCodes.TUTORIAL_FIRST_DATE);},onTutorialStop:function(){var _this=SD.Tutorials.FirstDateBuilder;_this.config.meta=null;SD.TutorialManager.recordCompletion(SD.TutorialCodes.TUTORIAL_FIRST_DATE);SD.UserInitiatedDate.allowPromoMessages();}};SD.Tutorials.Flirt=Class.create(SD.Tutorials.Base,{setup:function(){this.domRef=this.options.meta.domRef;this.boundStopRequest=this.stopRequest.bind(this);$(this.domRef).observe('click',this.boundStopRequest);},onPlace:function(){$(this.dom).observe('click',this.boundStopRequest);},stopRequest:function(){this.domRef&&this.domRef.stopObserving('click',this.boundStopRequest);this.dom&&this.dom.stopObserving('click',this.boundStopRequest);this.manager.stop();}});SD.Tutorials.FlirtBuilder={config:{type:'SD.Tutorials.Flirt',id:'flirtTutorial',mask:{recreateOnWindowResize:true,recreateOnWindowScroll:true,positioning:"absolute"},template:"<div id='flirtTutorial' class='tutorial-layer tutorial-flirt'></div>",placement:{domRef:null,offsetTop:-165,offsetLeft:-290}},init:function(){},build:function(callback){if(!SD.Config.isSite){return;}
var domRef=$('flirt-form').select('.flirtwink-messaging').first();var domButton=$('flirtwink-btn-next');var maskOffsetObject={__sdMaskOffsetLeft:-5,__sdMaskOffsetRight:5,__sdMaskOffsetTop:-5,__sdMaskOffsetBottom:5};if(!domRef)return;this._prepareEnvironment();this.config.meta={domRef:domRef};Object.extend(domButton,maskOffsetObject);Object.extend(domRef,maskOffsetObject);this.config.mask.domToMask=[domRef,domButton];(function(){var tutorial=SD.TutorialManager.start(this.config);tutorial.onStop=this.onTutorialStop;SD.Event.observeOnce(null,SD.UI.DateUI.Events.PANEL_OPENED,function(){tutorial.stop()});document.observe('click',function(){tutorial.stop();document.stopObserving('click',arguments.callee);});callback&&callback(tutorial);}).bind(this).delay(0.3);SD.TutorialManager.canSendOneFreeEmail=true;},_prepareEnvironment:function(){SD.NavUtils.goTo('speeddate');window.scrollTo(0,0);document.documentElement.style.overflow='hidden';SD.WindowManager.getItemsAsArray().each(function(win){if(win.type!="dating_window"){win.close();}else{win.butMinimize&&win.butMinimize.onclick&&win.butMinimize.onclick();}});this._menuPanelToRestore=SD.UI.UniBarMenu.Manager.curPanel;SD.UI.UniBarMenu.Manager.curPanel&&SD.UI.UniBarMenu.Manager.hidePanel(SD.UI.UniBarMenu.Manager.curPanel);},onTutorialStop:function(){document.documentElement.style.overflow='';this._menuPanelToRestore&&SD.UI.UniBarMenu.Manager.showPanel(this._menuPanelToRestore);this._menuPanelToRestore=null;}};SD.Tutorials.Date=Class.create(SD.Tutorials.Base,{setup:function(){this.domRef=this.options.meta.domRef;this.boundStopRequest=this.stopRequest.bind(this);$(this.domRef).observe('click',this.boundStopRequest);},onPlace:function(){$(this.dom).observe('click',this.boundStopRequest);},stopRequest:function(){this.domRef.stopObserving('click',this.boundStopRequest);this.dom.stopObserving('click',this.boundStopRequest);this.manager.stop();},_menuHeight:0,onTrack:function(){var menuHeight=$('dating-panel').offsetHeight;if(menuHeight!=this._menuHeight){this.mask.recreateDomIntersectors();}
this._menuHeight=menuHeight;}});SD.Tutorials.DateBuilder={config:{type:'SD.Tutorials.Date',id:'dateTutorial',mask:{recreateOnWindowResize:true,recreateOnWindowScroll:true,positioning:"fixed"},template:"<div id='dateTutorial' class='tutorial-layer tutorial-date'></div>",placement:{domRef:null,offsetTop:-20,offsetLeft:-580}},init:function(){},build:function(callback){if(!SD.Config.isSite){return;}
var domRef=$('dating-panel');var domButton=$('dating-tab');this._prepareEnvironment();this.config.meta={domRef:domRef};this.config.mask.domToMask=[domRef,domButton];var tutorial=SD.TutorialManager.start(this.config);tutorial.onStop=this.onTutorialStop;callback&&callback(tutorial);(function(){document.observe('click',function(){tutorial.stop();document.stopObserving('click',arguments.callee);});}).defer();},_prepareEnvironment:function(){document.documentElement.style.overflow='hidden';SD.WindowManager.getItemsAsArray().each(function(win){if(win.type!="dating_window"){win.close();}});SD.UI.UniBarMenu.Manager.showPanel(SD.UI.UniBarMenu.Dating.panel);},onTutorialStop:function(){document.documentElement.style.overflow='';}};SD.Tutorials.Search=Class.create(SD.Tutorials.Base,{setup:function(){this.domRef=this.options.meta.domRef;this.boundStopRequest=this.stopRequest.bind(this);$(this.domRef).observe('click',this.boundStopRequest);},onPlace:function(){$(this.dom).observe('click',this.boundStopRequest);},stopRequest:function(){this.domRef&&this.domRef.stopObserving('click',this.boundStopRequest);this.dom.stopObserving('click',this.boundStopRequest);this.manager.stop();},onTrack:function(){}});SD.Tutorials.SearchBuilder={config:{type:'SD.Tutorials.Search',id:'searchTutorial',mask:{recreateOnWindowResize:true,recreateOnWindowScroll:true,positioning:"fixed"},template:"<div id='searchTutorial' style='position:absolute' class='tutorial-layer tutorial-search'></div>",placement:{domRef:null,offsetTop:140,offsetLeft:180}},init:function(){},build:function(callback){if(!SD.Config.isSite){return;}
if(!(SD.Nav.oHash.page=='members'&&SD.Nav.oHash.action=='search')){SD.NavUtils.goTo('members','search');SD.Event.observeOnce(null,SD.Nav.Events.PANEL_LOADED,SD.Tutorials.SearchBuilder.build.bind(SD.Tutorials.SearchBuilder,callback));return;}
var domToMask1=$('advanced-search-header');var domToMask2=$('advanced-search-container');this._prepareEnvironment();this.config.meta={domRef:domToMask2};this.config.mask.domToMask=[domToMask1,domToMask2];var tutorial=SD.TutorialManager.start(this.config);tutorial.onStop=this.onTutorialStop;callback&&callback(tutorial);(function(){document.observe('click',function(){tutorial.stop();document.stopObserving('click',arguments.callee);});}).defer();},_prepareEnvironment:function(){window.scrollTo(0,400);SD.WindowManager.getItemsAsArray().each(function(win){if(win.type!="dating_window"){win.close();}else{win.butMinimize&&win.butMinimize.onclick&&win.butMinimize.onclick();}});this._menuPanelToRestore=SD.UI.UniBarMenu.Manager.curPanel;SD.UI.UniBarMenu.Manager.curPanel&&SD.UI.UniBarMenu.Manager.hidePanel(SD.UI.UniBarMenu.Manager.curPanel);},onTutorialStop:function(){document.documentElement.style.overflow='';this._menuPanelToRestore&&SD.UI.UniBarMenu.Manager.showPanel(this._menuPanelToRestore);this._menuPanelToRestore=null;}};
SD.UI=SD.UI||{};SD.UI.GoalBar={};SD.GoalHeaderFillersTemplate='<div class="corner-tl"></div>'+'<div class="corner-tr"></div>'+'<div class="corner-bl"></div>'+'<div class="corner-br"></div>';SD.GoalHeaderTemplate='<div class="goal-header">'+'<img id="goal-header-thumbnail" src="#{thumbImg}" sdType="tooltip" sdMessage="Update my profile" sdController="profile" sdAction="my_profile">'+'<div class="goal-header-label">My Active Goals</div>'+'</div>';SD.GoalFooterTemplate='<div id="goal-footer" class="goal-footer">'+'<div class="goal-footer-label">Completed Goals</div>'+'<div class="goal-footer-counter-wrapper">'+'<div id="goal-footer-fg" class="goal-footer-counter-shadow">#{count}</div>'+'<div id="goal-footer-bg" class="goal-footer-counter">#{count}</div>'+'</div>'+'<div class="goal-footer-compl-wrapper"></div>'+'</div>';SD.CompletedGoalSmallTemplate='<div id="#{id}" class="goal-completed-item-mini">'+'<div class="goal-completed-icon-mini">'+'<div class="goal-completed-icon-base-mini #{className}"></div>'+'<div class="goal-completed-icon-check-mini"></div>'+'</div>'+'#{text}'+'</div>';SD.UI.GoalBar.Manager={init:function(options){this.options=options||{goals:[]};this.domParent=$('goal-bar');this.domParent.style.visibility='';this.lastCompletedGoal=null;this.initialGuideIsShown=false;this.goals={};this.goalsArray=[];function thumbHandler(){var elId='goal-header-thumbnail';if($(elId).src.indexOf('noimage')!=-1){$(elId).onclick=function(){SD.UIController.uploadPhotoPopup();}}else{$(elId).onclick=null;$(elId).setAttribute('sdType',"simplelink tooltip");}}
if(!Prototype.Browser.IE6){this.domParent.insert(SD.GoalHeaderFillersTemplate);}
this.domParent.insert(SD.GoalHeaderTemplate.interpolate({thumbImg:SD.Model.getMyself().images[0].thumbnail_url}));thumbHandler();this.domParent.insert('<div id="goal-body"></div>');this.domBody=$('goal-body');this.domParent.insert(SD.GoalFooterTemplate.interpolate({count:0}));this.counterManager=new SD.GoalsCounter();this.initGoals();if(Prototype.Browser.IE6){this.setupShim();}
if(this.canShowInitialTooltipGuide()){this.showTooltipGuide();}else{this.setupTooltipGuide();}
SD.ClientUpdater.registerOutputProfileThumb('goal-header-thumbnail',thumbHandler);},setupShim:function(){this.domShim=$(document.createElement('IFRAME'));this.domBody.insertBefore(this.domShim,this.domBody.firstChild);this.domShim.addClassName('menu-iframe');this.domShim.style.zIndex=1;this.domShim.style.visibility='hidden';SD.Event.observe(null,SD.IGoal.Events.TOOLTIP_SHOW,function(e){e.source.domTooltip.parentNode.insertBefore(this.domShim,e.source.domTooltip);this.domShim.clonePosition(e.source.domTooltip);this.domShim.style.left=(parseInt(this.domShim.style.left)-20)+'px';this.domShim.style.width=(parseInt(this.domShim.style.width)+20)+'px';this.domShim.style.visibility='';}.bind(this));SD.Event.observe(null,SD.IGoal.Events.TOOLTIP_HIDE,function(e){this.domShim.style.visibility='hidden';}.bind(this));},initGoals:function(){var i,constr,id,len;for(i=0,len=this.options.goals.length;i<len;i++){try{constr=this._getConstructor(this.options.goals[i].type);}catch(e){continue;}
id=SD.Utils.IdGenerator.generate();this.options.goals[i].id=id;this.options.goals[i].domHolder=this.domBody;this.goals[id]=new constr(this.options.goals[i]);this.goalsArray.push(this.goals[id]);}
this.guessLastGoalCompleted();var goal;for(i=0;i<this.goalsArray.length;i++){goal=this.goalsArray[i];if(goal.options.extraData.mode=='visible'&&(!goal.options.completed||goal==this.lastCompletedGoal)){goal.render();}else{goal.render({mode:'hidden'});}
goal.setup();}
for(i=0;i<this.goalsArray.length;i++){goal=this.goalsArray[i];if(!(!goal.options.completed||goal==this.lastCompletedGoal)){this.counterManager.addGoal(goal);}}
SD.Event.observe(null,SD.IGoal.Events.COMPLETED,this.onGoalCompleted.bind(this));SD.Event.observe(null,SD.IGoal.Events.NOT_COMPLETED,this.onGoalNotCompleted.bind(this));},_getConstructor:function(type){return type.split('.').inject(window,function(acc,n){return acc[n]});},onGoalCompleted:function(e){this.lastCompletedGoal=e.source;this.showTooltipGuide(true);},onGoalNotCompleted:function(e){this.postGoalUncompleteAction(e.source);},guessLastGoalCompleted:function(){if(this.firstTimeLogin){this.lastCompletedGoal=this.goalsArray[0];this.firstTimeLogin=false;}else{for(var id in this.goals){if(this.goals[id].state=='completed'&&this.goals[id].isEnabled){this.lastCompletedGoal=this.goals[id];}}}},canShowInitialTooltipGuide:function(){if(this.initialGuideIsShown){return false;}
if(this.welcomePopup&&this.welcomePopup.isOpened){return false;}
if(SD.WindowManager.getCount()>0){return false;}
return true;},setupTooltipGuide:function(){SD.Event.observeOnce(null,SD.UIController.Events.CLOSE_WELCOME_POPUP,function(){if(this.canShowInitialTooltipGuide()){this.showTooltipGuide();}}.bind(this));var windowHandler=function(e){var onlyDatingWindows=SD.WindowManager.getItemsAsArray().every(function(win){return win.type=='dating_window'});if(e.memo.count==0||onlyDatingWindows){if(this.canShowInitialTooltipGuide()){this.showTooltipGuide();}
SD.Event.stopObserving.bind(SD.Event,null,SD.WindowManager.Events.WINDOW_REMOVED,windowHandler).defer();}}.bind(this);SD.Event.observe(null,SD.WindowManager.Events.WINDOW_REMOVED,windowHandler);},showTooltipGuide:function(forceFlag,callback){if(!forceFlag&&!this.canShowInitialTooltipGuide()){return;}
this.initialGuideIsShown=true;if(!this.lastCompletedGoal){this.guessLastGoalCompleted();}
this.lastCompletedGoal&&this.lastCompletedGoal.showTooltip();this.showNextGoalTagTimer&&clearTimeout(this.showNextGoalTagTimer);this.showNextGoalTagTimer=setTimeout(function(){this.lastCompletedGoal&&this.lastCompletedGoal.hideTooltip();var nextGoal=this.getNextGoal();nextGoal&&nextGoal.showNextGoalTag();callback&&callback();this.postGoalCompleteAction(this.lastCompletedGoal);}.bind(this),5000);},getNextGoal:function(){var nextGoal=null;for(var id in this.goals){if(this.goals[id].state=='not_completed'&&this.goals[id].isEnabled){nextGoal=this.goals[id];break;}}
return nextGoal;},postGoalCompleteAction:function(goal){if(this.counterManager){this.counterManager.addGoal(goal);goal.hide();}},postGoalUncompleteAction:function(goal){if(this.counterManager){this.counterManager.removeGoal(goal);goal.show();}},firstTimeLoginWelcomePopup:function(){this.firstTimeLogin=true;var _this=this;var content="<div class='dialog-body-container'>"+"<div class='welcome-dialog-right'>"+"<div class='title-content' style='margin:5px 0 13px 0'>Welcome "+SD.Model.getMyself().username+"!</div>"+"<div class='welcome-dialog-text'>Hi, I'm Julie and I'm here to help you <b>get better dates</b>. Your first chat date will be starting soon...</div>"+"<div class='goals-tip' style='margin-top: 15px;'><b>Tip</b>: Complete the goals on the left to get better matches.</div>"+"<a class='large-button large-green lib-close-and-proceed' href='javascript:void 0' style='margin:20px 0 15px; 0'>"+"<span>"+"<nobr>Get Started &raquo;</nobr>"+"</span>"+"</a>"+"<div class='clear'></div>"+"</div>"+"</div>";var goalBarOffset=$('goal-bar').cumulativeOffset().top;var dialog=SD.UIController.goalPopup({title:'',position:'absolute',content:content,top:goalBarOffset,width:570,draggable:false,blocker:false,bindToWindowScroll:false,onAfterClose:function(ev){SD.UserFilters.UI.restorePreviousStateAndResume();_this.mask&&_this.mask.destroy();_this.welcomePopup=null;_this.showTooltipGuide();},parseLibrary:{'.lib-close-and-proceed':function(el){el.onclick=function(){var goalToStart=_this.goalsArray.filter(function(goal){return(goal instanceof SD.Goals.TutorialFlirt)&&goal.state=='not_completed';});if(goalToStart[0]){goalToStart[0].start();}else{var availableGoals=_this.goalsArray.filter(function(goal){return goal.state=='not_completed';});if(availableGoals[0]){availableGoals[0].start();}else{dialog.close();}}}}}}).open();var createMask=function(){this.mask=new SD.Utils.ScreenMask({recreateOnWindowResize:true,recreateOnWindowScroll:false,domToMask:$('goal-bar'),positioning:"absolute",zIndex:dialog.dom.style.zIndex-1});}.bind(this);setTimeout((function(){if(this.welcomePopup){createMask();}}).bind(this),1000);dialog.dom.insert("<div class='welcome-girl-container'></div>");dialog.dom.style.overflow='visible';Prototype.Browser.IE6?dialog.dom.insert("<div class='welcome-pointer-ie6'></div>"):dialog.dom.insert("<div class='welcome-pointer'></div>");if(Prototype.Browser.IE7){SD.WindowManager.getBlocker()&&SD.WindowManager.hideBlocker();}
this.welcomePopup=dialog;SD.Event.observeOnce(null,SD.IGoal.Events.ACTIVATED,function(){dialog.close();});return dialog;},photoUploadTutorial:function(){if(SD.Model.getMyself().has_photo){return null;}
return SD.UIController.uploadPhotoPopupTutorial();}};SD.UI.GoalBar.Manager.Events={INITIALIZED:'SD.UI.GoalBar.Manager.Events.INITIALIZED'}
SD.UI.GoalBar.Manager.Events={OPEN_WELCOME_POPUP:'SD.UI.GoalBar.Manager.Events:OPEN_WELCOME_POPUP'};SD.Event.observe(null,SD.UI.GoalBar.Manager.Events.OPEN_WELCOME_POPUP,SD.UI.GoalBar.Manager.firstTimeLoginWelcomePopup.bind(SD.UI.GoalBar.Manager));SD.Goals={};SD.IGoal={Events:{COMPLETED:'SD.IGoal.Events:COMPLETED',NOT_COMPLETED:'SD.IGoal.Events:NOT_COMPLETED',ENABLED:'SD.IGoal.Events:ENABLED',DISABLED:'SD.IGoal.Events:DISABLED',ACTIVATED:'SD.IGoal.Events:ACTIVATED',SHOW:'SD.IGoal.Events:SHOW',HIDE:'SD.IGoal.Events:HIDE',TOOLTIP_SHOW:'SD.IGoal.Events:TOOLTIP_SHOW',TOOLTIP_HIDE:'SD.IGoal.Events:TOOLTIP_HIDE'}};SD.GoalTemplate='<div id="#{id}" class="goal-item #{baseClass}" style="display:#{display}">'+'<div class="base-layer goal-icon-layer"></div>'+'<div class="completed-layer goal-icon-layer"></div>'+'<div class="order-indicator"></div>'+'<div class="goal-tooltip">'+'<div class="goal-tooltip-beak"></div>'+'<nobr class="goal-tooltip-content"><span class="next-goal" style="display:none">Next Step: </span>#{tooltip}</nobr>'+'</div>'+'</div>';SD.Goal=Class.create({template:SD.GoalTemplate,initialize:function(options){this.options=options;this.id=options.id;this.domHolder=$(this.options.domHolder);this.isEnabled=this.options.enabled;this.state=this.options.completed?'completed':'not_completed';this.isVisible=false;},setup:function(){this.dom=$(this.id);this.domTooltip=this.dom.select('.goal-tooltip')[0];this.domTooltipContent=this.dom.select('.goal-tooltip-content')[0];this.domNextGoal=this.dom.select('.next-goal')[0];if(this.domTooltip&&!this.options.tooltip){this.domTooltip.addClassName('hide-tooltip');}
this.domTooltip&&this.dom.observe('mouseenter',function(){this.isEnabled&&this.showTooltip();}.bind(this));this.domTooltip&&this.dom.observe('mouseleave',function(){this.hideTooltip();}.bind(this));if(!this.options.enabled){this.disable();}
if(this.options.completed){this.setToCompleted();}
this.dom.observe('click',this.onClick.bind(this));},onClick:function(){if(this.state=="completed"){SD.ExperimentManager.recordOutput('Goals_ClickedOnAlreadyCompletedGoal',1,1);}else{var type=this.options.type;if(type){var sects=type.split('.');var name=sects[sects.length-1];SD.ExperimentManager.recordOutput('Goals_'+name+'_Click',1,1);}}
if(!this.isEnabled||this.state=="completed")
return;this.start();},render:function(options){options=options||{mode:'visible'};SD.Utils.Populator.append({domRoot:this.domHolder,template:this.template,data:{id:this.id,order:this.options.order,tooltip:this.options.tooltip||'',baseClass:this.baseClassName,display:options.mode=='visible'?'block':'none'}});this.isVisible=(options.mode=='visible');},show:function(callback){if(this.isVisible==true)return;this.isVisible=true;Effect.BlindDown(this.dom,{afterFinish:function(){callback&&callback();SD.Event.fire(this,SD.IGoal.Events.SHOW);}.bind(this)});},hide:function(callback){if(this.isVisible==false)return;this.isVisible=false;Effect.BlindUp(this.dom,{afterFinish:function(){callback&&callback();SD.Event.fire(this,SD.IGoal.Events.HIDE);}.bind(this)});},showTooltip:function(){this.domTooltip&&this.dom.addClassName('mod-tooltip');SD.Event.fire(this,SD.IGoal.Events.TOOLTIP_SHOW);},hideTooltip:function(){this.domTooltip&&this.dom.removeClassName('mod-tooltip');this.domNextGoal&&this.domNextGoal.hide();SD.Event.fire(this,SD.IGoal.Events.TOOLTIP_HIDE);},switchToNormalTooltip:function(){if(this.domTooltipContent){this.domTooltipContent.innerHTML=this.options.tooltip;}},switchToCompletedTooltip:function(){if(this.domTooltipContent&&this.options.tooltipCompleted){this.domTooltipContent.innerHTML=this.options.tooltipCompleted;}},enable:function(){this.isEnabled=true;this.dom.removeClassName('mod-disabled');SD.Event.fire(this,SD.IGoal.Events.ENABLED);},disable:function(){this.isEnabled=false;this.dom.addClassName('mod-disabled');SD.Event.fire(this,SD.IGoal.Events.DISABLED);},setToCompleted:function(){this.state='completed';this.dom.removeClassName(this.baseClassName);this.dom.addClassName(this.completedClassName);this.dom.addClassName('mod-completed');this.switchToCompletedTooltip();SD.Event.fire(this,SD.IGoal.Events.COMPLETED);},setToNotCompleted:function(){this.state='not_completed';this.dom.removeClassName(this.completedClassName);this.dom.removeClassName('mod-completed');this.dom.addClassName(this.baseClassName);this.switchToNormalTooltip();SD.Event.fire(this,SD.IGoal.Events.NOT_COMPLETED);},destroy:function(){this.dom.stopObserving();},showNextGoalTag:function(){if(!this.domNextGoal)
return;this.domNextGoal.show();this.nextGoalTimer&&clearTimeout(this.nextGoalTimer);this.nextGoalTimer=setTimeout(function(){this.hideNextGoalTag();}.bind(this),10000);this.showTooltip();},hideNextGoalTag:function(){if(!this.domNextGoal)
return;this.nextGoalTimer&&clearTimeout(this.nextGoalTimer);this.domNextGoal.hide();this.hideTooltip();},start:function(){}});SD.Goals.CreateAccount=Class.create(SD.Goal,{initialize:function($super,options){this.baseClassName='goal-create-account';this.completedClassName='goal-create-account-completed';$super(options);}});SD.Goals.PhotoUpload=Class.create(SD.Goal,{initialize:function($super,options){this.baseClassName='goal-upload-photo';this.completedClassName='goal-upload-photo-completed';$super(options);},setup:function($super){$super();SD.Event.observe(null,SD.ClientUpdater.Events.UPDATE_PROFILE_THUMB,function(e){if(SD.Model.getMyself().has_photo&&this.state!="completed"){this.setToCompleted();}else if(!SD.Model.getMyself().has_photo&&this.state!="not_completed"){this.setToNotCompleted();}}.bind(this));},start:function(){SD.UIController.uploadPhotoPopup({sourceType:SD.UIController.PopupSourceTypes.GOAL_PHOTO_UPLOAD});SD.Event.fire(this,SD.IGoal.Events.ACTIVATED);}});SD.Goals.SMS=Class.create(SD.Goal,{initialize:function($super,options){this.baseClassName='goal-sms';this.completedClassName='goal-sms-completed';$super(options);},setup:function($super){$super();SD.Event.observe(null,SD.UIController.Events.PHONE_VERIFIED,function(e){if(SD.Model.getMyself().has_phone&&this.state!="completed"){this.setToCompleted();}}.bind(this));},start:function(){SD.UIController.phoneNumberPopup({sourceType:SD.UIController.PopupSourceTypes.GOAL_SMS});SD.Event.fire(this,SD.IGoal.Events.ACTIVATED);}});SD.Goals.CompleteProfile=Class.create(SD.Goal,{_pe:null,initialize:function($super,options){this.baseClassName='goal-complete-profile';this.completedClassName='goal-complete-profile-completed';$super(options);},setup:function($super){$super();if(this.state=="not_completed"){this._pe=new PeriodicalExecuter(function(pe){if(SD.Model.getMyself().has_about_me){pe.stop();this.setToCompleted();this._pe=null;}}.bind(this),1);}},start:function(){SD.UIController.aboutMePopup({sourceType:SD.UIController.PopupSourceTypes.GOAL_MEMBER_INFO});SD.Event.fire(this,SD.IGoal.Events.ACTIVATED);}});SD.Goals.VerifyEmail=Class.create(SD.Goal,{_pe:null,initialize:function($super,options){this.baseClassName='goal-get-messages';this.completedClassName='goal-get-messages-completed';$super(options);},setup:function($super){$super();if(this.state=="not_completed"){this._pe=new PeriodicalExecuter(function(pe){if(!SD.Model.getMyself().has_bounced){pe.stop();this.setToCompleted();this._pe=null;}}.bind(this),3);}},start:function(){SD.UIController.emailVerificationPopup({sourceType:SD.UIController.PopupSourceTypes.GOAL_VERIFY_EMAIL});SD.Event.fire(this,SD.IGoal.Events.ACTIVATED);}});SD.Goals.SocialPower=Class.create(SD.Goal,{initialize:function($super,options){this.baseClassName='goal-social-power';this.completedClassName='goal-social-power-completed';$super(options);}});SD.Goals.IM=Class.create(SD.Goal,{initialize:function($super,options){this.baseClassName='goal-im';this.completedClassName='goal-im-completed';$super(options);},start:function(){SD.UIController.imPopup();SD.Event.fire(this,SD.IGoal.Events.ACTIVATED);}});SD.Goals.SpeedVerify=Class.create(SD.Goal,{initialize:function($super,options){this.baseClassName='goal-speedverify';this.completedClassName='goal-speedverify-completed';$super(options);},start:function(){SD.UIController.speedVerifyPopup();SD.Event.fire(this,SD.IGoal.Events.ACTIVATED);}});SD.Goals.Subscribe=Class.create(SD.Goal,{initialize:function($super,options){this.baseClassName='goal-subscribe';this.completedClassName='goal-subscribe-completed';$super(options);},start:function(){if(this.options.extraData.action){eval(this.options.extraData.action);}else{SD.UIController.upgradeMyself();}
SD.Event.fire(this,SD.IGoal.Events.ACTIVATED);}});SD.Goals.Reward=Class.create(SD.Goal,{initialize:function($super,options){this.baseClassName='goal-reward';this.completedClassName='goal-reward-completed';$super(options);},start:function(){SD.Event.fire(this,SD.IGoal.Events.ACTIVATED);}});SD.Goals.TutorialFlirt=Class.create(SD.Goal,{initialize:function($super,options){this.baseClassName='goal-flirt';this.completedClassName='goal-flirt-completed';$super(options);},recordCompletion:function(){SD.TutorialManager.recordCompletion(SD.TutorialCodes.TUTORIAL_FLIRTING);},_onEmailSent:function(){this.setToCompleted();this.recordCompletion();},_onTutorialStopped:function(e){this.tutorial=null;},start:function(){SD.Event.observeOnce(null,SD.TutorialManager.Events.TUTORIAL_STOPPED,this._onTutorialStopped.bind(this));SD.Event.observeOnce(null,SD.FlirtWink.Events.FLIRT,this._onEmailSent.bind(this));SD.Tutorials.FlirtBuilder.build((function(tutorial){this.tutorial=tutorial;SD.Event.fire(this,SD.IGoal.Events.ACTIVATED);}).bind(this));SD.ExperimentManager.recordOutput('Tutorial_Email_Click',1,1)}});SD.Goals.TutorialSearch=Class.create(SD.Goal,{initialize:function($super,options){this.baseClassName='goal-search';this.completedClassName='goal-search-completed';$super(options);},setup:function($super){$super();SD.Event.observeOnce(null,SD.TutorialManager.Events.TUTORIAL_STOPPED,this._onTutorialStopped.bind(this));},_onHashChanged:function(e){var filterCount=0;for(var key in SD.Nav.oHash){if(key.indexOf('s_member_info')!=-1){filterCount++;}}
if(filterCount>=3){var _this=this;setTimeout(function(){SD.Event.stopObserving(null,SD.Nav.Events.HASH_CHANGE,_this.boundHashChanged);},10);this.setToCompleted();this.recordCompletion();}},recordCompletion:function(){SD.TutorialManager.recordCompletion(SD.TutorialCodes.TUTORIAL_SEARCH);},_onTutorialStopped:function(e){this.tutorial=null;},start:function(){if(!this.isCompletionTrapSet){this.boundHashChanged=this._onHashChanged.bind(this);SD.Event.observe(null,SD.Nav.Events.HASH_CHANGE,this.boundHashChanged);}
this.isCompletionTrapSet=true;SD.Tutorials.SearchBuilder.build((function(tutorial){this.tutorial=tutorial;SD.Event.fire(this,SD.IGoal.Events.ACTIVATED);}).bind(this));SD.ExperimentManager.recordOutput('Tutorial_Search_Click',1,1)}});SD.Goals.TutorialDating=Class.create(SD.Goal,{initialize:function($super,options){this.baseClassName='goal-date';this.completedClassName='goal-date-completed';$super(options);},setup:function($super){$super();this._boundOnUpcomingDatesChanged=this._onUpcomingDatesChanged.bind(this);SD.Event.observe(null,SD.SpeedDateList.Events.UPCOMING_DATES_CHANGED,this._boundOnUpcomingDatesChanged);SD.Event.observeOnce(null,SD.TutorialManager.Events.TUTORIAL_STOPPED,this._onTutorialStopped.bind(this));SD.Event.observeOnce(null,SD.UserInitiatedDate.Events.USER_INITIATED_DATE,this._onStartDate.bind(this));},_onStartDate:function(){SD.UI.Date.allowFullDating=false;this.recordCompletion();this.setToCompleted();},recordCompletion:function(){SD.TutorialManager.recordCompletion(SD.TutorialCodes.TUTORIAL_DATING);},_onUpcomingDatesChanged:function(e){if(this.state!='completed'&&e.memo.count>0){this.show();SD.Event.stopObserving.bind(SD.Event,null,SD.SpeedDateList.Events.UPCOMING_DATES_CHANGED,this._boundOnUpcomingDatesChanged).defer();}},_onTutorialStopped:function(e){this.tutorial=null;},start:function(){if(!this.isEnabled||this.state=="completed"){this.hide();return;}
SD.Tutorials.DateBuilder.build((function(tutorial){this.tutorial=tutorial;SD.UI.Date.allowFullDating=true;SD.Event.fire(this,SD.IGoal.Events.ACTIVATED);}).bind(this));SD.ExperimentManager.recordOutput('Tutorial_Dating_Click',1,1);},destroy:function($super){SD.Event.stopObserving(this._boundOnUpcomingDatesChanged);$super();}});SD.GoalsCounter=Class.create({initialize:function(){this.dom=$('goal-footer');this.domCounterFg=$('goal-footer-fg');this.domCounterBg=$('goal-footer-bg');this.domGoalHolder=this.dom.select('.goal-footer-compl-wrapper').first();this.boundOnDocumentClick=this.onDocumentClick.bind(this);this.count=0;this.setup();},setup:function(){this.dom.observe('click',this.onClick.bind(this));this.dom.observe('mouseenter',this.onMouseOver.bind(this));this.dom.observe('mouseleave',this.onMouseOut.bind(this));if(Prototype.Browser.IE6){this.setupShim();}},setupShim:function(){this.domShim=$(document.createElement('IFRAME'));this.domGoalHolder.parentNode.insertBefore(this.domShim,this.domGoalHolder);this.domShim.addClassName('menu-iframe');this.domShim.style.zIndex=1;this.domShim.style.visibility='hidden';this.updateShim();},updateShim:function(){if(this.domShim){this.domShim.clonePosition(this.domGoalHolder);this.domShim.style.left='32px';}},setCount:function(c){this.count=Math.max(0,c);this.domCounterFg.update(c);this.domCounterBg.update(c);},incrementCount:function(){this.setCount(this.count+1);},decrementCount:function(){this.setCount(this.count-1);},addGoal:function(goal){if(this.hasGoal(goal)){return;}
this.domGoalHolder.insert(SD.CompletedGoalSmallTemplate.interpolate({id:goal.id+'-mini',className:goal.baseClassName+'-mini',text:goal.options.tooltip}));this.incrementCount();this.updateShim();},removeGoal:function(goal){if(!this.hasGoal(goal)){return;}
var domGoal=$(goal.id+'-mini');domGoal&&domGoal.parentNode.removeChild(domGoal);this.decrementCount();this.updateShim();},hasGoal:function(goal){return!!$(goal.id+'-mini');},onMouseOver:function(){this.dom.addClassName('goal-footer-over');},onMouseOut:function(){this.dom.removeClassName('goal-footer-over');},onClick:function(){if(this.dom.hasClassName('goal-footer-on')){this.dom.removeClassName('goal-footer-on');this.domShim&&(this.domShim.style.visibility='hidden');}else{this.dom.addClassName('goal-footer-on');document.observe('click',this.boundOnDocumentClick);this.domShim&&(this.domShim.style.visibility='');}},onDocumentClick:function(e){var target=e.target||e.srcElement;var parentEl=$('goal-footer');if(target.descendantOf(parentEl)||target==parentEl){return;}else{this.dom.removeClassName('goal-footer-on');this.domShim&&(this.domShim.style.visibility='hidden');document.stopObserving('click',this.boundOnDocumentClick);}}});
SD.UI=SD.UI||{};SD.UI.ChatObserverTemplates={connect_button:function(){return'<a sdType="fbchat-connect-toggle" class="fakebutton" rel="nofollow">'+'<span class="connecting fbchat-state">'+'<img style="border:none" src="'+SD.Config.imageDir+'fblike-ajax-loader.gif" alt="connecting"/>'+'Connecting...'+'</span>'+'<div class="connected fbchat-state">'+'<span>'+'Disconnect from Facebook Chat'+'</span>'+'</div>'+'<span class="disconnecting fbchat-state">'+'<img style="border:none" src="'+SD.Config.imageDir+'fblike-ajax-loader.gif" alt="disconnecting"/>'+'Disconnecting...'+'</span>'+'<div class="medium-button medium-fb disconnected  fbchat-state" style="margin-top: 15px; margin-left: 25px">'+'<span>'+'Connect to Facebook Chat'+'</span>'+'</div>'+'</a>'+'<br clear="all"/>';},frame:function(){return'';return'<div class="shareFriendContainer  chatObserverContainer" style="border:none; height:auto;">'+'<div class="list-header" style="font-size: 13px; font-weight: bold;">Select one friend to give you feedback on  this chat!</div>'+
SD.UI.ChatObserverTemplates.connect_button()+'<div class="list-content lib-content"></div>'+'</div>'}};SD.UI.ChatObserverItemViewTemplates={frame:'<div class="lib-list-item-dom">'+'<a sdUid="#{uid}" class="friend enabled lib-share-chat">'+'<img class="friend-image" src="#{small_pic_url}" width="50" height="50"><br/>'+'<span class="friend-name">#{username}</span><br />'+'<span class="status-sending now">Sending...</span>'+'<span class="status-sent now">Sent!</span>'+'</a>'+'</div>'};SD.UI.ChatObserverItemView=Class.create(SD.UI.Component,{templateSet:SD.UI.ChatObserverItemViewTemplates,initTemplate:SD.UI.ChatObserverItemViewTemplates.frame,dataFilter:function(user){this.rawData=user;var sCityName=user.city_name||'';return{uid:user.uid,username:user.username.truncate(15),small_pic_url:user.square_image_url};},parseLibrary:{'lib-list-item-dom':function(el){this.dom=el;},'lib-share-chat':function(el,domRoot){el.onclick=this.onItemClick.bind(this);}},onItemClick:function(){var friendUid=this.data.uid;if(friendUid&&this.options&&this.options.onClick){this.options.onClick();}},setNoneSelected:function(){this.dom&&this.dom.removeClassName("other-selected");this.dom&&this.dom.removeClassName("selected");},setOtherSelected:function(){this.dom&&this.dom.addClassName("other-selected");this.dom&&this.dom.removeClassName("selected");},setSelected:function(){this.dom&&this.dom.addClassName("selected");this.dom&&this.dom.removeClassName("other-selected");},selected:function(){return this.dom&&this.dom.hasClassName("selected");},onCloseItemClick:Prototype.emptyFunction,destroy:function($super){this.dom&&this.dom.parentNode.removeChild(this.dom);this.dom=null;$super();},Events:{SELECT:"SD.UI.ChatObserverItemView.Events:select"}});SD.UI.ChatObserverList=Class.create(SD.UI.Container,{templateSet:SD.UI.ChatObserverTemplates,initTemplate:SD.UI.ChatObserverTemplates.frame,_other:null,_selectedItem:null,initialize:function($super,options){$super(options);this._other=options.other;SD.UI.FBChatToggles.updateButtons.bind(SD.UI.FBChatToggles).delay(1);},getItemStore:function(){return this.itemStore?this.itemStore:new SD.Data.UniqOrderedStore({idField:'id',comparator:this._comparator.bind(this)});},addExistingRecords:function(){var records=SD.FBChat.friendStore.getRecords();records&&records.each(function(record,ind){this._addToList(record,ind);}.bind(this));},setup:function(){this.addExistingRecords.bind(this).defer();SD.Event.observe(SD.FBChat.friendStore,SD.Data.IStore.Events.RECORD_ADDED,this.onBuddyAdd.bind(this));SD.Event.observe(SD.FBChat.friendStore,SD.Data.IStore.Events.RECORD_REMOVED,this.onBuddyRemove.bind(this));SD.Event.observe(this.itemStore,SD.Data.IStore.Events.RECORD_ADDED,this._observerOnItemAdded.bind(this));SD.Event.observe(this.itemStore,SD.Data.IStore.Events.RECORD_REMOVED,this._observerOnItemRemoved.bind(this));},_comparator:function(itemA,itemB){var a=itemA.data.username.toLowerCase();var b=itemB.data.username.toLowerCase();return(a<b)?1:(a==b?0:-1);},onBuddyAdd:function(e){this._addToList(e.memo.record,e.memo.position);},onBuddyRemove:function(e){this._removeFromList(e.memo.record.uid);},_onItemRemove:function(item){item.destroy();},_observerOnItemAdded:function(e){this._insertItemIntoDOM(e.memo.record,e.memo.position);},_observerOnItemRemoved:function(e){this._removeFromList(e.memo.uid);},_addToList:function(record){if(this.hasItem(record.uid)){return;}
var item=new SD.UI.ChatObserverItemView({id:record.uid,data:record,domHolder:document.createElement("div"),otherId:this._other.uid,onClick:function(){var prevent=false;if(this.options.onSelect){var allow=this.options.onSelect({friend:record});if(allow===false){prevent=true;}}
if(!prevent){if(this._selectedItem){this._selectedItem.setOtherSelected();}
this._selectedItem=item;this._selectedItem.setSelected();this._unselectOthers();}}.bind(this)});item.domHolder=this.domContent;this.addItem(item);if(this._selectedItem){if(this._selectedItem.id==item.id){this._selectedItem=item;item.setSelected();}else{item.setOtherSelected();}}
return item;},unselectAll:function(){this._selectedItem=null;this.getItems().each(function(item){item.setNoneSelected();});},_unselectOthers:function(){this.getItems().each(function(item){if(!item.selected()){item.setOtherSelected();}});},_insertItemIntoDOM:function(item,position){var nextItem=this.itemStore.getAt(position+1)||null;this.domContent.insertBefore(item.dom,nextItem&&nextItem.dom);},_removeFromList:function(itemId){if(this.hasItem(itemId)){this.removeItem(itemId);}},parseLibrary:{'lib-buddylist':function(el,domRoot){this.domBuddies=el;},'lib-content':function(el,domRoot){this.domContent=el;this.adjustContentHeight();}},show:function(){this.dom.show();this.isVisible=true;},hide:function(){this.dom.hide();this.isVisible=false;},adjustContentHeight:function(){},onResize:function(){this.adjustContentHeight();}});SD.UI.ChatObserverList.Events={BUDDY_SELECTED:'SD.UI.ChatObserverList.Events:BUDDY_SELECTED'};
SD.FbWingman={_userFriendHash:{},_friendUserHash:{},_lastForwardedMsgTimestamps:{},_me:null,_outputControl:{},init:function(){this._me=SD.Model.getMyself();SD.Event.observe(null,SD.ChatMsgListener.Events.NEW_MESSAGE,this._onMessageSent.bind(this));SD.Event.observe(null,this.Events.START_OBSERVING,this._onStartObserving.bind(this));SD.Event.observe(null,this.Events.STOP_OBSERVING,this._onStopObserving.bind(this));SD.Event.observe(null,SD.Chat.Events.PANEL_CLOSED,this._onPanelClosed.bind(this));SD.Event.observe(null,SD.FBXMPP.Events.LOGOUT,this._onFbXMPPLogout.bind(this));SD.Event.observe(null,SD.User.Events.USER_ONLINE,this._onUserOnline.bind(this));SD.Event.observe(null,SD.User.Events.USER_OFFLINE,this._onUserOffline.bind(this));},getObserver:function(user){return this._userFriendHash[user.uid];},getObservedUser:function(friend){return this._friendUserHash[friend.uid];},_onPanelClosed:function(e){var user=e.memo.user;if(this._userFriendHash[user.uid]||this._friendUserHash[user.uid]){this.removeFriendFromObserving(user);}
if(this._friendUserHash[user.uid]){var match=this._friendUserHash[user.uid];this.removeFriendFromObserving(match);}},_onMessageSent:function(e){var sender=e.memo.sender;var receiver=e.memo.receiver;if(this._userFriendHash[sender.uid]){var friend=this._userFriendHash[sender.uid];SD.ChatMsgListener.sendMessage(friend,this.TEMPLATES.FB.RECEIVED_MSG.interpolate(this._createInterpolateParams({friend:friend,user:sender,me:this._me,text:e.memo.text})),true);this._updateLastForwardedMsg(friend,sender);}
if(this._userFriendHash[receiver.uid]){var friend=this._userFriendHash[receiver.uid];SD.ChatMsgListener.sendMessage(friend,this.TEMPLATES.FB.SENT_MSG.interpolate(this._createInterpolateParams({friend:friend,user:receiver,me:this._me,text:e.memo.text})),true);this._updateLastForwardedMsg(friend,receiver);}
if(!e.memo.dontBlink&&this._friendUserHash[sender.uid]){var outputKey="t"+sender.uid+"-"+this._friendUserHash[sender.uid].uid+"-in";if(!this._outputControl[outputKey]){this._outputControl[outputKey]=true;SD.ExperimentManager.recordOutput('UserReceivedAnAdvice',1,1);}}
if(!e.memo.dontBlink&&this._friendUserHash[receiver.uid]){var outputKey="t"+receiver.uid+"-"+this._friendUserHash[receiver.uid].uid+"-out";if(!this._outputControl[outputKey]){this._outputControl[outputKey]=true;SD.ExperimentManager.recordOutput('UserTalkedToTheAdvisor',1,1);}}},_updateLastForwardedMsg:function(friend,user){if(!this._lastForwardedMsgTimestamps[friend.uid]){this._lastForwardedMsgTimestamps[friend.uid]={};}
this._lastForwardedMsgTimestamps[friend.uid][user.uid]=Date.now()+500;},_getLastForwardedMsgTime:function(friend,user){if(!this._lastForwardedMsgTimestamps[friend.uid]){return 0;}
if(!this._lastForwardedMsgTimestamps[friend.uid][user.uid]){return 0;}
return this._lastForwardedMsgTimestamps[friend.uid][user.uid];},addFriendAsObserver:function(user,friend){if(this._userFriendHash[user.uid]){var observer=this._userFriendHash[user.uid];if(observer.uid==friend.uid){return;}
alert(this.TEMPLATES.ERROR.OBSERVER_EXISTS.interpolate(this._createInterpolateParams({friend:observer,user:user,me:this._me})));return false;}
if(this._friendUserHash[friend.uid]){var match=this._friendUserHash[friend.uid];if(match.uid==user.uid){return;}
alert(this.TEMPLATES.ERROR.ALREADY_OBSERVING_ANOTHER.interpolate(this._createInterpolateParams({friend:friend,user:match,me:this._me})));return false;}
this._userFriendHash[user.uid]=friend;this._friendUserHash[friend.uid]=user;SD.Event.fire(null,this.Events.START_OBSERVING,{friend:friend,user:user});return true;},removeFriendFromObserving:function(user){var friend=this._userFriendHash[user.uid];if(!friend){friend=user;user=this._friendUserHash[friend.uid];}
if(!friend||!user){return;}
SD.ExperimentManager.recordOutput('RemovedFacebookFriendFromObservingTheChat',1,1);delete this._userFriendHash[user.uid];delete this._friendUserHash[friend.uid];SD.Event.fire(null,this.Events.STOP_OBSERVING,{user:user,friend:friend});},_createInterpolateParams:function(data){var ret={};var attachWithPrefix=function(prefix){for(var i in data[prefix]){if(data[prefix].hasOwnProperty(i)){ret[prefix+"_"+i]=data[prefix][i];}}};attachWithPrefix("me");attachWithPrefix("friend");attachWithPrefix("user");delete data["me"];delete data["friend"];delete data["user"];for(var i in data){if(data.hasOwnProperty(i)){ret[i]=data[i];}}
return ret;},_onStartObserving:function(e){SD.ExperimentManager.recordOutput('InvitedFacebookFriendToObserveChat',1,1);SD.Chat.chatWithUser(e.memo.friend,true);(function(){var params=this._createInterpolateParams({friend:e.memo.friend,me:this._me,user:e.memo.user});if(!this._getLastForwardedMsgTime(e.memo.friend,e.memo.user)){SD.ChatMsgListener.sendMessage(e.memo.friend,this.TEMPLATES.FB.GREETINGS.interpolate(params),true);}else{SD.ChatMsgListener.sendMessage(e.memo.friend,this.TEMPLATES.FB.GREETINGS_READD.interpolate(params),true);}
var history=SD.Chat.getHistory(e.memo.user);if(history&&history.length){var sentHistory=false;var lastForwarded=this._getLastForwardedMsgTime(e.memo.friend,e.memo.user);if(lastForwarded==0){SD.ChatMsgListener.sendMessage(e.memo.friend,this.TEMPLATES.FB.HISTORY_TITLE.interpolate(params),true);sentHistory=true;}
history.each(function(msg){if(msg.time<=lastForwarded){return;}
if(!sentHistory){SD.ChatMsgListener.sendMessage(e.memo.friend,this.TEMPLATES.FB.HISTORY_READD_TITLE.interpolate(params),true);sentHistory=true;}
var template=msg.uid==this._me.uid?this.TEMPLATES.FB.SENT_MSG:this.TEMPLATES.FB.RECEIVED_MSG;params.text=msg.text;SD.ChatMsgListener.sendMessage(e.memo.friend,template.interpolate(params),true);}.bind(this));}}).bind(this).delay(1);this.updateObserverLinks(e.memo.friend,e.memo.user);SD.RPC.call(e.memo.user,"SD.Chat.__fbWingmanMsg",{msg:this.TEMPLATES.OTHER.SHARE_NOTICE.interpolate(this._createInterpolateParams({friend:e.memo.friend,me:this._me,user:e.memo.user}))});},_onStopObserving:function(e){if(e.memo.friend.online){(function(){SD.ChatMsgListener.sendMessage(e.memo.friend,this.TEMPLATES.FB.CANCEL.interpolate(this._createInterpolateParams({friend:e.memo.friend,me:this._me,user:e.memo.user})),true);}).bind(this).delay(1);}
this.updateObserverLinks(e.memo.friend,e.memo.user);SD.RPC.call(e.memo.user,"SD.Chat.__fbWingmanMsg",{msg:this.TEMPLATES.OTHER.STOP_SHARE_NOTICE.interpolate(this._createInterpolateParams({friend:e.memo.friend,me:this._me,user:e.memo.user}))});},updateObserverLinks:function(friend,user){user=user||this._friendUserHash[friend.uid];var template=user?this.TEMPLATES.UI.CHAT_OBSERVER_INFO:this.TEMPLATES.UI.CHAT_OBSERVER_NONE;var divs=$$("[sdType=chat-observer][sdFriendId="+friend.uid+"]");divs.each(function(div){SD.Utils.Populator.populate({domRoot:div,template:template,data:this._createInterpolateParams({me:this._me,friend:friend,user:user})});}.bind(this));},_onFbXMPPLogout:function(){for(var friendId in this._friendUserHash){if(this._friendUserHash.hasOwnProperty(friendId)){var user=this._friendUserHash[friendId];this.removeFriendFromObserving(user);}}},_onUserOffline:function(e){if(this._friendUserHash[e.memo.user.uid]){var friend=e.memo.user;var user=this._friendUserHash[friend.uid];this.removeFriendFromObserving(user);SD.Chat.displayInfoMessage(user,this.TEMPLATES.UI.FB_FRIEND_OFFLINE.interpolate(this._createInterpolateParams({me:this._me,friend:friend,user:user})));}else if(this._userFriendHash[e.memo.user.uid]){var user=e.memo.user;var friend=this._userFriendHash[user.uid];SD.ChatMsgListener.sendMessage(friend,this.TEMPLATES.FB.USER_WENT_OFFLINE.interpolate(this._createInterpolateParams({friend:friend,user:user,me:this._me})),true);}},_onUserOnline:function(e){var user=e.memo.user;if(this._userFriendHash[user.uid]){var friend=this._userFriendHash[user.uid];SD.ChatMsgListener.sendMessage(friend,this.TEMPLATES.FB.USER_CAME_ONLINE.interpolate(this._createInterpolateParams({friend:friend,user:user,me:this._me})),true);}},Events:{START_OBSERVING:"SD.FbWingman.Events:START_OBSERVING",STOP_OBSERVING:"SD.FbWingman.Events:STOP_OBSERVING"},TEMPLATES:{FB:{GREETINGS:"#{me_name} is chatting with #{user_username} on www.SpeedDate.com and would like your opinion."+"\n\nYou can send comments to #{me_name}, they wont be shown to #{user_username}."+"\n\n#{user_username}'s profile #{user_short_public_url}",CANCEL:"#{me_name} has closed the chat.  Thank you for helping #{me_name}!",GREETINGS_READD:"#{me_name} added you back to the chat with #{user_username}.",SENT_MSG:"To #{user_username}:\n #{text}",RECEIVED_MSG:"From #{user_username}:\n #{text}",HISTORY_TITLE:"Here is the conversation history between #{me_name} and #{user_username}",HISTORY_READD_TITLE:"Here is the conversation that you have missed:",USER_WENT_OFFLINE:"#{user_username} went offline",USER_CAME_ONLINE:"#{user_username} came online"},ERROR:{OBSERVER_EXISTS:"#{friend_username} is already helping in your chat with #{user_username}. You cannot add more than one friend to the same chat.",ALREADY_OBSERVING_ANOTHER:"#{friend_username} is already helping in your chat with #{user_username}. Please invite another friend."},UI:{CHAT_OBSERVER_INFO:'<div style="padding: 5px; margin: 5px 4px; background-color: white; border: #bbb; font-size: 12px"><span sdType="chat" class="fake-link" sdUid="#{user_uid}"><img src="#{user_square_image_url}"  width="40" style="float:left; padding-right: 5px"><span style="color: #333"><b>#{friend_username}</b> is observing your chat with</span><b> #{user_username}</b></span><div class="clear"></div></div>',CHAT_OBSERVER_NONE:"",FB_FRIEND_OFFLINE:"#{friend_name} went offline."},OTHER:{SHARE_NOTICE:"#{me_username} asked a friend's feedback on this chat.",STOP_SHARE_NOTICE:"#{me_username} stopped receiving feedback from their friend on this chat."}}};
SD.CartAbandonment={offerExpiration:0,process:function(){return;var url="/index.php?page=ajax&action=cart_abandonment";var params={unixtime_client:SD.CartAbandonment.getClientUnixTime()};new Ajax.Request(url,{method:'post',parameters:params,onSuccess:function(result){if(result.responseJSON.result&&result.responseJSON.data.displayOffer){var offerExpiration=result.responseJSON.data.offerExpiration;SD.CartAbandonment.offerExpiration=offerExpiration;if(result.responseJSON.data.displayOfferPopup){SD.CartAbandonment._openCartAbandonmentPopup(offerExpiration);}
SD.CartAbandonment._updateTimer(offerExpiration);}}});},getClientUnixTime:function(){return Math.floor(new Date().getTime()/1000);},_updateTimer:function(unixTimeExp){var counterContainer=$('sub-button-counter-container');if(!counterContainer){return;}
if(counterContainer.visible()){return;}
counterContainer.show();var fn=function(){var unixTimeNow=Math.floor(new Date().getTime()/1000);if(unixTimeExp>unixTimeNow){var expires=unixTimeExp-unixTimeNow;var expiresHumanReadable=Math.floor(expires%60);expiresHumanReadable=(expiresHumanReadable<10)?"0"+expiresHumanReadable.toString():expiresHumanReadable.toString();expiresHumanReadable=Math.floor(expires/60)+":"
+expiresHumanReadable;$('sub-button-counter').update(expiresHumanReadable);var popupTimer=$('cartabandonment-timer-offer');if(popupTimer){popupTimer.update(expiresHumanReadable);}
setTimeout(fn,1000);}else{$('sub-button-counter-container').hide();}};setTimeout(fn,1000);},_openCartAbandonmentPopup:function(unixTimeExp){winConfig={position:'absolute',resizable:false,title:'',content:'<p class="sd-window-msg">Loading...</p>',width:435,height:380,draggable:false,top:50,template:SD.Window.newStyle,className:"generic-popup-container",groupId:'group4',loader:{onParseElements:{'.accept-offer':function(el,domRoot){el.observe('click',function(){win.close();SD.UIController.upgradeMyself();});}}},bindToWindowScroll:false,enableYAdjustOnResize:false};var url="/index.php?page=cartabandonment&action=index&unixtime_client="
+SD.CartAbandonment.getClientUnixTime();var win=SD.UIController.standardPopup(winConfig).open().load(url);return win;}};
SD.Playspan={openPlayspanPopup:function(subscriptionPlanId,paymentMethod){var url="/index.php?page=playspan&action=index&subscriptionPlanId="
+subscriptionPlanId+"&paymentMethod="+paymentMethod;var iframeName="iframe-playspan";var content='<iframe id="'+iframeName+'" name="'+iframeName+'" '
+'src="'+url+'" frameborder="0" width="710" height="425" '
+'marginwidth="0" marginheight="0" hspace="0" vspace="0"></iframe>';var winConfig={position:'absolute',resizable:false,title:'',content:content,width:691,height:425,draggable:false,top:50,template:SD.Window.newStyle,className:"generic-popup-container",groupId:'group4',closable:false,onAfterClose:function(e){if(e){}},bindToWindowScroll:false,enableYAdjustOnResize:false};var win=SD.UIController.standardPopup(winConfig).open();return win;}};
SD.UIController={displayGift:true,displayReportImage:true,tabBlinkingEnabled:true,titleOptionsEnabled:true,hasFocus:true,appState:null,speeddateActive:true,welcomeDisplayed:true,platform_id:1,speedVerifyShownCounter:null,phoneNumberPopupCounter:null,numberOfDates:0,canSaveFilterGuard:true,initialize:function(options){this.options=options||{};this.speedVerifyShownCounter=new SD.Cookie.CounterWithTimeout("speedVerifyPopup",24*60);this.facebookShareShownCounter=new SD.Cookie.CounterWithTimeout("facebookSharePopup",24*60);this.phoneNumberPopupCounter=new SD.Cookie.CounterWithTimeout("phoneNumberPopup",24*60);this.speedWinkShownCounter=new SD.Cookie.CounterWithTimeout("speedWinkPopup",24*60);this.friendTreeShownCounter=new SD.Cookie.CounterWithTimeout("friendTreePopup",24*60*3);this.newYearCardShownCounter=new SD.Cookie.CounterWithTimeout("newYearCardPopup",24*60*3);this.valentineCardShownCounter=new SD.Cookie.CounterWithTimeout("valentineCardPopup",24*60*3);this.valentineCardBlocker=new SD.Cookie.PopupBlocker("valentine_card",30);$('initial-guard')&&$('initial-guard').fade();$('sd-message')&&$('sd-message').hide();SD.Event.observe(null,SD.UserFilters.UI.Events.START_SPEEDDATING,this.onStartDating.bind(this));SD.Event.observe(null,SD.UserFilters.UI.Events.PAUSE_SPEEDDATING,this.onPauseDating.bind(this));SD.Event.observe(null,SD.Date.Events.START_DATE,this.onStartDate.bind(this));SD.Event.observe(null,SD.User.Events.DATE_RESULT_FETCHED,this.onDateResultFetched.bind(this));SD.Event.observe(null,SD.UIController.Events.PHOTO_UPLOADED,this.onPhotoUpload.bind(this));SD.Event.observe(null,SD.UIController.Events.VIEW_PROFILE_REQUESTED,function(event){SD.ProfileViewer.UI.view(event.memo.user.uid);});SD.Event.observe(null,SD.UIController.Events.SEND_FLIRT_REQUESTED,function(event){SD.NavUtils.setLocation(SD.NavUtils.link('messages','flirt',{id:event.memo.user.uid}));});SD.Event.observe(null,SD.UIController.Events.BLOCK_BUDDY_REQUESTED,function(event){SD.User.fetch(event.memo.user,function(){if(confirm("Are you sure you want to block "+event.memo.user.username+"?")){SD.Event.fire(null,SD.BuddyList.Events.USER_BLOCK_CONFIRMED,{user:event.memo.user});SD.NavUtils.setLocation(SD.NavUtils.link('profile','block',{buddy_id:event.memo.user.uid}));}});});SD.Event.observe(null,SD.UIController.Events.REPORT_USER_REQUESTED,function(event){SD.NavUtils.setLocation(SD.NavUtils.link('messages','report',{id:event.memo.user.uid}));});SD.Event.observe(null,SD.UIController.Events.REPORT_USER_REQUESTED,function(event){SD.NavUtils.setLocation(SD.NavUtils.link('messages','report',{id:event.memo.user.uid}));});SD.Event.observe(null,SD.UIController.Events.SWITCHED_TO_SPEEDDATE,this.onSwitchedToSpeeddate.bind(this));SD.Event.observe(null,SD.UIController.Events.SWITCHED_TO_OTHER_TABS,this.onSwitchedToOtherTabs.bind(this));SD.Event.observe(null,SD.UIController.Events.BALANCE_UPDATED,this.onBalanceUpdated.bind(this));if(!SD.DisabledFeatures.addBuddiesButton){SD.Event.observe(null,SD.UIController.Events.ADD_BUDDIES_REQUESTED,this.onAddBuddiesRequested.bind(this));}
SD.Favicon.defaultTitle="SpeedDate.com";SD.Favicon.defaultIcon="favicon.ico";SD.Favicon.setTitle("");!this.userInfoMouseOverOutTrigger(function(){return true})&&SD.UIController.disableSubBadges();SD.Event.observe(null,SD.UIController.Events.SUBSCRIPTION_PAUSED,this.onSubscriptionPaused.bind(this));SD.Event.observe(null,SD.UIController.Events.SUBSCRIPTION_REACTIVATED,this.onSubscriptionReactivated.bind(this));!SD.Config.isProduction&&SD.UIController.startConsole();},initAds:function(){function updateBanner(bannerId){if(!frames[bannerId]){return;}
var href=frames[bannerId].location.href;var root=href.split("?")[0];frames[bannerId].location.replace(root+"?"+Date.now());}
SD.Event.observe(null,SD.Nav.Events.HASH_CHANGE,function(){updateBanner('topBarGoogleAds');updateBanner('towerGoogleAds');updateBanner('bottomGoogleAds');});},canSaveFilterState:function(){return this.canSaveFilterGuard;},onSubscriptionPaused:function(){$('sub-button-text').update("Reactivate &raquo;");$('sub-button').show();var domButAction=$('sub-button').select('a').first();domButAction.href='javascript:void(SD.UIController.reActivateAccount())';},onSubscriptionReactivated:function(){$('sub-button').hide();$('sub-button-text').update("");var domButAction=$('sub-button').select('a').first();domButAction.href='javascript:void(0)';},reActivateAccount:function(){if(SD.Nav.oHash.page=='profile'&&SD.Nav.oHash.action=='my_account'){SD.MyAccount.focusAndActivateAccountSettingsMenuItem('cancel-account-settings');}else{SD.Event.observeOnce(null,SD.Nav.Events.CONTENT_LOADED,function(){SD.MyAccount.focusAndActivateAccountSettingsMenuItem('cancel-account-settings');});SD.NavUtils.goTo('profile','my_account');}},onPhotoUpload:function(event){if($('user_profile_img_more')){$('user_profile_img_more').src=event.memo.photoUrl;}
SD.MyProfile.updateProfilePictureView(event.memo.photoBigUrl);SD.Model.getMyself().has_photo=!!event.memo.hasPhoto;SD.ClientUpdater.updateProfileThumb(event.memo.photoUrl);$$(".popup-banner-block").invoke("hide");SD.UIController.userInfoMouseOverOutTrigger(SD.UIController.enableSubBadges);},onProfileInfoUpdated:function(event){if(event.memo.invalidateProfileSection!==0){SD.Nav.invalidate("profile");}
SD.ClientUpdater.updateProfileInfo(event.memo);},onStartDating:function(event){this.welcomeDisplayed=false;},onStartDate:function(event){SD.Date.popupForDate(event.memo.otherUser,event.memo);if(this.tabBlinkingEnabled){if(!this.windowIsActive()){SD.Favicon.animateTitle(["Date found!","with "+event.memo.otherUser.username],1000);}}},onDateResultFetched:function(e){},onFlirtsSought:function(event){SD.NavUtils.setLocation(SD.NavUtils.link('messages','inbox'));},onAddBuddiesRequested:function(event){SD.NavUtils.setLocation(SD.NavUtils.link('invite','invite'));},userUnblockConfirmed:function(uid,username){if(confirm('Are you sure you want to unblock '+username+'?')){SD.Event.fire(null,SD.BuddyList.Events.USER_UNBLOCK_CONFIRMED,{user:{uid:uid,username:username}});return true;}
return false;},onSwitchedToSpeeddate:function(event){},onSwitchedToOtherTabs:function(event){},onBalanceUpdated:function(event){$('balance-field').innerHTML=event.memo.newBalance;},getSubViewData:function(options){options=options||{};var tc=options.tc||SD.TrackingCodes.trigger.banner.right_top_green_button._value;var tobj=options.tobj||SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.UPGRADE_BUTTON_DATING_CONTROLS);var PREMIUM='premium';var SUBSCRIBE='subscribe';var RESUBSCRIBE='resubscribe';var REACTIVATE='reactivate';var MODE_ONE_CLICK='one_click';var MODE_NOT_ACTIVE='not_active';var status=SD.Model.subStatus.status;var mode=SD.Model.subStatus.mode;var params=SD.Model.subStatus.params;var text='Premium';var action=Prototype.emptyFunction;if(status!=PREMIUM){if(status==REACTIVATE){text='Reactivate &raquo;';action=this.reActivateAccount.bind(this);}else if(status==RESUBSCRIBE){text='Resubscribe &raquo;';action=this.resubscribe.bind(this);}else if(status==SUBSCRIBE){text='Subscribe &raquo;';if(mode==MODE_ONE_CLICK){action=this.oneClickSubscriptionPopup.bind(this,'','',('length'in params)?'':$H(params).toQueryString());}else{action=this.upgradeMyself.bind(this,{tc:tc,tobj:tobj});}}}else if(status==RESUBSCRIBE&&mode==MODE_NOT_ACTIVE){text='Resubscribe &raquo;';action=this.resubscribe.bind(this);}
return{text:text,action:action};},needsToUpgrade:function(myself,user){if(myself.is_premium){return false;}else{return!user.relation.permissions.can_flirt;}},upgradeMyselfFor:function(uid){this.upgradeMyself({ti:uid});},upgradeMyself:function(params,dontCheckSegment,usePreviousParams,continuationCallback){var me=SD.Model.getMyself();if(me.is_premium){SD.warn('Already a premium user.');continuationCallback&&continuationCallback();return;}
if(me.shouldSeeFreeSubscriptionPromoPopup){this.freeSubscriptionPromoPopup();return;}
var originalParams=params;if(!params&&usePreviousParams){params=this._previousUpgradeParams;}
this._previousUpgradeParams=params||{};var tc=(params&&params.tc)||0;if(params){params="&"+$H(params).toQueryString();}else{params="";}
if(!me.is_premium){var excludedTrackingCodes=[SD.TrackingCodes.trigger.banner.right_top_green_button._value];if(SD.ViralPoints.isEnabled()){excludedTrackingCodes=[SD.TrackingCodes.trigger.banner.right_top_green_button._value,SD.TrackingCodes.trigger.communication.chat.non_premium_chat._value,SD.TrackingCodes.trigger.communication.date.find_out_why_date_ended._value,SD.TrackingCodes.trigger.banner.chat_popup._value];}
if(!dontCheckSegment&&(!params||excludedTrackingCodes.indexOf(originalParams.tc)==-1)&&SD.Segmentation.isLowSegmentForViral()){if(!originalParams){originalParams={};}
originalParams['from_upgrade']=true;SD.ViralPoints.onSubscribeTrigger(originalParams,continuationCallback);return false;}}
SD.AbandonPopup.disable();var premUrl=me.premium_signup_url+params;if(me.can_see_one_click_form){SD.UIController.oneClickSubscriptionPopup('','',params,continuationCallback);}else{SD.UIController.subscribePopup(premUrl,continuationCallback);}
return false;},speedVerifyMyself:function(){SD.AbandonPopup.disable();this.speedVerifyPopup.apply(this,arguments);},upgradeMyselfWithUrl:function(premUrl){if(SD.Config.platform.platformId==SD.Constants.PLATFORM.FACEBOOK){var openPopup=window.open(premUrl);if(!openPopup){top.location.href=premUrl;}}else{SD.UIController.subscribePopup(premUrl);}},goToFaq:function(){SD.Nav.redirectTo(SD.NavUtils.link('site','faq'));},onPauseDating:function(event){},onMessageReceived:function(user,message){if(this.tabBlinkingEnabled){if(!this.windowIsActive()){SD.Favicon.animateTitle(["Message from: "+user.username,message.substr(0,20)],1000);}}},onSendFlirtClick:function(canSendFlirt,otherMemberId){if(canSendFlirt){return true;}else{SD.User.addMessageAttempt(otherMemberId,function(){SD.UIController.upgradeMyself({tc:SD.TrackingCodes.trigger.communication.flirt.second_message._value,ti:otherMemberId});});return false;}},windowIsActive:function(){return this.hasFocus;},infoMessage:function(message,duration,options){if(SD.ExperimentManager.RecommendationsInNotification_SDWEB289.value){return this.infoNotification(message,5);}
options=options||{};var time=(duration)?duration*1000:3000;var win=new SD.Window({className:options.className||"message-dialog",resizable:false,content:'<div class="sd-message">'+message+'</div>',groupId:"notification",width:options.width||220,template:options.template||SD.Window.infoMessageTemplate,draggable:false,populateMethod:'direct'});if(SD.UIController.platform_id==3){win.showCenter(false,210,370);}else{win.showCenter(false,210);}
setTimeout(win.close.bind(win),time);return win;},infoNotification:function(message,duration,options){options=options||{};if(SD.UI.SiteBar.Notifications){SD.UI.SiteBar.Notifications.store.add(new SD.UI.HtmlNotification({showsInStaticList:options.showsInStaticList,showsInIndicator:options.showsInIndicator,stayTime:duration,html:options.html||'<div class="lib-html-notification" style="position:relative;display:none;zoom:1">'+'<div class="sd-message" style="padding:5px 15px 5px 5px;font-size:14px;">'+message+'</div>'+'<span class="notification-closer" style="position:absolute;top:5px;right:5px;">X</span>'+'</div>'}));}},_popupGenericWarning:function(title,upgradeArguments){this.upgradeMyself(upgradeArguments);},messageBox:function(title,content,options){options=options||{};var btnLabel=options.btnLabel||"OK";var win=this.standardPopup({title:title});var btnBar='<div style="text-align:center">'+'<input type="text" value="#{btnLabel}" class="input-button" />'+'</div>';Object.extend(win.getContent().style,{paddingTop:"10px",textAlign:"center"});win.getContent().insert(content);win.getContent().insert(btnBar.interpolate({btnLabel:btnLabel}));win.showCenter(true,100);win.getContent().select('input')[0].observe('click',function(e){e.stop();win.close()});return win;},reportUserPopup:function(user,options){var reportReasons=['Sexually Explicit','Under 18 years old','Profane Username','Cyberbullying/Harrassment','Scammer/Spammer/Advertising','Imposter/Fake User','User Not in Photo'];var formText="";reportReasons.each(function(option){formText+="<input type='radio' value='"+option+"' name='reason' />"+option+"<br/>";});formText+="<input type='radio' value='other' name='reason' /> Other<br/>"+"<textarea name='reason_other_msg'></textarea>";var template="<div>"+"<div class='chat-report-disclaimer' style='margin-bottom: 8px;'>"+"Select a reason below and click 'send' to ban your date from using SpeedDate.com. "+"Note that a copy of your chat history will also be sent to site admin for assurance.<br/>"+"</div>"+"<form id='report_form_"+user.uid+"'>"+"<div>"+
formText+"</div>"+"<div>"+"<input type='button' class='button' value='Send Report' name='submitButton'/>"+"<input type='button' class='button' value='Cancel' name='cancelButton'/>"+"</div>"+"</form>"+"</div>";var win=this.standardPopup({title:'Report '+user.username,draggable:true});win.getContent().insert(template.interpolate({uid:user.uid,username:user.username}));win.showCenter(true,100);var form=$('report_form_'+user.uid);if(form){form.submitButton.observe('click',function(){var data=form.serialize(true);var reasonText=data.reason=='other'?data.reason_other_msg:data.reason;SD.User.reportMember(user,reasonText,options.chatHistory,options.source);win.close();options.onDone&&options.onDone(true);});form.cancelButton.observe('click',function(){win.close();options.onDone&&options.onDone(false);});}
return win;},submitIMPopup:function(formId,title,juliet,errorDivId,onSubmit,onLater,onDontAsk,hasIM,continuationCallback){title=title||"Want to chat with "+juliet.username+"?";return this.imPopup(title,juliet.uid,continuationCallback);},askFbPermissionsPopup:function(){var win=this.standardPopup({title:'',width:500,draggable:false});var content='<div class="ask-friend-testimonial" style="padding: 10px 0px 0px; font-family:\'Arial\';">'+'<h1 style="font-size: 18px; font-weight: bold; color: #74B3CF;">'+'New Feature: Add testimonials to your profile!'+'</h1>'+'<h2 style="font-size: 12px; color: #666;">'+'Just click allow on the next popup'+'</h2>'+'<button class="give-permission-btn" style="color: #FFFFFF;'+'font-size: 22px; font-weight: bold; margin: 10px 0px 5px; padding: 14px 73px; cursor: pointer;'+'background-image: url(http://www.speeddate.com/static/site/images/green-button.png);">'+'Continue &raquo;'+'</button>'+'<h3 style="font-size: 11px; color: #999; margin:10px 0px;">'+'*We\'ll post testimonials to several of your friends\' walls every day, until your testimonials are complete.'+'You can approve the  testimonials before they appear in your SpeedDate profile.'+'All you need to do is allow us to publish feeds to your friends\' walls even when you are offline.'+'</h3>'+'<h2 style="color: #666;">Your testimonial progress (you need 15 more testimonials to reach 100%)</h2>'+'<div style="border: 1px solid #8F9FBF; width: 480px; background-color: #DFDFDF;">'+'<div style="background-color: #fff; color: #666; width: 25px; padding: 5px; font-size: 15px; text-align: center; font-weight: bold;">'+'0%'+'</div>'+'</div>'+'</div>';win.getContent().insert(content);win.getContent().select('.give-permission-btn').each(function(el){el.observe('click',function(e){askPermissionsForTestimonials();win.close();e.stop();});});win.showCenter(true,50);},facebookPhotoImportPopup:function(userFbPhotos,source){var win=this.standardPopup({title:'Update your profile with your Facebook photos!',width:620,draggable:true});var content='<style>'+'table.facebook-photo-table td:hover{'+'background-color: #C2D1EF;'+'}'+'</style>'+'<div class="facebook-photo-import" style="padding: 10px 0px 0px; font-family:\'Arial\';">'+'<h1 style="font-size: 18px; font-weight: bold; color: #597E8F;">'+'Use your Facebook Photos in SpeedDate!'+'</h1>'+'<h2 style="font-size: 12px; color: #666;">'+'Users with more photos get more matches!'+'</h2>'+'<form id="form-facebook-photos" method="post" style="margin-top: 10px; background-color: #E0E5EF;'+'border-top: 1px solid #AEC3CD; border-bottom: 1px solid #AEC3CD;">'+'<table class="facebook-photo-table">'+'<tr>';var photoIndex=0;userFbPhotos.each(function(photo){content+='<td style="width: 100px; padding: 10px 10px; text-align: center;">'+'<label for="fb_photo_'+photo["pid"]+'">'+'<img src="'+photo["src"]+'" style="max-width: 100px; max-height: 75px;" /><br />'+'<input id="fb_photo_'+photo["pid"]+'" name="photoIds['+photo["pid"]+']" type="checkbox" value="'+photo["src_big"]+'" />'+'</label>'+'</td>';if(photoIndex%5==4){content+='</tr><tr>';}
photoIndex++;});content+='</tr>'+'</table>'+'</form>'+'<div class="photo-import-buttons">'+'<table width="100%" style="margin-top: 20px;">'+'<tr>'+'<td class="photo-buttons" style="font-size: 10px; color: #666; text-align: left;">'+'note: we will save your photos<br />to display as part of your profile!'+'</td>'+'<td class="photo-buttons" style="text-align: right; padding-right: 10px;">'+'<a class="fb-photo-select-all-btn" href="#" onclick="SD.FB.selectAllFbPhotos(); return false;" style="font-size:13px; font-weight:bold; ">Select All Photos</a>'+'</td>'+'<td class="photo-buttons" style="width: 155px;">'+'<a href="#" class="save-user-fb-photos" style="width: 155px; height: 10px; display: block;'+'color: #FFFFFF; font-size: 16px; font-weight: bold; margin: 0px;'+'padding: 10px 0px 20px 42px; cursor: pointer;'+'background-image: url(http://www.speeddate.com/static/site/images/-sprite6.png);'+'background-position: -304px 0px;">Save Photos &raquo;</a>'+'</td>'+'</tr>'+'</table>'+'</div>'+'</div>';win.getContent().insert(content);win.getContent().select('.fb-photo-select-all-btn').each(function(el){el.observe('click',function(e){SD.FB.selectAllFbPhotos();e.stop();});});win.getContent().select('.save-user-fb-photos').each(function(el){el.observe('click',function(e){SD.FB.sendPhotoUrlsToBackend(source);win.close();e.stop();});});win.showCenter(true,20);},facebookSharePopup:function(context,continuationCallback){context=context||{};var sourceType=context.sourceType||'';var sourceMemberId=context.sourceMemberId||'';var actionType=context.actionType||'';var actionData=context.actionData||'';this.canSaveFilterState()&&SD.UserFilters.UI.saveStateAndPause();var winConfig={title:'&nbsp;',content:"<p class='sd-window-msg'>Loading...</p>",width:550,draggable:false,top:100,onAfterClose:function(ev){SD.UserFilters.UI.restorePreviousStateAndResume();if(continuationCallback){continuationCallback();}},loader:{onParseElements:{'.close-dialog':function(el,domRoot){el.observe('click',function(){dialog.close();});}}}};var dialog=this.standardPopup(winConfig);dialog.open().load(SD.NavUtils.link('profile','facebook_share_popup',{sourceMemberId:sourceMemberId||'',sourceType:sourceType||'',actionType:actionType||'',actionData:actionData||''}));return dialog;},changePasswordPopup:function(){var winConfig={title:'',content:"<p class='sd-window-msg'>Loading...</p>",top:80,width:700,groupId:"group4",draggable:false,blocker:true,closable:false,onAfterClose:function(ev){},template:SD.Window.goalPopupStyle,className:"lib-window goal-dialog speedv-tutorial"};var win=this.standardPopup(winConfig).open();win.load(SD.NavUtils.link('profile','change_password_popup'));if(!SD.Config.isFacebook){win.dom.appendChild(new Element('div',{'class':'left-section-lady'}));win.moveBy(100);}
win.domContent.style.overflow='hidden';return win;},freeSubscriptionPromoPopup:function(){var winConfig={title:'',content:"<p class='sd-window-msg'>Loading...</p>",top:80,width:520,groupId:"group3",draggable:false,blocker:true,closable:false,onAfterClose:function(ev){},loader:{onParseElements:{'.close-link':function(el,domRoot){el.observe('click',function(){win.close();});},'.activate-button':function(el,domRoot){el.observe('click',function(){new Ajax.Request(SD.NavUtils.link('ajax','activate_free_subscription'),{method:"post",evalJSON:true,onSuccess:function(response){var data=response.responseJSON||{};if(data.result){window.location.href=SD.NavUtils.link('payment','free_promo_payment_success');}else{win.close();}},onError:function(){win.close();}});});}}},template:SD.Window.goalPopupStyle,className:"lib-window goal-dialog signup-tutorial"};var win=this.standardPopup(winConfig).open();win.load(SD.NavUtils.link('profile','free_subscription_promo_popup'));win.domContent.style.overflow='hidden';return win;},friendTreePopup:function(){if(SD.UIController.friendTreeShownCounter.getValue()>1){return false;}else{SD.UIController.friendTreeShownCounter.increment();}
var winConfig={title:'',content:"<p class='sd-window-msg'>Loading...</p>",top:80,width:700,draggable:true,blocker:true,onAfterClose:function(ev){},template:SD.Window.newStyle,className:"generic-popup-container"};var dialog=this.standardPopup(winConfig);dialog.open().load(SD.NavUtils.link('fun','friend_tree',{'popup':1}));return dialog;},newYearCardPopup:function(){if(SD.UIController.newYearCardShownCounter&&SD.UIController.newYearCardShownCounter.getValue()>1){return false;}else{SD.UIController.newYearCardShownCounter&&SD.UIController.newYearCardShownCounter.increment();}
var winConfig={title:'',content:"<p class='sd-window-msg'>Loading...</p>",top:80,width:700,draggable:true,blocker:false,closeMethod:'remove',template:SD.Window.newStyle,className:"generic-popup-container"};var dialog=this.standardPopup(winConfig);dialog.open().load(SD.NavUtils.link('fun','new_year_card',{'isPopup':1}));return dialog;},valentineCardPopup:function(params){if(SD.UIController.valentineCardShownCounter&&SD.UIController.valentineCardShownCounter.getValue()>1){return false;}else if(SD.UIController.valentineCardBlocker&&SD.UIController.valentineCardBlocker.isBlocked()){return false;}else{SD.UIController.valentineCardShownCounter&&SD.UIController.valentineCardShownCounter.increment();}
var winConfig={title:'',content:"<p class='sd-window-msg'>Loading...</p>",top:60,width:700,draggable:true,blocker:false,closeMethod:'remove',template:SD.Window.newStyle,className:"generic-popup-container"};var dialog=this.standardPopup(winConfig);dialog.open().load(SD.NavUtils.link('fun','new_year_card',{'isPopup':1,'photoType':'valentine_card','popupId':dialog.id}));return dialog;},facebookLikePopup:function(status){status=status||"unknown";this.canSaveFilterState()&&SD.UserFilters.UI.saveStateAndPause();var dialog=this.standardPopup({title:'',content:"<p class='sd-window-msg'>Loading...</p>",top:80,width:470,draggable:true,blocker:true,onAfterClose:function(e){if(e.memo.closedByUser){SD.ExperimentManager.recordOutput('FBLikePopupSkipped',1,1);}
SD.UserFilters.UI.restorePreviousStateAndResume();},className:"generic-popup-container"});SD.Event.observe(null,SD.FbConnect.Events.LIKE,function(){dialog.close();});dialog.open().load(SD.NavUtils.link('profile','facebook_like_popup',{'connectStatus':status}));return dialog;},matchFriendPopup:function(context,continuationCallback){context=context||{};var sourceType=context.sourceType||'';var sourceMemberId=context.sourceMemberId||'';this.canSaveFilterState()&&SD.UserFilters.UI.saveStateAndPause();var winConfig={title:'',content:"<p class='sd-window-msg'>Loading...</p>",width:550,draggable:false,top:50,onAfterClose:function(ev){SD.UserFilters.UI.restorePreviousStateAndResume();if(continuationCallback){continuationCallback();}},loader:{onParseElements:{'.close-dialog':function(el,domRoot){el.observe('click',function(){dialog.close();});}}},template:SD.Window.newStyle,className:"generic-popup-container"};var dialog=this.standardPopup(winConfig);dialog.open().load(SD.NavUtils.link('fun','match_friend',{sourceMemberId:sourceMemberId||'',sourceType:sourceType||'','isPopup':'1'}));return dialog;},emailVerificationPopup:function(context,continuationCallback){context=context||{};var sourceType=context.sourceType;var sourceMemberId=context.sourceMemberId;this.canSaveFilterState()&&SD.UserFilters.UI.saveStateAndPause();var winConfig={title:'Please verify your email address to continue!',content:"<p class='sd-window-msg'>Loading...</p>",width:550,draggable:false,top:100,onAfterClose:function(ev){SD.UserFilters.UI.restorePreviousStateAndResume();if(continuationCallback){continuationCallback();}},loader:{onParseElements:{'.close-dialog':function(el,domRoot){el.observe('click',function(){dialog.close();});}}}};var dialog;if($('goal-bar')){winConfig.title='';winConfig.width=590;dialog=this.goalPopup(winConfig);}else{dialog=this.standardPopup(winConfig);}
dialog.open().load(SD.NavUtils.link('profile','email_verification_popup',{sourceMemberId:sourceMemberId||'',sourceType:sourceType||''}));return dialog;},phoneNumberPopup:function(context,continuationCallback){context=context||{};var sourceType=context.sourceType;var sourceMemberId=context.sourceMemberId;this.canSaveFilterState()&&SD.UserFilters.UI.saveStateAndPause();var winConfig={title:'&nbsp;',content:"<p class='sd-window-msg'>Loading...</p>",width:550,draggable:false,top:100,onAfterClose:function(ev){SD.UserFilters.UI.restorePreviousStateAndResume();if(continuationCallback){continuationCallback({fromAddPhone:true});}},loader:{onParseElements:{'.close-dialog':function(el,domRoot){el.observe('click',function(){dialog.close();});}}}};Object.extend(winConfig,{template:SD.Window.goalPopupStyle,className:"lib-window goal-dialog"});var dialog=this.standardPopup(winConfig);dialog.open().load(SD.NavUtils.link('profile','phone_number_popup',{sourceMemberId:sourceMemberId||'',sourceType:sourceType||''}));dialog.dom.insert('<div class="dialog-header-thumb">'+'<div class="dialog-goal-thumb"></div>'+'<div class="dialog-goal-icon goal-sms-icon"></div>'+'</div>');return dialog;},aboutMePopup:function(context,continuationCallback){SD.ExperimentManager.recordOutput('SeenAboutMePopup',1,1);return SD.Dialog.ProfileTwoQuestions.open(context,continuationCallback);},uploadPhotoPopup:function(context,continuationCallback){context=context||{};var sourceType=context.sourceType||'';var sourceMemberId=context.sourceMemberId||'';this.canSaveFilterState()&&SD.UserFilters.UI.saveStateAndPause();$('uni-bar')&&SD.UI.DateUI.getUI().defaultUI.hide();var winConfig={title:'',content:"<p class='sd-window-msg'>Loading...</p>",top:80,width:560,draggable:true,blocker:true,onAfterClose:function(ev){SD.UserFilters.UI.restorePreviousStateAndResume();$('uni-bar')&&SD.UI.DateUI.getUI().defaultUI.show();if(continuationCallback){continuationCallback();}},template:SD.Window.goalPopupStyle,className:"lib-window goal-dialog"};var dialog=this.goalPopup(winConfig);dialog.open().load(SD.NavUtils.link('profile','upload_photo_popup',{sourceMemberId:sourceMemberId||'',sourceType:sourceType||''}));SD.ExperimentManager.recordOutput('SeenUploadPhotoPopup',1,1);return dialog;},uploadPhotoPopupTutorial:function(context,continuationCallback){context=context||{};var sourceType=context.sourceType||'';var sourceMemberId=context.sourceMemberId||'';this.canSaveFilterState()&&SD.UserFilters.UI.saveStateAndPause();$('uni-bar')&&SD.UI.DateUI.getUI().defaultUI.hide();var winConfig={title:'',content:"<p class='sd-window-msg'>Loading...</p>",top:80,width:468,draggable:true,blocker:true,groupId:'group4',onAfterClose:function(ev){SD.UserFilters.UI.restorePreviousStateAndResume();$('uni-bar')&&SD.UI.DateUI.getUI().defaultUI.show();if(continuationCallback){continuationCallback();}},template:SD.Window.goalPopupStyle,className:"lib-window goal-dialog"};var domJulie=DIV({});domJulie.className='julie-side-pos1';domJulie.style.position='absolute';domJulie.style.top=0;domJulie.style.left='-203px';var dialog=this.goalPopup(winConfig);dialog.open().load(SD.NavUtils.link('profile','upload_photo_popup',{tutorial:1,sourceMemberId:sourceMemberId||'',sourceType:sourceType||''}));dialog.dom.style.overflow='visible';dialog.dom.appendChild(domJulie);SD.ExperimentManager.recordOutput('SeenUploadPhotoPopup',1,1);return dialog;},editPhotoPopup:function(mmid,title){title=title||'Please locate your face in the photo!';var winConfigV2={title:title,content:"<p class='sd-window-msg'>Loading...</p>",top:80,width:760,draggable:true,blocker:true,onAfterClose:function(ev){},template:SD.Window.newStyle,className:"generic-popup-container"};var dialog=this.standardPopup(winConfigV2);dialog.open().load(SD.NavUtils.link('profile','edit_photo',{mmid:mmid||''}));return dialog;},oneClickSubscriptionPopup:function(sourceType,sourceMemberId,params,continuationCallback){var me=SD.Model.getMyself();if(me.shouldSeeFreeSubscriptionPromoPopup){this.freeSubscriptionPromoPopup();return;}
SD.ExperimentManager.recordOutput('OneClickSub_ViewedSubPopupOutput',1,1);params=params||'';params+='&expandedMode=true&oneClick=true';if(sourceType){params+='&sourceType='+sourceType;}
if(sourceMemberId){params+='&sourceMemberId='+sourceMemberId;}
return SD.UIController.subscribePopup(SD.Model.getMyself().premium_signup_url+params,continuationCallback);},welcomePremiumPopup:function(){try{SD.UserFilters.UI.pauseSpeedDating();SD.UserFilters.UI.allowDating=false;SD.UserFilters.UI.setDatingOff();}catch(e){}
var dialog;var iframeName='paymentIframe';var url=SD.NavUtils.linkSecure('payment','welcome_premium_popup',{memberid:SD.Model.getUserId(),control_id:SD.Model.control_id});var width=710;var content='<iframe id="'+iframeName+'" name="'+iframeName+'" src="'+url+'" frameborder="0" width="100%" style="height:510px" '+'marginwidth="0" marginheight="0" hspace="0" vspace="0"></iframe>'+'<div style="position: absolute; width: 168px; right: 0px; bottom: 15px;">'+'<div class="lib-close-handle"><a href="javascript:void(0);">Close - find me SpeedDates!</a></div>'+'<div class="lib-close-and-do-not-date"><a href="javascript:void(0);">Close - just browsing</a></div>'+'</div>';var winConfig={position:'absolute',resizable:false,title:'',content:content,width:width,bindToWindowScroll:false,draggable:false,top:25,template:SD.Window.newStyle,className:"generic-popup-container",groupId:'group4',loader:{'onContentRendered':function(){dialog.dom.style.height='';dialog.domContent.style.height='';dialog.canMove=true;var viewportDimensions=document.viewport.getDimensions();if(dialog.dom.offsetHeight>viewportDimensions.height){dialog.moveTo(null,0);}else{dialog.moveTo(null,Math.min(100,(viewportDimensions.height-dialog.dom.offsetHeight)/2));}}},parseLibrary:{'.lib-close-handle':function(el,domRoot){var _this=this;el.onclick=function(){SD.UserFilters.UI.allowDating=true;SD.UserFilters.UI.startSpeedDating();_this.close();};el.removeClassName("lib-close-and-date");},'.lib-close-and-do-not-date':function(el,domRoot){var _this=this;el.onclick=function(){SD.UserFilters.UI.allowDating=true;_this.close();};el.removeClassName("lib-close-and-do-not-date");}}};dialog=this.standardPopup(winConfig).open();return dialog;},giftsPopup:function(other_memberid){var dialog;var iframeName='paymentIframe';var url=SD.NavUtils.linkSecure('payment','gifts_popup',{memberid:SD.Model.getUserId(),control_id:SD.Model.control_id,other_memberid:other_memberid});var winConfig={position:'absolute',resizable:false,title:'',content:'<iframe id="'+iframeName+'" name="'+iframeName+'" src="'+url+'" frameborder="0" width="100%" style="height:642px;" '+'marginwidth="0" marginheight="0" hspace="0" vspace="0"></iframe>',width:610,bindToWindowScroll:false,draggable:false,destroyOnClose:true,top:5,template:SD.Window.newStyle,className:"generic-popup-container",groupId:'group4',loader:{'onContentRendered':function(){dialog.dom.style.height='';dialog.domContent.style.height='';dialog.canMove=true;var viewportDimensions=document.viewport.getDimensions();if(dialog.dom.offsetHeight>viewportDimensions.height){dialog.moveTo(null,0);}else{dialog.moveTo(null,Math.min(100,(viewportDimensions.height-dialog.dom.offsetHeight)/2));}}}};dialog=this.standardPopup(winConfig).open();return dialog;},updatePaymentMethodPopup:function(){var dialog;var width=610;var height=622;var winConfig={position:'absolute',resizable:false,title:'',content:'<div id="paymentMethodIframeContainer"></div>',width:width-10,height:height,bindToWindowScroll:false,draggable:false,destroyOnClose:true,top:5,template:SD.Window.newStyle,className:"generic-popup-container",groupId:'group4'};dialog=this.standardPopup(winConfig).open();var iframe=document.createElement('iframe');iframe.id="payment"+SD.Utils.IdGenerator.generate();iframe.name=iframe.id;iframe.allowTransparency=true;iframe.frameBorder='0';iframe.src=SD.NavUtils.link('payment','update_payment_method_popup',{});Object.extend(iframe.style,{width:width+'px',height:height+'px'});$("paymentMethodIframeContainer").appendChild(iframe);return dialog;},__url_goToAccountSettings:function(){SD.MyAccount.forceMenuItemLoadAndFocus('account-info-settings');},subscribePopup:function(subscribeUrl,continuationCallback,closable,closeText){var me=SD.Model.getMyself();if(me.shouldSeeFreeSubscriptionPromoPopup){this.freeSubscriptionPromoPopup();return;}
var queryObject=subscribeUrl.split("?")[1].parseQuery();var containerUrl=SD.NavUtils.link('payment','subscribe_4396',{memberid:SD.Model.getUserId(),control_id:SD.Model.control_id,platformId:SD.Config.platform.platformId,tc:queryObject['tc'],ti:queryObject['ti'],isIframe:1,expandedMode:queryObject['expandedMode']||false,sourceType:queryObject['sourceType']||''});var formUrl=SD.NavUtils.link('payment','subscribe_form_4396',{memberid:me.uid,control_id:SD.Model.control_id,platformId:SD.Config.platform.platformId,tc:queryObject['tc'],td:queryObject['td'],lpid:queryObject['lpid'],isIframe:1,expandedMode:queryObject['expandedMode']||false});formUrl=formUrl.replace('/apps/facebook','');var win;var winConfig;SD.AbandonPopup.disable();SD.UserFilters.UI.saveStateAndPause();winConfig={position:'absolute',top:10,width:600,closable:closable==null?true:closable,resizable:false,title:'',content:'<div style="height:200px;text-align:center;margin-top:75px"><h1 style="color:#fff">Loading...</h1></div>',draggable:false,template:SD.Window.goalPopupStyle,className:"lib-window goal-dialog signup-tutorial",groupId:'group4',bindToWindowScroll:false,enableYAdjustOnResize:false,onAfterClose:function(){continuationCallback&&continuationCallback();$('uni-bar')&&SD.UI.DateUI.getUI().defaultUI.show();SD.UserFilters.UI.restorePreviousStateAndResume();},url:containerUrl,loader:{onContentRendered:function(){var iframe=document.createElement('iframe');iframe.id="payment"+SD.Utils.IdGenerator.generate();iframe.name=iframe.id;iframe.frameBorder='0';iframe.allowTransparency=true;iframe.src=formUrl;Object.extend(iframe.style,{width:"580px",height:(!queryObject['expandedMode']||queryObject['expandedMode']==='false')?"300px":"645px",overflow:"hidden",background:"transparent"});$("subscribeFormContainer").appendChild(iframe);win.domContent.style.paddingRight=0;}}};win=this.standardPopup(winConfig).open();if(!SD.Config.isFacebook){win.dom.appendChild(new Element('div',{'class':'left-section-lady'}));win.moveBy(100);}
win.domContent.style.overflow='hidden';if(closeText!=null){win.dom.select('.dialog-close-button').invoke('addClassName','window-close-text-link').invoke('addClassName','popup-close-auto-width').invoke('update',closeText);}
$('uni-bar')&&SD.UI.DateUI.getUI().defaultUI.hide();return win;},speedVerifyPopup:function(context,continuationCallback){context=context||{};var sourceType=context.sourceType;var sourceMemberId=context.sourceMemberId;var forceVerify=context.forceVerify||false;SD.AbandonPopup.disable();SD.UserFilters.UI.saveStateAndPause();var dialog;var url=SD.NavUtils.link('payment','speed_verify_popup_4262',{memberid:SD.Model.getUserId(),control_id:SD.Model.control_id,sourceMemberId:sourceMemberId||'',sourceType:sourceType||'',platformId:SD.Config.platform.platformId});var formUrl=SD.NavUtils.link('payment','speed_verify_form_4262',{memberid:SD.Model.getUserId(),control_id:SD.Model.control_id,sourceMemberId:sourceMemberId||'',sourceType:sourceType||'',platformId:SD.Config.platform.platformId});formUrl=formUrl.replace('/apps/facebook','');var winConfig={position:'absolute',bindToWindowScroll:false,title:'',content:"<p class='sd-window-msg'>Loading...</p>",width:625,draggable:false,top:40,template:SD.Window.goalPopupStyle,className:"lib-window goal-dialog speedv-tutorial",groupId:'group4',range:{x1:-Infinity,x2:Infinity,y1:-Infinity,y2:Infinity},onAfterClose:function(){SD.UserFilters.UI.restorePreviousStateAndResume();$('uni-bar')&&SD.UI.DateUI.getUI().defaultUI.show();if(continuationCallback){continuationCallback({forceVerify:forceVerify});}},url:url,loader:{onContentRendered:function(){var iframe=document.createElement('iframe');iframe.id="payment"+SD.Utils.IdGenerator.generate();iframe.name=iframe.id;iframe.frameBorder='0';iframe.allowTransparency=true;iframe.src=formUrl;Object.extend(iframe.style,{width:'580px',height:'405px',overflow:"hidden"});$("verifyIframeContainer").appendChild(iframe);if(context.expandedMode){$('verifyButton')&&$('verifyButton').hide();$('verifyIframeContainer')&&$('verifyIframeContainer').show();}}}};if(context.hideSkipLink!==undefined)winConfig.closable=context.hideSkipLink;dialog=this.standardPopup(winConfig).open();if(!SD.Config.isFacebook){dialog.dom.appendChild(new Element('div',{'class':'left-section-lady'}));dialog.moveBy(100);}
dialog.domContent.style.overflow='hidden';$('uni-bar')&&SD.UI.DateUI.getUI().defaultUI.hide();return dialog;},__url_resubscribe:function(){this.resubscribe();},resubscribe:function(){if(SD.ExperimentManager.ResubMerge_SDWEB66.value){SD.UIController.subscribePopup(SD.Model.getMyself().premium_signup_url);}else{var url=SD.NavUtils.link('profile','resubscribe',{displayType:'ajax'});this.resubscribePopup(url);}},resubscribePopup:function(url,width){var closeDialog=function(){dialog.close();}
SD.Event.observeOnce(null,SD.UIController.Events.REQUEST_RESUB_POPUP_CLOSE,closeDialog);SD.UserFilters.UI.saveStateAndPause();var winConfig={title:'',content:"<p class='sd-window-msg'>Loading...</p>",position:'absolute',width:width||748,draggable:false,blocker:true,top:100,bindToWindowScroll:false,template:SD.Window.newStyle,className:"lib-window new-window no-header mod-resub-in-popup",groupId:'group4',url:url,loader:{onContentRendered:function(el){}},onAfterClose:function(){$('uni-bar')&&SD.UI.DateUI.getUI().defaultUI.show();SD.Event.stopObserving(null,SD.UIController.Events.REQUEST_RESUB_POPUP_CLOSE,closeDialog);SD.UserFilters.UI.restorePreviousStateAndResume();}};$('uni-bar')&&SD.UI.DateUI.getUI().defaultUI.hide();var dialog=this.standardPopup(winConfig);dialog.open();dialog.domContent.style.overflow='hidden';return dialog;},updatePaymentFromResubPopup:function(url){       SD.Event.fire(null,SD.UIController.Events.REQUEST_RESUB_POPUP_CLOSE);       if(SD.Config.platform.name=="site"){window.location.href=url;       }else{           window.open(url);       }
   },termsForPlansPopup:function(el){if(el){var dialog=this.standardPopup({title:"Policy For All Billing Plans",draggable:true,width:400,height:375,groupId:'group4'});dialog.getContent().insert(el.innerHTML);dialog.showCenter();dialog.domContent.style.overflow='auto';dialog.domContent.style.height=(parseInt(dialog.domContent.style.height)-20)+'px';}},privacyPolicyPopup:function(el){if(el){var dialog=this.standardPopup({title:"Privacy Policy",draggable:true,width:400,height:375,groupId:'group4'});dialog.getContent().insert(el.innerHTML);dialog.showCenter();dialog.domContent.style.overflow='auto';dialog.domContent.style.height=(parseInt(dialog.domContent.style.height)-20)+'px';}},onSubscriptionInfoClick:function(){this.termsForPlansPopup($('rebill-info'));},showPrivacyPolicy:function(){this.privacyPolicyPopup($('privacy-policy'));},imPopup:function(title,julietUid,continuationCallback){var winConfig={title:title,content:"<p>Loading...</p>",width:540,draggable:false,top:100,template:SD.Window.newStyle,className:"generic-popup-container",groupId:"group4",onAfterClose:function(){continuationCallback&&continuationCallback();},loader:{onContentRendered:function(){win.domContent.style.overflow='hidden';}}};var params=julietUid?{juliet:julietUid,displayType:'ajax'}:{displayType:'ajax'};var win=SD.UIController.standardPopup(winConfig).open().load(SD.NavUtils.link('profile','im_solicitation',params));SD.Notification.IM.formWindow=win;return win;},imSolicitationUponDateRequest:function(formId,title,juliet,errorDivId,onSubmit,onLater,onDontAsk,hasIM){this.canSaveFilterState()&&SD.UserFilters.UI.saveStateAndPause();var dialog=this.standardPopup({title:title||'Request for Instant Message Information',content:"<p class='sd-window-msg'>Loading...</p>",top:80,width:500,draggable:false,onAfterClose:function(){SD.UserFilters.UI.restorePreviousStateAndResume();},loader:{onContentRendered:function(){$$('select.triggered-select').each(function(e){(new SD.TriggeredSelect(e));});$$('.tooltip-base').each(function(base){var tt=new SD.Tooltip.Signup(base);if(base.ancestors().any(function(dom){return dom.getStyle('position')=="fixed";})){tt.tooltipDiv.style.position="fixed";}});$('imFormSignup').onclick=onSubmit;$('imFormNotNow').onclick=onLater;$('imDontAsk').onclick=onDontAsk;}}});dialog.open().load(SD.NavUtils.link('profile','im_solicitation_upon_date_request'));return dialog;},facebookStatusUpdatePopup:function(params){params=params||{};this.canSaveFilterState()&&SD.UserFilters.UI.saveStateAndPause();var dialog=this.standardPopup({title:params.title||'',content:"<p class='sd-window-msg'>Loading...</p>",top:80,width:470,draggable:false,onAfterClose:function(){SD.UserFilters.UI.restorePreviousStateAndResume();},className:"generic-popup-container",loader:{onContentRendered:function(){$$('.dialog-close-button').each(function(e){e.onclick=function(){SD.ExperimentManager.recordOutput('FBConnectLandingPageSkippedUpdateStatus',1,1);dialog.close();}});}}});dialog.open().load(SD.NavUtils.link('profile','fb_status_update'));return dialog;},standardPopup:function(params){if(params.width){params.contentWidth=params.width;}
if(params.blocker===undefined){params.blocker=(params.draggable!==undefined)?!params.draggable:true;}
var baseParams={width:350,closable:true,template:SD.Window.newStyle,draggable:false,className:"lib-window generic-popup-container",isStandardPopup:true};var win=new SD.Window(Object.extend(baseParams,params));return win;},openStandardPopup:function(params){return this.standardPopup(params).open();},goalPopup:function(params){params=params||{};if(params.width){params.contentWidth=params.width;}
if(params.blocker===undefined){params.blocker=(params.draggable!==undefined)?!params.draggable:true;}
var baseParams={width:350,closable:true,template:SD.Window.goalPopupStyle,draggable:false,className:"lib-window goal-dialog",isStandardPopup:true};var win=new SD.Window(Object.extend(baseParams,params));Prototype.Browser.IE6&&win.observe("afterOpen",function(){win.dom.style.width=(parseInt(win.dom.style.width)-1)+'px';});return win;},forgotPassword:function(){new Ajax.Request(SD.NavUtils.link('ajax','forgot_password'),{method:"post",evalJSON:true,parameters:{},onSuccess:function(response){var data=response.responseJSON||{};if(data){$('password-change-message')&&$('password-change-message').removeClassName('result-error').addClassName('result-ok').update('An email has been sent to '+((SD&&SD.Model&&SD.Model.getMyself().email)||'your email')+'. This email describes how to get your new password. Please be patient; the delivery of email may be delayed. Remember to confirm the email you supplied is correct and to check your junk or spam folder or filter if you do not receive this email.').show();}else{$('password-change-message')&&$('password-change-message').removeClassName('result-ok').addClassName('result-error').update('Password recovery email could not be sent. Please try again later.').show();}},onError:function(){$('password-change-message')&&$('password-change-message').removeClassName('result-ok').addClassName('result-error').update('Password recovery email could not be sent. Please try again later.').show();}});},userInfoMouseOverOutTrigger:function(defaultAction,skipVerify,forceVerify){forceVerify=forceVerify||false;skipVerify=skipVerify||false;if(!SD.Model.getMyself().has_photo){return false;}else if(!SD.Model.getMyself().has_about_me){return false;}else if(!SD.Model.getMyself().is_organic&&!SD.Model.getMyself().is_verified&&forceVerify){return false;}else if(!SD.Model.getMyself().is_organic&&!SD.Model.getMyself().is_verified&&SD.UIController.speedVerifyShownCounter.getValue()<2&&!skipVerify){return false;}else if(SD.Model.getMyself().has_bounced){return false;}else{return defaultAction();}},popupBenefits:function(){var winConfig={title:'SpeedDate Benefits',content:"<p>Loading...</p>",width:700,contentHeight:400,draggable:false,top:100,template:SD.Window.newStyle,className:"generic-popup-container",groupId:'group4',loader:{onContentRendered:function(){win.domContent.style.overflow='auto';win.domContent.style.height='419px';}}};var win=SD.UIController.standardPopup(winConfig).open().load(SD.NavUtils.link('profile','get_benefits',{displayType:'ajax'}));return win;},openSpeedWinkDialog:function(context,continuationCallback){var content=("<h1 style='margin:20px;'>#{username}, SpeedWink for FREE - The fastest way to meet more #{people}!</h1>"+"<h2 style='margin:20px;' >Instantly wink at local matches who find you interesting!</h2>"+"<div style='margin:10px 0 20px 170px;' class='medium-green medium-button lib-trigger'>"+"    <span>"+"         <u>SpeedWink Now &raquo;</u>"+"    </span>"+"</div>"+"<div class='clear'></div>").interpolate({username:SD.Model.getMyself().username,people:SD.Model.getMyself().sex_pref=='M'?'men':'women'});var onSpeedWink=function(response){var message;if(response.status=='FAIL'){message=response.message||"SpeedWinking failed";}else{message="You have successfully SpeedWinked at some local matches!";}
SD.UIController.infoMessage(message,3);};var winConfig={title:'',content:content,width:500,draggable:false,top:100,template:SD.Window.newStyle,className:"generic-popup-container",groupId:'group4',onAfterClose:function(){continuationCallback&&continuationCallback();},parseLibrary:{'.lib-trigger':function(el,domRoot){el.onclick=function(){SD.SpeedWink.speedWink(onSpeedWink);this.close();}.bind(this);}}};SD.UIController.standardPopup(winConfig).open();},upgradeWarningPopup:function(dataObj){var dialog=SD.UIController.standardPopup({title:dataObj.dialogTitle,top:80,width:600,blocker:true});SD.TemplateStore.get('upgrade_to_template',function(data){var content=data;var upgradeMessage=SPAN({},dataObj.upgradeMessage).innerHTML;content=content.interpolate({upgradeMessage:upgradeMessage});dialog.domContent.insert(content);dialog.showCenter(true,100);dialog.domContent.select('.lib-upgrade-popup-link').first().onclick=SD.UIController.upgradeMyself.bind(SD.UIController,dataObj.upgradeArguments);});},showDateChatLog:function(link){var row=link.up('tr');var targetRow=$(row.up('table').rows[row.rowIndex+1]);var targetCell=targetRow.cells[0];if(!targetCell.innerHTML){new Ajax.Updater(targetCell,link.href);targetRow.show();link.innerHTML='Hide Chat History';}else{targetRow.hide();targetCell.update('');link.innerHTML='Show Chat History';}},androidDialog:function(){var winConfig={title:'Android App',content:"<p style='padding-top:10px;text-align:center'>"+"Scan this barcode<br>"+"<img src='http://qrcode.kaywa.com/img.php?s=5&d=market%3A%2F%2Fdetails%3Fid%3Dcom.nextmobileweb.speeddate'>"+"<br><br>"+"Or search Android Market for '<b>SpeedDate</b>'"+"</p>",top:100,contentWidth:220,draggable:true,className:"generic-popup-container",template:SD.Window.newStyle};this.standardPopup(winConfig).open();},searchSubmit:function(options){var form=$(options.form);var btn=$(options.btn);var loadingEl=$(options.loadingEl);SD.Event.observeOnce(null,SD.Nav.Events.HASH_CHANGE,function(){btn&&btn.hide();loadingEl&&loadingEl.show();});form&&SD.Nav.submitForm(form);},startConsole:function(){var domConsoleTrigger=document.createElement('div');domConsoleTrigger.style.cssText='z-index;80000;cursor:pointer;position:fixed;_position:absolute;bottom:50px;left:0;width:100px;height:30px;line-height:30px;text-align:center;background-color:#000000;color:#999999';domConsoleTrigger.innerHTML='console';domConsoleTrigger.onclick=function(){(Prototype.Browser.IE6||Prototype.Browser.IE7)?openInnerWindow():openWindow();}
document.body.appendChild(domConsoleTrigger);function openWindow(){window.open("/static/site/console/console.html","con","width=700,height=400");}
function openInnerWindow(){if(window.consoleWin){window.consoleWin.show();return;}
window.consoleWin=new SD.Window({groupId:'group5',title:"Console v0.1",content:'<iframe id="console-frame" src="/static/site/console/console.html" frameborder="0" noscroll="noscroll" width="100%" height="100%" '+'marginwidth="0" marginheight="0" hspace="0" vspace="0"></iframe>',width:960,height:420,draggable:true,resizable:true,closeMethod:"hide"}).open();}},popupTerms:function(){SD.UIController.popupStaticContent('Terms of Service',SD.NavUtils.link('site','get_terms'));},popupPrivacyPolicy:function(){SD.UIController.popupStaticContent('Privacy Policy',SD.NavUtils.link('site','get_policy'));},popupCCVInfo:function(){SD.UIController.popupStaticContent('CCV Info',SD.NavUtils.link('site','get_ccv_info'));},popupStaticContent:function(title,url,options){var winConfig=Object.extend({groupId:'group4',title:title,content:"<p class='sd-window-msg'>Loading...</p>",top:80,contentWidth:500,contentHeight:300,draggable:true,className:"generic-popup-container",template:SD.Window.newStyle,loader:{onContentRendered:function(){win.domContent.style.height=(winConfig.contentHeight+20)+'px';}}},options||{});var win=this.standardPopup(winConfig).open();win.domContent.style.overflow='auto';win.load(url);return win;},popupSpeedBump:function(){SD.SpeedBump.registerWin(this.popupStaticContent('&nbsp;',SD.NavUtils.link('signup','speed_bump_dialog'),{top:50,contentWidth:720,contentHeight:400,bindToWindowScroll:false,position:'absolute',className:"lib-window new-window no-header"}));},popupSpeedPlay:function(uid){uid=uid||(location.href.match(/speedPlayId=(\d*)/)||[])[1];return uid?SD.PreferenceAnalyzer.startSpeedPlay(uid):null;},dashboardPopup:function(){var winConfig={position:'absolute',blocker:true,bindToWindowScroll:false,enableYAdjustOnResize:false,groupId:'group4',title:'',content:"<p class='sd-window-msg'>Loading...</p>",top:80,contentWidth:630,draggable:true,className:"generic-popup-container",template:SD.Window.newStyle,range:{x1:-Infinity,x2:Infinity,y1:-Infinity,y2:Infinity},onAfterClose:function(){SD.Event.stopObserving(null,SD.UIController.Events.CLOSE_WELCOME_POPUP);},loader:{onParseElements:{'a':function(link){if(link.processed||link.rel=='nofollow'){return;}
link.processed=true;if(link.href&&link.href.indexOf("page=payment")==-1&&link.href.indexOf('javascript')!=0){link.href=SD.Nav.encode(link.href);}}}}};var win=this.standardPopup(winConfig).open();win.domContent.style.overflow='auto';win.load(SD.NavUtils.link('home','dashboard'));win.dom.addClassName('dashboard');SD.Event.observe(null,SD.UIController.Events.CLOSE_WELCOME_POPUP,function(){win.close();});win.dom.observe('click',function(e){if((e.target||e.srcElement).tagName.toLowerCase()=='a'){win.close();}});return win},startFirstTimeUXForWomen:function(){var showSearchTutorialAction=new SD.Action({id:'showSearchTutorialAction',async:true,callFunc:function(context,runnable){var continuationCallback=SD.Actions._continuationCallback.bind(SD.Actions,runnable);try{var searchGoal=SD.UI.GoalBar.Manager.goalsArray.filter(function(goal){return(goal instanceof SD.Goals.TutorialSearch)&&goal.state=='not_completed';});if(searchGoal[0]){searchGoal[0].start();SD.Event.observeOnce(null,SD.TutorialManager.Events.TUTORIAL_STOPPED,function(e){continuationCallback();});}else{continuationCallback();}}catch(e){continuationCallback();}}});var pauseDatesWatchDog;SD.UIController.canSaveFilterGuard=false;SD.Event.observe(null,SD.UIController.Events.ABOUT_ME_FLOW_LOADED,function(e){console.log(e.memo.page)});var womenUxFlow=new SD.Flow({id:'womenUxFlow',runnables:[function(){pauseDatesWatchDog=setInterval(function(){if(SD.UserFilters.UI.state=='running'){SD.XMPP.getFlash()&&SD.UserFilters.UI.pauseSpeedDating();}},1000);},SD.Actions.aboutMeDialog.clone(),SD.Actions.uploadPhotoDialogTutorial.clone({rules:{'I do not have a photo':function(){return!SD.Model.getMyself().has_photo},'PostSignupUXForWomen_4135 is option 1':function(){return SD.ExperimentManager.PostSignupUXForWomen_4135.value==1}}}),function(){clearInterval(pauseDatesWatchDog);SD.UIController.canSaveFilterGuard=true;SD.UserFilters.UI.startSpeedDating();},function(){SD.NavUtils.goTo('members','search',{'s_p':1});SD.Cookie.erase('PostSignupUXForWomen_4135');}]});console.log('startFirstTimeUXForWomen');SD.FlowManager.run(womenUxFlow,{sourceType:SD.UIController.PopupSourceTypes.POST_SIGNUP_WOMEN_UX,modTooltip:false});},emailVerificationTooltip:function(context,continuationCallback){if(!context.sourceElement){console.log('Missing domEvent in the flow context object');continuationCallback&&continuationCallback();return null;}
var ids=SD.Utils.IdGenerator.generateCollection('mainSectionId','infoSectionId','errorSectionId','emailInputId','submitId','resultSectionId','tryAgainLinkId');var registeredSections={'main':ids.mainSectionId,'info':ids.infoSectionId,'error':ids.errorSectionId,'result':ids.resultSectionId};var mainTemplate='<div class="thumbnail-left"></div>'+'<div style="margin:10px 10px 10px 70px">'+'<div id="#{infoSectionId}"   class="text section-top" style="display:none;padding:40px 0">Please wait ... </div>'+'<div id="#{errorSectionId}"  class="text section-top" style="color:red;display:none"></div>'+'<div id="#{resultSectionId}" class="text section-top" style="display:none"></div>'+'<div id="#{mainSectionId}" class="section-top-base">'+'<div class="text">'+'<div style="margin-bottom:10px;margin-right:15px;">#{text}</div>'+'<div><input style="width:205px;margin-left: 23px;" class="input-field" id="#{emailInputId}" spellcheck="false" value="#{email}"></div>'+'</div>'+'<div id="#{submitId}" class="small-green small-button tt-button" style="float:left;margin:5px 0 0 23px;position:relative" >'+'<span><u>Verify my Email &raquo;</u></span>'+'</div>'+'<div class="clear"></div>'+'</div>'+'</div>';var resultTemplate='<div class="text" style="margin-bottom:10px;">#{title}</div>'+'<div class="text">#{message}</div>';var successMessages={titles:{otherProvider:'Thanks! Check your inbox for the confirmation email.',provider:'Thanks! We sent you an email to #{email}.'},message:'If the address <b>#{email}</b> is incorrect, you can <span id="#{tryAgainLinkId}" class="fake-link">try again</span>'};var ctx=SD.Utils.mixin({},context,{sourceCmd:'VERIFY_EMAIL'});var send=function(){var validation=validate();if(!validation.isValid){showError(validation.message);return;}
new Ajax.Request(SD.NavUtils.link('profile','save_email_verification_popup'),{method:"post",evalJSON:true,parameters:{email:$(ids.emailInputId).value,responseType:'json',sourceType:ctx.sourceType||'',sourceMemberId:ctx.sourceMemberId||''},onSuccess:function(response){var data=response.responseJSON||{};if(data.result=='success'){populateResultSection(data);SD.Utils.UI.showSections(registeredSections,'result');}else if(data.result=='fail'){if(data.result.errors&&data.result.errors[0]){showError(data.result.errors[0]);}else{showError('There was a problem with your request.');}}},onError:function(){showError('We are sorry, but we could not process your request at this time.<br><br>Please try again later');}});};var validate=function(){var email=$(ids.emailInputId).value=$(ids.emailInputId).value.trim();if(!SD.Utils.Validators.isEmail(email)){return{message:'Please enter a valid email address.',isValid:false};}
return{isValid:true};};var populateResultSection=function(data){var msg=resultTemplate.interpolate({title:data.provider=='other'?successMessages.titles.otherProvider.interpolate({email:data.email}):successMessages.titles.provider.interpolate({email:data.email}),message:successMessages.message.interpolate({email:data.email,tryAgainLinkId:ids.tryAgainLinkId})});$(ids.resultSectionId).update(msg);$(ids.tryAgainLinkId)&&($(ids.tryAgainLinkId).onclick=function(){SD.Utils.UI.showSections(registeredSections,'main');});};var showError=function(error){$(ids.errorSectionId).update(error);SD.Utils.UI.showSections(registeredSections,'main','error');};SD.UI.Messages.Tooltips.getMessage(ctx,function(message){SD.TooltipDialog.create({refPoint:{x:context.pageX,y:context.pageY},refDom:context.sourceElement,width:340,loader:{content:mainTemplate.interpolate(SD.Utils.mixin({},ids,{text:message,email:SD.Model.getMyself().email})),onContentRendered:function(){$(ids.submitId).onclick=function(){SD.Utils.UI.showSections(registeredSections,'info');send();}}}},continuationCallback);});},fullAboutMeTooltip:function(context,continuationCallback){SD.Dialog.ProfileTwoQuestionsTooltip.open(context,continuationCallback);},speedVerifyTooltip:function(context,continuationCallback){if(!context.sourceElement){console.log('Missing domEvent in the flow context object');continuationCallback&&continuationCallback();return null;}
var ids=SD.Utils.IdGenerator.generateCollection('submitId');var mainTemplate='<table cellpadding="0" cellspacing="0" class="section-table">'+'<tr>'+'<td colspan="2">'+'<div class="title-text" style="padding-left:62px;height:30px;font-weight:bold;font-size:14px;color:#53BC00;margin:10px 30px 0 0;line-height:30px;">'+'Verify<span style="position:relative;top:-5px;font-size:70%">TM</span> Your Profile to Continue'+'</div>'+'</td>'+'</tr>'+'<tr>'+'<td class="left-subsection"></td>'+'<td valign="center" style="padding-bottom:10px;">'+'<div class="section">'+'<div class="right-subsection">'+'<div class="text green-subsection" style="padding:10px;margin:10px 38px 0 20px;">'+'<table cellpadding="3" cellspacing="0">'+'<tr><td><div class="checkmark-item"><div class="goal-completed-icon-check-mini"></div>Authenticated profile</div></td></tr>'+'<tr><td><div class="checkmark-item"><div class="goal-completed-icon-check-mini"></div>Priority in search results</div></td></tr>'+'<tr><td><div class="checkmark-item"><div class="goal-completed-icon-check-mini"></div>See who emailed you</div></td></tr>'+'</table>'+'</div>'+'<div style="margin:10px 0 0 55px;position:relative;color:#53BC00;font-weight:bold" >'+'Only <span style="font-size:16px">$3<span style="position:relative;top:-5px;font-size:70%">.95</span></span>/month'+'</div>'+'<div id="#{submitId}" class="medium-green medium-button tt-button" style="margin:10px 0 0 20px;position:relative" >'+'<span>'+'<u>Verify<nobr style="position:relative;top:-5px;font-size:70%">TM</nobr> My Profile &raquo;</u>'+'</span>'+'</div>'+'</div>'+'<div class="thumbnail-left"></div>'+'</div>'+'</td>'+'</tr>'+'</table>'+'<div class="speedverify-star"></div>';var tooltip=SD.TooltipDialog.create({refPoint:{x:context.pageX,y:context.pageY},refDom:context.sourceElement,width:330,className:"generic-popup-container tooltip-dialog",loader:{content:mainTemplate.interpolate(SD.Utils.mixin({},ids)),onContentRendered:function(){$(ids.submitId).onclick=function(){tooltip.close();context.expandedMode=SD.Exp.getValue('SpeedVerifyTooltip_SDWEB263');SD.UIController.speedVerifyPopup(context);}}}},continuationCallback);},subscribeTooltip:function(context,continuationCallback){if(!context.sourceElement){console.log('Missing domEvent in the flow context object');continuationCallback&&continuationCallback();return null;}
var ids=SD.Utils.IdGenerator.generateCollection('submitId');var mainTemplate='<table cellpadding="0" cellspacing="0" class="section-table">'+'<tr>'+'<td colspan="2">'+'<div class="title-text" style="padding-left:62px;height:30px;font-weight:bold;font-size:14px;color:#F6871E;margin:10px 30px 0 0;line-height:30px;">'+'Subscribe to continue'+'</div>'+'</td>'+'</tr>'+'<tr>'+'<td class="left-subsection"></td>'+'<td valign="center" style="padding-bottom:10px;">'+'<div class="section">'+'<div class="right-subsection">'+'<div class="text orange-subsection" style="padding:10px;margin:10px 10px 0 0;">'+'<table cellpadding="3" cellspacing="0">'+'<tr>'+'<td><div class="checkmark-item"><div class="goal-completed-icon-check-mini"></div>Full Email Access</div></td>'+'<td style="padding-left:10px;"><div class="checkmark-item"><div class="goal-completed-icon-check-mini"></div>Rank Higher</div></td>'+'</tr>'+'<tr>'+'<td><div class="checkmark-item"><div class="goal-completed-icon-check-mini"></div>Unlimited Chat</div></td>'+'<td style="padding-left:10px;"><div class="checkmark-item"><div class="goal-completed-icon-check-mini"></div>More Control</div></td>'+'</tr>'+'</table>'+'</div>'+'<div id="#{submitId}" class="medium-orange medium-button tt-button" style="margin:10px 0 0 60px;position:relative" >'+'<span>'+'<u>Continue &raquo;</u>'+'</span>'+'</div>'+'</div>'+'<div class="thumbnail-left"></div>'+'</div>'+'</td>'+'</tr>'+'</table>'+'<div class="subscribe-star"></div>';var tooltip=SD.TooltipDialog.create({refPoint:{x:context.pageX,y:context.pageY},refDom:context.sourceElement,width:340,className:"generic-popup-container tooltip-dialog mod-orange-border",fxShimClassName:"effect-tt-shim-orange effect-tt-shim",loader:{content:mainTemplate.interpolate(SD.Utils.mixin({},ids)),onContentRendered:function(){$(ids.submitId).onclick=function(){tooltip.close();SD.UIController.upgradeMyself({tc:context.tc,sourceType:context.sourceType,sourceMemberId:context.sourceMemberId,expandedMode:false},context.dontCheckSegment,context.usePreviousParams,continuationCallback);}}}},continuationCallback);},fbShareTooltip:function(context,continuationCallback){if(!context.sourceElement){console.log('Missing domEvent in the flow context object');continuationCallback&&continuationCallback();return null;}
var tooltipWin=SD.TooltipDialog.create({refPoint:{x:context.pageX,y:context.pageY},refDom:context.sourceElement,content:'<div style="padding:20px;text-align:center">Loading...</div>',width:350,url:SD.NavUtils.link('profile','facebook_share_popup',{sourceMemberId:'',sourceType:'',actionType:SD.UIController.ActionTypes.SHARE_PROFILE,actionData:'{"sharedMemberId" : "'+context.sourceMemberId+'"}',view:'tooltip',displayType:'ajax'}),loader:{onParseElements:{'.lib-fb-button':function(shareBut,domRoot){shareBut.onclick=function(){var domForm=domRoot.select('form')[0];domForm&&domForm.id&&SD.UI.DateUI.shareWithFacebook(domForm.id);}},'.lib-close':function(closeBut){closeBut.onclick=function(){tooltipWin.close();}},'form':function(domForm,domRoot){domForm.submit=domForm.request.bind(domForm,{onComplete:function(){tooltipWin.loader.loadContent('<div style="text-align:center;margin-top:20px">The profile was successfully shared!</div>'+'<div class="lib-close fake-link" style="margin-top:25px;text-align:center;cursor:pointer">Close</div>');}});}}}},continuationCallback);return tooltipWin;},fillProfilePrompt:function(context,continuationCallback){if(!context.sourceElement){console.log('Missing domEvent in the flow context object');continuationCallback&&continuationCallback();return null;}
var tooltipWin=SD.TooltipDialog.create({refDom:context.sourceElement,content:'<div style="padding:20px;text-align:center">Loading...</div>',width:350,url:SD.NavUtils.link('profile','facebook_share_popup',{sourceMemberId:'',sourceType:'',actionType:SD.UIController.ActionTypes.SHARE_PROFILE,actionData:'{"sharedMemberId" : "'+context.sourceMemberId+'"}',view:'tooltip',displayType:'ajax'}),loader:{onParseElements:{'.lib-fb-button':function(shareBut,domRoot){shareBut.onclick=function(){var domForm=domRoot.select('form')[0];domForm&&domForm.id&&SD.UI.DateUI.shareWithFacebook(domForm.id);}},'.lib-close':function(closeBut){closeBut.onclick=function(){tooltipWin.close();}},'form':function(domForm,domRoot){domForm.submit=domForm.request.bind(domForm,{onComplete:function(){tooltipWin.loader.loadContent('<div style="text-align:center;margin-top:20px">The profile was successfully shared!</div>'+'<div class="lib-close fake-link" style="margin-top:25px;text-align:center;cursor:pointer">Close</div>');}});}}}},continuationCallback);return tooltipWin;},imTooltip:function(context,continuationCallback){if(!context.sourceElement){console.log('Missing domEvent in the flow context object');continuationCallback&&continuationCallback();return null;}
var tooltip;var ids=SD.Utils.IdGenerator.generateCollection('imId','protocolId','mainId','messageHolderId','resultId','resultHolderId','errorId','errorHolderId','submitId','loadingId','cancelId','dontAskId');var sections={'main':ids.mainId,'result':ids.resultHolderId,'error':ids.errorHolderId,'loading':ids.loadingId};var descriptionMessageTemplate="Get notified when <b>#{username}</b> signs online with SpeedDate IM alerts ("+"<a href='javascript:void(0)' sdType='tooltip'"+"sdMessage='SpeedDate will notify you via IM when people you like and potential matches are online."+"Your IM will not be shared with anyone. You can adjust your IM preferences in account preferences panel.'>?</a>)";var mainTemplate='<table cellpadding="0" cellspacing="0" class="section-table">'+'<tr>'+'<td class="left-subsection"></td>'+'<td valign="center">'+'<div class="section" style="padding-right:23px;">'+'<div id="#{errorHolderId}" class="right-subsection" style="display:none;margin:10px 0">'+'<span id="#{errorId}" class="error-text"></span>'+'</div>'+'<div id="#{mainId}" class="right-subsection">'+'<div id="#{messageHolderId}" class="text">'+'<div class="title-text" style="font-weight:bold;margin:10px 0;">#{message}</div>'+'<div class="text" style="margin:10px 0;">#{descriptionMessage}</div>'+'<table border="0">'+'<tr>'+'<td valign="middle" style="height:25px;padding-right:5px;">'+'IM Name:'+'</td>'+'<td valign="middle">'+'<input style="width:140px" class="input-field" id="#{imId}">'+'</td>'+'</tr>'+'<tr>'+'<td valign="middle" style="height:25px;padding-right:5px;">'+'On:'+'</td>'+'<td valign="middle">'+'<select class="select-input" id="#{protocolId}" style="width:144px">'+'<option value="">Select</option>'+'<option value="msn">MSN</option>'+'<option value="yahoo">Yahoo</option>'+'<option value="gtalk">GTalk/GChat</option>'+'<option value="aim">AIM</option>'+'</select>'+'</td>'+'</tr>'+'</table>'+'</div>'+'<div id="#{submitId}" class="small-green small-button" style="float:left;margin:5px 0;position:relative" >'+'<span style="padding:0 15px">'+'<u>Submit &raquo;</u>'+'</span>'+'</div>'+'<div id="#{dontAskId}" class="fake-link" style="float:left;margin-top:5px;margin-left:15px;line-height:25px;">Don\'t ask me</div>'+'</div>'+'<div id="#{resultHolderId}" class="right-subsection" style="display:none">'+'<span id="#{resultId}"></span>'+'</div>'+'<div id="#{loadingId}" class="right-subsection" style="display:none">'+'<div class="text" style="padding-top:23px;display:none">Please wait ... </div>'+'</div>'+'<div class="thumbnail-left"></div>'+'</div>'+'</td>'+'</tr>'+'</table>';var showError=function(message){$(ids.errorId).update(message);SD.Utils.UI.showSections(sections,'main','error');};var showLoading=function(){SD.Utils.UI.showSections(sections,'loading');};var showResult=function(message){$(ids.resultId).update(message);SD.Utils.UI.showSections(sections,'result');};var validate=function(){var isValid=true;$(ids.imId).value=$(ids.imId).value.trim();if(!$(ids.imId).value.trim()){isValid=false;showError("Please specify your instant messenger name.");}else if($(ids.protocolId).value==''){isValid=false;showError("Please specify your instant messenger service.");}
return isValid;};var onSuccess=function(response){if(response.responseJSON.result==false){showError(response.responseJSON.error||'We could not save your data.');}else{showResult('You have successfully configured your instant messenger settings.')}};var onFail=function(){showError('There has been a problem saving your instant messenger settings.');};var send=function(){if(!validate())return;var me=SD.Model.getMyself();new Ajax.Request(SD.NavUtils.link('ajax','submit_im'),{method:'post',parameters:{protocol:$(ids.protocolId).value,im:$(ids.imId).value,mimId:me.ims.length?me.ims[0]._id.value:null},onSuccess:onSuccess,onFailure:onFail});showLoading();};var setup=function(){if($(ids.submitId)){$(ids.submitId).onclick=send;}
if($(ids.cancelId)){$(ids.cancelId).onclick=function(){tooltip.close();};}
if($(ids.dontAskId)){$(ids.dontAskId).onclick=function(){SD.Notification.IM.shouldAsk=false;tooltip.close();};}};var ctx=SD.Utils.mixin({},context,{sourceCmd:'IM',actionMode:'post'});SD.User.fetch(ctx.sourceMemberId,function(user){SD.UI.Messages.Tooltips.getMessage(ctx,function(message){var descriptionMessage=descriptionMessageTemplate.interpolate({username:user.username});tooltip=SD.TooltipDialog.create({refPoint:{x:context.pageX,y:context.pageY},refDom:context.sourceElement,width:350,loader:{content:mainTemplate.interpolate(SD.Utils.mixin({message:message,descriptionMessage:descriptionMessage},ids)),onContentRendered:setup}},continuationCallback);});});return tooltip;},phoneNumberTooltip:function(context,continuationCallback){if(!context.sourceElement){continuationCallback&&continuationCallback();return;}
var ids=SD.Utils.IdGenerator.generateCollection('formId','topTextHolderId','textHolderId','textHolderLoadingId');var inputLabel='Your mobile number';var errorMessage='<div style="color:red">Invalid Phone Number</div>';var topSection='<div class="section-top">'+'<div class="text" id="#{topTextHolderId}">#{text}</div>'+'</div>';var mainSection='<form id="#{formId}" method="post" action="#{formUrl}" method="post">'+'<table cellpadding="0" cellspacing="0" class="section-table">'+'<tr>'+'<td class="left-subsection"></td>'+'<td valign="center">'+'<div class="section">'+'<div class="right-subsection">'+'<div id="#{textHolderId}" class="text" style="">'+'<div style="font-weight:bold;margin-bottom:5px;">#{text}</div>'+'<div><input style="width:140px" class="input-field" name="phone-number" id="phone-number"></div>'+'</div>'+'<div id="#{textHolderLoadingId}" class="text" style="display:none">Please wait ... </div>'+'<div class="small-green small-button tt-button lib-submit" style="float:left;margin:5px 0 10px 0;position:relative" >'+'<span>'+'<u>Submit &raquo;</u>'+'</span>'+'</div>'+'</div>'+'<div class="thumbnail-left"></div>'+'</div>'+'</td>'+'</tr>'+'</table>'+'</form>';var ctx=SD.Utils.mixin({},context,{sourceCmd:'ADD_PHONE'});SD.UI.Messages.Tooltips.getMessage(ctx,function(message){SD.TooltipDialog.create({refPoint:{x:context.pageX,y:context.pageY},refDom:context.sourceElement,width:350,loader:{content:topSection.interpolate(SD.Utils.mixin({text:message},ids))+
mainSection.interpolate(SD.Utils.mixin({text:inputLabel,formUrl:SD.NavUtils.link('profile','phone_number_popup',{responseType:'json',isSubmitted:1})},ids)),onParseJson:{result:{_success:function(value){SD.Model.getMyself().has_phone=true;SD.Event.fire(null,SD.UIController.Events.PHONE_VERIFIED);this.dialog.close();},_fail:function(value){$(ids.topTextHolderId).update(errorMessage);$(ids.textHolderId).show();$(ids.textHolderLoadingId).hide();}}},onParseElements:{'.lib-submit':function(el){el.onclick=function(){$(ids.textHolderId).hide();$(ids.textHolderLoadingId).show();$(ids.formId).submit();}}}}},continuationCallback);});},aboutMeTooltip:function(context,continuationCallback){if(!context.sourceElement){console.log('Missing domEvent in the flow context object');continuationCallback&&continuationCallback();return;}
if(context.dialogRole=='fillProfilePrompt'){SD.WindowManager.getItemsAsArray().each(function(win){if(win.role=='fillProfilePrompt'){win.close();}});}
var ids=SD.Utils.IdGenerator.generateCollection('submitId');var mainTemplate='<table cellpadding="0" cellspacing="0" class="section-table">'+'<tr>'+'<td class="left-subsection"></td>'+'<td valign="center" style="padding-bottom:10px;">'+'<div class="section">'+'<div class="right-subsection">'+'<div class="text" style="padding:0 30px 10px 0;">#{text}</div>'+'<div id="#{submitId}" class="small-green small-button tt-button" style="margin:0 5px 0 23px;position:relative" >'+'<span>'+'<u><nobr>Update My Profile &raquo;</nobr></u>'+'</span>'+'</div>'+'</div>'+'<div class="thumbnail-left"></div>'+'</div>'+'</td>'+'</tr>'+'</table>';var ctx=SD.Utils.mixin({},context,{sourceCmd:'FILL_OUT_PROFILE'});SD.UI.Messages.Tooltips.getMessage(ctx,function(message){if(context.dialogRole=="fillProfilePrompt"){message='<div class="tip"><b>Tip</b>: Fill in more of your profile to see this profile section.</div>';}
var tooltip=SD.TooltipDialog.create({role:context.dialogRole,refPoint:{x:context.pageX,y:context.pageY},refDom:context.sourceElement,width:355,loader:{content:mainTemplate.interpolate(SD.Utils.mixin({},ids,{text:message})),onContentRendered:function(){$(ids.submitId).onclick=function(){tooltip.close();SD.UIController.aboutMePopup(context,continuationCallback);}}}},Prototype.emptyFunction());});},speedWinkTooltip:function(context,continuationCallback){if(!context.sourceElement){console.log('Missing domEvent in the flow context object');continuationCallback&&continuationCallback();return;}
var ids=SD.Utils.IdGenerator.generateCollection('submitId','mainSectionId','resultSectionId');var mainTemplate='<table cellpadding="0" cellspacing="0" class="section-table">'+'<tr>'+'<td class="left-subsection"></td>'+'<td valign="center" style="padding:10px 10px 10px 0">'+'<div class="section">'+'<div id="#{resultSectionId}" class="right-subsection" style="display:none"></div>'+'<div id="#{mainSectionId}" class="right-subsection">'+'<div class="title-text" style="padding:0 10px 10px 0;">#{text}</div>'+'<div class="text">'+'<h1 style="margin-bottom:10px">#{username}, SpeedWink for FREE!</h1>'+'It is the fastest way to meet more #{people}! Instantly wink at local matches!'+'</div>'+'<div id="#{submitId}" class="medium-green medium-button tt-button" style="margin:10px 0 0 0;position:relative" >'+'<span>'+'<u>SpeedWink Now &raquo;</u>'+'</span>'+'</div>'+'</div>'+'<div class="thumbnail-left"></div>'+'</div>'+'</td>'+'</tr>'+'</table>';var onSpeedWink=function(response){var message=response.status=='FAIL'?(response.message||"SpeedWinking failed."):"You have successfully SpeedWinked at some local matches!";$(ids.resultSectionId).update(message).show();$(ids.mainSectionId).hide();};var ctx=SD.Utils.mixin({},context,{sourceCmd:'FILL_OUT_PROFILE',actionMode:'post'});SD.UI.Messages.Tooltips.getMessage(ctx,function(message){SD.TooltipDialog.create({refPoint:{x:context.pageX,y:context.pageY},refDom:context.sourceElement,width:380,loader:{content:mainTemplate.interpolate(SD.Utils.mixin({},ids,{text:message,people:SD.Model.getMyself().sex_pref=='M'?'men':'women',username:SD.Model.getMyself().username})),onContentRendered:function(){$(ids.submitId).onclick=function(){SD.SpeedWink.speedWink(onSpeedWink);}}}},continuationCallback);});},uploadPhotoTooltip:function(context,continuationCallback){if(!context.sourceElement){console.log('Missing domEvent in the flow context object');continuationCallback&&continuationCallback();return;}
var ids=SD.Utils.IdGenerator.generateCollection('fbButId','fbProgressId','textHolderId','textHolderLoadingId','formId','errHolder','fileInput','btnHolderId');var fbLogin=0;var callbackName='__cb__'+(new Date().getTime());var mainSection='<div style="padding:5px 10px 8px 0">'+'<form id="#{formId}" class="lib-photo-upload-simple" method="post" action="#{formUrl}" enctype="multipart/form-data" method="post">'+'<input type="hidden" name="upload_from_popup" value="1" >'+'<input type="hidden" name="edit_photo_popup" value="1" >'+'<input type="hidden" name="sourceType" value="#{sourceType}">'+'<input type="hidden" name="sourceMemberId" value="#{sourceMemberId}">'+'<input type="hidden" name="responseType" value="json">'+'<input type="hidden" name="jscallback" value="parent.SD.UIController.'+callbackName+'">'+'<input type="submit" class="popup-upload-photo-btn" value="Upload">'+'<table cellpadding="0" cellspacing="0" class="section-table">'+'<tr>'+'<td class="left-subsection"></td>'+'<td valign="center">'+'<div class="section">'+'<div class="right-subsection">'+'<div class="text" style="margin-right: 25px;">#{text}</div>'+'<div id="#{errHolder}" class="red-box" style="display:none;margin:10px 0"></div>'+'<div id="#{textHolderId}" class="text" style="padding-top:10px;">'+'<ul class="bullet-list">'+'<li>No nudity or offensive material</li>'+'<li>No group photos, just YOU, for your main profile picture</li>'+'<li>Upload more photos!</li>'+'</ul>'+'</div>'+'<div id="#{textHolderLoadingId}" class="text" style="padding-top:10px;display:none">Please wait ... </div>'+'<div id="#{btnHolderId}">'+'<div class="small-green small-button tt-button" style="margin:10px 5px 0 0;position:relative" >'+'<span>'+'<u>Upload Photo &raquo;</u>'+'</span>'+'<input name="photo" id="#{fileInput}" type="file" style="-moz-opacity:0; filter:alpha(opacity:0); position: absolute; right: 0pt; top: 0pt; font-family: Arial; font-size: 30px; margin: 0pt; padding: 0pt; cursor: pointer; opacity: 0;">'+'</div>'+'<div class="clear"></div>'+'<div id="#{fbButId}" class="fake-link" style="margin:5px 0 0 0px; z-index:10000;position:relative;line-height:16px;height:16px;padding-left:20px;padding-top:2px;border-top:1px solid #CCC">'+'<div class="fb-icon-16x16" style="position:absolute;top:2px;left:0"></div>'+'Use a FaceBook photo'+'</div>'+'<div id="#{fbProgressId}" style="margin-top:10px 0 0 10px;display:none;text-align:center">Fetching FB Photos ...</div>'+'</div>'+'</div>'+'<div class="thumbnail-left"></div>'+'</div>'+'</td>'+'</tr>'+'</table>'+'</form>'+'</div>';var ctx=SD.Utils.mixin({},context,{sourceCmd:'UPLOAD_PHOTO'});var tooltip;SD.UIController[callbackName]=function(jsonData){if(jsonData.result=='success'){SD.Event.fire(null,SD.UIController.Events.PHOTO_UPLOADED,{hasPhoto:1,photoUrl:jsonData.photoUrl,photoBigUrl:jsonData.photoBigUrl});delete SD.UIController[callbackName];tooltip.close();}else{$(ids.errHolder).update(jsonData.messages.map(function(msg){return'<div>'+msg+'</div>'})).show();$(ids.textHolderLoadingId).hide();$(ids.textHolderId).show();$(ids.btnHolderId).show();$(ids.fileInput).disabled=false;}};continuationCallback=SD.Utils.connect(continuationCallback,function(){delete SD.UIController[callbackName]});SD.UI.Messages.Tooltips.getMessage(ctx,function(message){tooltip=SD.TooltipDialog.create({refPoint:{x:context.pageX,y:context.pageY},refDom:context.sourceElement,width:360,loader:{content:mainSection.interpolate(SD.Utils.mixin({text:message,formUrl:SD.NavUtils.link('profile','save_photo'),sourceMemberId:context.sourceMemberId||'',sourceType:context.sourceType||''},ids)),onContentRendered:function(){$(ids.fbButId)&&($(ids.fbButId).onclick=function(){fbImport();});$(ids.fileInput)&&($(ids.fileInput).onchange=function(){$(ids.textHolderId).hide();$(ids.btnHolderId).hide();$(ids.textHolderLoadingId).show();$(ids.formId).submit();})}}},continuationCallback);});var fbImport=function(){$(ids.fbButId).hide();$(ids.fbProgressId).show();FB.XFBML.parse();SD.XConnect.openFacebookAuthenticate(function(result){if(result){fbLogin=1;fbSave();}},{'skipPhotoSave':1});}
var fbSave=function(){new Ajax.Request(SD.NavUtils.link('profile','save_fb_photo_from_popup'),{method:"post",evalJSON:true,parameters:{displayType:'ajax',responseType:'json',sourceType:ctx.sourceType||'',sourceMemberId:ctx.sourceMemberId||'',fbLogin:fbLogin},onSuccess:function(response){var data=response.responseJSON||{};if(data.result=='success'){showResult('Successfully imported Facebook photos');}else if(data.result=='fail'){if(data.result.errors&&data.result.errors[0]){showError(data.result.errors[0]);}else{showError('There was a problem while fetching your photos.');}}},onError:function(){showError('There was a problem while fetching your photos.');}});}
var showError=function(msg){$(ids.fbButId).hide();$(ids.fbProgressId).update(msg).show();}
var showResult=showError;},__url_subscribeFromSignup:function(tc){SD.UIController.upgradeMyself({'memberid':SD.Model.getMyself().uid,'tc':tc});},Events:{START_CHAT_REQUESTED:"SD.UIController.Events:START_CHAT_REQUESTED",SEND_FLIRT_REQUESTED:"SD.UIController.Events:SEND_FLIRT_REQUESTED",FLIRT_WINK_DISPLAYED:"SD.UIController.Events:FLIRT_WINK_DISPLAYED",VIEW_PROFILE_REQUESTED:"SD.UIController.Events:VIEW_PROFILE_REQUESTED",BLOCK_BUDDY_REQUESTED:"SD.UIController.Events:BLOCK_BUDDY_REQUESTED",REPORT_USER_REQUESTED:"SD.UIController.Events:REPORT_USER_REQUESTED",START_FEEDBACK_REQUESTED:"SD.UIController.Events:START_FEEDBACK_REQUESTED",ADD_BUDDIES_REQUESTED:"SD.UIController.Events:ADD_BUDDIES_REQUESTED",SWITCHED_TO_OTHER_TABS:"SD.UIController.Events:SWITCHED_TO_OTHER_TABS",SWITCHED_TO_SPEEDDATE:"SD.UIController.Events:SWITCHED_TO_SPEEDDATE",CLOSE_WELCOME_POPUP:"SD.UIController.Events:CLOSE_WELCOME_POPUP",PHOTO_UPLOADED:"SD.UIController.Events:PHOTO_UPLOADED",INITIALIZATION_COMPLETE:"SD.UIController.Events:INITIALIZATION_COMPLETE",LAYOUT_UPDATED:"SD.UIController.Events:LAYOUT_UPDATED",SEARCH_CONTEXT_UPDATED:"SD.UIController.Events:SEARCH_CONTEXT_UPDATED",DATING_FILTERS_UPDATED:"SD.UIController.Events:DATING_FILTERS_UPDATED",BALANCE_UPDATED:"SD.UIController.Events:BALANCE_UPDATED",STORY_SUBMITTED:"SD.UIController.Events:STORY_SUBMITTED",SUBSCRIPTION_CANCELED:"SD.UIController.Events:SUBSCRIPTION_CANCELED",SUBSCRIPTION_PAUSED:"SD.UIController.Events:SUBSCRIPTION_PAUSED",SUBSCRIPTION_REACTIVATED:"SD.UIController.Events:SUBSCRIPTION_REACTIVATED",INVITED_FRIENDS:"SD.UIController.Events:INVITED_FRIENDS",ABOUT_ME_FLOW_LOADED:"SD.UIController.Events:ABOUT_ME_FLOW_LOADED",REQUEST_RESUB_POPUP_CLOSE:"SD.UIController.Events:REQUEST_RESUB_POPUP_CLOSE",PHONE_VERIFIED:"SD.UIController.Events:PHONE_VERIFIED",POPUP_FLOW_REQUEST:"SD.UIController.Events:POPUP_FLOW_REQUEST"},DateStates:{HIDDEN:"hidden",NORMAL:"normal",DATING:"dating",TABOTHER:"tabother",TABOTHERDATING:"tabotherdating"},PopupSourceTypes:{EMAIL:1,WINK:2,DATE:3,CHAT:4,MULTIPLE_PHOTO:5,MESSAGE_READ:6,RATING:7,CHAT_ATTEMPT:8,MESSAGE_ATTEMPT:9,TAG:10,VIEWED_YOU:11,ACCESS_TAB:12,CONTACT:13,SUBSCRIPTION_BUTTON:14,VERIFIED_BADGE:15,VIEW_MAIL_ATTEMPT:16,TEST_DRIVE:17,ADD_TO_FAVORITES:18,VIEW_CONVERSATION:19,FAVORITED_YOU:20,REQUESTED_TO_SPEEDDATE:21,EMAILED_YOU:22,NO_SOURCE:23,RATED_YOU:24,CHOSE_YOU:25,VC_INVITATION:26,VC_BUTTON:27,CONTACT_UPSELL:28,VIEW_VIRAL_QUIZ:29,SIGNUP_FLOW:30,GOAL_PHOTO_UPLOAD:31,GOAL_VERIFY_EMAIL:32,GOAL_MEMBER_INFO:33,GOAL_SMS:34,POST_SIGNUP_WOMEN_UX:35,INBOX:36,CONNECTIONS:37,DATING_LIST:38,INVITE_TO_DATE:39,GOAL_MEMBER_INFO_PROMPT:42},ActionTypes:{REGULAR_INVITATION:1,SHARE_PROFILE:2,VIEW_VIRAL_QUIZ:3,FLIRT:4,WINK:5,DATE:6,BROWSE_PROFILE:7,REFER_FRIENDS:8}};Object.extend(SD.UIController,(function(){var domStyle;return{enableSubBadges:function(){if(domStyle){domStyle.parentNode.removeChild(domStyle);}
domStyle=null;},disableSubBadges:function(){if(domStyle)return;var cssText='.subscribe-icon, .inline-subscribe-icon, .inline-subscribe-icon-small {'+'display:none !important;'+'}'+'body.site #container .secondary-navigation li.premium-feature2 a,'+'body.site #container .secondary-navigation li.premium-feature2 a:hover { '+'background-image: none !important;'+'}'+'.submenu-wrapper .grey-out {'+'color:#000000 !important;'+'}';domStyle=SD.Utils.Dom.injectCSS(cssText);},getInlineSubBadge:function(label){label=label||'';return'<span class="inline-subscribe-icon-small"></span> '+label+' ';}}})());(function(){var originalSend,originalClick,manager;var checkNum=0;var maxCheckNum=120;var checkInterval=1;function resolveCE(page,action){if(!manager.isSetup){manager.setup();}
if(page=='speeddate'){manager.enable();}else{manager.disable();}}
function init(){new PeriodicalExecuter(function(pe){if(manager.isReady()){pe.stop();resolveCE(SD.Nav.oHash.page,SD.Nav.oHash.action);}
checkNum++;if(checkNum>maxCheckNum){pe.stop();}},checkInterval);SD.Event.observe(null,SD.Nav.Events.HASH_CHANGE,function(e){if(manager.isReady()&&e&&e.memo){resolveCE(e.memo.hashNew.page,e.memo.hashNew.action);}});}
$(document).observe('dom:loaded',function(){if($('crazy-egg-source')&&SD.ExperimentManager.CrazyEggForHomePage.value){init();}});manager={getCE:function(){return window.CE2;},isReady:function(){return manager.getCE()&&manager.getCE().click;},setup:function(){manager.isSetup=true;originalSend=manager.getCE().send;CE2.click=CE2.click.wrap(function(p,f,q,n){if(f&&$(f).descendantOf($('site'))){return p(f,q,n);}
return null;});},enable:function(){if(!manager.isReady()){return;}
manager.getCE().send=originalSend;},disable:function(){if(!manager.isReady()){return;}
manager.getCE().send=Prototype.emptyFunction;}};return manager;})();SD.SpeedBump={win:null,registerWin:function(win){this.win=win;},targets:{speeddating:function(){SD.UserFilters.UI.startSpeedDating();},profile:function(){SD.NavUtils.goTo('profile','my_profile');},subscribe:function(){SD.UIController.upgradeMyself({tc:window.SD_SpeedBump_tc});}},go:function(target){SD.SpeedBump.targets[target]&&SD.SpeedBump.targets[target]();this.destroy();},showYTVideo:function(){$('youtube_video_holder').show();},closeYTVideo:function(){$('youtube_video_holder').hide();},destroy:function(){this.win.close();this.win=null;}};SD.Settings={};SD.Exp={getValue:function(expName){if(SD.ExperimentManager&&SD.ExperimentManager[expName]){if(this.experiments[expName]){return SD.Utils.getValue(this.experiments[expName]);}else{return SD.ExperimentManager[expName].value;}}else{return 0;}},experiments:{MatchMakerUI_v2:function(){return SD.Config.isSite?SD.ExperimentManager.MatchMakerUI_v2.value:0;}}};
document.observe('dom:loaded',function(){if(!SD.ExperimentManager)return;SD.Actions.init();});SD.Actions={isTooltipOn:true,init:function(){if(SD.Actions.isTooltipOn){var boundClearTooltip=this._clearTooltip.bind(this);SD.Event.observe(SD.FlowManager,SD.FlowManager.Events.BEFORE_RUN,boundClearTooltip);SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,boundClearTooltip);SD.Event.observe(null,SD.Nav.Events.HASH_CHANGE,boundClearTooltip);}},_clearTooltip:function(){SD.Actions._stopCurrentRunnable();SD.WindowManager.closeWindowsByType('TooltipDialog');},_stopCurrentRunnable:function(){var curRunnable=SD.FlowManager.execFlows.main.queue.first&&SD.FlowManager.execFlows.main.queue.first.value;curRunnable&&curRunnable.endRun();},_continuationCallback:function(runnable,context){if(context){SD.Utils.mixin(runnable.context,context||{});}
runnable.endRun();},aboutMeDialog:new SD.Action({sig:'aboutMeDialog',uiType:SD.UIType.POPUP,callFunc:function(context,runnable){(SD.Actions.isTooltipOn&&context.modTooltip)?SD.UIController.aboutMeTooltip(context,SD.Actions._continuationCallback.bind(SD.Actions,runnable)):SD.UIController.aboutMePopup(context,SD.Actions._continuationCallback.bind(SD.Actions,runnable));}}),uploadPhotoDialog:new SD.Action({sig:'uploadPhotoDialog',uiType:SD.UIType.POPUP,callFunc:function(context,runnable){SD.Actions.isTooltipOn&&context.modTooltip?SD.UIController.uploadPhotoTooltip(context,SD.Actions._continuationCallback.bind(SD.Actions,runnable)):SD.UIController.uploadPhotoPopup(context,SD.Actions._continuationCallback.bind(SD.Actions,runnable));}}),uploadPhotoDialogTutorial:new SD.Action({sig:'uploadPhotoDialogTutorial',uiType:SD.UIType.POPUP,callFunc:function(context,runnable){SD.UIController.uploadPhotoPopupTutorial(context,SD.Actions._continuationCallback.bind(SD.Actions,runnable));}}),facebookShareDialog:new SD.Action({sig:'facebookShareDialog',uiType:SD.UIType.POPUP,callFunc:function(context,runnable){(SD.Actions.isTooltipOn&&context.modTooltip)?SD.UIController.fbShareTooltip(context,SD.Actions._continuationCallback.bind(SD.Actions,runnable)):SD.UIController.facebookSharePopup(context,SD.Actions._continuationCallback.bind(SD.Actions,runnable));},rules:{'stub':function(context){if(!context.actionType){context.actionType=SD.UIController.ActionTypes.REGULAR_INVITATION;}
if(!context.actionData){if(!context.sourceMemberId){return false;}
context.actionData='{"sharedMemberId": "'+context.sourceMemberId+'"}';}
return true;},'no source member provided':function(context){return!!context.sourceMemberId},'share limit reached for winks-flirts-dates':function(context){return(context.actionType==SD.UIController.ActionTypes.WINK&&SD.FacebookFeed._winkCounter.getValue()<1)||(context.actionType==SD.UIController.ActionTypes.FLIRT&&SD.FacebookFeed._flirtCounter.getValue()<1)||(context.actionType==SD.UIController.ActionTypes.DATE&&SD.FacebookFeed._dateCounter.getValue()<1)||context.actionType==SD.UIController.ActionTypes.REGULAR_INVITATION;}},onAfterRun:function(e){if(e.memo.runBlocked){}}}),emailVerificationDialog:new SD.Action({sig:'emailVerificationDialog',uiType:SD.UIType.POPUP,callFunc:function(context,runnable){(SD.Actions.isTooltipOn&&context.modTooltip)?SD.UIController.emailVerificationTooltip(context,SD.Actions._continuationCallback.bind(SD.Actions,runnable)):SD.UIController.emailVerificationPopup(context,SD.Actions._continuationCallback.bind(SD.Actions,runnable));}}),phoneNumberDialog:new SD.Action({sig:'phoneNumberDialog',uiType:SD.UIType.POPUP,callFunc:function(context,runnable){SD.Actions.isTooltipOn&&context.modTooltip?SD.UIController.phoneNumberTooltip(context,SD.Actions._continuationCallback.bind(SD.Actions,runnable)):SD.UIController.phoneNumberPopup(context,SD.Actions._continuationCallback.bind(SD.Actions,runnable));}}),speedVerifyDialog:new SD.Action({sig:'speedVerifyDialog',uiType:SD.UIType.POPUP,callFunc:function(context,runnable){if(SD.Actions.isTooltipOn&&context.modTooltip&&SD.Exp.getValue('SpeedVerifyTooltip_SDWEB263')){SD.UIController.speedVerifyTooltip(context,SD.Actions._continuationCallback.bind(SD.Actions,runnable));}else{SD.UIController.speedVerifyPopup(context,SD.Actions._continuationCallback.bind(SD.Actions,runnable));}}}),emailDialog:new SD.Action({sig:'emailDialog',uiType:SD.UIType.POPUP,callFunc:function(context,runnable){context.showGift=!!context.showGift;SD.Dialogs.dialogFlirt(context,SD.Actions._continuationCallback.bind(SD.Actions,runnable));}}),basicEmail:new SD.Action({sig:'basicEmailAction',callFunc:function(context,runnable){SD.FlirtWink.Controller.flirt(context.sourceMember,context.message,null,context.virtualGift,SD.UIController.platform_id,context.onActionEnd||Prototype.emptyFunction);var permissions=context.sourceMember.relation.permissions;if(!SD.Model.getMyself().is_premium){permissions.can_wink=false;permissions.can_flirt=false;permissions.can_canned_flirt=false;permissions.can_type_in_flirt=false;}}}),basicWink:new SD.Action({sig:'winkAction',callFunc:function(context,runnable){SD.User.sendWink(SD.Model.getMyself(),context.sourceMember,context.onActionEnd||Prototype.emptyFunction);}}),favorite:new SD.Action({sig:'favoriteAction',callFunc:function(context){var sourceMember=context.sourceMember;var onActionEnd=context.onActionEnd;SD.FlirtWink.Controller.favorite(sourceMember,function(){SD.Tooltip.hide();SD.FlirtWink.View.displayFavoriteResponse(sourceMember,true);if(onActionEnd){sourceMember.relation.isFavorite=true;onActionEnd();}});},rules:{'user is not a favorite':function(context){return!context.sourceMember.relation.isFavorite}}}),unfavorite:new SD.Action({sig:'unfavoriteAction',callFunc:function(context){SD.FlirtWink.Controller.removeFavorite(context.sourceMember,{'other_memberid':context.sourceMember.uid},context.onActionEnd);}}),inviteToDate:new SD.Action({sig:'inviteToDateAction',async:true,callFunc:function(context,runnable){SD.Dialogs.dialogAddToDates(context.sourceMember,context.onActionEnd,{srcElement:context.sourceElement},SD.Actions._continuationCallback.bind(SD.Actions,runnable));}}),basicDate:new SD.Action({sig:'basicDateAction',callFunc:function(context,runnable){SD.UserInitiatedDate.dateUser(context.sourceMember,function(){SD.FlirtWink.View.date(context.sourceMember,Prototype.emptyFunction)},false,true,function(){SD.Event.fire(null,SD.UserInitiatedDate.Events.USER_INITIATED_DATE,{user:context.sourceMember});});},rules:{'user is online':function(context){return context.sourceMember.online||context.sourceMember.im_online}}}),basicChat:new SD.Action({sig:'basicChatAction',callFunc:function(context,runnable){var user=context.sourceMember;if(user.online){SD.Chat.chatWithUser(user);}else if(user.im_online){SD.Notification.IM.sendChatRequest(user);}else if(SD.Model.getMyself().wantsToDate(user)){SD.UIController.infoMessage(user.username+" is already invited to SpeedDate.We will notify you when "+user.username+" comes online.");}else{if(runnable.flow){runnable.flow.add(SD.Flows.inviteToDate.clone());}else{SD.Flows.inviteToDate.clone().run(context);}}}}),viewInbox:new SD.Action({sig:'viewInboxAction',callFunc:function(context,runnable){if(context.viewInboxUrl){SD.NavUtils.goToUrl(context.viewInboxUrl);}else{SD.NavUtils.goTo('messages','inbox');}}}),viewLikesMePage:new SD.Action({sig:'viewLikesMePageAction',callFunc:function(context,runnable){var urlMap={viewedMe:['likes_me','viewed_you'],favoritedMe:['likes_me','favorited_you'],invitedMe:['likes_me','want_to_date_you'],emailedMe:['likes_me','flirted_with_you'],triedToChatWithMe:['likes_me','attempted_to_chat_with_you'],triedToEmailMe:['likes_me','attempted_to_message_you'],choseMe:['likes_me','preference_analyzer_voted_you'],taggedMe:['likes_me','tagged_you']}
var urlParams=urlMap[context.pageType];if(urlParams){SD.NavUtils.goTo(urlParams[0],urlParams[1]);}}}),viewMessage:new SD.Action({sig:'viewMessageAction',callFunc:function(context,runnable){context.viewMessageUrl&&SD.NavUtils.goToUrl(context.viewMessageUrl);}}),subscribe:new SD.Action({sig:'subscribeAction',uiType:SD.UIType.POPUP,callFunc:function(context,runnable){var continuationCallback=SD.Actions._continuationCallback.bind(SD.Actions,runnable);if(SD.Actions.isTooltipOn&&context.modTooltip){SD.UIController.subscribeTooltip(context,continuationCallback);}else{SD.UIController.upgradeMyself({tc:context.tc,sourceType:context.sourceType,sourceMemberId:context.sourceMemberId,expandedMode:context.expandedMode},context.dontCheckSegment,context.usePreviousParams,continuationCallback);}},rules:{'must not be premium':function(context){return!SD.Model.getMyself().is_premium}}}),speedWinkDialog:new SD.Action({sig:'speedWinkAction',uiType:SD.UIType.POPUP,callFunc:function(context,runnable){(SD.Actions.isTooltipOn&&context.modTooltip)?SD.UIController.speedWinkTooltip(context,SD.Actions._continuationCallback.bind(SD.Actions,runnable)):SD.UIController.openSpeedWinkDialog(context,SD.Actions._continuationCallback.bind(SD.Actions,runnable));}}),imNotificationDialog:new SD.Action({sig:'imNotificationDialogAction',uiType:SD.UIType.POPUP,callFunc:function(context,runnable){if(SD.Actions.isTooltipOn&&context.modTooltip){SD.UIController.imTooltip(context,SD.Actions._continuationCallback.bind(SD.Actions,runnable))}else{SD.User.fetch(SD.User.get(context.sourceMemberId),function(user){SD.Notification.IM.showForm(user,'',null,SD.Actions._continuationCallback.bind(SD.Actions,runnable))});}},rules:{'should ask for IM':function(){return SD.Notification.IM.shouldAskForIM()},'undefined sourceMebmberId':function(context){return!!context.sourceMemberId}},onAfterRun:function(e){}}),recommendDialog:new SD.Action({sig:'recommendDialogAction',uiType:SD.UIType.POPUP,async:false,callFunc:function(context,runnable){if(context.sourceMemberId){SD.Recommendation.recommendFor(context.sourceMemberId,context.recommendActionType,null,SD.Actions._continuationCallback.bind(SD.Actions,runnable))}else{SD.Actions._continuationCallback(runnable);}},rules:{'valid source member':function(context){return!!context.sourceMemberId},'there is no other recommend dialog open':function(context){return!SD.Recommendation._recommendPopup}},onAfterRun:function(e){}})};SD.Flows={};SD.Flows.FLOW1='Flow1';SD.Flows.FLOW2='Flow2';SD.Flows.FLOW3='Flow3';SD.Flows.FLOW4='Flow4';SD.Flows.FLOW5='Flow5';SD.Flow.getFlow5=function(){return SD.Flows.FLOW5;};(function(){SD.Flows.sourceTypeToFlowMap={};var map={EMAIL:function(context){context=context||{};var _flirtee=context.sourceMember;if(_flirtee&&!_flirtee.injectedHot){if(context.messageType=='canned_flirt'&&_flirtee.relation&&_flirtee.relation.permissions&&_flirtee.relation.permissions.can_canned_flirt){return SD.Flows.FLOW1;}
if(context.messageType=='flirt'&&_flirtee.relation&&_flirtee.relation.permissions&&_flirtee.relation.permissions.can_type_in_flirt){return SD.Flows.FLOW2;}
if(_flirtee.relation&&_flirtee.relation.permissions&&_flirtee.relation.permissions.can_flirt){return SD.Flows.FLOW2;}}
return SD.Flows.FLOW4;},WINK:SD.Flows.FLOW1,DATE:SD.Flow.getFlow5(),CHAT:SD.Flows.FLOW4,MULTIPLE_PHOTO:null,MESSAGE_READ:SD.Flows.FLOW4,RATING:null,CHAT_ATTEMPT:SD.Flows.FLOW4,MESSAGE_ATTEMPT:SD.Flows.FLOW4,TAG:SD.Flows.FLOW4,VIEWED_YOU:SD.Flows.FLOW4,ACCESS_TAB:SD.Flows.FLOW3,CONTACT:null,SUBSCRIPTION_BUTTON:null,VERIFIED_BADGE:null,VIEW_MAIL_ATTEMPT:SD.Flows.FLOW3,TEST_DRIVE:null,ADD_TO_FAVORITES:SD.Flows.FLOW1,VIEW_CONVERSATION:SD.Flows.FLOW4,FAVORITED_YOU:SD.Flows.FLOW4,REQUESTED_TO_SPEEDDATE:SD.Flows.FLOW4,EMAILED_YOU:SD.Flows.FLOW4,NO_SOURCE:null,RATED_YOU:SD.Flows.FLOW4,CHOSE_YOU:SD.Flows.FLOW4,VC_INVITATION:null,VC_BUTTON:null,CONTACT_UPSELL:null,VIEW_VIRAL_QUIZ:null,SIGNUP_FLOW:null,GOAL_PHOTO_UPLOAD:null,GOAL_VERIFY_EMAIL:null,GOAL_MEMBER_INFO:null,GOAL_SMS:null,POST_SIGNUP_WOMEN_UX:null,INVITED_TO_DATE:SD.Flows.FLOW1};for(var key in map){SD.Flows.sourceTypeToFlowMap[SD.UIController.PopupSourceTypes[key]]=map[key];}})();(function(){SD.Flows.sourceDialogToFlowMap={};var map={DATE:SD.Flow.getFlow5()};for(var key in map){SD.Flows.sourceDialogToFlowMap[SD.Dialogs.Types[key]]=map[key];}})();(function(){SD.Flows.sourceUIToFlowMap={};var map={MAIL_SUBJECT:SD.Flows.FLOW4};for(var key in map){SD.Flows.sourceUIToFlowMap[SD.UI.Elements[key]]=map[key];}})();SD.Flows.resolveFlow=function(context){context=context||{};var flow=SD.Flows.FLOW1,mapping;mapping=SD.Flows.sourceUIToFlowMap[context.sourceUI]||SD.Flows.sourceDialogToFlowMap[context.sourceDialog]||SD.Flows.sourceTypeToFlowMap[context.sourceType];flow=mapping&&((typeof mapping=='function')?mapping(context):mapping);return flow;};SD.Flow.execFlow=function(context){var flow=SD.Flows.resolveFlow(context);if(flow&&SD.Flows[flow]){SD.Flows[flow].run(context);}};(function(){if(!SD.Model)return;var isPremium=SD.Model.getMyself().is_premium;SD.Flows.preActionFlow=new SD.RoundRobinBurstFlow({sig:'preActionFlow',enableCloning:false,blocking:true,onBeforeRun:function(){this.isBlocking=!(SD.Flows.resolveFlow(this.context)==SD.Flows.FLOW2||isPremium);},runnables:[SD.Actions.emailVerificationDialog.clone({weight:Infinity,rules:{'must be email bounced':function(){return SD.Model.getMyself().has_bounced}},onAfterRun:function(e){if(!e.memo.runBlocked){this.flow.isBlocking=true;}else{this.flow.isBlocking=!(SD.Flows.resolveFlow(this.context)==SD.Flows.FLOW2||isPremium);}}}),SD.Actions.uploadPhotoDialog.clone({weight:3,onBeforeRun:function(e){var curFlow=SD.Flows.resolveFlow(this.context);this.flow.isBlocking=!isPremium&&(curFlow==SD.Flows.FLOW3||curFlow==SD.Flows.FLOW4||curFlow==SD.Flow.getFlow5());},rules:{'must not be Flow1':function(context){return SD.Flows.resolveFlow(context)!=SD.Flows.FLOW1},'must not have a photo':function(){return!SD.Model.getMyself().has_photo}},onAfterRun:function(e){if(!e.memo.runBlocked&&SD.Model.getMyself().has_photo){this.flow.runNext=true;this.context.sourceDialog='photoDialog';}}}),SD.Actions.aboutMeDialog.clone({weight:2,onBeforeRun:function(e){var curFlow=SD.Flows.resolveFlow(this.context);this.flow.isBlocking=!isPremium&&(curFlow==SD.Flows.FLOW3||curFlow==SD.Flows.FLOW4||curFlow==SD.Flow.getFlow5());},rules:{'must not be Flow1':function(context){return SD.Flows.resolveFlow(context)!=SD.Flows.FLOW1},'must not have profile info':function(){return!SD.Model.getMyself().has_about_me}},onAfterRun:function(e){if(!e.memo.runBlocked&&SD.Model.getMyself().has_about_me){this.flow.runNext=true;this.context.sourceDialog='aboutMeDialog';}}}),SD.Actions.phoneNumberDialog.clone({weight:1,onBeforeRun:function(e){var curFlow=SD.Flows.resolveFlow(this.context);this.flow.isBlocking=!isPremium&&(curFlow==SD.Flows.FLOW3||curFlow==SD.Flows.FLOW4||curFlow==SD.Flow.getFlow5());},rules:{'must not be Flow1':function(context){return SD.Flows.resolveFlow(context)!=SD.Flows.FLOW1},'must be able to see sms':function(context){return SD.Model.getMyself().can_see_sms},'must not have a phone':function(context){return!SD.Model.getMyself().has_phone},'count limit per day':function(context){return SD.UIController.phoneNumberPopupCounter.getValue()<SD.Flows.preActionFlow.PHONE_NUMBER_LIMIT_PER_SESSION}},onAfterRun:function(e){if(!e.memo.runBlocked){SD.UIController.phoneNumberPopupCounter.increment();if(SD.Model.getMyself().has_phone){this.flow.runNext=true;this.context.sourceDialog='smsDialog';}}}}),SD.Actions.speedVerifyDialog.clone({weight:2,onBeforeRun:function(e){var curFlow=SD.Flows.resolveFlow(this.context);this.flow.isBlocking=!isPremium&&(curFlow==SD.Flows.FLOW3||curFlow==SD.Flows.FLOW4);},rules:{'must not be Flow4 && SDWEB339':function(context){return SD.Flows.resolveFlow(context)!=SD.Flows.FLOW4||!SD.ExperimentManager.RemoveSpeedVerifyFromFlow4_SDWEB339.value},'must not be Flow1':function(context){return SD.Flows.resolveFlow(context)!=SD.Flows.FLOW1},'must not be organic':function(context){return!SD.Model.getMyself().is_organic},'must not be verified':function(context){return!SD.Model.getMyself().is_verified},'count limit per day for flows other than Flow3':function(context){var flow=SD.Flows.resolveFlow(context);if(flow==SD.Flows.FLOW3)
return true;if(flow!=SD.Flows.FLOW3&&SD.UIController.speedVerifyShownCounter.getValue()<SD.Flows.preActionFlow.SPEEDVERIFY_LIMIT_PER_SESSION)
return true;return false;}},onAfterRun:function(e){e.memo&&!e.memo.runBlocked&&SD.UIController.speedVerifyShownCounter.increment();}}),SD.Actions.subscribe.clone({weight:2,onBeforeRun:function(e){var curFlow=SD.Flows.resolveFlow(this.context);this.flow.isBlocking=!isPremium&&(curFlow==SD.Flows.FLOW3||curFlow==SD.Flows.FLOW4);},rules:{'must be Flow4':function(context){return SD.Flows.resolveFlow(context)==SD.Flows.FLOW4}}})]});SD.Flows.preActionFlow.PHONE_NUMBER_LIMIT_PER_SESSION=1;SD.Flows.preActionFlow.SPEEDVERIFY_LIMIT_PER_SESSION=3;})();(function(){var facebookSharePreStartCounter=0;var imNotificationPreStartCounter=0;SD.Flows.postActionFlow=new SD.RoundRobinBurstFlow({sig:'postActionFlow',enableCloning:false,runnables:[SD.Actions.facebookShareDialog.clone({rules:{'must not be Flow1':function(context){return SD.Flows.resolveFlow(context)!=SD.Flows.FLOW1},'pre start counter':function(context){facebookSharePreStartCounter++;return facebookSharePreStartCounter>2},'count limit per day':function(context){return SD.UIController.facebookShareShownCounter.getValue()<SD.Flows.postActionFlow.FB_SHARE_LIMIT_PER_SESSION}},onAfterRun:function(e){e.memo&&!e.memo.runBlocked&&SD.UIController.facebookShareShownCounter.increment();}}),SD.Actions.imNotificationDialog.clone({rules:{'must not be Flow1':function(context){return SD.Flows.resolveFlow(context)!=SD.Flows.FLOW1},'pre start counter':function(context){imNotificationPreStartCounter++;return imNotificationPreStartCounter>2}}}),SD.Actions.speedWinkDialog.clone({rules:{'must not be Flow3':function(context){return SD.Flows.resolveFlow(context)!=SD.Flows.FLOW3},'only for Flow1 other than wink and email in Flow2 and Flow4':function(context){var flow=SD.Flows.resolveFlow(context);return(flow==SD.Flows.FLOW1)||(flow==SD.Flows.FLOW2&&context.sourceType==SD.UIController.PopupSourceTypes.EMAIL)||(flow==SD.Flows.FLOW4&&context.sourceType==SD.UIController.PopupSourceTypes.EMAIL);},'count limit per day':function(context){return SD.UIController.speedWinkShownCounter.getValue()<SD.Flows.postActionFlow.SPEEDWINK_LIMIT_PER_SESSION}},onAfterRun:function(e){e.memo&&!e.memo.runBlocked&&SD.UIController.speedWinkShownCounter.increment();}}),SD.Actions.recommendDialog.clone({rules:{'must not be Flow3':function(context){return SD.Flows.resolveFlow(context)!=SD.Flows.FLOW3},'only for Flow1 other than wink and email in Flow2 and Flow4':function(context){var flow=SD.Flows.resolveFlow(context);return(flow==SD.Flows.FLOW1&&context.sourceType!=SD.UIController.PopupSourceTypes.WINK)||(flow==SD.Flows.FLOW2&&context.sourceType==SD.UIController.PopupSourceTypes.EMAIL)||(flow==SD.Flows.FLOW4&&context.sourceType==SD.UIController.PopupSourceTypes.EMAIL);},'should not come from wink':function(context){return context.sourceType!=SD.UIController.PopupSourceTypes.WINK}}})]});}());if(SD.ExperimentManager&&SD.ExperimentManager.ReduceNumberOfSpeedWinksDialogsPerSessionTo1.value==1){SD.Flows.postActionFlow.SPEEDWINK_LIMIT_PER_SESSION=1;}else{SD.Flows.postActionFlow.SPEEDWINK_LIMIT_PER_SESSION=2;}
SD.Flows.postActionFlow.FB_SHARE_LIMIT_PER_SESSION=2;SD.Flows.email=new SD.Flow({sig:'EmailFlow',async:true,runnables:[function(context){var flirtee=context.sourceMember;var flirteePerimissions=flirtee.relation.permissions;if(flirtee&&flirtee.injectedHot&&!SD.Model.getMyself().is_premium){flirteePerimissions.can_canned_flirt=false;flirteePerimissions.can_flirt=false;flirteePerimissions.can_type_in_flirt=false;}},SD.Flows.preActionFlow,SD.Actions.basicEmail.clone({rules:{'requested from flirtwink page':function(context){return context.sourceUI=='FlirtWinkPageButton'}}}),SD.Flows.postActionFlow]});SD.Flows.dialogEmail=new SD.Flow({sig:'DialogEmailFlow',async:true,runnables:[function(context){var flirtee=context.sourceMember;var flirteePerimissions=flirtee.relation.permissions;if(flirtee&&flirtee.injectedHot&&!SD.Model.getMyself().is_premium){flirteePerimissions.can_canned_flirt=false;flirteePerimissions.can_flirt=false;flirteePerimissions.can_type_in_flirt=false;}},SD.Flows.preActionFlow,SD.Actions.emailDialog.clone({rules:{'requested from button':function(context){return context.sourceUI=='FlirtButton'}}})]});SD.Flows.wink=new SD.Flow({sig:'WinkFlow',async:true,runnables:[SD.Flows.preActionFlow,SD.Actions.basicWink.clone(),SD.Flows.postActionFlow]});SD.Flows.favorite=new SD.Flow({sig:'FavoriteFlow',async:true,runnables:[SD.Flows.preActionFlow,SD.Actions.favorite.clone(),SD.Flows.postActionFlow]});SD.Flows.inviteToDate=new SD.Flow({sig:'InviteToSpeedDateFlow',async:true,runnables:[SD.Flows.preActionFlow,SD.Actions.inviteToDate.clone(),SD.ExperimentManager&&SD.ExperimentManager.RecommendationsInNotification_SDWEB289.value?function(){}:new SD.FlowStopAction({'previous dialog was closed by user':function(context){return context.closedByUser;}}),SD.Flows.postActionFlow]});SD.Flows.basicDate=new SD.Flow({sig:'BasicDateFlow',async:true,runnables:[SD.Actions.basicDate.clone(),SD.Actions.inviteToDate.clone({rules:{'user is online':function(context){return!context.sourceMember}}})]});SD.Flows.date=new SD.Flow({sig:'DateFlow',async:true,runnables:[SD.Flows.preActionFlow,SD.Flows.basicDate.clone(),SD.Flows.postActionFlow]});SD.Flows.viewInbox=new SD.Flow({sig:'ViewInboxFlow',async:true,runnables:[SD.Flows.preActionFlow,SD.Actions.viewInbox.clone(),SD.Flows.postActionFlow]});SD.Flows.viewLikesMe=new SD.Flow({sig:'LikesMePageFlow',async:true,runnables:[SD.Flows.preActionFlow,SD.Actions.viewLikesMePage.clone(),SD.Flows.postActionFlow]});SD.Flows.viewMessage=new SD.Flow({sig:'viewMessageFlow',async:true,runnables:[SD.Flows.preActionFlow,SD.Actions.viewMessage.clone(),SD.Flows.postActionFlow]});SD.Flows.preActionFlowOnly=new SD.Flow({sig:'preActionFlowOnly',async:true,runnables:[SD.Flows.preActionFlow]});if(SD.FlowManager.debug==true){SD.Event.observe(null,SD.IRunnable.Events.STARTED,function(e){console.log('SD.IRunnable.Events.STARTED for: '+e.source.sig+' id: '+e.source.id);});SD.Event.observe(null,SD.IRunnable.Events.ENDED,function(e){console.log('SD.IRunnable.Events.ENDED for: '+e.source.sig+' id: '+e.source.id);});}
SD.UI.Events={MAIL_SUBJECT_CLICKED:'SD.UI.Events.MAIL_SUBJECT_CLICKED',BACK_TO_INBOX_BUT_CLICKED:'SD.UI.Events.BACK_TO_INBOX_BUT_CLICKED',MENU_INBOX_CLICKED:'SD.UI.Events.MENU_INBOX_CLICKED',MENU_LIKES_ME_CLICKED:'SD.UI.Events.MENU_LIKES_ME_CLICKED',DASHBOARD_LIKES_ME_CLICKED:'SD.UI.Events.DASHBOARD_LIKES_ME_CLICKED',DASHBOARD_INBOX_CLICKED:'SD.UI.Events.DASHBOARD_INBOX_CLICKED',NOTIFICATION_LIKES_ME_CLICKED:'SD.UI.Events.NOTIFICATION_LIKES_ME_CLICKED',NOTIFICATION_INBOX_CLICKED:'SD.UI.Events.NOTIFICATION_INBOX_CLICKED',VIEW_CONVERSATION:'SD.UI.Events.VIEW_CONVERSATION'};SD.UI.Manager={init:function(){this.setupMessageViewing();this.setupEmailViewPage();this.setupNavMenu();this.setupDashboard();this.setupNotifications();},setupMessageViewing:function(){SD.Event.observe(null,SD.UI.Events.MAIL_SUBJECT_CLICKED,function(e){SD.UI.Manager.onViewConversation(SD.Utils.buildContext({sourceMemberId:e.memo.sourceMemberId,sourceUI:SD.UI.Elements.MAIL_SUBJECT,viewMessageUrl:e.memo.link,premiumUrl:e.memo.premiumUrl,tc:e.memo.tc},e.memo.domEvent));});SD.Event.observe(null,SD.UI.Events.VIEW_CONVERSATION,function(e){SD.UI.Manager.onViewConversation(SD.Utils.buildContext({sourceMemberId:e.memo.sourceMemberId,sourceUI:e.memo.sourceUI,viewMessageUrl:e.memo.viewMessageUrl},e.memo.domEvent));});},onViewConversation:function(context){context.sourceType=SD.UIController.PopupSourceTypes.VIEW_CONVERSATION;SD.FlowManager.run(SD.Flows.viewMessage.clone(),context);},setupEmailViewPage:function(){SD.Event.forward(null,SD.UI.Events.BACK_TO_INBOX_BUT_CLICKED,SD.UI.Events.MENU_INBOX_CLICKED);},setupDashboard:function(){SD.Event.forward(null,SD.UI.Events.DASHBOARD_LIKES_ME_CLICKED,SD.UI.Events.MENU_LIKES_ME_CLICKED);SD.Event.forward(null,SD.UI.Events.DASHBOARD_INBOX_CLICKED,SD.UI.Events.MENU_LIKES_ME_CLICKED);},setupNotifications:function(){SD.Event.forward(null,SD.UI.Events.NOTIFICATION_LIKES_ME_CLICKED,SD.UI.Events.MENU_LIKES_ME_CLICKED);SD.Event.forward(null,SD.UI.Events.NOTIFICATION_INBOX_CLICKED,SD.UI.Events.MENU_LIKES_ME_CLICKED);},setupNavMenu:function(){SD.Event.observe(null,SD.UI.Events.MENU_INBOX_CLICKED,function(e){SD.FlowManager.run(SD.Flows.viewInbox.clone(),SD.Utils.buildContext({sourceType:SD.UIController.PopupSourceTypes.ACCESS_TAB,viewInboxUrl:e.memo.url},e.memo.domEvent));});this._setupLikesMeMenu();},_setupLikesMeMenu:function(){var contextMap={viewedMe:{sourceType:SD.UIController.PopupSourceTypes.VIEWED_YOU,tc:SD.TrackingCodes.trigger.feature.viewed_you._value},favoritedMe:{sourceType:SD.UIController.PopupSourceTypes.FAVORITED_YOU,tc:SD.TrackingCodes.trigger.feature.favorited_you._value},invitedMe:{sourceType:SD.UIController.PopupSourceTypes.REQUESTED_TO_SPEEDDATE,tc:SD.TrackingCodes.trigger.feature.requested_to_speeddate._value},emailedMe:{sourceType:SD.UIController.PopupSourceTypes.EMAILED_YOU,tc:SD.TrackingCodes.trigger.feature.emailed_you._value},triedToChatWithMe:{sourceType:SD.UIController.PopupSourceTypes.CHAT_ATTEMPT,tc:SD.TrackingCodes.trigger.feature.chat_attempt._value},triedToEmailMe:{sourceType:SD.UIController.PopupSourceTypes.MESSAGE_ATTEMPT,tc:SD.TrackingCodes.trigger.feature.message_attempt._value},choseMe:{sourceType:SD.UIController.PopupSourceTypes.CHOSE_YOU,tc:SD.TrackingCodes.trigger.feature.interested_in_you._value},taggedMe:{sourceType:SD.UIController.PopupSourceTypes.TAG,tc:SD.TrackingCodes.trigger.feature.tagged_you._value}};SD.Event.observe(null,SD.UI.Events.MENU_LIKES_ME_CLICKED,function(e){var context=contextMap[e.memo.pageType]||{};context.pageType=e.memo.pageType;SD.FlowManager.run(SD.Flows.viewLikesMe.clone(),SD.Utils.buildContext(context,e.memo.domEvent));});}};SD.UI.Manager.init();
SD.UI.Messages={};SD.UI.Messages.Tooltips={cmdType:{preActions:{UPLOAD_PHOTO:'upload your photo',FILL_OUT_PROFILE:'fill out your profile',GOAL_MEMBER_INFO_PROMPT:'complete your profile goal',VERIFY_EMAIL:'verify your email',ADD_PHONE:'add your phone number',VERIFY_PHONE:'verify your phone number',SHARE_ON_FACEBOOK:'connect with your friends'},postActions:{}},sourceType:{preActions:{EMAIL:'<b>#{name}</b> requests you #{actionMessage} before contacting #{him_her}!',DATE:'<b>#{name}</b> requests you #{actionMessage} before starting a SpeedDate with #{him_her}!',CHAT:'<b>#{name}</b> requests you #{actionMessage} before chatting with #{him_her}!',MULTIPLE_PHOTO:'<b>#{name}</b> requests you #{actionMessage} before viewing all #{his_her} photos!',MESSAGE_READ:function(sourceMemberId){return sourceMemberId?'Before you see if <b>#{name}</b> read your message, #{actionMessage}!':'Before you see if your message was read, #{actionMessage}!';},CHAT_ATTEMPT:'Before connecting with the #{man_woman} who tried to chat with you, #{actionMessage}!',MESSAGE_ATTEMPT:'Before connecting with the #{man_woman} who tried to contact you, #{actionMessage}!',TAG:'Before connecting with the #{man_woman} who tagged you, #{actionMessage}!',VIEWED_YOU:'Before connecting with the #{man_woman} who viewed you, #{actionMessage}!',ACCESS_TAB:'Before connecting with the #{man_woman} who sent you a message, #{actionMessage}!',CONTACT:'<b>#{name}</b> requests you #{actionMessage} before contacting #{him_her}!',ADD_TO_FAVORITES:'<b>#{name}</b> requests you #{actionMessage} before adding #{him_her} to your favorites!',VIEW_CONVERSATION:'<b>#{name}</b> requests you #{actionMessage} before viewing your conversation with #{him_her}!',TEST_DRIVE:'Before activating TestDrive&trade; #{actionMessage}!',FAVORITED_YOU:'Before connecting with the #{man_woman} who favorited you, #{actionMessage}!',RATED_YOU:'Before connecting with the #{man_woman} who rated you, #{actionMessage}!',REQUESTED_TO_SPEEDDATE:'Before connecting with the #{man_woman} who invited to SpeedDate with you, #{actionMessage}!',EMAILED_YOU:'Before connecting with the #{man_woman} who emailed you, #{actionMessage}!',CHOSE_YOU:'Before connecting with the #{man_woman} who chose you, #{actionMessage}!',VIEW_VIRAL_QUIZ:'Before you view <b>#{name}</b>\'s answers, #{actionMessage}!',GOAL_PHOTO_UPLOAD:'<div class="ballon-content-header">Upload your Photo to get more Matches</div>'+'<div class="ballon-content-text">Tip: Members with photos get 10 times more responses and get listed in search results!</div>',GOAL_VERIFY_EMAIL:'<div class="ballon-content-header">Verify your email below to receive messages from other Members</div>',GOAL_MEMBER_INFO_PROMPT:'<div class="goal-complete-profile-icon" style="margin:5px;float:left"></div><div style="padding-top:15px">To see <b>#{name}</b>\'s profile #{actionMessage}!</div>',NO_SOURCE:'Please #{actionMessage}!'},postActions:{EMAIL:'You successfully emailed <b>#{name}</b>!',WINK:'You successfully winked at <b>#{name}</b>!',INVITE_TO_DATE:'You successfully invited <b>#{name}</b> to a date!',FAVORITE:'You successfully favorited <b>#{name}</b>!',NO_SOURCE:''}},pageType:{},him_her:{him:'him',her:'her'},man_woman:{man:'men',woman:'women'},his_her:{his:'his',her:'her'},sourceTypeToMessagePre:{},sourceTypeToMessagePost:{},actionTypeToMessage:{},getMessage:function(context,callback){var sourceType=context.sourceType||SD.UIController.PopupSourceTypes.NO_SOURCE;var message=context.actionMode=='post'?SD.Utils.getValue(SD.UI.Messages.Tooltips.sourceTypeToMessagePost[sourceType]):SD.Utils.getValue(SD.UI.Messages.Tooltips.sourceTypeToMessagePre[sourceType]);message=message||'';if(context.sourceMember){this.buildMessageForUser(context.sourceMember,message,context,callback);}else if(context.sourceMemberId){SD.User.fetch(context.sourceMemberId,function(user){this.buildMessageForUser(user,message,context,callback);}.bind(this));}else if(message.indexOf('{name}')==-1){this.buildMessageForUser(SD.Model.getMyself(),message,context,callback);}else{callback(SD.UI.Messages.Tooltips.sourceType[context.actionMode=='post'?'postActions':'preActions'].NO_SOURCE.interpolate({actionMessage:this.resolveActionMessage(context)}));}},buildMessageForUser:function(user,message,context,callback){callback(message.interpolate({name:user.username,actionMessage:this.resolveActionMessage(context),man_woman:user.sex_pref=='M'?this.man_woman.man:this.man_woman.woman,him_her:user.sex=='M'?this.him_her.him:this.him_her.her,his_her:user.sex=='M'?this.his_her.his:this.his_her.her}));},resolveActionMessage:function(context){return context.mode=="post"?SD.Utils.getValue(SD.Utils.getValue(SD.UI.Messages.Tooltips.cmdType.postActions[context.sourceCmd])):SD.Utils.getValue(SD.Utils.getValue(SD.UI.Messages.Tooltips.cmdType.preActions[context.sourceCmd]));}};(function(){var sourceTypeToMessagePre=SD.UI.Messages.Tooltips.sourceTypeToMessagePre;var sourceTypeToMessagePost=SD.UI.Messages.Tooltips.sourceTypeToMessagePost;var sourceTypesPre=SD.UI.Messages.Tooltips.sourceType.preActions;var sourceTypesPost=SD.UI.Messages.Tooltips.sourceType.postActions;var popupSourceTypes=SD.UIController.PopupSourceTypes;for(var key in popupSourceTypes){sourceTypeToMessagePre[popupSourceTypes[key]]=sourceTypesPre[key];sourceTypeToMessagePost[popupSourceTypes[key]]=sourceTypesPost[key];}})();
SD=SD||{};SD.WeMatch=SD.WeMatch||{init:function(){SD.Model&&SD.Event.observe(null,SD.Model.Events.MODEL_CHANGED,function(){SD.WeMatch.reloadMatchInfo();});SD.Event.observe(null,SD.FlirtWink.Controller.Events.FLIRTEE_CHANGE,function(e){if(e.memo.flirtee.__match_rate_invalid){new Ajax.Request(SD.NavUtils.link('ajax','get_matching_score',{uid:e.memo.flirtee.uid}),{method:'get',evalJSON:true,onSuccess:function(response){if(response.responseJSON.success){SD.WeMatch.updateMatchUI(response.responseJSON.matching_score);delete e.memo.flirtee.__match_rate_invalid;e.memo.flirtee.matching_score=response.responseJSON.matching_score;}}});}});},answer:function(event){SD.Dialog.memberInfoTooltip({profileInfoId:this.parentNode.getAttribute('sdProfileInfoId'),sourceElement:this.parentNode},function(){SD.ExperimentManager.recordOutput('AddedProfileInfoInMatchViewOutput',1,1);SD.Event.fire(null,SD.Model.Events.MODEL_CHANGED);});},ask:function(event){var urlParams={otherMemberId:this.getAttribute('sdOtherMemberId')};var url=SD.NavUtils.link('ajax','request_member_info_we_match',urlParams);var target=this.parentNode;new Ajax.Request(url,{method:'get',evalJSON:true,onSuccess:function(result){target.addClassName('asked');}});},speedVerify:function(event){var flirtee=SD.FlirtWink.View.getFlirtee();SD.UIController.speedVerifyPopup({sourceType:41,sourceMemberId:flirtee.uid},SD.WeMatch.reloadMatchInfo.bind(SD.FlirtWink.View));},reloadMatchInfo:function(){var flirtee=SD.FlirtWink.View.getFlirtee();var url=SD.NavUtils.link('ajax','get_matching_score',{uid:flirtee.uid});new Ajax.Request(url,{method:'get',evalJSON:true,onSuccess:function(result){var data=result.responseJSON;if(data.success){flirtee.matching_score=data.matching_score;delete flirtee.__match_rate_invalid;SD.WeMatch.updateMatchUI(data.matching_score);}}});var oEl=$('profile-aboutmydate-tab');oEl.setAttribute('sdIsLoaded','false');SD.FlirtWink.View.activateTabMenu('profile-aboutmydate-tab');},updateMatchUI:function(matching_score){if($('matching-score')){if(matching_score>0){$('matching-score').innerHTML=matching_score+"%";}else{$('matching-score').innerHTML="0%";}}}};SD.WeMatch.init();
SD=SD||{}
SD.AutoCompleteV2={idElement:{},textElement:{},divElement:{},listingElement:null,iframe:null,timer:null,value:'',currentList:[],zIndex:null,activeItem:null,default_search_on:'name',callback:{},focusedItem:"",default_images:["67e1afc56902940776a21bf331d94baa.jpg","6f124b69eb35cef77f86ff28cb1cfe61.jpg","bf599714c7a8470c5c87b5fac6bda331.jpg","70a3bb27c3002de3e31f950f9cfabaef.jpg","eb842624951109150a907ec05850b2ba.jpg","vd1WlANxPY9.png","RUFy0JEpUl8.png","fwJFrO5KjAQ.png","GylKztrlHCg.png","C1LO4_1OOg0.png","Jdo-sLG5kLC.png","ekypbVpwBhF.png","gPDQbEKSvi3.png"],initialize:function(idElement,zIndex,callback){this.zIndex=zIndex;var k;if(SD.Dialog.ProfileTwoQuestions.dialog!=null){k=idElement.name+"-popup";}else{k=idElement.name;}
idElement.removeClassName("autocomplete-v2");this.callback[k]=callback||this.addSelection;this.idElement[k]=$(idElement);this.idElement[k].style.display='none';this.idElement[k].readOnly='readonly';this.divElement[k]=$(document.createElement('DIV'));this.divElement[k].addClassName('autocomplete-v2');this.idElement[k].parentNode.insertBefore(this.divElement[k],this.idElement[k]);if(this.idElement[k].tagName=='INPUT'){this.textElement[k]=$(document.createElement('INPUT'));this.textElement[k].type='TEXT';}else if(this.idElement[k].tagName=='TEXTAREA'){this.textElement[k]=$(document.createElement('TEXTAREA'));}
this.divElement[k].appendChild(this.textElement[k]);this.textElement[k].className=this.idElement[k].className;this.textElement[k].removeClassName('autocomplete-v2');this.textElement[k].name=this.idElement[k].name;this.textElement[k].value="";this.createListing([],"","");var val=this.idElement[k].value;this.textElement[k].observe('blur',this.onBlur.bindAsEventListener(this));this.textElement[k].observe('focus',this.onFocus.bindAsEventListener(this));this.textElement[k].observe('keydown',this.onKeyDown.bindAsEventListener(this));},createListing:function(show_fields,s_on,value){if(this.focusedItem==""){return;}
if(this.listingElement&&this.listingElement.parentNode){this.listingElement.parentNode.removeChild(this.listingElement);}
this.listingElement=$(document.createElement('DIV'));this.listingElement.addClassName('autocomplete-listing-v2');this.listingElement.style.display='none';this.listingElement.style.position='absolute';this.listingElement.style.border='1px solid #C3D0D9';if(this.zIndex){this.listingElement.style.zIndex=this.zIndex;}
this.divElement[this.focusedItem].appendChild(this.listingElement);var contains_match=false;this.currentList.each(function(item){var a=$(document.createElement('A'));a.href='#';a.addClassName('anchor-autocomplete-v2 passive');var span2=$(document.createElement('SPAN'));span2.innerHTML=item['id'];span2.style.display='none';span2.addClassName('id');a.appendChild(span2);show_fields.each(function(field){if(field=='photo_h'){var img1=$(document.createElement('IMG'));img1.src=item['photo'];a.appendChild(img1);img1.observe('mouseover',function(ev){if(this.activeItem!=null)this.setPassive(this.activeItem);this.activeItem=ev.target.parentNode;this.setActive(this.activeItem);ev.stop();}.bindAsEventListener(this));}else{var span1=$(document.createElement('SPAN'));span1.addClassName(field);if(item[field].toLowerCase().trim()==this.textElement[this.focusedItem].value.toLowerCase().trim()){contains_match=true;}
if(field.toString()==s_on.toString()){span1.innerHTML=this.highlight(item[field],new RegExp(value,"i"));}else{span1.innerHTML=item[field];}
span1.observe('mouseover',function(ev){if(this.activeItem!=null)this.setPassive(this.activeItem);this.activeItem=ev.target.tagName=="STRONG"?ev.target.parentNode.parentNode:ev.target.parentNode;this.setActive(this.activeItem);ev.stop();}.bindAsEventListener(this));a.appendChild(span1);}}.bind(this));this.listingElement.appendChild(a);a.observe('click',function(ev){this.onClick(this.activeItem);ev.stop();}.bindAsEventListener(this));a.observe('mouseover',function(ev){if(this.activeItem!=null)this.setPassive(this.activeItem);this.activeItem=ev.target;this.setActive(this.activeItem);ev.stop();}.bindAsEventListener(this));}.bind(this));if(!contains_match){var a=$(document.createElement('A'));a.href='#';a.addClassName('anchor-autocomplete-v2 passive no-click');var itemValue=this.textElement[this.focusedItem].value;itemValue=String(itemValue).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');a.innerHTML=itemValue;a.observe('click',function(ev){this.createNewProfileItem();ev.stop();}.bindAsEventListener(this));a.observe('mouseover',function(ev){if(this.activeItem!=null)this.setPassive(this.activeItem);this.activeItem=ev.target;this.setActive(this.activeItem);ev.stop();}.bindAsEventListener(this));this.listingElement.appendChild(a);}},createNewProfileItem:function(){new Ajax.Request(SD.NavUtils.link("profile","create_new_profile_item",{name:this.activeItem.innerHTML,member_info:this.focusedItem}),{method:'POST',onSuccess:function(response){if(response.responseText==null||response.responseText=='null'){return;}
response=response.responseText.evalJSON();var id=response._id.value;var name=response._name.value;var photo=response.photo;var anchor=$(document.createElement('A'));anchor.href='#';var span_n1=$(document.createElement('SPAN'));span_n1.addClassName('id');span_n1.innerHTML=id;anchor.appendChild(span_n1);var span_n2=$(document.createElement('SPAN'));span_n2.addClassName('name');span_n2.innerHTML=name;anchor.appendChild(span_n2);var img=$(document.createElement('IMG'));img.addClassName('photo');img.src=photo;anchor.appendChild(img);this.onClick(anchor);}.bind(this)});},onClick:function(item){this.hide();var cb=this.callback[this.focusedItem];cb(item);this.textElement[this.focusedItem].value="";},onFocus:function(ev){if(SD.Dialog.ProfileTwoQuestions.dialog!=null){this.focusedItem=ev.target.name+"-popup";}else{this.focusedItem=ev.target.name;}
this.timer=new PeriodicalExecuter(this.onTimer.bind(this),0.4);this.onTimer(null);},onBlur:function(ev){if(this.timer!==null){this.timer.stop();}
this.hide();},onTimer:function(pe){if(this.textElement[this.focusedItem].value==this.value){return;}
this.value=this.textElement[this.focusedItem].value;if(this.textElement[this.focusedItem].value.length<2){if(this.listingElement!=null){this.listingElement.style.display='none';}
return;}
var params={};params.value=this.textElement[this.focusedItem].value.trim();params.fields=["photo_h","name"];params.member_info=this.idElement[this.focusedItem].getAttribute("name");var url='/index.php?page=autocomplete&action=search&params='+Object.toJSON(params);new Ajax.Request(url,{method:'GET',onSuccess:function(transport){var response=transport.responseText.evalJSON();this.currentList=response.items;this.activeItem=null;this.createListing(params.fields,this.default_search_on,params.value);this.listingElement.style.display='block';this.divElement[this.focusedItem].removeChild(this.listingElement);$(document.body).appendChild(this.listingElement);this.listingElement.clonePosition(this.textElement[this.focusedItem],{setWidth:this.textElement[this.focusedItem].getWidth(),setHeight:false,offsetTop:this.textElement[this.focusedItem].getHeight()});}.bind(this)});},highlight:function(text,re){return text.replace(re,function(match){return'<strong>'+match+'<\/strong>'});},moveUp:function(){if(this.activeItem==null){this.activeItem=this.listingElement.lastChild;}else{this.setPassive(this.activeItem);this.activeItem=this.activeItem.previousSibling;}
if(this.activeItem!=null){this.setActive(this.activeItem);}},moveDown:function(){if(this.activeItem==null){this.activeItem=this.listingElement.firstChild;}else{this.setPassive(this.activeItem);this.activeItem=this.activeItem.nextSibling;}
if(this.activeItem!=null){this.setActive(this.activeItem);}},setActive:function(item){item.removeClassName('passive');item.addClassName('active');},setPassive:function(item){item.removeClassName('active');item.addClassName('passive');},onKeyDown:function(e){switch(e.keyCode){case Event.KEY_ESC:this.onBlur();break;case Event.KEY_TAB:case Event.KEY_RETURN:if(!this.activeItem)
break;if(this.activeItem.hasClassName('no-click')){this.createNewProfileItem();break;}
this.onClick(this.activeItem);break;case Event.KEY_UP:this.moveUp();break;case Event.KEY_DOWN:this.moveDown();break;default:return;}
Event.stop(e);},hide:function(){if(this.listingElement==null){return;}
(new PeriodicalExecuter(function(pe){pe.stop();if(this.listingElement.parentNode){this.listingElement.style.display='none';this.listingElement.parentNode.removeChild(this.listingElement);this.divElement[this.focusedItem].appendChild(this.listingElement);this.activeItem=null;}}.bind(this),0.4));},isItemExist:function(items,item){return items.indexOf(item)==-1?false:true;},removeSelection:function(item){},addSelection:function(item){},sanitize:function(name){name=name.stripTags();var l=name.length;name=name.substring(0,15);if(l>15)
name+="&hellip;";return name;}};
SD=SD||{}
SD.ProfileInfoOptionTooltip=SD.ProfileInfoOptionTooltip||{tooltipWindow:null,item_src:null,item_id:null,item_name:null,item_member_info:null,timer:null,on_item:false,ev_item:null,timestamp:null,init:function(){var ev=SD.ProfileInfoOptionTooltip.ev_item;var tw=SD.ProfileInfoOptionTooltip.tooltipWindow;if(tw!=null&&tw.isOpened){tw.close();}
var fnode=$(ev.target.parentNode.firstChild);if($(ev.target.parentNode).hasClassName('category-items'))
fnode=$(ev.target.firstChild);do{if(fnode.hasClassName("suggest-item-image")){SD.ProfileInfoOptionTooltip.item_src=fnode.src;}else if(fnode.hasClassName("suggest-item-id")){SD.ProfileInfoOptionTooltip.item_id=fnode.innerText||fnode.textContent;}else if(fnode.hasClassName("suggest-item-name")){SD.ProfileInfoOptionTooltip.item_name=fnode.innerText||fnode.textContent;}else if(fnode.hasClassName("fake-link")){SD.ProfileInfoOptionTooltip.item_member_info=fnode.name;}
fnode=$(fnode.nextSibling);}while(fnode)
SD.ProfileInfoOptionTooltip.tooltipWindow=SD.TooltipDialog.create({refDom:ev.target,content:'<div class="profile-tooltip" style="height: 80px;">'
+'<div style="float:left; padding:5px;">'
+'<img src="'+SD.ProfileInfoOptionTooltip.item_src+'" width="70px" height="70px" />'
+'</div>'
+'<div style="margin-left: 10px; position: relative; float: left;">'
+'<ul>'
+'<li style="padding: 3px">'
+'<a onclick="SD.ProfileInfoOptionTooltip.likeIt()" class="fake-link like-it-too">'
+'<span class="tooltip-icon like-it-icon"> </span> I like it too!'
+'</a>'
+'</li>'
+'<li style="padding: 3px">'
+'<a href="#index.php?page=members&action=search&s_keyword='+encodeURI('"'+SD.ProfileInfoOptionTooltip.item_name+'"')+'" class="fake-link search-for-others">'
+'<span class="tooltip-icon search-it-icon"> </span> Search for others'
+'</a>'
+'</li>'
+'<li style="padding: 3px">'
+'<a onclick="SD.ProfileInfoOptionTooltip.addIt()" class="fake-link add-to-mine">'
+'<span class="tooltip-icon add-it-icon"> </span> Add to my profile'
+'</a>'
+'</li>'
+'</ul>'
+'</div>'
+'</div>',width:250},Prototype.emptyFunction);},likeIt:function(){SD.FlirtWink.Controller.sendProfileNotification(SD.FlirtWink.View.getFlirtee(),this.item_id,0);SD.ProfileInfoOptionTooltip.tooltipWindow.close();SD.ProfileInfoOptionTooltip.tooltipWindow=SD.TooltipDialog.create({refPoint:SD.ProfileInfoOptionTooltip.tooltipWindow.refPoint,content:'<div class="profile-tooltip" style="height: 80px;">'
+'<div style="float:left; padding:5px;">'
+'<img src="'+SD.ProfileInfoOptionTooltip.item_src+'" width="70px" height="70px" />'
+'</div>'
+'<div style="margin-left: 10px; position: relative; float: left; padding:0px">'
+'<p style="margin-top:10px;width:150px">Great! You can also import your facebook interests!</p>'
+'<a onclick="SD.XConnect.openFacebookAuthenticate();" id="facebookButton" class="fb_button fb_button_large"> <span style="float:right;" class="fb_button_text">Import Facebook Interests</span></a>'
+'</div>'
+'</div>',width:310},Prototype.emptyFunction);},searchIt:function(){},addIt:function(){var params={};params.member_info=SD.ProfileInfoOptionTooltip.item_member_info;params.item=SD.ProfileInfoOptionTooltip.item_id;new Ajax.Request(SD.NavUtils.link('profile','add_to_my_profile'),{method:'post',evalJSON:false,parameters:params,onSuccess:function(response){if(response.responseText==null||response.responseText=='null'){SD.Error.record({error:'',url:SD.NavUtils.link('profile','add_to_my_profile',params),line_number:0,window_url:'',experiments:'',browser:Prototype.Browser.getName(),dumps:'',dump_exceptions:''});SD.UIController.infoMessage('We are sorry for the inconvenience, but we could not send your message at the moment, please try again later.',3);return;}
SD.Nav.invalidatePanel('profile');SD.FlirtWink.Controller.sendProfileNotification(SD.FlirtWink.View.getFlirtee(),SD.ProfileInfoOptionTooltip.item_id,1);SD.ProfileInfoOptionTooltip.tooltipWindow.close();SD.ProfileInfoOptionTooltip.tooltipWindow=SD.TooltipDialog.create({refPoint:SD.ProfileInfoOptionTooltip.tooltipWindow.refPoint,content:'<div class="profile-tooltip" style="height: 80px;">'
+'<div style="float:left; padding:5px;">'
+'<img src="'+SD.ProfileInfoOptionTooltip.item_src+'" width="70px" height="70px" />'
+'</div>'
+'<div style="margin-left: 10px; position: relative; float: left; padding:0px">'
+'<p style="margin-top:10px;width:150px">Great! '+SD.ProfileInfoOptionTooltip.item_name+' added to your profile!</p>'
+'<a onclick="SD.XConnect.openFacebookAuthenticate();" id="facebookButton" class="fb_button fb_button_large"> <span style="float:right;" class="fb_button_text">Import Facebook Interests</span></a>'
+'</div>'
+'</div>',width:310},Prototype.emptyFunction);}});},setTimer:function(ev){var fnode=$(ev.target.parentNode);if($(ev.target.parentNode).hasClassName('category-items'))
fnode=$(ev.target);fnode.select('.suggest-item-name').each(function(el){$(el).addClassName('hovered');});SD.ProfileInfoOptionTooltip.timestamp=new Date().getTime();SD.ProfileInfoOptionTooltip.on_item=true;SD.ProfileInfoOptionTooltip.ev_item=ev;SD.ProfileInfoOptionTooltip.checkitem.delay(0.5,SD.ProfileInfoOptionTooltip.timestamp);},checkitem:function(ts){if(ts!=SD.ProfileInfoOptionTooltip.timestamp){return;}
if(SD.ProfileInfoOptionTooltip.on_item){SD.ProfileInfoOptionTooltip.on_item=false;SD.ProfileInfoOptionTooltip.init();}},clearTimer:function(ev){var fnode=$(ev.target.parentNode);if($(ev.target.parentNode).hasClassName('category-items'))
fnode=$(ev.target);fnode.select('.suggest-item-name').each(function(el){$(el).removeClassName('hovered');});SD.ProfileInfoOptionTooltip.timestamp=0;SD.ProfileInfoOptionTooltip.on_item=false;},onclick:function(ev){SD.ProfileInfoOptionTooltip.on_item=false;SD.ProfileInfoOptionTooltip.ev_item=ev;SD.ProfileInfoOptionTooltip.init();}}
