var timer=0;
var starttime=new Date();
function SetCountdowns()
{
	$$('.countdown').each(function(i) {
		countdown(i.identify());
	});
	timer++;
	setTimeout('SetCountdowns()',1000);
}
function countdown(id)
{
	var i;
	i=$(id);
	if(!i)
	{
		return false;
	}
	if(i.innerHTML=='ENDED')
	{
		return false;
	}
	var dd;
	time=parseInt(i.getAttribute('time'));
	var timepassed=parseInt((new Date()-starttime)/1000);
	dd=(time-timepassed);
	if(time<=0)
	{
		if(i.innerHTML!='ENDED' && !i.timeoutset && i.innerHTML!='ENDING')
		{
			i.timeoutset=1;
			if($('bidscontent'))
			{
				$('bidscontent').hide();	
			}
			if($('bids') && !$('waitingimg'))
			{
				$('bids').appendChild(new Element('img',{src: '/images/waiting.gif',id: 'waitingimg'}));
			}
		}
		if(i.innerHTML!='ENDED')
		{
			setTimeout(function() {EndAuction(id);},12000);
		}
		if($('frmBid'))
		{
			$('frmBid').hide();
		}
		return ;
	}
	if(time!=0 && timer>0 && (dd<=0 || timer%300==0) && i.innerHTML!='ENDED')
	{
		new Ajax.Request('/auctionstatus', {parameters:'auctionid='+i.getAttribute('auctionid')+'&id='+i.identify(), onSuccess:CheckIfTimeExtended});
	}
	dd=Math.max(0,dd);
	var hours,mins,secs,shours,smins,ssecs;
	hours=Math.floor(dd/3600);
	mins=Math.floor((dd%3600)/60);
	secs=dd%60;
	if(hours<10)
		shours='0'+hours;
	else
		shours=hours;
	if(mins<10)
		smins='0'+mins;
	else 
		smins=mins;
	if(secs<10)
		ssecs='0'+secs;
	else
		ssecs=secs;
	i.innerHTML=shours+':'+smins+':'+ssecs;
}
function StopBidCountDown()
{
	stoppedbidcountdown=true;
	if($('updatebutton'))
	{
		$('updatebutton').hide();
		$('updatecountdown').hide();
	}

}
var CheckIfTimeExtended =function(t)
{
	 var json = t.responseText.evalJSON();
	 $(json.id).setAttribute('time',(parseInt(json.time)+parseInt((new Date()-starttime)/1000)));
	 if(json.percentage && json.auctionid && json.bids)
	 {
	//	 UpdateBidBar(json.auctionid, json.percentage, json.bids);
	 }
	 if(parseInt(json.time)<=0)
	 {
		$(json.id).setAttribute('time',0);
		$(json.id).innerHTML=json.msg;

		if(json.msg=='ENDED')
		{
			StopBidCountDown();
			if($$('.countdown').length==1)
			{
				location.reload(true);
			}
		}
		if(json.msg=='ENDING')
		{
			StopBidCountDown();
			if($('bidscontent'))
			{
				$('bidscontent').hide();	
			}
			if($('bids') && !$('waitingimg'))
			{
				$('bids').appendChild(new Element('img',{src: '/images/waiting.gif',id: 'waitingimg'}));
			}
			setTimeout(function() {EndAuction(json.id);},12000);
		}
		if(json.reload)
		{
			location.href='/auction/'+json.name+'/'+json.id;
		}
		if($('frmBid'))
		{
			$('frmBid').hide();
		}
		if($('multibid'))
		{
			$('multibid').hide();
		}
	 }
}
function EndAuction(id)
{
	var i;
	i=$(id);
	new Ajax.Request('/auctionstatus', {parameters:'auctionid='+i.getAttribute('auctionid')+'&id='+i.identify(), onSuccess:CheckIfTimeExtended});
}

function LoadOverlay()
{
	if($('overlay'))
		return false;
	overlay = new Element('div',{
            id: 'overlay'
        });
        $(document.body).appendChild(overlay);
        if(Prototype.Browser.IE){
            overlay.setStyle({position: 'absolute',
	    	    top: 0,
    		    left: 0,
	        	zIndex: 9998
			});
            Event.observe(window,'scroll',overlay.setStyle({
        	    width: document.body.clientWidth + 'px',
    	        height: document.body.clientHeight + 'px'
	        }));
            Event.observe(window,'resize',overlay.setStyle({
	            width: document.body.clientWidth + 'px',
    	        height: document.body.clientHeight + 'px'
        	}));
            Control.Overlay.observe('beforeShow',overlay.setStyle({
            	width: document.body.clientWidth + 'px',
	            height: document.body.clientHeight + 'px'
    	    }));


        }else{
            overlay.setStyle({
		        position: 'fixed',
		        top: 0,
        		left: 0,
		        width: '100%',
		        height: '100%',
		        zIndex: 9998
		    });
		}
        iFrameShim = new IframeShim();
        iFrameShim.hide();
		iFrameShim.positionIFrameShim=function() {
			if($('overlay').visible())
				iFrameShim.positionUnder($('overlay'));

		}
        Event.observe(window,'resize',iFrameShim.positionIFrameShim);
        overlay.hide();
        return true;
}

function BidbudgieAlert(msg){
	LoadOverlay();
	$('overlay').show();
	$('overlay').setOpacity(0.7);
	var alertdiv;
	if(!$('alert'))
	{
		alertdiv=new Element('div',{id: 'alert',});
		document.body.appendChild(alertdiv);
	}
	else
	{
		alertdiv=$('alert');
		alertdiv.show();
		alertdiv.innerHTML='';
	}
	alertdiv.setStyle({background: 'url(/images/hints/alertpopupbg.png)'});
	var alertmsg=new Element('div',{id: 'alertmsg'});
	alertmsg.innerHTML=msg;
	alertdiv.appendChild(alertmsg);
	var okbutton=new Element('div',{ id:'alertok'});
	
	okbutton.onclick=function() {
		$('overlay').hide(); 
		$('alert').hide();
	};
	okbutton.onmouseover=function () {
		okbutton.setStyle({backgroundPosition: '90px 0%'});
	}
	okbutton.onmouseout=function() {
		okbutton.setStyle({backgroundPosition: '0% 0%'});
	}

	alertdiv.appendChild(okbutton);
	var alertdivwidth=320;
	var alertdivheight=144;
	var viewport=document.viewport.getDimensions();
	alertdiv.setStyle({
		top: ((viewport.height-alertdivheight)/2)+'px',
		left: ((viewport.width-alertdivwidth)/2)+'px',
		width: alertdivwidth+'px',
		height: alertdivheight+'px'});

}



function BidbudgieConfirm(msg,okFunction){
	LoadOverlay();
	$('overlay').show();
	$('overlay').setOpacity(0.7);
	var alertdiv;
	if(!$('alert'))
	{
		alertdiv=new Element('div',{id: 'alert'});
		document.body.appendChild(alertdiv);
	}
	else
	{
		alertdiv=$('alert');
		alertdiv.show();
		alertdiv.innerHTML='';
	}
	alertdiv.setStyle({background: 'url(/images/hints/hintpopupbg.png)'});
	var alertmsg=new Element('div',{id: 'alertmsg'});
	alertmsg.innerHTML=msg;
	alertdiv.appendChild(alertmsg);
	var yesbutton=new Element('div',{ id:'alertyes'});
	yesbutton.onclick=function() {
		okFunction(); 
		$('overlay').hide(); 
		$('alert').hide();
	};
	yesbutton.onmouseover=function () {
		yesbutton.setStyle({backgroundPosition: '90px 0%'});
	}
	yesbutton.onmouseout=function() {
		yesbutton.setStyle({backgroundPosition: '0% 0%'});
	}

	var nobutton=new Element('div',{ id:'alertno'});
	nobutton.onclick=function() {
		$('overlay').hide(); 
		$('alert').hide();
	}
	nobutton.onmouseover=function () {
		nobutton.setStyle({backgroundPosition: '90px 0%'});
	}
	nobutton.onmouseout=function() {
		nobutton.setStyle({backgroundPosition: '0% 0%'});
	}
	alertdiv.appendChild(yesbutton);
	alertdiv.appendChild(nobutton);
	var alertdivwidth=320;
	var alertdivheight=144;
	var viewport=document.viewport.getDimensions();
	alertdiv.setStyle({
		top: ((viewport.height-alertdivheight)/2)+'px',
		left: ((viewport.width-alertdivwidth)/2)+'px',
		width: alertdivwidth+'px',
		height: alertdivheight+'px'});

}
function CurrentPageMode()
{
	var bids=parseInt($('progress'+auctionid).getAttribute('bids'));
	var hintcharge=$('hintcharge');
	if(!hintcharge)
	{
		return ;
	}
	var autothreshold=parseInt(hintcharge.getAttribute('autothreshold'));
	var freethreshold=parseInt(hintcharge.getAttribute('freethreshold'));
	var paidthreshold=parseInt(hintcharge.getAttribute('paidthreshold'));
	if(bids<autothreshold)
	{
		return 'auto';
	}
	if(bids<freethreshold)
	{
		return 'free';
	}
	if(bids<paidthreshold)
	{
		return 'paid';
	}
	return 'none';

}
function UpdateHintMessages()
{
	$('autohintson').hide();
	$('freehintson').hide();
	$('paidhintson').hide();
	$('nohintson').hide();
	switch(CurrentPageMode())
	{
		case 'auto':
			$('autohintson').show();
			break;
		case 'free':
			$('freehintson').show();
			break;
		case 'paid':
			$('paidhintson').show();
			break;
		case 'none':
			$('nohintson').show();
			break;
	}
	UpdateBidBarColour();
}
function SetupGetHints()
{
	$$('img.gethint').each(function(button) { button.onclick=function() {
			if($('hintcharge') && parseInt($('progress'+auctionid).getAttribute('bids'))<parseInt($('hintcharge').getAttribute('freethreshold')))
			{
				mode='free';
				msg='Reveal the hint for your bid of <span>'+button.up('td').previous().innerHTML+'</span>';
			}
			else
			{
				mode='paid';
				msg='Revealing the hint for your bid of <span>'+button.up('td').previous().innerHTML+'</span> will cost '+$('hintcharge').innerHTML;
			}
			UpdateHintMessages();
			BidbudgieConfirm(msg,function() {
		new Ajax.Request('/auction/'+auctiontitle+'/'+auctionid,{parameters:'mode='+mode+'&hintid='+button.identify(),onSuccess: UpdateBid});
		$(mode+'hintsused').innerHTML=parseInt($(mode+'hintsused').innerHTML)+1;
		});
	}
	});
}

var UpdateBid =function(t)
{
	var json = t.responseText.evalJSON();
	if(json.nomorehints)
	{
		BidbudgieAlert('Sorry, the bidbar is now full and you may not get any more hints');
		$$('img.gethint').each(function(button) { button.hide();});
		return;
	}
	if(json.nolongerfree)
	{
		BidbudgieAlert('Sorry, hints are now chargeable at '+$('hintcharge').innerHTML+' per bid. Please try again.');
		return ;
	}
	if(json.nopaidleft)
	{
		BidbudgieAlert('Sorry, you have no paid for alerts left');

		$$('img.gethint').each(function(button) { button.hide();});
		return ;
	}
	if(json.nofreeleft)
	{
		BidbudgieAlert('Sorry, you have no free alerts left');
		$$('img.gethint').each(function(button) { button.hide();});
		return ;
	}
	if(json.balance)
	{
		UpdateBalance(json.balance);
	}	
	$(json.id).up().innerHTML=json.msg;
	if(!json.bidsleft)
	{
		$$('img.gethint').each(function(button) { button.hide();});
	}
}	
var updatebidcountdown=16;
var stoppedbidcountdown=false;
function SetupBidReload()
{
	 if(!$('updatecontrol'))
	    {
	        return true;
	    }
	    if(!$('updatebutton'))
	        return true;
	    $('updatebutton').onclick=function() { 
	        updatebidcountdown=15;
	        Reload();
	    }

    $('updatecontrol').onclick=function() {
	        if(stoppedbidcountdown)
	        {
	            auctiontimeout=setTimeout('SetupBidReload()',1000);
	            this.innerHTML='Pause Updates';
	            stoppedbidcountdown=false;
	            $('updatecountdown').innerHTML='Updating in '+updatebidcountdown+' sec';
	            if(updatebidcountdown!=1)
	            {
	                $('updatecountdown').innerHTML+='s';
	            }
	        }
	        else
	        {
	            clearTimeout(auctiontimeout);
	            this.innerHTML='Resume Updates';
	            stoppedbidcountdown=true;   
	            $('updatecountdown').innerHTML='Updating Paused';
	        }
	    }
	    if(stoppedbidcountdown)
	        return true;
	    updatebidcountdown--;
	    $('updatecountdown').innerHTML='Updating in '+updatebidcountdown+' sec';
	    if(updatebidcountdown!=1)
	    {
	        $('updatecountdown').innerHTML+='s';
	    }
	    if(updatebidcountdown==0)
	    {
	        updatebidcountdown=16;
	        Reload();
	    }
	    auctiontimeout=setTimeout('SetupBidReload()',1000);
}
function Reload()
{
	var countdowns=$$('.countdown');
	if(countdowns.length==1)
	{
		if(countdowns[0].innerHTML=='ENDED')
		{
			stoppedbidcountdown=true;
			return false;
		}
	}
	new Ajax.Request('/auction/'+auctiontitle+'/'+auctionid,{parameters:'reload=1',onSuccess: ReloadBid});
}
var ReloadBid=function(t)
{
	var json = t.responseText.evalJSON();
	$('bidscontent').innerHTML=json.content;
	UpdateBidBar(json.auctionid,json.percentage,json.bids);
	if(json.balance)
	{
		UpdateBalance(json.balance);
	}
	SetupGetHints();
	$('updatecountdown').innerHTML='Updating in '+updatebidcountdown+' sec';
	if(updatebidcountdown!=1)
	{
		$('updatecountdown').innerHTML+='s';
	}

}
function UpdateBalance(balance)
{
	if($('curbal'))
	{
		$('curbal').innerHTML=balance;
	}	
}
function UpdateBidBar(auctionid,percentage,bids)
{
	var bidbar=$('progress'+auctionid);
	percentage=parseInt(percentage);
	
	if(bidbar)
	{
		bidbar.setAttribute('bids',bids);
		if(percentage>100)
		{
			bidbar.innerHTML='<a title="Bid Bar Status: FULL" style="text-decoration:none;"><table cellspacing="0"><tr><td class="selected" width="100%">&nbsp;</td></tr></table></a>Bid Bar:';
		}
		else if (percentage<=0)
		{
			bidbar.innerHTML='<a title="Bid Bar Status: EMPTY" style="text-decoration:none;"><table cellspacing="0"><tr><td class="empty" width="100%">&nbsp;</td></tr></table></a>Bid Bar:';
		}
		else
		{
			bidbar.innerHTML='<a title="Bid Bar Status: '+percentage+'&#37;" style="text-decoration:none;"><table cellspacing="0"><tr><td width="'+percentage+'%" class="selected">&nbsp;</td><td>&nbsp;</td></tr></table></a>Bid Bar:';
		}
		UpdateHintMessages();
		UpdateBidBarColour();
	}
}
function UpdateBidBarColour(newauctionid)
{

	var bidbar=$('progress'+auctionid);
	if(!bidbar)
		return false;
	td=bidbar.down('table').down('td');
	if(!td || td.getAttribute('class')=='empty')
	{
		return false;
	}

	switch(CurrentPageMode())
	{
		case 'auto':
			td.setStyle({backgroundColor: '#99FF99'});
			break;
		case 'free':
			td.setStyle({backgroundColor: '#FFFF7D'});
			break;
		case 'paid':
			td.setStyle({backgroundColor: '#FFA86F'});
			break;
		case 'none':
			td.setStyle({backgroundColor: '#FF4A4A'});
			break;
	}
}

