var AuctionPeriodicUpdater=new Class(
{Implements:[Options,Events],
	options:{},initialize:function(a){
		this.setOptions(a);
	  this.interval=this.interval.bind(this);
	  this.resetRequestCountdown=this.resetRequestCountdown.bind(this);
	  this.maxRequestCountdown=600;
	  this.resetRequestCountdown();
	  this.discoverUser();
	  this.discoverAuctions();
	  this.addButtons();
	  $(document.body).addEvent("mousemove",this.resetRequestCountdown);
	  this.connectionIssuesBox=document.id("having_connection_issues");
	  if(this.connectionIssuesBox){
	  	this.connectionIssuesBox.set("text","We're having problems talking to the server? Perhaps you can check your internet connection? ")
	  }
	  if($H(this.auctions).getKeys().length){
	  	this.start()
	  }else{
	  	$log("No Auctions.  Not starting any monitoring processes.")
	  }
	},
	discoverAuctions:function(){
		this.auctions={};
		$$(".auction_id").get("text").each(function(c){
			var d=this.auctions[c]={};
			var b="auction"+c+"_";
			d.price=document.id(b+"price");
			d.offRetail=document.id(b+"offretail");
			d.winner=document.id(b+"winner");
			d.countdown=document.id(b+"countdown");
			d.message=document.id(b+"message");
			d.priceChange=document.id(b+"pricechange");
			d.downIcon=document.id(b+"downicon");
			d.timeChange=document.id(b+"timechange");
			d.bidsNoBids=document.id(b+"bids_nobids");
			d.userAutobids=document.id(b+"user_autobids");
			d.userAutobidsEnabled=document.id(b+"autobids_enabled");
			d.excitement=document.id(b+"excitement");
			if(d.downIcon){
				d.downIconFx=new Fx.Tween(d.downIcon,{duration:400});
				d.downIconFx.set("opacity",0.6)
			}
			if(document.id(b+"bids")){
				d.bidNoBids=document.id(b+"autobids_enabled");
				var a=d.bids=[];
				for(var e=0;e<10;e++){
					var f=b+"bid_"+e+"_";
					a.push({id:document.id(f+"id"),time:document.id(f+"time"),user:document.id(f+"user"),bidType:document.id(f+"type")})
				}
			}
		},this)
	},
	discoverUser:function(){
		this.user={};
		this.user.loggedInStatus=document.id("logged_in_status");
		this.user.isLoggedIn=this.user.loggedInStatus&&(this.user.loggedInStatus.get("text")==="true");
		this.user.hasAccountDom=document.id("has_account");
		this.user.hasAccount=this.user.hasAccountDom&&(this.user.hasAccountDom.get("text")==="true")
	},
	
	start:function(){
		this.request=new Request.JSON(
		   {url:"/auctions/live"+(this.user.isLoggedIn?"?u=1":""),sendingJson:false,method:"get",
		   	noCache:true,dontHandleErrors:true,
		   	onSuccess:this.gotAuctionData.bind(this),
		   	onFailure:this.failedRequest.bind(this)}
		);
		this.auctionTimer=setTimeout(this.interval,1000)
	},
	interval:function(){
		this.request.send()},
		gotAuctionData:function(b){
			if(this.connectionIssuesBox){this.connectionIssuesBox.setStyle("display","none")}
			if($type(b.auctions)=="array"){
				var a=true;
				b.auctions.each(function(e){
					var d=this.auctions[e.id];
					if(d){
						this.updateAuction(e,d);
						a=a&&d.isEnded
					}
			  },this);
			  if(a){
			  	$clear(this.auctionTimer);
			  	this.auctionTimer=null
			  }
		 }
		 if(b.user){
		 	this.updateUser(b.user)
		 }
		 if((this.auctionTimer!==null)&&!b.stopIt){
		 	if(this.requestCountdown>0){
		 		this.requestCountdown--;
		 		this.auctionTimer=setTimeout(this.interval,900)
		 	}else{
		 		var c=new MessageBox({title:"Are you still there?",message:"<br />We haven't noticed any activity from you.<br /><br />If you're still there, click <a href='javascript:;' class='close'>here</a> to return to your auctions.",status:"notice",confusing:true});
		 		c.addEvent("hide",function(){
		 			this.resetRequestCountdown();
		 			this.auctionTimer=setTimeout(this.interval,900)
		 	  }.bind(this))
		 	}
		 }
		},
		failedRequest:function(){
			if(this.connectionIssuesBox){
				this.connectionIssuesBox.setStyle("display","block")
			}
			this.auctionTimer=setTimeout(this.interval,1000)
		},
		
		updateAuction:function(e,a){
			if(a.price){
				if(a.oldPriceData&&(a.oldPriceData!=e.price)){
					a.price.highlight();
					if(a.priceChange){
						var c=e.price-a.oldPriceData;
						if(c>=1||c<=-1){
							a.priceChange.flash((c<0?"-":"+")+"$"+Math.abs(c).toFixed(2),1000)
						}else{
							a.priceChange.flash((c<0?"-":"+")+(Math.abs(c).round(2)*100).round().toString()+"\u00a2",1000)
						}
					}
					if(a.downIconFx){
						a.downIconFx.set("opacity",1).start("opacity",1,0.5)
					}
				}
				a.price.set("text",(e.price<0?"-$":"$")+Math.abs(e.price).toFixed(2));
				a.oldPriceData=e.price
			}
			if(a.offRetail){
				a.offRetail.set("text",e.savings[1].round(2)+"%")
			}
			if(a.winner){
				if(a.oldWinnerData&&(a.oldWinnerData!=e.winner)){
					a.winner.highlight()
				}
				a.winner.set("text",e.winner||"-");
				a.oldWinnerData=e.winner
			}
			if(a.countdown){
				if(a.oldEndTime&&(a.oldEndTime!=e.end_time)){
					if(a.excitement){
						a.excitement.set("text","")
					}
					a.countdown.highlight();
					var h=(e.end_time-a.oldEndTime).round();
					if(a.timeChange){
						a.timeChange.flash((h>0?"+":"-")+Math.abs(h)+" secs",1000)
					}
				}
				if(e.is_ended){
					if(a.excitement){
						a.excitement.set("text","")
					}
					var b=a.countdown.get("text")==="Ended";
					a.countdown.set("text","Ended");
					document.id("auction"+e.id+"_winnerlabel").set("text","Winner:");
					a.isEnded=true;
					if(!b){
						if(($appInfo.controller=="auctions")&&($appInfo.action=="show")){
							window.location.href=window.location.href+"?closed=1"
						}
					}
				}else{
					a.countdown.set("text",e.countdown)
				}
				if(e.countdown.match(/^\d+ seconds/)){
					a.countdown.addClass("near")
				}
				a.oldEndTime=e.end_time
			}
			var g=e.bids;if(a.bids&&g){
				if(a.bidNoBids){
					a.bidsNoBids.setStyle("display",g.length?"none":(Browser.Engines.trident()?"block":"table-row"))
				}
				if(g.length){
					var d=g[0].id;
					if(a.bids[0].id.get("text")!=d){
						var f=0;
						g.each(function(i){
							var k=i.id;
							var j=Date.parse(i.time);
							a.bids[f].id.set("text",k);
							a.bids[f].time.set("text",j.format("%I:%M:%S"));
							a.bids[f].user.set("text",i.user);
							a.bids[f].bidType.set("text",i.bid_type);f+=1
						})
					}
				}
			}
		},
		
		updateUser:function(a){
			if($chk(a.bids_remaining)){
				this.user.bidsAvailable=this.user.bidsAvailable||document.id("user_bids");
				if(this.user.bidsAvailable){
					this.user.bidsAvailable.set("text",a.bids_remaining)
				}
			}
			if(a.autobids_remaining){
				$each(this.auctions,function(b,c){
					if(b.userAutobidsEnabled){
						b.userAutobidsEnabled.addClass("disabled").removeClass("enabled")
					}
				});
				$each(a.autobids_remaining,function(c,b){
					if(this.auctions[b]&&this.auctions[b].userAutobids&&this.auctions[b].userAutobidsEnabled){
						if(c){
							this.auctions[b].userAutobidsEnabled.addClass("enabled").removeClass("disabled")
					  }else{
					  	this.auctions[b].userAutobidsEnabled.addClass("disabled").removeClass("enabled")
					  }
					  this.auctions[b].userAutobids.set("text",c)
					}
			  }.bind(this))
			 }
			},
			
			addButtons:function(){
				$$(".bid_button").each(function(c){
					var a=c.get("rel");
					var b=new Request.JSON({
						url:c.get("href").slice(1),data:{},
						sendingJson:true,
						method:"post",
						onSuccess:this.bidSuccess.bind(this),
						onFailure:this.bidFailure.bind(this)
					});
					
					c.addEvent("click",function(d){
						$S(d);
						this.resetRequestCountdown();
						b.send()}.bind(this)
					)
				},this);
				
				$$(".bidbuddy_button").each(function(c){
					var b=c.get("rel");
					var a=new Request.JSON({
						url:c.get("href").slice(1),
						sendingJson:true,
						method:"post",
						onSuccess:this.bidSuccess.bind(this),
						onFailure:this.bidFailure.bind(this)
					});
					var d=document.id("autobid_count");
					c.addEvent("click",function(e){
						$S(e);
						this.resetRequestCountdown();
						var f=d.get("value");
						if(f==="0"){
							this.auctions[b].
							message.flash("Please select a bid quantity.")
						}else{
							a.send({data:{count:f,auction_id:b}
								})
						}
					}.bind(this))
				},this);
				
				$$(".cancel_autobids").each(function(b){
					var a=new Request.JSON({
						url:b.get("href").slice(1),method:"delete",
						sendingJson:false,
						onSuccess:this.bidSuccess.bind(this),
						onFailure:this.bidFailure.bind(this)
					});
					
					b.addEvent("click",function(c){
						$S(c);
						this.resetRequestCountdown();
						a.send()
					}.bind(this))
				},this)
			},
			
			bidSuccess:function(a){
				$log("Got into bidSuccess with ",a);
				if(a.message&&this.auctions[a.auction_id]&&this.auctions[a.auction_id].message){
					this.auctions[a.auction_id].message.flash(a.message)
				}
			},
			
			bidFailure:function(b){
				var a=this.request.response.json;
				if([404,409,422].contains(b.status)&&($type(a)=="object")){}
			},
			
			resetRequestCountdown:function(){
				this.requestCountdown=this.maxRequestCountdown
			}			
		});
		
		App.page({
			initialize:function(){
				$log("Auctions/index: entered");
				new AuctionPeriodicUpdater();
				var a=$$(".auction_panel");
				a.each(function(b){
					var c=$$(".auction_panel").erase(b);
					b.addEvents({
						mouseenter:function(){
							c.tween("opacity",0.5)
						},
						mouseleave:function(){
							c.tween("opacity",1)
						},
						click:function(f){
							$S(f);
							var d=this.getElement("h3 a");
							window.location=d.href
						}
					}
				)}
			 )
			}});