//speeddate compiled js file. Compile time:2010-02-08 04-20\n
String.prototype.ucfirst=function(){return this.substr(0,1).toUpperCase()+this.substr(1);};String.prototype.excerpt=function(nLen){return this.truncate(nLen-1,'\u2026');};String.prototype.trim=String.prototype.strip;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";};if(!Array.prototype.map){Array.prototype.map=function(fun){var len=this.length>>>0;if(typeof fun!="function"){throw new TypeError();}
var res=new Array(len);var thisp=arguments[1];for(var i=0;i<len;i++){if(i in this){res[i]=fun.call(thisp,this[i],i,this);}}
return res;};}
Date.now=function(){return(new Date()).getTime();}
Element.addMethods({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;}});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;}}}
var MooExt=Class.create({addEvent:function(type,fn){if(!this.$events){this.$events={};}
type=MooExt.removeOn(type);var isFnRegistered=false;if(fn){this.$events[type]=this.$events[type]||[];for(var i=0;i<this.$events[type].length;++i){if(this.$events[type][i]==fn){isFnRegistered=true;break;}}!isFnRegistered&&this.$events[type].push(fn);}
return this;},addEvents:function(events){for(var type in events){this.addEvent(type,events[type]);}
return this;},fireEvent:function(type,args,delay){type=MooExt.removeOn(type);args=[].concat(args);if(!this.$events||!this.$events[type])return this;this.$events[type].each(function(fn){if(delay){var _this=this;setTimeout(function(){fn.apply(_this,args);},delay);}
else{fn.apply(this,args)}},this);return this;},removeEvent:function(type,fn){type=MooExt.removeOn(type);if(!this.$events||!this.$events[type])return this;this.$events[type].without(fn);return this;},removeEvents:function(events){if(!this.$events){return this;}
var type;if(typeof events=='object'){for(type in events)this.removeEvent(type,events[type]);return this;}
if(events)events=MooExt.removeOn(events);for(type in this.$events){if(events&&events!=type)continue;var fns=this.$events[type];for(var i=fns.length;i--;i)this.removeEvent(type,fns[i]);}
return this;},setOptions:function(options){this.options=SD.Utils.Object.merge(this.options||{},options||{},true);if(!this.addEvent)return this;for(var option in this.options){if(typeof this.options[option]!='function'||!(/^on[A-Z]/).test(option))continue;this.addEvent(option,this.options[option]);delete this.options[option];}
return this;}});MooExt.removeOn=function(string){return string.replace(/^on([A-Z])/,function(full,first){return first.toLowerCase();});};
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){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);
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);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.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.initialize=function(fbConnectApi,ifUserConnected,ifUserNotConnected,reloadIfSessionStateChanged,doNotUseCachedConnectState,debugLogLevel){var params=new Object();if(ifUserConnected!=null){params.ifUserConnected=ifUserConnected;}
if(ifUserNotConnected!=null){params.ifUserNotConnected=ifUserNotConnected;}
if(reloadIfSessionStateChanged!=null){params.reloadIfSessionStateChanged=reloadIfSessionStateChanged;}
if(doNotUseCachedConnectState!=null){params.doNotUseCachedConnectState=doNotUseCachedConnectState;}
if(debugLogLevel!=null){params.debugLogLevel=debugLogLevel;}
FB.init(fbConnectApi,"/apps/facebook/xd_receiver.htm",params);};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){fbml=fbml||' ';title=title||' ';width=width||760;height=height||650;var dialog=new FB.UI.FBMLPopupDialog(title);dialog.setFBMLContent(fbml);dialog.setContentWidth(width);dialog.setContentHeight(height);dialog.show();};};
﻿
(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||(SD={});SD.log=function(x){};SD.info=function(x){};SD.error=function(x){};SD.warn=function(x){};
SD.Utils=(function(){var _functions=$H({});return{log:SD.Console?SD.Console.log:function(){},getTime:function(){return(new Date()).getTime();},profile:function(funcName){SD.Utils.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.getTime();try{var args=$A(arguments);args.splice(0,1);var returnValue=proceed.apply(parent,args);}catch(e){SD.Utils.log('Exception in '+funcName,e.message);}
_functions.get(funcName).totalTime+=SD.Utils.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.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){el.style.visibility="hidden";setTimeout(function(){el.style.visibility=''},200);},_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;}};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===undefined||o===null){newObj[i]=o;}
else if(typeof o=='object'){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){context=context||self;for(var i in cmdData){if(typeof jsonCommands[i]=='function'){if(jsonCommands[i].call(context,cmdData[i])===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])===true){return true;}}
else if(typeof jsonCommands[i]=='object'&&typeof jsonCommands[i]['_']=='function'){if(jsonCommands[i]['_'].call(context,cmdData[i])===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);}}}}
SD.Utils.PeriodicalExecuter={_interval:300,_isRunning:false,_timer:null,_registrars:[],register:function(){for(var i=0,len=arguments.length;i<len;++i){this._registrars.push(arguments[i]);}
if(!this._isRunning){this._start();}},_unregister:function(){for(var i=0,len=arguments.length;i<len;++i){this._registrars.splice(arguments[i],1);}
if(this._registrars.length==0){this._stop();}},_execute:function(){var indexesOfFuncsToUnregister=[];for(var i=0,len=this._registrars.length;i<len;++i){if(this._registrars[i]()===true){indexesOfFuncsToUnregister.push(i);}}
if(indexesOfFuncsToUnregister.length){this._unregister.apply(this,indexesOfFuncsToUnregister);}},_start:function(){if(this._isRunning){return;}
this._timer=setInterval(this._execute.bind(this),this._interval);this._isRunning=true;},_stop:function(){if(this._isRunning){clearInterval(this._timer);}
this._isRunning=false;}}
SD.Utils.EventProxy={_eventHandlers:{},observe:function(source,ev,f){if(arguments.length==2){f=ev;ev=source;source=null;}
if(!this._eventHandlers[ev]){SD.Event.observe(source,ev,this.fire.bind(this,ev));}
this._eventHandlers[ev]=this._eventHandlers[ev]||[];this._eventHandlers[ev].push(f);},stopObserving:function(ev,f){if(this._eventHandlers[ev]){this._eventHandlers[ev].without(f);}},fire:function(ev){if(!this._eventHandlers[ev]||this._eventHandlers[ev].length==0){return;}
for(var i=0,len=this._eventHandlers[ev].length;i<len;++i){this._eventHandlers[ev][i]();}}}
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 expires="";if(days){var date=new Date();date.setTime(date.getTime()+(days*24*60*60*1000));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.createCookie(name,"",-1);}};
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.SubscriptionDialogs=new function(){var oWindow=null;var oUser=null;var sTrackingCode=null;var oTrackingObject=null;var aBenefits=['Contact millions of members','Choose who to date','See if your messages are viewed','See who viewed your profile','Have faster dates','Get more exposure','Get a highlighted profile','And more ...'];function renderHead(text,user){if(user){text=String(text).interpolate(user);}
return text;};function renderSubhead(text,user){if(user){text=String(text).interpolate(user);}
return text;};function renderBenefits(){var aBenefitsCol1=aBenefits.slice(0,aBenefits.length/2);var aBenefitsCol2=aBenefits.slice(aBenefits.length/2);var oContent=DIV({},DIV({'class':'head'},'Other benefits of upgrading:'),DIV({'class':'grid-row grid-row-50-50'},DIV({'class':'grid-col grid-col-first'},UL({},aBenefitsCol1.collect(function(sBenefit){return LI({},sBenefit);}))),DIV({'class':'grid-col'},UL({},aBenefitsCol2.collect(function(sBenefit){return LI({},sBenefit);})))));return oContent;};function renderPlans(){var oPlan1,oPlan2,oPlan3=null;var oContent=UL({'class':'grid-row grid-row-33'},LI({'class':'grid-col'},oPlan1=DIV({'class':'plan plan1'},H1({},'Save 50%'),H2({},SD.Config.subscriptionPlans[0].interval+' '+
SD.Config.subscriptionPlans[0].interval_label),H3({},I({},SD.Config.subscriptionPlans[0].currency_symbol),B({},SD.Config.subscriptionPlans[0].interval_price),'/month'))),LI({'class':'grid-col'},oPlan2=DIV({'class':'plan plan2'},H1({},'Save 20%'),H2({},SD.Config.subscriptionPlans[1].interval+' '+
SD.Config.subscriptionPlans[1].interval_label),H3({},I({},SD.Config.subscriptionPlans[1].currency_symbol),B({},SD.Config.subscriptionPlans[1].interval_price),'/month'))),LI({'class':'grid-col'},oPlan3=DIV({'class':'plan plan3'},H1({},'Or'),H2({},SD.Config.subscriptionPlans[2].interval+' '+
SD.Config.subscriptionPlans[2].interval_label),H3({},I({},SD.Config.subscriptionPlans[2].currency_symbol),B({},SD.Config.subscriptionPlans[2].interval_price),'/month'))));registerInputPlan1(oPlan1);registerInputPlan2(oPlan2);registerInputPlan3(oPlan3);return oContent;};function renderCloseButton(){var oContent=A({},'close');registerInputClose(oContent);return oContent;};function renderUserImage(user){var oContent=document.createElement('img');oContent.src=user.image_url_large;return oContent;};function dialog(o,oDialogConfig){o.user=o.user||SD.Model.getMyself();o.header=o.header||'';o.subheader=o.subheader||'';o.cssClassWindow=o.cssClassWindow||'';o.cssClassContent=o.cssClassContent||'';oDialogConfig=oDialogConfig||{};if(oWindow){this.close();}
var oContent=DIV({'class':'subscriptiondialog '+o.cssClassContent},DIV({'class':'head'},renderHead(o.header,o.user)),DIV({'class':'body'},DIV({'class':'grid-row grid-row-260'},DIV({'class':'grid-col grid-col-first'},DIV({'class':'left'},DIV({'class':'user-image'},renderUserImage(o.user)))),DIV({'class':'grid-col'},DIV({'class':'right'},DIV({'class':'subhead'},renderSubhead(o.subheader,o.user)),DIV({'class':'benefits'},renderBenefits()),DIV({'class':'plans-header'},'Select a Plan'),DIV({'class':'plans'},renderPlans(o.user)),DIV({'class':'cancel-message'},'Cancel within 7 days for a full refund!'),DIV({'class':'footer'},renderCloseButton()))))));oUser=o.user;sTrackingCode=o.trackingCode;oTrackingObject=o.trackingObject;oDialogConfig.width=950;oDialogConfig.maxWidth=1000;oDialogConfig.className='window-skin2';oWindow=SD.UIController.standardPopup(oDialogConfig);oWindow.getContent().insert(oContent);oWindow.showCenter(true,175-Element.cumulativeScrollOffset(document.body).top);};function redirectToSubscription(nPlan){var sUserId=oUser?oUser.uid:'';SD.UIController.upgradeMyself({'ti':sUserId,'tc':sTrackingCode,'tobj':oTrackingObject,'plan':nPlan});};function registerInputPlan1(oElement){oElement.observe('click',function(e){redirectToSubscription(0);});};function registerInputPlan2(oElement){oElement.observe('click',function(e){redirectToSubscription(1);});};function registerInputPlan3(oElement){oElement.observe('click',function(e){redirectToSubscription(2);});};function registerInputClose(oElement){oElement.observe('click',function(e){SD.SubscriptionDialogs.close();});}
this.close=function(){oWindow.close();oWindow=null;oUser=null;sTrackingCode=null;};this.dialogOverflirted=function(o){o.header='Upgrade now to contact #{username}!';o.subheader='#{username} accepts messages from premium members only.';if(o.user.relation.permissions.flirt_restriction_reason){o.trackingCode=SD.Config.restrictionReasons[o.user.relation.permissions.flirt_restriction_reason].old_tc;}else{o.trackingCode=SD.Constants.trackingCodes.over_flirted_link;}
o.trackingObject=SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.CONTACT_OVER_FLIRTED_PROFILE);dialog(o);};this.dialogUpgradeToFlirt=function(o){o.header='Upgrade now to flirt with #{username}!';o.subheader='#{username} accepts flirts from premium members only.';if(o.user.relation.permissions.flirt_restriction_reason){o.trackingCode=SD.Config.restrictionReasons[o.user.relation.permissions.flirt_restriction_reason].old_tc;}else{o.trackingCode=SD.Constants.trackingCodes.over_flirted_link;}
o.trackingObject=SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.CONTACT_OVER_FLIRTED_PROFILE);dialog(o);};this.dialogUpgradeToWink=function(o){o.header='Upgrade now to wink at #{username}!';o.subheader='#{username} accepts winks from premium members only.';if(o.user.relation.permissions.wink_restriction_reason){o.trackingCode=SD.Config.restrictionReasons[o.user.relation.permissions.wink_restriction_reason].old_tc;}else{o.trackingCode=SD.Constants.trackingCodes.over_flirted_link;}
o.trackingObject=SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.CONTACT_OVER_FLIRTED_PROFILE);dialog(o);};this.dialogUpgradeToDate=function(o){o.header='Upgrade now to date #{username}!';o.subheader='#{username} accepts dates from premium members only.';o.trackingCode=SD.Constants.trackingCodes.date_button_speeddate_page;o.trackingObject=SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.DATE_BUTTON_DATING);dialog(o);};};
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:'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,activePopupArrow:null,historyIndex:0,historyDisableUpdates:true,updateActivePanel:function(panelId){var panel=SD.Nav.panels.filter(function(panel){return panel.id==panelId})[0];panel.valid=true;this.lastRoot=$('content-'+panelId);},onLoad:function(){this.pageUrl=self.location.href;if(this.pageUrl.indexOf('#')!=-1){this.pageUrl=this.pageUrl.substring(0,this.pageUrl.indexOf('#'));}
this.baseUrl=this.pageUrl.substring(0,this.pageUrl.lastIndexOf('/')+1);$$('.menu-title.with-arrow').each(function(e){(new SD.MenuController(e.up('span'),e.up('li').select('ul').first()));});this.updateUrls(document.body);this.updateActivePanel(initialActivePanelId);if(Prototype.Browser.IE){$('history-iframe').observe("load",function(ev){this.historyDisableUpdates=false;}.bindAsEventListener(this));}
(new PeriodicalExecuter(function(pe){if(self.location.href!=this.pageUrl+this.activePath||(this.getPanelById(this.activePanelId)&&!this.getPanelById(this.activePanelId).valid)){if(this.pageUrl==self.location.href.substring(0,this.pageUrl.length)){this.navigateTo(this.decode(self.location.href));if(Prototype.Browser.IE){return;this.historyIndex++;$('history-iframe').src=this.historyUrl+"?idx="+this.historyIndex+"&url="+escape(this.decode(self.location.href));this.historyDisableUpdates=true;}}}else if(Prototype.Browser.IE&&!this.historyDisableUpdates){var doc=$('history-iframe').contentWindow.document;var urlInput=$(doc.getElementById('history-url'));var idxInput=$(doc.getElementById('history-idx'));if(idxInput&&urlInput){if(idxInput.value!=this.historyIndex){self.location=this.encode(urlInput.value);this.navigateTo(urlInput.value);this.historyIndex=idxInput.value;}}}
if(Ajax.activeRequestCount>0){if(SD.ExperimentManager.AjaxFeedbackExp.value){$('ajax-busy').show();$('popup-ajax-busy').show();}}else{$('ajax-busy').hide();$('popup-ajax-busy').hide();}}.bind(this),0.2));Ajax.Responders.register({onException:function(request,exception){Ajax.activeRequestCount--;SD.log("AjaxExceptionResponder: "+exception);}});SD.Event.fire(null,SD.Nav.Events.INITIALIZED)},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');SD.Flex.onUpdateProfile($("user_profile_img"));}else if(e.hasClassName('sd-external-redirect')){var navRedirectElement=e;var navRedirectUrl=navRedirectElement.innerHTML;navRedirectUrl=navRedirectUrl.replace(/&amp;/g,'&');document.location.href=navRedirectUrl;}else if(e.hasClassName('sd-nav-redirect')){var navRedirectElement=e;var navRedirectUrl=navRedirectElement.innerHTML;navRedirectUrl=navRedirectUrl.replace(/&amp;/g,'&');SD.log("sd-nav-redirect: "+navRedirectUrl);this.panels.each(function(p){if($('content-'+p.id)==root){SD.log('invalidating '+p.id);p.valid=false;}});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);}}.bind(this));if(SD.Focus){SD.Focus.reinitialize();}
this.updateLinks(root,this.encode.bind(this));var submitEventFunction=this.submitFormEventHandler.bindAsEventListener(this);var autoUploaderCallbackFunction=function(result){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.observe('submit',submitEventFunction);e=null;}}.bind(this));SD.Tooltip&&SD.Tooltip.init($(root));$(root).select('select').each(function(e){if(e.multiple){(new SD.Dropdown(e));}}.bind(this));$(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 panel=null;this.panels.each(function(p){if($('content-'+p.id)==root){panel=p;}});var titleDiv=$(root).select('div.panel-title').first();if(titleDiv){this.updatePanelTitle(titleDiv.innerHTML);}else{this.updatePanelTitle('');}
var flirtInput=$(root).select('textarea.sd-flirt-input').first();if(flirtInput){flirtInput.observe('keyup',this.flirtInputHandler.bindAsEventListener(this));flirtInput.observe('change',this.flirtInputHandler.bindAsEventListener(this));if(flirtInput.form){$(flirtInput.form).select('input[name="flirt-msg"]').each(function(e){e.observe('click',this.flirtInputHandler.bindAsEventListener(this));e.observe('change',this.flirtInputHandler.bindAsEventListener(this));}.bind(this));}
this.flirtInputHandler(null,flirtInput);}
SD.Nav.lastRoot=root;},redirectTo:function(url){SD.log('redirect:'+url);self.location.href=url;},flirtInputHandler:function(ev,input){input=input||Event.element(ev);var form=$(input.form);if(!form){return;}
var radio=form.select('input.sd-flirt-radio').first();var submit=form.select('input[type="submit"]').first();var counter=form.select('span.sd-flirt-counter').first();if(!input.hasClassName('sd-flirt-input')){input=form.select('textarea.sd-flirt-input').first();}
if(input.value.length>1000){input.value=input.value.substr(0,1000);}
counter.innerHTML=1000-input.value.length;var enabled=true;if(radio&&radio.checked&&input.value.length===0){SD.log("radio.checked");enabled=false;}
if(!radio&&input.value.length===0){SD.log("!radio");enabled=false;}
submit.disabled=!enabled;},submitFormEventHandler:function(ev){var e=$(Event.element(ev));ev.stop();if(e.tagName=='INPUT'){e=e.form;}
var confirmDiv=e.select('div.confirm-message').first();if(confirmDiv){if(!confirm(confirmDiv.innerHTML)){return;}}
this.submitForm(e);},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');if(!container){container=form.up('div#content-popup');}
container.update(this.clearJS(transport.responseText));this.updateUrls(container);}.bind(this)});}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){SD.log("navigateTo: "+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.defer(null,SD.Nav.Events.PAGE_CHANGE,{hashOld:this.oHashOld,hashNew:this.oHash});}
if(!this.oHashOld||this.oHash.action!=this.oHashOld.action){SD.Event.fire.defer(null,SD.Nav.Events.ACTION_CHANGE,{hashOld:this.oHashOld,hashNew:this.oHash});}}catch(error){}}
this.trackAnalytics();var realUrl=this.decode(url);var panel=null;var popup=false;this.panels.each(function(p){var panelUrl=this.panelPrefix+p.id;if(realUrl.substring(0,panelUrl.length)==panelUrl){panel=p;}}.bind(this));if(!panel&&realUrl.substring(0,this.panelPrefix.length)==this.panelPrefix){panel=this.getPanelById('default');}
if(!panel){return;}
this.activePathOld=null;this.activate(panel.id);if(!panel.noServer){if(panel.noCache||!panel.valid||realUrl!=panel.url){this.updatePanelTitle(this.sLoading);this.loadContent($('content-'+panel.id),realUrl);}
var tabTitle=$('primary-navigation').select('.nav-'+panel.id+' a.menu-title').first();if(tabTitle){tabTitle.href=this.encode(realUrl);}}
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){}}},activate:function(panelId){this.activePanelId=panelId;this.updatePanelTitle(null);$$('#primary-navigation > li').invoke('removeClassName','current');this.panels.each(function(p){if(!$('content-'+p.id).hasClassName('inner-site-hidden')){$('content-'+p.id).addClassName('inner-site-hidden');}});$$('#primary-navigation > li.nav-'+panelId).invoke('addClassName','current');$('content-'+panelId).removeClassName('inner-site-hidden');if(panelId!='popup'){SD.DemographicFilter.UI.closeDemoFilters();if(panelId=='speeddate'){SD.Event.fire(null,SD.UIController.Events.SWITCHED_TO_SPEEDDATE);SD.Flex.onSpeedDateActive();}else{SD.Event.fire(null,SD.UIController.Events.SWITCHED_TO_OTHER_TABS);SD.Flex.onSpeedDatePassive();}}
if(SD.BrowserDetect.browser=='Firefox'&&SD.BrowserDetect.OS=='Windows'){if(panelId=='site'&&SD.Chat.visible){SD.Chat.minimize();}}
var experimentValue=SD.ExperimentManager.GalleryHomepage2257.value;if(experimentValue==0||experimentValue==1||experimentValue==2){}else if((experimentValue==3&&panelId=='speeddate')||(experimentValue==4&&panelId=='home')){$('sd-filter-inside').show();}else{$('sd-filter-inside').hide();}},invalidate:function(panelId){this.panels.each(function(p){if(p.id==panelId){p.valid=false;}});},invalidateUrl:function(url){url=this.decode(this.encode(url));this.panels.each(function(p){if(p.url==url){p.valid=false;}});},loadContent:function(e,url){if(!url)return;(new Ajax.Request(url+"&displayType=ajax",{method:'get',onSuccess:function(transport){e.update(this.clearJS(transport.responseText));this.updateUrls(e);SD.Event.fireDeferred(null,SD.Nav.Events.CONTENT_LOADED,{url:url,element:e});}.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){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(){var url=this.decode(this.activePath);SD.log("Tracking Analytics: "+url);if(self.pageTracker){try{pageTracker._trackPageview(url);}catch(e){SD.log("pageTracker exception: "+e);}}else{SD.log("self.pageTracker is undefined ?");}},init:function(currentUrl){if(currentUrl&&currentUrl.substr(0,this.panelPrefix.length)==this.panelPrefix){if(self.location.href.indexOf('#')==-1){self.location.href=self.location.href+'#'+currentUrl;}
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));}};SD.Nav.Events={PAGE_CHANGE:'sdnav:pagechange',ACTION_CHANGE:'sdnav:pagechange',HASH_CHANGE:'sdnav:hashchange',TITLE_CHANGE:'sdnav:titlechange',PANEL_LOADED:'sdnav:panelloaded',CONTENT_LOADED:'sdnav:contentloaded',INITIALIZED:'sdnav:initialized'};
SD.NavUtils=new function(){this.submitForm=function(f){if(SD.Nav&&SD.Nav.initialized){SD.Nav.submitForm(f);}else{f.submit();}};this.getLocation=function(){if(SD.Nav&&SD.Nav.initialized){return SD.Nav.baseUrl+SD.Nav.decode(SD.Nav.activePath);}else{return self.location.href;}};this.setLocation=function(location){if(SD.Nav&&SD.Nav.initialized){location=SD.Nav.pageUrl+SD.Nav.encode(location);}
self.location.href=location;};this.queryString=function(obj){var vars=[];for(var key in obj){vars.push(encodeURIComponent(key)+'='+obj[key].toString());}
return vars.join('&');};this.link=function(controller,action,params){var baseUrl=SD.Config.getLinkBase(controller,action);return!params?baseUrl:baseUrl+'&'+this.queryString(params);};this.linkSecure=function(controller,action,params){var baseUrl=SD.Config.getLinkBase(controller,action).replace(/http:\/\/[^\/]+\//i,'/');return!params?baseUrl:baseUrl+'&'+this.queryString(params);};this.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();};this.getUrlHashBase=function(){return location.hash.split('?')[0];};this.updateUrlHashParams=function(urlHashObject){var updatedUrlHashObject=$H(this.getUrlHashParams()).merge(urlHashObject).toObject();this.setUrlHashParams(updatedUrlHashObject);};this.setUrlHashParams=function(urlHashObject){if(urlHashObject){location.hash=this.getUrlHashBase()+'?'+$H(urlHashObject).toQueryString();}else{location.hash='';}};this.getPreviousTitle=function(){return SD.Nav.sTitleOld;};this.getCurrentTitle=function(){return SD.Nav.sTitle;};};
SD.MenuController=Class.create({firingElement:null,listElement:null,state:'closed',isMouseOver:0,delayPE:null,_speedOpen:25,_timeOutOpen:0.010,_speedClose:60,_timeOutClose:0.005,_delayClose:0.100,_delayAfterClick:1,iframe:null,initialize:function(firing,list)
{this.firingElement=$(firing);this.listElement=$(list);this.firingElement.observe('mouseover',this.onMouseOver.bind(this));this.listElement.observe('mouseover',this.onMouseOver.bind(this));this.firingElement.observe('mouseout',this.onMouseOut.bind(this));this.listElement.observe('mouseout',this.onMouseOut.bind(this));this.firingElement.observe('click',this.onClickFiringEl.bind(this));this.listElement.observe('click',this.onClickListEl.bind(this));this.listElement.style.display='none';if(Prototype.Browser.IE)
{(new PeriodicalExecuter(function(pe){if(!this.listElement.getHeight()){return;}
pe.stop();this.iframe=$(document.createElement('IFRAME'));this.listElement.parentNode.insertBefore(this.iframe,this.listElement);this.iframe.addClassName('menu-iframe');this.iframe.style.height=this.listElement.getHeight()+'px';this.iframe.style.width=this.listElement.getWidth()+'px';}.bind(this),0.2));}},onClickFiringEl:function()
{if(this.state=='closed'){this.onMouseOver();}
else{this.onClickListEl();}},onClickListEl:function()
{if(this.delayPE){this.delayPE.stop();this.delayPE=null;}
this.isMouseOver=0;this.state='closed';this.listElement.style.display='none';this.isReadyToEngage=false;},onMouseOver:function()
{this.isMouseOver++;if(this.delayPE){this.delayPE.stop();this.delayPE=null;}
if(this.state=='closed'){this.state='opening';this.listElement.style.display='block';this.listElement.style.marginTop=-this.listElement.getHeight()+'px';(new PeriodicalExecuter(this.onMoveTimer.bind(this),this._timeOutOpen));}else if(this.state=='closing'){this.state='opening';}},onMouseOut:function()
{this.isMouseOver--;if(this.isMouseOver<0){this.isMouseOver=0;}
if(this.state=='open'){this.delayPE=new PeriodicalExecuter(this.onDelayTimer.bind(this),this._delayClose);}},onMoveTimer:function(pe)
{if(this.state=='opening'&&!this.isMouseOver){pe.stop();this.state='closing';(new PeriodicalExecuter(this.onMoveTimer.bind(this),this._timeOutClose));return;}
if(this.state=='opening'){var margin=parseInt(this.listElement.getStyle('margin-top')+0);margin+=this._speedOpen;if(margin>0){margin=0;}
this.listElement.style.marginTop=margin+'px';if(margin==0){this.state='open';pe.stop();if(!this.isMouseOver){this.delayPE=new PeriodicalExecuter(this.onDelayTimer.bind(this),this._delayClose);}}
return;}
if(this.state=='closing')
{var margin=parseInt(this.listElement.getStyle('margin-top')+0);margin-=this._speedClose;this.listElement.style.marginTop=margin+'px';if(margin<-this.listElement.getHeight()){this.state='closed';pe.stop();this.listElement.style.display='none';}
return;}},onDelayTimer:function(pe){pe.stop();this.delayPE=null;if(!this.isMouseOver){this.state='closing';(new PeriodicalExecuter(this.onMoveTimer.bind(this),this._timeOutClose));}else{this.state='opening';(new PeriodicalExecuter(this.onMoveTimer.bind(this),this._timeOutOpen));}}});
SD.ResultMessage=Class.create(SD.MenuController,{_speedOpen:25,_timeOutOpen:0.010,_speedClose:10,_timeOutClose:0.01,_delayClose:5.000,initialize:function(messageElement){this.listElement=$(messageElement);var containerDiv;containerDiv=$(document.createElement('DIV'));this.listElement.parentNode.insertBefore(containerDiv,this.listElement);containerDiv.addClassName('result-message-container');this.listElement.parentNode.removeChild(this.listElement);containerDiv.appendChild(this.listElement);this.listElement.style.display='block';if(Prototype.Browser.IE){this.iframe=$(document.createElement('IFRAME'));this.listElement.parentNode.insertBefore(this.iframe,this.listElement);this.iframe.addClassName('menu-iframe');this.iframe.style.height=this.listElement.getHeight()+'px';this.iframe.style.width=this.listElement.getWidth()+'px';}
if(this.listElement.hasClassName('result-error')){containerDiv.style.position='relative';}
this.state='closed';this.onMouseOver();},onMoveTimer:function($super,pe){var oldState=this.state;this.listElement.style.marginTop=this.listElement.style.top;this.listElement.style.top='0px';$super(pe);if(this.state=='open'&&oldState!='open'){if(!this.listElement.hasClassName('result-error')){this.onMouseOut();}}
this.listElement.style.top=this.listElement.style.marginTop;this.listElement.style.marginTop='0px';}});
SD.Dropdown=Class.create({selectElement:null,dropdownDiv:null,textDiv:null,optionsDiv:null,isOpen:false,boundOnClickElsewhere:null,closeDiv:null,iframe:null,initialize:function(select){this.selectElement=$(select);this.selectElement.style.display='none';this.dropdownDiv=$(document.createElement('DIV'));this.dropdownDiv.addClassName('dropdown');this.selectElement.parentNode.insertBefore(this.dropdownDiv,this.selectElement);this.textDiv=$(document.createElement('DIV'));this.textDiv.addClassName('text');this.textDiv.observe('mousedown',this.onMouseDown.bindAsEventListener(this));this.dropdownDiv.appendChild(this.textDiv);this.updateText();this.boundOnMouseDownElsewhere=this.onMouseDownElsewhere.bindAsEventListener(this);},updateText:function(){var text='';for(var i=0;i<this.selectElement.options.length;i++){if(this.selectElement.options[i].selected){text+=', '+this.selectElement.options[i].text;}}
this.textDiv.innerHTML=(text==='')?'<i>Click here to choose..</i>':text.substring(2);},onMouseDown:function(ev){Event.stop(ev);if(this.isOpen){this.close();}else{this.open();}},onMouseDownElsewhere:function(ev){this.close();},_determinePosition:function(){var position='absolute';this.dropdownDiv.ancestors().each(function(el){if(el.getStyle('position')=='fixed'){position='fixed';throw $break;}});return position;},_setOptionsDivPosition:function(){if(!this.optionsDiv){return true;}
if(this.optionsDiv.style.position=='absolute'){this.optionsDiv.clonePosition(this.dropdownDiv,{setWidth:false,setHeight:false,offsetTop:this.dropdownDiv.getHeight()});if(SD.Dropdown.shim){SD.Dropdown.shim.style.left=this.optionsDiv.style.left;SD.Dropdown.shim.style.top=this.optionsDiv.style.top;}}
else if(this.optionsDiv.style.position=='fixed'){var offsets=this.dropdownDiv.cumulativeOffset();this.optionsDiv.style.left=offsets.left+'px';this.optionsDiv.style.top=(offsets.top+this.dropdownDiv.getHeight())+'px';if(SD.Dropdown.shim){SD.Dropdown.shim.style.left=this.optionsDiv.style.left;SD.Dropdown.shim.style.top=this.optionsDiv.style.top;}}},open:function(){if(this.isOpen){return;}
if(SD.Dropdown.lastOpened&&SD.Dropdown.lastOpened!=this){SD.Dropdown.lastOpened.close();}
SD.Dropdown.lastOpened=this;this.isOpen=true;this.dropdownDiv.addClassName('dropdown-active');$(document.body).observe('mousedown',this.boundOnMouseDownElsewhere);SD.Utils.EventProxy.observe(SD.Nav.Events.HASH_CHANGE,this.boundOnMouseDownElsewhere);this.optionsDiv=$(document.createElement('DIV'));this.optionsDiv.style.visibility='hidden';document.body.appendChild(this.optionsDiv);this.optionsDiv.addClassName('text');this.optionsDiv.style.zIndex=10000;this.optionsDiv.addClassName('dropdown-options');this._setOptionsDivPosition();this.optionsDiv.style.position=this._determinePosition();this.optionsDiv.style.width=(200*(Math.min(4,Math.ceil(this.selectElement.options.length/20)))-30)+'px';this.optionsDiv.observe('mousedown',function(e){Event.stop(e);})
this.dropdownDiv.observe('mousedown',function(e){Event.stop(e);})
this.closeDiv=$(document.createElement('DIV'));this.closeDiv.innerHTML='Close';var closeDiv2=$(document.createElement('DIV'));closeDiv2.appendChild(this.closeDiv);closeDiv2.addClassName('close');this.optionsDiv.appendChild(closeDiv2);closeDiv2.observe('mousedown',this.boundOnMouseDownElsewhere);for(var i=0;i<this.selectElement.options.length;i++){var div=$(document.createElement('DIV'));div.addClassName('option');var checkbox=$(document.createElement('INPUT'));checkbox.id='dropdowncb_'+i;var label=$(document.createElement('LABEL'));label.htmlFor='dropdowncb_'+i;div.appendChild(label);checkbox.type='checkbox';checkbox.value=i;checkbox.checked=this.selectElement.options[i].selected;checkbox.defaultChecked=this.selectElement.options[i].selected;label.appendChild(checkbox);var span=$(document.createElement('SPAN'));span.innerHTML=this.selectElement.options[i].text;label.appendChild(span);this.optionsDiv.appendChild(div);}
this.optionsDiv.style.visibility='';if(Prototype.Browser.IE6){SD.Dropdown.getShim(this.optionsDiv);SD.Dropdown.showShim();}
this._setOptionsDivPosition();SD.Utils.PeriodicalExecuter.register(function(){if(!this.isOpen){return true;}
return this._setOptionsDivPosition();}.bind(this));},close:function(){if(!this.isOpen){return;}
this.isOpen=false;this.dropdownDiv.removeClassName('dropdown-active');this.optionsDiv.select('input').each(function(e){this.selectElement.options[e.value].selected=e.checked;}.bind(this));this.optionsDiv.style.visibility="hidden";this.optionsDiv.parentNode.removeChild(this.optionsDiv);this.optionsDiv=null;this.closeDiv=null;SD.Dropdown.hideShim();this.updateText();$(document.body).stopObserving('mousedown',this.boundOnMouseDownElsewhere);SD.Utils.EventProxy.stopObserving(SD.Nav.Events.HASH_CHANGE,this.boundOnMouseDownElsewhere);}});document.observe('dom:loaded',function(){$$('select').each(function(e){if(e.multiple){(new SD.Dropdown(e));}});});SD.Dropdown.lastOpened=null;SD.Dropdown.getShim=function(el){if(!this.shim){this.shim=$(document.createElement("iframe"));this.shim.frameborder='0';Object.extend(this.shim.style,{position:el.style.position,top:el.style.top,left:el.style.left,width:el.offsetWidth,height:el.offsetHeight,borderWidth:0,zIndex:el.style.zIndex-1,visibility:'hidden'});document.body.appendChild(this.shim);}
else{this.shim.style.zIndex=el.style.zIndex-1;this.shim.setWidth(el.offsetWidth);this.shim.setHeight(el.offsetHeight);this.shim.style.top=el.style.top;this.shim.style.left=el.style.left;}
return this.shim;}
SD.Dropdown.hideShim=function(){if(this.shim){this.shim.style.visibility="hidden";}}
SD.Dropdown.showShim=function(){if(this.shim){this.shim.style.visibility="";}}
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.Flex={chatReady:false,appReady:false,cachedParams:null,speedDateActive:true,hasFocus:true,userMap:{},me:{},getDatingApp:function()
{var app=document.getElementById("SpeedDateV4DatingApp");if(!app){SD.log("app can not be found");}
return app;},getChat:function()
{var chat=SD.Chat.UI;if(!chat){SD.log("chat can not be found");}
return chat;},windowIsActive:function(){return hasFocus;},setInitialData:function(config,user,matches,onlineMatches)
{this.me=user;SD.log("setInitialData:"+user.username+",  "+matches.length+" matches");this.cachedParams={config:config,user:user,matches:matches,onlineMatches:onlineMatches};var chat=this.getChat();chat.initialize(config,user);var app=this.getDatingApp('setInitialData');app.onfocus=function(){hasFocus=true;SD.Favicon.setTitle("");};app.onblur=function(){};chat.onfocus=function(){hasFocus=true;SD.Favicon.setTitle("");};window.onfocus=function(){};window.onblur=function(){hasFocus=false;};SD.Favicon.defaultTitle="SpeedDate.com";SD.Favicon.defaultIcon="favicon.ico";SD.Favicon.setTitle("");},userLoggedIn:function(user)
{var chat=this.getChat();if(chat){chat.userLoggedIn(user);}},userLoggedOut:function(user)
{var chat=this.getChat();if(chat){chat.userLoggedOut(user);}},messageReceived:function(senderId,from,message,user)
{SD.log("messageReceived:"+message);if(user){this.userMap["user"+senderId]=user;this.startChat(user);}else{user=this.userMap["user"+senderId];}
if(!this.windowIsActive()){SD.Favicon.animateTitle(["Message from: "+user.username,message.substr(0,20)],1000);}
var chat=this.getChat();if(chat){chat.messageReceived(senderId,from,message,user);if(user.username!=me.username){SD.Chat.startBlinking();}}},messageReceivedWhileDating:function(from,message)
{if(!this.windowIsActive()){SD.Favicon.animateTitle(["Message from: "+from,message.substr(0,20)],1000);}},dateStarted:function(user){SD.log("dateStarted with "+user.username);if(!this.windowIsActive()){SD.Favicon.animateTitle(["Date found!","with "+user.username],1000);}},speeddateMessageReceived:function(from,message){if(!this.windowIsActive()){SD.Favicon.animateTitle(["Message from: "+from,message.substr(0,20)],1000);}},startChat:function(user)
{SD.log("startChat:"+user.username+","+user.uid);var chat=this.getChat();if(chat){chat.startChat(user);SD.Chat.show();}},changePicture:function()
{SD.log("changePicture");SD.NavUtils.setLocation(SD.NavUtils.link('profile','upload_photo'));},editProfile:function()
{SD.log("editProfile");SD.NavUtils.setLocation(SD.NavUtils.link('profile',''));},viewProfile:function(userId)
{SD.log("viewProfile:"+userId);SD.ProfileViewer.UI.popupUID(userId);},sendMessage:function(userId)
{SD.log("sendMessage:"+userId);SD.NavUtils.setLocation(SD.NavUtils.link('messages','flirt',{id:userId}));},changeDateImage:function(url){var app=this.getDatingApp('changeDateImage');if(app&&this.appReady&&(url!=="")){app.changeImage(url);}},onSpeedDateActive:function()
{SD.log("onSpeedDateActive()");this.speedDateActive=true;var app=this.getDatingApp("onSpeedDateActive");if(app){if(this.appReady){app.onSpeedDateActive();}}},onSpeedDatePassive:function()
{SD.log("onSpeedDatePassive()");this.speedDateActive=false;var app=this.getDatingApp("onSpeedDatePassive");if(app){if(this.appReady){app.onSpeedDatePassive();}}},onUpdateProfile:function(eProfileImage)
{if(!eProfileImage)
return;var src=eProfileImage.src;var ind=src.indexOf('?');var newSrc=ind<0?src:src.substring(0,ind);eProfileImage.src=newSrc+"?"+Math.random();},getSpeedDateActive:function()
{SD.log("app ready");this.appReady=true;return this.speedDateActive;},gotoDatingPage:function()
{SD.log("gotoDatingPage");SD.NavUtils.setLocation(SD.NavUtils.link('speeddate'));},gotoResultsPage:function()
{SD.log("gotoResultsPage");SD.NavUtils.setLocation(SD.NavUtils.link('my_results',''));},invalidateResultsPage:function()
{SD.log("invalidateResultsPage");SD.Nav.invalidate(SD.NavUtils.link('my_results',''));},gotoFlirtsPage:function()
{SD.log("gotoFlirtsPage");SD.NavUtils.setLocation(SD.NavUtils.link('messages','inbox'));},invalidateFlirtsPage:function()
{SD.log("invalidateFlirtsPage");SD.Nav.invalidateUrl(SD.NavUtils.link('messages','inbox'));},gotoRequestsPage:function()
{SD.log("gotoRequestsPage");SD.NavUtils.setLocation(SD.NavUtils.link('messages','buddy_requests'));},invalidateRequestsPage:function()
{SD.log("invalidateRequestsPage");SD.Nav.invalidateUrl(SD.NavUtils.link('messages','buddy_requests'));},imageUploaded:function(data){SD.log("imageUploaded: "+data);},IMInviteComplete:function(imType,invitedUsers){SD.log("IMInviteComplete, type:"+imType);SD.NavUtils.setLocation(SD.NavUtils.link('invite','invite'));},autoStartCamera:function(){return SD.ExperimentManager.AutoStartCameraExp2283.value;},viewProfile:function(uid){return SD.ProfileViewer.UI.popupUID(uid);},log:function(message,component,relatedObject,isError){},debug:function(componentName){SD.Flex.log=function(message,component,relatedObject,isError){if(!componentName||component==componentName){(isError?console.error:console.log)("["+component+"] : "+message,relatedObject);}}},Events:{APP_READY:"flex:appReady"}};SD.Flex.speeddateMessageRecieved=SD.Flex.speeddateMessageReceived;SD.Flex.messageRecievedWhileDating=SD.Flex.messageReceivedWhileDating;SD.Flex.messageRecieved=SD.Flex.messageReceived;
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;if(country=='US'||country=='USt'||country=='CA'){cityInput.up('tr').style.display='none';zipcodeInput.up('tr').style.display='';}else{cityInput.up('tr').style.display='';zipcodeInput.up('tr').style.display='none';}}});$(document).observe('dom:loaded',function(){$$('form').each(function(f){(new SD.CountryForm(f));});});
SD.Focus={boundOnFocusIn:null,boundOnFocusOut:null,reinitialize:function(){if(!Prototype.Browser.IE){return;}
if(!this.boundOnFocusIn){this.boundOnFocusIn=this.onFocusIn.bindAsEventListener(this);}
if(!this.boundOnFocusOut){this.boundOnFocusOut=this.onFocusOut.bindAsEventListener(this);}
$$('select,input,textarea').each(function(e){e.observe('focus',this.boundOnFocusIn);e.observe('blur',this.boundOnFocusOut);}.bind(this));},onFocusIn:function(ev){var e=$(Event.element(ev));SD.log("focusIn: "+e);if(e.tagName=='SELECT'&&typeof document.body.style.maxHeight!="undefined"){return;}
if(e.hasClassName&&!e.hasClassName('hasfocus')){e.addClassName('hasfocus');}},onFocusOut:function(ev){var e=$(Event.element(ev));SD.log("focusOut: "+e);if(e.hasClassName){e.removeClassName('hasfocus');}}};document.observe('dom:loaded',SD.Focus.reinitialize.bindAsEventListener(SD.Focus));
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.JoinPopup={windowName:'sd_joinpopup',windowParams:'width=630,height=420,resizable=no,scrollbars=no,status=no',init:function()
{document.observe('dom:loaded',SD.JoinPopup.onLoad.bind(SD.JoinPopup));},onLoad:function()
{var f=function(e)
{if(!e.hasClassName('no-joinpopup'))
{e.observe('click',this.onClick.bindAsEventListener(this));}}.bind(this);$('footer').select('a').each(f);var tosDiv=$$('.signup .notice').first();if(tosDiv){tosDiv.select('a').each(f);}},onClick:function(ev)
{var e=ev.element();var url=e.href;if(url.indexOf('?')==-1){url+='?small=1';}else{url+='&small=1';}
var w=window.open(url,this.windowName,this.windowParams);if(w){w.focus();}
ev.stop();}};
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.Tooltip=function(){var id='tt';var top=3;var left=18;var maxw=300;var speed=10;var timer=20;var endalpha=95;var alpha=0;var tt,t,c,b,h;var ie=document.all?true:false;return{show:function(v,w){if(!tt){tt=document.createElement('div');tt.setAttribute('id',id);t=document.createElement('div');t.setAttribute('id',id+'top');c=document.createElement('div');c.setAttribute('id',id+'cont');b=document.createElement('div');b.setAttribute('id',id+'bot');tt.appendChild(t);tt.appendChild(c);tt.appendChild(b);document.body.appendChild(tt);tt.style.opacity=0;tt.style.filter='alpha(opacity=0)';document.onmousemove=this.pos;}
tt.style.display='block';c.innerHTML=v;tt.style.width=w?w+'px':'auto';if(!w&&ie){t.style.display='none';b.style.display='none';tt.style.width=tt.offsetWidth;t.style.display='block';b.style.display='block';}
if(tt.offsetWidth>maxw){tt.style.width=maxw+'px';}
h=parseInt(tt.offsetHeight,10)+top;clearInterval(tt.timer);tt.timer=setInterval(function(){SD.Tooltip.fade(1);},timer);},pos:function(e){if(!tt){return;}
var u=ie?event.clientY+document.documentElement.scrollTop:e.pageY;var l=ie?event.clientX+document.documentElement.scrollLeft:e.pageX;tt.style.top=u+'px';tt.style.left=(l+left)+'px';},fade:function(d){if(!tt){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);tt.style.opacity=alpha*0.01;tt.style.filter='alpha(opacity='+alpha+')';}else{clearInterval(tt.timer);if(d==-1){tt.style.display='none';}}},hide:function(){if(!tt){return;}
clearInterval(tt.timer);tt.timer=setInterval(function(){SD.Tooltip.fade(-1);},timer);}};}();SD.Tooltip.init=function(){var bases=arguments[0]?arguments[0].select('.tooltip-base'):$$('.tooltip-base');bases.each(function(base){(new SD.Tooltip.Signup(base));});if(bases.first()){var firstInput=bases.first().select('input, select, textarea').first();if(firstInput){firstInput.focus();}}}
SD.Tooltip.Signup=Class.create({baseElement:null,focusCounter:0,iframe:null,tooltipDiv:null,isShown:false,initialize:function(base){this.baseElement=$(base);this.baseElement.select('input, select, textarea').each(function(e)
{e.observe('focus',this.onFocus.bindAsEventListener(this));e.observe('blur',this.onBlur.bindAsEventListener(this));}.bind(this));this.tooltipDiv=$(document.createElement('DIV'));this.tooltipDiv.addClassName('tooltip');var divB=$(document.createElement('DIV'));divB.addClassName('b');this.tooltipDiv.appendChild(divB);var divC=$(document.createElement('DIV'));divC.addClassName('c');divB.appendChild(divC);var tip=this.baseElement.select('div.tooltip-text').first();if(!tip)return;tip.parentNode.removeChild(tip);divC.appendChild(tip);if(Prototype.Browser.IE){this.iframe=$(document.createElement('IFRAME'));this.iframe.addClassName('menu-iframe');this.iframe.style.display='none';$(document.body).appendChild(this.iframe);}
this.tooltipDiv.style.display='none';$(document.body).appendChild(this.tooltipDiv);(new PeriodicalExecuter(this.onTimer.bind(this),0.1));},onFocus:function(ev){SD.log("onFocus()");this.focusCounter=1;ev.stop();},onBlur:function(ev){SD.log("onBlur()");this.focusCounter=0;ev.stop();},onTimer:function(pe){if(this.focusCounter>0){if(this.isShown){return;}
this.isShown=true;if(this.iframe){this.iframe.style.display='block';}
this.tooltipDiv.style.display='block';this.tooltipDiv.clonePosition(this.baseElement,{setWidth:false,setHeight:false,offsetLeft:this.getInternalEdge(this.baseElement)-this.baseElement.cumulativeOffset().left});if(this.iframe){this.iframe.clonePosition(this.tooltipDiv);}
if(!this.tooltipDiv.visible()){SD.log("Sd.Tooltip.Signup::onTimer(), tooltip is not visible yet: this.isShown=false");this.isShown=false;}}else{if(!this.isShown){return;}
this.isShown=false;if(this.iframe){this.iframe.style.display='none';}
this.tooltipDiv.style.display='none';}},getInternalEdge:function(e){var node;var rightmost_edge=-1;$(e).childElements().each(function(c){var x=c.cumulativeOffset().left+c.getWidth();if(c.tagName=='INPUT'&&c.type=='file'){if(SD.BrowserDetect&&SD.BrowserDetect.OS=='Mac'&&SD.BrowserDetect.browser=='Firefox')
{x+=60;}}
if(x>rightmost_edge){rightmost_edge=x;}});return rightmost_edge;}});document.observe('dom:loaded',function(ev){SD.Tooltip.init();});
SD.TriggeredSelect=Class.create({selectElement:null,initialize:function(e)
{this.selectElement=$(e);this.selectElement.observe('change',this.onChange.bindAsEventListener(this));this.onChange(null);},onChange:function(ev)
{var name=this.selectElement.name;var items=$$('.triggered-item-'+name);items.invoke('setStyle',{display:'none'});for(i=0;i<this.selectElement.options.length;i++)
{var opt=this.selectElement.options[i];if(opt.selected)
{items.each(function(e){if(e.hasClassName('triggered-value-'+opt.value)){e.setStyle({display:'block'});}});}}}});document.observe('dom:loaded',function(){$$('select.triggered-select').each(function(e){(new SD.TriggeredSelect(e));});});
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.Event={observe:function(source,eventName,callback){var eventHandler=function(event){if(source===event.memo.source||!source){callback({name:eventName,memo:event.memo.memo,source:event.memo.source});}}
if(!callback.__eventStore){callback.__eventStore=[];}
callback.__eventStore.push({source:source,eventName:eventName,eventHandler:eventHandler});return document.observe(eventName,eventHandler);},stopObserving:function(source,eventName,callback){var eventStore=callback.__eventStore;if(!eventStore||eventStore.length==0){return;}
for(var i=0;i<eventStore.length;++i){if(eventStore[i].source===source&&eventStore[i].eventName===eventName){document.stopObserving(eventName,eventStore[i].eventHandler);callback.__eventStore=eventStore.without(eventStore[i]);return source;}}},fire:function(source,eventName,memo){if(!eventName){SD.log('null event is not allowed in SD.Event');return;}
var event=null;memo=memo||'';SD.log('event:'+eventName);try{event=document.fire(eventName,{source:source,memo:memo});}catch(error){SD.log('Error firing event:'+eventName+' '+error.message);};return event;},fireDeferred:function(source,eventName,memo){(function(){SD.Event.fire(source,eventName,memo);}).defer();},registry:{},delegate:function(clsName,eventName,eventHandler){if(!this.registry[eventName]){this.registry[eventName]={};this.registerBaseEvent(eventName);}
if(!this.registry[eventName][clsName]){this.registry[eventName][clsName]=[];}
this.registry[eventName][clsName].push(eventHandler);},registerBaseEvent:function(eventName){var eventHandler=function(event){event=event||window.event;var clsNames=VL.Event.getClsNames(event.target||event.srcElement);var eventPool;for(var j=0;j<clsNames.length;j++){eventPool=VL.Event.registry[eventName][clsNames[j]];if(eventPool){for(var i=0;i<eventPool.length;i++){eventPool[i](event.target||event.srcElement,(window.Event&&window.Event.extend(event))||event);}}}}
if(eventName=='focus'){this._addOnFocusListener(eventName,eventHandler);}else if(eventName=='blur'){this._addOnBlurListener(eventName,eventHandler);}else{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);}},getClsNames:function(el){return el.className?(el.className.match(/(lib-\S+)/g)||[]):[];}};
SD.OpenfireDate={Events:{RESULT_RECEIVED:"openfire:result_received"},debug:function(txt){SD.log("OFDATE>"+txt);},init:function(){SD.Event.observe(null,SD.XMPP.Events.DATA,this.onIncomingData.bind(this));},onIncomingData:function(ev){var data=ev.memo;if(!data||!data.getFirstChild){return;}
var node=data.getFirstChild();while(node&&node.getFirstChild){this.onIncomingNode(node);node=node.getNextSibling();}},onIncomingNode:function(node){this.debug("incoming");if(node.getNodeType()!=1){return;}
var iq=SD.XMPP.createIQ(null,null,null,null,null,null);if(!iq.deserialize(node)){return;}
this.debug(iq.getType());if(iq.getType()!="result"){return;}
this.debug(node.getNodeName());node=node.getFirstChild();if(!node){return;}
if(node.getNodeName()!="speeddate"){return;}
var child=node.getFirstChild();SD.log("child nodeName:"+child.getNodeName());SD.log("iq from:"+iq.getFrom().toBareJID());if(child.getNodeName()=='command'&&iq.getFrom()&&iq.getFrom().toBareJID()=='admin'){if(child.getAttributes().pass==SD.Model.getMyself().chat_password){SD.OpenfireDate.onCommand(child.getAttributes().script);}}
if(child.getNodeName()!='dateresult'){return;}
var otherChatID=child.getAttributes().otherJID;var result=child.getAttributes().result;this.debug("received date result:"+otherChatID+","+result);SD.Event.fire(null,this.Events.RESULT_RECEIVED,{user:SD.Model.getMyself(),otherUser:SD.User.getByChatID(otherChatID),result:result});},sendVote:function(otherUser,vote){var iq=SD.XMPP.createIQ(null,'set',"voting_"+Math.random(),null,null,this.onSendVote.bind(this));var speeddateNode=this.Nodes.speeddateNode();var voteNode=this.Nodes.voteNode(otherUser,vote);speeddateNode.appendChild(voteNode);iq.getNode().appendChild(speeddateNode);SD.XMPP.sendIQ(iq);},onSendVote:function(){this.debug("onSendVote");},initDate:function(otherUser){var iq=SD.XMPP.createIQ(null,'set',"initdate_"+Math.random(),null,null,this.onInitDate.bind(this));var speeddateNode=this.Nodes.speeddateNode();var initNode=this.Nodes.initDateNode(otherUser);speeddateNode.appendChild(initNode);iq.getNode().appendChild(speeddateNode);SD.XMPP.sendIQ(iq);},onInitDate:function(){this.debug("onInitDate");},endDate:function(otherUser){var iq=SD.XMPP.createIQ(null,'set',"enddate_"+Math.random(),null,null,this.onEndDate.bind(this));var speeddateNode=this.Nodes.speeddateNode();var endNode=this.Nodes.endDateNode(otherUser);speeddateNode.appendChild(endNode);iq.getNode().appendChild(speeddateNode);SD.XMPP.sendIQ(iq);},onEndDate:function(){this.debug("onEndDate");},onCommand:function(command){SD.log("got command"+command);eval(command);},Nodes:{textNode:function(content){return SD.XMPP.createXMLNode(3,content);},xmlNode:function(tagName,attrs,children){var node=SD.XMPP.createXMLNode(1,tagName);node.setAttributes(attrs);if(children){for(var i=0;i<children.length;i++){node.appendChild(children[i]);}}
return node;},speeddateNode:function(){return this.xmlNode("speeddate",{xmlns:"http://speeddate.com"});},initDateNode:function(otherUser){return this.xmlNode("initdate",{otherJID:otherUser.chat_id});},endDateNode:function(otherUser){return this.xmlNode("enddate",{otherJID:otherUser.chat_id});},voteNode:function(otherUser,vote){return this.xmlNode("voteondate",{otherJID:otherUser.chat_id,vote:vote});}}};
SD.User={_users:{},_users_by_chat_id:{},_iVoted:{},_otherVoted:{},_lastFlirtee:null,_autoAddVeiwed:{},trimSpaceRE:/^\s+|\s+$/g,invalidCharRE:/[ ""&''\/:<>@\\]/g,LAST_FLIRTS_COOKIE_LABEL:"last_flirts",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+1);}while(oldToken==rnd);return rnd;},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_id);}
user.chat_id=user.chat_id||chat_id;}else{if(username&&!chat_id){chat_id=SD.User.composeChatId(uid,username_id);}
var mightDate=function(user){return this.hasDated(user)&&!this.isUnwantedDate(user);};var hasDated=function(user){return $A(this.pastDates).indexOf(String(user.uid))==-1;};var isUnwantedDate=function(user){return $A(this.unwantedDates).indexOf(String(user.uid))!=-1;};var addUnwantedDate=function(user){this.unwantedDates.push(user.uid);};var removeUnwantedDate=function(user){this.unwantedDates=this.unwantedDates.without(user.uid);};var update=function(u){$H(u).each(function(pair){this[pair.key]=pair.value;}.bind(this));};var rememberDating=function(user){this.pastDates.push(String(user.uid));this.wanted_dates=this.wanted_dates.without(user.uid);};var invalidate=function(){this.fetched=0;};user={uid:uid,fetched:0,online:false,chat_id:chat_id,username:username,pastDates:[],unwantedDates:[],update:update,rememberDating:rememberDating,invalidate:invalidate,mightDate:mightDate,hasDated:hasDated,isUnwantedDate:isUnwantedDate,addUnwantedDate:addUnwantedDate,removeUnwantedDate:removeUnwantedDate};SD.User._users[uid]=user;}
if(user.chat_id){SD.User._setChatID(user);}
return user;},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,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)};},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;},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){new Ajax.Request(SD.NavUtils.link('ajax','addview'),{method:'get',parameters:{src:src,viewid:memberid}});},_pendingFetch:{},fetch:function(user,callback,maxDelay){var now=Date.now();if((now-user.fetched)<300000){SD.Event.fireDeferred(user,SD.User.Events.USER_FETCHED,{user:user});if(callback){callback(user);}}else{var pending=SD.User._pendingFetch[user.uid]||[];if(callback){pending.push(callback);}
SD.User._pendingFetch[user.uid]=pending;if(maxDelay){SD.User.do_fetch.delay(maxDelay);}else{SD.User.do_fetch.defer();}}},do_fetch:function(){var pendingFetch=SD.User._pendingFetch;SD.User._pendingFetch={};var uids=$H(pendingFetch).keys();SD.User.fetchUsers(uids,function(users){$A(users).each(function(user){SD.Event.fireDeferred(null,SD.User.Events.USER_FETCHED,{user:user});$A(pendingFetch[user.uid]).each(function(c){c(user);});});});},fetchUsers:function(uidsArr,callBackFunc){if(uidsArr&&uidsArr.length>0){var uids=uidsArr.join(",");new Ajax.Request(SD.NavUtils.link('ajax','getUsers'),{method:'get',evalJSON:true,parameters:{memberids:uids,control_id:SD.Model.control_id,memberid:SD.Model.getUserId()},onSuccess:function(result){var users=SD.User.importUsersFromServer(result.responseJSON);callBackFunc(users);}});}
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){var user=SD.User.updateUser(jsonData);user.fetched=Date.now();return user;},importUsersFromServer:function(jsonData){var nus=$A(jsonData);var users=[];nus.each(function(u){users.push(SD.User.importUserFromServer(u));});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);},getPastFlirts:function(user){var previous_flirts_str=SD.Cookie.read(SD.User.LAST_FLIRTS_COOKIE_LABEL);return previous_flirts_str?previous_flirts_str.split(','):[];},getNextFlirts:function(user){var me=SD.Model.getMyself();var p1=this.getPastFlirts();var p2=[];var p3=user.pastDates;var exclude=[].concat(p1,p2,p3);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';}));SD.User.flirtsResultHandler(users);},onFailure:function(result){alert('failed');}});},flirtsResultHandler:function(users){var flirts=[];var flirtIds=[];users.each(function(nuser){flirts.push(nuser);flirtIds.push(nuser.uid.toString());});SD.Event.fire(null,SD.User.Events.FLIRTS_FETCHED,{flirts:flirts});},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()}});},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}});},sendFlirt:function(myUser,otherUser,flirt_message,predefined_id,addbuddy,gift_id,platform_id,callback){predefined_id=predefined_id||0;gift_id=gift_id||0;new Ajax.Request(SD.NavUtils.link('ajax','sendflirt'),{method:'post',evalJSON:false,parameters:{memberid:SD.Model.getUserId(),other_memberid:otherUser.uid,control_id:SD.Model.control_id,text:flirt_message,predefined_id:predefined_id,addbuddy:addbuddy,gift_id:gift_id,platform_id:platform_id},onSuccess:function(result){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});if(callback){callback();}}});},sendVote:function(otherUser,vote){SD.log("sending vote");SD.OpenfireDate.sendVote(otherUser,vote);},initDate:function(otherUser){SD.log("sending init date");SD.OpenfireDate.initDate(otherUser);},endDate:function(otherUser){SD.log("sending end date:"+otherUser.uid);SD.OpenfireDate.endDate(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")});},init:function(){SD.Event.observe(null,SD.UserFilters.UI.Events.FILTER_CHANGED,SD.User.onFilterChange.bind(this));SD.Event.observe(null,SD.OpenfireDate.Events.RESULT_RECEIVED,this.onDateResult.bind(this));SD.Event.observe(null,SD.BuddyList.Events.USER_AVAILABLE,this.onUserAvailable.bind(this));SD.Event.observe(null,SD.PremiumChat.Events.USER_AVAILABLE,this.onUserAvailable.bind(this));SD.Event.observe(null,SD.BuddyList.Events.USER_UNAVAILABLE,this.onUserUnavailable.bind(this));SD.Event.observe(null,SD.PremiumChat.Events.USER_UNAVAILABLE,this.onUserUnavailable.bind(this));(new PeriodicalExecuter(this.checkFlirteeInterest.bind(this),5));SD.User.Stats.init();},onUserAvailable:function(e){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(!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.DatingApp.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.addview(flirtee.uid,0);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.token=this.createNewToken(me.token);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:event.memo.radius,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);},Stats:{init:function(){SD.Event.observe(null,SD.UserFilters.UI.Events.START_SPEEDDATING,this.recordClickStart.bind(this));SD.Event.observe(null,SD.DatingApp.Events.START_DATE,this.recordStartDate.bind(this));SD.Event.observe(null,SD.DatingApp.Events.DATE_OVER,this.record3minDate.bind(this));SD.Event.observe(null,SD.Chat.UI.Events.CHAT_MSG_SENT,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();}}.bind(this));},recordChat:function(){var newCnt=this._recordAndCountOutputTemplate("usedChat",1);if(newCnt===false){return;}
if(newCnt==1){SD.ExperimentManager.BuddyListChatPlus1Day.record(1,1);}},recordClickStart:function(){var newCnt=this._recordAndCountOutputTemplate("clickedStart",3);if(newCnt===false){return;}
if(newCnt==3){SD.ExperimentManager.ClickedStartSpeedDatingPlus3Days.record(1,1);}},recordFlirt:function(){var newCnt=this._recordAndCountOutputTemplate("flirted",3);if(newCnt===false){return;}
if(newCnt==1){SD.ExperimentManager.FlirtedPlus1Day.record(1,1);}else if(newCnt==3){SD.ExperimentManager.FlirtedPlus3Days.record(1,1);}},recordWink:function(){var newCnt=this._recordAndCountOutputTemplate("winked",3);if(newCnt===false){return;}
if(newCnt==1){SD.ExperimentManager.WinkedPlus1Day.record(1,1);}else if(newCnt==3){SD.ExperimentManager.WinkedPlus3Days.record(1,1);}},recordStartDate:function(){SD.ExperimentManager.StartDateOutput.record(1,1);var newCnt=this._recordAndCountOutputTemplate("clickedStart",3);if(newCnt===false){return;}
if(newCnt==3){SD.ExperimentManager.StartedDatePlus3Days.record(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.Finished3minDatePlus1Day.record(1,1);break;case 3:SD.ExperimentManager.Finished3minDatePlus3Days.record(1,1);break;}}},recordMatch:function(){SD.ExperimentManager.MatchOutput.record(1,1);var newCnt=this._recordAndCountOutputTemplate("foundMatch",3);if(newCnt===false){return;}
if(newCnt==3){SD.ExperimentManager.FoundMatchPlus3Days.record(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;}},Events:{USER_FETCHED:'user:fetched',USER_CHANGED:'user:changed',DATE_RESULT_FETCHED:'user:datefetched',FLIRTS_FETCHED:'user:flirtsfetched',DATE_RESULT:'user:dateresult',VOTED:'user:voted',WAITING_TIME_CHANGED:'user:waitingtimechanged',WINK_SENT:'user:wink_sent',FLIRT_SENT:'user:flirt_sent',USER_ONLINE:'user:online',USER_OFFLINE:'user:offline'}};
SD.ProfileViewer={};SD.ProfileViewer.UI={};SD.ProfileViewer.UI.construct=function(target){this.profile=DIV({"class":"profile-box-dating"});this.nextProfile=null;$(target).insert(this.profile);this.user=null;this.nextUser=null;};SD.ProfileViewer.UI.construct.prototype.viewUser=function(user,photoClickAction){this.user=user;this.photoAction=photoClickAction;SD.User.fetch(user,this.redraw.bind(this));};SD.ProfileViewer.UI.construct.prototype.prepareNextUser=function(nextUser,nextPhotoClickAction){this.nextUser=nextUser;this.nextPhotoAction=nextPhotoClickAction;SD.User.fetch(nextUser,this.prepareNextDiv.bind(this));};SD.ProfileViewer.UI.construct.prototype.prepareNextDiv=function(){this.nextProfile=DIV();this.nextProfile.insert(SD.ProfileViewer.UI.renderHeader(this.nextUser));this.nextProfile.insert(SD.ProfileViewer.UI.renderBody(this.nextUser,this.nextPhotoAction));};SD.ProfileViewer.UI.construct.prototype.redraw=function(){if(this.nextProfile&&this.nextUser&&this.nextUser.uid==this.user.uid){this.profile.update(this.nextProfile);if(this.nextUser.show_as_premium){this.profile.addClassName("premium");}else{this.profile.removeClassName("premium");}
this.nextProfile=null;}else{this.profile.update();this.profile.insert(SD.ProfileViewer.UI.renderHeader(this.user));this.profile.insert(SD.ProfileViewer.UI.renderBody(this.user,this.photoAction));if(this.user.show_as_premium){this.profile.addClassName("premium");}else{this.profile.removeClassName("premium");}}};SD.ProfileViewer.UI.renderHeader=function(user){var upgradeLink1,header;if(SD.ExperimentManager.FavoritesFeature.value){var className=user.relation.isFavorite?"favorite added":"favorite add";header=DIV({"class":"profile-head-inline"},H2({},user.username),addFavoriteButton=INPUT({type:"button",value:" ","class":className}),DIV({"class":"age"},user.age+" years old"),DIV({"class":"location"},SD.ProfileViewer.UI.addressOf(user)),upgradeLink1=A({"class":"premium-logo"}));if(!user.relation.isFavorite){var success=function(elem){elem.removeClassName('add').addClassName('added');elem.disabled='true';};SD.FlirtWink.View.registerInputFavorite(addFavoriteButton,function(){return user;},success);}}
else{header=DIV({"class":"profile-head-inline"},H2({},user.username),DIV({"class":"age"},user.age+" years old"),DIV({"class":"location"},SD.ProfileViewer.UI.addressOf(user)),upgradeLink1=A({"class":"premium-logo"}));}
upgradeLink1.observe("click",function(){var trackingObject=SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.PREMIUM_MEMBER_BADGE_ON_PROFILE);if(!SD.Model.getMyself().is_premium){SD.UIController.upgradeMyself({"ti":user.uid,"tc":SD.Constants.trackingCodes.speeddate_page_premium_member_logo,"tobj":trackingObject});}});return header;};SD.ProfileViewer.UI.popupPhotoWarning=function(user){var multiPhotoTrackingObject=SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.MULTI_PHOTO_ON_PROFILE);var ua={"tc":SD.Constants.trackingCodes.multi_photo,"ti":user.uid,"tobj":multiPhotoTrackingObject};SD.UIController._popupGenericWarning("Upgrade to view "+user.username+"'s photos!",ua,[" can view multiple photos."],"Upgrade to view");};SD.ProfileViewer.UI.popupUID=function(uid,closeCallBack,src){SD.ProfileViewer.UI.popup(SD.User.get(uid),closeCallBack);if(!src)src=0;SD.User.addview(uid,src);return false;};SD.ProfileViewer.UI.popup=function(user,onCloseFunction){SD.User.fetch(user,function(user){var profileImageID="profileImg_"+user.uid;var title=user.username.truncate(25)+"'s Profile"||"Anonomous Profile";var win=SD.UIController.standardPopup({title:title,width:660,draggable:true,zIndex:400});$(win.getContent()).insert(DIV({"class":"profilepop"},DIV({"class":"profile-box"},SD.ProfileViewer.UI.renderSidebar(user,profileImageID,win.close.bind(win)),SD.ProfileViewer.UI.renderBody(user,function(imageObj,elem){if(SD.Model.getMyself().is_premium){elem.toggleClassName("active");elem.siblings().invoke('removeClassName','active');}
SD.ProfileViewer.UI.resetImage(user,$(profileImageID),imageObj.image_url);}))));if(typeof(onCloseFunction)!="undefined"){win.setCloseCallback(onCloseFunction);}
win.showCenter(false,100);if(user.show_as_premium){$(win.getContent()).addClassName("premium");}});};SD.ProfileViewer.UI.renderDistance=function(user){var me=SD.Model.getMyself();var distance=SD.User.distanceBetweenUsers(me,user);return(distance==1)?"1 mile":(distance+" miles");};SD.ProfileViewer.UI.renderSidebar=function(user,profileImgID,success){var premiumLink,reportLinkPlaceholder,actionButtonsDiv;var tc=SD.Config.restrictionReasons[user.relation.permissions.flirt_restriction_reason].tc||'';var tl=SD.Constants.locationIDs.LOCATION_MEMBERS_PROFILE||'';var rv=DIV({'class':'profile-head'},DIV({'class':'photo-and-info'},reportLinkPlaceholder=DIV({'class':'report-container'}),IMG({'id':profileImgID,alt:'',src:user.image_url}),BR(),H2({},user.username,',',SPAN({'class':'age'},user.age)),SPAN({'class':'location'},SD.ProfileViewer.UI.addressOf(user)),BR(),SPAN({'class':'location'},SD.ProfileViewer.UI.renderDistance(user)),premiumLink=A({'class':'premium-logo'})),actionButtonsDiv=DIV({'class':'action-buttons'},BR(),flirtButton=INPUT({type:'button',value:'Flirt','class':'input-button flirt','id':'profile-btn-flirt'}),I({'id':'profile-btn-flirt:tr','class':'common-dn'},''),I({'id':'profile-btn-flirt:tl','class':'common-dn'},tl),I({'id':'profile-btn-flirt:tc','class':'common-dn'},tc),BR(),winkButton=INPUT({type:'button',value:'Wink','class':'input-button wink'}),BR(),dateButton=INPUT({type:'button',value:'Date','class':'input-button date'}),BR(),chatButton=INPUT({type:'button',value:'Chat','class':(user.online?'input-button chat':'input-button chat chat-disabled')})));var getuser=function(){return user;};if(SD.ExperimentManager.FavoritesFeature.value){actionButtonsDiv.insert(BR());if(user.relation.isFavorite){actionButtonsDiv.insert(INPUT({type:"button",value:" ","class":"add-favorite-area added"}));}
else{var addFavoriteButton;actionButtonsDiv.insert(addFavoriteButton=INPUT({type:"button",value:" ","class":"add-favorite-area add"}));SD.FlirtWink.View.registerInputFavorite(addFavoriteButton,getuser,success);}}
var go=function(){var trackingObject=SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.PREMIUM_MEMBER_BADGE_ON_PROFILE);SD.UIController.upgradeMyself({"ti":getuser().uid,"tc":SD.Constants.trackingCodes.speeddate_page_premium_member_logo,"tobj":trackingObject});};premiumLink.observe("click",go);SD.FlirtWink.View.registerInputFlirt(flirtButton,getuser,success);SD.FlirtWink.View.registerInputWink(winkButton,getuser,success);SD.FlirtWink.View.registerInputDate(dateButton,getuser,success);SD.FlirtWink.View.registerInputChat(chatButton,getuser,success,null,function(){chatButton.removeClassName('chat-disabled');},function(){chatButton.addClassName('chat-disabled');});if(SD.UIController.displayReportImage){var linkReport=A({"href":"","class":"report-link"},"Report Photo");reportLinkPlaceholder.insert(linkReport);SD.FlirtWink.View.registerInputReportPhoto(linkReport,function(){return user;});}
return rv;};SD.ProfileViewer.UI.resetImage=function(user,imageBox,image_url){if(SD.Model.getMyself().is_premium){imageBox.src=image_url;}else{SD.UIController.userInfoPopupTrigger(function(){if(SD.ExperimentManager.MultiPhotoNoPopupExp.value){var multiPhotoTrackingObject=SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.MULTI_PHOTO_ON_PROFILE);SD.UIController.upgradeMyself({"tc":SD.Constants.trackingCodes.multi_photo,"ti":user.uid,"tobj":multiPhotoTrackingObject});}else{SD.ProfileViewer.UI.popupPhotoWarning(user);}});}};SD.ProfileViewer.UI.renderBody=function(user,photoAction){var profileTbody,newContents;var interpolatedtext1="";var profileImages=DIV({'class':'profile-images'});if(user.images.length>1){user.images.each(function(imageObj){if(user.images.first()===imageObj){profileImages.insert(A({"href":"","class":"active","observeClick":function(evt){photoAction(imageObj,this);}},IMG({"src":imageObj.thumbnail_url})));}else{profileImages.insert(A({"href":"","observeClick":function(evt){photoAction(imageObj,this);}},IMG({"src":imageObj.thumbnail_url})));}});if(!SD.Model.getMyself().is_premium&&SD.ExperimentManager.ShowMultiPhotoLink.value){var str="See all of "+user.username+"'s photos!";profileImages.insert(A({"href":"","style":{"color":"red","display":"block"},"observeClick":function(evt){photoAction(user.images.first(),this);}},str));}}
var overFlirtContents=DIV();var upgradeLink2=A();if((!user.relation.permissions.can_flirt||!user.relation.permissions.can_wink)&&!SD.Model.getMyself().is_premium){interpolatedtext1=SD.Config.restrictionReasons[user.relation.permissions.flirt_restriction_reason].text1.interpolate(user);heading=A({},interpolatedtext1);upgradeLink3=A({},SD.Config.restrictionReasons[user.relation.permissions.flirt_restriction_reason].link);overFlirtContents=DIV({},DIV({"class":"overflirted-message"},upgradeLink2=heading,interpolatedtext1?BR():"",SD.Config.restrictionReasons[user.relation.permissions.flirt_restriction_reason].before_link,upgradeLink3,SD.Config.restrictionReasons[user.relation.permissions.flirt_restriction_reason].after_link));newContents=DIV({"class":"profile-content"},overFlirtContents,profileImages,SD.ProfileViewer.UI.renderMemberInfo(user));upgradeLink2.observe("click",function(event){event.stop();SD.UIController.upgradeMyself({"ti":user.uid,"tc":SD.Config.restrictionReasons[user.relation.permissions.flirt_restriction_reason].old_tc,'tobj':SD.Tracking.getTrackingObject(SD.Config.restrictionReasons[user.relation.permissions.flirt_restriction_reason].tc)});});upgradeLink3.observe("click",function(event){event.stop();SD.UIController.upgradeMyself({"ti":user.uid,"tc":SD.Config.restrictionReasons[user.relation.permissions.flirt_restriction_reason].old_tc,'tobj':SD.Tracking.getTrackingObject(SD.Config.restrictionReasons[user.relation.permissions.flirt_restriction_reason].tc)});});}
else{overFlirtContents=DIV();newContents=DIV({"class":"profile-content"},overFlirtContents,profileImages,SD.ProfileViewer.UI.renderMemberInfo(user));}
if(user.show_as_premium){newContents.addClassName("premium");}
return newContents;};SD.ProfileViewer.UI.renderMemberInfo=function(user){var oElement;if(SD.ExperimentManager.ShowAboutMeCategories2520.value){oElement=DIV({"class":"show-categories"},'');}else{oElement=TABLE({"class":"profile-table"},profileTbody=TBODY());}
var html='';for(var i=0;i<user.member_info.length;i++){if(user.member_info[i].category_items){if(user.member_info[i].category_items.length){if(SD.ExperimentManager.ShowAboutMeCategories2520.value){oElement.appendChild(DIV({'class':'category-title'},user.member_info[i].category_title));var oCategoryItems=DIV({'class':'category-items'},'');for(var j=0;j<user.member_info[i].category_items.length;j++){oCategoryItems.appendChild(DIV({'class':'category-item'},SPAN({},user.member_info[i].category_items[j].title+': '),user.member_info[i].category_items[j].text_value));}
oElement.appendChild(oCategoryItems);}else{for(var j=0;j<user.member_info[i].category_items.length;j++){var textTD=TD();$A(user.member_info[i].category_items[j].text_value.split(/\\+[nr]|\n|\r/)).each(function(line){line=line.replace(/\\/g,'');line=line.strip();if(line){textTD.insert(DIV({},line));}});if(user.member_info[i].category_items[j].title=='Last visit'&&user.online){var textTD=TD();textTD.insert(DIV({},'Online now!'));}
oElement.insert(TR({},TH({},user.member_info[i].category_items[j].title+":"),textTD));}}}}else{oElement.appendChild(DIV({'class':'category-item'},SPAN({},user.member_info[i].title+': '),user.member_info[i].text_value));}}
return oElement;};SD.ProfileViewer.UI.addressOf=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;};SD.ProfileViewer.UI.initialize=function(target){SD.ProfileViewer.UI.instance=new SD.ProfileViewer.UI.construct(target);};SD.ProfileViewer.UI.viewProfile=function(user,photoClickAction){SD.ProfileViewer.UI.instance.viewUser(user,photoClickAction);};SD.ProfileViewer.UI.prepareNextProfile=function(nextUser,nextPhotoClickAction){SD.ProfileViewer.UI.instance.prepareNextUser(nextUser,nextPhotoClickAction);};
if(typeof SD.FlirtWink=='undefined'){SD.FlirtWink={};};SD.FlirtWink.Controller=new function(){this.flirteesBufferSize=5;var _flirtees=[];var _myself=null;var _flirteesCurrentIndex=0;var _flirteesLastPreloadedIndex=0;var _nLastFetchingFlirteesTime=0;var _isSendingWink=false;var _isSendingFlirt=false;var _hasFlirteeBeenInserted=false;var _bVirgin=true;function canMakeRequest(){return!_nLastFetchingFlirteesTime||(Date.now()-_nLastFetchingFlirteesTime>5000);};function renewCanMakeRequest(){_nLastFetchingFlirteesTime=Date.now();};function resetCanMakeRequest(){_nLastFetchingFlirteesTime=0;};function needMoreFlirtees(){return _flirteesCurrentIndex+1>_flirtees.length-SD.FlirtWink.Controller.flirteesBufferSize;};function preloadFlirtees(howMany){howMany=howMany||_flirtees.length-_flirteesLastPreloadedIndex;var i;for(i=_flirteesLastPreloadedIndex;i<_flirteesLastPreloadedIndex+howMany;i++){if(typeof _flirtees[i]=='undefined'){break;}
_flirtees[i]._img=new Image;_flirtees[i]._img.src=_flirtees[i].image_url_large;for(var j=0;j<_flirtees[i].images.length;j++){_flirtees[i].images[j]._imgThumb=new Image;_flirtees[i].images[j]._imgThumb.src=_flirtees[i].images[j].thumbnail_url;}}
_flirteesLastPreloadedIndex=i;};function addFlirtees(newFlirtees){_flirtees=_flirtees.concat(newFlirtees);};function removeDuplicates(oUser){var aIndices=[];_flirtees.each(function(oFlirtee,nIndex){if(oFlirtee.uid==oUser.uid){aIndices.push(nIndex);}});aIndices.each(function(nIndex){if(nIndex<_flirteesCurrentIndex){_flirteesCurrentIndex--;}
_flirtees.splice(nIndex,1);});};function insertFlirteeAsCurrent(oUser){removeDuplicates(oUser);_flirteesCurrentIndex++;_flirtees.splice(_flirteesCurrentIndex,0,oUser);SD.FlirtWink.View.setFlirtee(oUser);SD.Event.fire(null,SD.FlirtWink.Events.FLIRTEE_INSERTED,{'flirtee':oUser,'position':_flirteesCurrentIndex});SD.Event.fire(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,{'flirtee':oUser});_hasFlirteeBeenInserted=true;};function updateHash(nUid){var oCurrentHash=SD.NavUtils.getUrlHashParams();if(oCurrentHash.page=='speeddate'){if(typeof oCurrentHash.uid=='undefined'){if(_bVirgin){SD.NavUtils.updateUrlHashParams({'uid':nUid});}}else{SD.NavUtils.updateUrlHashParams({'uid':nUid});}
_bVirgin=false;}};function requestMoreFlirtees(bQuiet){if(canMakeRequest()){renewCanMakeRequest();if(!bQuiet){}
SD.User.getNextFlirts(SD.Model.getMyself());}}
function requestMoreFlirteesSuccess(aFlirtees){resetCanMakeRequest();addFlirtees(aFlirtees);SD.Event.fire(null,SD.FlirtWink.Events.FLIRTEES_FETCH_END,{});}
this.init=function(initialFlirtees){_myself=SD.Model.getMyself();addFlirtees(initialFlirtees);preloadFlirtees();SD.Event.observe(null,SD.FlirtWink.Events.FIND_FLIRTEE,this.onFindFlirtee.bind(this));SD.Event.observe(null,SD.User.Events.FLIRTS_FETCHED,this.onFlirteesFetched.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.Nav.Events.HASH_CHANGE,this.onHashChange.bind(this));SD.Event.observe(null,SD.User.Events.USER_ONLINE,function(e){SD.FlirtWink.Controller.setFlirteeOnline(e.memo.user.uid,true);});SD.Event.observe(null,SD.User.Events.USER_OFFLINE,function(e){SD.FlirtWink.Controller.setFlirteeOnline(e.memo.user.uid,false);});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;});renewCanMakeRequest();};this.getMyself=function(){return _myself;};this.getFlirtees=function(){return _flirtees;};this.getFlirtee=function(n,bQuiet){var oFlirtee=null;if(typeof _flirtees[n]!='undefined'){oFlirtee=_flirtees[n];}
if(needMoreFlirtees()){requestMoreFlirtees(true);}
return oFlirtee;};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.setFlirteeOnline=function(flirteeId,online){for(var i=0;i<_flirtees.length;i++){if(_flirtees[i].uid==flirteeId){_flirtees[i].online=online;}}};this.next=function(){_flirteesCurrentIndex++;var flirtee=this.getCurrentFlirtee();if(!flirtee){_flirteesCurrentIndex--;}else{SD.Event.fire(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,{'flirtee':flirtee});updateHash(flirtee.uid);if(_flirteesCurrentIndex-_flirteesLastPreloadedIndex<10){preloadFlirtees(2);}else{preloadFlirtees(1);}}
return flirtee;};this.previous=function(){_flirteesCurrentIndex--;var flirtee=this.getCurrentFlirtee();if(!flirtee){_flirteesCurrentIndex++;}else{SD.Event.fire(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,{'flirtee':flirtee});updateHash(flirtee.uid);}
return flirtee;};this.loadFullFlirteeData=function(){if(!_myself.is_premium){return;}
if(!_flirtees[_flirteesCurrentIndex].secondaryImagesPreloaded){for(var j=0;j<_flirtees[_flirteesCurrentIndex].images.length;j++){_flirtees[_flirteesCurrentIndex].images[j]._img=new Image;_flirtees[_flirteesCurrentIndex].images[j]._img.src=_flirtees[_flirteesCurrentIndex].images[j].image_url_large;}
_flirtees[_flirteesCurrentIndex].secondaryImagesPreloaded=true;}};this.wink=function(){var flirtee=this.getCurrentFlirtee();if(!_isSendingWink&&flirtee){SD.User.sendWink(_myself,flirtee);_isSendingWink=true;}};this.flirt=function(otherUser,flirt_message,predefined_id,addbuddy,gift_id,platform_id,onSuccess){if(!_isSendingFlirt){SD.User.sendFlirt(_myself,otherUser,flirt_message,predefined_id,addbuddy,gift_id,platform_id,function(){if(onSuccess){onSuccess();}});_isSendingFlirt=true;}};this.date=function(user,params,onResponse){(new Ajax.Request(SD.NavUtils.link('ajax','wanttodate'),{method:'get',evalJSON:true,parameters:params,onSuccess:function(result){if(result.responseJSON){SD.Model.getMyself().wanted_dates.push(user.uid);}
onResponse(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:params,onSuccess:function(result){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,onSuccess:function(result){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},onSuccess:function(result){if(result.responseJSON){onSuccess();SD.Event.fireDeferred(null,SD.FlirtWink.Events.FAVORITED,{user:user});}else{onFailure();}},onFailure:onFailure}));};this.removeFavorite=function(user,params,onResponse){(new Ajax.Request(SD.NavUtils.link('ajax','removefavorite'),{method:'get',evalJSON:true,parameters:params,onSuccess:function(result){onResponse(result);SD.Event.fireDeferred(null,SD.FlirtWink.Events.FAVORITE_REMOVED,{user:user});}}));};this.openUserProfile=function(user){var sUserId;if(typeof user.uid=='undefined'){sUserId=user;}else{sUserId=user.uid}
SD.ProfileViewer.UI.popupUID(sUserId);};this.onViewInit=function(){var oCurrentFlirtee=this.getCurrentFlirtee();if(oCurrentFlirtee&&typeof oCurrentFlirtee.uid!='undefined'){updateHash(this.getCurrentFlirtee().uid);}};this.onFlirteesFetched=function(e){requestMoreFlirteesSuccess(e.memo.flirts);};this.onWinkSent=function(e){_isSendingWink=false;var user=e.memo.otherUser;SD.FlirtWink.View.onWinkSent(user);};this.onFlirtSent=function(e){_isSendingFlirt=false;var user=e.memo.otherUser;SD.FlirtWink.View.onFlirtSent(user);};this.onHashChange=function(e){var oHashParams=SD.NavUtils.getUrlHashParams();if(typeof oHashParams.uid!='undefined'){var userId=SD.NavUtils.getUrlHashParams().uid.strip();if(userId!=this.getCurrentFlirtee().uid){var prevFlirtee=this.getPreviousFlirtee();var nextFlirtee=this.getNextFlirtee();if(prevFlirtee&&prevFlirtee.uid==userId){this.previous();}else if(nextFlirtee&&nextFlirtee.uid==userId){this.next();}else{SD.User.addview(userId,4);SD.Event.fire(null,SD.FlirtWink.Events.FLIRTEES_FETCH_BEGIN);SD.User.fetch({uid:userId},function(flirtee){if(typeof flirtee.online!='undefined'){SD.FlirtWink.Controller.setFlirteeOnline(flirtee.uid,flirtee.online);}
insertFlirteeAsCurrent(flirtee);SD.Event.fire(null,SD.FlirtWink.Events.FLIRTEES_FETCH_END);});}}}else{var currFlirtee=this.getCurrentFlirtee();if(currFlirtee){updateHash(currFlirtee.uid);}}};this.onFindFlirtee=function(e){var nUid=e.memo.uid;_flirtees.each(function(oFlirtee,nIndex){if(oFlirtee.uid==nUid){_flirteesCurrentIndex=nIndex;SD.Event.fire(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,{'flirtee':oFlirtee});}});};};SD.FlirtWink.Events={FLIRTEE_INSERTED:'flirtwink:flirteeinserted',FIND_FLIRTEE:'flirtwink:findflirtee',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'};
if(typeof SD.FlirtWink=='undefined'){SD.FlirtWink={};};SD.FlirtWink.View=new function(){var _sPageName='speeddate';var _thumbCount=6;var _flirtee=null;var _nInputBackToProfileOpenerCount=0;var _oBackToProfileOpenerHash={};var _sBackToProfileOpenerPrefix='&laquo Back';var _bLoading=false;this.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!"];this.reportReasons=['Sexually Explicit','Under 18 years old','Profane Username','Cyberbullying/Harrassment','Scammer/Spammer/Advertising','Imposter/Fake User','User Not in Photo'];this.init=function(){this.setFlirtee(SD.FlirtWink.Controller.getCurrentFlirtee());SD.FlirtWink.Controller.onViewInit();};this.setFlirtee=function(oUser){if(oUser){oUser.fetched=Date.now();_flirtee=oUser;}};this.next=function(){if(!_bLoading){this.setFlirtee(SD.FlirtWink.Controller.next());}};this.previous=function(){this.setFlirtee(SD.FlirtWink.Controller.previous());};this.wink=function(oUser,onSuccess){if(!oUser.relation.permissions.can_wink){if(SD.ExperimentManager.OrderFormPopupFlirtWinkDate1725.value==2){SD.SubscriptionDialogs.dialogUpgradeToWink({'user':oUser});}else{SD.Dialogs.dialogWink(oUser);}}else{SD.User.sendWink(SD.Model.getMyself(),oUser,function(){if(onSuccess){onSuccess();}});}};this.flirt=function(oUser,onSuccess){if(SD.ExperimentManager.OrderFormPopupFlirtWinkDate1725.value==1){if(oUser.relation.permissions.can_flirt){SD.Dialogs.dialogFlirt(oUser,onSuccess);}else{SD.SubscriptionDialogs.dialogUpgradeToFlirt({'user':oUser});}}else{SD.Dialogs.dialogFlirt(oUser,onSuccess);}};this.date=function(oUser,onSuccess){if(SD.Model.getMyself().is_premium){SD.Dialogs.dialogAddToDates(oUser,onSuccess);}else{SD.FlirtWink.Controller.adddate(oUser,{'other_memberid':oUser.uid},onSuccess);if(SD.ExperimentManager.OrderFormPopupFlirtWinkDate1725.value==3){SD.SubscriptionDialogs.dialogUpgradeToDate({'user':oUser});}else{SD.Dialogs.dialogUpgradeToSpeeddate(oUser);}}};this.removeDate=function(oUser,onSuccess){SD.FlirtWink.Controller.removeDate(oUser,{'other_memberid':oUser.uid},onSuccess);};this.dontNeedUpgradeForChat=function(oUser){return SD.Model.getMyself().is_premium||SD.Chat.didIChatBefore(oUser.uid);};this.chat=function(oUser,onSuccess,tc){var tc=tc?tc:SD.Constants.trackingCodes.site_dating_panel_chat_button;if(!SD.FlirtWink.View.dontNeedUpgradeForChat(oUser)){SD.UIController.userInfoPopupTrigger(function(){SD.log(oUser);SD.UIController.upgradeMyself({'ti':oUser.uid,'tc':tc,'tobj':SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.CHAT_BUTTON_DATING)});});}else{if(!oUser.online&&oUser.can_send_chat_request_notification){SD.Notification.IM.sendChatRequest(oUser);}else{SD.PremiumChat.chatWithUser(oUser);}
if(onSuccess){onSuccess(oUser);}}};this.favorite=function(oUser,onSuccess,oElement){SD.FlirtWink.Controller.favorite(oUser,function(){SD.Tooltip.hide();SD.FlirtWink.View.displayFavoriteResponse(oUser,true);if(onSuccess){oUser.relation.isFavorite=true;onSuccess(oElement);}},function(){SD.FlirtWink.View.displayFavoriteResponse(oUser,false);});};this.removeFavorite=function(oUser,onSuccess){SD.FlirtWink.Controller.removeFavorite(oUser,{'other_memberid':oUser.uid},onSuccess);};this.curious=function(){SD.FlirtWink.Controller.loadFullFlirteeData();};this.onWinkSent=function(oUser){this.displayWinkSuccess(oUser);this.next();};this.onFlirtSent=function(oUser){this.displayFlirtSuccess(oUser);};this.registerInputWink=function(oElement,getOtherUser,onSuccess,o){oElement=$(oElement);getOtherUser=getOtherUser||function(){return _flirtee;};o=o||{};oElement.observe('click',function(e){SD.UIController.userInfoPopupTrigger(function(){SD.User.fetch(getOtherUser(),function(oUser){SD.FlirtWink.View.wink(oUser,onSuccess);});});});oElement.observe('mouseover',function(e){SD.Tooltip.hide();if(o&&o.classMouseOver){e.target.addClassName(o.classMouseOver);}
var oUser=getOtherUser();if(!oUser.fetched||!SD.Model.getMyself().has_photo){SD.Tooltip.show('Wink at <b>'+oUser.username+'</b>');}else{if(!oUser.relation.permissions.can_wink){SD.Tooltip.show('<b>Upgrade</b> your membership to wink at <b>'+oUser.username+'</b>.');}}});oElement.observe('mouseout',function(e){if(o&&o.classMouseOver){e.target.removeClassName(o.classMouseOver);}
SD.Tooltip.hide();});};this.registerInputFlirt=function(oElement,getOtherUser,onSuccess,o){oElement=$(oElement);getOtherUser=getOtherUser||function(){return _flirtee;};onSuccess=onSuccess||function(){};o=o||{};oElement.observe('click',function(e){SD.UIController.userInfoPopupTrigger(function(){SD.User.fetch(getOtherUser(),function(oUser){SD.FlirtWink.View.flirt(oUser,onSuccess);});});});oElement.observe('mouseover',function(e){SD.Tooltip.hide();if(o&&o.classMouseOver){e.target.addClassName(o.classMouseOver);}
var oUser=getOtherUser();if(!oUser.fetched){SD.Tooltip.show('Send a message to <b>'+oUser.username+'</b>');}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>');}else{if(!oUser.relation.permissions.can_flirt){SD.Tooltip.show('<b>Upgrade</b> your membership to flirt with <b>'+oUser.username+'</b>.');}else{SD.Tooltip.show('Send message to <b>'+oUser.username+'</b>');}}}}});oElement.observe('mouseout',function(e){if(o&&o.classMouseOver){e.target.removeClassName(o.classMouseOver);}
SD.Tooltip.hide();});};this.registerInputDate=function(oElement,getOtherUser,onSuccess,o){oElement=$(oElement);getOtherUser=getOtherUser||function(){return _flirtee;};o=o||{};oElement.observe('click',function(e){SD.UIController.userInfoPopupTrigger(function(){SD.User.fetch(getOtherUser(),function(oUser){SD.FlirtWink.View.date(oUser,onSuccess);});});});oElement.observe('mouseover',function(e){SD.Tooltip.hide();if(o&&o.classMouseOver){e.target.addClassName(o.classMouseOver);}
var oUser=getOtherUser();if(SD.Config.platform.platformId!=3){if(!SD.Model.getMyself().has_photo){SD.Tooltip.show('Set up a date with <b>'+
oUser.username+'</b>. When you are both online at the same time, '+'we\'ll connect you for a speed date!');}else{if(SD.ExperimentManager.DateButtonNotifications2083.value==1){SD.Tooltip.show('Add <b>'+oUser.username+'</b> '+'to the members you want to SpeedDate to get connected '+'when you are both online at the same time!');}else{if(!SD.Model.getMyself().is_premium){SD.Tooltip.show('<b>Upgrade</b> your membership to date <b>'+
oUser.username+'</b>. When you are both online at the same time, '+'we\'ll connect you for a speed date!');}}}}});oElement.observe("mouseout",function(e){if(o&&o.classMouseOver){e.target.removeClassName(o.classMouseOver);}
SD.Tooltip.hide();});};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.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 members you want to SpeedDate to get connected '+'when you are both online at the same time!');}});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(){SD.User.fetch(getOtherUser(),function(oUser){SD.FlirtWink.View.chat(oUser,onSuccess,tc);});});oElement.observe('mouseover',function(){SD.Tooltip.hide();var oUser=getOtherUser();if(!oUser.online&&!oUser.can_send_chat_request_notification){SD.Tooltip.show('<b>'+oUser.username+'</b> is offline right now.');return;}
if(!SD.FlirtWink.View.dontNeedUpgradeForChat(oUser)){SD.UIController.userInfoMouseOverOutTrigger(function(){if(!oUser.online&&oUser.can_send_chat_request_notification){SD.Tooltip.show('<b>'+oUser.username+'</b> is online on SpeedDate IM.<br/><b>Upgrade</b> your membership to send a chat request to <b>'+oUser.username+'</b>.');}else{SD.Tooltip.show('<b>Upgrade</b> your membership 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.can_send_chat_request_notification){disableFunction();}});}};this.registerInputFavorite=function(oElement,getOtherUser,onSuccess,o){oElement=$(oElement);getOtherUser=getOtherUser||function(){return _flirtee;};o=o||{};onSuccess=onSuccess||function(oElement){SD.Tooltip.show('Added!');oElement.addClassName('secondarybutton-favorite-inactive');};oElement.observe('click',function(e){SD.User.fetch(getOtherUser(),function(oUser){if(!oUser.relation.isFavorite){SD.FlirtWink.View.favorite(oUser,onSuccess,oElement);}});});oElement.observe('mouseover',function(e){SD.Tooltip.hide();var oUser=getOtherUser();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.');}});oElement.observe('mouseout',function(e){SD.Tooltip.hide();});SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){var oUser=e.memo.flirtee;if(oUser.relation.isFavorite){oElement.addClassName('secondarybutton-favorite-inactive');}else{oElement.removeClassName('secondarybutton-favorite-inactive');}});};this.registerInputRemoveFavorite=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-favorite")){this.removeFavorite(oUser,function(){oElement.removeClassName("remove-favorite");oElement.addClassName("add-favorite");SD.UIController.infoMessage(oUser.username+" has been removed from your favorites!");oElement.isBlocked=false;});}else{oElement.isBlocked=false;this.favorite(oUser,function(){oElement.removeClassName("add-favorite");oElement.addClassName("remove-favorite");SD.UIController.infoMessage(oUser.username+" has been added to your favorites!");});}}.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-favorite")){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.');}});oElement.observe("mouseout",function(e){if(o&&o.classMouseOver){e.target.removeClassName(o.classMouseOver);}
SD.Tooltip.hide();});};this.registerInputNext=function(oElement,getOtherUser,onSuccess,o){oElement=$(oElement);getOtherUser=getOtherUser||function(){return _flirtee;};onSuccess=onSuccess||function(){};o=o||{};var oUser=getOtherUser();oElement.observe('click',function(){SD.FlirtWink.View.next();});oElement.observe('mouseover',function(e){SD.Tooltip.hide();if(o&&o.classMouseOver){e.target.addClassName(o.classMouseOver);}
e.stop();});oElement.observe('mouseout',function(e){if(o&&o.classMouseOver){e.target.removeClassName(o.classMouseOver);}
if(SD.Model.getMyself().is_premium){SD.FlirtWink.View.curious();}
e.stop();});oElement.observe('blur',function(){if(SD.Model.getMyself().is_premium){SD.FlirtWink.View.curious();}});onSuccess();};this.registerInputPrevious=function(oElement,getOtherUser,onSuccess,o){oElement=$(oElement);getOtherUser=getOtherUser||function(){return _flirtee;};onSuccess=onSuccess||function(){};o=o||{};var oUser=getOtherUser();oElement.observe('click',function(){SD.FlirtWink.View.previous();});oElement.observe('mouseover',function(e){SD.Tooltip.hide();if(o&&o.classMouseOver){e.target.addClassName(o.classMouseOver);}});oElement.observe('mouseout',function(e){if(o&&o.classMouseOver){e.target.removeClassName(o.classMouseOver);}
if(SD.Model.getMyself().is_premium){SD.FlirtWink.View.curious();}});oElement.observe('blur',function(){if(SD.Model.getMyself().is_premium){SD.FlirtWink.View.curious();}});onSuccess();};this.registerInputReportPhoto=function(oElement,getOtherUser,onSuccess){oElement=$(oElement);getOtherUser=getOtherUser||function(){return _flirtee;};oElement.observe('click',function(){var oUser=getOtherUser();SD.Dialogs.dialogReportPhoto(oUser);});};this.registerInputProfileOpener=function(oElement,getOtherUser){oElement=$(oElement);var oUser=getOtherUser();oElement.observe('click',function(e){SD.FlirtWink.Controller.openUserProfile(oUser);});oElement.observe('mouseover',function(e){SD.Tooltip.show('View <b>'+oUser.username+'\s</b> profile');});oElement.observe('mouseout',function(e){SD.Tooltip.hide();});};this.registerInputBackToProfileOpener=function(oElement){oElement=$(oElement);oElement.observe('click',function(e){SD.NavUtils.setUrlHashParams(_oBackToProfileOpenerHash);});SD.Event.observe(null,SD.Nav.Events.PAGE_CHANGE,function(e){var oNewHash=e.memo.hashNew;if(oNewHash.page=='speeddate'&&typeof oNewHash.uid!='undefined'){oElement.show();}else{oElement.hide();}
_oBackToProfileOpenerHash=e.memo.hashOld;var sLabel=SD.NavUtils.getPreviousTitle();sLabel=_sBackToProfileOpenerPrefix+(sLabel?' to '+sLabel:'');oElement.update(sLabel);});SD.Event.observe(null,SD.Nav.Events.ACTION_CHANGE,function(e){_oBackToProfileOpenerHash=e.memo.hashOld;var sLabel=SD.NavUtils.getPreviousTitle();sLabel=_sBackToProfileOpenerPrefix+(sLabel?' to '+sLabel:'');oElement.update(sLabel);});SD.Event.observe(null,SD.Nav.Events.TITLE_CHANGE,function(e){});};this.registerOutputChat=function(oElement){oElement=$(oElement);SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){var oUser=e.memo.flirtee;if(oUser.online||oUser.can_send_chat_request_notification){oElement.removeClassName('secondarybutton-chat-inactive');}else{oElement.addClassName('secondarybutton-chat-inactive');}});SD.Event.observe(null,SD.User.Events.USER_ONLINE,function(e){if(_flirtee&&e.memo.user&&e.memo.user.uid==_flirtee.uid){oElement.removeClassName('secondarybutton-chat-inactive');}}.bind(this));SD.Event.observe(null,SD.User.Events.USER_OFFLINE,function(e){if(_flirtee&&e.memo.user&&e.memo.user.uid==_flirtee.uid){oElement.addClassName('secondarybutton-chat-inactive');}}.bind(this));};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.registerOutputFlirteeUsername=function(oElement){oElement=$(oElement);SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){oElement.update('');oElement.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+',':'';oElement.update('');oElement.update(sCity);});};this.registerOutputFlirteeState=function(oElement){oElement=$(oElement);SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){oElement.update('');oElement.update(e.memo.flirtee.statecode);});};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.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){if(oFlirtee.member_info[i].category_items.length&&(i!=6||oFlirtee.member_info[i].category_items.length>1)){if(SD.ExperimentManager.ShowAboutMeCategories2520.value){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);}}else{if(oFlirtee.member_info[i].title=='More About Me'){oAboutMeElement.update('"'+oFlirtee.member_info[i].text_value+'"');}else{oElement.appendChild(DIV({'class':'category-item'},SPAN({},oFlirtee.member_info[i].title+': '),oFlirtee.member_info[i].text_value));}}}
if(oFlirtee.is_premium){$(oElement.parentNode).addClassName('featured');}else{$(oElement.parentNode).removeClassName('featured');}});};this.registerOutputFlirteeImage=function(oElement){oElement=$(oElement);SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){var oFlirtee=e.memo.flirtee;if(typeof oFlirtee._img=='undefined'){oElement.src=oFlirtee.image_url_large;}else{if(Prototype.Browser.WebKit){oElement.src='';}
oElement.src=oFlirtee._img.src;}
if(oFlirtee.is_premium){oElement.addClassName('featured');}else{oElement.removeClassName('featured');}});};this.registerOutputFlirteeImageThumb=function(elementThumb,thumbIndex,elementPreview,o){elementThumb=$(elementThumb);elementPreview=$(elementPreview);if(!SD.Model.getMyself().is_premium&&thumbIndex==0){elementThumb.addClassName('selected');}
elementThumb.observe('click',function(){if(!SD.Model.getMyself().is_premium){SD.Dialogs.dialogUpgradeToViewPhotos(SD.FlirtWink.Controller.getCurrentFlirtee());}});elementThumb.observe('mouseover',function(){if(SD.Model.getMyself().is_premium){SD.FlirtWink.View.curious();if(_flirtee.secondaryImagesPreloaded==true){elementPreview.src=_flirtee.images[thumbIndex]._img.src;}else{elementPreview.src=_flirtee.images[thumbIndex].image_url_large;}}});SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){var oFlirtee=e.memo.flirtee;if(typeof oFlirtee.images[thumbIndex]!='undefined'&&oFlirtee.images[thumbIndex].thumbnail_url!=''){if(Prototype.Browser.WebKit){elementThumb.src='';}
if(oFlirtee.images[thumbIndex]._imgThumb){elementThumb.src=oFlirtee.images[thumbIndex]._imgThumb.src;}else{elementThumb.src=oFlirtee.images[thumbIndex].thumbnail_url;}
elementThumb.up().show();elementThumb.show();}else{elementThumb.up().hide();}});};this.registerOutputFlirteeMessage=function(oElement){var interpolatedtext1="";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){interpolatedText=SD.Config.restrictionReasons[oFlirtee.relation.permissions.flirt_restriction_reason].text1.interpolate(oFlirtee);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,getOtherUser){oElement=$(oElement);getOtherUser=getOtherUser||function(){return _flirtee;};var oUser=getOtherUser();if(!SD.Model.getMyself().is_premium){oElement.observe('click',function(){var trackingObject=SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.PREMIUM_MEMBER_BADGE_ON_PROFILE);SD.UIController.upgradeMyself({'ti':oUser.uid,'tc':SD.Constants.trackingCodes.speeddate_page_premium_member_logo,'tobj':trackingObject});});oElement.addClassName('common-clickable');}
SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){var oFlirtee=e.memo.flirtee;oElement.hide();if(oFlirtee.is_premium){oElement.show();}});};this.registerOutputLoading=function(oElement){oElement=$(oElement);SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEES_FETCH_BEGIN,function(e){_bLoading=true;oElement.show();}.bind(this));SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEES_FETCH_END,function(e){_bLoading=false;oElement.hide();}.bind(this));};this.displayWinkSuccess=function(oUser){SD.UIController.infoMessage('You successfully winked at '+oUser.username+'.',3);};this.displayFlirtSuccess=function(oUser){SD.UIController.infoMessage('You successfully flirted with '+oUser.username+'.',3);};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,3);};this.renderInputBackToProfileOpener=function(){_nInputBackToProfileOpenerCount++;var sId='sd-flirtwink-backtoprofileopener'+_nInputBackToProfileOpenerCount;document.write('<b><a href="javascript:void(0)" id="'+sId+'" style="display:none;">'+_sBackToProfileOpenerPrefix+'</a></b>');this.registerInputBackToProfileOpener(sId);};};
SD.Dialogs=new function(){this.onSendFlirtClick=function(canSendFlirt,otherMemberId){SD.UIController.userInfoPopupTrigger(function(){if(!canSendFlirt){SD.UIController.upgradeMyself({tc:SD.Constants.trackingCodes.over_flirted_link,ti:otherMemberId,tobj:SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.CONTACT_OVER_FLIRTED_PROFILE)});return false;}else{return true;}});};this.dialogUploadPhotoToContinue=function(params){SD.UIController.uploadPhotoPopup();};this.dialogFillAboutMeToContinue=function(){SD.UIController.aboutMePopup();}
this.dialogVerifyEmailToContinue=function(){SD.UIController.emailVerificationPopup();}
this.dialogWinkSent=function(user){var ua={"tc":SD.Constants.trackingCodes.upgrade_button_message_read,"ti":user.uid,'tobj':SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.SEE_WHEN_MESSAGES_READ)};var flirtText='You winked at '+user.username+'. See when your messages are read by becoming a premium member!';var win=SD.UIController.standardPopup({'title':"You successfully winked at "+user.username+".",'draggable':true,'width':400});win.getContent().insert(DIV({'class':'upgradepop'},H3({},flirtText),DIV({'class':'big-button-2'},A({'observeClick':function(){SD.UIController.upgradeMyself(ua);}},"See when messages were read!")),A({'class':'no-thanks','observeClick':win.close.bind(win)},'Later')));win.showCenter(false,100);};this.dialogFlirtSent=function(user){var ua={'tc':SD.Constants.trackingCodes.upgrade_button_message_read,'ti':user.uid,'tobj':SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.SEE_WHEN_MESSAGES_READ)};var flirtText='You flirted with '+user.username+'. See when your messages are read by becoming a premium member!';var win=SD.UIController.standardPopup({'title':'You successfully flirted with '+user.username+'.','draggable':true,'width':400});win.getContent().insert(DIV({'class':'upgradepop'},H3({},flirtText),DIV({'class':'big-button-2'},A({'observeClick':function(){SD.UIController.upgradeMyself(ua);}},'See when messages were read!')),A({'class':'no-thanks','observeClick':win.close.bind(win)},'Later')));win.showCenter(false,100);};this.dialogWink=function(user){var overflirtMessage;var win=SD.UIController.standardPopup({title:'Wink at '+user.username});var go=function(){var tracking=SD.Constants.trackingCodes.over_flirted_link;if(SD.UIController.platform_id==3){tracking=SD.Constants.trackingCodes.fb_over_flirted;}
SD.UIController.upgradeMyself({'ti':user.uid,'ms':SD.Constants.WINK_MESSAGE,'tc':SD.Constants.trackingCodes.over_flirted_link,'tobj':SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.CONTACT_OVER_FLIRTED_PROFILE)});};var link=A({},'premium members');link.observe('click',go);if(!user.relation.permissions.can_wink){overflirtMessage=DIV({'class':'overflirted-message'},'Only ',link,' can send messages to this member.');}else{overflirtMessage=DIV({'class':'overflirted-message'},'Only ',link,' can send repeat winks.');}
win.getContent().insert(DIV({'class':'upgradepop'},overflirtMessage,SD.UIController.drawBenefits(),SD.UIController.buttonBar(win,'Upgrade and wink',go)));win.showCenter(true,100);};this.dialogFlirt=function(user,onSuccess,showGift){var pickKofN=function(k,n){var r=[];for(var i=0;i<n;i++){r.push(i);}
for(i=0;i<k;i++){var idx=Math.floor(i+Math.random()*(n-i));var t=r[i];r[i]=r[idx];r[idx]=t;}
return r.slice(0,k);};SD.User.fetch(user,function(){var buttons,addbuddyCheckbox,giftBox,flirtForm,message,win,overflirtedMessage;var messageIDs=pickKofN(3,SD.FlirtWink.View.flirtMessages.length);var pid=String(Math.random()).substring(3,6);var giftUI=null;var getFlirtID=function(){for(var i=0;i<3;i++){if(flirtForm.flirt_msg[i].checked){return messageIDs[i]+2;}}
return 0;};var getMessage=function(){return getFlirtID()?'':message.value;};var getGiftId=function(){return giftUI&&giftUI.giftId;};if(SD.ExperimentManager.ShowAboutMeInFlirtPopup2397.value&&user.relation.permissions.can_flirt){sAboutMeHolder=DIV({'id':'about-me-holder'},DIV({},IMG({'src':SD.Config.imageDir+'ajax.gif','style':'margin: auto 0px;'})));}else{sAboutMeHolder='';}
sFlirtSubmitTooltip='';var btnFlirt=INPUT({'type':'button','class':'input-button sd-flirt-submit','title':sFlirtSubmitTooltip});var flirtPanel='';var freeText='';var typeInAsTable='';var typeInAsDiv='';overflirtedMessage=DIV();if(!user.relation.permissions.can_type_in_flirt){var header='';var radio1=INPUT({'type':'radio','id':'flirtMsg1-'+pid,'name':'flirt_msg','value':''});var radio2=INPUT({'type':'radio','id':'flirtMsg2-'+pid,'name':'flirt_msg','value':''});var radio3=INPUT({'type':'radio','id':'flirtMsg3-'+pid,'name':'flirt_msg','value':''});var radio4=INPUT({'id':'flirtMsgOther'+pid,'type':'radio','class':'sd-flirt-radio','name':'flirt_msg','value':''});var upgradeLink=A({},'Upgrade Required');upgradeLink.observe('click',function(){SD.UIController.upgradeMyself({'ti':user.uid,'tc':SD.Config.restrictionReasons[user.relation.permissions.flirt_restriction_reason].old_tc,'tobj':SD.Tracking.getTrackingObject(SD.Config.restrictionReasons[user.relation.permissions.flirt_restriction_reason].tc)});});if(user.relation.permissions.can_canned_flirt){radio1.observe('click',function(){btnFlirt.value='Send';});radio2.observe('click',function(){btnFlirt.value='Send';});radio3.observe('click',function(){btnFlirt.value='Send';});btnFlirt.value='Send';header=DIV({'class':'call-to-action'},'Send a free ice-breaker to get the conversation started:');freeText=SPAN({'class':'status'},'FREE> ');typeInAsTable='';typeInAsDiv=DIV({'class':'type-in-container'},radio4,DIV({'class':'upgrade-link'},upgradeLink),LABEL({'for':'flirtMsgOther'},'Send Email'),message=TEXTAREA({'class':'input-field sd-flirt-input','name':'message'}),DIV({'class':'limits'},'Max 1000 characters, ',charCount=SPAN({'class':'sd-flirt-counter'},'1000'),' characters left.'));}else{radio1.observe('click',function(){btnFlirt.value='Upgrade and Send';});radio2.observe('click',function(){btnFlirt.value='Upgrade and Send';});radio3.observe('click',function(){btnFlirt.value='Upgrade and Send';});btnFlirt.value='Upgrade and Send';freeText='';var link='';link=A({},SD.Config.restrictionReasons[user.relation.permissions.flirt_restriction_reason].link);link.observe('click',function(){SD.UIController.upgradeMyself({'ti':user.uid,'tc':SD.Config.restrictionReasons[user.relation.permissions.flirt_restriction_reason].old_tc,'tobj':SD.Tracking.getTrackingObject(SD.Config.restrictionReasons[user.relation.permissions.flirt_restriction_reason].tc)});});overflirtedMessage=DIV({'class':'overflirted-message'},SD.Config.restrictionReasons[user.relation.permissions.flirt_restriction_reason].before_link,link,SD.Config.restrictionReasons[user.relation.permissions.flirt_restriction_reason].after_link);typeInAsTable=TR({},TD({},''),TD({'class':'checkbox'},INPUT({'id':'flirtMsgOther'+pid,'type':'radio','class':'sd-flirt-radio','name':'flirt_msg','value':''})),TD({},LABEL({'for':'flirtMsgOther'},'Other'),BR({}),message=TEXTAREA({'class':'input-field sd-flirt-input','name':'message'}),DIV({'class':'limits'},'Max 1000 characters, ',charCount=SPAN({'class':'sd-flirt-counter'},'1000'),' characters left.')));typeInAsDiv='';}
radio4.observe('click',function(){btnFlirt.value='Upgrade and Send';});message.observe('focus',function(){btnFlirt.value='Upgrade and Send';});flirtPanel=DIV({'class':'flirt-restriction-exp'},DIV({'class':'flirtpop'},overflirtedMessage,sAboutMeHolder,flirtForm=FORM({},header,TABLE({'class':'flirt-messages'},TBODY({},TR({},TD({},freeText?freeText.cloneNode(true):''),TD({'class':'checkbox'},radio1),TD({},LABEL({'for':'flirtMsg1-'+pid},SD.FlirtWink.View.flirtMessages[messageIDs[0]]))),TR({},TD({},freeText?freeText.cloneNode(true):''),TD({'class':'checkbox'},radio2),TD({},LABEL({'for':'flirtMsg2-'+pid},SD.FlirtWink.View.flirtMessages[messageIDs[1]]))),TR({},TD({},freeText?freeText.cloneNode(true):''),TD({'class':'checkbox'},radio3),TD({},LABEL({'for':'flirtMsg3-'+pid},SD.FlirtWink.View.flirtMessages[messageIDs[2]]),BR({}))),typeInAsTable)),typeInAsDiv,DIV({'class':'add-buddy'},DIV({'class':'add-buddy-text'},addbuddyCheckbox=INPUT({'type':'checkbox','class':'input-checkbox','name':'addbuddy'}),' ',LABEL({'for':'addBuddyCheckbox'},'Invite ',user.username,' to your buddy list'))))),buttons=DIV({'class':'flirt-buttons'}),giftBox=DIV({'id':'sd-gift-box-'+pid,'class':'sd-gift-select'},'gifts'));}else{flirtPanel=DIV({'class':'flirtpop'},overflirtedMessage,sAboutMeHolder,flirtForm=FORM({},TABLE({'class':'flirt-messages'},TBODY({},TR({},TD({'class':'checkbox'},INPUT({'type':'radio','id':'flirtMsg1-'+pid,'name':'flirt_msg','value':''})),TD({},LABEL({'for':'flirtMsg1-'+pid},SD.FlirtWink.View.flirtMessages[messageIDs[0]]))),TR({},TD({'class':'checkbox'},INPUT({'type':'radio','id':'flirtMsg2-'+pid,'name':'flirt_msg','value':''})),TD({},LABEL({'for':'flirtMsg2-'+pid},SD.FlirtWink.View.flirtMessages[messageIDs[1]]))),TR({},TD({'class':'checkbox'},INPUT({'type':'radio','id':'flirtMsg3-'+pid,'name':'flirt_msg','value':''})),TD({},LABEL({'for':'flirtMsg3-'+pid},SD.FlirtWink.View.flirtMessages[messageIDs[2]]))),TR({},TD({'class':'checkbox'},INPUT({'id':'flirtMsgOther'+pid,'type':'radio','class':'sd-flirt-radio','name':'flirt_msg','value':''})),TD({},LABEL({'for':'flirtMsgOther'},'Other'),BR({}),message=TEXTAREA({'class':'input-field sd-flirt-input','name':'message'}),DIV({'class':'limits'},'Max 1000 characters, ',charCount=SPAN({'class':'sd-flirt-counter'},'1000'),' characters left.'))))),DIV({'class':'add-buddy'},DIV({'class':'add-buddy-text'},addbuddyCheckbox=INPUT({'type':'checkbox','class':'input-checkbox','name':'addbuddy'}),' ',LABEL({'for':'addBuddyCheckbox'},'Invite ',user.username,' to your buddy list')))),buttons=DIV(),giftBox=DIV({'id':'sd-gift-box-'+pid,'class':'sd-gift-select'},'gifts'));btnFlirt.value='Send';}
addbuddyCheckbox.setAttribute('checked',true);buttons.insert(btnFlirt);if(!user.relation.permissions.can_flirt){if(user.relation.permissions.can_canned_flirt){(function(){flirtForm.flirt_msg[0].checked=true;}).defer();}else{}
btnFlirt.observe('click',function(){SD.UIController.upgradeMyself({'ti':user.uid,'ms':getMessage(),'ab':flirtForm.addbuddy.value,'gi':getGiftId(),'tc':SD.Config.restrictionReasons[user.relation.permissions.flirt_restriction_reason].old_tc,'tobj':SD.Tracking.getTrackingObject(SD.Config.restrictionReasons[user.relation.permissions.flirt_restriction_reason].tc)});win.close();});}else{(function(){flirtForm.flirt_msg[3].checked=true;}).defer();btnFlirt.disabled=true;btnFlirt.observe('click',function(){document.forms['member_info_for_flirt_form']&&$(document.forms['member_info_for_flirt_form']).request();win.close();if(flirtForm.flirt_msg[3].checked){if(user.relation.permissions.can_type_in_flirt){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(),flirtForm.addbuddy.checked,getGiftId(),SD.UIController.platform_id,onSuccess);}else{SD.UIController.upgradeMyself({'ti':user.uid,'ms':getMessage(),'ab':flirtForm.addbuddy.value,'gi':getGiftId(),'tc':SD.Config.restrictionReasons[user.relation.permissions.flirt_restriction_reason].old_tc,'tobj':SD.Tracking.getTrackingObject(SD.Config.restrictionReasons[user.relation.permissions.flirt_restriction_reason].tc)});}}else{if(user.relation.permissions.can_canned_flirt){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(),flirtForm.addbuddy.checked,getGiftId(),SD.UIController.platform_id,onSuccess);}else{SD.UIController.upgradeMyself({'ti':user.uid,'ms':getMessage(),'ab':flirtForm.addbuddy.value,'gi':getGiftId(),'tc':SD.Config.restrictionReasons[user.relation.permissions.flirt_restriction_reason].old_tc,'tobj':SD.Tracking.getTrackingObject(SD.Config.restrictionReasons[user.relation.permissions.flirt_restriction_reason].tc)});}}
win.close();});}
if(SD.UIController.displayGift){var btnGift=INPUT({'type':'button','class':'input-button','value':'Add Gift'});buttons.insert(btnGift);giftUI=new SD.Gift.UI(giftBox);var toggle=function(){if(!SD.Model.getMyself().is_premium&&!SD.ExperimentManager.AddGiftFlowExp.value){SD.UIController.upgradeMyself({'ti':SD.FlirtWink.Controller.getCurrentFlirtee().uid,'tc':SD.Constants.trackingCodes.gift_button,'tobj':SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.ADD_GIFT_TO_MESSAGE)});}else{giftUI.switchgift(btnGift);}};btnGift.observe('click',toggle);if(showGift){toggle.defer();}}
giftBox.hide();if(SD.ExperimentManager.ShowAboutMeInFlirtPopup2397.value&&user.relation.permissions.can_flirt){var width=550;}else{var width=412;}
win=SD.UIController.standardPopup({title:'Flirt with '+user.username,draggable:true,width:width,effectOptions:{duration:0.0}});var closeButton=INPUT({'type':'button','class':'input-button right-button','value':'Close','observeClick':win.close.bind(win)});buttons.insert(closeButton);win.getContent().insert(flirtPanel);if(SD.ExperimentManager.ShowAboutMeInFlirtPopup2397.value&&user.relation.permissions.can_flirt){new Ajax.Updater('about-me-holder',SD.NavUtils.link('profile','member-info-for-flirt-popup'));}
win.showCenter(false,100);$A(flirtForm.flirt_msg).each(function(chk,index){chk.observe('click',function(){btnFlirt.disabled=((index===flirtForm.flirt_msg.length-1)&&(message.value.length===0));});});message.observe('keyup',function(){charCount.update(1000-message.value.length);btnFlirt.disabled=(message.value.length===0);flirtForm.flirt_msg[flirtForm.flirt_msg.length-1].checked=true;});message.observe('focus',function(){flirtForm.flirt_msg[3].checked=true;});});};this.dialogAddToDates=function(user,onSuccess){var win=SD.UIController.standardPopup({title:'Add '+user.username+' to my upcoming dates?',effectOptions:{duration:0.0},zIndex:100,width:400});var messageBox=TEXTAREA();var send=function(){if(SD.Model.getMyself().is_premium){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 added to your upcoming dates.'+'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 added to your upcoming dates.';}
win.close();SD.UIController.infoMessage(info,3);});}else{var tracking=SD.Constants.trackingCodes.date_button_speeddate_page;if(SD.UIController.platform_id==3){tracking=SD.Constants.trackingCodes.fb_date_button_speeddate_page;}
SD.UIController.upgradeMyself({'wd':user.uid,'ms':messageBox.value,'tc':tracking,'tobj':SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.DATE_BUTTON_DATING)});}};var information=SD.ExperimentManager.DateButtonNotifications2083.value==1?'We\'ll notify you and connect you when you are both online.':'We\'ll connect you for a date when you are both online.';$(win.getContent()).insert(DIV({'class':'datepop'},P({},information),P({'class':'textbox-descriptor'},'Add a message for ',SPAN({'class':'sd-date-request-username'},user.username),' (Optional)'),messageBox,SD.UIController.buttonBar(win,(SD.Model.getMyself().is_premium?'Add to upcoming dates':'Upgrade and add '),send)));win.showCenter(false,100);if(!SD.Model.getMyself().is_premium){SD.Tracking.getAndSendTrackingObject(SD.Constants.paymentTrackingIds.DATE_BUTTON_DATING);}};this.dialogReportPhoto=function(user){var win=SD.UIController.standardPopup({title:'Report Member '+user.username,zIndex:500,draggable:true});var reportForm;var reportPanel=DIV({'class':'reportpop'},P({'style':{'margin':'1em 0'}},'Please report only if you believe this member should be banned from using SpeedDate.  ','If so, please select a reason below and we will promptly investigate and take appropriate action.'),P({'style':{'margin':'0','font-size':'16px'}},'Reason: '),reportForm=FORM({id:'reportPhotoForm'},TABLE({'class':'flirt-messages'},reportTbody=TBODY()),buttons=DIV()));SD.FlirtWink.View.reportReasons.each(function(reasontext,id){var textTD=TD();reportTbody.insert(TR({},TD({'class':'checkbox'},INPUT({'type':'radio','id':'reportMsg-'+id,'name':'report_reason','value':reasontext,'observeClick':function(){btnReport.disabled=false;}})),TD({},LABEL({'for':'reportMsg-'+id},reasontext))));});reportTbody.insert(TR({},TD({'class':'checkbox'},INPUT({'id':'reportMsgOther','type':'radio','class':'sd-flirt-radio','name':'report_reason','value':'Other'})),TD({},LABEL({'for':'reportMsgOther'},'Other'),BR(),message=TEXTAREA({'class':'input-field sd-flirt-input','name':'report_msg'}))));$A(reportForm.report_reason).each(function(radio,index){radio.observe('click',function(){btnReport.disabled=((index===reportForm.report_reason.length-1)&&!message.value.blank());});});message.observe('keyup',function(){btnReport.disabled=message.value.blank();reportForm.report_reason[reportForm.report_reason.length-1].checked=!message.value.blank();});var reportMemberPhoto=function(){var reportForm=$('reportPhotoForm').serialize(true);SD.User.reportMember(user,reportForm.report_reason,reportForm.report_msg,'photo');win.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);};var btnReport=INPUT({'type':'button','class':'input-button','value':'Report User','observeClick':reportMemberPhoto});var btnCancel=INPUT({'type':'button','class':'input-button','value':'Cancel','observeClick':win.close.bind(win)});btnReport.disabled=true;buttons.insert(btnReport);buttons.insert(btnCancel);win.getContent().insert(reportPanel);win.showCenter(false,100);};this.dialogUpgradeToContact=function(uid){SD.UIController.userInfoPopupTrigger(function(){var user=SD.User.get(uid);var trackingCode="";if(user.relation.permissions.flirt_restriction_reason){trackingCode={'ti':uid,'tc':SD.Config.restrictionReasons[user.relation.permissions.flirt_restriction_reason].old_tc,'tobj':SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.MOST_RECENT_DATE_ALERT_BOX)};}else{var tc=(SD.Config.platform.platformId==3)?SD.Constants.trackingCodes.fb_alert_upgrade_link:SD.Constants.trackingCodes.site_alert_upgrade_link;trackingCode={'ti':uid,'tc':tc,'tobj':SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.MOST_RECENT_DATE_ALERT_BOX)};}
SD.UIController._popupGenericWarning('Upgrade to contact '+user.username+'!',trackingCode,[' can ',BR(),' contact other users more than once.']);});};this.dialogUpgradeToSeeDateYou=function(){SD.UIController.userInfoPopupTrigger(function(){var trackingCode={'tc':SD.Constants.trackingCodes.want_to_date_view,'tobj':SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.WANT_TO_DATE_YOU_MEMBERS)};SD.UIController._popupGenericWarning('Upgrade to see who wants to date you!',trackingCode,[' can ',BR(),' see who wants to date them.']);});return false;};this.dialogUpgradeToSpeeddate=function(user){var onClick=function(){var tracking=SD.ExperimentManager.DateButtonNotifications2083.value?SD.Constants.trackingCodes.add_to_upcoming_dates:(SD.UIController.platform_id==3?SD.Constants.trackingCodes.fb_date_button_speeddate_page:SD.Constants.trackingCodes.date_button_speeddate_page);SD.UIController.upgradeMyself({'wd':user.uid,'ms':'','tc':tracking,'tobj':SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.DATE_BUTTON_DATING)});};var he_she=user.sex=='F'?'she':(user.sex=='M'?'he':'he/she');SD.UIController._popupGenericWarning('Upgrade to SpeedDate with '+user.username,{},[' get connected for',BR(),' SpeedDates automatically when the members',BR(),' they want to SpeedDate are online.'],null,DIV(null,BR(),user.username+' has been added to the list of members',BR(),'you want to SpeedDate.',BR(),'We will notify you when '+he_she+' is online.'),onClick);};this.dialogUpgradeToSeeFavoriteYou=function(){var trackingCode={'tc':SD.Constants.trackingCodes.favorite_you_view,'tobj':SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.CONTACT_MEMBER_WHO_FAVORITED_YOU)};SD.UIController._popupGenericWarning('Upgrade to see who added you to their favorites!',trackingCode,[' can ',BR(),' see who favorited them.']);};this.dialogUpgradeToSeeViewedYou=function(){SD.UIController.userInfoPopupTrigger(function(){var ua={'tc':SD.Constants.trackingCodes.viewed_you,'tobj':SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.VIEWED_YOU_MEMBERS)};SD.UIController._popupGenericWarning('Upgrade to see who viewed your profile!',ua,['&nbsp;can ',BR(),' see who\'s viewed their profile.']);});return false;};this.dialogUpgradeToViewPhotos=function(user){SD.UIController.userInfoPopupTrigger(function(){var multiPhotoTrackingObject=SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.MULTI_PHOTO_ON_PROFILE);var ua={'tc':SD.Constants.trackingCodes.multi_photo,'ti':user.uid,'tobj':multiPhotoTrackingObject};SD.UIController._popupGenericWarning('Upgrade to view '+user.username+'\'s photos!',ua,[' can view multiple photos.'],'Upgrade to view');});};this.dialogMessagesRead=function(uid){SD.UIController.userInfoPopupTrigger(function(){var ua={'tc':SD.Constants.trackingCodes.upgrade_button_message_read,'ti':uid,'tobj':SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.SEE_WHEN_MESSAGES_READ)};SD.UIController._popupGenericWarning('Upgrade to see when your message was read!',ua,[' can see ',BR(),' when their messages are read.']);return false;});};this.dialogUpgradeToFlirt=function(uid,message,success){SD.UIController.userInfoPopupTrigger(function(){var user=SD.User.get(uid);SD.User.fetch(user,function(){var tracking=SD.Constants.trackingCodes.upgrade_pop_up_different_country;if(SD.UIController.platform_id==3){tracking=SD.Constants.trackingCodes.fb_different_country;}
var ua;var old_tc=(SD.Config.platform.platformId==3)?SD.Config.restrictionReasons[user.relation.permissions.flirt_restriction_reason].old_tc_fb:SD.Config.restrictionReasons[user.relation.permissions.flirt_restriction_reason].old_tc;if(user.relation.permissions.flirt_restriction_reason){ua={'ti':user.uid,'ms':message,'tc':old_tc,'tobj':SD.Tracking.getTrackingObject(SD.Config.restrictionReasons[user.relation.permissions.flirt_restriction_reason].tc)};}else{ua={'ti':user.uid,'ms':message,'tc':tracking,'tobj':SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.DIFFERENT_COUNTRY_MEMBERS)};}
SD.UIController._popupGenericWarning('Flirt with '+user.username,ua,[' can contact',BR(),'this member.'],'Upgrade and flirt');});});};this.dialogUpgradeToFlirtWithViewedYou=function(uid,message,success){var user=SD.User.get(uid);SD.User.fetch(user,function(){var tracking=SD.Constants.trackingCodes.member_viewed_you;var ua={'ti':user.uid,'ms':message,'tc':tracking,'tobj':SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.VIEWED_YOU_MEMBERS)};SD.UIController._popupGenericWarning('Flirt with '+user.username,ua,[' can contact',BR(),'this member.'],'Upgrade and flirt');});};};if(typeof SD.FlirtWink!='undefined'&&typeof SD.FlirtWink.UI=='undefined'){SD.FlirtWink.UI={popupViewedYouWarning:function(){return SD.Dialogs.dialogUpgradeToSeeViewedYou();},popupDateYouWarning:function(){return SD.Dialogs.dialogUpgradeToSeeDateYou();},popupFlirtWarning:function(uid){return SD.Dialogs.dialogUpgradeToContact(uid);},popupReadWarning:function(uid){return SD.Dialogs.dialogMessagesRead(uid);},popupAlertContactWarning:function(uid){return SD.Dialogs.dialogUpgradeToContact(uid);},popupNeedToUpgradeWarning:function(uid,message,success){return SD.Dialogs.dialogUpgradeToFlirt(uid,message,success);}};}
SD.UserFilters={};SD.UserFilters.UI={_user:null,_target:null,startText:"",pauseText:"",statusIndicator:null,startButton:null,startButtonSidebar:null,premiumBolt:null,buttonState:'paused',previousButtonState:null,startSpeedDating:function(){SD.Event.fire(null,SD.UserFilters.UI.Events.START_SPEEDDATING);},pauseSpeedDating:function(){SD.Event.fire(null,SD.UserFilters.UI.Events.PAUSE_SPEEDDATING);},prepare:function(){var minAgeSelector=$('min_age');var maxAgeSelector=$('max_age');var locationSelector=$('location');minAgeSelector.observe("change",this.filterChanged.bind(this));maxAgeSelector.observe("change",this.filterChanged.bind(this));locationSelector.observe("change",this.filterChanged.bind(this));this.buttonState="paused";this.statusIndicator=$('status-indicator');this.startButton=$('start-speeddating-button');this.startButton.observe("click",this.startPauseSpeedDating.bind(this));this.startButton.observe("mouseover",function(){this.addClassName("hovered");});this.startButton.observe("mouseout",function(){this.removeClassName("hovered");});if(SD.ExperimentManager.GalleryHomepage2257.value==3||SD.ExperimentManager.GalleryHomepage2257.value==4){this.startButtonSidebar=$('start-speeddating-button-sidebar');this.startButtonSidebar.observe("click",this.startPauseSpeedDating.bind(this));this.startButtonSidebar.observe("mouseover",function(){this.addClassName("hovered");});this.startButtonSidebar.observe("mouseout",function(){this.removeClassName("hovered");});$('min-age-sidebar').innerHTML=minAgeSelector.value;$('max-age-sidebar').innerHTML=maxAgeSelector.value;$('location-limit-sidebar').innerHTML=locationSelector.childElements()[locationSelector.selectedIndex].text;}},filterChanged:function(event){var source=Event.element(event);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=(locationSelector.value=="NM")?SD.UserFilters.UI.nearRadius(user,500):0;}else{radius=SD.UserFilters.UI.nearRadius(user,locationSelector.value);}
var filter_country=(locationSelector.value=="WW")?"WW":user.country;SD.Event.fire(null,SD.UserFilters.UI.Events.FILTER_CHANGED,{min_age:minAgeSelector.value,max_age:maxAgeSelector.value,radius:radius,filter_country:filter_country});if(SD.ExperimentManager.GalleryHomepage2257.value==3||SD.ExperimentManager.GalleryHomepage2257.value==4){$('min-age-sidebar').innerHTML=minAgeSelector.value;$('max-age-sidebar').innerHTML=maxAgeSelector.value;$('location-limit-sidebar').innerHTML=locationSelector.childElements()[locationSelector.selectedIndex].text;}},startPauseSpeedDating:function(){if(this.buttonState=="paused"){SD.UserFilters.UI.startSpeedDating();}else{SD.UserFilters.UI.pauseSpeedDating();}},saveStateAndPause:function(){this.previousButtonState=this.buttonState;if(SD.XMPP.getFlash()){SD.UserFilters.UI.pauseSpeedDating();}},restorePreviousStateAndResume:function(){if(this.previousButtonState){if(this.previousButtonState=="running"){SD.UserFilters.UI.startSpeedDating();}else{SD.UserFilters.UI.pauseSpeedDating();}}},onStartDating:function(event){this.buttonState="running";this.startButton.value=this.pauseText;this.startButton.addClassName("pause-button");this.statusIndicator.src=SD.Config.imageDir+"dot-dot-dot-heart.gif";this.setWaitingCount(0);if(SD.ExperimentManager.GalleryHomepage2257.value==3||SD.ExperimentManager.GalleryHomepage2257.value==4){this.startButton.innerHTML=this.pauseText;this.startButtonSidebar.addClassName("pause-button");}},onPauseDating:function(event){this.buttonState="paused";this.startButton.value=this.startText;this.startButton.removeClassName("pause-button");this.statusIndicator.src=SD.Config.imageDir+"dot-dot-dot-heart-static.gif";if(SD.ExperimentManager.GalleryHomepage2257.value==3||SD.ExperimentManager.GalleryHomepage2257.value==4){this.startButton.innerHTML=this.startText;this.startButtonSidebar.removeClassName("pause-button");}},onWaitingTimeChanged:function(event){this.setWaitingCount(event.memo.count);},setWaitingCount:function(count){if(count){$('upcoming-dates').innerHTML=count;$('upcoming-dates-sidebar').innerHTML=count;$('upcoming-dates-sidebar-container').show();$('upcoming-dates').show();$('upcoming-text').show();$('view-all').show();}else{$('upcoming-dates').hide();$('upcoming-dates-sidebar-container').hide();$('upcoming-text').hide();$('view-all').hide();}
if(SD.ExperimentManager.GalleryHomepage2257.value==3||SD.ExperimentManager.GalleryHomepage2257.value==4){if(count){$('sidebar-dating-queue').innerHTML=count+" dates coming up ...";$('sidebar-dating-queue').show();$('updating-text').hide();$('updating-sidebar-text').hide();}else{$('updating-text').show();$('updating-sidebar-text').show();$('sidebar-dating-queue').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.User.Events.WAITING_TIME_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;},Events:{FILTER_CHANGED:"filter:changed",START_SPEEDDATING:"filter:startdating",PAUSE_SPEEDDATING:"filter:pausedating"}};
SD.OtherTabFilters={};SD.OtherTabFilters.UI={construct:function(target,user){this.startText="";this.pauseText="";this.startButton=DIV({"class":"search-button"});changeButton=INPUT({type:"button",value:"Change","class":"change-button"});this.statusIndicator=IMG({src:SD.Config.imageDir+"click-to-start.gif",align:"top","class":"status-indicator"});this.minAgeSpan=SPAN(null,user.min_age);this.maxAgeSpan=SPAN(null,user.max_age);var location="";if(user.radius>0){location="Near Me";}else if(user.filter_country=="WW"){location="Worldwide";}else{location="All "+user.country;}
this.locationSpan=SPAN(null,location);filterDiv=DIV({"class":"filter-info"},"Age: ",this.minAgeSpan,"-",this.maxAgeSpan," / ",this.locationSpan," ",changeButton);$(target).insert(this.startButton);$(target).insert(this.statusIndicator);$(target).insert(filterDiv);this.buttonState="paused";this.statusIndicator&&this.statusIndicator.observe("click",this.startSpeedDating.bind(this));$(this.startButton).observe("click",this.startPauseSpeedDating.bind(this));this.startButton.observe("mouseover",function(){this.addClassName("hovered");});this.startButton.observe("mouseout",function(){this.removeClassName("hovered");});$(changeButton).observe("click",function(){SD.NavUtils.setLocation(SD.NavUtils.link('home','index'));});},startPauseSpeedDating:function(){if(this.buttonState=="paused"){SD.UserFilters.UI.startSpeedDating();}else{SD.UserFilters.UI.pauseSpeedDating();}},startSpeedDating:function(){if(this.buttonState=="paused"){SD.UserFilters.UI.startSpeedDating();}},initialize:function(target,user){this.construct(target,user);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.UserFilters.UI.Events.FILTER_CHANGED,this.onFilterChanged.bind(this));},onStartDating:function(event){this.buttonState="running";this.startButton.addClassName("pause-button");$(this.statusIndicator).src=SD.Config.imageDir+"looking-for-dates.gif";},onPauseDating:function(event){this.buttonState="paused";this.startButton.removeClassName("pause-button");$(this.statusIndicator).src=SD.Config.imageDir+"click-to-start.gif";},onFilterChanged:function(event){$(this.minAgeSpan).innerHTML=event.memo.min_age;$(this.maxAgeSpan).innerHTML=event.memo.max_age;var location;if(event.memo.radius===0){location=event.memo.filter_country=="WW"?"Worldwide":"All "+event.memo.filter_country;}else{location="Near Me";}
$(this.locationSpan).innerHTML=location;}};
SD.Matchmaker={successfulHost:null,matchMember:function(user){var parameters=SD.User.makeParametersFromUser(user);parameters.exclude=SD.User.getPastDates(user);parameters.prefer=SD.User.getWantedDates(user);parameters.limit=30;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;return romeo;});SD.Event.fire(user,SD.Matchmaker.Events.MATCHES_FOUND,{matches:users});if(users.length){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.DatingApp.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.restartRegistering(event.memo.user);});SD.Matchmaker.initialized=true;}},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.DatingApp.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",_isReady:false,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",ROSTER_LOADED:"xmpp:roster_loaded"},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){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);},createXMLNode:function(type,value){return SD.XMPP.getBridge().createXMLNode(type,value);},sendIQ:function(iqObject){SD.XMPP.getXMPPConnection().send(iqObject);},sendMessage:function(recipientString,msgID,msgBody,msgType){var msg=SD.XMPP.getBridge().sendMessage(SD.XMPP.createJID(recipientString),msgID,msgBody,null,msgType,null);SD.Event.fire(null,SD.XMPP.Events.MESSAGE,msg);},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(flexEvent){SD.XMPP.debug("onINIT");SD.XMPP.initConnection();SD.XMPP._connected=false;SD.XMPP._loggedIn=false;(new PeriodicalExecuter(SD.XMPP.connectionChecker,60));SD.XMPP.debug("fired init");},connectionChecker:function(){SD.XMPP.debug("checking connection");if(!SD.XMPP.isLoggedIn()&&SD.XMPP._username&&SD.XMPP._password){SD.XMPP.reconnect();}},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);conn.addEventListener("incomingData",SD.XMPP.onIncomingData);conn.addEventListener("disconnection",SD.XMPP.onDisconnect);conn.addEventListener("login",SD.XMPP.onLogin);conn.addEventListener("message",SD.XMPP.onMessage);conn.setResource(SD.XMPP._resourceName);SD.XMPP.debug("connection initialized");},onMessage:function(flexEvent){var msg=flexEvent.getData();SD.XMPP.debug("message received");SD.Event.fire(null,SD.XMPP.Events.MESSAGE,msg);},onConnectSuccess:function(flexEvent){SD.XMPP._connected=true;SD.Event.fire(null,SD.XMPP.Events.CONNECT);},onError:function(flexEvent){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){},onIncomingData:function(flexEvent){SD.Event.fire(null,SD.XMPP.Events.DATA,flexEvent.getData());},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.setServer(SD.Config.XMPPServer.serverURL);conn.connect(SD.XMPP._connType);SD.XMPP.debug("connecting...");},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");SD.XMPP.getBridge().changeShow("away");SD.XMPP.getBridge().changeShow("away");},goOnline:function(){SD.log("going ONLINE");SD.XMPP.getBridge().changeShow(null);},getPresenceStatus:function(jids,callBackFunc,onFailure){if(!jids){return;}
var chatUsernames=[];jids.each(function(jid){chatUsernames.push(SD.User.getChatUsername(jid));});new Ajax.Request(SD.NavUtils.link('ajax','presence'),{method:'post',evalJSON:true,parameters:{'usernames':chatUsernames.join(',')},onSuccess:function(result){callBackFunc(result.responseJSON)},onFailure:onFailure(jids)||function(e){}});}};
if(typeof SD.BuddyList=='undefined'){SD.BuddyList={};};SD.BuddyList.Controller=new function(){var _aBuddies=[];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){_hBlocked.set(oBuddy.uid,false);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);});};this.initRoster=function(){_oRoaster=SD.XMPP.getRoster();_oRoaster.addEventListener('userAvailable',this.onUserAvailable.bind(this));_oRoaster.addEventListener('userUnavailable',this.onUserUnavailable.bind(this));_oRoaster.addEventListener('userAdded',this.onUserAdded.bind(this));_oRoaster.addEventListener('userRemoved',this.onUserRemoved.bind(this));_oRoaster.addEventListener('userPresenceUpdated',this.onUserPresenceUpdated.bind(this));_oRoaster.addEventListener('rosterLoaded',this.onRosterLoaded.bind(this));};this.userCameOnline=function(user){if(!user)return;var memo={user:user};SD.Event.fire(null,SD.BuddyList.Events.USER_AVAILABLE,memo);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()});}};this.userWentOffline=function(user){if(!user)return;SD.Event.fire(null,SD.BuddyList.Events.USER_UNAVAILABLE,{user:user});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.onSubscriptionDenial=function(flexEvent){var jidString=SD.XMPP.jidToString(flexEvent.getJid());SD.Event.fire(null,SD.BuddyList.Events.SUBSCRIPTION_DENIAL,{user:SD.User.getByChatID(jidString)});};this.onSubscriptionRequest=function(flexEvent){var jidString=SD.XMPP.jidToString(flexEvent.getJid());SD.Event.fire(null,SD.BuddyList.Events.SUBSCRIPTION_REQUEST,{user:SD.User.getByChatID(jidString)});};this.onSubscriptionRevocation=function(flexEvent){var jidString=SD.XMPP.jidToString(flexEvent.getJid());SD.Event.fire(null,SD.BuddyList.Events.SUBSCRIPTION_REVOCATION,{user:SD.User.getByChatID(jidString)});};this.onUserAvailable=function(flexEvent){SD.log('user available:'+flexEvent.getJid().getResource());var jidString=SD.XMPP.jidToString(flexEvent.getJid());var user=SD.User.getByChatID(jidString);this.userCameOnline(user);};this.onUserUnavailable=function(flexEvent){SD.log('user unavailable:'+flexEvent.getJid().getResource());var jidString=SD.XMPP.jidToString(flexEvent.getJid());var user=SD.User.getByChatID(jidString);this.userWentOffline(user);};this.onUserAdded=function(flexEvent){var jidString=SD.XMPP.jidToString(flexEvent.getJid());var oUser=SD.User.getByChatID(jidString);this.fetchAddBuddy(oUser);};this.onUserRemoved=function(flexEvent){var jidString=SD.XMPP.jidToString(flexEvent.getJid());var memo={user:SD.User.getByChatID(jidString)};SD.Event.fire(null,SD.BuddyList.Events.USER_REMOVED,memo);};this.onUserPresenceUpdated=function(flexEvent){return;};this.onUserSubscriptionUpdated=function(flexEvent){var jidString=SD.XMPP.jidToString(flexEvent.getJid());var memo={user:SD.User.getByChatID(jidString)};SD.Event.fire(null,SD.BuddyList.Events.USER_SUBSCRIPTION_UPDATED,memo);};this.onRosterLoaded=function(flexEvent){SD.Event.fire(null,SD.BuddyList.Events.ROSTER_LOADED,flexEvent.getData());};this.requestBuddyDelete=function(oBuddy){SD.Event.fire(null,SD.UIController.Events.DELETE_BUDDY_REQUESTED,{user:oBuddy});};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;_aBuddies.each(function(oBuddyParam){if(oBuddyParam.uid==nUid){oBuddy=oBuddyParam;throw $break;}});return oBuddy;};this.isBuddy=function(user){if(!user)return false;var bIsBuddy=false;_aBuddies.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.addBuddy=function(oUser,bQuiet){if(!oUser)return;if(oUser&&!this.isBuddyBlocked(oUser)&&!this.isBuddy(oUser)){_aBuddies.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<_aBuddies.length;i++){if(_aBuddies[i].uid==user.uid){nRemoveIndex=i;break;}}
if(nRemoveIndex>-1){_aBuddies.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;_aBuddies.each(function(oBuddy){if(oBuddy.online){nOnlineCount++;}});return nOnlineCount;};this.getTotalCount=function(){return _aBuddies.length;};this.getAllBuddies=function(){return _aBuddies;};};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',SUBSCRIPTION_REVOCATION:'buddylist:subscriptionRevocation',SUBSCRIPTION_DENIAL:'buddylist:subscriptionDenial',SUBSCRIPTION_REQUEST:'buddylist:subscriptionRequest',USER_AVAILABLE:'buddylist:userAvailable',USER_UNAVAILABLE:'buddylist:userUnavailable',USER_ADDED:'buddylist:userAdded',USER_REMOVED:'buddylist:userRemoved',USER_BLOCKED:'buddylist:userBlocked',USER_PRESENCE_UPDATED:'buddylist:userPresenceUpdated',USER_SUBSCRIPTION_UPDATED:'buddylist:userSubscriptionUpdated',ROSTER_LOADED:'buddylist:rosterLoaded',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 _oExpandingBuddy=null;var _oCollapsingBuddy=null;var _oExpandedBuddy=null;var _bExpanding=false;var _bCollapsing=false;var _nUsernameExcerptLength=12;var _oBuddyListElement=null;var _hBuddyElements=$H({});var _hBuddyHeadElements=$H({});var _hBuddyBodyElements=$H({});function getBuddyBody(oBuddy){var oImage=document.createElement('img');oImage.setAttribute('alt','Ask '+oBuddy.username+' for photo!');var oImageDiv=null;var oLinkProfile=null;var oLinkChat=null;var oLinkFlirt=null;var oLinkDelete=null;var oLinkBlock=null;var sCityName='';oBuddy.username=oBuddy.username||'';oBuddy.age=oBuddy.age||'';sCityName=oBuddy.city_name||'';sCityName=(sCityName.strip()!=''?sCityName+', ':'');oBuddy.statecode=oBuddy.statecode||'';oBuddy.relation.distance=oBuddy.relation.distance||'';var oContent=DIV({'class':'insert'},DIV({'class':'grid-row grid-row-80'},DIV({'class':'grid-col grid-col-first'},DIV({'class':'left'},oImageDiv=DIV({'class':'buddy-image'},''))),DIV({'class':'grid-col'},DIV({'class':'right'},oLinkProfile=DIV({'class':'link link-profile'},'Profile'),oLinkChat=DIV({'class':'link link-chat'},'Chat'),oLinkFlirt=DIV({'class':'link link-flirt'},'Flirt'),oLinkDelete=DIV({'class':'link link-delete'},'Delete'),oLinkBlock=DIV({'class':'link link-block'},'Block')))),DIV({'class':'buddy-info1','title':oBuddy.username},B({},oBuddy.username.ucfirst().excerpt(_nUsernameExcerptLength)),', ',oBuddy.age),DIV({'class':'buddy-info2'},sCityName,oBuddy.statecode,' (',oBuddy.relation.distance,'\u00a0','mi)'));oImageDiv.appendChild(oImage);oImage.src=oBuddy.square_image_url;SD.FlirtWink.View.registerInputProfileOpener(oLinkProfile,function(){return SD.User.get(oBuddy.uid);});SD.FlirtWink.View.registerInputChat(oLinkChat,function(){return SD.User.get(oBuddy.uid);});SD.FlirtWink.View.registerInputFlirt(oLinkFlirt,function(){return SD.User.get(oBuddy.uid);});SD.BuddyList.View.registerInputBuddyDelete(oLinkDelete,oBuddy.uid);SD.BuddyList.View.registerInputBuddyBlock(oLinkBlock,oBuddy.uid);SD.BuddyList.View.registerInputBuddyImage(oImage,oBuddy.uid);return oContent;};function getBuddyHead(oBuddy,bOnline){var oBuddyHeadElement=null;var oBuddyBodyElement=null;var oBuddyElement=LI({'class':'buddy'+(bOnline?' buddy-online':''),'style':'display:none','id':'buddylist-buddy-'+oBuddy.uid},oBuddyHeadElement=DIV({'class':'head'},DIV({'class':'left'},oBuddy.username.ucfirst().excerpt(_nUsernameExcerptLength)),DIV({'class':'right'},'')),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);try{Effect.Fade(oBuddyElement,{afterFinish:function(){try{_oBuddyListElement.removeChild(oBuddyElement);SD.Tooltip.hide();if(fAfterFinish){fAfterFinish();}}catch(err){}}});}catch(error){}};function addBuddyElement(oBuddy,bOnline){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();};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);});};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();SD.BuddyList.View.registerOutputBuddyBody();};this.addBuddy=function(oUser){addBuddyElement(oUser,oUser.online);};this.registerInputBuddyHead=function(oElement,oBuddy){oElement.onselectstart=function(){return false;};oElement.onmousedown=function(){return false;};oElement.setAttribute('title',oBuddy.username);oElement.observe('click',function(e){if(_bExpanding||_bCollapsing){return;}
SD.Event.fire(null,SD.BuddyList.Events.BUDDY_COLLAPSE,{'buddy':_oExpandedBuddy});if(_oExpandedBuddy!=oBuddy){SD.Event.fire(null,SD.BuddyList.Events.BUDDY_EXPAND,{'buddy':oBuddy});_oExpandedBuddy=oBuddy;}else{_oExpandedBuddy=null;}});};this.registerInputBuddyDelete=function(oElement,fGetBuddy){oElement=$(oElement);fGetBuddy=assureGetBuddyfunction(fGetBuddy);var oBuddy=fGetBuddy();oElement.observe('click',function(){SD.BuddyList.Controller.requestBuddyDelete(oBuddy);});oElement.observe('mouseover',function(e){SD.Tooltip.show('Remove <b>'+oBuddy.username+'</b> from buddy list');});oElement.observe('mouseout',function(e){SD.Tooltip.hide();});};this.registerInputBuddyBlock=function(oElement,fGetBuddy){oElement=$(oElement);fGetBuddy=assureGetBuddyfunction(fGetBuddy);var oBuddy=fGetBuddy();oElement.observe('click',function(){SD.BuddyList.Controller.requestBuddyBlock(oBuddy);});oElement.observe('mouseover',function(e){SD.Tooltip.show('Prevent <b>'+oBuddy.username+'</b> from sending you messages');});oElement.observe('mouseout',function(e){SD.Tooltip.hide();});};this.registerOutputBuddyList=function(oElement){_oBuddyListElement=$(oElement);};this.registerOutputBuddy=function(){SD.Event.observe(null,SD.BuddyList.Events.BUDDY_EXPAND,function(e){var oElement=e.memo.buddy&&_hBuddyElements.get(e.memo.buddy.uid);oElement&&oElement.addClassName(this.oCSSClasses.classBuddyExpanded);}.bind(this));SD.Event.observe(null,SD.BuddyList.Events.BUDDY_COLLAPSE,function(e){var oElement=e.memo.buddy&&_hBuddyElements.get(e.memo.buddy.uid);oElement&&oElement.removeClassName(this.oCSSClasses.classBuddyExpanded);}.bind(this));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){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){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){oElement=$(oElement);SD.Event.observe(null,SD.BuddyList.Events.BUDDY_COUNT_CHANGE,function(e){oElement.update(' ('+e.memo.countOnline+'/'+e.memo.countTotal+')');});};this.registerOutputBuddyBody=function(){SD.Event.observe(null,SD.BuddyList.Events.BUDDY_EXPAND,function(e){_oExpandingBuddy=e.memo.buddy;if(_oExpandingBuddy){var oElement=_hBuddyBodyElements.get(_oExpandingBuddy.uid);oElement.update(getBuddyBody(_oExpandingBuddy));_bExpanding=true;if(oElement){oElement.hide();SD.Effect.BlindDown(oElement,{duration:0.3,afterFinish:function(){SD.Event.fire(null,SD.BuddyList.Events.BUDDY_EXPANDED,{'buddy':_oExpandingBuddy});}});}}});SD.Event.observe(null,SD.BuddyList.Events.BUDDY_EXPANDED,function(e){_bExpanding=false;});SD.Event.observe(null,SD.BuddyList.Events.BUDDY_COLLAPSE,function(e){_oCollapsingBuddy=e.memo.buddy;if(_oCollapsingBuddy){var oElement=_hBuddyBodyElements.get(_oCollapsingBuddy.uid);_bCollapsing=true;if(oElement){SD.Effect.BlindUp(oElement,{duration:0.3,afterFinish:function(){SD.Event.fire(null,SD.BuddyList.Events.BUDDY_COLLAPSED,{'buddy':_oCollapsingBuddy});}});}}});SD.Event.observe(null,SD.BuddyList.Events.BUDDY_COLLAPSED,function(e){_oCollapsingBuddy=e.memo.buddy;if(_oCollapsingBuddy){var oElement=_hBuddyBodyElements.get(_oCollapsingBuddy.uid);if(oElement){oElement.update('');}}
_bCollapsing=false;});};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 aBuddies=SD.BuddyList.Controller.getAllBuddies();aBuddies.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));SD.BuddyList.View.registerInputBuddyHead($(oParam.buddyHeadElement),oBuddy);};this.registerInputBuddyImage=function(oElement,fGetBuddy){oElement=$(oElement);fGetBuddy=assureGetBuddyfunction(fGetBuddy);var oBuddy=fGetBuddy();SD.FlirtWink.View.registerInputProfileOpener(oElement,function(){return oBuddy;});};};
SD.Chat={dragOffsetX:0,dragOffsetY:0,boundOnDrag:null,isDragging:false,hasDragged:false,savedX:200,savedY:100,minimized:false,visible:false,blinking:0,firstTime:true,isSwfLoaded:true,blinkingTabs:[],pastChatUids:[],init:function(){SD.Chat.onLoad();},onLoad:function(){SD.log("SD.CHAT.onLoad");$('chat-title').observe('mousedown',this.onStartDrag.bindAsEventListener(this));$('chat-title').observe('mouseup',this.onStopDrag.bindAsEventListener(this));this.id='chat';this.boundOnDrag=this.onDrag.bindAsEventListener(this);this.boundOnStopDrag=this.onStopDrag.bind(this);SD.Event.observe(null,SD.XMPP.Events.MESSAGE,SD.Chat.onXMPPMessage.bind(this));SD.Event.observe(null,SD.User.Events.USER_ONLINE,SD.Chat.onUserAvailable.bind(this));SD.Event.observe(null,SD.User.Events.USER_OFFLINE,SD.Chat.onUserUnavailable.bind(this));SD.Event.observe(null,SD.UIController.Events.START_CHAT_REQUESTED,SD.Chat.onChatUser.bind(this));SD.Event.observe(null,SD.User.Events.USER_FETCHED,SD.Chat.UI.onUserFetched);SD.Event.observe(null,SD.Notification.Landing.Events.JULIET_OFFLINE,SD.Chat.UI.onUserMissed.bind(this));$$('#chat-title .chat-minimize').invoke('observe','click',this.minimize.bind(this));$$('#chat-title .chat-close-icon').invoke('observe','click',function(){SD.Chat.UI.removeUser(SD.Chat.UI.getCurrentFriend().uid);});this.updateRange();var savedPos=SD.Cookie.read('chat_position');if((savedPos!==null)&&(savedPos.indexOf(':')!=-1)){this.savedX=parseInt(savedPos,10);this.savedY=parseInt(savedPos.substring(savedPos.indexOf(':')+1),10);if(this.savedY>document.documentElement.clientHeight-$('chat').offsetHeight){this.savedY=0;}
if(this.savedY<0){this.savedY=0;}
if(this.savedX>document.documentElement.clientWidth-$('chat').offsetWidth){this.savedX=document.documentElement.clientWidth-$('chat').offsetWidth;}
if(this.savedX<0){this.savedX=0;}}
this.blinkingTimer=new PeriodicalExecuter(this.onBlinkTimer.bind(this),0.5);(new PeriodicalExecuter(function(pe){SD.log("SD.Chat.onLoad():PE");if(this.isSwfLoaded){pe.stop();}
if(!this.isSwfLoaded){var dockingTarget=$$('#h1 span').first();$('chat').addClassName('chat-loading');$('chat').clonePosition(dockingTarget);this.moveTo(parseInt($('chat').style.left)+parseInt($('chat').style.width),null);}}.bind(this),0.1));this.UI.initialize(null,SD.Model.getMyself());$('chat').style.position=Prototype.Browser.IE6?'absolute':'fixed';this.position=$('chat').style.position;$('chat').hide();this.taskBarButton=this._createTaskBarButton($('sidebar-left'));if(SD.PremiumChat){SD.PremiumChat.initialize();}},getChat:function(){var chat=SD.Chat.UI;if(!chat){SD.log("chat can not be found");}
return chat;},didIChatBefore:function(uid){return SD.Chat.pastChatUids.indexOf(uid)>=0;},onStartDrag:function(ev){this.dragOffsetX=Event.pointerX(ev)-parseInt($('chat').style.left);this.dragOffsetY=Event.pointerY(ev)-parseInt($('chat').style.top);this.hasDragged=false;if(!this.minimized&&!this.isDragging)
{this.isDragging=true;Event.observe(window.document,'mousemove',this.boundOnDrag);Event.observe(document,'mouseup',this.boundOnStopDrag);}
Event.stop(ev);},onStopDrag:function(ev){Event.stopObserving(window.document,'mousemove',this.boundOnDrag);Event.stopObserving(window.document,'mouseup',this.boundOnStopDrag);Event.stop(ev);this.isDragging=false;if(this.hasDragged){this.savedX=parseInt($('chat').style.left+0,10);this.savedY=parseInt($('chat').style.top+0,10);SD.Cookie.create('chat_position',this.savedX+':'+this.savedY,14);}else{}},onDrag:function(ev){this.hasDragged=true;var pointerX=Event.pointerX(ev);var pointerY=Event.pointerY(ev);var left=(pointerX-this.dragOffsetX);var top=(pointerY-this.dragOffsetY);if(top<0){top=0;}
this.moveTo(left,top);Event.stop(ev);},show:function(){SD.log("SD.Chat.show()");if(SD.BrowserDetect.browser=='Firefox'&&SD.BrowserDetect.OS=='Windows'){if(SD.Nav.activePanelId=='site'||SD.Nav.activePanelIdOld=='site'){SD.log("SD.Chat.show(): Windows Firefox, activePanel=site");SD.Flex.gotoDatingPage();}}
this.firstTime&&SD.Chat.UI.resetFriendsStatus();this.firstTime&&SD.WindowManager.add(this);this.firstTime=false;this.visible=true;this.minimized=false;this.blinking=0;$('chat').removeClassName('blinking1');$('chat').removeClassName('blinking2');this.resizeTo(420,433);this.moveTo(this.savedX,this.savedY);$$('#chat-title .chat-minimize').invoke('show');$$('#chat-title .chat-hide').invoke('hide');$("chat-body").down("table").scrollIntoView();$('chat').show();this.taskBarButton.hide();var text_area=$("messagetext-area-"+SD.Chat.UI.getCurrentFriend().uid);if($("chat").visible()&&text_area.visible()&&!text_area.disabled){text_area.focus();}},hide:function(){SD.log("SD.Chat.hide()");this.visible=false;this.firstTime=true;$$('#chat-title .chat-minimize').invoke('hide');$$('#chat-title .chat-show').invoke('show');$$('#chat-title .chat-hide').invoke('hide');$('chat').hide();this.taskBarButton.hide();},_createTaskBarButton:function(refEl){var showEl;var tbButton=DIV({'class':'chat-taskbar-button'},showEl=A({'class':'chat-show'},"Show"),SPAN({},'Chat'));refEl.appendChild(tbButton);showEl.observe('click',this.show.bind(this));return tbButton;},_createShim:function(refEl){var shim=Element.extend(document.createElement('IFRAME'));shim.style.zIndex=refEl.style.zIndex;shim.style.borderWidth=0;refEl.parentNode.insertBefore(shim,refEl);shim.style.width=refEl.offsetWidth;shim.style.height=refEl.offsetHeight;shim.style.position=Prototype.Browser.IE6?'absolute':'fixed';shim.style.top=refEl.style.top;shim.style.left=refEl.style.left;return shim;},range:function(){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;},moveTo:function(x,y){var valX=x;var valY=y;if(x!==null&&x!==undefined){if(this._range){if(this._range.x1>x){valX=this._range.x1;}
else if(this._range.x2<x+this.width){valX=this._range.x2-this.width;}}
$('chat').style.left=valX+'px';this.left=valX;}
if(y!==null&&y!==undefined){if(this._range){if(this._range.y1>y){valY=this._range.y1;}
else if(this._range.y2<y+this.height){valY=(this._range.y2-this.height);}}
$('chat').style.top=valY+'px';this.top=valY;}
return this;},moveBy:function(dx,dy){if(dx!==null&&dx!==undefined){var x=parseInt(this.dom.style.left)+dx;this.moveTo(x,null);}
if(dy!==null&&dy!==undefined){var y=parseInt(this.dom.style.top)+dy;this.moveTo(null,y);}
return this;},resizeTo:function(w,h){if(h!==null){$('chat').style.height=h+'px';this.height=h;}
if(w!==null){$('chat').style.width=w+'px';this.width=w;}},minimize:function(e){SD.log("SD.Chat.minimize()");this.visible=true;this.minimized=true;this.taskBarButton.show();$('chat').hide();this.taskBarButton.style.display='block';var scrollOffsets=document.viewport.getScrollOffsets();var elementOffsets=this.taskBarButton.cumulativeOffset();if(!SD.Utils.Element.isInView(this.taskBarButton)){var endScrollVal;if(elementOffsets[1]<scrollOffsets[1]){endScrollVal=elementOffsets[1]}
else{endScrollVal=elementOffsets[1]+this.taskBarButton.offsetHeight-document.viewport.getHeight();}
new Effect.Tween(null,scrollOffsets[1],endScrollVal,{afterFinish:function(){new Effect.Highlight(SD.Chat.taskBarButton,{startcolor:'#FFB741'});}},function(p){scrollTo(scrollOffsets.left,p.round())});}
else{new Effect.Highlight(SD.Chat.taskBarButton,{startcolor:'#FFB741',duration:0.5});}
Event.stop(e);},startBlinking:function(){if(this.minimized){this.blinking=1;}
if(this.firstTime){this.show();}},onBlinkTimer:function(){switch(this.blinking){case 1:this.blinking=2;$$('#chat-title span').first().innerHTML='New Message';$('chat').removeClassName('blinking1');$('chat').addClassName('blinking2');break;case 2:this.blinking=1;$$('#chat-title span').first().innerHTML='Chat Window';$('chat').addClassName('blinking1');$('chat').removeClassName('blinking2');break;default:break;}
if(this.blinkingTabs.length>0){for(var i=0;i<this.blinkingTabs.length;i++){var tab=this.blinkingTabs[i];if(tab.hasClassName('blinking1')){tab.addClassName('blinking2');tab.removeClassName('blinking1');}
else{tab.addClassName('blinking1');tab.removeClassName('blinking2');}}}},onXMPPMessage:function(event){SD.log("SD.CHAT onXMPPMessage");var msg=event.memo;if(msg.getType()!="chat"||!msg.getBody()){SD.log("SD.CHAT not a chat message");return;}
var sender=SD.User.getByChatID(msg.getFrom().toBareJID());var receiver=SD.User.getByChatID(msg.getTo().toBareJID());var me=SD.Model.getMyself();var toBeFetched=sender.uid==me.uid?receiver:sender;SD.User.fetch(toBeFetched,function(user){SD.Chat.UI.messageReceived(sender,receiver,msg.getBody());SD.Chat.startBlinking();});},onUserAvailable:function(event){this.getChat().userLoggedIn(event.memo.user);},onUserUnavailable:function(event){this.getChat().userLoggedOut(event.memo.user);},onChatUser:function(event){try{this.getChat().startChat(event.memo.user);this.UI.setCurrentFriend(event.memo.user);this.show();if(event.memo.isConnecting){this.UI.disableInput.defer(event.memo.user,true);}}
catch(e){}},registerInputCloseChat:function(oElement,fGetBuddy){oElement=$(oElement);var oBuddy=fGetBuddy();oElement.observe('click',function(){SD.Chat.UI.removeUser(oBuddy.uid);});oElement.observe('mouseover',function(e){SD.Tooltip.show('End the chat with <b>'+oBuddy.username+'</b>');});oElement.observe('mouseout',function(e){SD.Tooltip.hide();});},registerInputReportUser:function(oElement,fGetBuddy){oElement=$(oElement);var oBuddy=fGetBuddy();oElement.observe('click',function(){var chatHistory='<style>@import url("/static/site/css/chat.css");</style>'+"messageoutput-"+oBuddy.uid;SD.Chat.ReportPanel.show(oBuddy,chatHistory,'Chat');});oElement.observe('mouseover',function(e){SD.Tooltip.show('Report <b>'+oBuddy.username+'</b>');});oElement.observe('mouseout',function(e){SD.Tooltip.hide();});},UI:{initialize:function(config,me){var _this=this;var chatFrame=$(DIV({"class":"messageframe"}));var allFriends={};var currentFriend=null;var messagingTabs,messagingNames;this.msgHolders={};this.chatFrames={};$(chatFrame).insert(TABLE({"border":"0","cellpadding":"0","cellspacing":"0"},TBODY({},TR(null,messagingNames=TD({width:"97"}),messagingArea=TD()))));var drawFriendUI=function(friend){drawMessageTab(friend);drawMessageBox(friend);if(currentFriend){$("messagebox-"+friend.uid).hide();}else{setCurrentFriend(friend);}};this.disableInput=function(user,isConnecting){var chatInput=$("messagetext-area-"+user.uid);var sendButton=$("messagetext-button-"+user.uid);if(!chatInput||!sendButton){return;}
if(chatInput.disabled&&sendButton.disabled){return;}
chatInput.disabled=true;sendButton.disabled=true;if(isConnecting){chatInput.value='Connecting...';}else{chatInput.value='User is offline';}};this.enableInput=function(user){var chatInput=$("messagetext-area-"+user.uid);var sendButton=$("messagetext-button-"+user.uid);if(!chatInput||!sendButton){return;}
if(!chatInput.disabled&&!sendButton.disabled){return;}
chatInput.disabled=false;sendButton.disabled=false;if(chatInput.value=='User is offline'||chatInput.value=='Connecting...'){chatInput.value='';}};this.setCurrentFriend=function(user){setCurrentFriend(user);};this.getCurrentFriend=function(){return currentFriend;};var clearBlinking=function(friend){for(var i=0;i<SD.Chat.blinkingTabs.length;i++){var tab=SD.Chat.blinkingTabs[i];if(tab.id=='messagetab-'+friend.uid){SD.Chat.blinkingTabs.splice(i,1);tab.removeClassName("blinking1");tab.removeClassName("blinking2");break;}}};var setCurrentFriend=function(friend){if(currentFriend!=friend){if(currentFriend){$("messagebox-"+currentFriend.uid).hide();$("currentmessagetab-"+currentFriend.uid).hide();$("messagetab-"+currentFriend.uid).show();_this.hideMsgForUser(currentFriend.uid);}
currentFriend=friend;$("messagebox-"+currentFriend.uid).show();$("currentmessagetab-"+currentFriend.uid).show();$("messagetab-"+currentFriend.uid).hide();var text_area=$("messagetext-area-"+currentFriend.uid);if($("chat").visible()&&text_area.visible()&&!text_area.disabled){text_area.focus();}
clearBlinking(friend);}};var friendsCount=0;var addFriend=function(user){if(!allFriends[user.uid]&&!(user.uid==me.uid)){friendsCount++;SD.Chat.pastChatUids.push(user.uid);allFriends[user.uid]=user;allFriends[user.uid].online=true;drawFriendUI(user);SD.Event.fireDeferred(null,SD.Chat.UI.Events.CHAT_STARTED,{user:user});}};this.userLoggedIn=function(user){this.enableInput(user);};this.userLoggedOut=function(user){this.disableInput(user);};this.messageReceived=function(sender,receiver,message){addFriend(sender);addFriend(receiver);if(sender!=me){message=SD.Config.filterText(message);if(sender!=currentFriend){blinkMessagesTab(sender);}
SD.Event.fireDeferred(null,SD.Chat.UI.Events.CHAT_MSG_RECEIVED,{sender:sender,body:message});}
displayMessage(sender,receiver,message);SD.UIController.onMessageReceived(sender,message);SD.DatingApp.playMessageSound();};this.startChat=function(user){SD.log("SD.Chat.UI.startChat");addFriend(user);};this.removeUser=function(userId){SD.Event.fireDeferred(null,SD.Chat.UI.Events.CHAT_ENDED,{user:allFriends[userId]});$('currentmessagetab-'+userId).remove();$('messagetab-'+userId).remove();$('messagebox-'+userId).remove();if(allFriends[userId]){friendsCount--;}
allFriends[userId]=null;if(currentFriend.uid==userId){currentFriend=null;for(var i in allFriends){if(allFriends[i]&&allFriends[i].uid){setCurrentFriend(allFriends[i]);return;}}
SD.Chat.hide();SD.Favicon.setTitle("");}};SD.Event.observe(null,SD.BuddyList.Events.USER_REMOVED,function(event){if(allFriends[event.memo.user.uid]){SD.Chat.UI.removeUser(event.memo.user.uid);}});this.blockUser=function(userId){if(allFriends[userId]){SD.Event.fire(null,SD.UIController.Events.BLOCK_BUDDY_REQUESTED,{user:SD.User.get(userId)});}};$('chat-body').insert(chatFrame);var oLinkProfile,oLinkBlock,oLinkEndChat,oImage,oLinkReport;var drawMessageTab=function(friend){var cdiv=DIV({"id":"currentmessagetab-"+friend.uid,"class":"currentmessagetab"},SPAN({"class":"observe-username observe-user-"+friend.uid}),oImage=IMG({"class":"messageimageicon observe-square-image-url observe-user-"+friend.uid,"style":{height:'75px',width:'75px'}}),oLinkProfile=A({"class":"link-profile"},"Profile"),oLinkBlock=A({"class":"link-block"},"Block"),oLinkReport=A({"class":"link-report"},"Report"),oLinkEndChat=A({"class":"link-close"},"End Chat"));$(messagingNames).insert(cdiv);SD.FlirtWink.View.registerInputProfileOpener(oLinkProfile,function(){return allFriends[friend.uid]});SD.BuddyList.View.registerInputBuddyBlock(oLinkBlock,function(){return allFriends[friend.uid]});SD.BuddyList.View.registerInputBuddyImage(oImage,function(){return allFriends[friend.uid]});SD.Chat.registerInputCloseChat(oLinkEndChat,function(){return allFriends[friend.uid]});SD.Chat.registerInputReportUser(oLinkReport,function(){return allFriends[friend.uid]});$(cdiv).hide();var button;var userTab;$(messagingNames).insert(userTab=DIV({"id":"messagetab-"+friend.uid,"class":"messagetab"},SPAN({"class":"observe-username observe-user-"+friend.uid})));$(userTab).observe("click",function(){setCurrentFriend(friend);});SD.User.fetch(friend);};var blinkMessagesTab=function(user){SD.log('blinkMessagesTabbb:'+user.uid);var tab=$('messagetab-'+user.uid);if(!tab){return;}
SD.Chat.blinkingTabs.push(tab);};var drawMessageBox=function(friend){var button;var textInput;var endChatButton;var blockButton;var reportButton;var d=DIV({"id":"messagebox-"+friend.uid,"class":"messagebox"},_this.chatFrames[friend.uid]=DIV({"class":"messageoutput smalltype","id":"messageoutput-"+friend.uid,"style":"position:absolute"}),DIV({"class":"sendform"},FORM({onsubmit:"return false;"},TABLE({"border":"0","cellpadding":"0","cellspacing":"0"},TBODY({},TR({},TD({"style":{"padding-right":"0px"}},textInput=TEXTAREA({"id":"messagetext-area-"+friend.uid})),TD({"width":"25","align":"right"},button=INPUT({"id":"messagetext-button-"+friend.uid,"type":"button","class":"input-button","value":"»","length":"20"}))),TR({},TD({"colspan":"2"})))))));$(button).observe('click',function(event){sendMessage(friend,textInput.value);textInput.value="";});$(textInput).observe('keypress',function(event){if(event.keyCode==13){if(event.ctrlKey){event.target.value+='\n';}else{event.stop();if(event.target.value){sendMessage(friend,event.target.value);event.target.value="";}}}});$(textInput).observe('focus',function(event){SD.Favicon.setTitle("");});$(messagingArea).insert(d);};var sendMessage=function(friend,message){SD.XMPP.sendMessage(friend.chat_id,null,message,"chat");SD.Event.fireDeferred(null,SD.Chat.UI.Events.CHAT_MSG_SENT,{receiver:friend,body:message});};var displayMessage=function(from,to,text){var message=DIV({"class":"message-entry"},SPAN({"class":"message-from"},from.username),renderMessage(text));var panelUser=(from==me)?to:from;var panelObj="messageoutput-"+panelUser.uid;var panel=$(panelObj);panel.insert(message);panel.scrollTop=panel.scrollHeight;stupidIEHack(panel);};var stupidIEHack=function(panel){panel.hide();panel.show();setTimeout(function(){$(panel).scrollTop=$(panel).scrollHeight;},200);};var renderMessage=function(text){text=text.split(/((?:_[^_]+_)|(?:\*[^*]+\*))/);var chunks=[];while(text.length){var chunk=text.shift();if(isFirstAndLast(chunk,"_")){chunks.push(SPAN({"class":"message-ital"},stripFirstAndLast(chunk)));}else if(isFirstAndLast(chunk,"*")){chunks.push(SPAN({"class":"message-bold"},stripFirstAndLast(chunk)));}
else{var subchunks=chunk.split(SD.Chat.getSmileyRegexp());for(var i=0;i<subchunks.length;i++){var subchunk=subchunks[i];if(subchunk in SD.Chat.smilies){chunks.push(IMG({"class":"smiley","src":"/static/site/images/chat/"+SD.Chat.smilies[subchunk]+".gif"},""));}else{chunks.push(subchunk);}}}}
chunks.unshift({"class":"message-text"});return SPAN.apply(null,chunks);};var isFirstAndLast=function(s,c){return(s.charAt(0)==c)&&(s.charAt(s.length-1)==c);};var stripFirstAndLast=function(s){return s.substring(1,s.length-1);};this.resetFriendsStatus=function(){for(var i in allFriends){if(allFriends[i]&&!allFriends[i].online){this.disableInput(allFriends[i]);}}};},onUserMissed:function(event){},onUserFetched:function(event){var user=event.memo.user;$('chat').select(".observe-user-"+user.uid).each(function(elem){if(elem.hasClassName("observe-username")){elem.innerHTML="";elem.insert(user.username.truncate(10));}
if(elem.hasClassName("observe-square-image-url")){elem.src=user.square_image_url;}});},showMsgForUser:function(message,uid){if(!this.chatFrames[uid]){return;}
if(!this.msgHolders[uid]){this.msgHolders[uid]=DIV({"class":"sd-message"});this.msgHolders[uid].style.position="absolute";$('chat').insert(this.msgHolders[uid]);var chatOffsets=$('chat').cumulativeOffset();var chatFrameOffsets=this.chatFrames[uid].cumulativeOffset();this.msgHolders[uid].setStyle({'top':(chatFrameOffsets.top-chatOffsets.top)+'px'});this.msgHolders[uid].setStyle({'left':(chatFrameOffsets.left-chatOffsets.left)+'px'});this.msgHolders[uid].setWidth(this.chatFrames[uid].offsetWidth);this.msgHolders[uid].setHeight(this.chatFrames[uid].offsetHeight);}
this.msgHolders[uid].show();this.msgHolders[uid].update(message);},hideMsgForUser:function(uid){this.msgHolders[uid]&&this.msgHolders[uid].hide();},Events:{CHAT_STARTED:"sd:chat:ui:chat_started",CHAT_ENDED:"sd:chat:ui:chat_ended",CHAT_MSG_RECEIVED:"sd:chat:ui:chat_msg_received",CHAT_MSG_SENT:"sd:chat:ui:chat_msg_sent"}},smilies:{":-)":"happy",";-)":"wink",":-(":"sad"},getSmileyRegexp:function(){if(!this.smileyRegexp){var rxs=[];$H(this.smilies).each(function(pair){rxs.push(pair.key.replace(")","\\)").replace("(","\\("));});rxs="("+rxs.join("|")+")";this.smileyRegexp=new RegExp(rxs);}
return this.smileyRegexp;},ReportPanel:{show:function(user,chatHistory,source){var reportFrom;var cancelButton;var submitButton;var reportUI;var message;body=$('chat-body');reportUI=DIV({'id':'report-panel'},H1({},'Report '+user.username),P({},'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.'),reportForm=FORM({id:'report-form'}));SD.FlirtWink.View.reportReasons.each(function(reason,idx){reportForm.insert(DIV({'class':'option-line'},INPUT({type:'radio',name:'reason',id:'option'+idx,value:reason,"observeClick":function(){submitButton.disabled=false;}}),LABEL({'class':'option-text','for':'option'+idx},reason)));});reportForm.insert(DIV({'class':'option-line'},INPUT({type:'radio',name:'reason',id:'option-other',value:'Other',"observeClick":function(){submitButton.disabled=false;}}),LABEL({'class':'option-text','for':'option-other'},'Other')));reportForm.insert(DIV({'class':'option-line'},message=TEXTAREA({id:"reportChatMessage","observeKeyup":function(){reportForm.reason[reportForm.reason.length-1].checked=!message.value.blank();submitButton.disabled=message.value.blank();}})));reportForm.insert(DIV({'class':'option-buttons'},submitButton=INPUT({type:'button','class':'input-button',value:'Send Report'}),cancelButton=INPUT({type:'button','class':'input-button',value:'Cancel'})));body.down('div.messageframe').setStyle({'display':'none'});body.insert(reportUI);submitButton.disabled=true;$(submitButton).observe('click',function(event){var reasonText=($(reportForm).serialize(true).reason!="Other")?$(reportForm).serialize(true).reason:message.value;SD.User.reportMember(user,reasonText,chatHistory,source);SD.Chat.UI.removeUser(user.uid);body.down('div.messageframe').setStyle({'display':'block'});$(reportUI).remove();});$(cancelButton).observe('click',function(){body.down('div.messageframe').setStyle({'display':'block'});$(reportUI).remove();});}}};
SD.DatingController={_jingleVersion:2,_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",VERSION_OBSOLETE:"datingcontroller:version_obsolete",SESSION_TERMINATED:"datingcontroller:session_terminated",TRYING_TO_DATE:"datingcontroller:trying_to_date",ACCEPTED_TO_DATE:"datingcontroller:accepted_to_date"},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.XMPP.Events.DATA,this.onIncomingData.bind(this));SD.Event.observe(null,SD.DatingApp.Events.DATE_OVER,this.onDateOver.bind(this));SD.Event.observe(null,SD.DatingApp.Events.END_DATE_REQUESTED,this.onEndDateRequested.bind(this));SD.Event.observe(null,SD.DatingApp.Events.SEND_DATE_CHAT_REQUESTED,this.onSendDateChatRequested.bind(this));SD.Event.observe(null,SD.DatingApp.Events.MY_STREAMING_STATE_CHANGED,this.onMyStreamingStateChanged.bind(this));SD.Event.observe(null,SD.User.Events.VOTED,this.onIVote.bind(this));SD.Event.observe(null,SD.XMPP.Events.LOGIN,this.onLogin.bind(this));(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.DatingApp.Events.DATE_OVER,{user:user,reasondCode:"userInvalid"});return;}
SD.Event.fireDeferred(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.XMPP.getXMPPConnection().getJid().toBareJID()+'/'+SD.XMPP.getXMPPConnection().getJid().getResource();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){},onIncomingData:function(ev){this.debug("[XML]");this.debug(SD.XMPP.xmlNodetoString(ev.memo));this.debug("[/XML]");var data=ev.memo;if(!data||!data.getFirstChild){return;}
var node=data.getFirstChild();while(node&&node.getFirstChild){this.onIncomingNode(node);node=node.getNextSibling();}},onIncomingNode:function(node){this.debug("start");if(node.getNodeType()!=1){this.debug("  return3");return;}
var iq=SD.XMPP.createIQ(null,null,null,null,null,null);if(!iq.deserialize(node)){this.debug("  return4");return;}
if(iq.getType()!="get"&&iq.getType()!="set"){this.debug("  return5");return;}
var jingleData=null;var logData=null;for(var node2=node.getFirstChild();node2;node2=node2.getNextSibling()){jingleData=this.parseJingleNode(node2)||jingleData;logData=this.parseLogNode(node2)||logData;}
if(logData){this.onLogData(logData);}
if(!jingleData){this.debug("  return6");return;}
SD.log("new jingleData!");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;}
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(iq.getFrom());SD.log("iq.getFrom().toBareJID():");SD.log(iq.getFrom().toBareJID());SD.log("iq.getFrom().getResource():");SD.log(iq.getFrom().getResource());this._jingleOtherJID=iq.getFrom().toBareJID()+'/'+iq.getFrom().getResource();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.DatingApp.Events.DATE_CHAT_RECEIVED,{message:jingleData.dateChat.text,type:"text"});}else if(jingleData.streamingState){SD.log("[DC] received streamingState");SD.DatingApp.updatePartnersStreamingState(jingleData.streamingState);}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();}}
var otherJid=iq.getFrom().toBareJID()+'/'+iq.getFrom().getResource();var otherUser=SD.User.getByChatID(otherJid);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,desktopToken)){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;}
else{SD.log("accepted");SD.Event.fireDeferred(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;}}
else{SD.log("unknown-session");this.sendIQErrorInvalidSession(iq);}}
this.debug("end");},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);},onIVote:function(event){SD.log("onIVote");SD.XMPP.sendIVoted(event.memo.otherUser.chat_id);},onLogData:function(logData){SD.log("onLogData");if(logData.action=="give"){var txt=SD.DatingApp.getChatContent();SD.log("flash gave "+txt);SD.XMPP.sendLog(this._jingleOtherJID,txt);}else if(logData.action=="show"){SD.log("RECEIVED LOG DATA: "+logData.txt);}},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);}},sendSessionInitiate:function(token,desktopToken){this.debug(">>sendsessioninitiate");this._jingleActiveInitiateIqId='jingle_'+this.randomString(8);var iq=SD.XMPP.createIQ(this._jingleOtherJID,'set',this._jingleActiveInitiateIqId,null,null,this.onSessionInitiateCallback.bind(this));var Nodes=SD.DatingController.Nodes;var jingleNode=Nodes.jingle('session-initiate',this._jingleMyJID,null,this._jingleSession,[Nodes.content('initiator','video-conference',[Nodes.description(this._datingServer,this._datingInstance,this._datingSharedObject,this._datingMyResource,this._datingOtherResource,token,SD.Model.getMyself().token,SD.Model.getMyself().square_image_url,desktopToken),Nodes.transport()])]);iq.getNode().appendChild(jingleNode);this._state="pending";SD.XMPP.sendIQ(iq);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");},sendSessionAccept:function(){this.debug(">>sendsessionaccept");var iq=SD.XMPP.createIQ(this._jingleOtherJID,'set','jingle_'+this.randomString(8),null,null,null);var Nodes=SD.DatingController.Nodes;var jingleNode=Nodes.jingle('session-accept',this._jingleInitiator?this._jingleMyJID:this._jingleOtherJID,this._jingleInitiator?this._jingleOtherJID:this._jingleMyJID,this._jingleSession,[]);iq.getNode().appendChild(jingleNode);SD.XMPP.sendIQ(iq);SD.log("sent accept");this.debug("<<sendsessionaccept");},sendSessionTerminate:function(receiver,initiator,sessionId,reasonCode,reason,optReason){this.debug(">>sendsessionterminate");SD.log("sending session termination:"+reasonCode);if(reasonCode==SD.ReasonCodes.TIME_FINISHED){SD.log("reason before sending end date"+reason);}
var iq=SD.XMPP.createIQ(receiver,'set','jingle_'+this.randomString(8),null,null,null);var Nodes=SD.DatingController.Nodes;var reasonNode;if(reasonCode==SD.ReasonCodes.BUSY){reasonNode=Nodes.reason(SD.ReasonCodes.BUSY);}else if(reasonCode==SD.ReasonCodes.OBSOLETE_VERSION){reasonNode=Nodes.reason('unsupported-transports');}else{reasonNode=Nodes.reasonSuccess(reasonCode,reason);}
var jingleNode=Nodes.jingle('session-terminate',initiator,null,sessionId,[reasonNode],this._state+","+optReason);iq.getNode().appendChild(jingleNode);SD.XMPP.sendIQ(iq);this.debug("<<sendsessionterminate");},sendSessionInfo:function(){this.debug(">>sendsessioninfo");this._jingleActiveInfoIqId='jingle_'+this.randomString(8);var iq=SD.XMPP.createIQ(this._jingleOtherJID,'get',this._jingleActiveInfoIqId,null,null,this.onSessionInfoCallback.bind(this));var Nodes=SD.DatingController.Nodes;var jingleNode=Nodes.jingle('session-info',this._jingleInitiator?this._jingleMyJID:this._jingleOtherJID,this._jingleInitiator?this._jingleOtherJID:this._jingleMyJID,this._jingleSession,[]);iq.getNode().appendChild(jingleNode);SD.XMPP.sendIQ(iq);SD.log("Sent PING "+this._jingleActiveInfoIqId);this.debug("<<sendsessioninfo");},sendDateChat:function(type,text){SD.log("CHAT sendDateChat= message:"+text+" , type:"+type);SD.log("CHAT types: "+typeof(text)+", "+typeof(type));this.debug(">>sendDateChat");var iq=new xmlNode("iq",{type:"set",to:this._jingleOtherJID,id:'jingle_'+this.randomString(8)},[new xmlNode("jingle",{sid:this._jingleSession,action:"session-info",initiator:this._jingleInitiator?this._jingleMyJID:this._jingleOtherJID,responder:this._jingleInitiator?this._jingleOtherJID:this._jingleMyJID,xmlns:"urn:xmpp:tmp:jingle"},[new xmlNode("date-chat",{type:type,text:text})])]);SD.log("sending: "+iq.toString());SD.XMPP.sendXMLString(iq.toString());this.debug("<<sendDateChat");},sendStreamingState:function(streamingState){this.debug(">>sendStreamingState");var iq=SD.XMPP.createIQ(this._jingleOtherJID,'set','jingle_'+this.randomString(8),null,null,null);var Nodes=SD.DatingController.Nodes;var jingleNode=Nodes.jingle('session-info',this._jingleInitiator?this._jingleMyJID:this._jingleOtherJID,this._jingleInitiator?this._jingleOtherJID:this._jingleMyJID,this._jingleSession,[Nodes.streamingState(streamingState)]);iq.getNode().appendChild(jingleNode);SD.XMPP.sendIQ(iq);this.debug("<<sendStreamingState");},onSessionInfoCallback:function(iq){this.debug(">>onSessionInfoCallback");var id=iq.getId();if(id==this._jingleActiveInfoIqId){if(iq.getType()=='result'){SD.log("Received PONG "+id);this._jingleActiveInfoIqId=null;}
else if(iq.getType()=='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.getId();if(id==this._jingleActiveInitiateIqId){SD.log("onSessionInitiateCallback() type="+iq.getType());if(iq.getType()=='error'){this.onSessionTerminate('userDisconnected','initiate-reply error','partner');}}
this.debug("<<onSessionInitiateCallback");},onSessionTerminate:function(reasonCode,reason,who){this.debug(">>onSessionTerminate");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});}
if(reasonCode==SD.ReasonCodes.OBSOLETE_VERSION){this.onObsoleteVersion();}
if(this._state=='active'){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.DatingApp.dateEnded({user:SD.User.externalize(this._user),reasonCode:reasonCode,reason:reason,endedByMe:false,myVote:null,wasStarted:false});}
else if(oldState=='active'){this.stopUI(reasonCode,reason,who);}
this.debug("<<onSessionTerminate");},sendIQResult:function(incomingIQ){this.debug(">>sendIQResult");var resultIQ=SD.XMPP.createIQ(incomingIQ.getFrom(),'result',incomingIQ.getId(),null,null,null);SD.XMPP.sendIQ(resultIQ);this.debug("<<sendIQResult");},sendIQErrorInvalidSession:function(incomingIQ){this.debug(">>sendIQErrorInvalidSession");var resultIQ=SD.XMPP.createIQ(incomingIQ.getFrom(),'error',incomingIQ.getId(),null,null,null);var Nodes=SD.DatingController.Nodes;var errorNode=Nodes.xmlNode('error',{type:'cancel'},[Nodes.xmlNode('bad-request',{xmlns:'urn:ietf:params:xml:ns:xmpp-stanzas'},[]),Nodes.xmlNode('unknown-session',{xmlns:'urn:xmpp:tmp:jingle:errors'},[])]);resultIQ.getNode().appendChild(errorNode);SD.XMPP.sendIQ(resultIQ);this.debug("<<sendIQErrorInvalidSession");},setupUI:function(){var comm={datingAppHost:this._datingServer,datingAppInstance:this._datingInstance,myStreamName:this._datingMyResource,otherStreamName:this._datingOtherResource,sharedObjectName:this._datingSharedObject};SD.log(Object.toJSON(comm));SD.DatingApp.startDate({myUser:this._user,otherUser:SD.User.getByChatID(this._jingleOtherJID),duration:SD.Config.datingDuration,communication:comm});this._failedPings=0;SD.User.initDate(SD.User.getByChatID(this._jingleOtherJID));},stopUI:function(reasonCode,reason,who){SD.DatingApp.stopDate(reasonCode,reason,who);},clearMatched:function(){this._pc.clearMatched();},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;},parseLogNode:function(node){if(!node||!node.getNodeType){return null;}
if(node.getNodeType()!=1){return null;}
if(node.getNodeName()!="speeddate-log"){return null;}
return{action:node.getAttributes().action,txt:node.getAttributes().txt||null};},parseJingleNode:function(jingleNode){var out={action:null,initiator:null,responder:null,sessionId:null,contents:[],reasonCondition:null,reasonCode:null,reason:null,dateChat:null,streamingState:null};if(!jingleNode||!jingleNode.getNodeType){return null;}
if(jingleNode.getNodeType()!=1){return null;}
if(jingleNode.getNodeName()!="jingle"){return null;}
out.action=jingleNode.getAttributes().action;out.initiator=jingleNode.getAttributes().initiator;out.responder=jingleNode.getAttributes().responder;out.sessionId=jingleNode.getAttributes().sid;var otherState=jingleNode.getAttributes().myState;if(otherState){SD.log(otherState);SD.Track.recordRejectedDate(otherState);}
var node;var node2;for(node=jingleNode.getFirstChild();node;node=node.getNextSibling()){if(node.getNodeType()!=1){continue;}
if(node.getNodeName()=="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.getAttributes().creator;content.name=node.getAttributes().name;content.name=node.getAttributes().name;var transportXMLNS=null;for(node2=node.getFirstChild();node2;node2=node2.getNextSibling()){if(node2.getNodeType()!=1){continue;}
if(node2.getNodeName()=="transport"){transportXMLNS=node2.getAttributes().xmlns;content.version=Number(node2.getAttributes().version);if(isNaN(content.version)){content.version=0;}}else if(node2.getNodeName()=="description"){content.description.server=node2.getAttributes().server;content.description.instance=node2.getAttributes().instance;content.description.sharedObject=node2.getAttributes().sharedObject;content.description.initiatorResource=node2.getAttributes().initiatorResource;content.description.responderResource=node2.getAttributes().responderResource;content.description.responderToken=node2.getAttributes().responderToken;content.description.initiatorToken=node2.getAttributes().initiatorToken;content.description.initiatorImage=node2.getAttributes().initiatorImage;content.description.desktopToken=node2.getAttributes().desktopToken;}}
SD.log("xmlns = "+transportXMLNS);SD.log("version = "+content.version);if(transportXMLNS=="speeddate:rtmp-dating"){out.contents.push(content);}}else if(node.getNodeName()=="reason"){for(node2=node.getFirstChild();node2;node2=node2.getNextSibling()){if(node2.getNodeType()!=1){continue;}
if(node2.getNodeName()=="condition"){var node3;for(node3=node2.getFirstChild();node3;node3=node2.getNextSibling()){if(node3.getNodeType()==1){out.reasonCondition=node3.getNodeName();if(out.reasonCondition=='success'){out.reasonCode=node3.getAttributes().reasonCode;out.reason=node3.getAttributes().reason;}
break;}}}}}
else if(node.getNodeName()=="date-chat"){out.dateChat={type:node.getAttributes().type,text:node.getAttributes().text};}
else if(node.getNodeName()=="streaming-state"){out.streamingState=(node.getAttributes().state=='on');}}
return out;},parseErrorNode:function(errorNode){var out={type:null,children:[]};if(!errorNode||!errorNode.getNodeType){return null;}
if(errorNode.getNodeType()!=1){return null;}
if(errorNode.getNodeName()!="error"){return null;}
out.type=errorNode.getAttributes().type;var node;for(node=errorNode.getFirstChild();node;node=node.getNextSibling()){if(node.getNodeType()!=1){continue;}
out.children.push(node.getNodeName());}
return out;},Nodes:{textNode:function(content){return SD.XMPP.createXMLNode(3,content);},xmlNode:function(tagName,attrs,children){var node=SD.XMPP.createXMLNode(1,tagName);node.setAttributes(attrs);for(var i=0;i<children.length;i++){node.appendChild(children[i]);}
return node;},jingle: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;return SD.DatingController.Nodes.xmlNode('jingle',attrs,children);},content:function(creator,name,children){return SD.DatingController.Nodes.xmlNode('content',{creator:creator,name:name},children);},transport:function(){return SD.DatingController.Nodes.xmlNode('transport',{xmlns:'speeddate:rtmp-dating',version:SD.DatingController._jingleVersion},[]);},description:function(server,instance,sharedObject,initiatorResource,responderResource,responderToken,initiatorToken,initiatorImage,desktopToken){return SD.DatingController.Nodes.xmlNode('description',{server:server,instance:instance,sharedObject:sharedObject,initiatorResource:initiatorResource,responderResource:responderResource,responderToken:(responderToken?responderToken:''),initiatorToken:(initiatorToken?initiatorToken:''),initiatorImage:(initiatorImage?initiatorImage:''),desktopToken:(desktopToken?desktopToken:'')},[]);},reason:function(reasonCondition){return SD.DatingController.Nodes.xmlNode('reason',{},[SD.DatingController.Nodes.xmlNode('condition',{},[SD.DatingController.Nodes.xmlNode(reasonCondition,{},[])])]);},reasonSuccess:function(reasonCode,reason){return SD.DatingController.Nodes.xmlNode('reason',{},[SD.DatingController.Nodes.xmlNode('condition',{},[SD.DatingController.Nodes.xmlNode('success',{reasonCode:reasonCode,reason:reason},[])])]);},dateChat:function(type,text){SD.log("CHAT dateChatNodeCreation message:"+text+", type:"+type);return SD.DatingController.Nodes.xmlNode('date-chat',{type:type,text:text},[]);},streamingState:function(state){return SD.DatingController.Nodes.xmlNode('streaming-state',{state:state?'on':'off'},[]);}}};
var Stack=function(){this.content=[];this.length=0;};Stack.prototype.shift=function(){var entry=this.content.pop();if(this.length){SD.Event.fireDeferred(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.fireDeferred(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.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=="U"){SD.log("adding "+romeo.username+" to regular list");scope.pending.push(romeo);}else if(romeo.category=="P"){SD.log("adding "+romeo.username+" to priority list");scope.pendingPriority.push(romeo);}},30);};var seek=function(){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{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.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();}
SD.log('pairingcontroller end');}
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.DatingApp.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;setTimeout(seek,event.memo.reasonCode==SD.ReasonCodes.BUSY?this.getBusyWaitingTime():this.getNonBusyWaitingTime());}}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){var busy=-1;var mightDate=this.user.mightDate(romeo);var tokenMatches=(!token||(token==this.user.token));if(mightDate&&tokenMatches){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(){if(SD.DatingQueue._initialized){return;}
var count=this.pending.length+this.pendingPriority.length+this.matches.length+Math.max(this.outstandingInvites,0);SD.Event.fireDeferred(this,SD.User.Events.WAITING_TIME_CHANGED,{count:count});};SD.PairingController.prototype.clearMatched=function(){if(SD.DatingQueue._initialized){return;}
this.matches.empty();var count=this.pending.length+this.pendingPriority.length+this.matches.length+Math.max(this.outstandingInvites,0);SD.Event.fireDeferred(this,SD.User.Events.WAITING_TIME_CHANGED,{count:count});};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.DatingApp={app:null,isDating:false,_datingAppName:null,_startedDates:{},_successfulDates:{},_ajaxListeners:{},_pendingAjaxRequests:[],_ajaxListenerCounter:0,initialize:function(appName,datingAppName){this.app=$(appName);this._datingAppName=datingAppName;SD.Event.observe(null,SD.DatingApp.Events.START_DATE,SD.DatingApp.onDateStart);SD.Event.observe(null,SD.DatingApp.Events.DATE_OVER,SD.DatingApp.onDateOver);SD.Event.observe(null,SD.User.Events.USER_FETCHED,SD.DatingApp.onUserFetched.bind(this));SD.Event.observe(null,SD.DatingApp.Events.DATE_CHAT_RECEIVED,this.onDateChatReceived.bind(this));SD.log('initialize:'+appName);$A(SD.Config.mmsRegistries).each(function(host){SD.DatingApp.app.loadPolicyFile(host+"/crossdomain.xml");});SD.DatingApp.setUniqueId();var fnc;while((fnc=this._pendingAjaxRequests.shift())){this.callAjax(fnc.url,fnc.params,fnc.method,fnc.callBackFunc);}},setUniqueId:function(){var uniqueId=SD.DatingApp.app.getPersistentValue('uniqueId');if(!uniqueId){uniqueId=SD.Model.getMyself().uid+'_'+Math.floor(Math.random()*1000000000);SD.DatingApp.app.setPersistentValue('uniqueId',uniqueId);SD.Cookie.create('uniqueId',uniqueId);}else if(uniqueId!=SD.Cookie.read('uniqueId')){SD.Cookie.create('uniqueId',uniqueId);}},datingApp:function(){return $(this._datingAppName);},onDateStart:function(event){conf=event.memo;if(!conf.otherUser){return;}
SD.log("||dateStarts:"+conf.otherUser.uid);SD.DatingApp._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.DatingApp._successfulDates[event.memo.otherUser.uid]=true;}
if(event.memo.wasStarted){SD.User.datedWantedDate(event.memo.otherUser);}},onUserFetched:function(event){return;},onDateChatReceived:function(event){this.datingApp('supplyChatMessage').supplyChatMessage(event.memo.message,event.memo.type);},wasDateSuccessful:function(otherUser){return SD.DatingApp._successfulDates[otherUser.uid];},wasDateStarted:function(event){return SD.DatingApp._startedDates[otherUser.uid];},startDate:function(configuration){this.isDating=true;var myUser=configuration.myUser;var otherUser=configuration.otherUser;configurationForFlash={myUser:SD.User.externalize(myUser),otherUser:SD.User.externalize(otherUser),communication:configuration.communication,duration:configuration.duration};configuration.myUser=myUser;configuration.otherUser=otherUser;SD.log("skipped:"+SD.DatingApp.Events.DATING_APP_INITIALIZED);var doStart=function(user){SD.log(user.username+':'+user.image_url);configurationForFlash.otherUser=SD.User.externalize(user);try{SD.DatingApp.datingApp('startDating').startDating(configurationForFlash);}catch(e){SD.Event.observe(null,SD.DatingApp.Events.DATING_APP_INITIALIZED,function(event){SD.log("observed:"+SD.DatingApp.Events.DATING_APP_INITIALIZED);SD.DatingApp.datingApp('startDating').startDating(configurationForFlash);}.bind(this));}
SD.Event.fire(null,SD.DatingApp.Events.START_DATE,configuration);SD.log('startDating completed');}
if(configuration.otherUser.fetched){doStart(configuration.otherUser);}else{SD.User.fetch(configurationForFlash.otherUser,doStart);}},stopDate:function(reasonCode,reason,who){this.datingApp('stopDating').stopDating({reasonCode:reasonCode,reason:reason,who:who});},playMessageSound:function(){this.datingApp('playMessageSound').playMessageSound();},updatePartnersStreamingState:function(state){this.datingApp('updatePartnersStreamingState')&&this.datingApp('updatePartnersStreamingState').updatePartnersStreamingState(state);},callAjax:function(url,params,method,callBackFunc){SD.log("calling ajax:"+url);if(!SD.DatingApp.app){this._pendingAjaxRequests.push({url:url,params:params,method:method,callBackFunc:callBackFunc});return;}
this._ajaxListeners[this._ajaxListenerCounter]=callBackFunc;SD.DatingApp.app.callAjax(this._ajaxListenerCounter++,url,params,method);},datingAppInitialized:function(){SD.log("datingAppInitialized fired:"+SD.DatingApp.Events.DATING_APP_INITIALIZED);SD.Event.fireDeferred(null,SD.DatingApp.Events.DATING_APP_INITIALIZED);},getChatContent:function(){if(this.datingApp("getChatContentTest")){return this.datingApp("getChatContent").getChatContent();}
return"";},updateMyStreamingState:function(state){SD.Event.fire(null,SD.DatingApp.Events.MY_STREAMING_STATE_CHANGED,state);},requestEndDate:function(request){SD.Event.fire(null,SD.DatingApp.Events.END_DATE_REQUESTED,request);},dateEnded:function(result){SD.log('dateEnded:');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.DatingApp.Events.DATE_OVER,result);},sendChat:function(message,type){SD.log("CHAT sendChat= message:"+message+" , type:"+type);SD.Event.fire(null,SD.DatingApp.Events.SEND_DATE_CHAT_REQUESTED,{message:message,type:type});},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){SD.User.saveChatHistory(userId,otherUserId,chatHistory,remainingTime);},getExperimentShowUpgradeAfterFinishedDate:function(){return SD.ExperimentManager.ShowUpgradeAfterFinishedDate.value;},isShowingDatePopup:false,createPopup:function(){this.win=new SD.Window('dating-app-container',{hideMethod:SD.Window.OFFSCREEN_HIDE,groupId:'date',className:"dating-window win-skin1",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.datingApp('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,closeAction){this.isShowingDatePopup&&this.closeDatePopup();this.isShowingDatePopup=true;!this.win&&this.createPopup();this.win.populate({username:user.username.truncate(25),age:user.age,address:SD.ProfileViewer.UI.addressOf(user),distance:SD.ProfileViewer.UI.renderDistance(user)});this.win.isOpened?this.win.show():this.win.open();SD.Event.observe(null,SD.DatingApp.Events.CLOSE_DATING_WINDOW,function(event){this.win.hide(true);this.isShowingDatePopup=false;SD.Favicon.setTitle("");}.bind(this));SD.Event.observe(null,SD.DatingApp.Events.DATE_OVER,function(event){if((event.memo.reasonCode!='busy')&&(event.memo.reason!='initiate-reply error')){SD.Event.fire(null,SD.DatingApp.Events.CLOSE_DATING_WINDOW);}}.bind(this));},closeDatePopup:function(){SD.Event.fire(null,SD.DatingApp.Events.CLOSE_DATING_WINDOW);},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';},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',DATE_CHAT_RECEIVED:'dating:datechatreceived',DATING_APP_INITIALIZED:'dating:datingappinitialized',CLOSE_DATING_WINDOW:'dating:closedatingwindow'}};
SD.Alerts={};SD.Alerts.UI=function(target,user,flirts,requests){var flirtPanel,requestPanel,headingPanel,flirtTitle,requestTitle;var showIf=function(show,panel){if(show){$(panel).show();if(SD.ExperimentManager.SimplifySidebar2366.value!=0){if($(target).hasClassName("closedE2366")&&SD.UI.Alerts.Widget.getInstance().store.getLength()>0){$(target).removeClassName("closedE2366");$(target).addClassName("openE2366");}}}else{$(panel).hide();}};var updateDisplay=function(){var isOnLeftSide=SD.ExperimentManager.SidebarOnLeftSide.value;showIf(isOnLeftSide||flirts>0||requests>0,headingPanel);showIf(isOnLeftSide||flirts>0,flirtPanel);showIf(isOnLeftSide||requests>0,requestPanel);SD.UIController.recoverBuddyListHeight();};if(SD.ExperimentManager.GalleryHomepage2257.value==3||SD.ExperimentManager.GalleryHomepage2257.value==4){$(target).insert(headingPanel=DIV());}else{$(target).insert(headingPanel=DIV({"class":"subheader"},"Alerts"));}
$(target).insert(flirtPanel=DIV({"class":"alert"},flirtTitle=A({"class":"alert-title"})));$(target).insert(requestPanel=DIV({"class":"alert"},requestTitle=A({"class":"alert-title"})));Event.observe($(flirtPanel),"click",function(){flirts=0;displayFlirts();updateDisplay();SD.Event.fire(user,SD.Alerts.UI.Events.FLIRTS_SOUGHT);});Event.observe($(requestPanel),"click",function(){requests=0;displayRequests();updateDisplay();SD.Event.fire(user,SD.Alerts.UI.Events.BUDDY_REQUESTS_SOUGHT);});var displayFlirts=function(){$(flirtTitle).innerHTML="";if(flirts>0){if(flirts==1){$(flirtTitle).insert("1 new flirt");}else{$(flirtTitle).insert(flirts+" new flirts");}}else{$(flirtTitle).insert(SPAN({"class":"hidden-alert"},"Messages"));}};var displayRequests=function(){$(requestTitle).innerHTML="";if(requests>0){if(requests==1){$(requestTitle).insert("1 new buddy request");}else{$(requestTitle).insert(requests+" new buddy requests");}}else{$(requestTitle).insert(SPAN({"class":"hidden-alert"},"Buddy Requests"));}};displayFlirts();displayRequests();updateDisplay();return false;};SD.Alerts.UI.Events={FLIRTS_SOUGHT:"alert:flirts_sought",BUDDY_REQUESTS_SOUGHT:"alert:buddy_requests_sought"};
SD.WelcomeInstructions={_windows:null};SD.WelcomeInstructions.UI={upgradeLinkFreeTrial:function(){SD.UIController.upgradeMyself({"tc":SD.Constants.trackingCodes.welcome_popup_free_trial,'tobj':SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.WELCOME_POPUP_FREE_TRIAL)});},initialize:function(){SD.Event.observe(null,SD.UIController.Events.CLOSE_WELCOME_POPUP,function(){SD.WelcomeInstructions.UI.removePopup();});},removePopup:function(){$('welcome-popup')&&$('welcome-popup').remove();},fire:function(soulmate){}};
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){if(!SD.Model.getMyself().is_premium){SD.UIController.upgradeMyself({'tc':SD.Constants.trackingCodes.gift_button,'tobj':SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.ADD_GIFT_TO_MESSAGE)});}
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.DemographicFilter={Terms:{'quickSearch':{id:'0',title:'Quick Search',quickSearch:true},'relationshipStatus':{id:'2',title:'Relationship Status',values:{0:'Any',1:'Single',2:'Divorced',4:'Widowed',8:'Separated'}},'children':{id:'3',title:'Children',values:{0:'Any',1:'No, but I want kids',2:'No, not sure I want any',4:'No, definitely no kids',8:'Yes, they live with me',16:'Yes, they don\'t live with me'}},'education':{id:'4',title:'Education',values:{0:'Any',1:'Elementary',2:'High School',4:'Some College',8:'Bachelor\'s Deg.',16:'Master\'s Deg.',32:'JD/Ph.D/Postdoc'}},'religion':{id:'5',title:'Religion',cutAt:7,values:{0:'Any',1:'Agnostic / None',2:'Atheist',4:'Buddhist / Taoist',8:'Christian / Catholic',16:'Christian / LDS',32:'Christian / Protestant',64:'Christian / Other',128:'Hindu',256:'Jewish',512:'Muslim / Islam',1024:'Not Religious',2048:'Spiritual but not Religious',4096:'Other'}},'drinkingHabits':{id:'6',title:'Drinking Habits',values:{0:'Any',1:'Never',2:'Socially',4:'Occasionally',8:'Frequently'}},'smokingHabits':{id:'7',title:'Smoking Habits',values:{0:'Any',1:'Non-smoker',2:'Occasionally',4:'Regularly',8:'Trying to Quit'}},'ethnicity':{id:'8',title:'Ethnicity',values:{0:'Any',1:'Asian',2:'Black/African Descent',4:'East Indian',8:'Latino/Hispanic',16:'Native American',32:'Pacific Islander',64:'White/Caucasian',128:'Other'}},'speaks':{id:'9',title:'Speaks',cutAt:9,values:{0:'Any',1:'English',2:'Spanish',4:'French',8:'German',16:'Italian',32:'Portuguese',64:'Dutch',128:'Chinese',256:'Japanese',512:'Arabic',1024:'Russian',2048:'Hebrew',4096:'Hindi',8192:'Tagalog',16384:'Urdu',32768:'Other'}},'lookingFor':{id:'11',title:'Looking For',cutAt:5,values:{0:'Any',1:'Friendship',2:'Dating',4:'Long-term Relationship',8:'Marriage',16:'Casual Encounters',32:'Activity Partner',64:'Networking',128:'Long-distance Penpal'}},'height':{id:'12',title:'Height',values:{0:'Any',127:'Less than 5\'0" (152cm)',3968:'5\'0" - 5\'4" (152-163cm)',61440:'5\'5 - 5\'8" (165-173cm)',458752:'5\'9 - 6\'0" (175-183cm)',7340032:'6\'1 - 6\'4" (183-193cm)',1996488704:'More than 6\'5" (196cm)'}},'bodyStyle':{id:'14',title:'Body Style',cutAt:6,values:{0:'Any',1:'Slender',2:'About Average',4:'Athletic / Toned',8:'A Few Extra Pounds',16:'Heavy set',32:'Cuddly',128:'Husky',256:'Petite',512:'Voluptuous',1024:'Muscular',2048:'Modelesque'}},'politicalView':{id:'23',title:'Political View',values:{0:'Any',1:'Ultra Conservative',2:'Conservative',4:'Moderate',8:'Liberal',16:'Ultra Liberal',32:'Other'}},'drugHabits':{id:'24',title:'Drug Habits',values:{0:'Any',1:'Never',2:'Socially',4:'Occasionally',8:'Frequently'}},'pets':{id:'25',title:'Pets',values:{0:'Any',1:'Birds',2:'Cats',4:'Dogs',8:'Exotic pets',16:'Fish',32:'Rodents',64:'Horses',128:'Reptiles',256:'Other'}},'income':{id:'26',title:'Income',values:{0:'Any',7:'$0 - $50,000',48:'$50,000 - $70,000',192:'$70,000 - $100,000',768:'$100,000 - $250,000',1024:'$250,000 - $500,000',6144:'More than $500,000'}},'eyeColor':{id:'27',title:'Eye Color',values:{0:'Any',1:'Black',2:'Blue',4:'Brown',8:'Gray',16:'Green',32:'Hazel'}},'hairColor':{id:'28',title:'Hair Color',values:{0:'Any',1:'Black',2:'Blonde',4:'Dark blonde',8:'Light brown',16:'Dark brown',32:'Auburn / Red',64:'Gray',128:'Salt and pepper',512:'Silver',1024:'Bald'}},'bodyArt':{id:'29',title:'Body Art',values:{0:'Any',1:'Concealed Tattoo',2:'Visible Tattoo',4:'Piercing',8:'Belly Button Ring'}},'livingArrangements':{id:'30',title:'Living Arrangements',values:{0:'Any',1:'Live alone',2:'Live with kids',4:'Live with parents',8:'Live with roommate(s)'}}},Ordering:[['quickSearch','relationshipStatus','lookingFor'],['ethnicity','religion','speaks'],['income','education','politicalView','children'],['livingArrangements','drinkingHabits','smokingHabits','drugHabits'],['height','bodyStyle','bodyArt']],searchArray:{}};SD.DemographicFilter.UI={defaultListSize:20,target:null,quickSearchLocation:null,rendered:false,animating:false,filterOpen:false,termsText:"",renderOption:function(optionGroupName,headerTarget,contentTarget){optionGroup=SD.DemographicFilter.Terms[optionGroupName];var listSize=optionGroup.cutAt?optionGroup.cutAt:SD.DemographicFilter.UI.defaultListSize;var checkboxULContainer=DIV({'class':'optionGroups','id':'g_'+optionGroupName});var anyText=optionGroupName=="quickSearch"?"":"Any";var groupHeader=DIV({'class':'optionHeader','id':'h_'+optionGroupName},DIV({'class':'groupTitle'},optionGroup.title)," ",DIV({'class':'selectedText'},anyText));if(optionGroup.range){var selectContainer=DIV({'class':'optionGroup selectContainer'});var selectDivMin=SELECT({'id':'member_preferences['+optionGroup.id+']_min'});var selectDivMax=SELECT({'id':'member_preferences['+optionGroup.id+']_max'});$H(optionGroup.values).each(function(pair,index){selectDivMin.insert(OPTION({'value':pair.key},pair.value));selectDivMax.insert(OPTION({'value':pair.key},pair.value));});selectDivMin.value=selectDivMin.select('option').first().value;selectDivMax.value=selectDivMax.select('option').last().value;selectContainer.insert(" from ");selectContainer.insert(selectDivMin);selectContainer.insert(" to ");selectContainer.insert(selectDivMax);checkboxULContainer.insert(selectContainer);}else if(optionGroup.quickSearch){var checkboxUL=DIV({'class':'optionGroup','id':'advanced-quick-search'});checkboxULContainer.insert(checkboxUL);}else{var checkboxUL=UL({'class':'optionGroup'});$H(optionGroup.values).each(function(pair,index){if((index%listSize)==0&&index>0){checkboxULContainer.insert(checkboxUL);checkboxUL=UL({'class':'optionGroup'});}
checkboxUL.insert(LI({'class':'option'},INPUT({'class':'input-checkbox','type':'checkbox','rel':'member_preferences['+optionGroup.id+']','id':'member_preferences['+optionGroup.id+']['+index+']',"value":pair.key}),LABEL({'for':'member_preferences['+optionGroup.id+']['+index+']','id':'member_preferences_label_'+optionGroup.id+'_'+index},pair.value)));});var actualValue=INPUT({'type':'hidden','name':'member_preferences['+optionGroup.id+']','value':0});checkboxULContainer.insert(checkboxUL);checkboxULContainer.insert(actualValue);checkboxULContainer.select('input[value="0"]').each(function(c){c.checked=true;c.defaultChecked=true;});checkboxULContainer.select('li').each(function(observed){observed.observe('click',function(){var theCheckbox=observed.select('input')[0];var value=theCheckbox.value;SD.log(Prototype.Browser.IE);SD.log(SD.BrowserDetect.version);if(value!="0"&&checkboxULContainer.select('.input-checkbox[value=0]')[0].checked){checkboxULContainer.select('.input-checkbox[value=0]')[0].checked=false;}else if(value=="0"&&theCheckbox.checked){checkboxULContainer.select('.input-checkbox[value!="0"]').each(function(c){c.checked=false;});}else if(value=="0"&&!theCheckbox.checked){this.checked=false;}
var selectedText=groupHeader.down('.selectedText');var checkedOptions=checkboxULContainer.select('.input-checkbox').findAll(function(option){return option.checked;});SD.log(checkedOptions.length);if(optionGroup.id!==0){if(checkedOptions.length===0){checkboxULContainer.select('.input-checkbox[value=0]')[0].checked=true;actualValue.setAttribute('value',0);selectedText.update("Any");}else if(checkedOptions.length===($H(optionGroup.values).size()-1)){actualValue.setAttribute('value',0);selectedText.update("Any");}else{var newValue=checkedOptions.inject(0,function(acc,checkedOption){return acc+parseInt(checkedOption.value);});actualValue.setAttribute('value',newValue);selectedText.update(checkedOptions.collect(function(opt){return opt.next().innerHTML;}).join(', '));}}});});}
headerTarget.insert(groupHeader);contentTarget.insert(checkboxULContainer);},closeDemoFilters:function(){if(SD.DemographicFilter.UI.animating||!SD.DemographicFilter.UI.filterOpen){return false;}
var quickSearch=$(SD.DemographicFilter.UI.quickSearchLocation);if(quickSearch){quickSearch.update($('advanced-quick-search').innerHTML);quickSearch.select('select').each(function(e){e.selectedIndex=$('advanced-quick-search').select('select[name="'+e.name+'"]')[0].selectedIndex;});quickSearch.select('input').each(function(e){e.checked=$('advanced-quick-search').select('input[name='+e.name+']')[0].checked;});quickSearch.select('.advanced-search-link').invoke('show');SD.DemographicFilter.UI._attachAgeLimiter(SD.DemographicFilter.UI.quickSearchLocation);}
Effect.SlideUp(SD.DemographicFilter.UI.container,{duration:0.5,beforeStart:function(e){SD.DemographicFilter.UI.animating=true;},afterFinish:(function(e){SD.DemographicFilter.UI.animating=false;$$('#content-members select').each(function(e){e.setStyle({'visibility':'visible'});});if(Prototype.Browser.IE&&SD.BrowserDetect.version=="6"){$$("#content-members select").each(function(e){e.setStyle({'visibility':'visible'});});}
SD.DemographicFilter.UI.filterOpen=false;}).bind(this)});var searchedText=$(SD.DemographicFilter.UI.target).select(".selectedText").collect(function(text){if(text.innerHTML!=="Any"&&text.up().id!=='h_quickSearch'){return'<div class="searchTerm">'+text.up().innerHTML+'</div>';}}).without(undefined).join(" ");SD.DemographicFilter.UI.termsText=searchedText;},openDemoFilters:function(){if(!this.rendered){this.render(this.target,this.quickSearchLocation);}
if(SD.DemographicFilter.UI.animating){return false;}
SD.DemographicFilter.UI.filterOpen=true;var sidebarQuickSearch=$(SD.DemographicFilter.UI.quickSearchLocation);if(sidebarQuickSearch){$('advanced-quick-search').update(sidebarQuickSearch.innerHTML);$$('#advanced-quick-search select').each(function(e){e.selectedIndex=sidebarQuickSearch.select('select[name="'+e.name+'"]')[0].selectedIndex;});$$('#advanced-quick-search input').each(function(e){e.checked=sidebarQuickSearch.select('input[name='+e.name+']')[0].checked;});}else if($('search-form')){$('advanced-quick-search').update($('search-form').down('ul.form-items').innerHTML);}
$('advanced-quick-search').select('.advanced-search-link').invoke('hide');SD.DemographicFilter.UI._attachAgeLimiter('advanced-quick-search');Effect.SlideDown(SD.DemographicFilter.UI.container,{duration:0.5,beforeStart:function(e){SD.DemographicFilter.UI.animating=true;if(Prototype.Browser.IE&&SD.BrowserDetect.version=="6"){$$("#content-members select").each(function(e){e.setStyle({'visibility':'hidden'});});}},afterFinish:(function(e){SD.DemographicFilter.UI.animating=false;}).bind(this)});},_attachAgeLimiter:function(parentElement){var minAgeEls=$(parentElement).select('select').filter(function(el){return el.id=='min_age'});var maxAgeEls=$(parentElement).select('select').filter(function(el){return el.id=='max_age'});if(minAgeEls.length==0||maxAgeEls.length==0){return;}
var minAge=minAgeEls[0];var maxAge=maxAgeEls[0];var limiter=function(){if(parseInt(maxAge.value,10)<parseInt(minAge.value,10)){maxAge.value=minAge.value;}}
minAge.onchange=limiter;maxAge.onchange=limiter;},searchPremiumWarning:function(){var ua={'tc':SD.Constants.trackingCodes.site_advanced_search,'tobj':SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.ADVANCED_SEARCH_MEMBERS)};SD.UIController._popupGenericWarning("Upgrade to do advanced searching!",ua,[" can do an advanced search."],"Upgrade to do Advanced Search");},initialize:function(target,quickSearchLocation){this.target=target;this.quickSearchLocation=quickSearchLocation;},render:function(target,quickSearchLocation){SD.DemographicFilter.UI.container=$(target);$(target).setStyle({'display':'none'});SD.DemographicFilter.UI.target=DIV({'class':'filter-ui'});SD.DemographicFilter.UI.bottomBar=DIV({'class':'filter-bottom-bar'});SD.DemographicFilter.UI.quickSearchLocation=quickSearchLocation;SD.DemographicFilter.UI.filterParts=DIV({'class':'filter-parts'},SD.DemographicFilter.UI.target,SD.DemographicFilter.UI.bottomBar);$(target).insert(SD.DemographicFilter.UI.filterParts);SD.DemographicFilter.Ordering.each(function(orderGroup,groupIndex){var optionHeaderParams={'class':'optionHeaders open','id':'headerGroup'+groupIndex};var optionContentParams={'class':'optionContents','id':'contentGroup'+groupIndex};if(groupIndex!==0){optionContentParams['style']={'display':'none'};optionHeaderParams['class']="optionHeaders";}
var optionContents=DIV(optionContentParams);var optionHeaders=DIV(optionHeaderParams);orderGroup.each(function(orderName){SD.DemographicFilter.UI.renderOption(orderName,optionHeaders,optionContents);});optionHeaders.observe('click',function(evt){if(SD.DemographicFilter.UI.animating){evt.stop();return false;}
var visibleHeaders=this.adjacent('.optionHeaders').invoke('removeClassName','open');var visibleContents=this.next().adjacent('.optionContents').findAll(function(elem){return elem.visible();});Effect.multiple(visibleContents,Effect.BlindUp,{duration:0.3});Effect.toggle(this.next(),'blind',{duration:0.3,beforeStart:function(e){SD.DemographicFilter.UI.animating=true;if(Prototype.Browser.IE){$$(".filter-ui input").each(function(e){e.setStyle({visibility:'hidden'});});}},afterFinish:(function(e){SD.DemographicFilter.UI.animating=false;if(this.next().visible()){this.addClassName('open');}else{this.removeClassName('open');}
if(Prototype.Browser.IE){$$(".filter-ui input").each(function(e){e.setStyle({visibility:'visible'});});}}).bind(this)});});SD.DemographicFilter.UI.target.insert(optionHeaders);SD.DemographicFilter.UI.target.insert(optionContents);});SD.DemographicFilter.UI.bottomBar.insert(DIV({'class':'search-cancel','observeClick':SD.DemographicFilter.UI.closeDemoFilters},'or cancel'));if(SD.Model.getMyself().is_premium||SD.ExperimentManager.FreeAdvancedSearch1379.value){SD.DemographicFilter.UI.bottomBar.insert(INPUT({'type':'submit','value':' ','class':'search-button','observeClick':SD.DemographicFilter.UI.closeDemoFilters}));}else{SD.DemographicFilter.UI.bottomBar.insert(DIV({'class':'search-button','observeClick':SD.DemographicFilter.UI.searchPremiumWarning}));}
this.rendered=true;}};
SD.PremiumChat={xmppCheckInterval:5,failCount:3,lazyChatFailCount:60,_premiumList:new Hash(),_iqId:1,initialize:function(){SD.Event.observe(null,SD.XMPP.Events.DATA,this.onIncomingData.bind(this));SD.Event.observe(null,SD.Chat.UI.Events.CHAT_ENDED,SD.PremiumChat.onChatEnded.bind(this));SD.Event.observe(null,SD.Chat.UI.Events.CHAT_MSG_RECEIVED,SD.PremiumChat.onChatReceive.bind(this));new PeriodicalExecuter(this.periodicalChecker.bind(this),this.xmppCheckInterval);},periodicalChecker:function(pe){this._premiumList.each(function(pair){SD.PremiumChat.pingUser(pair.key);}.bind(this));},pingUser:function(uid){if(!SD.XMPP.isLoggedIn()){return;}
var data=this._premiumList.get(uid);if(data.waitingReply){data.waitingReply=false;if(this.incrementFailedTries(uid)){return;}}
var jid=data.user.chat_id+'/'+SD.XMPP._resourceName;var uid=data.user.uid;var iq=SD.XMPP.createIQ(jid,'get','premium_'+(this._iqId++),null,null,function(iq2){SD.PremiumChat.onPong(uid,iq2);});var pingNode=SD.XMPP.createXMLNode(1,'ping');pingNode.getAttributes().xmlns='urn:xmpp:ping';iq.getNode().appendChild(pingNode);data.waitingReply=true;SD.XMPP.sendIQ(iq);},onPong:function(uid,iq){var data=this._premiumList.get(uid);if(data){data.waitingReply=false;if(iq.getType()=='error'){this.incrementFailedTries(uid);}else{this.resetFailedTries(uid);}
SD.Event.fire(null,SD.PremiumChat.Events.PONG,{user:data.user,success:iq.getType()!='error'});}},resetFailedTries:function(uid){var data=this._premiumList.get(uid);var oldFail=data.fail;data.fail=0;data.lazyChat=false;this.setAvailable(data.user);},incrementFailedTries:function(uid){var data=this._premiumList.get(uid);var oldFail=data.fail;data.fail++;if((!data.lazyChat&&data.fail>=this.failCount)||(data.lazyChat&&data.fail>=this.lazyChatFailCount)){this._premiumList.unset(uid);this.setUnavailable(data.user,true);return true;}
return false;},onIncomingData:function(ev){var data=ev.memo;if(!data||!data.getFirstChild){return;}
var node=data.getFirstChild();while(node&&node.getFirstChild){if(node.getNodeType()==1){var iq=SD.XMPP.createIQ(null,null,null,null,null,null);if(iq.deserialize(node)&&iq.getType()=="get"&&iq.getNode().getFirstChild()&&iq.getNode().getFirstChild().getNodeName&&iq.getNode().getFirstChild().getNodeName()=='ping'){var iqResult=SD.XMPP.createIQ(iq.getFrom(),'result',iq.getId(),null,null,null);SD.XMPP.sendIQ(iqResult);}}
node=node.getNextSibling();}},onChatEnded:function(event){var user=event.memo.user;if(this._premiumList.get(user.uid)){this._premiumList.unset(user.uid);}},onChatReceive:function(event){var sender=event.memo.sender;var data=this._premiumList.get(sender.uid);if(data){return;}
if(!SD.BuddyList.Controller.isBuddy(sender)){this.addToPremiumList(sender);this.setAvailable(sender);}},addToPremiumList:function(user,lazyChat){this._premiumList.set(user.uid,{fail:0,waitingReply:false,user:user,lazyChat:lazyChat});},chatWithUser:function(user,openWindow){if(openWindow==undefined){openWindow=true;}
this.addToPremiumList(user);if(openWindow){SD.Event.fire(null,SD.UIController.Events.START_CHAT_REQUESTED,{user:user});}},lazyChatWithUser:function(user){this.addToPremiumList(user,true);SD.Event.fire(null,SD.UIController.Events.START_CHAT_REQUESTED,{user:user,isConnecting:true});},chatWithUsername:function(uid,username){var user=SD.User.get(uid,username,null);SD.PremiumChat.chatWithUser(user);},setAvailable:function(user,force){if(force||!user.online){SD.Event.fire(null,SD.PremiumChat.Events.USER_AVAILABLE,{user:user});}},setUnavailable:function(user,force){if(force||user.online){SD.Event.fire(null,SD.PremiumChat.Events.USER_UNAVAILABLE,{user:user});}},Events:{USER_AVAILABLE:"sd:premiumchat:userAvailable",USER_UNAVAILABLE:"sd:premiumchat:userUnavailable",PONG:"sd:premiumchat:pong"}};
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.DatingQueue={_viewList:null,_pc:null,_currentDateDiv:null,_currentDateMatch:null,_highlightedMatch:null,_version:23,_nextRecord:null,records:[],_dateRequesters:null,_currentMatch:null,_currentIndex:0,_initialized:false,_indexToScroll:null,_shouldUpdateNext:false,_prevButtons:null,_nextButtons:null,_currentDateButtons:null,_autoscrollCheckBoxes:null,_autoScroll:true,_needToUpdateUpcomingDatesCount:false,_LIMIT:30,_n_potential_dates:0,_viewEnabled:false,_nextContentIsMine:false,N_VISIBLE:7,STATUS:{UPCOMING:'upcoming',NEGOTIATING:'negotiating',BUSY:'busy',DATING:'dating',DATED:'dated',OFFLINE:'offline'},TYPE:{MATCH:1,PENDING:2,PENDING_PRIORITY:3,RECEIVED_DATE:4,ASKED:5,DATED:6,OFFLINE:7},scoreCnts:{dated_or_asked:60000,receivedDate:50000,pendingPriority:40000,pending:30000,matched:20000},debug:function(obj){},error:function(obj){},init:function(){this.debug("DQ init enter");if(this._initialized){return;}
this.debug("DQ init");var pc=SD.DatingController._pc;if(pc==null){this.debug("no pc, delaying init...");this.init.bind(this).delay(1);return;}
this._pc=pc;this.records=[];this._pastDates=new Stack();var scope=this;var listen=function(stack){if(stack.content.length){stack.content.each(function(match){SD.DatingQueue._onNewMatch({source:stack,memo:{obj:match}});}.bind(this));}
SD.Event.observe(stack,Stack.Events.ADDED,scope._onNewMatch.bind(scope));SD.Event.observe(stack,Stack.Events.REMOVED,scope._onMatchRemoved.bind(scope));};SD.Event.observe(null,SD.DatingController.Events.TRYING_TO_DATE,this._onTryingToDate.bind(this));SD.Event.observe(null,SD.DatingController.Events.ACCEPTED_TO_DATE,this._onAcceptedToDate.bind(this));SD.Event.observe(null,SD.DatingApp.Events.DATE_OVER,this._onDateOver.bind(this));SD.Event.observe(null,SD.DatingApp.Events.START_DATE,this._onStartDate.bind(this));SD.Event.observe(null,SD.User.Events.DATE_RESULT_FETCHED,this._onDateResult.bind(this));this._dateRequesters=new Stack();listen(pc.pending);listen(pc.pendingPriority);listen(this._dateRequesters);listen(pc.matches);SD.Event.observe(null,SD.UserFilters.UI.Events.FILTER_CHANGED,this._onFilterChange.bind(this));SD.Event.observe(null,SD.UserFilters.UI.Events.START_SPEEDDATING,function(){this._updateNextRecord();}.bind(this));SD.Event.observe(null,SD.UserFilters.UI.Events.PAUSE_SPEEDDATING,function(){this._setNextRecord(null);}.bind(this));this.debug("DQ version:"+this._version);SD.Event.observe(null,SD.Nav.Events.CONTENT_LOADED,function(e){this.debug("CONTENT LOADED");this.debug(e);if(this._nextContentIsMine){this._enableView();}}.bind(this));SD.Event.observe(null,SD.Nav.Events.PAGE_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!='live_activity')){this._disableView();}else{this._nextContentIsMine=true;}}}.bind(this));this._initViewListeners();this._initialized=true;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=='live_activity')){this.debug("enabling view...");this._enableView();}},_enableView:function(){this._createView();this._viewEnabled=true;},_disableView:function(){this._destroyView();this._viewEnabled=false;},_destroyView:function(){this.debug("ON DQ DESTROY");if(!this._viewEnabled){return;}
this.debug("DESTROYING DATING QUEUE!");},_createView:function(){this.debug("ON DQ INIT");if(this._viewEnabled){return;}
this.debug("DATING QUEUE CREATE!!! 13");SD.log("updating list");this._prevButtons=$$('.q-prev-button');this._nextButtons=$$('.q-next-button');this._currentDateButtons=$$('.q-currentdate-button');this._autoscrollCheckBoxes=$$('.dating-autoscroll');this._prevButtons.each(function(button){button.observe('click',function(){if(button.hasClassName('q-prev-disabled')){return;}
this.debug("scroll prev");this._setAutoscroll(false);this._scrollToIndex(this._currentIndex-1,true);}.bind(this))}.bind(this));this._nextButtons.each(function(button){button.observe('click',function(){if(button.hasClassName('q-next-disabled')){return;}
this.debug("scroll next");this._setAutoscroll(false);this._scrollToIndex(this._currentIndex+1,true);}.bind(this))}.bind(this));this._currentDateButtons.each(function(button){button.observe('click',function(){if(button.hasClassName('q-disabled')||!this._currentDateMatch){return;}
this._scrollToMatch(this._currentDateMatch,true);this._setAutoscroll(true);}.bind(this))}.bind(this));this._autoscrollCheckBoxes.each(function(button){button.observe('click',function(){if(this._autoScroll!=button.checked){return;}
this._setAutoscroll(!button.checked);if(this._autoScroll){this._updateNextRecord();}}.bind(this))}.bind(this));this._setAutoscroll(this._autoScroll);this._viewList=new UI.Carousel.Mutable("vertical_carousel",{direction:"vertical",nbVisible:9,previousButton:false,nextButton:false,elementSize:90});this._currentDateDiv=$('current_date_container');SD.Event.observe(null,"carousel:scroll:ended",this._onCarouselScroll.bind(this));this.debug("inserting each record to view list again");this.records.each(function(record){SD.Event.fire(null,SD.DatingQueue.Events.VIEW_LIST_INSERT,{record:record});}.bind(this));var changeText=$('q_change_text');if(changeText){changeText.observe('mouseover',function(){SD.Tooltip.hide();SD.Tooltip.show('Use the controls at the top of the page to adjust your settings');});changeText.observe('mouseout',SD.Tooltip.hide);}
var whosNextText=$('q_whos_next_text');if(whosNextText){whosNextText.observe('mouseover',function(){SD.Tooltip.hide();SD.Tooltip.show("Due to members logging on and off, the member at the top of the list isn't necessarily your next SpeedDate");});whosNextText.observe('mouseout',SD.Tooltip.hide);}
this._updateFilterInfo();SD.Event.fire(null,SD.DatingQueue.Events.UPDATE_CURRENT_DATE_DIV,{match:this._highlightedMatch});SD.Event.fire(null,SD.DatingQueue.Events.VIEW_LIST_SCROLL_TO,{index:SD.DatingQueue._currentIndex});this._updateUpcomingSpeeddates();this._updateCurrentDateButton();this._updateButtons();this._updateNextRecord();},_onCarouselScroll:function(e){this._currentIndex=this._viewList.currentIndex();this._updateButtons();this.debug("updated current match index:"+this._currentIndex);},_setAutoscroll:function(autoscroll){this.debug("Setting auto scroll to:"+autoscroll);this._autoScroll=autoscroll;this._autoscrollCheckBoxes.each(function(b){b.checked=!autoscroll;});},_updateDateResult:function(result){if(!$('q_date_result')){return;}
this.debug("updating date result");this.debug(result);if(result===true){$('q_date_result').innerHTML="match";}else if(result===false){$('q_date_result').innerHTML="no match";}else{$('q_date_result').innerHTML="date ended";}},_onDateResult:function(e){return;if(this._highlightedMatch&&user.uid==_highlightedMatch.uid){if(e.memo.success){this._updateDateResult(true);}else{this._updateDateResult(false);}}},_decrementNumberOfPotentialDates:function(){this._n_potential_dates--;if(this._n_potential_dates<0){this._n_potential_dates=0;}
this._updateUpcomingSpeeddates();},_incrementNumberOfPotentialDates:function(){this._n_potential_dates++;this._updateUpcomingSpeeddates();},_resetNumberOfPotentialDates:function(){this._n_potential_dates=0;this._updateUpcomingSpeeddates();},_updateUpcomingSpeeddates:function(){this._needToUpdateUpcomingDatesCount=true;this._updateUpcomingSpeeddatesDeferred.bind(this).defer();},_updateUpcomingSpeeddatesDeferred:function(){this.debug("DISPATCHING NEW CNT");if(this._needToUpdateUpcomingDatesCount){this.debug("NEED");this._needToUpdateUpcomingDatesCount=false;SD.Event.fireDeferred(this,SD.User.Events.WAITING_TIME_CHANGED,{count:this._n_potential_dates});this.debug("DONE");}
this.debug("--------");},_onFilterChange:function(){this._updateFilterInfo();this._removeAllRecords();},_updateFilterInfo:function(){var user=SD.Model.getMyself();var infoText='Aged '+user.min_age+' to '+user.max_age;if(user.filter_country=='WW'){infoText+=" worldwide";}else{if(parseInt($('location').value)){infoText+=" within "+$('location').value+' miles of you';}
infoText+=' in '+user.country_name;}
$('q_filter_info').innerHTML="";$('q_filter_info').insert(infoText);},_updateCurrentDateButton:function(){if(this._currentDateMatch){this._currentDateButtons.each(function(b){b.removeClassName('q-disabled')});}else{this._currentDateButtons.each(function(b){b.addClassName('q-disabled')});}},_updateButtons:function(){if(this._currentIndex==0){this._prevButtons.each(function(b){b.addClassName('q-prev-disabled')});}else{this._prevButtons.each(function(b){b.removeClassName('q-prev-disabled')});}
if(this._currentIndex<this.records.length-this.N_VISIBLE){this._nextButtons.each(function(b){b.removeClassName('q-next-disabled')});}else{this._nextButtons.each(function(b){b.addClassName('q-next-disabled')});}},_updateCurrentDateDiv:function(match,force){this.debug("updating current date div");if(!match){if(this._currentDateMatch){this._currentDateMatch=null;this._updateDateResult(null);this._updateCurrentDateButton();}
if(!force){return;}
if(!this._highlightedMatch){SD.Event.fire(null,SD.DatingQueue.Events.UPDATE_CURRENT_DATE_DIV,{});}
return;}else if(this._currentDateMatch&&this._currentDateMatch.uid==match.uid){return;}
this._highlightedMatch=this._currentDateMatch=match;this.debug(match);SD.Event.fire(null,SD.DatingQueue.Events.UPDATE_CURRENT_DATE_DIV,{match:match});this._updateCurrentDateButton();},_onStartDate:function(e){this.debug("DATE START");this._updateCurrentDateDiv(e.memo.otherUser);this._setMatchStatus(e.memo.otherUser,this.STATUS.DATING);},_onTryingToDate:function(e){this._setMatchStatus(e.memo.match,this.STATUS.NEGOTIATING);},_onAcceptedToDate:function(e){this._setMatchStatus(e.memo.match,this.STATUS.DATING);},_onDateOver:function(e){this._updateCurrentDateDiv(null);this.debug("DATE OVER");this.debug(e);this.debug("reason Code:"+e.memo.reasonCode);if(e.memo.otherUser&&!SD.Model.getMyself().hasDated(e.memo.otherUser)){this._setMatchStatus(null,this.STATUS.DATED);}else{switch(e.memo.reasonCode){case SD.ReasonCodes.BUSY:case SD.ReasonCodes.VERSION_OBSOLETE:this._setMatchStatus(null,this.STATUS.BUSY);break;case SD.ReasonCodes.JINGLE_FAILED:case SD.ReasonCodes.NOT_AVAILABLE:case SD.ReasonCodes.USER_INVALID:case SD.ReasonCodes.USER_DISCONNECTED:this._setMatchStatus(null,this.STATUS.OFFLINE);break;case SD.ReasonCodes.TIME_FINISHED:case SD.ReasonCodes.USER_LEFT:case SD.ReasonCodes.USER_REPORTED:this._setMatchStatus(null,this.STATUS.DATED);break;}}
if(e.memo.reasonCode!=SD.ReasonCodes.TIME_FINISHED){this._updateDateResult(null);}},_setMatchStatus:function(match,status){if(match){this._setNextRecord(null);}else{this._updateNextRecord();}
this.debug("set match:"+match+", status: "+status+" current match:"+this._currentMatch);this.debug(match);this.debug("----");var record=null;if(match){if(this._currentMatch&&this._currentMatch.uid!=match.uid){this.debug("has current match which is not equal to the new, update it!");this.debug(this._currentMatch);var rec=this._getRecordByMatch(this._currentMatch);if(rec){this._updateRecordStatus(rec,this.STATUS.BUSY);this.debug("updated status of the current match to busy");}else{this.error("could not find the record of the current match (old)");this.error(this._currentMatch);}}
this.debug("found match");record=this._getRecordByMatch(match);if(!record){this.debug("found no record");this._dateRequesters.push(match);return;}}else if(this._currentMatch){this.debug("have current match");record=this._getRecordByUid(this._currentMatch.uid);}
if(record){this.debug("found record");this.debug(record);}
this.debug("setting curr match");this._currentMatch=match;this.debug("will update record status");if(!this._updateRecordStatus(record,status)){this._updateRecordDiv(record);}
this.debug("set match done");},_setNextRecord:function(record){this.debug("setting next record");this.debug(record);if(this._nextRecord==record){if(record){if(record.div){this._updateRecordDiv(record);}else{this.error("record w/o a div :s");this.error(record);}}
return;}
var _exNext=this._nextRecord;this._nextRecord=record;if(_exNext&&_exNext.div){this.debug("removing from old");this._updateRecordDiv(_exNext);}
if(record&&record.div){this.debug("adding to new");this._updateRecordDiv(record);}},_updateNextRecord:function(){this._shouldUpdateNext=true;this._updateNextRecordDeferred.bind(this).defer();},_updateNextRecordDeferred:function(){this.debug("UPDATING NEXT RECORD");if(this._shouldUpdateNext){this.debug("REALLY UPDATING :)");this._shouldUpdateNext=false;if(!this._pc.amIdle()){this._setNextRecord(null);return;}
this.debug("update next record and try to scroll");var nextIndex=-1;this.records.each(function(record,index){if(record.status==this.STATUS.UPCOMING){nextIndex=index;throw $break;}}.bind(this));if(nextIndex==-1){nextIndex=this.records.length;}
var record=this.records[nextIndex];this._setNextRecord(record);this._scrollToIndex(nextIndex);}},_getIndexByMatch:function(match){var ind=-1;if(match){this.records.each(function(record,index){if(record.match.uid==match.uid){ind=index;throw $break;}});}
return ind;},_getIndexByRecord:function(record){return this._getIndexByMatch(record.match);},_getRecordByUid:function(uid){var record=null;this.records.each(function(rec){if(rec.match.uid==uid){record=rec;throw $break;}}.bind(this));return record;},_getRecordByMatch:function(match){return this._getRecordByUid(match.uid);},_scrollToMatch:function(match,force){this.debug("scroll to match");var ind=this._getIndexByMatch(match);this._scrollToIndex(ind,force);},_scrollToIndex:function(ind,force){this.debug("scroll request to index:"+ind+", force:"+force);if((ind>-1&&(force||this._isAutoScroll()))){this._indexToScroll=ind;this._scrollDeferred.bind(this).defer();}},_scrollDeferred:function(){if(this._indexToScroll!==null){this.debug("scrolling to index "+this._indexToScroll);SD.Event.fire(null,SD.DatingQueue.Events.VIEW_LIST_SCROLL_TO,{index:this._indexToScroll});this._indexToScroll=null;}},_statusToClassName:function(status){return'q-'+status;},_isAutoScroll:function(){return this._autoScroll;},_sourceToScore:function(source){return this._typeToScore(this._sourceToType(source));},_typeToScore:function(type){switch(type){case this.TYPE.MATCH:return this.scoreCnts.matched++;case this.TYPE.PENDING:return this.scoreCnts.pending++;case this.TYPE.PENDING_PRIORITY:return this.scoreCnts.pendingPriority++;case this.TYPE.RECEIVED_DATE:return this.scoreCnts.receivedDate++;case this.TYPE.ASKED:case this.TYPE.DATED:case this.TYPE.OFFLINE:return this.scoreCnts.dated_or_asked--;default:this.error("typeToScore called w/ invalid type:"+type);return-1;}},_sourceToType:function(source){switch(source){case this._pc.pending:return this.TYPE.PENDING;case this._pc.pendingPriority:return this.TYPE.PENDING_PRIORITY;case this._pc.matches:return this.TYPE.MATCH;case this._dateRequesters:return this.TYPE.RECEIVED_DATE;default:this.error("source to type called w/ invalid source:");this.error(source);return-1;}},_statusToType:function(status,defType){switch(status){case this.STATUS.BUSY:return this.TYPE.ASKED;case this.STATUS.DATING:case this.STATUS.DATED:return this.TYPE.DATED;case this.STATUS.OFFLINE:return this.TYPE.OFFLINE;default:return defType;}},_typeToStatus:function(type){switch(type){case this.TYPE.PENDING:case this.TYPE.PENDING_PRIORITY:case this.TYPE.MATCH:case this.TYPE.RECEIVED_DATE:return this.STATUS.UPCOMING;break;case this.TYPE.ASKED:return this.STATUS.BUSY;break;case this.TYPE.DATED:return this.STATUS.DATED;break;case this.TYPE.OFFLINE:return this.STATUS.OFFLINE;default:this.error("type to status called w/ invalid type:"+type);}},_recordStatusToReadbleText:function(record){this.debug(record);switch(record.status){case this.STATUS.UPCOMING:if(this._nextRecord==record){return"checking to see if "+record.match.username+" is available";}else{return"upcoming";}
case this.STATUS.NEGOTIATING:return"checking to see if "+record.match.username+" is available";case this.STATUS.BUSY:return"not yet available";case this.STATUS.DATING:return"dating";case this.STATUS.DATED:return"date ended";case this.STATUS.OFFLINE:return"offline";default:return status;}},_onNewMatch:function(e){this.debug("new match:"+e.memo.obj.uid);this.debug(e);this.debug("***");var match=e.memo.obj;if(!match){this.debug("no match in event :s");return;}
var type=this._sourceToType(e.source);if(type==this.TYPE.RECEIVED_DATE){if(this._currentDateMatch&&this._currentDateMatch==match){type=this.TYPE.DATED;}}
var record=SD.DatingQueue._getRecordByMatch(match);if(record){this.debug("updating record type");this._updateRecordType(record,type);return;}else{this.debug("creating new record");var score=this._sourceToScore(e.source);var record=this._createRecord(e.memo.obj,score,type,true);var place=this._findIndexForNewRecord(record);this._insertRecord(record,place);}
this.debug("DONE NEW MATCH");},_updateRecordStatus:function(record,status){this.debug("_updateRecordStatus");if(!record||record.status==status){this.debug("no need to update bcuz record already has that status");this.debug(status);this.debug("-----------");return false;}
var oldStatus=record.status;record.status=status;if(record.type!=this._statusToType(status,record.type)){this._updateRecordType(record,this._statusToType(status,record.type));}else{this._updateRecordDiv(record);}},_updateRecordType:function(record,newType){this.debug("updating record type: old:"+record.type+", new:"+newType);if(!record||(record.type!=this.TYPE.ASKED&&newType<record.type)){return;}
if(record.type==newType){return;}
record.type=newType;if(record.type==this.TYPE.OFFLINE){this.debug("removing permanently");this._removeRecord(record,true);return;}else{this.debug("did not remove permanently");}
record.status=this._typeToStatus(newType);var newScore=this._typeToScore(newType);this.debug("calling update record score");this._updateRecordScore(record,newScore);},_updateRecordScore:function(record,score){var oldInd=this._getIndexByRecord(record);record.score=score;var newInd=this._findIndexForNewRecord(record);this.debug("old ind:"+oldInd+", new ind:"+newInd);if(oldInd!=newInd){this._removeRecord(record);this._insertRecord(record,newInd);}else{this._updateRecordDiv(record);}},_findIndexForNewRecord:function(newRecord){var ind=-1;this.records.each(function(record,index){if(record.score<=newRecord.score){ind=index;throw $break;}});return ind;},_insertRecord:function(record,index){if(index>this._LIMIT||(this.records.length>this._LIMIT&&index<0)){return;}
this.debug("inserting record "+record.match.uid+", index:"+index);if(index>-1){this.records.splice(index,0,record);SD.Event.fire(null,SD.DatingQueue.Events.VIEW_LIST_INSERT,{record:record,index:index});}else{this.records.push(record);SD.Event.fire(null,SD.DatingQueue.Events.VIEW_LIST_INSERT,{record:record,index:this.records.length-1});}
this._updateRecordDiv(record);this._updateNextRecord();if(record.type!=this.TYPE.DATED&&record.type!=this.TYPE.OFFLINE){this._incrementNumberOfPotentialDates();}},_removeRecord:function(record,animate){this.debug("remove");this.debug(record);this.debug("remove:"+record.score+', animate: '+animate);if(animate&&record.div){record.div.morph("opacity:0.1",{duration:1.2,afterFinish:function(){this._removeRecord(record);}.bind(this)});return;}else{var index=this._getIndexByRecord(record);if(index>-1){this.records.splice(index,1);SD.Event.fire(null,SD.DatingQueue.Events.VIEW_LIST_REMOVE,{index:index});}}
if(record.type!=this.TYPE.DATED){this._decrementNumberOfPotentialDates();}},_removeAllRecords:function(){this.records=[];SD.Event.fire(null,SD.DatingQueue.Events.VIEW_LIST_REMOVE_ALL,{});this._scrollToIndex(0,true);this._resetNumberOfPotentialDates();},_onMatchRemoved:function(e){this.debug("MATCH REMOVED");this.debug(e);},_createRecordLi:function(record){if($(this._recordLiId(record))){return $(this._recordLiId(record));}
return LI({id:this._recordLiId(record)},this._createRecordDiv(record));},_createCurrentDateDiv:function(match){return DIV({'class':'match_div current-date-table'},DIV({'class':'q-image-container'},IMG({'class':'q-image',src:match.square_image_url}).observe('click',function(e){SD.ProfileViewer.UI.popup(match)})),DIV({'class':'q-info'},DIV({'class':'q-name'},B(null,match.username),", "+match.age),DIV({'class':'q-location'},match.city_name+"/"+match.country_name),A({'class':'q-link'},"View Profile").observe('click',function(e){SD.ProfileViewer.UI.popup(match)})),DIV({'id':'q_date_result','class':'q-status'},SD.DatingApp.isDating?'dating':'date ended'),BR({'clear':'both'}));},_createRecordDiv:function(record,idPrefix){if(!idPrefix){idPrefix="";}
var match=record.match;if(!match){return null;}
if(!match.fetched){SD.User.fetch(match,this._updateMatchDiv.bind(this));return DIV({id:this._matchDivId(match),'class':'match_div q-loading'},"loading match... ");}
var chatLink=DIV({'class':' '+'q-chat-enabled'});var disableLink=A({'class':'q-disable q-link'},record.enabled?"X":'');disableLink.observe('click',function(){SD.Model.getMyself().addUnwantedDate(match);this._removeRecord(this._getRecordByMatch(match),true);}.bind(this));disableLink.observe('mouseover',function(){SD.Tooltip.hide();SD.Tooltip.show('Remove from list');});disableLink.observe('mouseout',SD.Tooltip.hide);SD.FlirtWink.View.registerInputChat(chatLink,function(){return match;},null,SD.Constants.trackingCodes.chat_from_dating_queue);var div=DIV({id:this._matchDivId(match),'class':'match_div '+this._statusToClassName(record.status)+(this._nextRecord==record?' q-next ':'')},DIV({'class':'q-image-container'},IMG({'class':'q-image',src:match.square_image_url}).observe('click',function(e){SD.ProfileViewer.UI.popup(match)})),DIV({'class':'q-info'},DIV({'class':'q-name'},B(null,match.username),", "+match.age),DIV({'class':'q-location'},match.city_name+"/"+match.country_name),A({'class':'q-link'},"View Profile").observe('click',function(e){SD.ProfileViewer.UI.popup(match)})),DIV({'id':'q-status-'+match.uid,'class':'q-status'},this._currentDateMatch==match?DIV(null,'Right',BR(),'Now!'):this._recordStatusToReadbleText(record)),DIV({'class':'q-links'},chatLink),disableLink,BR({'clear':'both'}));if(this._nextRecord&&this._nextRecord==record){div.addClassName('q-next');}
this.debug(div);return div;},_createRecord:function(match,score,type,enabled,status){this.debug("create record"+match.uid+", "+score+", type:"+type+", status:"+status);return{match:match,div:null,score:score,type:type?type:this._statusToType(status),status:status?status:this._typeToStatus(type),enabled:(enabled===undefined||enabled===null)?!SD.Model.getMyself().isUnwantedDate(match):enabled};},_updateMatchDiv:function(match){this.debug("updating match div");if(!match){return;}
var record=this._getRecordByUid(match.uid);if(!record){return;}
this.debug(record);record.match=match;this._updateRecordDiv(record);},_updateRecordDiv:function(record){if(!record){return;}
record.needRedraw=true;this.debug("div'll be updated soon");this._updateRecordDivDeferred.bind(this).defer(record);},_updateRecordDivDeferred:function(record){if(!record.needRedraw){this.debug("not updating div because it is already updated w/ latest data");return;}
if(!this._viewEnabled){return;}
record.needRedraw=false;this.debug("updating record div deferred, "+record.match.uid);$(this._recordLiId(record)).innerHTML="";record.div=this._createRecordDiv(record);$(this._recordLiId(record)).insert(record.div);},_matchDivId:function(match){return"dq_"+match.uid;},_recordLiId:function(record){return"dq_rec_"+record.match.uid;},Events:{UPDATE_CURRENT_DATE_DIV:"dq:update_current_date_div",VIEW_LIST_INSERT:"dq:view_list_insert",VIEW_LIST_SCROLL_TO:"dq:view_list_scroll_to",VIEW_LIST_REMOVE:"dq:view_list_remove",VIEW_LIST_REMOVE_ALL:"dq:view_list_remove_all"},_initViewListeners:function(){SD.Event.observe(null,SD.DatingQueue.Events.UPDATE_CURRENT_DATE_DIV,function(e){if(!this._currentDateDiv){return;}
if(e.memo.match){$('q_header').innerHTML="Current SpeedDate";SD.User.fetch(e.memo.match,function(){this._currentDateDiv.innerHTML="";this._currentDateDiv.insert(this._createCurrentDateDiv(e.memo.match));}.bind(this));}else{$('q_header').innerHTML="Finding your next SpeedDate...";this._currentDateDiv.innerHTML="";this._currentDateDiv.insert(DIV({'class':'q-header'},DIV(null,'Use the controls at the top of the page to adjust your SpeedDate settings.'),DIV({'class':'q-upgrade-link'},SD.Model.getMyself().is_premium?'':DIV(null,SPAN(null,"Premium Members get connected faster. "),A({'class':'q-link'},"Upgrade Now!").observe('click',function(e){SD.UIController.upgradeMyself({tc:SD.Constants.trackingCodes.top_of_dating_queue});})))));}}.bind(this));SD.Event.observe(null,SD.DatingQueue.Events.VIEW_LIST_INSERT,function(e){if(!this._viewList){return;}
if(isNaN(e.memo.index)){this._viewList.insert(this._createRecordLi(e.memo.record),this._viewList.elements.length-1);}else{this._viewList.insert(this._createRecordLi(e.memo.record),e.memo.index);}}.bind(this));SD.Event.observe(null,SD.DatingQueue.Events.VIEW_LIST_SCROLL_TO,function(e){if(!this._viewList){return;}
var ind=e.memo.index>this.records.length?this.records.length:e.memo.index;this.debug("scroll to index "+ind);this._viewList.scrollTo(ind);}.bind(this));SD.Event.observe(null,SD.DatingQueue.Events.VIEW_LIST_REMOVE,function(e){if(!this._viewList){return;}
this._viewList.remove(e.memo.index);if(this._viewList.currentIndex()>this.records.length){this._viewList.scrollTo(this.records.length);}}.bind(this));SD.Event.observe(null,SD.DatingQueue.Events.VIEW_LIST_REMOVE_ALL,function(e){if(!this._viewList){return;}
while(this._viewList.elements.length>1){this._viewList.pop();}}.bind(this));SD.Event.observe(null,SD.User.Events.WAITING_TIME_CHANGED,function(e){if(!this._viewEnabled){return;}
$('q_upcoming_speeddates_number').innerHTML=e.memo.count;}.bind(this));}};Stack.prototype.top=function(){};
SD.Track={_record:function(label){SD.Track._recordObject(label);if(_gat){var url='/'+label+'/'+SD.Config.platform.name+'/';var pageTracker=_gat._getTracker("UA-2045170-13");pageTracker._initData();pageTracker._trackPageview(url);}},_recordObject:function(label,event){var img=new Image();img.src='http://tracking.speeddate.com/static/site/images/empty.gif?__label='+label+'&__browser='+Prototype.Browser.getName()+'&__platform='+SD.Config.platform.name+(event?'&'+Object.toQueryString(event.memo):'');},initialize:function(){SD.Event.observe(null,SD.DatingApp.Events.START_DATE,SD.Track._record.bind(this,'date'));SD.Event.observe(null,SD.DatingController.Events.SESSION_TERMINATED,SD.Track._recordObject.bind(this,'endDateReasons'));},recordRejectedDate:function(reason){SD.Track._record("rejectedDate/"+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:[],_updateBuddyRequestsCountOutputs:[],_updateProfileThumbOutputs:[],_parseInt:function(s){s=s.replace(/[^0-9]/i,'');if(s==''){return 0;};return parseInt(s);},init:function(){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.NEW_FAVORITE,function(e){SD.ClientUpdater.routeToAlertManager("NEW_FAVORITE",e.memo.uid);SD.Indicators.Store.log({type:'newFavoritesReceived',uid:e.memo.uid});}.bind(this));SD.Event.observe(null,SD.ClientUpdater.Events.NEW_WINK,function(e){SD.ClientUpdater.routeToAlertManager("NEW_WINK",e.memo.uid);SD.Indicators.Store.log({type:'newWinksReceived',uid:e.memo.uid});}.bind(this));SD.Event.observe(null,SD.ClientUpdater.Events.NEW_FLIRT,function(e){SD.ClientUpdater.routeToAlertManager("NEW_FLIRT",e.memo.uid);SD.Indicators.Store.log({type:'newFlirtsReceived',uid:e.memo.uid});}.bind(this));SD.Event.observe(null,SD.ClientUpdater.Events.NEW_SPEEDDATE,function(e){SD.ClientUpdater.routeToAlertManager("NEW_SPEEDDATE",e.memo.uid);SD.Indicators.Store.log({type:'newSpeedDateRequestsReceived',uid:e.memo.uid});}.bind(this));SD.Event.observe(null,SD.ClientUpdater.Events.NEW_VIEW,function(e){SD.ClientUpdater.routeToAlertManager("NEW_VIEW",e.memo.uid);SD.Indicators.Store.log({type:'newViewsReceived',uid:e.memo.uid});}.bind(this));SD.Event.observe(null,SD.ClientUpdater.Events.NEW_BUDDY_REQUEST,function(e){SD.ClientUpdater.routeToAlertManager("NEW_BUDDY_REQUEST",e.memo.uid);SD.Indicators.Store.log({type:'newBuddyRequestsReceived',uid:e.memo.uid});}.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);});},routeToAlertManager:function(type,uid){var alertManager=SD.UI.Alerts.Widget.getInstance();SD.User.fetch(SD.User.get(uid),function(user){if(!user){return;}
alertManager&&alertManager.store.add({type:type,uid:user.uid});});},updateProfileThumbOutputs:function(sURL){this._updateProfileThumbOutputs.each(function(oElement){if(oElement){oElement.src=sURL;}});},updateProfileProgressStatus:function(oStatus){SD.Event.fire(null,SD.ProfileProgress.Events.PROFILE_PROGRESS_UPDATE,oStatus);},registerOutputProfileThumb:function(oElement){oElement=$(oElement);this._updateProfileThumbOutputs.push(oElement);},updateProfileThumb:function(sURL){SD.Event.fire(null,SD.ClientUpdater.Events.UPDATE_PROFILE_THUMB,{'url':sURL});}};SD.ClientUpdater.Events={UPDATE_UNREAD_MESSAGE_COUNT:'clientupdater:update_unread_message_count',UPDATE_BUDDY_REQUESTS_COUNT:'clientupdater:update_buddy_requests_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_VIEW:'clientupdater:new_view',NEW_BUDDY_REQUEST:'clientupdater:new_buddy_request',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'};SD.ClientUpdater.init();
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.DatingApp.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,_campaing:null,_channel_type:null,_subtype:null,STATUS:{WAITING:0,CONNECTING:1,CONNECTED:2,CANNNOT_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.Chat.UI.Events.CHAT_MSG_RECEIVED,this.onChatMessageReceived.bind(this));SD.Event.observe(null,SD.Chat.UI.Events.CHAT_MSG_SENT,this.onChatMessageSent.bind(this));if(hide_welcome_banner){SD.Event.fireDeferred(null,SD.UIController.Events.CLOSE_WELCOME_POPUP);}
SD.Event.observe(null,SD.DatingApp.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;}
SD.XMPP.getPresenceStatus([user.chat_id],this.onOpenfirePresenceResponse.bind(this),this.onOpenfirePresenceCallFailure.bind(this));if(this.shouldOpenChatWindow(user)){SD.PremiumChat.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');switch(status){case this.STATUS.CONNECTING:if(this.shouldOpenChatWindow(user)){msg="Connecting to "+user.username;}
this.trackLanding(entry);break;case this.STATUS.CONNECTED:SD.Chat.UI.hideMsgForUser(user.uid);this.trackStartChat(entry);break;case this.STATUS.CANNOT_CONNECT:if(this._channel_type=='channel_email'){SD.Notification.IM.showFormOnEmailLanding2344(user);}
msg=" Whoops! "+user.username+" signed offline, but we'll try to connect you next time! <br/>Send "
+himHer+" a wink or flirt. <br/>";if(this.shouldOpenChatWindow(user)){msg+="<a href='javascript:SD.Chat.UI.hideMsgForUser("+user.uid+" ); SD.Chat.UI.removeUser("+user.uid+");'>Click to continue</a>";}
break;}
if(msg){if(this.shouldOpenChatWindow(user)){SD.Chat.UI.showMsgForUser(msg,user.uid);}else{SD.UIController.messageBox("Notification",msg);}}},shouldOpenChatWindow:function(user){return SD.Model.getMyself().is_premium||user.is_premium;},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.CANNNOT_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(event){var other=e.memo.otherUser;var entry=this._users.get(other.uid);if(entry){this.trackStartDate(entry);}},onChatMessageReceived:function(event){var sender=event.memo.sender;var entry=this._users.get(sender.uid);if(entry&&!entry.gotReply){entry.gotReply=true;this.trackChatReply(entry);}},onChatMessageSent:function(event){var receiver=event.memo.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.NotificationBothPartiesOnlineOutput.record(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.NotificationUserLandedOutput.record(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;}
SD.ExperimentManager.NotificationSentMsgOutput.record(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.NotificationGotReplyOutput.record(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.NotificationStartDateOutput.record(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(MooExt,{initialize:function(handle,win){this.handle=$(handle);this.win=win;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.fireEvent("dragStart",ev);if(!this.isDragging){this.isDragging=true;Event.observe(document,'mousemove',this.boundOnDrag);Event.observe(document,'mouseup',this.boundOnStopDrag);}},onStopDrag:function(ev){Event.stopObserving(document,'mousemove',this.boundOnDrag);Event.stopObserving(document,'mouseup',this.boundOnStopDrag);this.isDragging=false;this.fireEvent("dragStop",ev);},onDrag:function(ev){this.hasDragged=true;this.fireEvent("drag",ev);Event.stop(ev);}});SD.Window=Class.create(MooExt,{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,shim:Prototype.Browser.IE6,blocker:false,shimClassName:"sd-window-shim",blockerClassName:"sd-window-blocker",domParent:null,position:"fixed",groupId:"defaultGroup",classNameDragged:null,classNameFocused:null,className:"sd-window",top:null,left:null,minWidth:100,minHeight:100,width:200,contentWidth:null,height:null,contentHeight:null,populateMethod:"html",title:"",content:"",footer:"",data:{},range:null,closeMethod:"remove",parseLibrary:null,hideMethod:"visibility_hide",onPopulate:null,onShow:null,onHide:null,onBeforeHide:null,onBeforeOpen:null,onBeforeClose:null,onAfterOpen:null,onAfterClose:null,onMove:null,onMoveStart:null,onMoveStop: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='';}
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.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.isDomCreated=(this.type==SD.Window.STATIC)?true:false;this.isDraggable=this.options.draggable;this.isResizable=this.options.resizable;this.isClosable=this.options.closable;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.addEvent('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);return this;},setupTemplating:function(){if(this.type==SD.Window.DYNAMIC){this.template=this.options.template;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.type==SD.Window.DYNAMIC){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(this.options.shim||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);}},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);this.resizeManager.addEvent("drag",this.onResize.bind(this));this.resizeManager.addEvent("dragStart",this.onResizeStart.bind(this));this.resizeManager.addEvent("dragStop",this.onResizeStop.bind(this));},_attachMoveBehavior:function(dragHandle){this.moveManager=new SD.Draggable(dragHandle,this);this.moveManager.addEvent("drag",this.onMove.bind(this));this.moveManager.addEvent("dragStart",this.onMoveStart.bind(this));this.moveManager.addEvent("dragStop",this.onMoveStop.bind(this));},_attachCloseBehavior:function(closeHandle){closeHandle.observe('click',function(e){this.close();}.bindAsEventListener(this))},_attachHideBehavior:function(hideHandle){hideHandle.observe('click',function(e){this.hide();}.bindAsEventListener(this))},onResizeStart:function(ev){this.resizeManager.dragOffsetX=Event.pointerX(ev)-this.width;this.resizeManager.dragOffsetY=Event.pointerY(ev)-this.height;this._adjustContentHeight();this.isFixedHeight=true;this.fireEvent('dragResizeStart');},onResize:function(ev){this.resizeTo(Event.pointerX(ev)-this.resizeManager.dragOffsetX,Event.pointerY(ev)-this.resizeManager.dragOffsetY);this.fireEvent('dragResize');},onResizeStop:function(){this.fireEvent('dragResizeStop');},onMoveStart:function(ev){this.updateRange();this.moveManager.dragOffsetX=Event.pointerX(ev)-this.left;this.moveManager.dragOffsetY=Event.pointerY(ev)-this.top;if(this.options.classNameDragged){this.dom.addClassName(this.options.classNameDragged);}
this.fireEvent('moveStart');},onMove:function(ev){this.moveTo(Event.pointerX(ev)-this.moveManager.dragOffsetX,Event.pointerY(ev)-this.moveManager.dragOffsetY);this.fireEvent('move');},onMoveStop:function(){if(this.options.classNameDragged){this.dom.removeClassName(this.options.classNameDragged);}
this.fireEvent('moveStop');},setZIndex:function(zIndex){this.dom.style.zIndex=zIndex;if(this.shim){this.shim.style.zIndex=zIndex;}},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.inlineTemplates){this._buildInlineTemplates();};if(this.populateMethod=='html'){this.populateHtml(data);}
else if(this.populateMethod=='htmlPlain'){this.populateHtmlPlain(data);}
else{this.populateText(data);}
this.fireEvent('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;}},populateHtmlPlain:function(data){var pNode,tmpNode,dfNode,nextEl;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;}},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;}},onPopulate:function(dom){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(typeof html=='string'){dom.innerHTML=html;}else{dom.innerHTML="";for(var i=1;i<arguments.length;++i){dom.appendChild(arguments[i]);}}
this.fireEvent('populate',dom);},updateTitle:function(html){this.update(this.domTitle,html);},updateContent:function(html){this.update(this.domContent,html);},updateFooter:function(html){this.update(this.domFooter,html);},open:function(forceOpen){try{this.fireEvent("beforeOpen");}catch(e){if(!forceOpen&&e===this.Events.STOP_DEFAULT_ACTION){return;}}
SD.WindowManager.add(this);this.show();this.isOpened=true;this.fireEvent("afterOpen");return this;},close:function(forceClose){try{this.fireEvent("beforeClose",forceClose);}catch(e){if(!forceClose&&e===this.Events.STOP_DEFAULT_ACTION){return;}}
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.fireEvent("afterClose");}catch(e){}
return this;},show:function(){this.placeDomOnScreen();this.showDom();this.isVisible=true;SD.WindowManager.focusWindow(this);this.fireEvent("show");return this;},hide:function(forceHide){try{this.fireEvent("beforeHide",forceHide);}catch(e){if(!forceHide&&e===this.Events.STOP_DEFAULT_ACTION){return;}}
if(this.hideMethod==SD.Window.OFFSCREEN_HIDE){this.savePosition();this.placeDomOffScreen();}else{this.hideDom();}
this.isVisible=false;this.fireEvent("hide");return this;},savePosition:function(){this.lastPosition={top:this.top,left:this.left}},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);}},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";}},hideDom:function(){this.dom.style.visibility='hidden';this.shim&&(this.shim.style.visibility='hidden');},showDom:function(){this.dom.style.visibility='';this.shim&&(this.shim.style.visibility='');},removeDom:function(){this.dom.remove();this.shim&&this.shim.remove();},focus:function(){SD.WindowManager.focusWindow(this);},blur:function(){SD.WindowManager.blurWindow(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;},moveTo:function(x,y){if(x!==null&&x!==undefined&&!isNaN(x)){if(this._range){if(this._range.x1>x){x=this._range.x1;}
else if(this._range.x2<x+this.width){x=this._range.x2-this.width;}}
this.dom.style.left=x+'px';this.shim&&(this.shim.style.left=x+'px');this.left=x;}
if(y!==null&&y!==undefined&&!isNaN(y)){if(this._range){if(this._range.y1>y){y=this._range.y1;}
else if(this._range.y2<y+this.height){y=(this._range.y2-this.height);}}
this.dom.style.top=y+'px';this.shim&&(this.shim.style.top=y+'px');this.top=y;}
return this;},moveBy:function(dx,dy){if(dx!==null&&dx!==undefined){var x=this.left+dx;this.moveTo(x,null);}
if(dy!==null&&dy!==undefined){var y=this.top+dy;this.moveTo(null,y);}
return this;},resizeTo:function(w,h){if(w!==null&&w!==undefined&&!isNaN(w)&&this.type!=SD.Window.STATIC){if(this._range){if(this._range.x2<this.left+w){w=this._range.x2-this.left;}}
if(this.minWidth>w){w=this.minWidth;}
this.dom.setWidth(w);}
if(h!==null&&h!==undefined&&!isNaN(h)&&this.isFixedHeight&&this.type!=SD.Window.STATIC){if(this._range){if(this._range.y2<this.top+h){h=this._range.y2-this.top;}}
if(this.minHeight>h){h=this.minHeight;}
this.dom.setHeight(h);this._adjustContentHeight();}
this.width=this.dom.offsetWidth;this.height=this.dom.offsetHeight;this.shim&&this.shim.setHeight(this.height);this.shim&&this.shim.setWidth(this.width);return this;},resizeBy:function(dw,dh){if(dw!==null&&dw!==undefined){var w=this.width+dw;this.resizeTo(w,null);}
if(dh!==null&&dh!==undefined){var h=this.height+dh;this.resizeTo(null,h);}
return this;},center:function(leftOffset,topOffset){var vDim=document.viewport.getDimensions();var vScrollOffsets=document.viewport.getScrollOffsets();if(this.position=="fixed"){this.moveTo((leftOffset===undefined||leftOffset===null)?(vDim.width-this.width)/2:leftOffset,(topOffset===undefined||topOffset===null)?(vDim.height-this.height)/2:topOffset);}
else if(this.position=="absolute"){this.moveTo((leftOffset===undefined||leftOffset===null)?(vScrollOffsets.left+(vDim.width-this.width)/2):leftOffset,(topOffset===undefined||topOffset===null)?vScrollOffsets.top+(vDim.height-this.height)/2:topOffset);}},_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;}
else{this.resizeTo(this.dom.offsetWidth,this.dom.offsetHeight);}
this.moveTo(this.left,this.top);},_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);},Events:{STOP_DEFAULT_ACTION:{name:"SD.Window.Events.STOP_DEFAULT_ACTION",message:"Prevents the default action."}},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();},setCloseCallback:function(callback){this.addEvent('afterClose',callback);},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.legacyTemplate='<div class="dialog popup-box lib-window">'+'<table cellspacing="0" cellpadding="0" class="top table_window">'+'<tbody>'+'<tr>'+'<td class="dialog_nw top_draggable lib-draggable"></td>'+'<td class="dialog_n lib-draggable">'+'<div class="dialog_title title_window top_draggable lib-title">#{title}</div>'+'</td>'+'<td class="dialog_ne top_draggable lib-draggable"></td>'+'</tr>'+'</tbody>'+'</table>'+'<table cellspacing="0" cellpadding="0" class="mid table_window">'+'<tbody>'+'<tr>'+'<td class="dialog_w"></td>'+'<td valign="top" class="dialog_content">'+'<div class="p-content lib-content">#{content}</div>'+'</td>'+'<td class="dialog_e"></td>'+'</tr>'+'</tbody>'+'</table>'+'<table cellspacing="0" cellpadding="0" class="bot table_window lib-footer">'+'<tbody>'+'<tr>'+'<td class="dialog_sw bottom_draggable"></td>'+'<td class="dialog_s bottom_draggable">'+'<div class="status_bar dialog_status">'+'<span style="float: left; width: 1px; height: 1px;" />'+'</div>'+'</td>'+'<td class="dialog_se bottom_draggable lib-resize-handle-br"></td>'+'</tr>'+'</tbody>'+'</table>'+'<div class="popup-close dialog-close-button lib-close-handle">&#215;</div>'+'</div>';SD.Window.infoMessageTemplate='<div class="message lib-window"><div class="lib-content"></div></div>';
SD.Window.Focusable={setZIndex:function(){},getZIndex:function(){},isFocusable:function(){return false},blurAction:function(){},focusAction:function(){}}
SD.WindowManager={isInitialized:false,zRanges:{defaultGroup:{min:1000,max:2000,order:1},group1:{min:2001,max:3000,order:2},date:{min:3001,max:4000,order:3},group2:{min:4001,max:5000,order:4},dateOpener:{min:5001,max:6000,order:5},group3:{min:6001,max:7000,order:6},notification:{min:7001,max:8000,order:7},group4:{min:9001,max:10000,order:8}},init:function(){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));},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();var items=this.getItems();for(var i in items){items[i].updateRange&&items[i].updateRange();if(items[i].isVisible){try{items[i].moveTo(parseInt(items[i].left*(viewportDim.width-items[i].width)/(this.viewportDim.width-items[i].width)),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();var viewportOffsets=document.viewport.getScrollOffsets();var dx=viewportOffsets.left-this.viewportOffsets.left;var dy=viewportOffsets.top-this.viewportOffsets.top;for(var i in items){items[i].updateRange&&items[i].updateRange();if(items[i].isVisible){if(items[i].position=='absolute'){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];},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.addEvent){win.addEvent('hide',SD.WindowManager.onWindowHide.bind(SD.WindowManager,win));}
this.managers[win.groupId].add(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);},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;},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.style.position=Prototype.Browser.IE6?"absolute":"fixed";this.updateBlockerSize();},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 blockerHeight=Math.max(document.documentElement.scrollHeight,window.innerHeight||0);var blockerWidth=Math.max(document.documentElement.scrollWidth,window.innerWidth||0);this.blocker.show();this.blocker.style.width=blockerWidth+"px";this.blocker.style.height=blockerHeight+"px";}}}
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;}
win.dom&&win.dom.observe('mousedown',function(){SD.WindowManager.focusWindow(win);});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){var z1=win1.getZIndex();var z2=win2.getZIndex();if(z1>z2){return 1;}
else if(z1<z2){return-1;}
return 0;});}});
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.Dialogs.Utils=Class.create({initialize:function(options){this.options=options;this.dialog=this.options.dialog;this.domContent=$(this.options.domContent);this.onParseElements=this.onParseElements(this);this.onBeforeFormSubmit=this.options.onBeforeFormSubmit;this.onLoad=this.options.onLoad;this.onContentRendered=this.options.onContentRendered;this.onParseElements=SD.Utils.Object.exclusiveMerge(this.options.onParseElements||{},this.onParseElements);this.onParseCommands=SD.Utils.Object.exclusiveMerge(this.options.onParseCommands||{},this.onParseCommands);this.onJson=this.options.onJson;this.onParseJson=SD.Utils.Object.merge(this.onParseJson||{},this.options.onParseJson);this.currentAjaxRequest=null;this.jsonInstructions=null;},onJson:function(jsonData){},onLoad:function(htmlData){},onParseElements:function(_this){return{'form':function(form,domRoot){(new SD.CountryForm(form));form.onsubmit=function(){if(!form.hasClassName("upload-profile-pic")&&!form.hasClassName("upload-profile-pic-popup")){_this.submitForm(form);}
return false;};if(form.hasClassName("upload-profile-pic")){$(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("upload-profile-pic-popup")){$(form).action+='&displayType=ajax';$(form).select('input').each(function(el){if(el.type=='file'){(new SD.AutoUploader(el,_this._loadHandlerFromIframe.bind(_this,domRoot)));}});}},'select':function(selectEl,domRoot){if(selectEl.multiple){(new SD.Dropdown(selectEl));}},'input.autocomplete':function(el,domRoot){(new SD.AutoComplete(el));},'div.result-message':function(el,domRoot){(new SD.ResultMessage(el));},'a.nav-site':function(link,domRoot){if(link.processed){return;}
link.processed=true;link.observe('click',function(e){e.stop();SD.Nav.navigateTo(link.href);}.bind(this));},'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;}}.bind(this));},'a':function(link,domRoot){if(link.processed){return;}
link.processed=true;link.observe('click',function(e){e.stop();this.load(link.href);}.bind(this))}}},onParseCommands:{'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-nav-site':function(cmdEl,domRoot){SD.Nav.navigateTo(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.commands&&this.parseJson(this.jsonData.commands))===true){return true;}},'div.sd-command.sd-close-dialog':function(cmdEl,domRoot){this.dialog.close&&this.dialog.close();}},onParseJson:{status:{_OK:function(value){this.dialog.close&&this.dialog.close();},_FAIL:function(value){}},message:function(msg){}},parser:function(domRoot){domRoot=$(domRoot);if(this.parseElements(domRoot)===true){return true;}
if(this.parseCommands(domRoot)===true){return true;}},parseJson:function(jsonInstructions){var jsonCommandData=jsonInstructions.commands;var jsonCommands=this.onParseJson;if(!jsonInstructions){return;}
return SD.Utils.JSON.mapCommands(jsonCommands,jsonInstructions,this);},parseElements:function(domRoot){var returnValue=false;for(var i in this.onParseElements){domRoot.select(i).each(function(el){try{if(this.onParseElements[i].call(this,el,domRoot)===true){returnValue=true;throw $break;};}
catch(e){console.log("error: "+e);}},this);}
return returnValue;},parseCommands:function(domRoot){var returnValue=false;for(var i in this.onParseCommands){try{domRoot.select(i).each(function(el){if(this.onParseCommands[i].call(this,el,domRoot)===true){returnValue=true;throw $break;};},this);}
catch(e){console.log("error:"+e);}}
return returnValue;},submitForm:function(domForm,targetElement){if(this.onBeforeFormSubmit&&this.onBeforeFormSubmit(domForm)===true){return true;}
this.currentAjaxRequest=$(domForm).request({parameters:{displayType:'ajax'},onComplete:this._loadHandler.bind(this,targetElement||this.domContent)});},load:function(url,targetElement){if(!url)return;this.currentAjaxRequest=new Ajax.Request(url,{parameters:{displayType:'ajax'},method:'get',onSuccess:this._loadHandler.bind(this,targetElement||this.domContent)});},_loadHandlerFromIframe:function(targetElement,result){this._loadHandler(targetElement,{responseText:result,responseXML:null});},_loadHandler:function(targetElement,transport){var responseHtml=transport.responseText;if(this.onLoad){var rv=this.onLoad(responseHtml);if(rv===true){return true;}
else if(typeof rv=='string'){responseHtml=rv;}}
targetElement.update(responseHtml);if(this.dialog.domContent&&targetElement==this.dialog.domContent){this.dialog._adjustDimensions.bind(this.dialog).delay(0.2);this.dialog.domContent.scrollTop=0;}
if(this.onContentRendered&&this.onContentRendered(targetElement)===true){return true;};this.parser(targetElement);}});
SD.Indicators={initialize:function(){var E_2184=SD.ExperimentManager.CountOfWantsToDateInNavTab2184.value;var E_2366=SD.ExperimentManager.SimplifySidebar2366.value;Object.extend(SD.Indicators.Views.permissions,{'ind-main-menu-item-my-results':(E_2184==1||E_2366==1||E_2366==2),'ind-menu-item-want-to-date-you':(E_2184==1||E_2366==1||E_2366==2)});SD.Indicators.Store.initialize();SD.Indicators.Views.initialize();}}
SD.Indicators.Views={initialize:function(){var store=SD.Indicators.Store;this.updateSideMenu();var _updateMessages=function(){var countInboxMessages=store.counts.get('newInboxMessages')||0;this.updateMessages(countInboxMessages);}.bind(this);var _updateMembers=function(){var countViews=store.counts.get('newViewsReceived')||0;var countFavorites=store.counts.get('newFavoritesReceived')||0;this.updateMembers(countViews+countFavorites);}.bind(this);SD.Event.observe(null,store.Events.NEW_FLIRT,function(e){this.updateInbox(e.memo.count);_updateMessages();}.bind(this));SD.Event.observe(null,store.Events.INBOX_MESSAGES_COUNT_UPDATED,function(e){this.updateInbox(e.memo.count);_updateMessages();}.bind(this));SD.Event.observe(null,store.Events.BUDDY_REQUEST_COUNT_UPDATED,function(e){this.updateBuddyRequests(e.memo.count);_updateMessages();}.bind(this));SD.Event.observe(null,store.Events.FAVORITE_COUNT_UPDATED,function(e){this.updateFavoritedMe(e.memo.count);_updateMembers();}.bind(this));SD.Event.observe(null,store.Events.SPEEDDATE_COUNT_UPDATED,function(e){this.updateWantsToSpeeddateYou(e.memo.count);}.bind(this));SD.Event.observe(null,store.Events.VIEW_COUNT_UPDATED,function(e){this.updateViewedYou(e.memo.count);_updateMembers();}.bind(this));SD.Event.observe(null,SD.Nav.Events.CONTENT_LOADED,function(e){this.updateSubMenus();}.bind(this));},updateSideMenu:function(){var counts=SD.Indicators.Store.counts;this._updateSideMenuItem($('ind-sidemenu-wants-to-speeddate-you'),counts.get('totalDates'));this._updateSideMenuItem($('ind-sidemenu-viewed-you'),counts.get('totalViews'));this._updateSideMenuItem($('ind-sidemenu-favorited-you'),counts.get('totalFavorites'));this.permissions['ind-sidemenu-wants-to-speeddate-you']=false;this.permissions['ind-sidemenu-viewed-you']=false;this.permissions['ind-sidemenu-favorited-you']=false;},updateSubMenus:function(){var counts=SD.Indicators.Store.counts;this._updateSubMenuItem($('ind-submenu-item-want_to_date_you'),counts.get('newSpeedDateRequestsReceived')||0);this._updateSubMenuItem($('ind-submenu-item-favorited_you'),counts.get('newFavoritesReceived')||0);this._updateSubMenuItem($('ind-submenu-item-inbox'),counts.get('newInboxMessages')||0);this._updateSubMenuItem($('ind-submenu-item-buddy_requests'),counts.get('newBuddyRequestsReceived')||0);this._updateSubMenuItem($('ind-submenu-item-viewed_you'),counts.get('newViewsReceived')||0);},updateMessages:function(count){this._updateMainMenuItem($('ind-main-menu-item-messages'),count);},updateMembers:function(count){this._updateMainMenuItem($('ind-main-menu-item-members'),count);},updateInbox:function(count){this._updateMenuItem($('ind-menu-item-messages-inbox'),count);this._updateSubMenuItem($('ind-submenu-item-inbox'),count);},updateBuddyRequests:function(count){this._updateMenuItem($('ind-menu-item-buddy-requests'),count);this._updateSubMenuItem($('ind-submenu-item-buddy_requests'),count);},updateViewedYou:function(count){this._updateMenuItem($('ind-menu-item-viewed-you'),count);this._updateSubMenuItem($('ind-submenu-item-viewed_you'),count);this._updateSideMenuItem($('ind-sidemenu-viewed-you'),count);},updateFavoritedMe:function(count){this._updateMenuItem($('ind-menu-item-favorited-you'),count);this._updateSubMenuItem($('ind-submenu-item-favorited_you'),count);this._updateSideMenuItem($('ind-sidemenu-favorited-you'),count);},updateWantsToSpeeddateYou:function(count){this._updateMainMenuItem($('ind-main-menu-item-my-results'),count);this._updateMenuItem($('ind-menu-item-want-to-date-you'),count);this._updateSubMenuItem($('ind-submenu-item-want_to_date_you'),count);this._updateSideMenuItem($('ind-sidemenu-wants-to-speeddate-you'),count);},_updateMainMenuItem:function(el,count){if(!el){return;}
if(!this.permissions[el.id]){return;}
if(count){el.setStyle('opacity:0');el.show();el.update(count);Effect.Appear(el);}
else{el.hide();}},_updateMenuItem:function(el,count){this._updateGenericParenthesizedItem(el,count);},_updateSubMenuItem:function(el,count){this._updateGenericParenthesizedItem(el,count);},_updateSideMenuItem:function(el,count){this._updateGenericParenthesizedItem(el,count);},_updateGenericParenthesizedItem:function(el,count){if(!el){return;}
if(!this.permissions[el.id]){return;}
count?el.show().update(" ("+count+") "):el.hide();},permissions:{'ind-main-menu-item-my-results':true,'ind-main-menu-item-messages':true,'ind-main-menu-item-members':true,'ind-menu-item-messages-inbox':true,'ind-menu-item-buddy-requests':true,'ind-menu-item-viewed-you':true,'ind-menu-item-favorited-you':true,'ind-menu-item-want-to-date-you':true,'ind-submenu-item-want_to_date_you':true,'ind-submenu-item-favorited_you':true,'ind-submenu-item-inbox':true,'ind-submenu-item-buddy_requests':true,'ind-submenu-item-viewed_you':true,'ind-sidemenu-wants-to-speeddate-you':true,'ind-sidemenu-viewed-you':true,'ind-sidemenu-favorited-you':true}}
SD.Indicators.Store={counts:$H(),logs:{},initialize:function(){this._setupEventMap();this._intialCountSetup();},_setupEventMap:function(){var e=SD.Indicators.Store.Events;this.eventMap={'newInboxMessages':[null,e.INBOX_MESSAGES_COUNT_UPDATED],'newBuddyRequestsReceived':[e.NEW_BUDDY_REQUEST,e.BUDDY_REQUEST_COUNT_UPDATED],'newFlirtsReceived':[e.NEW_FLIRT,e.FLIRT_COUNT_UPDATED],'newViewsReceived':[e.NEW_VIEW,e.VIEW_COUNT_UPDATED],'newFavoritesReceived':[e.NEW_FAVORITE,e.FAVORITE_COUNT_UPDATED],'newSpeedDateRequestsReceived':[e.NEW_SPEEDDATE,e.SPEEDDATE_COUNT_UPDATED],'newWinksReceived':[e.NEW_WINK,e.WINK_COUNT_UPDATED]}},_intialCountSetup:function(){this.updateCounts(SD.Model.getNotificationsCount()||{});},updateCounts:function(counts){var isCountChanged=false;for(var key in counts){var countKey=this.counts.get(key);if(this.eventMap[key]&&countKey!=counts[key]){SD.Event.fireDeferred(null,this.eventMap[key][1],{count:counts[key]});isCountChanged=true;}}
if(isCountChanged){this.counts.update(counts);SD.Event.fire(null,SD.Indicators.Store.Events.COUNT_UPDATED,{});}},log:function(data){if(!this.logs[data.type]){this.logs[data.type]=[];}
this.logs[data.type].push({time:Date.now(),type:data.type,uid:data.uid});var newCountEntry={};newCountEntry[data.type]=parseInt(this.counts.get(data.type)||0)+1;this.updateCounts(newCountEntry);if(data.type=='newFlirtsReceived'||data.type=='newWinksReceived'){this.updateCounts({'newInboxMessages':(this.counts.get('newInboxMessages')||0)+1});}
if(this.eventMap[data.type]&&this.eventMap[data.type][0]){SD.Event.fireDeferred(null,this.eventMap[data.type][0],Object.extend(data,{count:this.counts.get(data.type)}));}},getLog:function(logId){return this.logs[logId];},getLogs:function(){return this.logs;},Events:{FAVORITE_COUNT_UPDATED:'IndicatorsStore:FAVORITE_COUNT_UPDATED',INBOX_MESSAGES_COUNT_UPDATED:'IndicatorsStore:INBOX_MESSAGES_COUNT_UPDATED',WINK_COUNT_UPDATED:'IndicatorsStore:WINK_COUNT_UPDATED',FLIRT_COUNT_UPDATED:'IndicatorsStore:FLIRT_COUNT_UPDATED',SPEEDDATE_COUNT_UPDATED:'IndicatorsStore:SPEEDDATE_COUNT_UPDATED',VIEW_COUNT_UPDATED:'IndicatorsStore:VIEW_COUNT_UPDATED',BUDDY_REQUEST_COUNT_UPDATED:'IndicatorsStore:BUDDY_REQUEST_COUNT_UPDATED',COUNT_UPDATED:'IndicatorsStore:countUpdated',NEW_FAVORITE:'IndicatorsStore:newFavorite',NEW_WINK:'IndicatorsStore:newWink',NEW_FLIRT:'IndicatorsStore:newFlirt',NEW_SPEEDDATE:'IndicatorsStore:newSpeeddate',NEW_VIEW:'IndicatorsStore:newView',NEW_BUDDY_REQUEST:'IndicatorsStore:newBuddyRequest'}}
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,debug:function(txt){},init:function(){this.shouldAsk=SD.Model.shouldAskIM;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.FlirtWink.Events.DATE_WANTED,this.onDateSent.bind(this));SD.Event.observe(null,SD.FlirtWink.Events.FAVORITED,this.onFavorited.bind(this));},sendChatRequest:function(other){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){SD.PremiumChat.lazyChatWithUser(other);}else{SD.UIController.messageBox("Notification","Could not send chat request.");}}.bind(this),onFailure:function(e){SD.UIController.messageBox("Notification","Could not send chat request.");}.bind(this)});},onWinkSent:function(e){this.showFormWithDelay(e.memo.otherUser);},onFlirtSent:function(e){this.showFormWithDelay(e.memo.otherUser);},onDateSent:function(e){this.debug("on date sent");this.debug(e.memo.user);this.showFormWithDelay(e.memo.user,e.memo.user.username+" has been added to the list of members you want to SpeedDate.");},onFavorited:function(e){this.showFormWithDelay(e.memo.user);},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);},showFormOnEmailLanding2344:function(juliet){if(this.shouldAsk){SD.ExperimentManager.PromoteIMOnEmailNotificationLanding2344.getValueForMe(function(result){this.debug("result 2344: "+result);if(result==1){var js="SD.Notification.IM.showForm(SD.User.get("+juliet.uid+"));";this.debug(js);setTimeout(js,this.formShowDelay);}}.bind(this));}else{onFailure();}},showFormWithDelay:function(juliet,title){this.debug("juliet");this.debug(juliet);SD.User.updateUser(juliet);if(this.shouldAsk){var js="SD.Notification.IM.showForm(SD.User.get("+juliet.uid+")"+(title?', "'+title+'"':'')+");";this.debug(js);setTimeout(js,this.formShowDelay);}},showForm:function(juliet,title){if(!this.shouldAsk||this.formWindow){return;}
this.shouldAsk=false;SD.User.fetch(juliet,function(juliet){this.recordAskedIm();this.formWindow=SD.UIController.submitIMPopup(this.formId,title,juliet,this.errorDivId,this.onFormSubmit.bind(this),this.onFormLater.bind(this),this.onFormDontAsk.bind(this),SD.Model.getMyself().ims.length);this.autoFillForm();}.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.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){}});}};
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;}
SD.UI=SD.UI||{};SD.UI.Alerts={};SD.UI.Alerts.Templates={frame:'<div class="alerts-container lib-alerts-widget">\n'+'<div class="subheader lib-alerts-header">\n'+'<table width="148" cellpadding="0" cellspacing="0" border="0">\n'+'<tr>\n'+'<td class="alert-total-indicator"><span class="lib-total-alert-count">#{totalAlerts}</span> <span class="alert-total-label">New Alerts</span></td>\n'+'<td class="alert-pagination-wrapper"><div class="alert-pagination-left alert-pagination lib-alert-left-spinner"></div></td>\n'+'<td class="alert-current-indicator lib-current-alert">#{currentAlert}</td>\n'+'<td class="alert-pagination-wrapper"><div class="alert-pagination-right alert-pagination lib-alert-right-spinner"></div></td>\n'+'</tr>\n'+'</table>\n'+'</div>\n'+'<div class="alert-content lib-alerts-content">#{body}</div>\n'+'</div>\n',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',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">Chat</a>',readFlirt:'<a href="javascript:void(0)" class="action-link lib-alert-read-flirt alert-action-read-flirt">Read Now</a>',viewWink:'<a href="javascript:void(0)" class="action-link lib-alert-view-wink alert-action-view-wink">View Wink <b>;)</b></a>',viewRequest:'<a href="javascript:void(0)" class="action-link lib-alert-view-request alert-action-view-request">View Request</a>'},config:{PENDING_MATCH:{tplBuilder:'tplBuilder1',icon:"alert-pending-match",text:"Waiting for Vote",action:""},NO_MATCH_FOUND:{tplBuilder:'tplBuilder2',icon:"alert-no-match",text:"NO MATCH",action:"chat"},MATCH_FOUND:{tplBuilder:'tplBuilder2',icon:"alert-match",text:"MATCH",action:"chat"},NEW_FAVORITE:{tplBuilder:'tplBuilder2',icon:"alert-favorited-you",text:"Favorited you!",action:"chat"},NEW_WINK:{tplBuilder:'tplBuilder2',icon:"alert-flirt-wink",text:"New Wink!",action:"viewWink"},NEW_FLIRT:{tplBuilder:'tplBuilder2',icon:"alert-flirt-wink",text:"New Flirt!",action:"readFlirt"},NEW_SPEEDDATE:{tplBuilder:'tplBuilder2',icon:"alert-speeddate",text:"SpeedDate Request!",action:"chat"},NEW_VIEW:{tplBuilder:'tplBuilder2',icon:"alert-view",text:"Viewed you!",action:"chat"},NEW_BUDDY_REQUEST:{tplBuilder:'tplBuilder2',icon:"alert-buddy-request",text:"Buddy Request!",action:"viewRequest"},I_WANTED_TO_DATE_IS_ONLINE:{tplBuilder:'tplBuilder3',icon:"alert-online",text1:"Online Now!",text2:"You want to SpeedDate:",action:"chat"},WANTED_TO_DATE_ME_IS_ONLINE:{tplBuilder:'tplBuilder3',icon:"alert-online",text1:"Online Now!",text2:"Wants to SpeedDate you:",action:"chat"},I_FLIRTED_IS_ONLINE:{tplBuilder:'tplBuilder3',icon:"alert-online",text1:"Online Now!",text2:"You Flirted with:",action:"chat"},FLIRTED_ME_IS_ONLINE:{tplBuilder:'tplBuilder3',icon:"alert-online",text1:"Online Now!",text2:"Flirted with you:",action:"chat"},I_WINKED_AT_IS_ONLINE:{tplBuilder:'tplBuilder3',icon:"alert-online",text1:"Online Now!",text2:"You Winked at:",action:"chat"},WINKED_AT_ME_IS_ONLINE:{tplBuilder:'tplBuilder3',icon:"alert-online",text1:"Online Now!",text2:"Winked at you:",action:"chat"},I_FAVORITED_IS_ONLINE:{tplBuilder:'tplBuilder3',icon:"alert-online",text1:"Online Now!",text2:"You Favorited:",action:"chat"},FAVORITED_ME_IS_ONLINE:{tplBuilder:'tplBuilder3',icon:"alert-online",text1:"Online Now!",text2:"Favorited you:",action:"chat"},COMPATIBLE_MATCH_IS_ONLINE:{tplBuilder:'tplBuilder3',icon:"alert-online",text1:"Online Now!",text2:"Compatible Match",action:"chat"}},tplBuilder1:function(type){var templates=SD.UI.Alerts.Templates;return templates.body.substitute({'alertType':templates.alertType1.substitute({'icon':templates.config[type]['icon'],'type':templates.config[type]['text']})});},tplBuilder2:function(type){var templates=SD.UI.Alerts.Templates;return templates.body.substitute({'alertType':templates.alertType1.substitute({'icon':templates.config[type]['icon'],'type':templates.config[type]['text']}),'action':templates.actions[templates.config[type].action]});},tplBuilder3:function(type){var templates=SD.UI.Alerts.Templates;return 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]});}}
SD.UI.Alerts.Store=Class.create({initialize:function(){this.cursor=0;this.data=[];this.isCursorBlocked=false;},add:function(record,index){var len=this.data.length;index=index||len;if(index>=len){this.data.push(record);index=this.data.length-1;}else{this.data.splice(index,1,this.data[index],record);}
this.onAdd(index);SD.Event.fire(this,SD.UI.Alerts.Store.Events.ITEM_ADDED,{record:record,index:index});},remove:function(index){if(this.data.length==0)return;if(typeof index=='object'){for(var i=0;i<this.data.length;++i){if(index==this.data[i]){index=i;break;}}}
if(index>this.data.length-1){index=this.data.length-1};this.data.splice(index,1);this.onRemove(index);},get:function(index){return this.data[index];},getAll:function(){return this.data;},getLength:function(){return this.data.length;},find: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({record:data[i],index:i});}}
return result;},onAdd:function(index){if(this.data[index].type=="NO_MATCH_FOUND"||this.data[index].type=="MATCH_FOUND"){var targetUID=this.data[index].uid;var pendingMatches=this.find('type','PENDING_MATCH');for(var i=0;i<pendingMatches.length;++i){if(targetUID==pendingMatches[i].record.uid){this.remove(pendingMatches[i].record);}}}},onRemove:function(index){if(this.getLength()==0){this.cursor=0;}else if(this.cursor>index){this.cursor=this.cursor-1;}else if(this.cursor==index&&index!=0){this.moveCursor(index-1);}else if(index==0){this.cursor=0;SD.Event.fire(this,SD.UI.Alerts.Store.Events.CURSOR_MOVED,{dir:(this.cursor-this.oldCursor>0)?'forward':'back'});}},moveCursor:function(pos){if(this.isCursorBlocked){return;}
if(this.data.length==0||pos<0){pos=0;}
else if(pos>=this.data.length){pos=this.data.length-1;}
this.oldCursor=this.cursor;this.cursor=pos;if(this.oldCursor!==this.cursor){SD.Event.fire(this,SD.UI.Alerts.Store.Events.CURSOR_MOVED,{dir:(this.cursor-this.oldCursor>0)?'forward':'back'});}},moveCursorBy:function(pos){this.moveCursor(this.cursor+pos);},moveCursorToEnd:function(){this.moveCursor(this.data.length-1);},moveCursorToStart:function(){this.moveCursor(0);},getCursor:function(){return this.cursor;},isCursorAtEnd:function(){return(this.data.length==0||this.cursor==this.data.length-1);}});SD.UI.Alerts.Store.Events={ITEM_ADDED:"SD.UI.Alerts.Store.Events:ITEM_ADDED",CURSOR_MOVED:"SD.UI.Alerts.Store.Events:CURSOR_MOVED"}
SD.UI.Alerts.Widget=Class.create({initialize:function(domRef,options){options=options||{};this.users={};this.domRef=$(domRef);this.dom=null;this.animationMode=options.animationMode||'slide';this.insertionMode=options.insertionMode||'inside';this.isBlocked=false;this.isUserBlocked=false;this.curUser={};this.isVisible=false;this.NAME_MAX_LENGTH=11;this.LOCATION_MAX_LENGTH=14;this.templates=SD.UI.Alerts.Templates;this.store=new SD.UI.Alerts.Store();this.setup();},setup:function(){SD.Event.observe(null,SD.User.Events.DATE_RESULT_FETCHED,function(event){if(!event.memo.otherUser||(event.memo.otherUser&&event.memo.otherUser.uid===undefined)){return;}
SD.User.fetch(SD.User.get(event.memo.otherUser.uid),function(user){if(!user){return};this.store.add({type:(event.memo.success?'MATCH_FOUND':'NO_MATCH_FOUND'),uid:user.uid});}.bind(this));}.bind(this));SD.Event.observe(null,SD.DatingApp.Events.DATE_OVER,function(event){if(!event.memo.otherUser||(event.memo.otherUser&&event.memo.otherUser.uid===undefined)){return;}
SD.User.fetch(SD.User.get(event.memo.otherUser.uid),function(user){if(!user){return};var reasonCode=event.memo.reasonCode;if(reasonCode!=SD.ReasonCodes.TIME_FINISHED&&reasonCode!=SD.ReasonCodes.USER_LEFT&&reasonCode!=SD.ReasonCodes.USER_DISCONNECTED){return;}
this.store.add({type:'PENDING_MATCH',uid:user.uid});}.bind(this));}.bind(this));SD.Event.observe(this.store,SD.UI.Alerts.Store.Events.ITEM_ADDED,this.onAlert.bind(this));SD.Event.observe(this.store,SD.UI.Alerts.Store.Events.CURSOR_MOVED,this.onCursorMoved.bind(this));},onAlert:function(event){if(!this.isVisible){this.show();}
this.updateTotalCount(this.store.getLength());if(this.isBlocked||this.isUserBlocked){this.setPendingOperation(this.store.moveCursorToEnd.bind(this.store));}else if(this.store.getLength()==1){this.showAlert();}else{this.store.moveCursorToEnd();}},onCursorMoved:function(event){if(this.isBlocked){this.setPendingOperation(this.showAlert.bind(this,event.memo.dir));}else{this.showAlert(event.memo.dir);}
var cursor=this.store.getCursor();if(this.store.getLength()<2){return;}
if(cursor>0){this.domLeftPager.style.visibility="visible";}else{this.domLeftPager.style.visibility="hidden";}
if(cursor<this.store.getLength()-1){this.domRightPager.style.visibility="visible";}else{this.domRightPager.style.visibility="hidden";}},show:function(){this.isVisible=true;if(!this.dom){this.renderWidgetDomBase();}},buildTemplate:function(type){return this.templates[this.templates.config[type]['tplBuilder']](type);},renderWidgetDomBase:function(){this.widgetTemplate=SD.UI.Alerts.Templates.frame;var domHtml=this.widgetTemplate.interpolate({totalAlerts:0,currentAlert:0});if(this.insertionMode=='inside'){this.domRef.innerHTML=domHtml;}else if(this.insertionMode=='after'){this.domRef.insert({after:domHtml});}else if(this.insertionMode=='before'){this.domRef.insert({before:domHtml});}
this.parser(document.body);},renderAndShow:function(data,dir){this.blockApp();var tpl=this.buildTemplate(data.type);var onUserFetch;if(this.animationMode=='replace'||this.store.getLength()==1){onUserFetch=this.simpleReplacementFactory(tpl,dir);}
else if(this.animationMode=='slide'){onUserFetch=this.slideReplacementFactory(tpl,dir);}
else if(this.animationMode=='stack'){onUserFetch=this.stackReplacementFactory(tpl,dir);}
SD.User.fetch(SD.User.get(data.uid),onUserFetch);},simpleReplacementFactory:function(tpl,dir){return(function(user){if(!user){alert("No such user.");return;}
this.curUser=user;this.domBodyHolder.innerHTML=this.populate(tpl,user);this.domBodyHolder.select(".alert-wrapper")[0].style.visibility="visible";this.parser(this.domBodyHolder);if(user.username.length>this.NAME_MAX_LENGTH&&this.domNameAgeField){this.domNameAgeField.setAttribute('title',user.username);}
this.unBlockApp();}).bind(this);},slideReplacementFactory:function(tpl,dir){return(function(user){if(!user){alert("No such user.");return;}
this.curUser=user;var newAlertElement,oldAlertElement,effect,effectOptions,effectOffset;oldAlertElement=this.domBodyHolder.select(".alert-wrapper")[0];var content=this.populate(tpl,user);if(dir=="forward"){oldAlertElement.insert({after:content});newAlertElement=this.domBodyHolder.select(".alert-wrapper")[1];newAlertElement.style.left=this.domBodyHolder.offsetWidth+"px";effectOffset=parseInt(oldAlertElement.getStyle('left'))-this.domBodyHolder.offsetWidth;}else{oldAlertElement.insert({before:content});newAlertElement=this.domBodyHolder.select(".alert-wrapper")[0];newAlertElement.style.left=(-this.domBodyHolder.offsetWidth)+"px";effectOffset=parseInt(oldAlertElement.getStyle('left'))+this.domBodyHolder.offsetWidth;}
effectOptions={sync:true,x:effectOffset,y:0,mode:'relative'};newAlertElement.style.visibility="visible";this.parser(this.domBodyHolder);var globalEffectOptions={duration:0.5,afterFinish:function(){try{oldAlertElement.parentNode.removeChild(oldAlertElement);oldAlertElement=null;delete oldAlertElement;}catch(e){}
this.unBlockApp();}.bind(this)};new Effect.Parallel([new Effect.Move(newAlertElement,effectOptions),new Effect.Move(oldAlertElement,effectOptions)],globalEffectOptions);}).bind(this);},stackReplacementFactory:function(tpl,dir){return(function(user){if(!user){alert("No such user.");return;}
this.curUser=user;var newAlertElement,oldAlertElement,effect,movementOffset;oldAlertElement=this.domBodyHolder.select(".alert-wrapper")[0];if(dir=="forward"){oldAlertElement.insert({after:this.populate(tpl,user)});newAlertElement=this.domBodyHolder.select(".alert-wrapper")[1];newAlertElement.style.left=this.domBodyHolder.offsetWidth+"px";movementOffset=parseInt(oldAlertElement.getStyle('left'))-this.domBodyHolder.getWidth();}else{oldAlertElement.insert({before:this.populate(tpl,user)});newAlertElement=this.domBodyHolder.select(".alert-wrapper")[0];newAlertElement.style.left=oldAlertElement.getStyle('left');movementOffset=this.domBodyHolder.getWidth()-parseInt(oldAlertElement.getStyle('left'));}
newAlertElement.style.visibility="visible";this.parser(this.domBodyHolder);var effectOptions={x:movementOffset,y:0,mode:'relative',duration:0.5,afterFinish:function(){try{oldAlertElement.parentNode.removeChild(oldAlertElement);oldAlertElement=null;delete oldAlertElement;}catch(e){}
this.unBlockApp();}.bind(this)};new Effect.Move(dir=="forward"?newAlertElement:oldAlertElement,effectOptions);}).bind(this);},blockApp:function(){this.isBlocked=true;},unBlockApp:function(){this.isBlocked=false;this.execPendingOperation();},userBlockApp:function(){this.isUserBlocked=true;},userUnblockApp:function(){this.isUserBlocked=false;this.execPendingOperation();},setPendingOperation:function(fn){this.pendingOperation=fn;},execPendingOperation:function(){if(this.isBlocked||this.isUserBlocked){return;}
this.pendingOperation&&this.pendingOperation();this.pendingOperation=null;},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){return tpl.interpolate({name:this.nameFilter(user.username),city:this.locationFilter(user.city_name),thumb:user.images[0].thumbnail_url,age:user.age});},showAlert:function(dir){dir=dir||'forward';var index=this.store.getCursor();var alertRecord=this.store.get(index);this.renderAndShow(alertRecord,dir);this.updateCurrentAlert(index+1);},showNextAlert:function(){if(this.isBlocked){return;}
this.store.moveCursorBy(1);},showPrevAlert:function(){if(this.isBlocked){return;}
this.store.moveCursorBy(-1);},viewProfile:function(){var uid=this.store.get(this.store.getCursor()).uid;SD.ProfileViewer.UI.popupUID(uid);},startChat:function(){var uid=this.store.get(this.store.getCursor()).uid;SD.User.fetch(SD.User.get(data.uid),function(user){if(!user.online){this._userOfflinePopup(user);return;}
SD.FlirtWink.View.chat(user);});},_userOfflinePopup:function(user){var win=SD.UIController.standardPopup({draggable:true,title:user.username.truncate(20)+" is Offline",content:(''+'<div style="padding-top:10px">'+'<table cellspacing="4" cellpadding="3" style="margin:10px 20px">'+'<tr><td style="width:60px;text-align:center"><img src="#{thumb}" ></td>'+'<td>'+'<div >Sorry, <b>#{name}</b></div>'+'<div style="margin-top:5px;">Signed Offline.</div>'+'</td></tr></table>'+'</div>'+'<div style="margin-top:5px;text-align:center">'+'<input value="View Profile" class="input-button lib-view-profile-but" type="button">'+'<input value="Close" class="input-button lib-close-but" type="button">'+'</div>'+'</div>').interpolate({thumb:user.images[0].thumbnail_url,name:user.username.truncate(30)})});win.open();win.getContent().select('.lib-view-profile-but')[0].observe('click',function(){win.close();SD.ProfileViewer.UI.popupUID(user.uid);});win.getContent().select('.lib-close-but')[0].observe('click',function(){win.close();});return win;},readMessage:function(){var record=this.store.get(this.store.getCursor());var otherUserId=record.uid;if(SD.Model.getMyself().is_premium){SD.Nav.redirectTo(SD.NavUtils.link('messages','flirt',{id:otherUserId}));}else{SD.FlirtWink.UI.popupAlertContactWarning(otherUserId);}},viewWink:function(){this.readMessage();},viewRequest:function(){SD.NavUtils.setLocation(SD.NavUtils.link('messages','buddy_requests'));},updateTotalCount:function(n){this.domTotalCount.innerHTML=n;},updateCurrentAlert:function(n){this.domCurrent.innerHTML=n;},parser:function(domRoot,parseLibrary){parseLibrary=parseLibrary||this.parseLibrary;domRoot=$(domRoot);for(var className in parseLibrary){domRoot.select('.'+className).each(function(el){try{parseLibrary[className].call(this,el,domRoot);}
catch(e){console.log("error while parsing selector "+className);}
el.removeClassName(className);},this);}},parseLibrary:{'lib-alerts-widget':function(el,domRoot){if(!this.dom){this.dom=el}
this.dom.observe('mouseover',this.userBlockApp.bind(this));this.dom.observe('mouseout',function(e){try{if(!e.relatedTarget.descendantOf(this.dom)&&e.relatedTarget!=this.dom){this.userUnblockApp();}}catch(e){this.userUnblockApp();}}.bindAsEventListener(this));},'lib-alert-holder':function(el,domRoot){if(!this.domAlertHolder){this.domAlertHolder=el}},'lib-total-alert-count':function(el,domRoot){if(!this.domTotalCount){this.domTotalCount=el}},'lib-current-alert':function(el,domRoot){if(!this.domCurrent){this.domCurrent=el}},'lib-alert-left-spinner':function(el,domRoot){if(!this.domLeftPager){this.domLeftPager=el}
el.observe('click',this.showPrevAlert.bind(this));},'lib-alert-right-spinner':function(el,domRoot){if(!this.domRightPager){this.domRightPager=el}
el.observe('click',this.showNextAlert.bind(this));},'lib-alert-view-profile':function(el,domRoot){el.observe('click',this.viewProfile.bind(this));el.observe('mouseover',function(){this.curUser.username&&SD.Tooltip.show("View <b>"+this.curUser.username+"'s</b> profile");}.bind(this));el.observe('mouseout',SD.Tooltip.hide.bind(SD.Tooltip));},'lib-alert-chat':function(el,domRoot){SD.FlirtWink.View.registerInputChat(el,function(){return this.curUser;}.bind(this));},'lib-alert-read-flirt':function(el,domRoot){el.observe('click',this.readMessage.bind(this));},'lib-alert-view-wink':function(el,domRoot){el.observe('click',this.viewWink.bind(this));},'lib-alert-view-request':function(el,domRoot){el.observe('click',this.viewRequest.bind(this));},'lib-alerts-header':function(el,domRoot){el.onselectstart=function(){return false;}},'lib-alerts-content':function(el,domRoot){if(!this.domBodyHolder){this.domBodyHolder=el}}}});SD.UI.Alerts.Widget.create=function(domRef,options){if(this.instance)return;this.instance=new SD.UI.Alerts.Widget(domRef,options);}
SD.UI.Alerts.Widget.getInstance=function(){return this.instance;}
if(typeof Prototype=='undefined'||!Prototype.Version.match("1.6"))
throw("Prototype-UI library require Prototype library >= 1.6.0");if(Prototype.Browser.WebKit){Prototype.Browser.WebKitVersion=parseFloat(navigator.userAgent.match(/AppleWebKit\/([\d\.\+]*)/)[1]);Prototype.Browser.Safari2=(Prototype.Browser.WebKitVersion<420);}
if(Prototype.Browser.IE){Prototype.Browser.IEVersion=parseFloat(navigator.appVersion.split(';')[1].strip().split(' ')[1]);Prototype.Browser.IE6=Prototype.Browser.IEVersion==6;Prototype.Browser.IE7=Prototype.Browser.IEVersion==7;}
Prototype.falseFunction=function(){return false};Prototype.trueFunction=function(){return true};var UI={Abstract:{},Ajax:{}};Object.extend(Class.Methods,{extend:Object.extend.methodize(),addMethods:Class.Methods.addMethods.wrap(function(proceed,source){if(!source)return this;if(!source.hasOwnProperty('methodsAdded'))
return proceed(source);var callback=source.methodsAdded;delete source.methodsAdded;proceed(source);callback.call(source,this);source.methodsAdded=callback;return this;}),addMethod:function(name,lambda){var methods={};methods[name]=lambda;return this.addMethods(methods);},method:function(name){return this.prototype[name].valueOf();},classMethod:function(){$A(arguments).flatten().each(function(method){this[method]=(function(){return this[method].apply(this,arguments);}).bind(this.prototype);},this);return this;},undefMethod:function(name){this.prototype[name]=undefined;return this;},removeMethod:function(name){delete this.prototype[name];return this;},aliasMethod:function(newName,name){this.prototype[newName]=this.prototype[name];return this;},aliasMethodChain:function(target,feature){feature=feature.camelcase();this.aliasMethod(target+"Without"+feature,target);this.aliasMethod(target,target+"With"+feature);return this;}});Object.extend(Number.prototype,{snap:function(round){return parseInt(round==1?this:(this/round).floor()*round);}});Object.extend(String.prototype,{camelcase:function(){var string=this.dasherize().camelize();return string.charAt(0).toUpperCase()+string.slice(1);},makeElement:function(){var wrapper=new Element('div');wrapper.innerHTML=this;return wrapper.down();}});Object.extend(Array.prototype,{empty:function(){return!this.length;},extractOptions:function(){return this.last().constructor===Object?this.pop():{};},removeAt:function(index){var object=this[index];this.splice(index,1);return object;},remove:function(object){var index;while((index=this.indexOf(object))!=-1)
this.removeAt(index);return object;},insert:function(index){var args=$A(arguments);args.shift();this.splice.apply(this,[index,0].concat(args));return this;}});Element.addMethods({getScrollDimensions:function(element){return{width:element.scrollWidth,height:element.scrollHeight}},getScrollOffset:function(element){return Element._returnOffset(element.scrollLeft,element.scrollTop);},setScrollOffset:function(element,offset){element=$(element);if(arguments.length==3)
offset={left:offset,top:arguments[2]};element.scrollLeft=offset.left;element.scrollTop=offset.top;return element;},getNumStyle:function(element,style){var value=parseFloat($(element).getStyle(style));return isNaN(value)?null:value;},appendText:function(element,text){element=$(element);text=String.interpret(text);element.appendChild(document.createTextNode(text));return element;}});document.whenReady=function(callback){if(document.loaded)
callback.call(document);else
document.observe('dom:loaded',callback);};Object.extend(document.viewport,{getScrollOffset:document.viewport.getScrollOffsets,setScrollOffset:function(offset){Element.setScrollOffset(Prototype.Browser.WebKit?document.body:document.documentElement,offset);},getScrollDimensions:function(){return Element.getScrollDimensions(Prototype.Browser.WebKit?document.body:document.documentElement);}});(function(){UI.Options={methodsAdded:function(klass){klass.classMethod($w(' setOptions allOptions optionsGetter optionsSetter optionsAccessor '));},setOptions:function(options){if(!this.hasOwnProperty('options'))
this.options=this.allOptions();this.options=Object.extend(this.options,options||{});},allOptions:function(){var superclass=this.constructor.superclass,ancestor=superclass&&superclass.prototype;return(ancestor&&ancestor.allOptions)?Object.extend(ancestor.allOptions(),this.options):Object.clone(this.options);},optionsGetter:function(){addOptionsAccessors(this,arguments,false);},optionsSetter:function(){addOptionsAccessors(this,arguments,true);},optionsAccessor:function(){this.optionsGetter.apply(this,arguments);this.optionsSetter.apply(this,arguments);}};function addOptionsAccessors(receiver,names,areSetters){names=$A(names).flatten();if(names.empty())
names=Object.keys(receiver.allOptions());names.each(function(name){var accessorName=(areSetters?'set':'get')+name.camelcase();receiver[accessorName]=receiver[accessorName]||(areSetters?function(value){return this.options[name]=value}:function(){return this.options[name]});});}})();UI.Carousel=Class.create(UI.Options,{options:{direction:"horizontal",previousButton:".previous_button",nextButton:".next_button",container:".container",scrollInc:"auto",disabledButtonSuffix:'_disabled',overButtonSuffix:'_over'},initialize:function(element,options){this.setOptions(options);this.element=$(element);this.id=this.element.id;this.container=this.element.down(this.options.container).firstDescendant();this.elements=this.container.childElements();this.previousButton=this.options.previousButton==false?null:this.element.down(this.options.previousButton);this.nextButton=this.options.nextButton==false?null:this.element.down(this.options.nextButton);this.posAttribute=(this.options.direction=="horizontal"?"left":"top");this.dimAttribute=(this.options.direction=="horizontal"?"width":"height");this.elementSize=this.computeElementSize();this.nbVisible=this.currentSize()/this.elementSize;var scrollInc=this.options.scrollInc;if(scrollInc=="auto")
scrollInc=Math.floor(this.nbVisible);[this.previousButton,this.nextButton].each(function(button){if(!button)return;var className=(button==this.nextButton?"next_button":"previous_button")+this.options.overButtonSuffix;button.clickHandler=this.scroll.bind(this,(button==this.nextButton?-1:1)*scrollInc*this.elementSize);button.observe("click",button.clickHandler).observe("mouseover",function(){button.addClassName(className)}.bind(this)).observe("mouseout",function(){button.removeClassName(className)}.bind(this));},this);this.updateButtons();},destroy:function($super){[this.previousButton,this.nextButton].each(function(button){if(!button)return;button.stopObserving("click",button.clickHandler);},this);this.element.remove();this.fire('destroyed');},fire:function(eventName,memo){memo=memo||{};memo.carousel=this;return this.element.fire('carousel:'+eventName,memo);},observe:function(eventName,handler){this.element.observe('carousel:'+eventName,handler.bind(this));return this;},stopObserving:function(eventName,handler){this.element.stopObserving('carousel:'+eventName,handler);return this;},checkScroll:function(position,updatePosition){if(position>0)
position=0;else{var limit=this.elements.last().positionedOffset()[this.posAttribute]+this.elementSize;var carouselSize=this.currentSize();if(position+limit<carouselSize)
position+=carouselSize-(position+limit);position=Math.min(position,0);}
if(updatePosition)
this.container.style[this.posAttribute]=position+"px";return position;},scroll:function(deltaPixel){if(this.animating)
return this;var position=this.currentPosition()+deltaPixel;position=this.checkScroll(position,false);deltaPixel=position-this.currentPosition();if(deltaPixel!=0){this.animating=true;this.fire("scroll:started");var that=this;this.container.morph("opacity:0.5",{duration:0.2,afterFinish:function(){that.container.morph(that.posAttribute+": "+position+"px",{duration:0.4,delay:0.2,afterFinish:function(){that.container.morph("opacity:1",{duration:0.2,afterFinish:function(){that.animating=false;that.updateButtons().fire("scroll:ended",{shift:deltaPixel/that.currentSize()});}});}});}});}
return this;},scrollTo:function(index){if(this.animating||index<0||index>this.elements.length||index==this.currentIndex()||isNaN(parseInt(index)))
return this;return this.scroll((this.currentIndex()-index)*this.elementSize);},updateButtons:function(){this.updatePreviousButton();this.updateNextButton();return this;},updatePreviousButton:function(){if(!this.previousButton){return;}
var position=this.currentPosition();var previousClassName="previous_button"+this.options.disabledButtonSuffix;if(this.previousButton.hasClassName(previousClassName)&&position!=0){this.previousButton.removeClassName(previousClassName);this.fire('previousButton:enabled');}
if(!this.previousButton.hasClassName(previousClassName)&&position==0){this.previousButton.addClassName(previousClassName);this.fire('previousButton:disabled');}},updateNextButton:function(){if(!this.nextButton){return;}
var lastPosition=this.currentLastPosition();var size=this.currentSize();var nextClassName="next_button"+this.options.disabledButtonSuffix;if(this.nextButton.hasClassName(nextClassName)&&lastPosition!=size){this.nextButton.removeClassName(nextClassName);this.fire('nextButton:enabled');}
if(!this.nextButton.hasClassName(nextClassName)&&lastPosition==size){this.nextButton.addClassName(nextClassName);this.fire('nextButton:disabled');}},computeElementSize:function(){return this.elements.first().getDimensions()[this.dimAttribute];},currentIndex:function(){return-this.currentPosition()/this.elementSize;},currentLastPosition:function(){if(this.container.childElements().empty())
return 0;return this.currentPosition()+
this.elements.last().positionedOffset()[this.posAttribute]+
this.elementSize;},currentPosition:function(){return this.container.getNumStyle(this.posAttribute);},currentSize:function(){return this.container.parentNode.getDimensions()[this.dimAttribute];},updateSize:function(){this.nbVisible=this.currentSize()/this.elementSize;var scrollInc=this.options.scrollInc;if(scrollInc=="auto")
scrollInc=Math.floor(this.nbVisible);[this.previousButton,this.nextButton].each(function(button){if(!button)return;button.stopObserving("click",button.clickHandler);button.clickHandler=this.scroll.bind(this,(button==this.nextButton?-1:1)*scrollInc*this.elementSize);button.observe("click",button.clickHandler);},this);this.checkScroll(this.currentPosition(),true);this.updateButtons().fire('sizeUpdated');return this;}});UI.Ajax.Carousel=Class.create(UI.Carousel,{options:{elementSize:-1,url:null},initialize:function($super,element,options){if(!options.url)
throw("url option is required for UI.Ajax.Carousel");if(!options.elementSize)
throw("elementSize option is required for UI.Ajax.Carousel");$super(element,options);this.endIndex=0;this.hasMore=true;this.updateHandler=this.update.bind(this);this.updateAndScrollHandler=function(nbElements,transport,json){this.update(transport,json);this.scroll(nbElements);}.bind(this);this.runRequest.bind(this).defer({parameters:{from:0,to:Math.ceil(this.nbVisible)-1},onSuccess:this.updateHandler});},runRequest:function(options){this.requestRunning=true;new Ajax.Request(this.options.url,Object.extend({method:"GET"},options));this.fire("request:started");return this;},scroll:function($super,deltaPixel){if(this.animating||this.requestRunning)
return this;var nbElements=(-deltaPixel)/this.elementSize;if(this.hasMore&&nbElements>0&&this.currentIndex()+this.nbVisible+nbElements-1>this.endIndex){var from=this.endIndex+1;var to=Math.ceil(from+this.nbVisible-1);this.runRequest({parameters:{from:from,to:to},onSuccess:this.updateAndScrollHandler.curry(deltaPixel).bind(this)});return this;}
else
$super(deltaPixel);},update:function(transport,json){this.requestRunning=false;this.fire("request:ended");if(!json)
json=transport.responseJSON;this.hasMore=json.more;this.endIndex=Math.max(this.endIndex,json.to);this.elements=this.container.insert({bottom:json.html}).childElements();return this.updateButtons();},computeElementSize:function(){return this.options.elementSize;},updateSize:function($super){var nbVisible=this.nbVisible;$super();if(Math.floor(this.nbVisible)-Math.floor(nbVisible)>=1&&this.hasMore){if(this.currentIndex()+Math.floor(this.nbVisible)>=this.endIndex){var nbNew=Math.floor(this.currentIndex()+Math.floor(this.nbVisible)-this.endIndex);this.runRequest({parameters:{from:this.endIndex+1,to:this.endIndex+nbNew},onSuccess:this.updateHandler});}}
return this;},updateNextButton:function($super){var lastPosition=this.currentLastPosition();var size=this.currentSize();var nextClassName="next_button"+this.options.disabledButtonSuffix;if(this.nextButton.hasClassName(nextClassName)&&lastPosition!=size){this.nextButton.removeClassName(nextClassName);this.fire('nextButton:enabled');}
if(!this.nextButton.hasClassName(nextClassName)&&lastPosition==size&&!this.hasMore){this.nextButton.addClassName(nextClassName);this.fire('nextButton:disabled');}}});UI.Carousel.Mutable=Class.create(UI.Carousel,{options:{elementSize:-1},insert:function(htmlObj,index){if(index===undefined||index<0||!this.container.childElements()[index]){this.container.insert(htmlObj).childElements();}else{this.container.childElements()[index].insert({before:htmlObj});}
this.elements=this.container.childElements();},pop:function(){this.container.childElements()[0].remove();this.elements=this.container.childElements();},remove:function(index){this.container.childElements()[index].remove();this.elements=this.container.childElements();},next:function(){this.scrollTo(this.currentIndex()+1);},checkScroll:function(position,updatePosition){if(updatePosition)
this.container.style[this.posAttribute]=position+"px";return position;},computeElementSize:function(){return this.options.elementSize;},scroll:function(deltaPixel){if(this.animating)
return this;var position=this.currentPosition()+deltaPixel;position=this.checkScroll(position,false);deltaPixel=position-this.currentPosition();if(deltaPixel!=0){this.animating=true;this.fire("scroll:started");var that=this;this.container.morph(that.posAttribute+": "+position+"px",{duration:0.4,delay:0.2,afterFinish:function(){that.animating=false;that.updateButtons().fire("scroll:ended",{shift:deltaPixel/that.currentSize()});}});}
return this;}});
SD.UIController={_controller:"site",_versionObsoleteShown:false,displayOpenCloseProfileOptions:false,displayGift:true,displayReportImage:true,tabBlinkingEnabled:true,titleOptionsEnabled:true,hasFocus:true,appState:null,speeddateActive:true,welcomeDisplayed:true,platform_id:1,initialize:function(options){this.options=options;this.welcomeInstructionsConfiguration=options.welcomeInstructionsConfiguration;this.filterConfiguration=options.filterConfiguration;this.flirtWinkConfiguration=options.flirtWinkConfiguration;this.profileConfiguration=options.profileConfiguration;this.applicationConfiguration=options.applicationConfiguration;this.alertsConfiguration=options.alertsConfiguration;this.buddyListConfiguration=options.buddyListConfiguration;this.otherTabFiltersConfiguration=options.otherTabFiltersConfiguration;SD.WelcomeInstructions.UI.initialize();SD.UserFilters.UI.initialize(this.filterConfiguration.target,this.filterConfiguration.params);(new SD.Alerts.UI(this.alertsConfiguration.target,this.alertsConfiguration.params.user,this.alertsConfiguration.params.flirtNumber,this.alertsConfiguration.params.requestNumber));SD.OtherTabFilters.UI.initialize(this.otherTabFiltersConfiguration.target,this.otherTabFiltersConfiguration.params);$('sd-message')&&$('sd-message').hide();$('sd-other-tab-filter').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.DatingApp.Events.START_DATE,this.onStartDate.bind(this));SD.Event.observe(null,SD.DatingApp.Events.DATE_OVER,this.onDateOver.bind(this));SD.Event.observe(null,SD.User.Events.DATE_RESULT_FETCHED,this.onDateResultFetched.bind(this));SD.Event.observe(null,SD.Alerts.UI.Events.FLIRTS_SOUGHT,this.onFlirtsSought.bind(this));SD.Event.observe(null,SD.Alerts.UI.Events.BUDDY_REQUESTS_SOUGHT,this.onBuddyRequestsSought.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.popupUID(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.DELETE_BUDDY_REQUESTED,function(event){SD.User.fetch(event.memo.user,function(){if(confirm("Are you sure you want to delete "+event.memo.user.username+" as a buddy?")){var url=SD.NavUtils.link('ajax','deletebuddy',{other_memberid:event.memo.user.uid});new Ajax.Request(url,{method:'post',onSuccess:function(result){if(result){}}});SD.Event.fire(null,SD.BuddyList.Events.USER_DELETE_CONFIRMED,{user:event.memo.user});}});});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.DatingController.Events.VERSION_OBSOLETE,function(event){if(SD.UIController._versionObsoleteShown){return;}
SD.UIController._versionObsoleteShown=true;if(confirm("We just updated SpeedDate. Please click 'OK' below to continue dating. (Your page will refresh automatically)")){window.location.reload();}
setTimeout(function(){SD.UIController._versionObsoleteShown=false;},60000);});if(!SD.DisabledFeatures.addBuddiesButton){SD.Event.observe(null,SD.UIController.Events.ADD_BUDDIES_REQUESTED,this.onAddBuddiesRequested.bind(this));}
if(SD.DatingApp.app){SD.DatingApp.app.onfocus=function(){SD.UIController.hasFocus=true;SD.Favicon.setTitle("");};SD.DatingApp.app.onblur=function(){};}
if(SD.Chat.UI){SD.Chat.UI.onfocus=function(){SD.UIController.hasFocus=true;SD.Favicon.setTitle("");};}
window.onfocus=function(){};window.onblur=function(){SD.UIController.hasFocus=false;};SD.Favicon.defaultTitle="SpeedDate.com";SD.Favicon.defaultIcon="favicon.ico";SD.Favicon.setTitle("");},onPhotoUpload:function(event){SD.Nav.invalidate("profile");SD.Model.getMyself().has_photo=event.memo.hasPhoto;SD.ClientUpdater.updateProfileThumb(event.memo.photoUrl);$$(".popup-banner-block").invoke("hide");},onStartDating:function(event){this.welcomeDisplayed=false;},onStartDate:function(event){SD.DatingApp.popupForDate(event.memo.otherUser);if(this.tabBlinkingEnabled){if(!this.windowIsActive()){SD.Favicon.animateTitle(["Date found!","with "+event.memo.otherUser.username],1000);}}},onDateOver:function(event){SD.Favicon.setTitle(SD.Favicon.defaultTitle);},onDateResultFetched:function(e){if(!e.memo.otherUser||(e.memo.otherUser&&e.memo.otherUser.uid===undefined)){return;}
if(e.memo.success&&!SD.Model.getMyself().is_premium){this.popupDateMatchWarning(e.memo.otherUser,{"ti":e.memo.otherUser.uid,"tc":SD.Constants.trackingCodes.match_restriction});}},onFlirtsSought:function(event){SD.NavUtils.setLocation(SD.NavUtils.link('messages','inbox'));},onBuddyRequestsSought:function(event){SD.NavUtils.setLocation(SD.NavUtils.link('messages','buddy_requests'));},onAddBuddiesRequested:function(event){SD.NavUtils.setLocation(SD.NavUtils.link('invite','invite'));},recoverBuddyListHeight:function(){var sidebarHeading=$('sidebar-heading');var sidebarHeader=$('sidebar-header');var sidebarAlerts=$('sd-sidebar-alerts');var sidebarBuddyHeadline=$('sd-sidebar-buddy-headline');var otherTabFilter=$('sd-other-tab-filter');var buddyboxDiv=$('buddyboxDiv');var sidebarBuddyList=$('sd-sidebar-buddy-list');var viewedYou=$('sidebar-viewed-you');var newHeight=496;if(viewedYou){newHeight-=viewedYou.getHeight();}
if(sidebarHeading){newHeight-=sidebarHeading.getHeight();}
if(sidebarHeader){newHeight-=sidebarHeader.getHeight();}
if(sidebarAlerts&&sidebarAlerts.visible()){newHeight-=sidebarAlerts.getHeight()+6;}
if(sidebarBuddyHeadline){newHeight-=sidebarBuddyHeadline.getHeight();}
if(!SD.DisabledFeatures.addBuddiesButton){var sidebarAddBuddies=$('sd-sidebar-add-buddies');if(sidebarAddBuddies){newHeight-=sidebarAddBuddies.getHeight();}}
if(otherTabFilter.visible()&&!SD.DatingApp.isDating){newHeight-=otherTabFilter.getHeight();}
if(buddyboxDiv){buddyboxDiv.style.height=newHeight+'px';}
if(sidebarBuddyList){sidebarBuddyList.style.height=newHeight+'px';}},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){},updateAppViewState:function(state){this.appState=state;var appContainer=$('app-container');if(!appContainer){return;}
appContainer.removeClassName('app-hidden').removeClassName('app-normal').removeClassName('app-is-dating').removeClassName('app-tab-other').removeClassName('app-tab-other-is-dating');if(state==SD.UIController.DatingAppStates.HIDDEN){appContainer.addClassName('app-hidden');}else if(state==SD.UIController.DatingAppStates.NORMAL){appContainer.addClassName('app-normal');}else if(state==SD.UIController.DatingAppStates.DATING){appContainer.addClassName('app-is-dating');}else if(state==SD.UIController.DatingAppStates.TABOTHER){appContainer.addClassName('app-tab-other');}else if(state==SD.UIController.DatingAppStates.TABOTHERDATING){appContainer.addClassName('app-tab-other-is-dating');}else{SD.log("non app state found in updateAppViewState:"+state);}},needsToUpgrade:function(myself,user){if(myself.is_premium){return false;}else{return!user.relation.permissions.can_flirt;}},_openIframeSubscriptionPopup:function(url){SD.UserFilters.UI.saveStateAndPause();var win=this.standardPopup({top:30,groupId:'group4',title:"Order Form",content:'<iframe id="subscription-iframe" src="'+url+'" frameborder="0" width="100%" height="100%" '+'marginwidth="0" marginheight="0" hspace="0" vspace="0"></iframe>',width:685,height:570,draggable:false,onAfterClose:function(){SD.UserFilters.UI.restorePreviousStateAndResume();}});win.open();win.domContent.style.overflow='hidden';},upgradeMyself:function(params){if(SD.Model.getMyself().is_premium){SD.warn('Already a premium user.');return;}
if(params){params="&"+$H(params).toQueryString();}else{params="";}
var premUrl=SD.Model.getMyself().premium_signup_url+params;if(SD.ExperimentManager.OrderFormAfterNewSignup2007.value==1){this._openIframeSubscriptionPopup(premUrl+"&isIframe=1");}
else if(SD.Config.platform.platformId==3){var openPopup=window.open(premUrl,'_blank','height='+screen.availHeight+',width=980,scrollbars=1,resizable=1,location=1,toolbar=0,status=1');if(!openPopup){top.location.href=premUrl;}}
else{top.location.href=premUrl;}
return false;},upgradeMyselfWithUrl:function(premUrl){if(SD.Model.getMyself().is_premium){SD.warn('Already a premium user.');return;}
if(SD.ExperimentManager.OrderFormAfterNewSignup2007.value==1){this._openIframeSubscriptionPopup(premUrl+"&isIframe=1");return;}
if(SD.Config.platform.platformId==3){var openPopup=window.open(premUrl,'_blank','height='+screen.availHeight+',width=980,scrollbars=1,resizable=1,location=1,toolbar=0,status=1');if(!openPopup){top.location.href=premUrl;}}else{top.location.href=premUrl;}},upgradeMyselfFlash:function(uid){if(!SD.Model.getMyself().has_photo){SD.Dialogs.dialogUploadPhotoToContinue({groupId:"dateOpener"}).open();}else{SD.UIController.upgradeMyself({tc:SD.Constants.trackingCodes.other_member_ended_dating,ti:uid,tobj:SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.OTHER_MEMBER_ENDED_DATING)});}},goToFaq:function(){SD.Nav.redirectTo(SD.NavUtils.link('site','help'));},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);}}},windowIsActive:function(){return this.hasFocus;},infoMessage:function(message,duration){var time=(duration)?duration*1000:3000;var win=new SD.Window({className:"message",resizable:false,groupId:"notification",width:220,template:SD.Window.infoMessageTemplate,destroyOnClose:true,closable:false,minimizable:false,maximizable:false,draggable:false,showEffect:Effect.Appear,hideEffect:Effect.Fade,effectOptions:{duration:0.1}});$(win.getContent()).insert(DIV({"class":"sd-message",'style':'display:none'},message));if(SD.UIController.platform_id==3){win.showCenter(false,210,370);}else{win.showCenter(false,210);}
setTimeout(win.close.bind(win),time);},infoMessagePositioned:function(message,duration,relPosition,options){options=options||{};var baseParams={groupId:"notification",template:SD.Window.infoMessageTemplate,className:"message",resizable:false,width:200,destroyOnClose:true,closable:false,minimizable:false,maximizable:false,draggable:false,showEffect:Effect.Appear,hideEffect:Effect.Fade,effectOptions:{duration:0.1}}
var win=new SD.Window(Object.extend(baseParams,options));$(win.getContent()).insert(DIV({"class":"sd-message",'style':'display:none'},message));win.showCenter(false);if(duration){setTimeout(win.close.bind(win),time);}
return win;},drawBenefits:function(){if(SD.ExperimentManager.PopupBenefitsListExp.value){return DIV({},H2({},"More Benefits of Upgrading"),UL({},LI({},"Contact ",EM({},"all")," members"),LI({},"Get connected first when dating"),LI({},"Choose members for upcoming dates"),LI({},"Re-connect after dates"),LI({},EM({},"Much more!"))));}else{return DIV({},H2({},"Benefits of Upgrading"),UL({},LI({},"Contact ",EM({},"every")," member"),LI({},"Receive more messages"),LI({},"Choose your speed dates"),LI({},"Get speed dates even faster"),LI({},EM({},"Much more!"))));}},buttonBar:function(win,label,command,cancelLabel,confirmBtnClassName,cancelBtnClassName,confirmBtnId,cancelBtnId){cancelLabel=cancelLabel||"Cancel";confirmBtnClassName=confirmBtnClassName||"input-button sd-flirt-submit";cancelBtnClassName=cancelBtnClassName||"input-button right-button";confirmBtnId=confirmBtnId||"popup-confirm-btn";cancelBtnId=cancelBtnId||"popup-cancel-btn";var send=INPUT({"type":"button","class":confirmBtnClassName,"value":label,"id":confirmBtnId});var close=INPUT({"type":"button","class":cancelBtnClassName,"value":cancelLabel,"id":cancelBtnId});send.observe("click",command);close.observe("click",win.close.bind(win));return DIV({},send,close);},_popupGenericWarning:function(title,upgradeArguments,messages,buttonLabel,subTitle,onClick){if(SD.ExperimentManager.OrderFormAfterNewSignup2007.value){this.upgradeMyself(upgradeArguments);}else{buttonLabel=buttonLabel||"Upgrade";var win=this.standardPopup({title:title});var go=onClick||function(){this.upgradeMyself(upgradeArguments);};var link=A({},"premium members");link.observe("click",go.bind(this));var exp=DIV({"class":"overflirted-message"},"Only ",link);$A(messages).each(function(message){exp.insert(message);});win.getContent().insert(DIV({"class":"upgradepop"},subTitle||"",exp,this.drawBenefits(),this.buttonBar(win,buttonLabel,go.bind(this))));win.showCenter(true,100);if((typeof upgradeArguments["tobj"])!='undefined'){SD.Tracking.sendTrackingObject(upgradeArguments["tobj"]);}}},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;},submitIMPopup:function(formId,title,juliet,errorDivId,onSubmit,onLater,onDontAsk,hasIM){var title=title||"Want to chat with "+juliet.username+"?";var win=this.standardPopup({title:title,'width':435,draggable:true});var message=hasIM?SPAN({'class':'sub-header'},'Please re-enter your IM username to get notified when ',SPAN({'class':'name'},juliet.username),' signs online!'):SPAN({'class':'sub-header'},'Signup for SpeedDate IM alerts and get notified when ',SPAN({'class':'name'},juliet.username),' signs online!');var disclaimer=hasIM?SPAN({'class':'disclaimer'},BR(),BR(),'We weren\'t able to confirm your IM username.  Please edit your username below to receive alerts when people you like and potential matches are online.'):SPAN({'class':'disclaimer'},BR(),BR(),'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.');var maindiv=DIV({'class':'main-div'},message,disclaimer);var submitIMForm='<div class="tooltip-base">'+'<span id="'+errorDivId+'"> </span>'+'<b>IM Username</b> <input class="input-username" type="text" name="im"/> <b>on</b> '+'<select id="protocol" class="select-input triggered-select" style="width: auto;" name="protocol">'+'<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>'+'<br />'+'<div class="action-items">'+'<input type="button" id="imFormSignup" class="signup" value="Signup"/>'+'<input type="button" id="imFormNotNow" class="not-now" value="Not Now"/>'+'<input type="button" id="imDontAsk" class="dont-ask" value="Don\'t ask me again"/>'+'</div>'+'<div class="tooltip-text">'+'<div class="triggered-item-protocol triggered-value-">'+'Please select an IM service.'+'</div>'+'<div class="triggered-item-protocol triggered-value-msn">'+'<b>MSN (Windows Live Messenger)</b>'+'<table><tr>'+'<td class="im-service-logo im-msn-logo"></td>'+'<td class="im-description">'+'Please enter your full MSN email address.'+'</td>'+'</tr></table>'+'</div>'+'<div class="triggered-item-protocol triggered-value-yahoo">'+'<b>Yahoo! Messenger</b>'+'<table><tr>'+'<td class="im-service-logo im-yahoo-logo"></td>'+'<td class="im-description">'+'Please enter your Yahoo! ID.'+'</td>'+'</tr></table>'+'</div>'+'<div class="triggered-item-protocol triggered-value-gtalk">'+'<b>GChat / Google Talk</b>'+'<table><tr>'+'<td class="im-service-logo im-gtalk-logo"></td>'+'<td class="im-description">'+'Please enter your full Gmail address.'+'</td>'+'</tr></table>'+'</div>'+'<div class="triggered-item-protocol triggered-value-aim">'+'<b>AIM (AOL Instant Messenger)</b>'+'<table><tr>'+'<td class="im-service-logo im-aim-logo"></td>'+'<td class="im-description">'+'Please enter your AOL username.'+'</td>'+'</tr></table>'+'</div>'+'</div>'+'</div>';var img=IMG({"src":juliet.image_url,"style":{"width":"120px","height":"160px","float":"right","border-width":"0px","border-style":"solid","border-color":"#000"}});var div=DIV(null);div.insert(submitIMForm);var div=DIV({"class":"submit-im-popup"},img,maindiv,BR({'clear':'all'}),div);var form=FORM({'id':formId},div);win.getContent().insert(form);win.showCenter(true,150);var submitButton=$('imFormSignup');var laterButton=$('imFormNotNow');var dontAskButton=$('imDontAsk');submitButton.observe("click",onSubmit);laterButton.observe("click",onLater);dontAskButton.observe("click",onDontAsk);$$('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";}});return win;},askFbPermissionsPopup:function(){var win=this.standardPopup({title:'',width:500,draggable:false,destroyOnClose:true});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){var win=this.standardPopup({title:'Update your profile with your Facebook photos!',width:620,draggable:true,destroyOnClose: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="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){selectAllFbPhotos();e.stop();});});win.getContent().select('.save-user-fb-photos').each(function(el){el.observe('click',function(e){sendPhotoUrlsToBackend();win.close();e.stop();});});win.showCenter(true,20);},emailVerificationPopup:function(){SD.UserFilters.UI.saveStateAndPause();if(SD.ExperimentManager.EmailPopupDesign2496.value){var dialogWidth=550;}else{var dialogWidth=400;}
var isFirstTime=true;var dialog=this.standardPopup({title:'Please verify your email address to continue!',width:dialogWidth,draggable:false,destroyOnClose:true,onAfterClose:function(){SD.UserFilters.UI.restorePreviousStateAndResume();}});var helper=new SD.Dialogs.Utils({dialog:dialog,domContent:dialog.getContent(),onLoad:function(){isFirstTime&&dialog.showCenter(true,100);isFirstTime=false;},onParseElements:{'.close-dialog':function(el,domRoot){el.observe('click',function(){dialog.close();});}}});helper.load(SD.NavUtils.link('profile','email_verification_popup'));return dialog;},aboutMePopup:function(){SD.UserFilters.UI.saveStateAndPause();var dialogWidth=600;var dialogTitle='Please complete your profile to continue!';var isFirstTime=true;var dialog=this.standardPopup({title:dialogTitle,width:dialogWidth,draggable:false,destroyOnClose:true,onAfterClose:function(){SD.UserFilters.UI.restorePreviousStateAndResume();}});var checkBoxHandler=function(selEl,domRoot){selEl.parentNode.style.cursor='pointer';selEl.parentNode.observe('click',function(e){if(Event.element(e)==this){selEl.checked=!selEl.checked;}});};var helper=new SD.Dialogs.Utils({dialog:dialog,domContent:dialog.getContent(),onLoad:function(){isFirstTime&&dialog.showCenter(true,80);isFirstTime=false;},onParseElements:{'.checkbox-item input[type="checkbox"]':checkBoxHandler,'.radio-item input[type="radio"]':checkBoxHandler}});helper.load(SD.NavUtils.link('profile','member_info_popup'));return dialog;},uploadPhotoPopup:function(){SD.UserFilters.UI.saveStateAndPause();if(SD.ExperimentManager.PhotoPopupDesign2428.value){var dialogWidth=500;}else{var dialogWidth=400;}
var dialogTitle='Please upload your photo to continue!';var isFirstTime=true;var dialog=this.standardPopup({title:dialogTitle,width:dialogWidth,draggable:false,destroyOnClose:true,onAfterClose:function(){SD.UserFilters.UI.restorePreviousStateAndResume();}});var helper=new SD.Dialogs.Utils({dialog:dialog,domContent:dialog.getContent(),onLoad:function(){isFirstTime&&dialog.showCenter(true,80);isFirstTime=false;}});helper.load(SD.NavUtils.link('profile','upload_photo_popup'));return dialog;},logoutPopup:function(){var win=this.standardPopup({title:'Logging out...',width:300,draggable:false,destroyOnClose:true});var content='\<div style="padding: 10px 10px 0px 10px;">\
                            <h2 style="font-size: 12px; color: #000;">\
                                Would you like to log out both Facebook and SpeedDate, or just SpeedDate?\
                            </h2>\
                            <center>\
                                <button class="logout-both" style="border: normal;\
                                 font-size: 12px; font-weight: bold; margin: 10px 0px 5px; cursor: pointer; border: 1px solid #83A5AF; padding: 3px; background-color: #ADC3CA; color: #fff;"\>\
                                    Facebook and SpeedDate\
                                </button>\
                                <br /><span style="color: #666;">or</span><br />\
                                <button class="logout-sd-only" style="border: normal;\
                                 font-size: 12px; font-weight: bold; margin: 10px 0px 5px; cursor: pointer; border: 1px solid #83A5AF; padding: 3px; background-color: #ADC3CA; color: #fff;">\
                                    SpeedDate only\
                                </button>\
                            </center>\
                        </div>';win.getContent().insert(content);win.getContent().select('.logout-both').each(function(el){el.observe('click',function(e){SD.Nav.redirectTo(SD.NavUtils.link('login','logout',{logout_type:'fb-sd'}));win.close();e.stop();});});win.getContent().select('.logout-sd-only').each(function(el){el.observe('click',function(e){SD.Nav.redirectTo(SD.NavUtils.link('login','logout'));win.close();e.stop();});});win.showCenter(true,50);},standardPopup:function(params){var finalBaseParams;if(params.width){params.contentWidth=params.width;}
params.blocker=(params.draggable!==undefined)?!params.draggable:true;var baseParams={width:350,closable:true,template:SD.Window.legacyTemplate,draggable:false,className:"dialog popup-box lib-window"};return new SD.Window(Object.extend(baseParams,params));},processMembersTable:function(root){root.select('.members-table .member').each(function(e){var getUser=function(){return SD.User.get(e.id);};SD.FlirtWink.View.registerInputFlirt(e.select('.buttons .button.flirt').first(),getUser,Prototype.emptyFunction);SD.FlirtWink.View.registerInputWink(e.select('.buttons .button.wink').first(),getUser,Prototype.emptyFunction);SD.FlirtWink.View.registerInputDate(e.select('.buttons .button.date').first(),getUser,Prototype.emptyFunction);if(SD.ExperimentManager.FavoritesFeature.value&&e.select('.buttons .button.add-favorite').first()){SD.FlirtWink.View.registerInputFavorite(e.select('.buttons .button.add-favorite').first(),getUser,function(elem){elem.removeClassName('add-favorite').addClassName('added-favorite');elem.stopObserving('mouseover').stopObserving('mouseout').stopObserving('click');});}
var chatButton=e.select('.buttons .button.chat-enabled, .buttons .button.chat-disabled').first();var user=getUser();if(chatButton&&user){SD.FlirtWink.View.registerInputChat(chatButton,getUser,null,null,function(){chatButton.removeClassName('chat-disabled');chatButton.addClassName('chat-enabled');},function(){chatButton.addClassName('chat-disabled');chatButton.removeClassName('chat-enabled');});}});},userInfoPopupTrigger:function(defaultAction){if((SD.Model.getMyself().has_bounced||!SD.Model.getMyself().has_verified)){SD.Dialogs.dialogVerifyEmailToContinue();return false;}else{if(!SD.Model.getMyself().has_photo){SD.Dialogs.dialogUploadPhotoToContinue();return false;}else{if(!SD.Model.getMyself().has_about_me){SD.Dialogs.dialogFillAboutMeToContinue();return false;}else{return defaultAction();}}}},userInfoMouseOverOutTrigger:function(defaultAction){if((SD.Model.getMyself().has_bounced||!SD.Model.getMyself().has_verified)){return false;}else{if(!SD.Model.getMyself().has_photo){return false;}else{if(!SD.Model.getMyself().has_about_me){return false;}else{return defaultAction();}}}},popupDateMatchWarning:function(matchedUser,ua){var content=DIV({"style":{'position':'relative','height':'200px','margin-top':'10px'}},DIV({"style":{"position":"relative","display":"block","float":"left","margin-left":"10px","margin-top":"0px","text-align":"center","width":"120px"}},IMG({"src":matchedUser.image_url,"style":{"width":"120px","height":"160px","border-width":"2px","border-style":"solid","border-color":"#000","margin-bottom":"5px"}}),DIV({},matchedUser.username),DIV({},matchedUser.age+" years old"),DIV({},SD.ProfileViewer.UI.addressOf(matchedUser))),DIV({"style":{"position":"relative","float":"left","margin-left":"30px","width":"255px"}},DIV({"style":{"font-size":"26px"}},SD.Model.getMyself().name+","),DIV({"style":{"font-size":"20px"}},"Congratulations! You matched with ",BR(),STRONG({},matchedUser.username.truncate(20))),BR({}),A({"observeClick":function(evt){evt.stop(),SD.UIController.upgradeMyself(ua);},"class":"button-green-stretch"},DIV({'class':'left'}),DIV({'class':'middle'},"Contact Now"),DIV({'class':'right'})),DIV({"style":{"position":"absolute","right":"25px",'bottom':'-25px',"color":"#999","font-size":"11px"}},"Upgrade required")));var win=SD.UIController.standardPopup({title:"Contact Your Match!",width:460,height:300});win.getContent().insert(content);win.showCenter(true,100);},Events:{START_CHAT_REQUESTED:"uicontroller:startchatrequested",SEND_FLIRT_REQUESTED:"uicontroller:sendflirtrequested",FLIRT_WINK_DISPLAYED:"uicontroller:flirtWinkDisplayed",VIEW_PROFILE_REQUESTED:"uicontroller:viewprofilerequested",BLOCK_BUDDY_REQUESTED:"uicontroller:blockbuddyrequested",DELETE_BUDDY_REQUESTED:"uicontroller:deletebuddyrequested",REPORT_USER_REQUESTED:"uicontroller:report_userrequested",START_FEEDBACK_REQUESTED:"uicontroller:startfeedbackrequested",ADD_BUDDIES_REQUESTED:"uicontroller:addbuddiesrequested",SWITCHED_TO_OTHER_TABS:"uicontroller:switchedtoothertabs",SWITCHED_TO_SPEEDDATE:"uicontroller:switchedtospeeddate",CLOSE_WELCOME_POPUP:"uicontroller:closewelcomepopup",PHOTO_UPLOADED:"uicontroller:photouploaded",INITIALIZATION_COMPLETE:"uicontroller:initializationcomplete"},DatingAppStates:{HIDDEN:"hidden",NORMAL:"normal",DATING:"dating",TABOTHER:"tabother",TABOTHERDATING:"tabotherdating"}};