//speeddate compiled js file. Compile time:2009-11-24 07-52\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);borderRightWidth=isNaN(borderRightWidth)?0:borderRightWidth;var borderLeftWidth=parseInt(element.getStyle("border-left-width")||0);borderLeftWidth=isNaN(borderLeftWidth)?0:borderLeftWidth;var paddingRight=parseInt(element.getStyle("padding-right")||0);paddingRight=isNaN(paddingRight)?0:paddingRight;var paddingLeft=parseInt(element.getStyle("padding-left")||0);paddingLeft=isNaN(paddingLeft)?0:paddingLeft;element.setStyle({'width':(w-borderRightWidth-borderLeftWidth-paddingRight-paddingLeft)+'px'});return element;},setHeight:function(element,h){var borderTopWidth=parseInt(element.getStyle("border-top-width")||0);borderTopWidth=isNaN(borderTopWidth)?0:borderTopWidth;var borderBottomWidth=parseInt(element.getStyle("border-bottom-width")||0);borderBottomWidth=isNaN(borderBottomWidth)?0:borderBottomWidth;var paddingTop=parseInt(element.getStyle("padding-top")||0);paddingTop=isNaN(paddingTop)?0:paddingTop;var paddingBottom=parseInt(element.getStyle("padding-bottom")||0);paddingBottom=isNaN(paddingBottom)?0:paddingBottom;element.setStyle({'height':(h-borderTopWidth-borderBottomWidth-paddingTop-paddingBottom)+'px'});return element;}});
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)+0.5;},reverse:function(pos){return 1-pos;},flicker:function(pos){var pos=((-Math.cos(pos*Math.PI)/4)+0.75)+Math.random()/4;return pos>1?1:pos;},wobble:function(pos){return(-Math.cos(pos*Math.PI*(9*pos))/2)+0.5;},pulse:function(pos,pulses){pulses=pulses||5;return(((pos%(1/pulses))*pulses).round()==0?((pos*pulses*2)-(pos*pulses*2).floor()):1-((pos*pulses*2)-(pos*pulses*2).floor()));},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){element=$(element);effect=(effect||'appear').toLowerCase();var options=Object.extend({queue:{position:'end',scope:(element.id||'global'),limit:1}},arguments[2]||{});Effect[element.visible()?Effect.PAIRS[effect][1]:Effect.PAIRS[effect][0]](element,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){function codeForEvent(options,eventName){return((options[eventName+'Internal']?'this.options.'+eventName+'Internal(this);':'')+
(options[eventName]?'this.options.'+eventName+'(this);':''));}
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;eval('this.render = function(pos){ '+'if (this.state=="idle"){this.state="running";'+
codeForEvent(this.options,'beforeSetup')+
(this.setup?'this.setup();':'')+
codeForEvent(this.options,'afterSetup')+'};if (this.state=="running"){'+'pos=this.options.transition(pos)*'+this.fromToDelta+'+'+this.options.from+';'+'this.position=pos;'+
codeForEvent(this.options,'beforeUpdate')+
(this.update?'this.update(pos);':'')+
codeForEvent(this.options,'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(),max=(window.height||document.body.scrollHeight)-document.viewport.getHeight();if(options.offset)elementOffsets[1]+=options.offset;return new Effect.Tween(null,scrollOffsets.top,elementOffsets[1]>max?max: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]||{};var oldOpacity=element.getInlineOpacity();var transition=options.transition||Effect.Transitions.sinoidal;var reverser=function(pos){return transition(1-Effect.Transitions.pulse(pos,options.pulses))};reverser.bind(transition);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(hash,property){hash.set(property,css[property]);return hash;});if(!styles.opacity)styles.set('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(e){SD.log(e);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};}
﻿
(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 Window=Class.create();Window.keepMultiModalWindow=false;Window.hasEffectLib=(typeof Effect!='undefined');Window.resizeEffectDuration=0.4;Window.prototype={initialize:function(){var id;var optionIndex=0;if(arguments.length>0){if(typeof arguments[0]=="string"){id=arguments[0];optionIndex=1;}
else
id=arguments[0]?arguments[0].id:null;}
if(!id)
id="window_"+new Date().getTime();if($(id))
alert("Window "+id+" is already registered in the DOM! Make sure you use setDestroyOnClose() or destroyOnClose: true in the constructor");this.options=Object.extend({className:"dialog",blurClassName:null,minWidth:300,minHeight:20,maxWidth:790,maxHeight:570,resizable:true,closable:true,minimizable:true,maximizable:true,draggable:true,userData:null,showEffect:(Window.hasEffectLib?Effect.Appear:Element.show),hideEffect:(Window.hasEffectLib?Effect.Fade:Element.hide),showEffectOptions:{},hideEffectOptions:{},effectOptions:null,parent:document.body,title:"&nbsp;",url:null,onload:Prototype.emptyFunction,width:300,opacity:1,recenterAuto:true,wiredDrag:false,closeCallback:null,destroyOnClose:false,gridX:1,gridY:1},arguments[optionIndex]||{});if(this.options.blurClassName)
this.options.focusClassName=this.options.className;if(typeof this.options.top=="undefined"&&typeof this.options.bottom=="undefined")
this.options.top=this._round(Math.random()*500,this.options.gridY);if(typeof this.options.left=="undefined"&&typeof this.options.right=="undefined")
this.options.left=this._round(Math.random()*500,this.options.gridX);if(this.options.effectOptions){Object.extend(this.options.hideEffectOptions,this.options.effectOptions);Object.extend(this.options.showEffectOptions,this.options.effectOptions);if(this.options.showEffect==Element.Appear)
this.options.showEffectOptions.to=this.options.opacity;}
if(Window.hasEffectLib){if(this.options.showEffect==Effect.Appear)
this.options.showEffectOptions.to=this.options.opacity;if(this.options.hideEffect==Effect.Fade)
this.options.hideEffectOptions.from=this.options.opacity;}
if(this.options.hideEffect==Element.hide)
this.options.hideEffect=function(){Element.hide(this.element);if(this.options.destroyOnClose)this.destroy();}.bind(this)
if(this.options.parent!=document.body)
this.options.parent=$(this.options.parent);this.element=this._createWindow(id);this.element.win=this;this.eventMouseDown=this._initDrag.bindAsEventListener(this);this.eventMouseUp=this._endDrag.bindAsEventListener(this);this.eventMouseMove=this._updateDrag.bindAsEventListener(this);this.eventOnLoad=this._getWindowBorderSize.bindAsEventListener(this);this.eventMouseDownContent=this.toFront.bindAsEventListener(this);this.eventResize=this._recenter.bindAsEventListener(this);this.topbar=$(this.element.id+"_top");this.bottombar=$(this.element.id+"_bottom");this.content=$(this.element.id+"_content");Event.observe(this.topbar,"mousedown",this.eventMouseDown);Event.observe(this.bottombar,"mousedown",this.eventMouseDown);Event.observe(this.content,"mousedown",this.eventMouseDownContent);Event.observe(window,"load",this.eventOnLoad);if(this.options.draggable){var that=this;[this.topbar,this.topbar.up().previous(),this.topbar.up().next()].each(function(element){element.observe("mousedown",that.eventMouseDown);element.addClassName("top_draggable");});[this.bottombar.up(),this.bottombar.up().previous(),this.bottombar.up().next()].each(function(element){element.observe("mousedown",that.eventMouseDown);element.addClassName("bottom_draggable");});}
if(this.options.resizable){this.sizer=$(this.element.id+"_sizer");Event.observe(this.sizer,"mousedown",this.eventMouseDown);}
this.useLeft=null;this.useTop=null;if(typeof this.options.left!="undefined"){this.element.setStyle({left:parseFloat(this.options.left)+'px'});this.useLeft=true;}
else{this.element.setStyle({right:parseFloat(this.options.right)+'px'});this.useLeft=false;}
if(typeof this.options.top!="undefined"){this.element.setStyle({top:parseFloat(this.options.top)+'px'});this.useTop=true;}
else{this.element.setStyle({bottom:parseFloat(this.options.bottom)+'px'});this.useTop=false;}
this.storedLocation=null;this.setOpacity(this.options.opacity);if(this.options.zIndex)
this.setZIndex(this.options.zIndex)
if(this.options.destroyOnClose)
this.setDestroyOnClose(true);this._getWindowBorderSize();this.width=this.options.width;this.height=this.options.height;this.visible=false;this.constraint=false;this.constraintPad={top:0,left:0,bottom:0,right:0};this.setTitle(this.options.title)
Windows.register(this);},destroy:function(){this._notify("onDestroy");Event.stopObserving(this.topbar,"mousedown",this.eventMouseDown);Event.stopObserving(this.bottombar,"mousedown",this.eventMouseDown);Event.stopObserving(this.content,"mousedown",this.eventMouseDownContent);Event.stopObserving(window,"load",this.eventOnLoad);Event.stopObserving(window,"resize",this.eventResize);Event.stopObserving(window,"scroll",this.eventResize);Event.stopObserving(this.content,"load",this.options.onload);if(this._oldParent){var content=this.getContent();var originalContent=null;for(var i=0;i<content.childNodes.length;i++){originalContent=content.childNodes[i];if(originalContent.nodeType==1)
break;originalContent=null;}
if(originalContent)
this._oldParent.appendChild(originalContent);this._oldParent=null;}
if(this.sizer)
Event.stopObserving(this.sizer,"mousedown",this.eventMouseDown);if(this.options.url)
this.content.src=null
if(this.iefix)
Element.remove(this.iefix);if(this.modal){Windows.removeModalWindow(this);Windows.resetOverflow();}
Element.remove(this.element);Windows.unregister(this);},setCloseCallback:function(callback){this.options.closeCallback=callback;},getContent:function(){return this.content;},setContent:function(id,autoresize,autoposition){var element=$(id);if(null==element)throw"Unable to find element '"+id+"' in DOM";this._oldParent=element.parentNode;var d=null;var p=null;if(autoresize)
d=Element.getDimensions(element);if(autoposition)
p=Position.cumulativeOffset(element);var content=this.getContent();this.setHTMLContent("");content=this.getContent();content.appendChild(element);element.show();if(autoposition)
this.setLocation(p[1]-this.heightN,p[0]-this.widthW);},setHTMLContent:function(html){if(this.options.url){this.content.src=null;this.options.url=null;var content="<div id=\""+this.getId()+"_content\" class=\""+this.options.className+"_content\"> </div>";$(this.getId()+"_table_content").innerHTML=content;this.content=$(this.element.id+"_content");}
this.getContent().innerHTML=html;},setAjaxContent:function(url,options,showCentered,showModal){this.showFunction=showCentered?"showCenter":"show";this.showModal=showModal||false;options=options||{};this.setHTMLContent("");this.onComplete=options.onComplete;if(!this._onCompleteHandler)
this._onCompleteHandler=this._setAjaxContent.bind(this);options.onComplete=this._onCompleteHandler;new Ajax.Request(url,options);options.onComplete=this.onComplete;},_setAjaxContent:function(originalRequest){Element.update(this.getContent(),originalRequest.responseText);if(this.onComplete)
this.onComplete(originalRequest);this.onComplete=null;this[this.showFunction](this.showModal)},setURL:function(url){if(this.options.url)
this.content.src=null;this.options.url=url;var content="<iframe frameborder='0' name='"+this.getId()+"_content'  id='"+this.getId()+"_content' src='"+url+"' width='"+this.width+"' height='"+this.height+"'> </iframe>";$(this.getId()+"_table_content").innerHTML=content;this.content=$(this.element.id+"_content");},getURL:function(){return this.options.url?this.options.url:null;},refresh:function(){if(this.options.url)
$(this.element.getAttribute('id')+'_content').src=this.options.url;},setCookie:function(name,expires,path,domain,secure){name=name||this.element.id;this.cookie=[name,expires,path,domain,secure];var value=WindowUtilities.getCookie(name)
if(value){var values=value.split(',');var x=values[0].split(':');var y=values[1].split(':');var w=parseFloat(values[2]),h=parseFloat(values[3]);var mini=values[4];var maxi=values[5];this.setSize(w,h);if(mini=="true")
this.doMinimize=true;else if(maxi=="true")
this.doMaximize=true;this.useLeft=x[0]=="l";this.useTop=y[0]=="t";this.element.setStyle(this.useLeft?{left:x[1]}:{right:x[1]});this.element.setStyle(this.useTop?{top:y[1]}:{bottom:y[1]});}},getId:function(){return this.element.id;},setDestroyOnClose:function(){this.options.destroyOnClose=true;},setConstraint:function(bool,padding){this.constraint=bool;this.constraintPad=Object.extend(this.constraintPad,padding||{});if(this.useTop&&this.useLeft)
this.setLocation(parseFloat(this.element.style.top),parseFloat(this.element.style.left));},_initDrag:function(event){if(Event.element(event)==this.sizer&&this.isMinimized())
return;if(Event.element(event)!=this.sizer&&this.isMaximized())
return;if(Prototype.Browser.IE&&this.heightN==0)
this._getWindowBorderSize();this.pointer=[this._round(Event.pointerX(event),this.options.gridX),this._round(Event.pointerY(event),this.options.gridY)];if(this.options.wiredDrag)
this.currentDrag=this._createWiredElement();else
this.currentDrag=this.element;if(Event.element(event)==this.sizer){this.doResize=true;this.widthOrg=this.width;this.heightOrg=this.height;this.bottomOrg=parseFloat(this.element.getStyle('bottom'));this.rightOrg=parseFloat(this.element.getStyle('right'));this._notify("onStartResize");}
else{this.doResize=false;var closeButton=$(this.getId()+'_close');if(closeButton&&Position.within(closeButton,this.pointer[0],this.pointer[1])){this.currentDrag=null;return;}
this.toFront();if(!this.options.draggable)
return;this._notify("onStartMove");}
Event.observe(document,"mouseup",this.eventMouseUp,false);Event.observe(document,"mousemove",this.eventMouseMove,false);WindowUtilities.disableScreen('__invisible__','__invisible__',this.overlayOpacity);document.body.ondrag=function(){return false;};document.body.onselectstart=function(){return false;};this.currentDrag.show();Event.stop(event);},_round:function(val,round){return round==1?val:val=Math.floor(val/round)*round;},_updateDrag:function(event){var pointer=[this._round(Event.pointerX(event),this.options.gridX),this._round(Event.pointerY(event),this.options.gridY)];var dx=pointer[0]-this.pointer[0];var dy=pointer[1]-this.pointer[1];if(this.doResize){var w=this.widthOrg+dx;var h=this.heightOrg+dy;dx=this.width-this.widthOrg
dy=this.height-this.heightOrg
if(this.useLeft)
w=this._updateWidthConstraint(w)
else
this.currentDrag.setStyle({right:(this.rightOrg-dx)+'px'});if(this.useTop)
h=this._updateHeightConstraint(h)
else
this.currentDrag.setStyle({bottom:(this.bottomOrg-dy)+'px'});this.setSize(w,h);this._notify("onResize");}
else{this.pointer=pointer;if(this.useLeft){var left=parseFloat(this.currentDrag.getStyle('left'))+dx;var newLeft=this._updateLeftConstraint(left);this.pointer[0]+=newLeft-left;this.currentDrag.setStyle({left:newLeft+'px'});}
else
this.currentDrag.setStyle({right:parseFloat(this.currentDrag.getStyle('right'))-dx+'px'});if(this.useTop){var top=parseFloat(this.currentDrag.getStyle('top'))+dy;var newTop=this._updateTopConstraint(top);this.pointer[1]+=newTop-top;this.currentDrag.setStyle({top:newTop+'px'});}
else
this.currentDrag.setStyle({bottom:parseFloat(this.currentDrag.getStyle('bottom'))-dy+'px'});this._notify("onMove");}
if(this.iefix)
this._fixIEOverlapping();this._removeStoreLocation();Event.stop(event);},_endDrag:function(event){WindowUtilities.enableScreen('__invisible__');if(this.doResize)
this._notify("onEndResize");else
this._notify("onEndMove");Event.stopObserving(document,"mouseup",this.eventMouseUp,false);Event.stopObserving(document,"mousemove",this.eventMouseMove,false);Event.stop(event);this._hideWiredElement();this._saveCookie()
document.body.ondrag=null;document.body.onselectstart=null;},_updateLeftConstraint:function(left){if(this.constraint&&this.useLeft&&this.useTop){var width=this.options.parent==document.body?WindowUtilities.getPageSize().windowWidth:this.options.parent.getDimensions().width;if(left<this.constraintPad.left)
left=this.constraintPad.left;if(left+this.width+this.widthE+this.widthW>width-this.constraintPad.right)
left=width-this.constraintPad.right-this.width-this.widthE-this.widthW;}
return left;},_updateTopConstraint:function(top){if(this.constraint&&this.useLeft&&this.useTop){var height=this.options.parent==document.body?WindowUtilities.getPageSize().windowHeight:this.options.parent.getDimensions().height;var h=this.height+this.heightN+this.heightS;if(top<this.constraintPad.top)
top=this.constraintPad.top;if(top+h>height-this.constraintPad.bottom)
top=height-this.constraintPad.bottom-h;}
return top;},_updateWidthConstraint:function(w){if(this.constraint&&this.useLeft&&this.useTop){var width=this.options.parent==document.body?WindowUtilities.getPageSize().windowWidth:this.options.parent.getDimensions().width;var left=parseFloat(this.element.getStyle("left"));if(left+w+this.widthE+this.widthW>width-this.constraintPad.right)
w=width-this.constraintPad.right-left-this.widthE-this.widthW;}
return w;},_updateHeightConstraint:function(h){if(this.constraint&&this.useLeft&&this.useTop){var height=this.options.parent==document.body?WindowUtilities.getPageSize().windowHeight:this.options.parent.getDimensions().height;var top=parseFloat(this.element.getStyle("top"));if(top+h+this.heightN+this.heightS>height-this.constraintPad.bottom)
h=height-this.constraintPad.bottom-top-this.heightN-this.heightS;}
return h;},_createWindow:function(id){var className=this.options.className;var win=document.createElement("div");win.setAttribute('id',id);win.className="dialog sd-dialog "+id;win.width=this.options.width;var content;if(this.options.url)
content="<iframe frameborder=\"0\" name=\""+id+"_content\"  id=\""+id+"_content\" src=\""+this.options.url+"\"> </iframe>";else
content="<div id=\""+id+"_content\" class=\""+id+"-content p-content\"> </div>";var closeDiv=this.options.closable?"<div class='popup-close "+className+"-close-button' id='"+id+"_close' onclick='Windows.close(\""+id+"\", event)'>×</div>":"";var minDiv=this.options.minimizable?"<div class='"+className+"_minimize' id='"+id+"_minimize' onclick='Windows.minimize(\""+id+"\", event)'> </div>":"";var maxDiv=this.options.maximizable?"<div class='"+className+"_maximize' id='"+id+"_maximize' onclick='Windows.maximize(\""+id+"\", event)'> </div>":"";var seAttributes=this.options.resizable?"class='"+className+"_sizer' id='"+id+"_sizer'":"class='"+className+"_se'";var blank="../themes/default/blank.gif";win.innerHTML="\
    <div class='popup-box "+className+"'>\
      <table id='"+id+"_row1' class=\"top table_window\" cellpadding='0' cellspacing='0'>\
        <tr>\
          <td class='"+className+"_nw'>&nbsp;</td>\
          <td class='"+className+"_n'><div id='"+id+"_top' class='"+className+"_title title_window'>"+this.options.title+"</div></td>\
          <td class='"+className+"_ne'>&nbsp;</td>\
        </tr>\
      </table>\
      <table id='"+id+"_row2' class=\"mid table_window\" cellpadding='0' cellspacing='0'>\
        <tr>\
          <td class='"+className+"_w'>&nbsp;</td>\
            <td id='"+id+"_table_content' class='"+className+"_content' valign='top'>"+content+"</td>\
          <td class='"+className+"_e'>&nbsp;</td>\
        </tr>\
      </table>\
        <table id='"+id+"_row3' class=\"bot table_window\" cellpadding='0' cellspacing='0'>\
        <tr>\
          <td class='"+className+"_sw'>&nbsp;</td>\
            <td class='"+className+"_s'><div id='"+id+"_bottom' class='status_bar "+className+"_status'><span style='float:left; width:1px; height:1px'></span></div></td>\
            <td "+seAttributes+">&nbsp;</td>\
        </tr>\
      </table>\
      </div>\
    "+closeDiv+minDiv+maxDiv;Element.hide(win);this.options.parent.insertBefore(win,this.options.parent.firstChild);Event.observe($(id+"_content"),"load",this.options.onload);return win;},changeClassName:function(newClassName){var className=this.options.className;var id=this.getId();$A(["_close","_minimize","_maximize","_sizer","_content"]).each(function(value){this._toggleClassName($(id+value),className+value,newClassName+value)}.bind(this));this._toggleClassName($(id+"_top"),className+"_title",newClassName+"_title");$$("#"+id+" td").each(function(td){td.className=td.className.sub(className,newClassName);});this.options.className=newClassName;},_toggleClassName:function(element,oldClassName,newClassName){if(element){element.removeClassName(oldClassName);element.addClassName(newClassName);}},setLocation:function(top,left){top=this._updateTopConstraint(top);left=this._updateLeftConstraint(left);var e=this.currentDrag||this.element;e.setStyle({top:top+'px'});e.setStyle({left:left+'px'});this.useLeft=true;this.useTop=true;},getLocation:function(){var location={};if(this.useTop)
location=Object.extend(location,{top:this.element.getStyle("top")});else
location=Object.extend(location,{bottom:this.element.getStyle("bottom")});if(this.useLeft)
location=Object.extend(location,{left:this.element.getStyle("left")});else
location=Object.extend(location,{right:this.element.getStyle("right")});return location;},getSize:function(){return{width:this.width,height:this.height};},setSize:function(width,height,useEffect){width=parseFloat(width);height=parseFloat(height);if(!this.minimized&&width<this.options.minWidth)
width=this.options.minWidth;if(this.options.maxHeight&&height>this.options.maxHeight)
height=this.options.maxHeight;if(this.options.maxWidth&&width>this.options.maxWidth)
width=this.options.maxWidth;if(this.useTop&&this.useLeft&&Window.hasEffectLib&&Effect.ResizeWindow&&useEffect){new Effect.ResizeWindow(this,null,null,width,height,{duration:Window.resizeEffectDuration});}else{this.width=width;this.height=height;var e=this.currentDrag?this.currentDrag:this.element;e.setStyle({width:width+this.widthW+this.widthE+"px"})
e.setStyle({height:height+this.heightN+this.heightS+"px"})
if(!this.currentDrag||this.currentDrag==this.element){var content=$(this.element.id+'_content');}}},updateHeight:function(){this.setSize(this.width,this.content.scrollHeight,true);},updateWidth:function(){this.setSize(this.content.scrollWidth,this.height,true);},toFront:function(){if(this.element.style.zIndex<Windows.maxZIndex)
this.setZIndex(Windows.maxZIndex+1);if(this.iefix)
this._fixIEOverlapping();},getBounds:function(insideOnly){if(!this.width||!this.height||!this.visible)
this.computeBounds();var w=this.width;var h=this.height;if(!insideOnly){w+=this.widthW+this.widthE;h+=this.heightN+this.heightS;}
var bounds=Object.extend(this.getLocation(),{width:w+"px",height:h+"px"});return bounds;},computeBounds:function(){if(!this.width||!this.height){var size=WindowUtilities._computeSize(this.content.innerHTML,this.content.id,this.width,this.height,0,this.options.className)
if(this.height)
this.width=size+5
else
this.height=size+5}
this.setSize(this.width,this.height);if(this.centered)
this._center(this.centerTop,this.centerLeft);},show:function(modal){this.visible=true;if(modal){if(typeof this.overlayOpacity=="undefined"){var that=this;setTimeout(function(){that.show(modal)},10);return;}
Windows.addModalWindow(this);this.modal=true;this.setZIndex(Windows.maxZIndex+1);Windows.unsetOverflow(this);}
else
if(!this.element.style.zIndex)
this.setZIndex(Windows.maxZIndex+1);if(this.oldStyle)
this.getContent().setStyle({overflow:this.oldStyle});this.computeBounds();this._notify("onBeforeShow");if(this.options.showEffect!=Element.show&&this.options.showEffectOptions)
this.options.showEffect(this.element,this.options.showEffectOptions);else
this.options.showEffect(this.element);this._checkIEOverlapping();WindowUtilities.focusedWindow=this
this._notify("onShow");},showCenter:function(modal,top,left){this.centered=true;this.centerTop=top;this.centerLeft=left;this.show(modal);},isVisible:function(){return this.visible;},_center:function(top,left){var windowScroll=WindowUtilities.getWindowScroll(this.options.parent);var pageSize=WindowUtilities.getPageSize(this.options.parent);if(typeof top=="undefined")
top=(pageSize.windowHeight-(this.height+this.heightN+this.heightS))/2;top+=0*windowScroll.top;if(typeof left=="undefined")
left=(pageSize.windowWidth-(this.width+this.widthW+this.widthE))/2;left+=windowScroll.left
this.setLocation(top,left);this.toFront();},_recenter:function(event){if(this.centered){var pageSize=WindowUtilities.getPageSize(this.options.parent);var windowScroll=WindowUtilities.getWindowScroll(this.options.parent);if(this.pageSize&&this.pageSize.windowWidth==pageSize.windowWidth&&this.pageSize.windowHeight==pageSize.windowHeight&&this.windowScroll.left==windowScroll.left&&this.windowScroll.top==windowScroll.top)
return;this.pageSize=pageSize;this.windowScroll=windowScroll;if($('overlay_modal'))
$('overlay_modal').setStyle({height:(pageSize.pageHeight+'px')});if(this.options.recenterAuto)
this._center(this.centerTop,this.centerLeft);}},hide:function(){this.visible=false;if(this.modal){Windows.removeModalWindow(this);Windows.resetOverflow();}
this.oldStyle=this.getContent().getStyle('overflow')||"auto"
this.getContent().setStyle({overflow:"hidden"});this.options.hideEffect(this.element,this.options.hideEffectOptions);if(this.iefix)
this.iefix.hide();if(!this.doNotNotifyHide)
this._notify("onHide");},close:function(){if(this.visible){if(this.options.closeCallback&&!this.options.closeCallback(this))
return;if(this.options.destroyOnClose){var destroyFunc=this.destroy.bind(this);if(this.options.hideEffectOptions.afterFinish){var func=this.options.hideEffectOptions.afterFinish;this.options.hideEffectOptions.afterFinish=function(){func();destroyFunc()}}
else
this.options.hideEffectOptions.afterFinish=function(){destroyFunc()}}
Windows.updateFocusedWindow();this.doNotNotifyHide=true;this.hide();this.doNotNotifyHide=false;this._notify("onClose");}},minimize:function(){if(this.resizing)
return;var r2=$(this.getId()+"_row2");if(!this.minimized){this.minimized=true;var dh=r2.getDimensions().height;this.r2Height=dh;var h=this.element.getHeight()-dh;if(this.useLeft&&this.useTop&&Window.hasEffectLib&&Effect.ResizeWindow){new Effect.ResizeWindow(this,null,null,null,this.height-dh,{duration:Window.resizeEffectDuration});}else{this.height-=dh;this.element.setStyle({height:h+"px"});r2.hide();}
if(!this.useTop){var bottom=parseFloat(this.element.getStyle('bottom'));this.element.setStyle({bottom:(bottom+dh)+'px'});}}
else{this.minimized=false;var dh=this.r2Height;this.r2Height=null;if(this.useLeft&&this.useTop&&Window.hasEffectLib&&Effect.ResizeWindow){new Effect.ResizeWindow(this,null,null,null,this.height+dh,{duration:Window.resizeEffectDuration});}
else{var h=this.element.getHeight()+dh;this.height+=dh;this.element.setStyle({height:h+"px"})
r2.show();}
if(!this.useTop){var bottom=parseFloat(this.element.getStyle('bottom'));this.element.setStyle({bottom:(bottom-dh)+'px'});}
this.toFront();}
this._notify("onMinimize");this._saveCookie()},maximize:function(){if(this.isMinimized()||this.resizing)
return;if(Prototype.Browser.IE&&this.heightN==0)
this._getWindowBorderSize();if(this.storedLocation!=null){this._restoreLocation();if(this.iefix)
this.iefix.hide();}
else{this._storeLocation();Windows.unsetOverflow(this);var windowScroll=WindowUtilities.getWindowScroll(this.options.parent);var pageSize=WindowUtilities.getPageSize(this.options.parent);var left=windowScroll.left;var top=windowScroll.top;if(this.options.parent!=document.body){windowScroll={top:0,left:0,bottom:0,right:0};var dim=this.options.parent.getDimensions();pageSize.windowWidth=dim.width;pageSize.windowHeight=dim.height;top=0;left=0;}
if(this.constraint){pageSize.windowWidth-=Math.max(0,this.constraintPad.left)+Math.max(0,this.constraintPad.right);pageSize.windowHeight-=Math.max(0,this.constraintPad.top)+Math.max(0,this.constraintPad.bottom);left+=Math.max(0,this.constraintPad.left);top+=Math.max(0,this.constraintPad.top);}
var width=pageSize.windowWidth-this.widthW-this.widthE;var height=pageSize.windowHeight-this.heightN-this.heightS;if(this.useLeft&&this.useTop&&Window.hasEffectLib&&Effect.ResizeWindow){new Effect.ResizeWindow(this,top,left,width,height,{duration:Window.resizeEffectDuration});}
else{this.setSize(width,height);this.element.setStyle(this.useLeft?{left:left}:{right:left});this.element.setStyle(this.useTop?{top:top}:{bottom:top});}
this.toFront();if(this.iefix)
this._fixIEOverlapping();}
this._notify("onMaximize");this._saveCookie()},isMinimized:function(){return this.minimized;},isMaximized:function(){return(this.storedLocation!=null);},setOpacity:function(opacity){if(Element.setOpacity)
Element.setOpacity(this.element,opacity);},setZIndex:function(zindex){this.element.setStyle({zIndex:zindex});Windows.updateZindex(zindex,this);},setTitle:function(newTitle){if(!newTitle||newTitle=="")
newTitle="&nbsp;";Element.update(this.element.id+'_top',newTitle);},getTitle:function(){return $(this.element.id+'_top').innerHTML;},setStatusBar:function(element){var statusBar=$(this.getId()+"_bottom");if(typeof(element)=="object"){if(this.bottombar.firstChild)
this.bottombar.replaceChild(element,this.bottombar.firstChild);else
this.bottombar.appendChild(element);}
else
this.bottombar.innerHTML=element;},_checkIEOverlapping:function(){if(!this.iefix&&(navigator.appVersion.indexOf('MSIE')>0)&&(navigator.userAgent.indexOf('Opera')<0)&&(this.element.getStyle('position')=='absolute')){new Insertion.After(this.element.id,'<iframe id="'+this.element.id+'_iefix" '+'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" '+'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');this.iefix=$(this.element.id+'_iefix');}
if(this.iefix)
setTimeout(this._fixIEOverlapping.bind(this),50);},_fixIEOverlapping:function(){Position.clone(this.element,this.iefix);this.iefix.style.zIndex=this.element.style.zIndex-1;this.iefix.show();},_getWindowBorderSize:function(event){var div=this._createHiddenDiv(this.options.className+"_n")
this.heightN=Element.getDimensions(div).height;div.parentNode.removeChild(div)
var div=this._createHiddenDiv(this.options.className+"_s")
this.heightS=Element.getDimensions(div).height;div.parentNode.removeChild(div)
var div=this._createHiddenDiv(this.options.className+"_e")
this.widthE=Element.getDimensions(div).width;div.parentNode.removeChild(div)
var div=this._createHiddenDiv(this.options.className+"_w")
this.widthW=Element.getDimensions(div).width;div.parentNode.removeChild(div);var div=document.createElement("div");div.className="overlay_"+this.options.className;document.body.appendChild(div);var that=this;setTimeout(function(){that.overlayOpacity=($(div).getStyle("opacity"));div.parentNode.removeChild(div);},10);if(Prototype.Browser.IE){this.heightS=$(this.getId()+"_row3").getDimensions().height;this.heightN=$(this.getId()+"_row1").getDimensions().height;}
if(Prototype.Browser.WebKit&&Prototype.Browser.WebKitVersion<420)
this.setSize(this.width,this.height);if(this.doMaximize)
this.maximize();if(this.doMinimize)
this.minimize();},_createHiddenDiv:function(className){var objBody=document.body;var win=document.createElement("div");win.setAttribute('id',this.element.id+"_tmp");win.className=className;win.style.display='none';win.innerHTML='';objBody.insertBefore(win,objBody.firstChild);return win;},_storeLocation:function(){if(this.storedLocation==null){this.storedLocation={useTop:this.useTop,useLeft:this.useLeft,top:this.element.getStyle('top'),bottom:this.element.getStyle('bottom'),left:this.element.getStyle('left'),right:this.element.getStyle('right'),width:this.width,height:this.height};}},_restoreLocation:function(){if(this.storedLocation!=null){this.useLeft=this.storedLocation.useLeft;this.useTop=this.storedLocation.useTop;if(this.useLeft&&this.useTop&&Window.hasEffectLib&&Effect.ResizeWindow)
new Effect.ResizeWindow(this,this.storedLocation.top,this.storedLocation.left,this.storedLocation.width,this.storedLocation.height,{duration:Window.resizeEffectDuration});else{this.element.setStyle(this.useLeft?{left:this.storedLocation.left}:{right:this.storedLocation.right});this.element.setStyle(this.useTop?{top:this.storedLocation.top}:{bottom:this.storedLocation.bottom});this.setSize(this.storedLocation.width,this.storedLocation.height);}
Windows.resetOverflow();this._removeStoreLocation();}},_removeStoreLocation:function(){this.storedLocation=null;},_saveCookie:function(){if(this.cookie){var value="";if(this.useLeft)
value+="l:"+(this.storedLocation?this.storedLocation.left:this.element.getStyle('left'))
else
value+="r:"+(this.storedLocation?this.storedLocation.right:this.element.getStyle('right'))
if(this.useTop)
value+=",t:"+(this.storedLocation?this.storedLocation.top:this.element.getStyle('top'))
else
value+=",b:"+(this.storedLocation?this.storedLocation.bottom:this.element.getStyle('bottom'))
value+=","+(this.storedLocation?this.storedLocation.width:this.width);value+=","+(this.storedLocation?this.storedLocation.height:this.height);value+=","+this.isMinimized();value+=","+this.isMaximized();WindowUtilities.setCookie(value,this.cookie)}},_createWiredElement:function(){if(!this.wiredElement){if(Prototype.Browser.IE)
this._getWindowBorderSize();var div=document.createElement("div");div.className="wired_frame "+this.options.className+"_wired_frame";div.style.position='absolute';this.options.parent.insertBefore(div,this.options.parent.firstChild);this.wiredElement=$(div);}
if(this.useLeft)
this.wiredElement.setStyle({left:this.element.getStyle('left')});else
this.wiredElement.setStyle({right:this.element.getStyle('right')});if(this.useTop)
this.wiredElement.setStyle({top:this.element.getStyle('top')});else
this.wiredElement.setStyle({bottom:this.element.getStyle('bottom')});var dim=this.element.getDimensions();this.wiredElement.setStyle({width:dim.width+"px",height:dim.height+"px"});this.wiredElement.setStyle({zIndex:Windows.maxZIndex+30});return this.wiredElement;},_hideWiredElement:function(){if(!this.wiredElement||!this.currentDrag)
return;if(this.currentDrag==this.element)
this.currentDrag=null;else{if(this.useLeft)
this.element.setStyle({left:this.currentDrag.getStyle('left')});else
this.element.setStyle({right:this.currentDrag.getStyle('right')});if(this.useTop)
this.element.setStyle({top:this.currentDrag.getStyle('top')});else
this.element.setStyle({bottom:this.currentDrag.getStyle('bottom')});this.currentDrag.hide();this.currentDrag=null;if(this.doResize)
this.setSize(this.width,this.height);}},_notify:function(eventName){if(this.options[eventName])
this.options[eventName](this);else
Windows.notify(eventName,this);}};var Windows={windows:[],modalWindows:[],observers:[],focusedWindow:null,maxZIndex:0,overlayShowEffectOptions:{duration:0.1},overlayHideEffectOptions:{duration:0.1},addObserver:function(observer){this.removeObserver(observer);this.observers.push(observer);},removeObserver:function(observer){this.observers=this.observers.reject(function(o){return o==observer});},notify:function(eventName,win){this.observers.each(function(o){if(o[eventName])o[eventName](eventName,win);});},getWindow:function(id){return this.windows.detect(function(d){return d.getId()==id});},getFocusedWindow:function(){return this.focusedWindow;},updateFocusedWindow:function(){this.focusedWindow=this.windows.length>=2?this.windows[this.windows.length-2]:null;},register:function(win){this.windows.push(win);},addModalWindow:function(win){if(this.modalWindows.length==0){WindowUtilities.disableScreen(win.options.className,'overlay_modal',win.overlayOpacity,win.getId(),win.options.parent);}
else{if(Window.keepMultiModalWindow){$('overlay_modal').style.zIndex=Windows.maxZIndex+1;Windows.maxZIndex+=1;WindowUtilities._hideSelect(this.modalWindows.last().getId());}
else
this.modalWindows.last().element.hide();WindowUtilities._showSelect(win.getId());}
this.modalWindows.push(win);},removeModalWindow:function(win){this.modalWindows.pop();if(this.modalWindows.length==0)
WindowUtilities.enableScreen();else{if(Window.keepMultiModalWindow){this.modalWindows.last().toFront();WindowUtilities._showSelect(this.modalWindows.last().getId());}
else
this.modalWindows.last().element.show();}},register:function(win){this.windows.push(win);},unregister:function(win){this.windows=this.windows.reject(function(d){return d==win});},closeAll:function(){this.windows.each(function(w){Windows.close(w.getId())});},closeAllModalWindows:function(){WindowUtilities.enableScreen();this.modalWindows.each(function(win){if(win)win.close()});},minimize:function(id,event){var win=this.getWindow(id)
if(win&&win.visible)
win.minimize();Event.stop(event);},maximize:function(id,event){var win=this.getWindow(id)
if(win&&win.visible)
win.maximize();Event.stop(event);},close:function(id,event){var win=this.getWindow(id);if(win)
win.close();if(event)
Event.stop(event);},blur:function(id){var win=this.getWindow(id);if(!win)
return;if(win.options.blurClassName)
win.changeClassName(win.options.blurClassName);if(this.focusedWindow==win)
this.focusedWindow=null;win._notify("onBlur");},focus:function(id){var win=this.getWindow(id);if(!win)
return;if(this.focusedWindow)
this.blur(this.focusedWindow.getId())
if(win.options.focusClassName)
win.changeClassName(win.options.focusClassName);this.focusedWindow=win;win._notify("onFocus");},unsetOverflow:function(except){this.windows.each(function(d){d.oldOverflow=d.getContent().getStyle("overflow")||"auto";d.getContent().setStyle({overflow:"hidden"})});if(except&&except.oldOverflow)
except.getContent().setStyle({overflow:except.oldOverflow});},resetOverflow:function(){this.windows.each(function(d){if(d.oldOverflow)d.getContent().setStyle({overflow:d.oldOverflow})});},updateZindex:function(zindex,win){if(zindex>this.maxZIndex){this.maxZIndex=zindex;if(this.focusedWindow)
this.blur(this.focusedWindow.getId())}
this.focusedWindow=win;if(this.focusedWindow)
this.focus(this.focusedWindow.getId())}};var Dialog={dialogId:null,onCompleteFunc:null,callFunc:null,parameters:null,confirm:function(content,parameters){if(content&&typeof content!="string"){Dialog._runAjaxRequest(content,parameters,Dialog.confirm);return}
content=content||"";parameters=parameters||{};var okLabel=parameters.okLabel?parameters.okLabel:"Ok";var cancelLabel=parameters.cancelLabel?parameters.cancelLabel:"Cancel";parameters=Object.extend(parameters,parameters.windowParameters||{});parameters.windowParameters=parameters.windowParameters||{};parameters.className=parameters.className||"alert";var okButtonClass="class ='"+(parameters.buttonClass?parameters.buttonClass+" ":"")+" ok_button'"
var cancelButtonClass="class ='"+(parameters.buttonClass?parameters.buttonClass+" ":"")+" cancel_button'"
var content="\
      <div class='"+parameters.className+"_message'>"+content+"</div>\
        <div class='"+parameters.className+"_buttons'>\
          <input type='button' value='"+okLabel+"' onclick='Dialog.okCallback()' "+okButtonClass+"/>\
          <input type='button' value='"+cancelLabel+"' onclick='Dialog.cancelCallback()' "+cancelButtonClass+"/>\
        </div>\
    ";return this._openDialog(content,parameters)},alert:function(content,parameters){if(content&&typeof content!="string"){Dialog._runAjaxRequest(content,parameters,Dialog.alert);return}
content=content||"";parameters=parameters||{};var okLabel=parameters.okLabel?parameters.okLabel:"Ok";parameters=Object.extend(parameters,parameters.windowParameters||{});parameters.windowParameters=parameters.windowParameters||{};parameters.className=parameters.className||"alert";var okButtonClass="class ='"+(parameters.buttonClass?parameters.buttonClass+" ":"")+" ok_button'"
var content="\
      <div class='"+parameters.className+"_message'>"+content+"</div>\
        <div class='"+parameters.className+"_buttons'>\
          <input type='button' value='"+okLabel+"' onclick='Dialog.okCallback()' "+okButtonClass+"/>\
        </div>";return this._openDialog(content,parameters)},info:function(content,parameters){if(content&&typeof content!="string"){Dialog._runAjaxRequest(content,parameters,Dialog.info);return}
content=content||"";parameters=parameters||{};parameters=Object.extend(parameters,parameters.windowParameters||{});parameters.windowParameters=parameters.windowParameters||{};parameters.className=parameters.className||"alert";var content="<div id='modal_dialog_message' class='"+parameters.className+"_message'>"+content+"</div>";if(parameters.showProgress)
content+="<div id='modal_dialog_progress' class='"+parameters.className+"_progress'>  </div>";parameters.ok=null;parameters.cancel=null;return this._openDialog(content,parameters)},setInfoMessage:function(message){$('modal_dialog_message').update(message);},closeInfo:function(){Windows.close(this.dialogId);},_openDialog:function(content,parameters){var className=parameters.className;if(!parameters.height&&!parameters.width){parameters.width=WindowUtilities.getPageSize(parameters.options.parent||document.body).pageWidth/2;}
if(parameters.id)
this.dialogId=parameters.id;else{var t=new Date();this.dialogId='modal_dialog_'+t.getTime();parameters.id=this.dialogId;}
if(!parameters.height||!parameters.width){var size=WindowUtilities._computeSize(content,this.dialogId,parameters.width,parameters.height,5,className)
if(parameters.height)
parameters.width=size+5
else
parameters.height=size+5}
parameters.effectOptions=parameters.effectOptions;parameters.resizable=parameters.resizable||false;parameters.minimizable=parameters.minimizable||false;parameters.maximizable=parameters.maximizable||false;parameters.draggable=parameters.draggable||false;parameters.closable=parameters.closable||false;var win=new Window(parameters);win.getContent().innerHTML=content;win.showCenter(true,parameters.top,parameters.left);win.setDestroyOnClose();win.cancelCallback=parameters.onCancel||parameters.cancel;win.okCallback=parameters.onOk||parameters.ok;return win;},_getAjaxContent:function(originalRequest){Dialog.callFunc(originalRequest.responseText,Dialog.parameters)},_runAjaxRequest:function(message,parameters,callFunc){if(message.options==null)
message.options={}
Dialog.onCompleteFunc=message.options.onComplete;Dialog.parameters=parameters;Dialog.callFunc=callFunc;message.options.onComplete=Dialog._getAjaxContent;new Ajax.Request(message.url,message.options);},okCallback:function(){var win=Windows.focusedWindow;if(!win.okCallback||win.okCallback(win)){$$("#"+win.getId()+" input").each(function(element){element.onclick=null;})
win.close();}},cancelCallback:function(){var win=Windows.focusedWindow;$$("#"+win.getId()+" input").each(function(element){element.onclick=null})
win.close();if(win.cancelCallback)
win.cancelCallback(win);}}
if(Prototype.Browser.WebKit){var array=navigator.userAgent.match(new RegExp(/AppleWebKit\/([\d\.\+]*)/));Prototype.Browser.WebKitVersion=parseFloat(array[1]);}
var WindowUtilities={getWindowScroll:function(parent){var T,L,W,H;parent=parent||document.body;if(parent!=document.body){T=parent.scrollTop;L=parent.scrollLeft;W=parent.scrollWidth;H=parent.scrollHeight;}
else{var w=window;with(w.document){if(w.document.documentElement&&documentElement.scrollTop){T=documentElement.scrollTop;L=documentElement.scrollLeft;}else if(w.document.body){T=body.scrollTop;L=body.scrollLeft;}
if(w.innerWidth){W=w.innerWidth;H=w.innerHeight;}else if(w.document.documentElement&&documentElement.clientWidth){W=documentElement.clientWidth;H=documentElement.clientHeight;}else{W=body.offsetWidth;H=body.offsetHeight}}}
return{top:T,left:L,width:W,height:H};},getPageSize:function(parent){parent=parent||document.body;var windowWidth,windowHeight;var pageHeight,pageWidth;if(parent!=document.body){windowWidth=parent.getWidth();windowHeight=parent.getHeight();pageWidth=parent.scrollWidth;pageHeight=parent.scrollHeight;}
else{var xScroll,yScroll;if(window.innerHeight&&window.scrollMaxY){xScroll=document.body.scrollWidth;yScroll=window.innerHeight+window.scrollMaxY;}else if(document.body.scrollHeight>document.body.offsetHeight){xScroll=document.body.scrollWidth;yScroll=document.body.scrollHeight;}else{xScroll=document.body.offsetWidth;yScroll=document.body.offsetHeight;}
if(self.innerHeight){windowWidth=self.innerWidth;windowHeight=self.innerHeight;}else if(document.documentElement&&document.documentElement.clientHeight){windowWidth=document.documentElement.clientWidth;windowHeight=document.documentElement.clientHeight;}else if(document.body){windowWidth=document.body.clientWidth;windowHeight=document.body.clientHeight;}
if(yScroll<windowHeight){pageHeight=windowHeight;}else{pageHeight=yScroll;}
if(xScroll<windowWidth){pageWidth=windowWidth;}else{pageWidth=xScroll;}}
return{pageWidth:pageWidth,pageHeight:pageHeight,windowWidth:windowWidth,windowHeight:windowHeight};},disableScreen:function(className,overlayId,overlayOpacity,contentId,parent){WindowUtilities.initLightbox(overlayId,className,function(){this._disableScreen(className,overlayId,overlayOpacity,contentId)}.bind(this),parent||document.body);},_disableScreen:function(className,overlayId,overlayOpacity,contentId){var objOverlay=$(overlayId);var pageSize=WindowUtilities.getPageSize(objOverlay.parentNode);if(contentId&&Prototype.Browser.IE){WindowUtilities._hideSelect();WindowUtilities._showSelect(contentId);}
objOverlay.style.height=(pageSize.pageHeight+'px');objOverlay.style.display='none';if(overlayId=="overlay_modal"&&Window.hasEffectLib&&Windows.overlayShowEffectOptions){objOverlay.overlayOpacity=overlayOpacity;new Effect.Appear(objOverlay,Object.extend({from:0,to:overlayOpacity},Windows.overlayShowEffectOptions));}
else
objOverlay.style.display="block";},enableScreen:function(id){id=id||'overlay_modal';var objOverlay=$(id);if(objOverlay){if(id=="overlay_modal"&&Window.hasEffectLib&&Windows.overlayHideEffectOptions)
new Effect.Fade(objOverlay,Object.extend({from:objOverlay.overlayOpacity,to:0},Windows.overlayHideEffectOptions));else{objOverlay.style.display='none';objOverlay.parentNode.removeChild(objOverlay);}
if(id!="__invisible__")
WindowUtilities._showSelect();}},_hideSelect:function(id){if(Prototype.Browser.IE){id=id==null?"":"#"+id+" ";$$(id+'select').each(function(element){if(!WindowUtilities.isDefined(element.oldVisibility)){element.oldVisibility=element.style.visibility?element.style.visibility:"visible";element.style.visibility="hidden";}});}},_showSelect:function(id){if(Prototype.Browser.IE){id=id==null?"":"#"+id+" ";$$(id+'select').each(function(element){if(WindowUtilities.isDefined(element.oldVisibility)){try{element.style.visibility=element.oldVisibility;}catch(e){element.style.visibility="visible";}
element.oldVisibility=null;}
else{if(element.style.visibility)
element.style.visibility="visible";}});}},isDefined:function(object){return typeof(object)!="undefined"&&object!=null;},initLightbox:function(id,className,doneHandler,parent){if($(id)){Element.setStyle(id,{zIndex:Windows.maxZIndex+1});Windows.maxZIndex++;doneHandler();}
else{var objOverlay=document.createElement("div");objOverlay.setAttribute('id',id);objOverlay.className="overlay_"+className
objOverlay.style.display='none';objOverlay.style.position='absolute';objOverlay.style.top='0';objOverlay.style.left='0';objOverlay.style.zIndex=Windows.maxZIndex+1;Windows.maxZIndex++;objOverlay.style.width='100%';parent.insertBefore(objOverlay,parent.firstChild);if(Prototype.Browser.WebKit&&id=="overlay_modal"){setTimeout(function(){doneHandler()},10);}
else
doneHandler();}},setCookie:function(value,parameters){document.cookie=parameters[0]+"="+escape(value)+
((parameters[1])?"; expires="+parameters[1].toGMTString():"")+
((parameters[2])?"; path="+parameters[2]:"")+
((parameters[3])?"; domain="+parameters[3]:"")+
((parameters[4])?"; secure":"");},getCookie:function(name){var dc=document.cookie;var prefix=name+"=";var begin=dc.indexOf("; "+prefix);if(begin==-1){begin=dc.indexOf(prefix);if(begin!=0)return null;}else{begin+=2;}
var end=document.cookie.indexOf(";",begin);if(end==-1){end=dc.length;}
return unescape(dc.substring(begin+prefix.length,end));},_computeSize:function(content,id,width,height,margin,className){var objBody=document.body;var tmpObj=document.createElement("div");tmpObj.setAttribute('id',id);tmpObj.className=className+"_content";if(height)
tmpObj.style.height=height+"px"
else
tmpObj.style.width=width+"px"
tmpObj.style.position='absolute';tmpObj.style.top='0';tmpObj.style.left='0';tmpObj.style.display='none';tmpObj.innerHTML=content;objBody.insertBefore(tmpObj,objBody.firstChild);var size;if(height)
size=$(tmpObj).getDimensions().width+margin;else
size=$(tmpObj).getDimensions().height+margin;objBody.removeChild(tmpObj);return size;}}
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:'home',url:'',valid:true,title:'home panel',noServer:false},{id:'speeddate',url:'',valid:true,title:'',noServer:true},{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},{id:'popup',url:'',valid:false,title:'popup 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,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);$('popup-div').observe('click',function(e){self.location=this.pageUrl+'#close-popup';}.bind(this));if(SD.BrowserDetect.OS!='Mac'){$('popup-div').addClassName('no-mac');}
$$('.menu-title.with-arrow').each(function(e){(new SD.MenuController(e.up('span'),e.up('li').select('ul').first()));});this.updateUrls(document.body);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);}});},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));$(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));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;}
if(url=='#close-popup'){this.activePath=this.activePathOld;this.activePathOld=null;if(!this.activePath){this.activePath='#';}
self.location=this.pageUrl+this.activePath;this.trackAnalytics();return;}
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;}
if(panel.id=='popup'){if(!this.activePathOld){this.activePathOld=activePathOld;}
if(!panel.valid||realUrl!=panel.url){this.updatePanelTitle(this.sLoading);this.loadContent($('content-'+panel.id),realUrl);}}else{this.activePathOld=null;this.activate(panel.id);if(!panel.noServer){if(!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;},activate:function(panelId){this.activePanelId=panelId;this.updatePanelTitle(null);$$('#primary-navigation > li').invoke('removeClassName','current');this.panels.each(function(p){if(p.id!='popup'){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.NewHomepageTest2187.value;if(experimentValue==0){}else if((experimentValue==1&&panelId=='speeddate')||(experimentValue==2&&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'};
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){var base=SD.Config.getLinkBase(controller,action);var params=arguments.length>2?arguments[2]:null;return!params?base:base+'&'+this.queryString(params);};this.linkSecure=function(controller,action){var base=SD.Config.getLinkBase(controller,action);base=base.replace(/http:\/\/[^\/]+\//i,'/');var params=arguments.length>2?arguments[2]:null;return!params?base:base+'&'+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()});}
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';}},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.IE){this.iframe=$(document.createElement('IFRAME'));this.iframe.style.position=this.optionsDiv.style.position;this.optionsDiv.parentNode.insertBefore(this.iframe,this.optionsDiv);this.iframe.addClassName('menu-iframe');this.iframe.clonePosition(this.optionsDiv);}
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;if(this.iframe){this.iframe.parentNode.removeChild(this.iframe);}
this.iframe=null;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.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'));},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.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();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){var bases=$$('.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.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++){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){return document.observe(eventName,function(event){if((source===event.memo.source)||!source){callback({name:eventName,memo:event.memo.memo,source:event.memo.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();}};
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,isOnline: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));(new PeriodicalExecuter(this.checkFlirteeInterest.bind(this),5));SD.User.Stats.init();},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'}};
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"},SD.ProfileViewer.UI.yearsSince(user.birthday)+" 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"},SD.ProfileViewer.UI.yearsSince(user.birthday)+" 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:670,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'},SD.ProfileViewer.UI.yearsSince(user.birthday))),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.isOnline?'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);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{if(SD.ExperimentManager.PhotoUploadTriggerMore2109.value&&!SD.Model.getMyself().has_photo){SD.Dialogs.dialogUploadPhotoMore(SD.Dialogs.photoUploadReasons.NON_PRIMARY_PHOTO);}else{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();console.log("can-flirt=",user.relation.permissions.can_flirt," can_wink=",user.relation.permissions.can_wink," am i premium=",SD.Model.getMyself().is_premium);if((!user.relation.permissions.can_flirt||!user.relation.permissions.can_wink)&&!SD.Model.getMyself().is_premium){if(SD.ExperimentManager.CommunicationTracking1437.value){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({},DIV({"class":"overflirted-message"},upgradeLink2=A({},"Upgrade to contact me"),BR(),"I only accept messages from premium members"));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.Constants.trackingCodes.over_flirted_link,'tobj':SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.CONTACT_OVER_FLIRTED_PROFILE)});});}}
else{overFlirtContents=DIV();newContents=DIV({"class":"profile-content"},overFlirtContents,profileImages,SD.ProfileViewer.UI.renderMemberInfo(user));}
if(SD.ExperimentManager.MinimizePopUps1048.value>0&&SD.Config.platform.platformId!=3){newContents=DIV({"class":"profile-content"},profileImages,SD.ProfileViewer.UI.renderMemberInfo(user));}
if(user.show_as_premium){newContents.addClassName("premium");}
return newContents;};SD.ProfileViewer.UI.renderMemberInfo=function(user){var profileTbody,profileInfoTable;profileInfoTable=TABLE({"class":"profile-table"},profileTbody=TBODY());$A(user.member_info).each(function(mi){var textTD=TD();$A(mi.text_value.split(/\\+[nr]|\n|\r/)).each(function(line){line=line.replace(/\\/g,'');line=line.strip();if(line){textTD.insert(DIV({},line));}});if(mi.title=='Last visit'&&user.isOnline){var textTD=TD();textTD.insert(DIV({},'Online now!'));}
profileTbody.insert(TR({},TH({},mi.title+":"),textTD));});return profileInfoTable;};SD.ProfileViewer.UI.renderMemberInfoVertical=function(user,className){var profileTbody,profileInfoTable;profileInfoTable=TABLE({'class':className},profileTbody=TBODY());$A(user.member_info).each(function(mi){var textTD=TD();$A(mi.text_value.split(/\\+[nr]|\n|\r/)).each(function(line){line=line.replace(/\\/g,'');line=line.strip();if(line){profileTbody.insert(TR({},TH({},mi.title+':')));if(mi.title=='Last visit'&&user.isOnline){line='Online now!';}
profileTbody.insert(TR({},TD({},line)));}});});return profileInfoTable;};SD.ProfileViewer.UI.yearsSince=function(then){return Math.floor((new Date().getTime()-then)/(365.25*24*60*60*1000));};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(){var _flirtees=[];var _myself=null;var _flirteesCurrentIndex=0;var _flirteesLastPreloadedIndex=0;var _flirteesBufferSize=20;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-_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.BuddyList.Events.USER_AVAILABLE,function(e){SD.FlirtWink.Controller.setFlirteeOnline(e.memo.user.uid,true);});SD.Event.observe(null,SD.BuddyList.Events.USER_UNAVAILABLE,function(e){SD.FlirtWink.Controller.setFlirteeOnline(e.memo.user.uid,false);});renewCanMakeRequest();SD.User.getNextFlirts(_myself);};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,isOnline){for(var i=0;i<_flirtees.length;i++){if(_flirtees[i].uid==flirteeId){_flirtees[i].isOnline=isOnline;}}};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);SD.DatingController.clearMatched();}
onResponse(result);}}));};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);}}));};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();}else{onFailure();}},onFailure:onFailure}));};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.isOnline!='undefined'){SD.FlirtWink.Controller.setFlirteeOnline(flirtee.uid,flirtee.isOnline);}
insertFlirteeAsCurrent(flirtee);SD.Event.fire(null,SD.FlirtWink.Events.FLIRTEES_FETCH_END);});}}}else{updateHash(this.getCurrentFlirtee().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'};
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){_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.ExperimentManager.DateButtonNotifications2083.value==1){SD.FlirtWink.Controller.adddate(oUser,{'other_memberid':oUser.uid});}
if(SD.Model.getMyself().is_premium){SD.Dialogs.dialogAddToDates(oUser,onSuccess);}else{if(SD.ExperimentManager.DateButtonNotifications2083.value==1){SD.Dialogs.dialogUpgradeToSpeeddate(oUser);}else if(SD.ExperimentManager.OrderFormPopupFlirtWinkDate1725.value==3){SD.SubscriptionDialogs.dialogUpgradeToDate({'user':oUser});}else{SD.Dialogs.dialogAddToDates(oUser,onSuccess);}}};this.dontNeedUpgradeForChat=function(oUser){return SD.Model.getMyself().is_premium||SD.Chat.didIChatBefore(oUser.uid)||(SD.BuddyList.Controller.isBuddy(oUser)&&!SD.ExperimentManager.MatchRestrictionRedo1735.value);};this.chat=function(oUser,onSuccess){if(!oUser.isOnline){return;}
if(!SD.FlirtWink.View.dontNeedUpgradeForChat(oUser)){if(SD.ExperimentManager.PhotoUploadTriggerMore2109.value&&!SD.Model.getMyself().has_photo){SD.Dialogs.dialogUploadPhotoMore(SD.Dialogs.photoUploadReasons.CHAT);}else{SD.log(oUser);SD.UIController.upgradeMyself({'ti':oUser.uid,'tc':SD.Constants.trackingCodes.site_dating_panel_chat_button,'tobj':SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.CHAT_BUTTON_DATING)});}}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.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){if(SD.ExperimentManager.EncourageEmailValidation1079.value&&(SD.Model.getMyself().has_bounced||!SD.Model.getMyself().has_verified)){SD.Dialogs.dialogVerifyEmailToContinue('wink');}else{if(!SD.Model.getMyself().has_photo){SD.Dialogs.dialogUploadPhotoToContinue();}else{if(SD.ExperimentManager.AboutMePopupExp2203.value&&!SD.Model.getMyself().has_about_me){SD.Dialogs.dialogFillAboutMeToContinue();}else{var oUser=getOtherUser();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(!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){if(SD.ExperimentManager.EncourageEmailValidation1079.value&&(SD.Model.getMyself().has_bounced||!SD.Model.getMyself().has_verified)){SD.Dialogs.dialogVerifyEmailToContinue('flirt');}else{if(!SD.Model.getMyself().has_photo){SD.Dialogs.dialogUploadPhotoToContinue();}else{if(SD.ExperimentManager.AboutMePopupExp2203.value&&!SD.Model.getMyself().has_about_me){SD.Dialogs.dialogFillAboutMeToContinue();}else{var oUser=getOtherUser();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.relation.permissions){if(SD.ExperimentManager.MinimizePopUps1048.value!=2&&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){if(SD.ExperimentManager.EncourageEmailValidation1079.value&&(SD.Model.getMyself().has_bounced||!SD.Model.getMyself().has_verified)){SD.Dialogs.dialogVerifyEmailToContinue('date');}else{if(!SD.Model.getMyself().has_photo){SD.Dialogs.dialogUploadPhotoToContinue();}else{if(SD.ExperimentManager.AboutMePopupExp2203.value&&!SD.Model.getMyself().has_about_me){SD.Dialogs.dialogFillAboutMeToContinue();}else{var oUser=getOtherUser();SD.FlirtWink.View.date(oUser,onSuccess);}}}});oElement.observe('mouseover',function(e){SD.Tooltip.hide();if(o&&o.classMouseOver){e.target.addClassName(o.classMouseOver);}
if(SD.ExperimentManager.MinimizePopUps1048.value<2&&SD.Config.platform.platformId!=3){if(!SD.Model.getMyself().has_photo){SD.Tooltip.show('Set up a date with <b>'+
getOtherUser().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>'+getOtherUser().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>'+
getOtherUser().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.registerInputChat=function(oElement,getOtherUser,onSuccess,o){oElement=$(oElement);getOtherUser=getOtherUser||function(){return _flirtee;};onSuccess=onSuccess||function(){};o=o||{};oElement.observe('click',function(){var oUser=getOtherUser();SD.FlirtWink.View.chat(oUser,onSuccess);});oElement.observe('mouseover',function(){SD.Tooltip.hide();var oUser=getOtherUser();if(!oUser.isOnline){SD.Tooltip.show('<b>'+oUser.username+'</b> is offline right now.');return;}
if(!SD.FlirtWink.View.dontNeedUpgradeForChat(oUser)){if(SD.ExperimentManager.PhotoUploadTriggerMore2109.value&&!SD.Model.getMyself().has_photo){}else{SD.Tooltip.show('<b>Upgrade</b> your membership to chat with <b>'+oUser.username+'</b>.');}}else{SD.Tooltip.show('Chat with <b>'+oUser.username+'</b>');}});oElement.observe('mouseout',SD.Tooltip.hide);};this.registerInputFavorite=function(oElement,getOtherUser,onSuccess,o){oElement=$(oElement);getOtherUser=getOtherUser||function(){return _flirtee;};o=o||{};onSuccess=onSuccess||function(oElement){var oUser=getOtherUser();SD.Tooltip.show('Added!');oElement.addClassName('secondarybutton-favorite-inactive');};oElement.observe('click',function(e){var oUser=getOtherUser();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.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;};var oUser=getOtherUser();oElement.observe('click',function(oUser){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.isOnline){oElement.removeClassName('secondarybutton-chat-inactive');}else{oElement.addClassName('secondarybutton-chat-inactive');}});};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);if(SD.ExperimentManager.BrowsePageRedesign2204.value==0){SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){var oFlirtee=e.memo.flirtee;oElement.update('');for(var i=0;i<oFlirtee.member_info.length;i++){oElement.appendChild(DIV({},B({},oFlirtee.member_info[i].title+': '),oFlirtee.member_info[i].text_value));}
if(oFlirtee.is_premium){$(oElement.parentNode).addClassName('featured');}else{$(oElement.parentNode).removeClassName('featured');}});}else{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].title=='More About Me'){oAboutMeElement.update('"'+oFlirtee.member_info[i].text_value+'"');}else{oElement.appendChild(DIV({},B({},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;}}else{if(SD.ExperimentManager.MinimizePopUps1048.value==1&&SD.Config.platform.platformId!=3){SD.Tooltip.show('Upgrade to view multiple photos');}}});elementThumb.observe('mouseout',function(){if(SD.ExperimentManager.MinimizePopUps1048.value==1&&SD.Config.platform.platformId!=3){SD.Tooltip.hide();}});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.ExperimentManager.MinimizePopUps1048.value==0&&SD.Config.platform.platformId!=3){if(SD.ExperimentManager.CommunicationTracking1437.value){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);}else{messageContents=SPAN({},A({},'Upgrade to contact me!'),BR(),'I only accept messages from premium members');}
oElement.observe('click',function(event){event.stop();if(SD.ExperimentManager.CommunicationTracking1437.value){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);}else{var trackingCode=SD.Constants.trackingCodes.over_flirted_link;var trackingObject=SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.CONTACT_OVER_FLIRTED_PROFILE,null,null,oElement);}
if(SD.ExperimentManager.SubscriptionDialog.value==0){SD.UIController.upgradeMyself({'ti':oFlirtee.uid,'tc':trackingCode,'tobj':trackingObject});}else{SD.SubscriptionDialogs.dialogOverflirted({'user':oFlirtee});}});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.photoUploadReasons={VIEWED_YOU:1,WANT_TO_DATE:2,NON_PRIMARY_PHOTO:3,MESSAGE_READ:4,CONTACT_NON_REPLIED:5,CHAT:6,SECOND_CHANCE:7,CONTACT_MORE:8,CONTACT_OTHERS:9};this.dialogUploadPhotoMore=function(reason){var reasonSubText='contact other members.';switch(reason){case SD.Dialogs.photoUploadReasons.VIEWED_YOU:reasonSubText='see who\'s viewed their profile.';break;case SD.Dialogs.photoUploadReasons.WANT_TO_DATE:reasonSubText='see who wants to date them.';break;case SD.Dialogs.photoUploadReasons.NON_PRIMARY_PHOTO:reasonSubText='view other member\'s multiple photos.';break;case SD.Dialogs.photoUploadReasons.MESSAGE_READ:reasonSubText='see when their messages are read.';break;case SD.Dialogs.photoUploadReasons.CONTACT_NON_REPLIED:reasonSubText='contact other members.';break;case SD.Dialogs.photoUploadReasons.CHAT:reasonSubText='start a chat with other online members.';break;case SD.Dialogs.photoUploadReasons.SECOND_CHANCE:reasonSubText='get a second chance to make a match.';break;case SD.Dialogs.photoUploadReasons.CONTACT_MORE:reasonSubText='contact other users more than once.';break;case SD.Dialogs.photoUploadReasons.CONTACT_OTHERS:reasonSubText='contact other users more than once.';break;}
SD.UIController._photoUploadPopup('Upload Photo to Continue!','Only <b>members with photos</b> can <br>'+reasonSubText+'<br><br>Adding a photo to your profile also gets <br>you 10x as many responses!','Upload Photo','Later');};this.onSendFlirtClick=function(canSendFlirt,otherMemberId){if(SD.ExperimentManager.PhotoUploadTriggerMore2109.value&&!SD.Model.getMyself().has_photo){SD.Dialogs.dialogUploadPhotoMore(SD.Dialogs.photoUploadReasons.CONTACT_OTHERS);return false;}else{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(){SD.UIController._photoUploadPopup('Upload Photo to Continue!','Only <b>members with photos</b> can <br>contact other members.<br><br>Adding a photo to your profile also gets <br>you 10x as many responses!','Upload Photo','Later');};this.dialogFillAboutMeToContinue=function(){if(SD.ExperimentManager.AboutMePopupExp2203.value==1){SD.UIController.aboutMePopup(1);}else{SD.UIController.aboutMePopup(3);}}
this.dialogVerifyEmailToContinue=function(popupSource){if(SD.Model.getMyself().has_bounced){SD.UIController.emailVerificationPopup(1,popupSource);}else{SD.UIController.emailVerificationPopup(2,popupSource);}}
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)});};if(SD.ExperimentManager.MinimizePopUps1048.value>0&&SD.Config.platform.platformId!=3){go();return;}
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(){if(SD.ExperimentManager.MinimizePopUps1048.value>0&&SD.Config.platform.platformId!=3&&!user.relation.permissions.can_flirt){if(SD.ExperimentManager.CommunicationTracking1437.value){SD.UIController.upgradeMyself({'ms':'Upgrade to contact this member','ti':user.uid,'tc':SD.Constants.trackingCodes.over_flirted_link,'tobj':SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.CONTACT_OVER_FLIRTED_PROFILE)});}else{SD.UIController.upgradeMyself({'ms':'Upgrade to contact this member','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)});}
return;}
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;};sFlirtSubmitTooltip='';if(SD.ExperimentManager.MinimizePopUps1048.value==1&&SD.Config.platform.platformId!=3){switch(user.relation.permissions.flirt_restriction_reason){case 10:sFlirtSubmitTooltip='Upgrade your membership to flirt with '+user.username;break;case 30:sFlirtSubmitTooltip='Only premium members can contact members who haven\'t yet replied. '+'Upgrade to send another message to '+user.username;break;}}
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(){if(SD.ExperimentManager.CommunicationTracking1437.value){SD.UIController.upgradeMyself({'ti':user.uid,'tc':SD.Constants.trackingCodes.over_flirted_link,'tobj':SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.CONTACT_OVER_FLIRTED_PROFILE)});}else{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='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='';if(SD.ExperimentManager.CommunicationTracking1437.value){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);}else{link=A({},'premium members');link.observe('click',function(){SD.UIController.upgradeMyself({'ti':user.uid,'tc':SD.Constants.trackingCodes.over_flirted_link,'tobj':SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.CONTACT_OVER_FLIRTED_PROFILE)});});overflirtedMessage=DIV({'class':'overflirted-message'},'Only ',link,' can send messages to this member.');}
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,flirtForm=FORM({},DIV({'class':'call-to-action'},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,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{}
if(SD.ExperimentManager.MinimizePopUps1048.value==1&&SD.Config.platform.platformId!=3){btnFlirt.value='Send';}
btnFlirt.observe('click',function(){if(SD.ExperimentManager.CommunicationTracking1437.value){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{SD.UIController.upgradeMyself({'ti':user.uid,'ms':getMessage(),'ab':flirtForm.addbuddy.value,'gi':getGiftId(),'tc':SD.Constants.trackingCodes.over_flirted_link,'tobj':SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.CONTACT_OVER_FLIRTED_PROFILE)});}
win.close();});}else{(function(){flirtForm.flirt_msg[3].checked=true;}).defer();btnFlirt.disabled=true;btnFlirt.observe('click',function(){if(flirtForm.flirt_msg[3].checked){if(user.relation.permissions.can_type_in_flirt){user.relation.permissions.can_type_in_flirt=false;user.relation.permissions.can_canned_flirt=false;SD.FlirtWink.Controller.flirt(user,getMessage(),getFlirtID(),flirtForm.addbuddy.checked,getGiftId(),SD.UIController.platform_id,onSuccess);}else{if(SD.ExperimentManager.CommunicationTracking1437.value){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{SD.UIController.upgradeMyself({'ti':user.uid,'ms':getMessage(),'ab':flirtForm.addbuddy.value,'gi':getGiftId(),'tc':SD.Constants.trackingCodes.over_flirted_link,'tobj':SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.CONTACT_OVER_FLIRTED_PROFILE)});}}}else{if(user.relation.permissions.can_canned_flirt){user.relation.permissions.can_type_in_flirt=false;user.relation.permissions.can_canned_flirt=false;SD.FlirtWink.Controller.flirt(user,getMessage(),getFlirtID(),flirtForm.addbuddy.checked,getGiftId(),SD.UIController.platform_id,onSuccess);}else{if(SD.ExperimentManager.CommunicationTracking1437.value){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{SD.UIController.upgradeMyself({'ti':user.uid,'ms':getMessage(),'ab':flirtForm.addbuddy.value,'gi':getGiftId(),'tc':SD.Constants.trackingCodes.over_flirted_link,'tobj':SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.CONTACT_OVER_FLIRTED_PROFILE)});}}}
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();win=SD.UIController.standardPopup({title:'Flirt with '+user.username,draggable:true,width:375,height:375,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);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._fillAboutMeStepOnePopup=function(){var title='Fill the form';var message='We need more information before you will truly get all the benefits out of SpeedDate.com. Tell us about yourself:';var buttonLabel='Save';var cancelButtonLabel='Later';var win=this.standardPopup({title:title,'width':500,closable:true});var go=function(){this.saveAboutMe();};var exp=DIV({"class":"upload-photo-message"});exp.insert(message);var aboutMeFormContent='<div>'+'<form id="about-me-form-in-popup" method="post" action="'+SD.NavUtils.link('profile','save_aboutme')+'"><table class="profile-table"><tbody>'+'<table class="profile-table"><tbody><tr><th><label for="member_info[14]">Body Style&nbsp;:</label></th><td><select name="member_info[14]"><option value="-1">-- Select One --</option><option value="208">Slender</option><option value="209">About Average</option><option value="210">Athletic / Toned</option><option value="211">A Few Extra Pounds</option><option value="212">Heavy set</option><option value="213">Cuddly</option><option value="215">Husky</option><option value="216">Petite</option><option value="217">Voluptuous</option><option value="218">Muscular</option><option value="219">Modelesque</option></select></td></tr><tr><th><label for="member_info[12]">Height&nbsp;:</label></th><td><select name="member_info[12]"><option value="-1">-- Select One --</option><option value="74">&lt; 4\'6"(137cm)</option><option value="75">4\'6"(137cm)</option><option value="76">4\'7"(140cm)</option><option value="77">4\'8"(142cm)</option><option value="78">4\'9"(145cm)</option><option value="79">4\'10"(147cm)</option><option value="80">4\'11"(150cm)</option><option value="81">5\'0"(152cm)</option><option value="82">5\'1"(155cm)</option><option value="83">5\'2"(157cm)</option><option value="84">5\'3"(160cm)</option><option value="85">5\'4"(163cm)</option><option value="86" selected="selected">5\'5"(165cm)</option><option value="87">5\'6"(168cm)</option><option value="88">5\'7"(170cm)</option><option value="89">5\'8"(173cm)</option><option value="90">5\'9"(175cm)</option><option value="91">5\'10"(178cm)</option><option value="92">5\'11"(180cm)</option><option value="93">6\'0"(183cm)</option><option value="94">6\'1"(185cm)</option><option value="95">6\'2"(188cm)</option><option value="96">6\'3"(191cm)</option><option value="97">6\'4"(193cm)</option><option value="98">6\'5"(196cm)</option><option value="99">6\'6"(198cm)</option><option value="100">6\'7"(201cm)</option><option value="101">6\'8"(203cm)</option><option value="102">6\'9"(206cm)</option><option value="103">6\'10"(208cm)</option><option value="104">6\'11"(211cm)</option><option value="105">7\'0"(213cm)</option><option value="106">&gt; 7\'0"(213cm)</option></select></td></tr><tr><th><label for="member_info[8]">Ethnicity&nbsp;:</label></th><td><div class="dropdown"><div class="text">White/Caucasian</div></div><select name="member_info[8][]" multiple="multiple" size="4"><option value="37">Asian</option><option value="38">Black/African Descent</option><option value="39">East Indian</option><option value="40">Latino/Hispanic</option><option value="41">Native American</option><option value="42">Pacific Islander</option><option value="43" selected="selected">White/Caucasian</option><option value="44">Other</option></select></td></tr><tr><th><label for="member_info[1]">More About Me&nbsp;:</label></th><td><textarea name="member_info[1]" cols="40" rows="2"></textarea></td></tr></tbody></table>'+'</tbody></table>'+'<input type="submit" value="Save" />'+'<input type="hidden" name="aboutme_from_popup" value="1" />'+'<input type="hidden" name="win_name" value="'+win.getId()+'" />'+'<input type="hidden" name="return_url_after_upload" value="'+encodeURIComponent(window.location.href)+'" />'+'</form>'+'</div>';exp.insert(aboutMeFormContent);win.getContent().insert(DIV({"class":"upgradepop"},exp));win.showCenter(true,200);SD.Nav.updateUrls(exp);};this.saveAboutMe=function(){$('about-me-form-in-popup').submit();};this.dialogUpgradeToContact=function(uid){if(SD.ExperimentManager.PhotoUploadTriggerMore2109.value&&!SD.Model.getMyself().has_photo){SD.Dialogs.dialogUploadPhotoMore(SD.Dialogs.photoUploadReasons.CONTACT_MORE);}else{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)};}
if(SD.ExperimentManager.MinimizePopUps1048.value>0&&SD.Config.platform.platformId!=3){SD.UIController.upgradeMyself(trackingCode);return;}
SD.UIController._popupGenericWarning('Upgrade to contact '+user.username+'!',trackingCode,[' can ',BR(),' contact other users more than once.']);}};this.dialogUpgradeToSeeDateYou=function(){if(SD.ExperimentManager.PhotoUploadTriggerMore2109.value&&!SD.Model.getMyself().has_photo){SD.Dialogs.dialogUploadPhotoMore(SD.Dialogs.photoUploadReasons.WANT_TO_DATE);}else{var trackingCode={'tc':SD.Constants.trackingCodes.want_to_date_view,'tobj':SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.WANT_TO_DATE_YOU_MEMBERS)};if(SD.ExperimentManager.MinimizePopUps1048.value>0&&SD.Config.platform.platformId!=3){SD.UIController.upgradeMyself(trackingCode);return;}
SD.UIController._popupGenericWarning('Upgrade to see who wants to date you!',trackingCode,[' can ',BR(),' see who wants to date them.']);}};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)});};if(SD.ExperimentManager.MinimizePopUps1048.value>0&&SD.Config.platform.platformId!=3){SD.UIController.upgradeMyself(trackingCode);return;}
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(){if(SD.ExperimentManager.PhotoUploadTriggerMore2109.value&&!SD.Model.getMyself().has_photo){SD.Dialogs.dialogUploadPhotoMore(SD.Dialogs.photoUploadReasons.VIEWED_YOU);}else{var ua={'tc':SD.Constants.trackingCodes.viewed_you,'tobj':SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.VIEWED_YOU_MEMBERS)};if(SD.ExperimentManager.MinimizePopUps1048.value>0&&SD.Config.platform.platformId!=3){SD.UIController.upgradeMyself(ua);return;}
SD.UIController._popupGenericWarning('Upgrade to see who viewed your profile!',ua,['&nbsp;can ',BR(),' see who\'s viewed their profile.']);}};this.dialogUpgradeToViewPhotos=function(user){if(SD.ExperimentManager.PhotoUploadTriggerMore2109.value&&!SD.Model.getMyself().has_photo){SD.Dialogs.dialogUploadPhotoMore(SD.Dialogs.photoUploadReasons.NON_PRIMARY_PHOTO);}else{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};if(SD.ExperimentManager.MinimizePopUps1048.value>0&&SD.Config.platform.platformId!=3){SD.UIController.upgradeMyself(ua);return;}
SD.UIController._popupGenericWarning('Upgrade to view '+user.username+'\'s photos!',ua,[' can view multiple photos.'],'Upgrade to view');}};this.dialogMessagesRead=function(uid){if(SD.ExperimentManager.PhotoUploadTriggerMore2109.value&&!SD.Model.getMyself().has_photo){SD.Dialogs.dialogUploadPhotoMore(SD.Dialogs.photoUploadReasons.MESSAGE_READ);}else{var ua={'tc':SD.Constants.trackingCodes.upgrade_button_message_read,'ti':uid,'tobj':SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.SEE_WHEN_MESSAGES_READ)};if(SD.ExperimentManager.MinimizePopUps1048.value>0&&SD.Config.platform.platformId!=3){SD.UIController.upgradeMyself(ua);return;}
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){if(SD.ExperimentManager.PhotoUploadTriggerMore2109.value&&!SD.Model.getMyself().has_photo){SD.Dialogs.dialogUploadPhotoMore(SD.Dialogs.photoUploadReasons.CONTACT_NON_REPLIED);}else{var user=SD.User.get(uid);if(SD.ExperimentManager.MinimizePopUps1048.value>0&&SD.Config.platform.platformId!=3){SD.UIController.upgradeMyself({'ti':user.uid,'ms':message,'tc':SD.Constants.trackingCodes.upgrade_pop_up_different_country,'tobj':SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.DIFFERENT_COUNTRY_MEMBERS)});return;}
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)};if(SD.ExperimentManager.MinimizePopUps1048.value>0&&SD.Config.platform.platformId!=3){SD.UIController.upgradeMyself(ua);return;}
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',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.NewHomepageTest2187.value==1||SD.ExperimentManager.NewHomepageTest2187.value==2){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.NewHomepageTest2187.value==1||SD.ExperimentManager.NewHomepageTest2187.value==2){$('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.Event.fire(null,SD.UserFilters.UI.Events.START_SPEEDDATING);}else{SD.Event.fire(null,SD.UserFilters.UI.Events.PAUSE_SPEEDDATING);}},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.NewHomepageTest2187.value==1||SD.ExperimentManager.NewHomepageTest2187.value==2){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.NewHomepageTest2187.value==1||SD.ExperimentManager.NewHomepageTest2187.value==2){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').show();$('upcoming-text').show();}else{$('upcoming-dates').hide();$('upcoming-text').hide();}
if(SD.ExperimentManager.NewHomepageTest2187.value==1||SD.ExperimentManager.NewHomepageTest2187.value==2){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.Event.fire(null,SD.UserFilters.UI.Events.START_SPEEDDATING);}else{SD.Event.fire(null,SD.UserFilters.UI.Events.PAUSE_SPEEDDATING);}},startSpeedDating:function(){if(this.buttonState=="paused"){SD.Event.fire(null,SD.UserFilters.UI.Events.START_SPEEDDATING);}},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);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));SD.Event.observe(null,SD.PremiumChat.Events.USER_AVAILABLE,function(e){var user=e.memo.user;user.online=true;SD.Event.fire(null,SD.BuddyList.Events.USER_AVAILABLE,{user:user});SD.Event.fireDeferred(null,SD.BuddyList.Events.BUDDY_COUNT_CHANGE,{'countOnline':SD.BuddyList.Controller.getOnlineCount(),'countTotal':SD.BuddyList.Controller.getTotalCount()});});SD.Event.observe(null,SD.PremiumChat.Events.USER_UNAVAILABLE,function(e){var user=e.memo.user;user.online=false;SD.Event.fire(null,SD.BuddyList.Events.USER_UNAVAILABLE,{user:user});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);if(user){user=this.getBuddyById(user.uid);user.isOnline=true;var memo={user:user,show:flexEvent.getData().getShow(),status:flexEvent.getData().getStatus(),priority:flexEvent.getData().getPriority()};SD.Event.fire(null,SD.BuddyList.Events.USER_AVAILABLE,memo);SD.Event.fireDeferred(null,SD.BuddyList.Events.BUDDY_COUNT_CHANGE,{'countOnline':SD.BuddyList.Controller.getOnlineCount(),'countTotal':SD.BuddyList.Controller.getTotalCount()});}};this.onUserUnavailable=function(flexEvent){SD.log('user unavailable:'+flexEvent.getJid().getResource());var jidString=SD.XMPP.jidToString(flexEvent.getJid());var user=SD.User.getByChatID(jidString);if(user){user=this.getBuddyById(user.uid);user.isOnline=false;SD.Event.fire(null,SD.BuddyList.Events.USER_UNAVAILABLE,{user:user});SD.Event.fireDeferred(null,SD.BuddyList.Events.BUDDY_COUNT_CHANGE,{'countOnline':SD.BuddyList.Controller.getOnlineCount(),'countTotal':SD.BuddyList.Controller.getTotalCount()});}};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){var jidString=SD.XMPP.jidToString(flexEvent.getJid());var memo={user:SD.User.getByChatID(jidString)};if(!memo.user.onlineKnown){memo.user.isOnline=true;memo.user.onlineKnown=true;}
SD.Event.fire(null,SD.BuddyList.Events.USER_PRESENCE_UPDATED,memo);};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){nUid=parseInt(nUid);var oBuddy=null;_aBuddies.each(function(oBuddyParam){if(oBuddyParam.uid==nUid){oBuddy=oBuddyParam;throw $break;}});return oBuddy;};this.isBuddy=function(user){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(!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&&!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){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.isOnline){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 oBuddy;});SD.FlirtWink.View.registerInputChat(oLinkChat,function(){return oBuddy;});SD.FlirtWink.View.registerInputFlirt(oLinkFlirt,function(){return oBuddy;});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.isOnline=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.isOnline||oNodeBuddy.username.toLowerCase()>oBuddy.username.toLowerCase()){oNode.insert({'before':oBuddyElement});bInserted=true;break;}}else{if(!oNodeBuddy.isOnline&&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){if(oBuddy.isOnline==bOnline){return;}
oBuddy.isOnline=bOnline;var oElement=_hBuddyElements.get(oBuddy.uid);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.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.isOnline);};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.isOnline);}}.bind(this));SD.Event.observe(null,SD.BuddyList.Events.USER_AVAILABLE,function(e){if(e.memo.user){setBuddyOnline(e.memo.user,true);}}.bind(this));SD.Event.observe(null,SD.BuddyList.Events.USER_UNAVAILABLE,function(e){if(e.memo.user){setBuddyOnline(e.memo.user,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.isOnline&&!oSomeBuddy.bubbled){removeBuddyElement(oSomeBuddy,function(){addBuddyElement(oSomeBuddy,oSomeBuddy.isOnline);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.BuddyList.Events.USER_AVAILABLE,SD.Chat.onUserAvailable.bind(this));SD.Event.observe(null,SD.BuddyList.Events.USER_UNAVAILABLE,SD.Chat.onUserUnavailable.bind(this));SD.Event.observe(null,SD.PremiumChat.Events.USER_AVAILABLE,SD.Chat.onUserAvailable.bind(this));SD.Event.observe(null,SD.PremiumChat.Events.USER_UNAVAILABLE,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.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'));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());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();}
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.name+'</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.name+'</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){var chatInput=$("messagetext-area-"+user.uid);var sendButton=$("messagetext-button-"+user.uid);if(!chatInput||!sendButton){return;}
chatInput.disabled=true;sendButton.disabled=true;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;}
chatInput.disabled=false;sendButton.disabled=false;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].isOnline=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.name),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].isOnline){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.name.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.name),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();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);this.length=this.content.length;};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);return entries[0];};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=[];scope.pending=new Stack();scope.pendingPriority=new Stack();scope.pendingRomeos=new Stack();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=[];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){init();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(){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(){this.matches=[];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(){var src=SD.ExperimentManager.DatingPopupExp.value?$(this._datingAppName):this.app;return src;},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){if(SD.ExperimentManager.DatingPopupExp.value)return;if(this.app&&this.isDating){SD.log("supplying user data to flex, image_url:"+event.memo.user.image_url);setTimeout(function(){SD.DatingApp.app.supplyUserData(SD.User.externalize(event.memo.user));SD.log("supplied user data to flex, image_url:"+event.memo.user.image_url);},5000);}},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){if(SD.ExperimentManager.DatingPopupExp.value){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);}}else{SD.log('startDating');this.isDating=true;var myUser=configuration.myUser;var otherUser=configuration.otherUser;configuration.myUser=SD.User.externalize(myUser);configuration.otherUser=SD.User.externalize(otherUser);this.app.startDating(configuration);configuration.myUser=myUser;configuration.otherUser=otherUser;SD.Event.fire(null,SD.DatingApp.Events.START_DATE,configuration);}},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',{setupType:SD.Window.STATIC,closeMethod:SD.Window.OFFSCREEN_CLOSE,onBeforeOpen:function(win){if(win.isFirstTimeOpened){win.domContent.removeClassName("win-content-hack");win.domContent.addClassName("win-content");Prototype.Browser.Opera&&win.repaint.bind(win,win.domContent).delay(0.6);}
Prototype.Browser.FF3&&this.overflowElementsHack();}.bind(this),onBeforeClose:function(){this.datingApp('onClose').onEndDate();return true;}.bind(this),onAfterClose:function(){Prototype.Browser.FF3&&this.overflowElementsHack(true);}.bind(this),centered:true,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:SD.ProfileViewer.UI.yearsSince(user.birthday),address:SD.ProfileViewer.UI.addressOf(user),distance:SD.ProfileViewer.UI.renderDistance(user)});SD.Event.observe(null,SD.DatingApp.Events.CLOSE_DATING_WINDOW,function(event){this.win.close(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));this.win.open();},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,newAlertsHasLink){var showIf=function(show,panel){if(show){$(panel).show();}else{$(panel).hide();}};var resultsPanel;var resultsHeadline;var resultItemsPanel;var resultEntries=new Hash();var updateDisplay=function(){showIf(SD.ExperimentManager.SidebarOnLeftSide.value||((flirts>0)||(requests>0)||(resultEntries.size()>0)),headingPanel);showIf(SD.ExperimentManager.SidebarOnLeftSide.value||(flirts>0),flirtPanel);showIf(SD.ExperimentManager.SidebarOnLeftSide.value||(requests>0),requestPanel);showIf((resultEntries.size()>0),resultsPanel);SD.UIController.recoverBuddyListHeight();};if(SD.ExperimentManager.NewHomepageTest2187.value==0||SD.ExperimentManager.NewHomepageTest2187.value==3){$(target).insert(headingPanel=DIV({"class":"subheader"},"Alerts"));}else{$(target).insert(headingPanel=DIV());}
$(target).insert(flirtPanel=DIV({"class":"alert"},flirtTitle=A({"class":"alert-title"})));$(target).insert(requestPanel=DIV({"class":"alert"},requestTitle=A({"class":"alert-title"})));if(newAlertsHasLink){$(target).insert(resultsPanel=DIV({"class":"alert result"},resultsHeadline=A({"class":"alert-title"}),resultItemsPanel=DIV()));}else{$(target).insert(resultsPanel=DIV({"class":"alert result"},resultsHeadline=SPAN({"style":{"font-weight":"bold"}}),resultItemsPanel=DIV()));}
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);});Event.observe($(resultsHeadline),"click",function(){SD.Event.fire(user,SD.Alerts.UI.Events.RESULTS_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"));}};var currentEntry=null;var goPage=function(indx){var page=(currentEntry.page+indx+resultEntries.size())%resultEntries.size();resultEntries.each(function(pair){var entry=pair.value;if(entry.page==page){currentEntry=entry;}});displayResults();updateDisplay();};var displayResults=function(){if(resultEntries.size()>0){$(resultsHeadline).innerHTML="";if(resultEntries.size()==1){$(resultsHeadline).insert("1 new result");}else{$(resultsHeadline).insert(resultEntries.size()+" new results").insert(left=A({"class":"result-arrow"},"<")).insert(right=A({"class":"result-arrow"},">"));$(left).observe("click",function(event){event.stop();goPage(-1);});$(right).observe("click",function(event){event.stop();goPage(+1);});}
resultEntries.each(function(pair){var entry=pair.value;if(entry==currentEntry){$(entry.display).show();}else{$(entry.display).hide();}});}
updateDisplay();};var popupDateMatchWarning=function(matchedUser,ua){var content=DIV({"style":{'position':'relative','height':'200px'}},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({},SD.ProfileViewer.UI.yearsSince(matchedUser.birthday)+" year(s) 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({}),upgradeLink=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({className:"bluedialog",title:"",width:460});win.getContent().insert(content);win.showCenter(true,100);};var showDateResult=function(entry,success,otherUser,resultlink){if(entry){$(entry.results).removeClassName("match-unknown").removeClassName("match-no").removeClassName("match-yes").addClassName(success?"match-yes":"match-no").innerHTML="";$(entry.results).insert(SPAN({}),(success?"":"No ")+"Match!");if(success){if(!SD.Model.getMyself().is_premium&&SD.ExperimentManager.MatchRestrictionRedo1735.value){popupDateMatchWarning(otherUser,{"ti":otherUser.uid,"tc":SD.Constants.trackingCodes.match_restriction});SD.Alerts.UI.contactlink.observe('click',function(evt){evt.stop();SD.UIController.upgradeMyself({"ti":otherUser.uid,"tc":SD.Constants.trackingCodes.match_restriction,"tobj":SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.CONTACT_MATCHED_YES_PROFILE)});});}else{$("result-username-text").update("<b>"+otherUser.username.truncate(20)+"</b><br> Added to buddy list.");}}
currentEntry=entry;displayResults();updateDisplay();if($('recent-dates-box')){new Ajax.Updater($('recent-dates-box'),SD.NavUtils.link('home','recent_dates',{displayType:'ajax'}));}}else{SD.warn("Error, entry was undefined in function showDateResult().");}};SD.Event.observe(null,SD.User.Events.DATE_RESULT_FETCHED,function(event){var entry=resultEntries.get(event.memo.user.uid);showDateResult(entry,event.memo.success,event.memo.user);});SD.Event.observe(null,SD.DatingApp.Events.DATE_OVER,function(event){var reasonCode=event.memo.reasonCode;if(reasonCode!=SD.ReasonCodes.TIME_FINISHED&&reasonCode!=SD.ReasonCodes.USER_LEFT&&reasonCode!=SD.ReasonCodes.USER_DISCONNECTED){return;}
var otherUser=event.memo.otherUser;if(!otherUser||SD.Model.getMyself().mightDate(otherUser)){return;}
var entry=resultEntries.get(otherUser.uid);if(!entry){entry={};SD.Alerts.UI.contactlink=A({"class":"alert-title"},"Contact "+otherUser.username.truncate(12))
entry.display=DIV({"class":"match-container"},DIV({"class":"match"},entry.results=DIV({"class":"match-unknown"},SPAN())),DIV({"class":"img-container"},IMG({"align":"middle","src":otherUser.square_image_url})),DIV({"id":"result-username-text","class":"result-username"},SD.Alerts.UI.contactlink));$(SD.Alerts.UI.contactlink).observe("click",function(evt){evt.stop();if(SD.Model.getMyself().is_premium){SD.Nav.redirectTo(SD.NavUtils.link('messages','flirt',{id:otherUser.uid}));}else{SD.FlirtWink.UI.popupAlertContactWarning(otherUser.uid);}});$(resultItemsPanel).insert(entry.display);entry.page=resultEntries.size();resultEntries.set(otherUser.uid,entry);}
currentEntry=entry;displayResults();updateDisplay();if(reasonCode!='timeFinished'){showDateResult(entry,false);}});displayResults();displayFlirts();displayRequests();updateDisplay();return false;};SD.Alerts.UI.Events={FLIRTS_SOUGHT:"alert:flirts_sought",BUDDY_REQUESTS_SOUGHT:"alert:buddy_requests_sought",RESULTS_SOUGHT:"alert:results_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.BuddyPopup={buddy:null,popupDiv:null,showPopup:function(user,xpos,ypos){this.buddy=user;this.usernameH.innerHTML=user.username.truncate(17);this.popupDiv.style.left=(xpos-160)+'px';this.popupDiv.style.top=(ypos-10)+'px';this.popupDiv.show();if(this.buddy.isOnline){this.popupDiv.addClassName("online");}
else{this.popupDiv.removeClassName("online");}},initialize:function(target){this.popupDiv=$(target);var makeLILink=function(event_name,label){var link=A({href:"#"},label);$(link).observe("click",function(){SD.BuddyPopup.popupDiv.hide();if(event_name==SD.UIController.Events.START_CHAT_REQUESTED){if(!SD.Model.getMyself().is_premium&&SD.ExperimentManager.MatchRestrictionRedo1735.value){SD.UIController.upgradeMyself({"ti":SD.BuddyPopup.buddy.uid,"tc":SD.Constants.trackingCodes.match_restriction,"tobj":SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.CONTACT_MATCHED_YES_PROFILE)});}else{if(SD.BuddyPopup.buddy.isOnline){SD.Event.fire(null,event_name,{user:SD.BuddyPopup.buddy});}}}else if(event_name==SD.UIController.Events.SEND_FLIRT_REQUESTED){if(!SD.BuddyPopup.buddy.relation.permissions.can_flirt){if(SD.ExperimentManager.CommunicationTracking1437.value){SD.UIController.upgradeMyself({"ti":SD.BuddyPopup.buddy.uid,"tc":SD.Config.restrictionReasons[buddy.relation.permissions.flirt_restriction_reason].old_tc,"tobj":SD.Tracking.getTrackingObject(SD.Config.restrictionReasons[buddy.relation.permissions.flirt_restriction_reason].tc)});}else{SD.UIController.upgradeMyself({"ti":SD.BuddyPopup.buddy.uid,"tc":SD.Constants.trackingCodes.match_restriction,"tobj":SD.Tracking.getTrackingObject(SD.Constants.paymentTrackingIds.CONTACT_MATCHED_YES_PROFILE)});}}else{SD.Event.fire(null,event_name,{user:SD.BuddyPopup.buddy});}}else{SD.Event.fire(null,event_name,{user:SD.BuddyPopup.buddy});}});if(event_name==SD.UIController.Events.SEND_FLIRT_REQUESTED){return LI({"class":"send-message"},link);}
if(event_name==SD.UIController.Events.START_CHAT_REQUESTED){return LI({"class":"start-chat"},link);}
if(event_name==SD.UIController.Events.VIEW_PROFILE_REQUESTED){return LI({"class":"view-profile"},link);}
if(event_name==SD.UIController.Events.DELETE_BUDDY_REQUESTED){return LI({"class":"delete-buddy"},link);}
if(event_name==SD.UIController.Events.BLOCK_BUDDY_REQUESTED){return LI({"class":"block-buddy"},link);}};var content=DIV({style:{border:"thin solid gray","background-color":"white","width":"140px","padding":"5px 5px 0"}},this.usernameH=H4({style:{"padding-left":0}},""),UL({"class":"buddy-popup-list",style:{"margin-left":"0"}},makeLILink(SD.UIController.Events.SEND_FLIRT_REQUESTED,"Send Message"),makeLILink(SD.UIController.Events.START_CHAT_REQUESTED,"Chat Now"),makeLILink(SD.UIController.Events.VIEW_PROFILE_REQUESTED,"View Profile"),makeLILink(SD.UIController.Events.DELETE_BUDDY_REQUESTED,"Delete Buddy"),makeLILink(SD.UIController.Events.BLOCK_BUDDY_REQUESTED,"Block User")));this.popupDiv.insert(content);this.popupDiv.hide();this.popupDiv.observe('mouseout',this.onMouseOut.bind(this));this.popupDiv.observe('mouseover',this.onMouseOver.bind(this));},onMouseOver:function(event){this.popupDiv.show();},onMouseOut:function(event){this.popupDiv.hide();}};
SD.Feedback={UI:{logHistory:"",renderWindow:function(win,htmlbody,form){var cancelbutton=INPUT({type:"button","class":"input-button",value:"Cancel","observeClick":win.close.bind(win)});var sendbutton=INPUT({type:"button","class":"input-button",disabled:"disabled",value:"Send"});var textbox=TEXTAREA({"name":"description","observeKeyup":function(){sendbutton.disabled=textbox.value.blank();}});form.insert(textbox);form.insert(BR({}));form.insert(sendbutton);form.insert(cancelbutton);sendbutton.observe("click",function(){var params=form.serialize(true);params.log_history=SD.Feedback.UI.logHistory;params.memberid=SD.Model.getUserId();params.control_id=SD.Model.control_id;(new Ajax.Request(SD.NavUtils.linkSecure('ajax','givefeedback'),{method:'post',evalJSON:false,parameters:params}));win.close();SD.UIController.infoMessage("Your feedback has been sent. Thank you.",3);});win.getContent().insert(htmlbody);win.showCenter(true,200);},subscriptionPopup:function(){var feedBackwin=SD.UIController.standardPopup({title:"Help",width:400,height:375});var feedbackbox,feedbackform;feedbackbox=DIV({"class":"feedbackpop"},feedbackform=FORM({},feedbackMessage=DIV({"class":"feedback-message"},"Please let us know if you need help subscribing.",INPUT({"name":"feedback_type","type":"hidden","value":"PREM3"}),BR({}))));SD.Feedback.UI.renderWindow(feedBackwin,feedbackbox,feedbackform);},standardPopup:function(){var feedBackwin=SD.UIController.standardPopup({title:"Feedback",width:400,height:375});var feedbackFaqInfoHolder,feedbackMessage,feedbackform;var goToFaq=function(){feedBackwin.close();SD.UIController.goToFaq();};var dropdown=SELECT({"name":"feedback_type"},OPTION({value:"SUG"},"I have a suggestion."),OPTION({value:"FAQ"},"How do I...?"),OPTION({value:"BUG"},"Something stopped working!"),OPTION({value:"DATES"},"Faster dates, more dates."),OPTION({value:"DEL"},"Remove me from the dating pool."),OPTION({value:"TOU"},"Report offensive content/behavior."));var feedbackbox=DIV({"class":"feedbackpop"},feedbackform=FORM({},feedbackMessage=DIV({"class":"feedback-message"},"You are welcome to submit feedback to our customer support team below. Be sure to check the SpeedDate ",A({"href":"#","observeClick":goToFaq},"FAQ")," first.",feedbackFaqInfoHolder=DIV({"class":"feedbackInfoHolder"}),BR({}),dropdown,BR({}))));if(!SD.DisabledFeatures.feedbackInfo){feedbackFaqInfoHolder.insert(H2({},"Top Questions:"));feedbackFaqInfoHolder.insert(OL({},LI({},A({"observeClick":goToFaq},"How can I switch between viewing men/women?")),LI({},A({"observeClick":goToFaq},"How do I choose who I date?")),LI({},A({"observeClick":goToFaq},"Can I change my username?")),LI({},A({"observeClick":goToFaq},"How can I attract more attention?"))));feedbackFaqInfoHolder.insert(DIV({},"Find answers to more questions in our ",A({"href":"#","observeClick":goToFaq},"FAQ")," or fill out the form below:"));}
SD.Feedback.UI.renderWindow(feedBackwin,feedbackbox,feedbackform);}}};
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;});}
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);}
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)});},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,_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;this.setAvailable(data.user);},incrementFailedTries:function(uid){var data=this._premiumList.get(uid);var oldFail=data.fail;data.fail++;if(data.fail>=this.failCount){this._premiumList.unset(uid);this.setUnavailable(data.user);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){this._premiumList.set(user.uid,{fail:0,waitingReply:false,user:user});},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});}
this.setAvailable(user,true);},chatWithUsername:function(uid,username){var user=SD.User.get(uid,username,null);SD.PremiumChat.chatWithUser(user);},setAvailable:function(user,fireAlways){var old=user.isOnline;user.isOnline=true;if(!fireAlways&&!old)
SD.Event.fire(null,SD.PremiumChat.Events.USER_AVAILABLE,{user:user});},setUnavailable:function(user,fireAlways){var old=user.isOnline;user.isOnline=false;if(!fireAlways&&old)
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={_div:null,_pc:null,_currentMatch:null,_toBeClearedMatch:null,_currentMatchStatusMsg:"",SHOW_LIMIT:7,records:[],TYPE:{PENDING:1,PENDING_PRIORITY:2,PENDING_ROMEO:3,MATCH:4},scoreCnts:{pending:30000,pendingPriority:40000,pendingRomeos:10000,matched:20000},init:function(){SD.log("updating list");var div=DIV({width:200,height:500,style:'auto'});this._div=div;var pc=SD.DatingController._pc;this._pc=pc;this.records=[];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));listen(pc.pending);listen(pc.pendingPriority);listen(pc.pendingRomeos);listen(pc.matches);$('sidebar').insert(div);this._updateDisplayList();},_onStartDate:function(e){this._setMatch(e.memo.otherUser,"Dating");},_onTryingToDate:function(e){this._setMatch(e.memo.match,"Negotiating with...");},_onAcceptedToDate:function(e){this._setMatch(e.memo.match,"Accepted to date...");},_onDateOver:function(e){var msg=e.memo.reason||e.memo.reasonCode||"Date ended";this._setMatch(null,msg);this._toBeClearedMatch=this._currentMatch;setTimeout('SD.DatingQueue._clearCurrentMatch()',3000);},_setMatch:function(match,msg){if(match||!msg){this._currentMatch=match;}
this._currentMatchStatusMsg=msg;this._updateDisplayList();},_clearCurrentMatch:function(forWhom){if(this._toBeClearedMatch!=this._currentMatch){return;}
this._setMatch(null,null);},_sourceToScore:function(source){switch(source){case this._pc.pending:return this.scoreCnts.pending++;case this._pc.pendingPriority:return this.scoreCnts.pendingPriority++;case this._pc.pendingRomeos:return this.scoreCnts.pendingRomeos++;default:return this.scoreCnts.matched++;}},_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.pendingRomeos:return this.TYPE.PENDING_ROMEO;default:return this.TYPE.MATCH;}},_onNewMatch:function(e){var match=e.memo.obj;if(!match||!SD.Model.getMyself().mightDate(match)){return;}
var score=this._sourceToScore(e.source);var type=this._sourceToType(e.source);if(!match.fetched){SD.User.fetch(match,this._updateMatchDiv.bind(this));}
var i=0;var place=-1;for(;i<this.records.length;i++){if(this.records[i].score<score){place=i;break;}}
var record=this._createRecord(e.memo.obj,score,type,true);if(place>-1){this.records.splice(place,0,record);}else{this.records.push(record);}
if(this.records.length<this.SHOW_LIMIT||(place>0&&place<this.SHOW_LIMIT)){this._updateDisplayList();}},_onMatchRemoved:function(e){var match=e.memo.obj;var type=this._sourceToType(e.source);var index=-1;var i=0;for(;i<this.records.length;i++){if(this.records[i].type==type&&this.records[i].match.uid==match.uid){index=i;break;}}
if(index>-1){this.records.splice(index,1);if(this.records.length<this.SHOW_LIMIT||index<this.SHOW_LIMIT){this._updateDisplayList();}}},_createNegoMatchDiv:function(match){return DIV({id:"currentMatchDiv"},IMG({height:40,widht:40,src:match.square_image_url}),P(null,match.uid));},_createRecordDiv:function(record){var match=record.match;if(!match){return null;}
if(!match.fetched){return DIV({id:this._matchDivId(match)},"loading... "+match.uid);}
return DIV({id:this._matchDivId(match)},TABLE(null,TR(null,TD(null,IMG({height:40,widht:40,src:match.square_image_url})),TD(null,match.is_premium?'*':''+
match.username+" ("+match.age+")",BR(),match.city_name+" / "+match.country_name,match!=this._currentMatch?P(null,A({href:'javascript:void(0);',onclick:"SD.DatingQueue.toggleMatchByUid("+match.uid+");"},record.enabled?"disable":'enable')):A(null,"")))));},_createRecord:function(match,score,type,enabled){return{match:match,score:score?score:this._sourceToScore(null),type:type?type:this._sourceToType(null),enabled:(enabled===undefined||enabled===null)?!SD.Model.getMyself().isUnwantedDate(match):enabled};},_getRecordByUid:function(uid){var i=0;for(;i<this.records.length;i++){if(this.records[i].match.uid==uid){return this.records[i];}}
return null;},toggleMatchByUid:function(uid){var record=SD.DatingQueue._getRecordByUid(uid);if(!record){return;}
record.enabled=record.enabled?false:true;if(record.enabled==false){SD.Model.getMyself().addUnwantedDate(record.match);}else{SD.Model.getMyself().removeUnwantedDate(record.match);}
this._updateRecordDiv(record);},_updateDisplayList:function(){var div=this._div;var pc=this._pc;div.innerHTML="";if(this._currentMatch){div.insert(P(null,"Current match..."));if(!this._currentMatch.fetched){div.insert(this._createNegoMatchDiv(this._currentMatch));}else{div.insert(this._createRecordDiv(this._currentMatchRecord()));}
if(this._currentMatchStatusMsg){div.insert(P(null,"Status: "+this._currentMatchStatusMsg));}}
div.insert(P(null,"Upcoming Dates..."));var limit=Math.min(this.SHOW_LIMIT,this.records.length);var i=0;for(;i<limit;i++){div.insert(this._createRecordDiv(this.records[i]));}},_currentMatchRecord:function(){return this._createRecord(this._currentMatch,100000,null,true);},_updateMatchDiv:function(match){if(!match){return;}
if(this._currentMatch&&match.uid==this._currentMatch){var div=$('currentMatchDiv');if(div){var record=this._currentMatchRecord();div.innerHTML=this._createRecordDiv(record).innerHTML;}}
var record=this._getRecordByUid(match.uid);if(!record){return;}
record.match=match;this._updateRecordDiv(record);},_updateRecordDiv:function(record){if(!record){return;}
var div=$(this._matchDivId(record.match));if(div){div.innerHTML=this._createRecordDiv(record).innerHTML;}},_matchDivId:function(match){return"dq_"+match.uid;}};
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.registerInputFeedback=function(oElement){oElement=$(oElement);oElement.observe('click',function(){SD.Feedback.UI.subscriptionPopup();});};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.Carousel=new function(){var _nSize=0;var _nBufferSize=15;var _nViewerPosition=0;var _nContainerWidth=0;var _nUserIconWidth=0;var _aUsers=[];var _oUserIconListElement=null;var _oSelectedUserIconElement=null;var _sSelectedUserIconClassName='selected';var _bScrolling=false;function unselectUserIcons(){_oUserIconListElement.select('li').each(function(oUserIconInput){oUserIconInput.removeClassName(_sSelectedUserIconClassName);});};function selectUserIcon(oElement){unselectUserIcons();oElement.addClassName(_sSelectedUserIconClassName);if(isUserIconInViewer(_oSelectedUserIconElement)&&!isUserIconInViewer(oElement)){if(getUserIconPosition(_oSelectedUserIconElement)<getUserIconPosition(oElement)){SD.Carousel.forward();}else{SD.Carousel.backward();}}
_oSelectedUserIconElement=oElement;};function createUserIcon(oUser){var oUserIcon=LI({},'');var oImg=document.createElement('img');oImg.src=oUser.square_image_url;oUserIcon.appendChild(oImg);return oUserIcon;};function appendUserIcon(oUser){var oUserIcon=createUserIcon(oUser);_oUserIconListElement.appendChild(oUserIcon);_oUserIconListElement.setStyle('width: '+parseInt(_oUserIconListElement.getWidth())+80+'px');SD.Carousel.registerInputUserIcon(oUserIcon,oUser.uid);};function insertUserIcon(oUser){removeDuplicates(oUser.uid);var oUserIcon=createUserIcon(oUser);oUserIcon.hide();_oSelectedUserIconElement.insert({'after':oUserIcon});selectUserIcon(oUserIcon);_oUserIconListElement.setStyle('width: '+parseInt(_oUserIconListElement.getWidth())+80+'px');SD.Carousel.registerInputUserIcon(oUserIcon,oUser.uid);oUserIcon.appear();};function removeDuplicates(nUid){var aUserIconElements=_oUserIconListElement.select('li');var aUserIconElements4Removal=[];aUserIconElements.each(function(oUserIconElement,nPosition){if(oUserIconElement.uid==nUid){aUserIconElements4Removal.push(oUserIconElement);}});aUserIconElements4Removal.each(function(oUserIconElement){_oUserIconListElement.removeChild(oUserIconElement);oUserIconElement.is_removed=true;});};function needMoreUserIcons(){return _oUserIconListElement.select('li').length-_nViewerPosition<=_nBufferSize;};function canForward(){return!_bScrolling&&(_oUserIconListElement.select('li').length-_nViewerPosition-_nSize>_nSize);};function canBackward(){return!_bScrolling&&(_nViewerPosition>0);};function getMoreUserIcons(){if(needMoreUserIcons()){var nStartPos=_oUserIconListElement.select('li').length;var nEndPos=nStartPos+_nBufferSize;for(var i=nStartPos;i<nEndPos;i++){var oUser=SD.FlirtWink.Controller.getFlirtee(i,true);if(oUser){appendUserIcon(oUser);}else{return false;}}}
return true;};function getUserIconPosition(oElement){var aUserIcons=_oUserIconListElement.select('li');for(var i=0;i<aUserIcons.length;i++){if(oElement==aUserIcons[i]){return i;}}
return-1;};function isUserIconInViewer(oElement){var nPosition=getUserIconPosition(oElement);return(nPosition>-1&&nPosition>=_nViewerPosition&&nPosition<_nViewerPosition+_nSize);};this.init=function(nSize,aUsers){_nSize=nSize;_aUsers=aUsers;SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_INSERTED,function(e){insertUserIcon(e.memo.flirtee);}.bind(this));};this.forward=function(){getMoreUserIcons();if(canForward()){_bScrolling=true;var nContainerWidth=$(_oUserIconListElement.parentNode).getWidth();new Effect.Move(_oUserIconListElement,{x:-nContainerWidth,afterFinish:function(){_nViewerPosition+=_nSize;_bScrolling=false;}.bind(this)});}};this.backward=function(){if(canBackward()){_bScrolling=true;var nContainerWidth=$(_oUserIconListElement.parentNode).getWidth();new Effect.Move(_oUserIconListElement,{x:nContainerWidth,afterFinish:function(){_nViewerPosition-=_nSize;_bScrolling=false;}.bind(this)});}};this.registerInputBack=function(oElement){oElement=$(oElement);oElement.observe('click',function(e){this.backward();}.bind(this));};this.registerInputForward=function(oElement){oElement=$(oElement);oElement.observe('click',function(e){this.forward();}.bind(this));};this.regusterInputUserList=function(oElement){oElement=$(oElement);_oUserIconListElement=oElement;};this.registerInputUserIcon=function(oElement,nUid){oElement=$(oElement);oElement.uid=nUid;_oUserIconListElement.select('li').push(oElement);if(_oSelectedUserIconElement==null){_oSelectedUserIconElement=oElement;}
oElement.observe('click',function(e){SD.Event.fire(null,SD.FlirtWink.Events.FIND_FLIRTEE,{'uid':nUid});selectUserIcon(oElement);});SD.Event.observe(null,SD.FlirtWink.Events.FLIRTEE_CHANGE,function(e){if(!oElement.is_removed){getMoreUserIcons();if(nUid==e.memo.flirtee.uid){selectUserIcon(oElement);}}});};};
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.Indicators.Store.log({type:'newFavoritesReceived',uid:e.memo.uid});}.bind(this));SD.Event.observe(null,SD.ClientUpdater.Events.NEW_WINK,function(e){SD.Indicators.Store.log({type:'newWinksReceived',uid:e.memo.uid});}.bind(this));SD.Event.observe(null,SD.ClientUpdater.Events.NEW_FLIRT,function(e){SD.Indicators.Store.log({type:'newFlirtsReceived',uid:e.memo.uid});}.bind(this));SD.Event.observe(null,SD.ClientUpdater.Events.NEW_SPEEDDATE,function(e){SD.Indicators.Store.log({type:'newSpeedDateRequestsReceived',uid:e.memo.uid});}.bind(this));SD.Event.observe(null,SD.ClientUpdater.Events.NEW_VIEW,function(e){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.Indicators.Store.log({type:'newBuddyRequestsReceived',uid:e.memo.uid});}.bind(this));},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'};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(A({'class':'avatar-link','href':''}));if(oNoDates){oNoDates.remove();};});};};
SD.Notification={CAMPAIGNS:{WANTS_TO_DATE:'event_wants_to_date_you',WANTED_DATE_IS_ONLINE:'event_user_online'}};SD.Notification.Landing={_users:new Hash(),_iqId:1,_campaing:null,_channel_type: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};},debug:function(txt){SD.log(txt);},init:function(uids,campaign,channel_type){this._channel_type=channel_type||'channel_email';this._campaign=campaign;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.onChatMessage.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: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.ExperimentManager.StartChatOnNotificationLanding2138.value||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});},onChatMessage:function(event){var sender=event.memo.sender;var entry=this._users.get(sender.uid);if(!entry.gotReply){entry.gotReply=true;this.trackChatReply(entry);}},trackStartChat:function(entry){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});},trackLanding:function(entry){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});},trackChatReply:function(entry){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});}}
SD.Draggable=Class.create({initialize:function(handle,win){this.handle=$(handle);this.win=win;this.dragOffsetX=0;this.dragOffsetY=0;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);Event.observe(document,'mouseup',this.boundOnStopDrag);},onStartDrag:function(ev){this.dragOffsetX=Event.pointerX(ev)-this.win.left;this.dragOffsetY=Event.pointerY(ev)-this.win.top;this.hasDragged=false;this.win.onBeforeDrag&&this.win.onBeforeDrag();if(!this.isDragging){this.isDragging=true;Event.observe(document,'mousemove',this.boundOnDrag);Event.observe(document,'mouseup',this.boundOnStopDrag);}
Event.stop(ev);},onStopDrag:function(ev){Event.stopObserving(document,'mousemove',this.boundOnDrag);Event.stopObserving(document,'mouseup',this.boundOnStopDrag);Event.stop(ev);this.isDragging=false;this.win.onAfterDrag&&this.win.onAfterDrag();},onDrag:function(ev){this.hasDragged=true;this.win.moveTo((Event.pointerX(ev)-this.dragOffsetX),(Event.pointerY(ev)-this.dragOffsetY));Event.stop(ev);}})
SD.Window=Class.create({initialize:function(dom,options){this.options=options;this.setupType=options.setupType||SD.Window.STATIC;this.position=Prototype.Browser.IE6?"absolute":(options.position||"fixed");this.isDomCreated=(this.setupType==SD.Window.STATIC)?true:false;this.isPopulated=false;this.isCentered=!!options.centered;this.dom=dom?$(dom):null;this.isFirstTimeOpened=true;this.template=options.template||(SD.Window.STATIC&&dom)&&dom.innerHTML;this.domParent=$(options.domParent)||document.body;this.closeMethod=this.options.closeMethod;if(!this.closeMethod&&this.setupType==SD.Window.STATIC){this.closeMethod=SD.Window.HIDE_CLOSE;}
else if(!this.closeMethod&&this.setupType==SD.Window.DYNAMIC){this.closeMethod=SD.Window.REMOVE_CLOSE;}
this.data=options.data||{};this.range=options.range||this.range;this._range=this.range;this.setup();this.populate();this._adjustWindowSections();},setup:function(){if(!this.dom&&this.setupType==SD.Window.DYNAMIC){this._createDom(this.template);}
this._createShim();if(this.options.width){this.dom.setWidth(this.options.width);}
if(this.options.height){this.dom.setHeight(this.options.height);}
if(!this.dom.id){this.dom.id="window"+(new Date).getTime();}
this.id=this.dom.id;this._parseElements(this.dom);this.dom.style.position=this.position||this.dom.style.position;this.top=parseInt(this.options.top||this.dom.style.top);this.left=parseInt(this.options.left||this.dom.style.left);this.template=this.template||this.dom.innerHTML;this.width=this.dom.offsetWidth;this.height=this.dom.offsetHeight;if(this.top){this.dom.style.top=parseInt(this.top)+"px";this.shim&&(this.shim.style.top=parseInt(this.top)+"px");}
if(this.left){this.dom.style.left=parseInt(this.left)+"px";this.shim&&(this.shim.style.left=parseInt(this.left)+"px");}
if(this.shim){this.shim.style.width=this.dom.offsetWidth+'px';this.shim.style.height=this.dom.offsetHeight+'px';}
if(this.top===undefined||this.top===null||this.left===undefined||this.left===null){this.isCentered=true;}
return this;},_parseElements:function(rootDom){if(rootDom==this.dom){this.domTitle=rootDom.select('.lib-title')[0];this.domContent=rootDom.select('.lib-content')[0];this.domFooter=rootDom.select('.lib-footer')[0];}
this.isDraggable=this.isDraggable||rootDom.hasClassName("lib-draggable");this.domCloseHandles=this.domCloseHandles||[];if(this.isDraggable){this._attachDragBehavior(this.domTitle,this);}
var closeHandles=rootDom.select('.lib-close-handle');closeHandles.length>0&&this.domCloseHandles.concat(this._attachCloseBehavior(closeHandles));rootDom.select('*').each(function(el){el.container=this}.bind(this));},_attachDragBehavior:function(dragHandle,dragObject){return new SD.Draggable(dragHandle,dragObject);},_attachCloseBehavior:function(closeHandles){if(closeHandles.length>0){closeHandles.each(function(closeHandle){closeHandle.observe('click',function(e){e&&Event.stop(e);this.close();}.bindAsEventListener(this))}.bind(this));}
return closeHandles;},_createShim:function(){if(this.options.shim){this.shim=$(document.createElement("iframe"));this.shim.frameborder="0";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.dom.insert({before:this.shim});}},_createDom:function(domHtml){if(this.setupType==SD.Window.DYNAMIC){var _el=document.createElement("div");_el.style.visibility="hidden";_el.innerHTML=domHtml;document.body.appendChild(_el);if(_el.childNodes[0]&&_el.childNodes[0].nodeType!=3){this.dom=$(_el.childNodes[0].cloneNode(true));this.domParent.appendChild(this.dom);document.body.removeChild(_el);}
else if(_el.childNodes[1]&&_el.childNodes[1].nodeType!=3){this.dom=$(_el.childNodes[1].cloneNode(true));this.domParent.appendChild(this.dom);document.body.removeChild(_el);}
else{this.dom=$(_el);}}
this.isDomCreated=true;return this;},_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(data){this.data=data||this.data;if(!this.inlineTemplates){this._buildInlineTemplates();};if(this.data){for(var i=0;i<this.inlineTemplates.length;++i){this.inlineTemplates[i].node.nodeValue=this.inlineTemplates[i].template.interpolate(this.data);this.isPopulated=true;}}
else{this.isPopulated=false;}
return this;},_adjustWindowSections:function(){this.domTitle&&this.domTitle[this.domTitle.innerHTML.trim()==''?'hide':'show']();this.domFooter&&this.domFooter[this.domFooter.innerHTML.trim()==''?'hide':'show']();this._adjustDimensions();},_adjustDimensions:function(){this.width=this.dom.offsetWidth;this.height=this.dom.offsetHeight;if(this.shim){this.shim.style.width=this.dom.offsetWidth+'px';this.shim.style.height=this.dom.offsetHeight+'px';}
this.moveTo(this.left,this.top);},setTitle:function(html){if(!this.domTitle){return;}
this.domTitle.innerHTML=html;this._parseElements(this.domTitle);this._adjustWindowSections();},setContent:function(html){this.domContent.innerHTML=html;this._parseElements(this.domContent);this._adjustDimensions();},setFooter:function(html){if(!this.domFooter){return;}
this.domFooter.innerHTML=html;this._parseElements(this.domFooter);this._adjustWindowSections();},onBeforeOpen:function(){return this.options.onBeforeOpen&&this.options.onBeforeOpen(this)},onAfterOpen:function(){return this.options.onAfterOpen&&this.options.onAfterOpen(this)},onBeforeClose:function(){return this.options.onBeforeClose&&this.options.onBeforeClose(this)},onAfterClose:function(){return this.options.onAfterClose&&this.options.onAfterClose(this)},open:function(forceOpen){try{if(!forceOpen&&this.onBeforeOpen&&this.onBeforeOpen(this)){return;}}
catch(e){}
this._open();SD.WindowManager.add(this);try{this.onAfterOpen&&this.onAfterOpen(this);}
catch(e){}
return this;},close:function(forceClose){try{if(!forceClose&&this.onBeforeClose&&this.onBeforeClose(this)){return;}}
catch(e){}
this._close();SD.WindowManager.remove(this.id);try{this.onAfterClose&&this.onAfterClose(this);}
catch(e){}
return this;},_open:function(){this._show();if(this.isFirstTimeOpened){this.isCentered&&this.center();}
else if(this.top!==undefined&&this.top!==null&&this.left!==undefined&&this.left!==null){this.updateRange();this.moveTo(this.left,this.top);}
this.isFirstTimeOpened=false;},_close:function(mode){mode=this.closeMethod||mode;if(mode==SD.Window.OFFSCREEN_CLOSE){this.dom.style.top="-2000px";this.dom.style.left="-2000px";if(this.shim){this.shim.style.top="-2000px";this.shim.style.left="-2000px";}}
else if(mode==SD.Window.HIDE_CLOSE){this._hide();}
else if(mode==SD.Window.REMOVE_CLOSE){this.dom.remove();this.shim&&this.shim.remove();}},_hide:function(){this.dom.style.visibility='hidden';this.shim&&(this.shim.style.visibility='hidden');},_show:function(){if(this.dom.style.display=='none'){this.dom.style.display='block';}
this.dom.style.visibility='visible';this.shim&&(this.shim.style.visibility='visible');},onBeforeDrag:function(){this.updateRange();},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&&!isNaN(valX)){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;}}
this.dom.style.left=valX+'px';this.shim&&(this.shim.style.left=valX+'px');this.left=valX;}
if(y!==null&&y!==undefined&&!isNaN(valY)){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);}}
this.dom.style.top=valY+'px';this.shim&&(this.shim.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;},center:function(){var vDim=document.viewport.getDimensions();var vScrollOffsets=document.viewport.getScrollOffsets();if(this.dom.style.position=="fixed"){this.moveTo((vDim.width-this.width)/2,(vDim.height-this.height)/2);}
else if(this.dom.style.position=="absolute"){this.moveTo(vScrollOffsets.left+(vDim.width-this.width)/2,vScrollOffsets.top+(vDim.height-this.height)/2);}},repaint:function(el){el=el||this.dom;el.style.visibility="hidden";setTimeout(function(){el.style.visibility="";}.bind(this),100);}});SD.Window.DYNAMIC="dynamic";SD.Window.STATIC="static";SD.Window.HIDE_CLOSE="hide";SD.Window.REMOVE_CLOSE="remove";SD.Window.OFFSCREEN_CLOSE="offscreen";
SD.WindowManager={init:function(){this.windows={};this.viewportDim=document.viewport.getDimensions();this.viewportOffsets=document.viewport.getScrollOffsets();this.winCount=0;Event.observe(window,'resize',this.onResize.bind(this));Event.observe(window,'scroll',this.onScroll.bind(this));},onResize:function(){var viewportDim=document.viewport.getDimensions();for(var i in this.windows){this.windows[i].updateRange&&this.windows[i].updateRange();try{this.windows[i].moveTo(parseInt(this.windows[i].left*(viewportDim.width-this.windows[i].width)/(this.viewportDim.width-this.windows[i].width)),parseInt(this.windows[i].top*(viewportDim.height-this.windows[i].height)/(this.viewportDim.height-this.windows[i].height)));}
catch(e){}}
this.viewportDim=viewportDim;this.viewportOffsets=document.viewport.getScrollOffsets();},onScroll:function(){var viewportOffsets=document.viewport.getScrollOffsets();var dx=viewportOffsets.left-this.viewportOffsets.left;var dy=viewportOffsets.top-this.viewportOffsets.top;for(var i in this.windows){this.windows[i].updateRange&&this.windows[i].updateRange();if(this.windows[i].position=='absolute'){try{this.windows[i].moveBy(dx,dy);}
catch(e){}}}
this.viewportOffsets=document.viewport.getScrollOffsets();},add:function(win){if(!this.windows[win.id]){this.winCount++;this.windows[win.id]=win;}},remove:function(winId){if(this.windows[winId]){this.winCount--;delete this.windows[winId];}}}
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(null,{setupType:SD.Window.DYNAMIC,template:this.winTemplate,position:"fixed",centered:true,width:400,shim:true}).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.observe('submit',function(ev){Event.stop(ev);_this.submitForm(form);})},'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':function(link,domRoot){link.observe('click',function(e){e.stop();this.load(link.href);}.bind(this))},'a.nav-site':function(link,domRoot){link.observe('click',function(e){e.stop();SD.Nav.navigateTo(link.href);}.bind(this));},'a.external':function(link,domRoot){link.observe('click',function(e){e.stop();location.href=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){alert(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)});},_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.onContentRendered&&this.onContentRendered(targetElement)===true){return true;};this.parser(targetElement);}});
SD.Indicators={initialize:function(){var E_2073=!!SD.ExperimentManager.ActivityCountsInNavigation2_2073.value;var E_2184=!!SD.ExperimentManager.CountOfWantsToDateInNavTab2184.value;Object.extend(SD.Indicators.Views.permissions,{'ind-main-menu-item-members':E_2073,'ind-menu-item-viewed-you':E_2073,'ind-menu-item-favorited-you':E_2073,'ind-menu-item-viewed-you':E_2073,'ind-menu-item-favorited-you':E_2073,'ind-submenu-item-favorited_you':E_2073,'ind-submenu-item-viewed_you':E_2073});Object.extend(SD.Indicators.Views.permissions,{'ind-main-menu-item-my-results':E_2184,'ind-menu-item-want-to-date-you':E_2184});SD.Indicators.Store.initialize();SD.Indicators.Views.initialize();}}
SD.Indicators.Views={initialize:function(){var store=SD.Indicators.Store;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));},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]){el.hide();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){if(this.permissions[el.id]==false){return;}
this._updateGenericParenthesizedItem(el,count);this.permissions[el.id]=false;},_updateGenericParenthesizedItem:function(el,count){if(!el){return;}
if(!this.permissions[el.id]){el.hide();return;}
count?el.show().update(" ("+count+") "):el.hide();},_flags:{'ind-sidemenu-wants-to-speeddate-you':true,'ind-sidemenu-viewed-you':true,'ind-sidemenu-favorited-you':true},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.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(welcomeInstructionsConfiguration,filterConfiguration,flirtWinkConfiguration,profileConfiguration,applicationConfiguration,alertsConfiguration,buddyListConfiguration,otherTabFiltersConfiguration,buddyPopupConfiguration){this.welcomeInstructionsConfiguration=welcomeInstructionsConfiguration;this.filterConfiguration=filterConfiguration;this.flirtWinkConfiguration=flirtWinkConfiguration;this.profileConfiguration=profileConfiguration;this.applicationConfiguration=applicationConfiguration;this.alertsConfiguration=alertsConfiguration;this.buddyListConfiguration=buddyListConfiguration;this.otherTabFiltersConfiguration=otherTabFiltersConfiguration;this.buddyPopupConfiguration=buddyPopupConfiguration;SD.WelcomeInstructions.UI.initialize();SD.UserFilters.UI.initialize(filterConfiguration.target,filterConfiguration.params);(new SD.Alerts.UI(alertsConfiguration.target,alertsConfiguration.params.user,alertsConfiguration.params.flirtNumber,alertsConfiguration.params.requestNumber,true));SD.OtherTabFilters.UI.initialize(otherTabFiltersConfiguration.target,otherTabFiltersConfiguration.params);SD.BuddyPopup.initialize(buddyPopupConfiguration.target);$('sd-message')&&$('sd-message').hide();$('sd-other-tab-filter').hide();if(!SD.ExperimentManager.DatingPopupExp.value){this.updateAppViewState(SD.UIController.DatingAppStates.HIDDEN);}
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.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.Alerts.UI.Events.RESULTS_SOUGHT,this.onResultsSought.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.START_FEEDBACK_REQUESTED,SD.Feedback.UI.standardPopup.bind(SD.Feedback.UI));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("");SD.ExperimentManager.ShowDatingQueue.getValueForMe(function(enabled){if(enabled){SD.DatingQueue.init();}});},extendUICommon:function(context){Object.extend(context,SD.UIControllerCommon);},onStartDating:function(event){this.welcomeDisplayed=false;if(!SD.ExperimentManager.DatingPopupExp.value){if(!SD.DatingApp.isDating){if(this.speeddateActive){this.updateAppViewState(SD.UIController.DatingAppStates.NORMAL);}else{this.updateAppViewState(SD.UIController.DatingAppStates.TABOTHER);}}}},onStartDate:function(event){if(SD.ExperimentManager.DatingPopupExp.value){SD.DatingApp.popupForDate(event.memo.otherUser);if(this.tabBlinkingEnabled){if(!this.windowIsActive()){SD.Favicon.animateTitle(["Date found!","with "+event.memo.otherUser.username],1000);}}}else{$(this.flirtWinkConfiguration.target).hide();SD.ProfileViewer.UI.viewProfile(event.memo.otherUser,function(imageObj,elem){elem.toggleClassName("active");elem.siblings().invoke('removeClassName','active');SD.Flex.changeDateImage(imageObj.image_url);});if(this.speeddateActive){this.updateAppViewState(SD.UIController.DatingAppStates.DATING);}else{this.updateAppViewState(SD.UIController.DatingAppStates.TABOTHERDATING);}
if(this.tabBlinkingEnabled){if(!this.windowIsActive()){SD.Favicon.animateTitle(["Date found!","with "+event.memo.otherUser.username],1000);}}
SD.UIController.recoverBuddyListHeight();}},onDateOver:function(event){SD.Favicon.setTitle(SD.Favicon.defaultTitle);if(!SD.ExperimentManager.DatingPopupExp.value){$(this.flirtWinkConfiguration.target).show();var user=SD.FlirtWink.UI.getCurrentFlirtee();if(user){SD.ProfileViewer.UI.viewProfile(user,function(imageObj,elem){if(SD.Model.getMyself().is_premium){elem.toggleClassName("active");elem.siblings().invoke('removeClassName','active');}
SD.ProfileViewer.UI.resetImage(user,$('flirtAndWink_img'),imageObj.image_url);});}
if(this.speeddateActive){this.updateAppViewState(SD.UIController.DatingAppStates.NORMAL);}else{this.updateAppViewState(SD.UIController.DatingAppStates.TABOTHER);}
SD.UIController.recoverBuddyListHeight();}},onFlirtsSought:function(event){SD.NavUtils.setLocation(SD.NavUtils.link('messages','inbox'));},onBuddyRequestsSought:function(event){SD.NavUtils.setLocation(SD.NavUtils.link('messages','buddy_requests'));},onResultsSought:function(event){SD.NavUtils.setLocation(SD.NavUtils.link('my_results','all'));},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){if(!SD.ExperimentManager.DatingPopupExp.value){this.speeddateActive=true;$('sd-other-tab-filter').hide();if(!this.welcomeDisplayed){if(SD.DatingApp.isDating){this.updateAppViewState(SD.UIController.DatingAppStates.DATING);}else{this.updateAppViewState(SD.UIController.DatingAppStates.NORMAL);}}
this.recoverBuddyListHeight();}},onSwitchedToOtherTabs:function(event){if(!SD.ExperimentManager.DatingPopupExp.value){this.speeddateActive=false;$('sd-other-tab-filter').show();if(!this.welcomeDisplayed){if(SD.DatingApp.isDating){this.updateAppViewState(SD.UIController.DatingAppStates.TABOTHERDATING);}else{this.updateAppViewState(SD.UIController.DatingAppStates.TABOTHER);}}
this.recoverBuddyListHeight();}},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){var iframeTpl='\
   <div id="subscription-iframe-container">\
       <div class="subscription-lightbox-shadow"> </div>\
       <div class="subscription-iframe-content">\
        <iframe id="subscription-iframe" src="#{url}" frameborder="0" width="650" scrolling="yes" height="550" marginwidth="0" marginheight="0" hspace="0" vspace="0"></iframe>\
       </div>\
      </div>';document.body.insert(iframeTpl.interpolate({url:url}));},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;var E_2007=SD.ExperimentManager.OrderFormAfterNewSignup2007.value;if(E_2007==1){this._openIframeSubscriptionPopup(premUrl+"&isIframe=1");}
else if(SD.Config.platform.platformId==3){if(SD.ExperimentManager.OrderFormNewBrowserWindow1460.value){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;}}
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.Config.platform.platformId==3){if(SD.ExperimentManager.OrderFormNewBrowserWindow1460.value){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;}}else{top.location.href=premUrl;}},upgradeMyselfFlash:function(uid){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 Window({className:"message",resizable:false,zIndex:1000,width:200,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={className:"message",resizable:false,zIndex:1000,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 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){cancelLabel=cancelLabel||"Cancel";confirmBtnClassName=confirmBtnClassName||"input-button sd-flirt-submit";cancelBtnClassName=cancelBtnClassName||"input-button right-button";var send=INPUT({"type":"button","class":confirmBtnClassName,"value":label});var close=INPUT({"type":"button","class":cancelBtnClassName,"value":cancelLabel});send.observe("click",command);close.observe("click",win.close.bind(win));return DIV({},send,close);},_popupGenericWarning:function(title,upgradeArguments,messages,buttonLabel,subTitle,onClick){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;},_photoUploadPopup:function(title,message,buttonLabel,cancelButtonLabel){buttonLabel=buttonLabel||"Go To Photo Upload";cancelButtonLabel=cancelButtonLabel||"Later";var win=this.standardPopup({title:title});var go=function(){this.tryUploadPhoto();};var exp=DIV({"class":"upload-photo-message"});exp.insert(message);var photoUploadContent='<div class="upload-photo-popup-bar">'+'<span class="upload-photo-label">Select a photo:</span>'+'<form id="upload-photo-form-in-popup" class="upload-profile-pic-popup" method="post" action="'+SD.NavUtils.link('profile','save_photo')+'" enctype="multipart/form-data">'+'<input class="input-file btn" type="file" name="photo" />'+'<input type="hidden" name="upload_from_popup" value="1" />'+'<input type="hidden" name="win_name" value="'+win.getId()+'" />'+'<input type="hidden" name="return_url_after_upload" value="'+encodeURIComponent(window.location.href)+'" />'+'<input type="submit" class="upload-photo-btn" value="Upload" />'+'</form>'+'</div>';exp.insert(photoUploadContent);win.getContent().insert(DIV({"class":"upgradepop"},exp,this.buttonBar(win,buttonLabel,go.bind(this),cancelButtonLabel,"input-button sd-flirt-submit popup-upload-photo-btn")));win.showCenter(true,200);SD.Nav.updateUrls(exp);},_fillAboutMeStepOnePopup:function(){var title='Fill the form';var message='We need more information before you will truly get all the benefits out of SpeedDate.com. Tell us about yourself:';var buttonLabel='Save';var cancelButtonLabel='Later';var win=this.standardPopup({title:title,'width':500,closable:true});var go=function(){this.saveAboutMe();};var dom=DIV({"class":"upload-photo-message"});dom.insert(message);var aboutMeFormContent='<div>'+'<form id="about-me-form-in-popup" method="post" action="'+SD.NavUtils.link('profile','save_aboutme')+'"><table class="profile-table"><tbody>'+'<table class="profile-table"><tbody><tr><th><label for="member_info[14]">Body Style&nbsp;:</label></th><td><select name="member_info[14]"><option value="-1">-- Select One --</option><option value="208">Slender</option><option value="209">About Average</option><option value="210">Athletic / Toned</option><option value="211">A Few Extra Pounds</option><option value="212">Heavy set</option><option value="213">Cuddly</option><option value="215">Husky</option><option value="216">Petite</option><option value="217">Voluptuous</option><option value="218">Muscular</option><option value="219">Modelesque</option></select></td></tr><tr><th><label for="member_info[12]">Height&nbsp;:</label></th><td><select name="member_info[12]"><option value="-1">-- Select One --</option><option value="74">&lt; 4\'6"(137cm)</option><option value="75">4\'6"(137cm)</option><option value="76">4\'7"(140cm)</option><option value="77">4\'8"(142cm)</option><option value="78">4\'9"(145cm)</option><option value="79">4\'10"(147cm)</option><option value="80">4\'11"(150cm)</option><option value="81">5\'0"(152cm)</option><option value="82">5\'1"(155cm)</option><option value="83">5\'2"(157cm)</option><option value="84">5\'3"(160cm)</option><option value="85">5\'4"(163cm)</option><option value="86" selected="selected">5\'5"(165cm)</option><option value="87">5\'6"(168cm)</option><option value="88">5\'7"(170cm)</option><option value="89">5\'8"(173cm)</option><option value="90">5\'9"(175cm)</option><option value="91">5\'10"(178cm)</option><option value="92">5\'11"(180cm)</option><option value="93">6\'0"(183cm)</option><option value="94">6\'1"(185cm)</option><option value="95">6\'2"(188cm)</option><option value="96">6\'3"(191cm)</option><option value="97">6\'4"(193cm)</option><option value="98">6\'5"(196cm)</option><option value="99">6\'6"(198cm)</option><option value="100">6\'7"(201cm)</option><option value="101">6\'8"(203cm)</option><option value="102">6\'9"(206cm)</option><option value="103">6\'10"(208cm)</option><option value="104">6\'11"(211cm)</option><option value="105">7\'0"(213cm)</option><option value="106">&gt; 7\'0"(213cm)</option></select></td></tr><tr><th><label for="member_info[8]">Ethnicity&nbsp;:</label></th><td><div class="dropdown"><div class="text">White/Caucasian</div></div><select name="member_info[8][]" multiple="multiple" size="4"><option value="37">Asian</option><option value="38">Black/African Descent</option><option value="39">East Indian</option><option value="40">Latino/Hispanic</option><option value="41">Native American</option><option value="42">Pacific Islander</option><option value="43" selected="selected">White/Caucasian</option><option value="44">Other</option></select></td></tr><tr><th><label for="member_info[1]">More About Me&nbsp;:</label></th><td><textarea name="member_info[1]" cols="40" rows="2"></textarea></td></tr></tbody></table>'+'</tbody></table>'+'<input type="submit" value="Save" />'+'<input type="hidden" name="aboutme_from_popup" value="1" />'+'<input type="hidden" name="win_name" value="'+win.getId()+'" />'+'<input type="hidden" name="return_url_after_upload" value="'+encodeURIComponent(window.location.href)+'" />'+'</form>'+'</div>';dom.insert(aboutMeFormContent);win.getContent().insert(DIV({"class":"upgradepop"},dom));win.showCenter(true,200);},saveAboutMe:function(){$('about-me-form-in-popup').submit();},_popupPhotoWarning:function(title,message,buttonLabel,cancelButtonLabel){buttonLabel=buttonLabel||"Go To Photo Upload";cancelButtonLabel=cancelButtonLabel||"Later";var win=this.standardPopup({title:title});var go=function(){this.goToPhotoUpload();};var exp=DIV({"class":"upload-photo-message"});exp.insert(message);win.getContent().insert(DIV({"class":"upgradepop"},exp,this.buttonBar(win,buttonLabel,go.bind(this),cancelButtonLabel,"input-button sd-flirt-submit popup-upload-photo-btn-go")));win.showCenter(true,200);},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);},aboutMePopup:function(formId){var isFirstTime=true;var dialog=this.standardPopup({title:'Fill Your Profile Information',width:500,draggable:true,destroyOnClose:true});var helper=new SD.Dialogs.Utils({dialog:dialog,domContent:dialog.getContent(),onLoad:function(){isFirstTime&&dialog.showCenter(true,100);isFirstTime=false;}});helper.load(SD.NavUtils.link('profile','aboutme_popup',{formId:formId}));return dialog;},emailVerificationPopup:function(formId,popupSource){var isFirstTime=true;var dialog=this.standardPopup({title:'Verify Your Email',width:400,draggable:true,destroyOnClose:true});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',{formId:formId,popupSource:popupSource}));return dialog;},goToPhotoUpload:function(){top.location.href=SD.NavUtils.link('profile','upload_photo');},tryUploadPhoto:function(){$('upload-photo-form-in-popup').submit();},standardPopup:function(params){var baseParams={className:"dialog",zIndex:1000,width:350,destroyOnClose:true,closable:true,minimizable:false,maximizable:false,draggable:false,resizable:false,showEffect:Effect.Appear,hideEffect:Effect.Fade,effectOptions:{duration:0.1}};return new 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);if(user.online||user.isOnline){chatButton.removeClassName('chat-disabled');chatButton.addClassName('chat-enabled');}else{chatButton.addClassName('chat-disabled');chatButton.removeClassName('chat-enabled');}}});},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",INITIALIZATION_COMPLETE:"uicontroller:initializationcomplete"},DatingAppStates:{HIDDEN:"hidden",NORMAL:"normal",DATING:"dating",TABOTHER:"tabother",TABOTHERDATING:"tabotherdating"}};