
Application.Modules.ITicker=new Class({Implements:Events,tickerChannel:'*ticker',tickerTooltip:null,tickerMaxItems:28,tickerItemWidth:24,$tickerContainer:null,$tickerPointer:null,useTooltip:true,animating:false,initialize:function(client,$tickerContainer,tickerOverlayClass){client.addChannel(this.tickerChannel);if($tickerContainer==null){$tickerContainer=$('#ticker');}
this.$tickerContainer=$tickerContainer;this.resetTicker();client.onRaw('AddToTicker',this.addToTickerQueue.bind(this));var min=this.$tickerPointer.children().length;var self=this;this.$tickerContainer.children().each(function(){if($(this).children().length<min){min=$(this).children().length;self.$tickerPointer=$(this);}});try{if(this.useTooltip){if(tickerOverlayClass==null){tickerOverlayClass=Application.Tools.TickOverlay;}
this.tickerTooltip=new tickerOverlayClass({container:this.$tickerContainer});}}catch(e){}
this.initializeClickable();},initializeClickable:function(){$('img.user.vs').live('click',function(){window.location=$(this).data('href');});},tickerQueue:[],tickerProcessor:null,addToTickerQueue:function(params){console.log('addToTickerQueue',params);var self=this;this.tickerQueue.push(params);if(this.tickerProcessor==null){this.tickerProcessor=setInterval(this.addToTicker.bind(this),1000);this.fireEvent('tickerOn');}},getTickFromQueue:function(){if(this.tickerQueue.length<=0){clearInterval(this.tickerProcessor);this.tickerProcessor=null;this.fireEvent('tickerOff');return false;}else{return this.tickerQueue.pop();}},getTickerContent:function(params){return $(params.data.output.user);},addToTicker:function(){if(this.animating===true){return;}
var params;if((params=this.getTickFromQueue())===false){return;}
var $element=this.getTickerContent(params);var $toRemove=this.$tickerPointer.children(':nth-child('+(this.tickerMaxItems-1)+')').nextAll();var uid=$element.attr('data-uid');if(this.$tickerContainer.find('img[data-uid='+uid+']').length>0){if($toRemove.find('[data-uid=='+uid+']').length<=0){return;}}
$toRemove.remove();this.initializeTick($element,$(params.data.output.event));$('#ticker_data').append(params.data.output.stats);this.animateIntoPlace($element);this.fireEvent('ticked',$element);this.$tickerPointer=this.$tickerPointer.next();if(this.$tickerPointer.length<=0){this.resetTicker();}},initializeTick:function($tick,$info){this.$tickerPointer.prepend($tick);},resetTicker:function(){this.$tickerPointer=this.$tickerContainer.children().first();},animateIntoPlace:function($element,callback){if($element.length<=0){return;}
this.$tickerPointer.css({marginLeft:-this.tickerItemWidth}).animate({marginLeft:0},500);this.animating=true;$element.css({opacity:0}).animate({opacity:1},500,null,function(){this.animating=false;if(callback){callback();}}.bind(this));this.fireEvent('ticked',$element);}});Application.Modules.OmniTicker=new Class({Extends:Application.Modules.ITicker,tickerMaxItems:150,tickerItemWidth:36,bufferLength:10,autoTimeout:8500,initialize:function(client,$tickerContainer,tickerOverlayClass){if(!tickerOverlayClass){tickerOverlayClass=Application.Tools.HistoryOverlay;}
this.extractBuffer();this.parent(client,$tickerContainer,tickerOverlayClass);this.autoSetMax();$(window).resize(this.autoSetMax.bind(this));this.addEvent('ticked',function(){$('#tickertip').hide();});this.addEvent('tickerOn',this.stopAuto);this.addEvent('tickerOff',this.startAuto);this.startAuto();this.autoTickHandler();this.disableAuto();this.tickerTooltip.addEvent('manualShow',this.disableAuto.bind(this));},initializeClickable:function(){},extractBuffer:function(){this.$buffer=$('#ticker .row img.user:lt('+this.bufferLength+')').detach();this.bufferIndex=this.bufferLength-1;},getNext:function(){var $next=$(this.$buffer[this.bufferIndex]);this.bufferIndex--;return $next;},autoTicker:null,disableAuto:function(){this.autoDisabled=true;},stopAuto:function(){window.clearInterval(this.autoTicker);this.autoTicker=null;},startAuto:function(){if(this.autoDisabled){return;}
if(this.autoTicker==null&&this.bufferIndex>=0){this.autoTicker=window.setInterval(this.autoTickHandler.bind(this),this.autoTimeout);}},autoTickHandler:function(){if(this.bufferIndex>=0){if(Math.random()<=1&&this.animating!==true){var $next=this.getNext();if($next==null){return;}
this.initializeTick($next);this.animateIntoPlace($next,function(){if(this.autoDisabled){return;}
this.tickerTooltip.showToolTip(this.$tickerContainer.find('img.user:nth-child(2)').data('uid'));}.bind(this));}}else{this.stopAuto();}},getTickerContent:function(params){var $history=$(params.data.output.history);this.tickerTooltip.hideTickOverlay();var $tickerTip=$('#tickertip_content');$tickerTip.children().hide();var $current=$tickerTip.children('div[data-uid='+$history.data('uid')+']');if($current.length>0){var show=($current.is(':visible'));$current.replaceWith($history);if(show){$current.show();}else{$current.hide();}}else{$('#tickertip').append($history);}
return this.parent(params);},autoSetMax:function(){$('#ticker_wrapper').css({width:Math.floor($(window).width()/this.tickerItemWidth)*this.tickerItemWidth});}});Application.Modules.ICheckoutController=new Class({checkoutForms:[],creditCardValidators:{CCNumber:function($elem,val){try{var cc=new Application.Tools.CreditCard(val);if(!cc.isValid()){return'Please enter a valid credit card number.';}
else{return true;}}catch(e){if(e.name==='TypeError'){return'Please enter a valid credit card number.';}
return true;}},CCCode:function($elem,val){if(!val||val===''){return'Please enter the Security Code for your card.';}
else{return true;}},CCName:function($elem,val){if(!val||val===''){return'Please enter the full name on the Credit Card.';}
else{return true;}}},whenBeforeSubmit:function(){$('#purchase_progress').css('display','block');},whenFormSubmit:function(data,textStatus,XMLHttpRequest){this.clearFormErrors();if(data.controller.next){if(typeof data.controller.next==='boolean'){console.log('should go next...');this.targetForm.trigger('gotoNext',data);}
else if(typeof data.controller.next.url==='string'){console.log('should redirect to "'+data.next.url+'"');window.location=data.controller.next.url;}
else if(typeof data.controller.next==='number'){this.targetForm.trigger('gotoItem',data);}}
if(data.errorMessage){this.displayErrorMessage(data.errorMessage);}
for(var error in data.errors_cc){if(data.errors_cc.hasOwnProperty(error)){var $elem=this.targetForm.find('input[name='+error+']');this.markFormFieldWithError($elem);}}
$('#purchase_progress').css('display','none');},setupCheckoutController:function(){var $elem=$('#main-content');var scrollable=$elem.find('.scrollable').scrollable().data('scrollable');var pageController=this;$elem.find('a[rel=next]').bind('click',{overlay:scrollable},function(e){console.log('click on: ',this,e);e.stopPropagation();e.data.overlay.move(1);return false;});$elem.find('a[rel=previous]').bind('click',{overlay:scrollable},function(e){console.log('click on: ',this);e.stopPropagation();e.data.overlay.move(-1);return false;});$elem.find('form').each(function(){var selector=this,newForm=new Application.Tools.AjaxForm({errorMessageContainer:'.error_message',validators:pageController.creditCardValidators,myCustomSubmit:pageController.whenFormSubmit,myBeforeSubmit:pageController.whenBeforeSubmit,buttons:$elem.find('.button').add('button')},selector);$(newForm.targetForm).data('overlay',scrollable);newForm.targetForm.bind('gotoNext',{overlay:scrollable},pageController.onGotoNext);newForm.targetForm.bind('gotoItem',{overlay:scrollable},pageController.onGotoItem);pageController.checkoutForms.push(newForm);});$elem.find('button[rel]').unbind().click(function(){$('form'+$(this).attr('rel')).submit();});},onGotoNext:function(e){$('#purchase_progress').css('display','none');e.data.overlay.move(1);if(data.controller.address){var elem=$('#thankyou_address');elem.find('#street1').html(data.controller.address.Street1);elem.find('#street2').html(data.controller.address.Street1);elem.find('#city').html(data.controller.address.City);elem.find('#state').html(data.controller.address.State);elem.find('#zipcode').html(data.controller.address.Zip_Code);}},onGotoItem:function(e){$('#purchase_progress').css('display','none');e.data.overlay.seekTo(e.data.controller.next);}});Application.Modules.AchievementOverlay=new Class({Implements:[Application.Tools.StarList],getPosition:function(el){var p=el.offset();return{top:p.top+el.height()/2,left:p.left+el.width()/2};},setupAchievementOverlay:function($context,initLive){if(initLive!==false){$('a.achievement-link').live('click',function(){$('a.overlay_trigger').not('.stars').click();});}
if($context==null){$context=$('body');}
var self=this;var
initOverlayContent=function(){Application.Tools.BasicTooltip.initTooltips(this.getOverlay().find('img[title]'));self.setupBlinds(this.getOverlay());},onBeforeLoad=function(){var overlay=this,wrap=overlay.getOverlay().find(".contentWrap"),trigger=overlay.getTrigger(),onSuccess=function(data,textStatus,XMLHttpRequest){var context=this.options.context;$(context).html(data);overlay.getConf().onContentLoad.call(overlay);},onComplete=function(XMLHttpRequest,textStatus){},onError=function(XMLHttpRequest,textStatus,errorThrown){};wrap.html(overlay.getConf().loader||'');var req=new Application.Tools.AjaxRequest({context:wrap,url:overlay.getTrigger().attr("href"),success:onSuccess,complete:onComplete,error:onError});req.execute();};$('a.overlay_trigger').not('.initialized').overlay({mask:{closeSpeed:0,color:'#fff'},loader:'<div class="loader"></div>',fixed:false,closeOnClick:false,onBeforeLoad:onBeforeLoad,onContentLoad:initOverlayContent}).addClass('initialized');}});Application.Modules.CheckoutOverlay=new Class({checkoutForms:[],getPosition:function(el){var p=el.offset();return{top:p.top+el.height()/2,left:p.left+el.width()/2};},creditCardValidators:{CCNumber:function($elem,val){try{var cc=new Application.Tools.CreditCard(val);if(!cc.isValid()){return'Please enter a valid credit card number.';}
else{return true;}}catch(e){if(e.name==='TypeError'){return'Please enter a valid credit card number.';}
return true;}},CCCode:function($elem,val){if(!val||val===''){return'Please enter the Security Code for your card.';}
else{return true;}},CCName:function($elem,val){if(!val||val===''){return'Please enter the full name on the Credit Card.';}
else{return true;}}},whenFormSubmit:function(data,textStatus,XMLHttpRequest){this.clearFormErrors();if(data.controller.next){if(typeof data.controller.next==='boolean'){console.log('should go next...');this.targetForm.trigger('gotoNext',data);}
else if(typeof data.controller.next.url==='string'){console.log('should redirect to "'+data.next.url+'"');window.location=data.controller.next.url;}
else if(typeof data.controller.next==='number'){this.targetForm.trigger('gotoItem',data);}}
if(data.errorMessage){this.displayErrorMessage(data.errorMessage);}
for(var error in data.errors_cc){if(data.errors_cc.hasOwnProperty(error)){var $elem=this.targetForm.find('input[name='+error+']');this.markFormFieldWithError($elem);}}},whenItemAdded:function(e,elem,overlay){var pageController=this;$(elem).find('a[rel=next]').bind('click',{overlay:overlay},function(e){e.stopPropagation();e.data.overlay.move(1);return false;});$(elem).find('a[rel=previous]').bind('click',{overlay:overlay},function(e){e.stopPropagation();e.data.overlay.move(-1);return false;});$(elem).find('form').each(function(){var selector=this,newForm=new Application.Tools.AjaxForm({errorMessageContainer:'.error_message',validators:pageController.creditCardValidators,myCustomSubmit:pageController.whenFormSubmit,buttons:$(elem).find('.button').add('button')},selector);$(newForm.targetForm).data('overlay',overlay);newForm.targetForm.bind('gotoNext',{overlay:overlay},pageController.onGotoNext);newForm.targetForm.bind('gotoItem',{overlay:overlay},pageController.onGotoItem);pageController.checkoutForms.push(newForm);});$(elem).find('button[rel]').unbind().click(function(){$('form'+$(this).attr('rel')).submit();});},setupCheckoutOverlay:function(){var
pageController=this,onAddItemHandler=function(e,elem){pageController.whenItemAdded(e,elem,this);};$('.checkout_trigger').each(function(){var config={mask:{closeSpeed:0,color:'#fff',opacity:0},navi:'#checkoutnavi',fixed:false,closeOnClick:false,onAddItem:onAddItemHandler};if($(this).attr('data-autoload')){config.load=true;}
$(this).tabbedoverlay(config);});},onGotoNext:function(e){e.data.overlay.move(1);if(data.controller.address){var elem=$('#thankyou_address');elem.find('#street1').html(data.controller.address.Street1);elem.find('#street2').html(data.controller.address.Street1);elem.find('#city').html(data.controller.address.City);elem.find('#state').html(data.controller.address.State);elem.find('#zipcode').html(data.controller.address.Zip_Code);}},onGotoItem:function(e){e.data.overlay.seekTo(e.data.controller.next);}});Application.Modules.IBrowser=new Class({initializeBrowseBehavior:function(){this.setupAjaxPagination();this.setupAjaxLowerPrice();this.formatTimers();},setupAjaxLowerPrice:function(){this.lowerprice=new Application.Modules.LowerPriceTriggerBehavior('a.lower-price');},updateBreadcrumb:function(){var breadcrumbElem=$('#navigation').find('a[href*="page="]'),activePagerElem,m;if(breadcrumbElem){activePagerElem=$('.pagination').find('a.active');m=(/page=([\d])*/i).exec(activePagerElem.attr('href'));if(m&&m[0]&&m[1]){breadcrumbElem.attr('href',activePagerElem.attr('href'));breadcrumbElem.text('Page '+m[1]);}}},setupAjaxPagination:function(){var self=this;$('.pagination a.loader').each(function(){new Application.Tools.AjaxTrigger($(this),{complete:function(){console.log($(this));self.initializeBrowseBehavior();self.lowerPriceTriggers.initialize();self.updateBreadcrumb();self.fireEvent('newPageLoad');}});});}});Application.Modules.IFeaturedItemTicker=new Class({Extends:Application.Modules.OmniTicker,Implements:[Events],tickerChannel:'*ticker',tickerTooltip:null,tickerMaxItems:28,tickerItemWidth:24,useTooltip:true,bufferLength:5,autoTimeout:10000,initialize:function(client,tickerChannel){this.tickerChannel=tickerChannel;this.parent(client,null,Application.Tools.TickOverlay);this.addEvent('ticked',this.onTicked);},getCount:function(){return this.$tickerContainer.find('img.user').length;},getItemAtIndex:function(i){return this.$tickerContainer.find('img.user:eq('+i+')');},onTicked:function($element){$target=this.$tickerContainer.find('.row img:eq(2)');if($target.length>0){this.fireEvent('onChange',$target);}}});Application.Modules.IHotList=new Class({hotlistChannel:'*hotlist',initialize:function($context){throw"IHotlist is a PARTIAL class and should not be used as standalone, or parent class. It has to be implemented into a class that extends from Ape.Client";},initializeHotList:function($context,makeFirstVisible){this.addChannel(this.hotlistChannel);this.addEvent('userJoin',function(user,pipe){var pipe=this.core.getPipe(user.pubid);});this.onRaw('AddToHotlist',this.addToHotlist);this.setupHotlist($context,null,makeFirstVisible);},setupHotlist:function($context,$content,makeFirstVisible){if(makeFirstVisible==null){makeFirstVisible=true;}
if($context==null){$context=$('#hotlist .item img');}
$context.each(function(index){var $this=$(this);var eventId=this.id.match(/([\d]+)/)[1];$domContent=$('#hotlist-social-info-'+eventId);$content=$domContent.length>0?$domContent.detach().html():$content;$this.eventData({data:"EventId="+eventId,startVisible:index==0?makeFirstVisible:false,content:$content});});},addToHotlist:function(param){var $newItem=$(param.data.output.item);var $content=$(param.data.output.social);$('#hotlist').append($newItem);var $trigger=$newItem.find('img');this.setupHotlist($trigger,$content,false);$('#hotlist .item img').first().eventData('hide');$('#hotlist .item').first().animate({marginLeft:"-160px",opacity:0},500,'',function(){var $this=$(this);$this.find('img').eventData('remove');$this.next().find('img').eventData('show');$this.remove();});}});Application.Modules.ILogin=new Class({Binds:['signInFailed','signInPopup'],loginRules:{rules:{Email_Address:{required:true,email:true},Password:{required:true}},messages:{Email_Address:{required:"We need your email so we can contact you.",email:"This is not a valid email address"},Password:{required:"Can't login without your password."}}},initialize:function(){this.$trigger=$('a.sign-in');this.shortcutParser=new Application.Tools.Shortcut();if($_YOTTA_.action!='login'){this.trigger=new Application.Tools.AjaxTrigger(this.$trigger,{});this.trigger.addEvent('success',this.signInPopup.bind(this));}},setupLoginForm:function(){this.$form=$('#signin-form');this.$form.validate(this.loginRules);this.form=new Application.Tools.AjaxTrigger(this.$form,{});var self=this;this.form.addEvent('success',this.signInFailed.bind(this));this.form.addEvent('beforeSend',this.beforeSend.bind(this));},beforeSend:function(){this.dialog.$content.find('.message:visible').slideUp();},signInFailed:function(html){this.dialog.close();this.signInPopup(html);this.dialog.$content.find('.message').hide().slideDown();},signInPopup:function(html){this.dialog=new Application.Tools.QuickDialog(html,'Sign In',true,{modal:true,width:350});console.log(this);this.shortcutParser.parseShortcuts(this.dialog.$content);this.setupLoginForm();this.dialog.$content.addClass('ajax-popup');}});Application.Modules.IPlaxo=new Class({activePlaxoSaleId:null,initPlaxo:function(){var self=this;var callback=function(event){event.stopPropagation();self.openPlaxo(this);return false;};$('a.plaxo, button.plaxo').not('.initialized').bind('click',callback).addClass('initialized');},openPlaxo:function(elem){var $trigger=$(elem);var url=$trigger.data('plaxo');this.iframeOverlay=new Application.Tools.IframeOverlay({src:url,iframeAttributes:{scrolling:'no'}});}});Application.Modules.IRegister=new Class({initialize:function(){this.signupLink=new Application.Tools.AjaxTrigger($('a.sign-up'),{success:this.signUpPopup.bind(this)});},signUpPopup:function(html){var dialog=new Application.Tools.QuickDialog(html,'Create an Account',true,{modal:true,width:350});dialog.$content.addClass('ajax-popup');console.log();var sparser=new Application.Tools.Shortcut();sparser.parseShortcuts(dialog.$content);this.setupRegistrationForm();},setupRegistrationForm:function(){this.$form=$('#register-form');this.$form.validate({rules:{Email_Address:{required:true,email:true,remote:'?action=register.EmailCheck'},First_Name:{required:true},Last_Name:{required:true},Zip_Code:{required:true,digits:true},Password:{required:true,minlength:6},Confirm_Password:{required:true,equalTo:'#register-password'}},messages:{Email_Address:{required:"We need your email so we can contact you.",email:"This is not a valid email address"},First_Name:{required:"What's your first name?"},Last_Name:{required:"What's your last name?"},Zip_Code:{required:"You forgot your zip code",digits:"This doesn't look like a valid zip code"},Password:{required:"You need a password",minlength:"A 6-character password is safer"},Confirm_Password:{required:"Please confirm your password",equalTo:"This doesn't match your password."}}});}});Application.Modules.ISheet=new Class({$sheet:null,initialize:function($context){throw"ISheet is a partial class and should not be used as standalone, or parent class. It has to be implemented into a page controller.";},initializeSheet:function(){if(!this.getSheet().length){return;}
$('#sheet_close').bind('click',function(e){if(this.getSheet().data('action')=='open'){this.showSheet();}
else{this.closeSheet();}}.bind(this));this.getSheet().data('action','open').data('borderWidth',this.getSheet().css('borderWidth')).css({'display':'block','borderWidth':0});$('#sheet_close').hover(function(e){$(this).addClass('hover');},function(e){$(this).removeClass('hover');});this.initVideoLinks();this.addEvent('preShow',function(){this.closeSheet();}.bind(this));},animateUnwatchedVideos:function(){this.getSheet().find('.video.unwatched').each(function(i){var $elem=$(this);setTimeout(function(){$elem.find('img').stop(true,true).effect('bounce',{times:3,distance:25,direction:'up'},200);$elem.find('canvas').stop(true,true).effect('bounce',{times:3,distance:25,direction:'down'},200);},125*i);});},initVideoLinks:function(){var self=this;this.getSheet().find('.video').not('.locked').find('a[data-video]').not('.activated').each(function(){$(this).click(function(e){e.stopPropagation();self.displayVideo(Application.Videos[$(this).data('video')]);self.markVideoAsWatched($(this).data('video'));$(this).closest('.video').removeClass('unwatched');return false;});}).addClass('activated');},unlockVideo:function(vidName){var $vid=$('#sheet').find('a[data-video='+vidName+']').closest('.video');if($vid.length&&$vid.hasClass('locked')){this.markVideoAsUnlocked(vidName);$vid.removeClass('locked').addClass('unwatched');this.initVideoLinks();}},getSheet:function(){if(!this.$sheet){this.$sheet=$('#sheet');}
return this.$sheet;},setSheetMessage:function(message){this.getSheet().find('#sheet_content').html(message);return this;},showSheet:function(autoHide){var timerInterval=this.getSheet().data('timerInterval');this.getSheet().removeClass('closed').data('action','close').css('borderWidth',this.getSheet().data('borderWidth')).find('#sheet_content').slideDown(800,'easeOutElastic');$('#sheet_close').removeClass('hidden').removeClass('hover').animate({'right':''+($(window).width()/2-$('#sheet_close').width()/2)+'px'},800,'easeOutElastic');if(timerInterval){clearTimeout(timerInterval);}
if(autoHide){this.getSheet().data('timerInterval',setTimeout(this.closeSheet.bind(this),5000));}
clearInterval(this.getSheet().data('bounceInterval'));var interval=setInterval(this.animateUnwatchedVideos.bind(this),2500);this.getSheet().data('bounceInterval',interval);},closeSheet:function(){var self=this,timerInterval=this.getSheet().data('timerInterval');if(timerInterval){clearTimeout(timerInterval);}
this.getSheet().find('#sheet_content').slideUp(500,'easeInBack',function(){self.getSheet().css('borderWidth',0);self.getSheet().addClass('closed');});this.getSheet().data('action','open');this.getSheet().find('#sheet_close').removeClass('hover');$('#sheet_close').delay(300).animate({'right':'40px'},800,'easeOutElastic');clearInterval(this.getSheet().data('bounceInterval'));}});Application.Modules.ISocialize=new Class({initializeSocialize:function(){$('a.social').each(function(){var $this=$(this);var trigger=$this.data('ajax-trigger');if(trigger)
{trigger.options.success=function(html){console.log(html);};}});}});Application.Modules.ITimer=new Class({defaultTimerFormat:'<span class="label time_left">Time Left:</span> <span class="amount">{dn}</span> <span class="label">days</span> '
+'<span class="amount">{hn}</span> <span class="label">hrs</span> '
+'<span class="amount">{mn}</span> <span class="label">min</span> '
+'<span class="amount">{sn}</span> <span class="label">sec</span> ',setDefaultTimerFormat:function(format){this.defaultTimerFormat=format;},formatTimers:function(format,selector,value){var empty;if(format==null){format=this.defaultTimerFormat;}
if(selector==null){selector='.countdown-timer';}
var self=this;$(selector).each(function(){var $this=$(this);var offset=value==null?parseInt($(this).html()):value;if(isNaN(offset)){return;}
$this.countdown({until:((new Date()).increment('second',offset)),layout:format,onExpiry:self.countdownTimeout.bind(self,$this)});});},countdownTimeout:function($timer){console.log($timer,'just expired');}});Application.Tools.UserInfoRules={rules:{Street1:'required',Zip_Code:{required:true,digits:true,minlength:5,maxlength:5},Phone:{digits:true,required:false},Gender:'required',First_Name:'required',Last_Name:'required',State:'required',City:'required',Country:'required',ConfirmPassword:{equalTo:'#new-password'},Email_AddressConfirm:{equalTo:'#email'}},messages:{First_Name:'Please enter your first name',Last_Name:'Please enter your last name',Street1:'Please enter your street address',City:'Please enter your city',State:'Please enter your state',Phone:'Invalid Phone Number',Zip_Code:{required:'Please enter your zip code',digits:'Numbers only please',minlength:'5 Digits zip codes only please'},ConfirmPassword:'Please confirm your new password'}};Application.Modules.TopBarSlidable=new Class({Implements:[Events],Binds:['slide'],hiding:false,$target:null,initialize:function($target){this.hiding=false;if($target!=null){this.setupSlidable($target);}},setupSlidable:function($target){this.$target=$target;$('#layout-container').scroll(this.hide.bind(this));this.addEvent('preHide',function(){this.hiding=true;});this.addEvent('hide',function(){this.hiding=false;});},slide:function(){if(this.$target.is(':hidden')&&!this.$target.is(':animated')){this.$target.show();this.fireEvent('preShow');this.$target.hide();this.$target.toggle('slide',{easing:'easeOutElastic',duration:5000,direction:'up'},'slow',function(){this.fireEvent('show');}.bind(this));}else if(this.$target.is(':visible')&&!this.$target.is(':animated')){this.fireEvent('preHide');this.$target.toggle('slide',{easing:'easeInBack',duration:5000,direction:'up'},'slow',function(){this.fireEvent('hide');}.bind(this));}},hide:function(){if(this.$target.is(':visible')&&this.hiding!=true){this.slide();}}});Application.Modules.CoinHelpTip=new Class({Extends:Application.Modules.HelpTip,Binds:['triggerShow'],initialize:function($drawer){this.$drawer=$drawer;this.parent(this.$drawer,{placement:'cr',offset:{cr:{left:30,top:0}},source:false});this.$content.append($('.coin-drawer-tips'));},triggerShow:function(mode,message){var event={target:this.$drawer};if(typeof mode=="string"){event.displayMode=mode;event.displayMessage=message;}
this.parent(event);},showError:function(error){this.triggerShow("error");},showSuccess:function(error){this.triggerShow("error");},setContent:function(event){this.$content.find('.coin-tip').hide();switch(event.displayMode){case"error":this.getElem().addClass('error').removeClass('alert');this.$content.find('.coin-error').show().find('.answer').html(event.displayMessage);break;case"success":this.getElem().addClass('alert').removeClass('error');this.$content.find('.coin-success').show().find('.answer').html(event.displayMessage);break;default:this.getElem().removeClass('alert error');var $content=this.$content.find('.coin-drawer-description').show();$content.find('.answer').html($content.find('.answer').html().substitute({'coin.amount':this.$drawer.find('.coin').not('.ready').length+' coins'}));break;}}});Application.Modules.ITopbar=new Class({initializeTopbar:function(){this.UserInformationWidget=new Application.Modules.UserInformation();this.PointHistoryWidget=new Application.Modules.PointsHistory();this.UserCoins=Application.Modules.UserCoins.getInstance(this,{});this.UserInformationWidget.addEvent('preShow',function(){this.fireEvent('preShow');}.bind(this));this.PointHistoryWidget.addEvent('preShow',function(){self.fireEvent('preShow');}.bind(this));}});Application.Modules.UserCoins=new Class.Singleton({countdownLayouts:['Just {d<}{dn} day, {d>}{h<}{hn} hrs, {h>}{m<}{mn} min, {m>}{sn} sec to go'],Implements:[Options,Events],options:{triggerSelect:'div.coin-list',drawerSelect:'#coin-drawer',coinSelect:'.coins',readySelect:'.ready',templateClass:'template',animationDuration:500,easeIn:'easeOutElastic',easeOut:'easeInBack',hideWaitTime:500},initialize:function(ape,options){this.setOptions(options);this.setupDrawer();this.$template=this.$drawer.find('.'+this.options.templateClass).detach().removeClass(this.options.templateClass);this.$coinList=this.$drawer.find(this.options.coinSelect);this.hide(0);this.setupTrigger();this.CoinReloader=new Application.Modules.CoinReloader(ape);this.CoinReloader.addEvent('CompletionChangedAll',this.initializeDrawer.bind(this));this.CoinReloader.addEvent('coinsReplaced',this.setupTrigger.bind(this));this.CoinReloader.addEvent('CoinUnlocked',this.coinUnlocked.bind(this));this.initializeDrawer(this.CoinReloader.$getCoins(),true);this.initialize=true;$(window).resize(this.centerBox.bind(this));this.centerBox();},setupDrawer:function(){this.$drawer=$(this.options.drawerSelect);this.$drawer.show();this.drawerTip=new Application.Modules.CoinHelpTip(this.$drawer);this.addEvent('drawerHidden',function(){this.drawerTip.hide();});},centerBox:function(){this.$drawer.css({left:this.$trigger.offset().left});},setupTrigger:function(){this.$trigger=$(this.options.triggerSelect+','+this.options.drawerSelect);this.$trigger.hover(this.show.bind(this),this.hideWait.bind(this));},coinUnlocked:function(message){this.show(false,message,false);},show:function(duration,message,isError){clearTimeout(this.hideWaiter);this.fireEvent('drawerMoving');this.$drawer.removeClass('hiding hidden shown').addClass('showing');this.$drawer.show();this.$drawer.stop(true,false).animate({top:0},typeof duration!='number'?this.options.animationDuration:duration,this.options.easeIn,function(){this.$drawer.removeClass('hiding hidden showing').addClass('shown');if(message){if(isError!==false){this.drawerTip.triggerShow('error',message);}else{this.drawerTip.triggerShow('success',message);}}
this.fireEvent('drawerShown');}.bind(this));},showWithTooltip:function(){this.show();this.drawerTip.triggerShow();},hideWaiter:null,hideWait:function(duration){clearTimeout(this.hideWaiter);this.hideWaiter=setTimeout(function(){this.hide(duration);}.bind(this),this.options.hideWaitTime);},hide:function(duration){this.fireEvent('drawerMoving');this.$drawer.removeClass('hidden shown showing').addClass('hiding');this.$drawer.stop(true,false).animate({top:-this.$drawer.height()},typeof duration!='number'?this.options.animationDuration:duration,this.options.easeOut,function(){this.$drawer.removeClass('hiding shown showing').addClass('hidden');this.$drawer.hide();this.fireEvent('drawerHidden');}.bind(this));},initializeDrawer:function($coins,force){if(this.skipDraw()&&force!==true){return;}
$coins.each(function(i,elem){var $coin=$(elem);this.updateRow($coin);}.bind(this));},getIconTimerRow:function($coin,autoCreate){var coinId=$coin.data('coin-id');var $row=this.$drawer.find('.coin[data-for-coin='+coinId+']');if($row.length<=0&&autoCreate!==false){$row=this.$template.clone();this.$coinList.append($row);$row.attr('data-for-coin',coinId);this.addEvent('drawerMoving',function(){}.bind(this));this.addEvent('drawerShown',function(){this.initCountdown($row);});}
return $row;},reinsert:function($row,prepend){if(prepend===true){this.$coinList.prepend($row);}else{this.$coinList.append($row);}},initCountdown:function($row){clearTimeout($row.data('stopCountdown-waiter'));if($row.is('.done')){this.stopCountdown($row,"Ready to lower prices");}else{$row.find('.counter').fadeIn().countdown({until:$row.data('countdown-date'),layout:this.countdownLayouts.getRandom()});}},stopCountdown:function($row,newText,wait){if(wait===true){clearTimeout($row.data('stopCountdown-waiter'));var counter=setTimeout(function(){this.stopCountdown($row,newText);}.bind(this),1000);$row.data('stopCountdown-waiter',counter);}else{var $counter=$row.find('.counter');if(newText!=null){$counter.countdown('destroy');$counter.html(newText);}else if(!this.$drawer.is('.shown')){$counter.countdown('destroy');}}},updateRow:function($coin){var $row=this.getIconTimerRow($coin);$row.data('countdown-date',new Date($coin.data('ready')*1000));var percent=$coin.data('completion')*100;if(percent>=100){$row.addClass('done');this.reinsert($row,true);}else{if($row.is('.done')){$row.removeClass('done');this.reinsert($row);}}
var numeric=percent.toFixed(2)+'%';if(percent>=100){numeric='Complete';}else if(numeric=='100.000%'){numeric='99.999%';}
$row.find('.numeric span').html(numeric);var $progress=$row.find('.progress');if(percent>=100){$progress.css({width:'100%'});}else{$progress.css({width:Math.max(percent,6)+'%'});}},skipDraw:function(){return!this.$drawer.is('.shown');}});Application.Modules.CoinReloader=new Class({Extends:Application.Tools.AjaxRequest,Implements:[Options,Events],$container:null,countdownPre:null,countdown:null,url:null,initialize:function(ape,options){this.ape=ape;this.ape.onRaw('unlock_coin',this.apeNotification.bind(this));this.$container=$('#top-bar div.coin-list');this.url=this.$container.data('source');options=$.extend({url:this.url,type:'get'},options);this.parent(options);this.setOptions(options);this.addEvent('success',this.success);this.setup();this.refresherTimer=window.setInterval(this.refresher.bind(this),5000);this.addEvent('CompletionChanged',this.resetCompletionState);this.refresher();},apeNotification:function(apeMsg){var html=apeMsg.data.Content.coins;var message=apeMsg.data.Content.message;this.success(html);this.fireEvent('CoinUnlocked',message);},refresher:function(newData){this.$getCoins().each(function(i,elem){this.calculateCompletion($(elem));}.bind(this));this.fireEvent('CompletionChangedAll',[this.$getCoins(),newData===true?true:false]);},execute:function(){clearTimeout(this.countdown);this.parent();},$getCoins:function(){return this.$container.find('a.coin');},setup:function(newData){var timer=this.$container.data('refresh');if(timer<=0){if(newData){this.refresher(newData);}
return;}
timer=timer-5000;if(timer<0){timer=0;}
this.countdown=setTimeout(function(){this.execute();}.bind(this),Math.max(timer-5000,5000));this.refresher(newData);},calculateCompletion:function($coin){var now=new Date();var ready=new Date(parseInt($coin.data('ready'),10)*1000);var used=new Date(parseInt($coin.data('used'),10)*1000);var completion;if(now>ready){completion=1;}else{completion=(now-used)/(ready-used);}
$coin.data('completion',completion);this.fireEvent('CompletionChanged',[$coin,completion]);return completion;},resetCompletionState:function($coin,completion){var transform;if(completion==1){transform={height:$coin.height(),backgroundPosition:"0px 0px"};}else{var show=$coin.height()-Math.round($coin.height()*completion);transform={height:$coin.height()-show+'px',backgroundPosition:"0px -"+show+"px"};}
var $coinProgress=$coin.find('.active');$coinProgress.stop(true,true).css(transform);},success:function(html){$('#top-bar div.coin-list').replaceWith(html);this.fireEvent('coinsReplaced');this.$container=$('#top-bar div.coin-list');this.setup(true);}});Application.Modules.UserInformation=new Class({Extends:Application.Modules.TopBarSlidable,initialize:function(){this.parent();var $link=$('#top-bar .name a.user-information');$('.profile-link').live('click',function(){$link.click();});this.userInfoLink=new Application.Tools.AjaxTrigger($link,{success:this.initializeWidget.bind(this)});$('a.userInfo-close, #user-info-dropdown a.x.close').live('click',this.hide.bind(this));this.addEvent('preShow',function(){this.formatContainer(0);});this.autoClick($link);},autoClick:function($link){var uri=new URI(window.location);if(uri.getData('userinfo')==1){window.addEvent('load',function(){$try($link.click());});}},initializeWidget:function(html){this.$userInfo=$(html).addClass('ajax-popup');$('body').append(this.$userInfo);this.setupSlidable(this.$userInfo);this.addEvent('hide',this.onHideCleanup);this.userInfoReset();this.$scrollable=this.$userInfo.find('.user-info-scrollable');this.$scrollable.scrollable({onSeek:this.scrollSeek.bind(this),onBeforeSeek:function(event,page){this.formatContainer(page);}.bind(this)});this.scrollable=this.$scrollable.data('scrollable');this.initializeStepper(this.$scrollable.find('.content'));$('#user-info-dropdown .headers div').each(function(i,elem){var $div=$(elem);console.log($div);this.initializeStepper($div);}.bind(this));$(window).resize(this.userInfoReset.bind(this));this.fireEvent('InfoLoad',this);this.formatContainer();this.$userInfo.hide();this.slide();},initializeStepper:function($context){var $stepper=$context.find('.stepper');var trigger=new Application.Tools.AjaxTrigger($stepper,{success:this.initializePage.bind(this)});},nextPageIsLoaded:function(){var $next=this.getPage(this.scrollable.getIndex()+1);return($next.length>0)?$next:false;},initializePage:function(html){if(html=='done'){this.scrollable.begin();return;}
var $page=$(html);var $next=this.nextPageIsLoaded();if($next!==false){$next.replaceWith($page);}else{this.scrollable.addItem($page);}
var $form=$page.find('form');var formTrigger=new Application.Tools.AjaxTrigger($form,{success:this.initializePage.bind(this)});$form.validate(Application.Tools.UserInfoRules);this.scrollable.next();this.initializeStepper($page);},getPage:function(page){return $(this.$scrollable.find('div.content')[page]);},scrollSeek:function(event,requestedPage){Application.Tools.fixTabs(this.scrollable.getItems());this.pageSetup(requestedPage);},pageSetup:function(requestedPage){switch(requestedPage){case 0:this.refreshUserProfile();break;case 2:this.photoPageSetup();break;default:return;}},refreshUserProfile:function(){var request=new Application.Tools.AjaxRequest({url:$('.user-information-data').data('source'),type:'get',success:function(html){$('.user-information-data').replaceWith($(html));}.bind(this)});request.execute();},photoPageSetup:function(){var $skip=$('.user-photo-picker a.skip');$('.user-photo-picker img.avatar').each(function(){var $img=$(this);var $a=$img.closest('a');var trigger=new Application.Tools.AjaxTrigger($a,{success:function(json){$('img[data-uid='+json[0]+']').attr('src',json[1]);$skip.click();}});});},formatContainer:function(requestedPage){if(requestedPage==null){requestedPage=this.scrollable.getIndex();}
var $requestedPage=this.getPage(requestedPage);$requestedPage.addClass('active').removeClass('inactive');if(requestedPage==1){this.fitUserInfoIntoWindow(requestedPage);}
this.resizeContainer($requestedPage);},fitUserInfoIntoWindow:function(page){var $page=this.getPage(page);var newHeight=$(window).height()-80;var $ul=$('ul.form-input');var props;if($ul.height()<newHeight){props={height:'auto',marginRight:0,overflow:'auto'};}else{props={height:newHeight,marginRight:0,overflow:'auto'};}
$ul.css(props);},resizeContainer:function($page){if($page.length>0){var height=parseInt($page.height(),10);if(height<=0){height=this.initHeight;}
var resizeProps={height:height};if(this.doAnimateOnResize){this.$scrollable.animate(resizeProps);}else{this.$scrollable.css(resizeProps);}}},onHideCleanup:function(){this.formatContainer(0);this.scrollable.begin();},userInfoReset:function(){this.$userInfo.css({top:parseInt($('#top-bar').css('top'),10),left:this.userInfoLink.$element.offset().left});this.userInfoLink.$element.unbind('click').click(function(){this.slide();return false;}.bind(this));if(this.scrollable){this.formatContainer();}}});Application.Modules.PointsHistory=new Class({Extends:Application.Modules.TopBarSlidable,loadedPages:[],initialize:function(){var self=this;this.parent();this.pointsHistoryLink=new Application.Tools.AjaxTrigger($('#top-bar .score a'),{success:function(html){self.initializeWidget(html);}});if($_YOTTA_.Application.QueryStringObject().showPoints!=null){this.pointsHistoryLink.$element.click();}},initializeWidget:function(html){var self=this;self.seeking=false;this.$pointsHistory=$(html).addClass('ajax-popup');$('body').append(this.$pointsHistory);this.setupSlidable(this.$pointsHistory);this.$pointsHistory.find('.close').click(function(){self.hide();});this.reset();$(window).resize(function(){self.reset();});this.$scrollable=this.$pointsHistory.find('.history-scrollable');this.$pages=this.$scrollable.find('div.history-item');this.scroller=this.$scrollable.scrollable({items:'.history-items',onBeforeSeek:function(event,page){if(self.seeking){return false;}
if(page>=this.getItems().length){return false;}
self.seeking=true;self.beforeSeek(event,page,this);},onSeek:function(event,page){self.seeking=false;self.seek(event,page,this);},mousewheel:true,vertical:true}).data('scrollable');this.loadedPages.push(this.scroller.getIndex());this.resizeContainer(0,0);this.$pointsHistory.hide();this.slide();},beforeSeek:function(event,page,scroller){var self=this;if($.inArray(page,this.loadedPages)>-1){}else{var request=new Application.Tools.AjaxRequest({url:'?action=points_history.page&page='+(page+1),type:'get',success:function(html){self.loadPage(page,html);},error:function(){self.loadedPages=$.grep(self.loadedPages,function(element,arrIndex){return element!=page;});}});request.execute();}
this.loadedPages.push(page);},seek:function(event,page,scroller){this.resizeContainer(page);},resizeContainer:function(page,duration){if(duration==null){duration=100;}
var $pageDiv=$(this.$pages[page]);this.$scrollable.stop(true,false).animate({height:$pageDiv.height()},duration);},loadPage:function(page,html){$(this.$pages[page]).html("").append($(html));this.resizeContainer(page);},reset:function(){var self=this;this.$pointsHistory.css({top:parseInt($('#top-bar').css('top'),10),left:$('#top-bar .score').offset().left+$('#top-bar .score').width()/2
-$('#points-history-dropdown').width()/2});this.pointsHistoryLink.$element.unbind('click').click(function(){self.slide(self.$pointsHistory);return false;});}});Application.Modules.IUnlockedStar=new Class({Extends:Application.Tools.MailOverlay,Implements:Application.Tools.StarList,starChannel:'*star',initialize:function($context){throw"this is a partial class that requires the child to be an extension of Ape.Client";},initializeUnlockedStar:function($context){var self=this;$('#unlockedStarTrigger').tabbedoverlay({fixed:false,onAddItem:function(e,elem){var count=this.getItems().length;var countElem=$(elem).closest('.overlay').find('.count');if(count>1){countElem.text(count).css({display:'block',height:'0px',top:'0px'}).animate({height:'35px',top:'-35px'});}else{countElem.css('display','none');}
$(elem).find('a.view-achievements').not('initialized').click(function(){var overlay=self.getUnlockedStarOverlay();setTimeout(function(){$('a.overlay_trigger').not('.stars').click();},500);overlay.close();}).addClass('initialized');Application.Tools.BasicTooltip.initTooltips($(elem).find('img[title]'));},whenClose:function(e){this.getOverlay().find('items').remove();this.getOverlay().find('.count').removeClass('star');}});this.addChannel(this.starChannel);this.onRaw('DisplayUnlockedStar',this.displayUnlockedStar);},displayUnlockedStar:function(param){var overlay=this.getUnlockedStarOverlay();if(overlay){overlay.getOverlay().find('.count').addClass('star');if(overlay.isOpened()){overlay.addItem(param.data.Content);}else{overlay.addItem(param.data.Content);overlay.load();}}},displayInApeMessageOverlay:function(content){this.displayOverlay(content);}});Application.Modules.IVideo=new Class({displayVideo:function(vidName){var self=this;if(typeof self.displayInApeMessageOverlay!=='function'){throw'controller must implement the iunlockedstar interface to display videos';}
var n=vidName.toLowerCase();var vid=$('#'+n);if(vid.length){self.displayInApeMessageOverlay(vid.html());}
else{var onSuccess=function(data,textStatus,XMLHttpRequest){self.displayInApeMessageOverlay(data);};var req=new Application.Tools.AjaxRequest({url:$_YOTTA_.Application.GetApplicationURL('video.'+vidName.toLowerCase()),success:onSuccess});req.execute();}},markVideoAsWatched:function(vidName){var request=new Application.Tools.AjaxRequest({url:'?action=video.markAsWatched&video='+vidName,type:'post',success:function(html){}});request.execute();},markVideoAsUnlocked:function(vidName){var request=new Application.Tools.AjaxRequest({url:'?action=video.unlockVideo&video='+vidName,type:'post',success:function(html){console.log(html);}});request.execute();}});Application.Videos={LowerPrice:'LowerPrice',UnlockedStar:'UnlockedStar'};Application.Modules.LowerPriceTriggerBehavior=new Class({Implements:[Application.Tools.ScoreUpdater,Events],Binds:['onLowerPriceSuccess','onTriggerSuccess'],captchaGenerator:null,options:{initializedFlag:'trigger-initialized',defaultSelector:'a.ajax-lower-price'},initialize:function(selector,$buttonOriginal){if(selector==null){selector=this.options.defaultSelector;}
$(selector).not('.'+this.options.initializedFlag).each(function(i,element){var $elem=$(element);$elem.addClass(this.options.initializedFlag);var options={};if($elem.is('form')){options.success=function(html){this.onTriggerSuccess(html,$buttonOriginal);}.bind(this);}else{$elem.click(function(){$elem.addClass('grey-button');this.bounceButton($elem,{});}.bind(this));options.success=function(html){this.onTriggerSuccess(html,$elem);}.bind(this);}
var trigger=new Application.Tools.AjaxTrigger($elem,options);}.bind(this));},onLowerPriceSuccess:function($html,$button){var itemData=$html.find('.item-data').contentAsJson();var user=itemData[2],sale=itemData[0],hasLowered=itemData[1],actionInfo=itemData[3];this.createPoints($button,{points:actionInfo.points,$boundingBox:this.createTextContainer($button)});this.createSaved($button,{saved:actionInfo.saved,$boundingBox:this.createTextContainer($button)});this.fireEvent('itemReport',[user,hasLowered,sale,actionInfo]);console.log(this);this.SetScore(user.Score);return true;},createTextContainer:function($button){var $container=$('<div/>').appendTo($button.parent()).css({width:500,height:500});$container.css(this.calculateContainerPlacement($button,$container));this.fireEvent("containerCreated",$container);return $container;},calculateContainerPlacement:function($button,$container){return{position:'absolute',bottom:$button.position().top+$button.height()-parseFloat($button.css('margin-bottom')),left:$button.position().left+$button.width()/2-$container.width()/2,overflow:'hidden'};},onTriggerSuccess:function(html,$button){$button.removeClass('grey-button');var $html=$(html);if($html.find('.confirmation-passed').length>0){this.onLowerPriceSuccess($html,$button);return;}else if(($noCoins=$html.find('.no-coins-error')).length>0){this.showNoCoinsError($noCoins);}else{this.showRequestDialog($html,$button);}},showNoCoinsError:function($noCoins){var userCoins=Application.Modules.UserCoins.getInstance();userCoins.show(null,$noCoins.html());$noCoins.remove();},showRequestDialog:function($html,$button){var shortcuts=new Application.Tools.Shortcut();shortcuts.parseShortcuts($html);$html.dialog({width:450,title:'...ooops',modal:true,resizable:false,close:function(){$html.remove();}});var itemData=$html.find('.item-data').contentAsJson();var user=itemData[2],sale=itemData[0],hasLowered=itemData[1],actionInfo=itemData[3];this.fireEvent('itemReport',[user,hasLowered,sale,actionInfo]);var $captcha=$('#rate-captcha');if($captcha.length>0){captcha=new Application.Tools.ReCaptcha();captcha.create($captcha);$html.dialog('option',{title:"Humans Only",height:350});}
var $form=$html.find('form');var formTrigger=new Application.Modules.LowerPriceTriggerBehavior($form,$button);formTrigger.addEvent('itemReport',function(){this.fireEvent('itemReport',arguments);}.bind(this));$form.submit(function(){$html.dialog('close');});},floatText:function($button,value,renderer,options){if(options==null){options={};}
options=$.extend({},{startOffset:-50,offset:-40,duration:400,opacity:0},options);options.offset=parseInt(options.offset,10);options.startOffset=parseInt(options.startOffset,10);var randomizer=new Application.Tools.RandomStringGenerator();var divid=randomizer.generateRandomString();console.log('bounding box',options.$boundingBox);var $text;if(options.$container==null){$text=$('<div id="pqr'+divid+'"></div>').addClass('animated-points');}else{$text=options.$container;}
var $boundingBox=options.$boundingBox;$boundingBox.append($text);renderer.render(value,$text);var initPosition={bottom:0,left:$boundingBox.width()/2-$text.width()/2};$text.css(initPosition);var target=options.offset+options.startOffset;target="-="+target+'px';$text.animate({bottom:target,opacity:options.opacity},options.duration,function(){if(options.onFinish==null){$boundingBox.remove();}else{options.onFinish.call(this,$button,$text,options);}}.bind(this));return $text;},createPoints:function($button,options){var renderer=new Application.Tools.TextRenderer();var points="+"+options.points.toString()+" P";this.floatText($button,points,renderer,{duration:1600,offset:-80,$boundingBox:options.$boundingBox});},createSaved:function($button,options){var renderer=new Application.Tools.DollarRenderer();var saved=parseFloat(options.saved);console.log(saved,saved*100);if(saved<1){saved=parseInt(saved*100,10).toString()+"c OF";console.log(saved);}else{saved=saved+" OF";}
var callback=function(){this.floatText($button,saved,renderer,{duration:1600,startOffset:-60,offset:-80,opacity:0.8,$container:$("<div />").addClass('animated-points saved-points').appendTo($('body')),$boundingBox:options.$boundingBox,onFinish:function($button,$text,options){$text.animate({opacity:0},1000,function(){$text.remove();options.$boundingBox.remove();});}});}.bind(this);setTimeout(callback,500);},bounceButton:function($button,options){options=$.extend({},options,{xDisplacement:"-=30px",yDisplacement:"+=0px",jumpTime:50,resetTime:150});var resetPosition=$button.position();if(options.onStartJump){options.onStartJump.call(this,$button,options);}
$button.animate({top:options.xDisplacement,left:options.yDisplacement},options.jumpTime,function(){$(this).animate({top:"0"},150,function(){if(options.onEndJump){options.onEndJump.call(this,options);}}.bind(this));});}});Application.Modules.LowerPriceTriggerBehavior=new Class({Extends:Application.Modules.LowerPriceTriggerBehavior,Implements:[Application.Tools.ScoreUpdater]});Application.Modules.LowerPriceOverlay=new Class({Extends:Application.Tools.MailOverlay,Implements:[Options,Events],Binds:['PriceLowered','close'],apeClient:null,options:{channel:'*star'},initialize:function(apeClient,options){this.apeClient=apeClient;this.setOptions(options);this.apeClient.onRaw('PriceLowered',this.PriceLowered);this.apeClient.addChannel(this.options.channel);},PriceLowered:function(message){var $content=$(message.data.Content.confirmation);var temp=new Application.Modules.LowerPriceOverlayPage($content);temp.addEvent('close',this.close);this.displayOverlay($content);}});Application.Modules.LowerPriceOverlayPage=new Class({Implements:[Events,Options],Binds:['lowerPriceClick','coinCheckClick','returnClick','settingsUpdateSuccess'],options:{scrollableSelector:'.lower-price-scrollable',scrollableOptions:{}},initialize:function($content,options){this.setOptions(options);this.$content=$content;this.initializeScrollable();this.initializeTriggers();this.initializeRedoBar();this.initializeTooltips();this.initializeSettings();this.initializeSocials();},initializeSettings:function(){this.$settingsForm=this.$content.find('form[name=no-confirmation-form]');this.settingsFormRequest=new Application.Tools.AjaxTrigger(this.$settingsForm,{success:this.settingsUpdateSuccess});this.$settingsForm.find('input[type=checkbox]').change(function(){this.settingsFormRequest.execute();}.bind(this));},settingsUpdateSuccess:function(){this.close();},initializeTooltips:function(){this.settingTip=new Application.Tools.Tooltip(this.$content.find('.no-confirm-input span'),{showWaitTime:50});this.settingTip.options.source=this.$content.find('.no-confirm-tooltip');this.settingTip.getElem().addClass('achievement-tip');},initializeSocials:function(){this.socials=[];this.$content.find('a.facebook, a.twitter').each(function(i,elem){var $trigger=$(elem);this.socials.push(new Application.Tools.SocialTrigger($trigger,{zOverError:10003,modalErrorDialog:false}));}.bind(this));},initializeRedoBar:function(){this.redoBar=new Application.Tools.RedoBar({context:this.$content,toolTip:false});},initializeScrollable:function(){this.$scrollable=this.$content.find(this.options.scrollableSelector);this.scrollable=this.$scrollable.scrollable(this.options.scrollableOptions).scrollable();this.scrollable.seekToSelector=this.helperSeekToSelector.bind(this.scrollable);},initializeTriggers:function(){this.$lowerPrice=this.$content.find('a.button.lower-price-explain');this.$checkCoin=this.$content.find('a.button.coins');this.$returnLink=this.$content.find('a.return, a.return-button');this.$lowerPrice.click(this.lowerPriceClick);this.$checkCoin.click(this.coinCheckClick);if($_YOTTA_.action=='browse'){this.$returnLink.click(this.returnClick);}
this.$content.find('a.view-achievements').not('initialized').click(function(){setTimeout(function(){$($('a.overlay_trigger').not('.stars')[0]).click();},500);this.close();}.bind(this)).addClass('initialized');},lowerPriceClick:function(event){this.scrollable.seekToSelector('.sale-info');},coinCheckClick:function(event){this.UserCoins=Application.Modules.UserCoins.getInstance();this.UserCoins.show();setTimeout(this.UserCoins.drawerTip.triggerShow,500);this.close();},returnClick:function(){this.close();return false;},close:function(){this.settingTip.cleanup();this.socials.each(function(social,i){social.cleanup();},this);this.fireEvent('close');},helperSeekToSelector:function(selector,speed){var $items=this.getItems();var found=false;$items.each(function(i,elem){if(found!==false){return;}
var $elem=$(elem);if($elem.is(selector)){found=i;}});if(found!==false){this.seekTo(found,speed);}}});Application.Modules.TickerTalkBubble=new Class({Extends:Application.Tools.TalkBubble,initialize:function(options){this.parent(options);this.initTextTokens();},initTextTokens:function(){var tokens=[{key:'{user.name}',value:'<span class="username"></span>'},{key:'{user.subjective}',value:'<span class="gender subjective"></span>'},{key:'{user.objective}',value:'<span class="gender objective"></span>'},{key:'{user.possessive}',value:'<span class="gender possessive"></span>'},{key:'{user.reflexive}',value:'<span class="gender reflexive"></span>'}],text=this.$elem.html();if(text){for(var i=0;i<tokens.length;i++){var token=tokens[i];var regex=new RegExp(tokens[i].key,'gi');text=text.replace(regex,tokens[i].value);}
this.$elem.html(text);}},messageCount:null,messageIndex:0,loadNextMessage:function(){if(this.messageCount==null){this.messageCount=this.$elem.find('.row.title').children('p').length;}
var index=(this.messageIndex%this.messageCount)+1;console.log('the index',index);window.test=this.$elem;this.$elem.find('.row.title').children('p').css('display','none');this.$elem.find('.row.title').children('p:nth-child('+index+')').css('display','block');this.$elem.find('.row.quote').children('blockquote').css('display','none');this.$elem.find('.row.quote').children('blockquote:nth-child('+index+')').css('display','block');this.messageIndex++;},loadRandomMessage:function(){if(this.$elem.find('.row.title').children('p').not('.used').length==0){this.$elem.find('.row.title').children('p').removeClass('used');}
var $titles=this.$elem.find('.row.title').children('p'),$availableTitles=$titles.not('.used'),$visible=$availableTitles.filter(':visible'),$targetTitle=$($availableTitles[$random(0,$availableTitles.length-1)]),$quotes=this.$elem.find('.row.quote').children('blockquote'),$targetQuote=this.$elem.find($targetTitle.attr('rel'));$titles.css('display','none');$quotes.css('display','none');$targetTitle.css('display','block').addClass('used');$targetQuote.css('display','block');}});
