var g_time = 0;
var g_fullView = 0;

var ASystem = Class.create({
	initialize: function(time,url,loggedIn) {
		this.m_auctions = [];
		this.m_time = time;
		g_time = this.m_time;
		this.m_url = url;
		this.m_loggedIn = loggedIn;
		this.m_sessionTimer = setTimeout("g_system.SessionEnd()",1000*60*10);
		setTimeout("g_system.GetNewTime()",1000);
		setTimeout("g_system.GetAuctions()",2000);
	},
	SessionEnd: function() {
		document.location = g_system.m_url+'pages/sessionend.php';
	},
	RestartSessionTimer: function() {
		clearTimeout(this.m_sessionTimer);
		this.m_sessionTimer = setTimeout("g_system.SessionEnd()",1000*60*10);
	},
	IsLoggedIn: function() {
		return this.m_loggedIn;
	},
	GetURL: function() {
		return this.m_url;
	},
	AddAuction: function(auction) {
		this.m_auctions.push(auction);
	},
	GetAuction: function(auctionId) {
		foundAuction = null;
		this.m_auctions.each(function(item)
		{
			if(item.m_id == auctionId)
			{
				foundAuction = item;
			}
		});
		return foundAuction;
	},
	UpdateTimers: function() {
		this.m_time++;
		g_time = this.m_time;
		this.m_auctions.each(function(item)
		{
			item.UpdateTimer(g_time);
		});
		var dateObj = new Date(g_time*1000);
		$('SystemTime').innerHTML = AddLeadingZero(dateObj.getHours())+":"+AddLeadingZero(dateObj.getMinutes())+":"+AddLeadingZero(dateObj.getSeconds());
		setTimeout("g_system.UpdateTimers()",1000);
	},
	SetTime: function(time) {
		this.m_time = time;
	},
	GetNewTime: function() {
		new Ajax.Request(g_system.m_url+'ajax/getTime.php', 
		{
			method:'get',
			parameters: {"rand": g_time},
			onSuccess: function(transport)
			{
				var json = transport.responseText.evalJSON(true);
				if(json.result == 'OK')
				{
					g_system.SetTime(json.time);
				}else
				{
					alert(result);
				}
				setTimeout("g_system.GetNewTime()",30000);
			},
			onFailure: function()
			{
				setTimeout("g_system.GetNewTime()",30000);
			}
		});
	},
	GetAuctions: function() {
		new Ajax.Request(g_system.m_url+'ajax/updateAuctions.php', 
		{
			method:'get',
			parameters: {"rand": g_time},
			onSuccess: function(transport)
			{
				try
				{
					var json = transport.responseText.evalJSON(true);
					if(json.result == 'OK')
					{
						g_system.UpdateAuctionsFromJSON(json);
					}else
					{
						alert(result);
					}
				}
				catch(exception)
				{
					
				}
				
				setTimeout("g_system.GetAuctions()",3000);
			},
			onFailure: function()
			{
				setTimeout("g_system.GetAuctions()",3000);
			}
		});
	},
	UpdateAuctionsFromJSON: function(json) {
		//alert(json.auctions[0].Header);
		for(var i=0; i < json.auctions.length; i++)
		{
			var auction = this.GetAuction(json.auctions[i].AuctionId);
			if(auction != null)
			{
				var paused = false;
				if(json.auctions[i].Paused == 1)
				{
					paused = true;
				}
				auction.SetParameters(json.auctions[i].Header, json.auctions[i].StartTime, json.auctions[i].EndTime, json.auctions[i].BidBlock, json.auctions[i].NrOfBids, json.auctions[i].Bidders, paused, json.auctions[i].PausedReason, json.auctions[i].Status);
			}
		}
	}
});

var Auction = Class.create({
	initialize: function(id, header, value, starttime, endtime, bids, bidders, paused, pausedReason, fameview, fameonly, status) {
		this.m_id = id;
		this.m_header = header;
		this.m_value = value;
		this.m_startTime = starttime;
		this.m_endTime = endtime;
		this.m_bids = bids;
		this.m_bidders = bidders;
		this.m_fullView = false;
		this.m_fameView = fameview;
		this.m_fameOnly = fameonly;
		this.m_paused = paused;
		this.m_pausedReason = pausedReason;
		this.m_status = status;
		var self = this;
		if(this.m_fameOnly == false)
		{
			if(g_system.IsLoggedIn())
			{
				$('auction_bidbutton_'+this.m_id).onclick = function()
				{
					self.MakeBid();
				}
			}else
			{
				$('auction_bidbutton_'+this.m_id).onclick = function()
				{
					document.location = g_system.GetURL()+'pages/register.php';
				}
	
			}
			var descClicks = $$('.auction_description_'+this.m_id);
			for(var i =0; i < descClicks.length; i++)
			{
				descClicks[i].onclick = function()
				{
					/*g_fullView = self.m_id;
					myLightWindow.activateWindow({
						href: '#auctionDescription', 
						title: self.m_header, 
						type: 'inline',
						width: 600,
						height: 500
					});
					new Ajax.Updater($$('#lightwindow_contents .auctionDescription')[0], g_system.m_url+'ajax/getAuctionDescription.php', {
						parameters: { 'auctionId': self.m_id },
						method:'get'
					});*/
					document.location = g_system.m_url+'pages/showauction.php?auction='+self.m_id;
				}
			}
			if(this.m_status == 1)
			{
				if(this.m_paused == false)
				{
					$('auction_time_'+this.m_id).style.display = '';
					$('auction_warning_'+this.m_id).style.display = 'none';
					$('auction_info_'+this.m_id).style.display = 'none';
					$('auction_bottom_'+this.m_id).style.display = '';
					$('auction_winner_'+this.m_id).style.display = 'none';
				}
				
				$('auction_header_'+this.m_id).innerHTML = this.m_header;
				$('auction_bid_'+this.m_id).innerHTML = RoundNumber(this.m_bids/10,2);
				if(this.m_bidders.length > 0)
				{
					$('auction_lastbiddertext_'+this.m_id).innerHTML = 'Senaste bud:';
					$('auction_lastbidder_'+this.m_id).innerHTML = this.m_bidders[0];
				}else
				{
					$('auction_lastbiddertext_'+this.m_id).innerHTML = 'Inga bud har inkommit';
				}
				if(this.m_startTime > g_time)
				{
					$('auction_timedescription_'+this.m_id).innerHTML = 'Auktionen startar om ';
				}else
				{
					$('auction_timedescription_'+this.m_id).innerHTML = 'Om inga bud kommer in, så stängs auktionen om ';
				}
			}else if(this.m_status == 2)
			{
				$('auction_time_'+this.m_id).style.display = 'none';
				$('auction_bidtime_'+this.m_id).style.display = 'none';
				$('auction_warning_'+this.m_id).style.display = 'none';
				$('auction_info_'+this.m_id).style.display = '';
				$('auction_info_'+this.m_id).innerHTML = '<br /><br />Auktionen är avslutad, vinnare kontrolleras';
				//$('auction_timedescription_'+this.m_id).style.display = 'none';
				$('auction_lastbidder_'+this.m_id).style.display = 'none';
				$('auction_bid_'+this.m_id).innerHTML = RoundNumber(this.m_bids/10,2);
				$('auction_bottom_'+this.m_id).style.display = 'none';
				$('auction_winner_'+this.m_id).style.display = 'none';
				//$('auction_bid_'+this.m_id).style.display = 'none';
			}else if(this.m_status > 2)
			{
				$('auction_time_'+this.m_id).style.display = 'none';
				$('auction_bidtime_'+this.m_id).style.display = 'none';
				$('auction_warning_'+this.m_id).style.display = 'none';
				$('auction_info_'+this.m_id).style.display = '';
				$('auction_info_'+this.m_id).innerHTML = '<br /><br />Auktionen är avslutad och vinnare utsedd';
				$('auction_lastbidder_'+this.m_id).style.display = '';
				$('auction_bid_'+this.m_id).innerHTML = RoundNumber(this.m_bids/10,2);
				$('auction_bidbutton_'+this.m_id).style.display = 'none';
				$('auction_bottom_'+this.m_id).style.display = 'none';
				$('auction_winner_'+this.m_id).style.display = '';
				
				$('auction_winner_'+this.m_id).innerHTML = 'Vinnare: '+this.m_bidders[0];
			}
		}
		if(this.m_fameView == true)
		{
			
			if(g_system.IsLoggedIn())
			{
				$('fame_bidbutton').onclick = function()
				{
					self.MakeBid();
				}
			}else
			{
				$('fame_bidbutton').onclick = function()
				{
					document.location = g_system.GetURL()+'pages/register.php';
				}
	
			}
			var descClicks = $$('.fame_description');
			for(var i =0; i < descClicks.length; i++)
			{
				descClicks[i].onclick = function()
				{
					document.location = g_system.m_url+'pages/showauction.php?auction='+self.m_id;
				}
			}
			/*$('fame_description').onclick = function()
			{
				document.location = g_system.m_url+'pages/showauction.php?auction='+self.m_id;
			}*/
			if(this.m_status == 1)
			{
				if(this.m_paused == false)
				{
					$('fame_time').style.display = '';
					$('fame_warning').style.display = 'none';
					$('fame_info').style.display = 'none';
					$('fame_bottom').style.display = '';
					$('fame_winner').style.display = 'none';
				}
				
				$('fame_header').innerHTML = this.m_header;
				$('fame_bid').innerHTML = RoundNumber(this.m_bids/10,2);
				if(this.m_bidders.length > 0)
				{
					$('fame_lastbiddertext').innerHTML = 'Senaste bud:';
					$('fame_lastbidder').innerHTML = this.m_bidders[0];
				}else
				{
					$('fame_lastbiddertext').innerHTML = 'Inga bud har inkommit';
				}
				if(this.m_startTime > g_time)
				{
					$('fame_timedescription').innerHTML = 'Auktionen startar om ';
				}else
				{
					$('fame_timedescription').innerHTML = 'Om inga bud kommer in, så stängs auktionen om ';
				}
			}else if(this.m_status == 2)
			{
				$('fame_time').style.display = 'none';
				$('fame_warning').style.display = 'none';
				$('fame_info').style.display = '';
				$('fame_info').innerHTML = 'Auktionen är avslutad, vinnare kontrolleras';
				//$('fame_timedescription').style.display = 'none';
				$('fame_lastbidder').style.display = 'none';
				$('fame_bid').innerHTML = RoundNumber(this.m_bids/10,2);
				$('fame_bottom').style.display = 'none';
				$('fame_winner').style.display = 'none';
				//$('fame_bid').style.display = 'none';
			}else if(this.m_status > 2)
			{
				$('fame_time').style.display = 'none';
				$('fame_warning').style.display = 'none';
				$('fame_info').style.display = '';
				$('fame_info').innerHTML = 'Auktionen är avslutad och vinnare utsedd';
				$('fame_lastbidder').style.display = '';
				$('fame_bid').innerHTML = RoundNumber(this.m_bids/10,2);
				$('fame_bidbutton').style.display = 'none';
				$('fame_bottom').style.display = 'none';
				$('fame_winner').style.display = '';
				
				$('fame_winner').innerHTML = 'Vinnare: '+this.m_bidders[0];
			}
			/*$('fame_header').innerHTML = this.m_header;
			$('fame_bid').innerHTML = RoundNumber(this.m_bids/10,2);
			$('fame_value').innerHTML = this.m_value;
			$('fame_description').onclick = function()
			{
				g_fullView = self.m_id;
				myLightWindow.activateWindow({
					href: '#auctionDescription', 
					title: self.m_header, 
					type: 'inline',
					width: 600,
					height: 400
				});
				new Ajax.Updater($$('#lightwindow_contents .auctionDescription')[0], g_system.m_url+'ajax/getAuctionDescription.php', {
					parameters: { 'auctionId': self.m_id },
					method:'get'
				});

			}*/
		}
	},
	SetParameters: function(header, startTime, endTime, bidBlock, bids, bidders, paused, pausedReason, status) {
		this.m_header = header;
		this.m_startTime = startTime;
		this.m_endTime = endTime;
		this.m_bidBlock = bidBlock;
		var newBid = false;
		if(this.m_bids != bids)
		{
			newBid = true;
		}
		this.m_bids = bids;
		this.m_bidders = bidders;
		this.m_paused = paused;
		this.m_pausedReason = pausedReason;
		this.m_status = status;
		if(this.m_fameOnly == false)
		{
			$('auction_header_'+this.m_id).innerHTML = this.m_header;
			if(this.m_status == 1)
			{
				if(this.m_paused == false)
				{
					$('auction_time_'+this.m_id).style.display = '';
					$('auction_warning_'+this.m_id).style.display = 'none';
					$('auction_info_'+this.m_id).style.display = 'none';
				}
				
				$('auction_bid_'+this.m_id).innerHTML = RoundNumber(this.m_bids/10,2);
				if(this.m_bidders.length > 0)
				{
					$('auction_lastbiddertext_'+this.m_id).innerHTML = 'Senaste bud:';
					$('auction_lastbidder_'+this.m_id).innerHTML = this.m_bidders[0]['Username'];
				}else
				{
					$('auction_lastbiddertext_'+this.m_id).innerHTML = 'Inga bud har inkommit';
				}
				if(this.m_startTime > g_time)
				{
					$('auction_timedescription_'+this.m_id).innerHTML = 'Auktionen startar om ';
					if(this.m_bidBlock == 1)
					{
						$('auction_bidbutton_'+this.m_id).className = 'bidbutton_disabled';
						$('auction_bidbutton_'+this.m_id).disabled = true;
					}
				}else
				{
					$('auction_timedescription_'+this.m_id).innerHTML = 'Om inga bud kommer in, så stängs auktionen om ';
					$('auction_bidbutton_'+this.m_id).className = 'bidbutton';
					$('auction_bidbutton_'+this.m_id).disabled = false;
				}
				this.UpdateLast5Bids();
			}else if(this.m_status == 2)
			{
				$('auction_time_'+this.m_id).style.display = 'none';
				$('auction_warning_'+this.m_id).style.display = 'none';
				$('auction_info_'+this.m_id).style.display = '';
				$('auction_info_'+this.m_id).innerHTML = '<br /><br />Auktionen är avslutad, vinnare kontrolleras';
				//$('auction_timedescription_'+this.m_id).style.display = 'none';
				$('auction_lastbidder_'+this.m_id).style.display = 'none';
				$('auction_bid_'+this.m_id).innerHTML = RoundNumber(this.m_bids/10,2);
				
				$('auction_bidbutton_'+this.m_id).style.display = 'none';
				//$('auction_bid_'+this.m_id).style.display = 'none';
			}
			if(newBid == true)
			{
				new Effect.Highlight('auction_timeleft_'+this.m_id);
			}
		}
		if(g_fullView == this.m_id)
		{
			if(this.m_startTime > g_time)
			{
				$$('#lightwindow_contents .auctionTimeDescription')[0].innerHTML = 'Auktionen startar om ';
			}else
			{
				$$('#lightwindow_contents .auctionTimeDescription')[0].innerHTML = 'Om inga bud kommer in, så stängs auktionen om ';
			}
		}
		if(this.m_fameView == true)
		{
			$('fame_header').innerHTML = this.m_header;
			if(this.m_status == 1)

			{
				if(this.m_paused == false)
				{
					$('fame_time').style.display = '';
					$('fame_warning').style.display = 'none';
					$('fame_info').style.display = 'none';
				}
				
				$('fame_bid').innerHTML = RoundNumber(this.m_bids/10,2);
				if(this.m_bidders.length > 0)
				{
					$('fame_lastbiddertext').innerHTML = 'Senaste bud:';
					$('fame_lastbidder').innerHTML = this.m_bidders[0];
				}else
				{
					$('fame_lastbiddertext').innerHTML = 'Inga bud har inkommit';
				}
				if(this.m_startTime > g_time)
				{
					$('fame_timedescription').innerHTML = 'Auktionen startar om ';
					if(this.m_bidBlock == 1)
					{
						$('fame_bidbutton').className = 'fame_bidbutton_disabled';
						$('fame_bidbutton').disabled = true;
					}
				}else
				{
					$('fame_timedescription').innerHTML = 'Om inga bud kommer in, så stängs auktionen om ';
					$('fame_bidbutton').className = 'fame_bidbutton';
					$('fame_bidbutton').disabled = false;
				}
			}else if(this.m_status == 2)
			{
				$('fame_time').style.display = 'none';
				$('fame_timeleft').style.display = 'none';
				$('fame_warning').style.display = 'none';
				$('fame_info').style.display = '';
				$('fame_info').innerHTML = 'Auktionen är avslutad, vinnare kontrolleras';
				//$('fame_timedescription').style.display = 'none';
				$('fame_lastbidder').style.display = 'none';
				$('fame_bid').innerHTML = RoundNumber(this.m_bids/10,2);
				
				$('fame_bidbutton').style.display = 'none';
				//$('fame_bid').style.display = 'none';
			}
			if(newBid == true)
			{
				new Effect.Highlight('fame_timeleft');
			}
			//$('fame_header').innerHTML = this.m_header;
			//$('fame_bid').innerHTML = RoundNumber(this.m_bids/10,2);
		}
	},
	UpdateLast5Bids: function() {
		if($('last5bids') != null)
		{
			if($('last5bids').style.display == 'none') { $('last5bids').style.display = ''; }
			
			var bid = this.m_bids; //RoundNumber(this.m_bids/10,2)
			for(var i = 0; i < this.m_bidders.length; i++)
			{
				$('last5_name_'+(i+1)).innerHTML = this.m_bidders[i]['Username'];
				$('last5_bid_'+(i+1)).innerHTML = RoundNumber(bid/10,2);
				bid--;
			}
		}
	},
	UpdateTimer: function(currentTime) {
		if(this.m_status > 1) { return; } 
		if(this.m_paused == true)
		{
			if(this.m_fameOnly == false)
			{
				$('auction_timeleft_'+this.m_id).innerHTML = '';
				
				$('auction_time_'+this.m_id).style.display = 'none';
				$('auction_warning_'+this.m_id).style.display = '';
				$('auction_info_'+this.m_id).style.display = 'none';
				$('auction_warning_'+this.m_id).innerHTML = this.m_pausedReason;
			}
			if(g_fullView == this.m_id)
			{
				$$('#lightwindow_contents .auctionTimeLeft')[0].innerHTML = this.m_pausedReason;
			}
			if(this.m_fameView == true)
			{
				$('fame_timeleft').innerHTML = '';
				
				$('fame_time').style.display = 'none';
				$('fame_warning').style.display = '';
				$('fame_info').style.display = 'none';
				$('fame_warning').innerHTML = this.m_pausedReason;
			}
			return;
		}
		var timeLeft = 0;
		if(this.m_startTime > currentTime)
		{
			timeLeft = this.m_startTime-currentTime;
		}else
		{
			timeLeft = this.m_endTime-currentTime;
		}
		var minutes = 0;
		var seconds = 0;
		var hours = 0;
		var days = Math.floor(timeLeft/(60*60*24));
		if(days > 0)
		{
			timeLeft -= days*60*60*24;
			hours = Math.floor(timeLeft/(60*60));
		}else
		{
			hours = Math.floor(timeLeft/(60*60));
		}
		if(hours >= 0)
		{
			timeLeft -= hours*60*60;
			minutes = Math.floor(timeLeft/60);
			seconds = timeLeft-minutes*60;
		}
		var dayText = '';
		var hourText = '';
		var minuteText = '';
		var secondText = '';
		if(days > 0)
		{
			if(days > 1)
			{
				dayText = days+' dagar, ';
			}else
			{
				dayText = days+' dag, ';
			}
		}
		if(hours > 0)
		{
			hourText = hours+' h, ';
		}
		if(minutes > 0 || hours > 0)
		{
			minuteText = minutes+' m och ';
		}
		if(seconds > 0 || minutes > 0 || hours > 0)
		{
			secondText = seconds+' s';
		}else
		{
			minuteText = 'Synkroniserar...';
		}
		if(this.m_fameOnly == false)
		{
			$('auction_timeleft_'+this.m_id).innerHTML = dayText+hourText+minuteText+secondText;
			if(this.m_startTime < currentTime)
			{
				if(this.m_endTime-currentTime < 5)
				{
					Effect.Pulsate('auction_timeleft_'+this.m_id, { pulses: 2, duration: 0.5 });	
				}
			}
		}
		if(g_fullView == this.m_id)
		{
			$$('#lightwindow_contents .auctionTimeLeft')[0].innerHTML = dayText+hourText+minuteText+secondText;
		}
		if(this.m_fameView == true)
		{
			$('fame_timeleft').innerHTML = dayText+hourText+minuteText+secondText;
			if(this.m_startTime < currentTime)
			{
				if(this.m_endTime-currentTime < 5)
				{
					Effect.Pulsate('fame_timeleft', { pulses: 2, duration: 0.5 });	
				}
			}
		}
	},
	MakeBid: function() {
		g_system.RestartSessionTimer();
		if($('user_bids').innerHTML == '0')
		{
			document.location = g_system.GetURL()+'pages/load.php';
			return;
		}
		new Ajax.Request(g_system.m_url+'ajax/makeBid.php', 
		{
			method:'post',
			parameters: {"auctionId": this.m_id, "rand": g_time},
			onSuccess: function(transport)
			{
				if(transport.responseText == '')
				{
					alert('Något blev fel vid budgivningen. Försök igen...');
				}else
				{
					var json = transport.responseText.evalJSON(true);
					if(json.result == 'OK')
					{
						g_system.UpdateAuctionsFromJSON(json);
						
						$('user_bids').innerHTML = $('user_bids').innerHTML-1;
					}else if(json.result == 'NOBIDS')
					{
						alert('Du har inga bud kvar att lägga.');
					}else if(json.result == 'ERROR')
					{
						alert('Något blev fel vid budgivningen. Försök igen...');
					}
				}
			},
			onFailure: function()
			{
				alert('Något blev fel vid budgivningen. Försök igen...');
			}
		});
	}
});


function RoundNumber(number,decimal_points) {
	if(!decimal_points) return Math.round(number);
	if(number == 0) {
		var decimals = "";
		for(var i=0;i<decimal_points;i++) decimals += "0";
		return "0."+decimals;
	}

	var exponent = Math.pow(10,decimal_points);
	var num = Math.round((number * exponent)).toString();
	num = num.slice(0,-1*decimal_points) + "." + num.slice(-1*decimal_points);
	if(num.substr(0,1) == '.')
	{
		return '0'+num;
	}else
	{
		return num;
	}
	 
}

function AddLeadingZero(number)
{
	var newNumber = number;
	if(number < 10)
	{
		newNumber = "0"+number;
	}
	return newNumber;
}
