// ajax bidder classes and junctions
var timedLot;
var siteRoot;
var dreamLots;
var dreamQuery = '';
var userID;
var serverTime = 0;
var serverTimeUpdate;
var timeUpdateStarted=false;
var inTransit=false;
var delayCount=0;
function lotFullImage(url,wid,hei){
	var scWid;
	var scHei;
	if(window.innerHeight!=null){
		scWid = window.innerWidth;
		scHei = window.innerHeight;
	} else if(document.documentElement.clientHeight!=null){
		scWid = document.documentElement.clientWidth;
		scHei = document.documentElement.clientHeight;
	} else {
		scWid = document.body.clientWidth;
		schei = document.body.clientHeight;
	}
	scWid-=100;
	scHei-=100;
	if(wid>hei){
		if(wid>scWid){
			hei = Math.round((hei/wid)*scWid);
			wid = scWid;
		}
		if(hei>scHei){
			if(hei>scHei){
				wid = Math.round((wid/hei)*scHei);
				hei = scHei;
			}
		}
	} else {
		if(hei>scHei){
			wid = Math.round((wid/hei)*scHei);
			hei = scHei;
		}
		if(wid>scWid){
			if(wid>scWid){
				hei = Math.round((hei/wid)*scWid);
				wid = scWid;
			}
		}
	}
	var boxWid = wid;
	var boxHei = hei;
	if(boxWid<400){
		boxWid=400;
	}
	html = '<div style="position:relative; float:left; width:'+boxWid+'px; height:'+boxHei+'px; padding:10px; text-align:center;">';
	html += '<img src="'+url+'" style="width:'+wid+'px; height:'+hei+'px; border:none;" />';
	html += '</div>';
	showPopUp(html,true);
}
function lotChangeImage(url,wid,hei){
	var sWid = wid;
	var sHei = hei;
	var maxHei = 200;
	var maxWid = 300;
	if(wid>hei){
		hei = Math.round((hei/wid)*maxWid);
		wid = maxWid;
		if(hei>maxHei){
			wid = Math.round((wid/hei)*maxHei);
			hei = maxHei;
		}
	} else {
		wid = Math.round((wid/hei)*maxHei);
		hei = maxHei;
		if(wid>maxWid){
			hei = Math.round((hei/wid)*maxWid);
			wid = maxWid;
		}
	}
	var con = document.getElementById('largeImageContainer');
	var html = '<a href="javascript:lotFullImage(\''+url+'\','+sWid+','+sHei+');" title="Click here to view a larger image"><img src="'+url+'" style="width:'+wid+'px; height:'+hei+'px; border:none;" /></a>';
	con.innerHTML = html;
}
function setFilter(type,value){
	switch(type){
		case 'priceRange':
			category._setPrice(document.getElementById('pbFilter').value,document.getElementById('ptFilter').value);
			break;
		default:
			category._setFilter(type,value);
			break;
	}
	window.scroll(0,0);
}
function restrictNumeric(elm){
	if(elm.value.length>0){
		if(!isNaN(parseFloat(elm.value))){
			elm.value = parseFloat(elm.value); 
		} else {
			elm.value = '';
		}
	}
}
function urlString(str){
	var arr = new Array();
	var str2 = new String('&rsquo;,&pound;,!,@,#,$,%,^,:,;,",|,/,<,>,~');
	arr = str2.split(',');
	arr[arr.length] = ',';
	arr[arr.length] = '\'';
	for(var i=0;i<arr.length;i++){
		var reg = new RegExp(arr[i],"g");
		str = str.replace(reg,"");
		//alert(arr[i]+'-'+str);
	}
	
	str = str.replace(/ /g,"-");
	str = str.replace(/\+/g,"");
	str = str.replace(/\./g,"");
	str = str.replace(/\*/g,"");
	str = str.replace(/\=/g,"");
	str = str.replace(/\\/g,"");
	str = str.replace(/\?/g,"");
	str = str.replace(/\)/g,"");
	str = str.replace(/\(/g,"");
	str = str.replace(/_/g,"");
	str = str.replace(/\[/g,"");
	str = str.replace(/\]/g,"");
	str = str.replace(/\{/g,"");
	str = str.replace(/\}/g,"");
	str = str.replace(/â/g,"");
	str = str.replace(/Â/g,"");
	
	str = str.replace("&","and");
	return str.toLowerCase();
}
var zBo = 0;
var zBoCount = 0;
function startDeadTimer(){
	zBo = setInterval(deadCheck,1000);
}
function deadCheck(){
	zBoCount++;
	if(zBoCount==15){
		clearInterval(zBo);
		window.location = window.location;
	}
}
function showProcessing(){
	startDeadTimer();
	var popup = '<div style="width:300px; padding-top:20px; padding-bottom:20px; text-align:center;"><h1 style="text-align:center;">Processing...</h1><img src="'+siteRoot+'images/processing.gif" style="border:none;" /></div>';
	showPopUp(popup,false);
}
function confirmInstantWin(id,value){
	closePopUp();
	showProcessing();
	var found=false;
	var correct=false;
	for(var m=0;m<dreamLots.length;m++){
		if(dreamLots[m]._id==id){
			found=true;
			if(value==parseFloat(dreamLots[m]._lot.buy_now_price)){
				correct=true;
			}
			break;
		}
	}
	if((found)&&(correct)){
		if(xmlHttp!=null){
			dreamQuery = 'placeinstantwin';
			var url=siteRoot+'includes/javascript-data-queries.php?id='+dreamQuery+'&lot_id='+id+'&user_id='+userID+'&bid_amount='+value;
			xmlHttp.onreadystatechange = dreamStateChanged;
			xmlHttp.open("GET",url,true);
			xmlHttp.send(null);
		}
	} else {
		//show pop up error
	}
}
function confirmMaximumBid(id,value){
	closePopUp();
	showProcessing();
	var found=false;
	var correct=false;
	for(var m=0;m<dreamLots.length;m++){
		if(dreamLots[m]._id==id){
			found=true;
			break;
		}
	}
	if(found){
		if(xmlHttp!=null){
			dreamQuery = 'placemaximumbid';
			var url=siteRoot+'includes/javascript-data-queries.php?id='+dreamQuery+'&lot_id='+id+'&user_id='+userID+'&bid_amount='+value;
			xmlHttp.onreadystatechange = dreamStateChanged;
			xmlHttp.open("GET",url,true);
			xmlHttp.send(null);
		}
	} else {
		//show pop up error
	}
}
function placeMaximumBid(id){
	var lot;
	for(var m=0;m<dreamLots.length;m++){
		if(id==dreamLots[m]._id){
			lot = dreamLots[m]._lot;
			break;
		}
	}
	var maxBid = document.getElementById('maximum_bid').value;
	if(parseFloat(maxBid)>=parseFloat(lot.current_asking)){
		var popup = '<div class="instantWinPopUp">'
		popup += '<div class="siteBlock">';
		popup += '<h1>Maximum Bid Confirmation</h1>';
		popup += '<p>Please confirm that you would like to leave a maximum bid for the lot below & for the amount specified</p>';
		popup += '</div>';
		popup += '<div class="siteBlock">';
		popup += '<table style="width:100%; font-size:12px;">';
		popup += '<tr><td class="infoCell" style="width:120px;">Lot ID:</td>';
		popup += '<td class="inputCell" style="width:auto; text-align:left;">'+lot.id+'</td></tr>';
		popup += '<tr><td class="infoCell" style="width:120px;">Lot Title:</td>';
		popup += '<td class="inputCell" style="width:auto; text-align:left;">'+lot.title+'</td></tr>';
		popup += '<tr><td class="infoCell" style="width:120px;">Bid Amount:</td>';
		popup += '<td class="inputCell" style="width:auto; text-align:left;">&pound;'+formatNumber(maxBid)+'</td></tr>';
		popup += '<tr><td colspan="2" style="text-align:center; padding-top:10px; padding-bottom:10px;"><a href="javascript:confirmMaximumBid('+lot.id+','+maxBid+');" class="bidButton"><span>Confirm Bid</span></a></td></tr>';
		popup += '</table>';
		popup += '</div>';
		popup+='</div>';
	} else {
		var popup = '<div class="instantWinPopUp">'
		popup += '<div class="siteBlock">';
		popup += '<h1>Maximum Bid Too Low</h1>';
		popup += '<p>Unfortunately the minimum bid amount is '+formatNumber(lot.current_asking)+', please click close and try again.</p>';
		popup += '</div>';
		popup += '<div class="siteBlock">';
		popup += '<table style="width:100%; font-size:12px;">';
		popup += '<tr><td colspan="2" style="text-align:center; padding-top:10px; padding-bottom:10px;"><a href="javascript:closePopUp();" class="bidButton"><span>Close</span></a></td></tr>';
		popup += '</table>';
		popup += '</div>';
		popup+='</div>';
	}
	showPopUp(popup);
}
function placeInstantWin(id){
	var lot;
	for(var m=0;m<dreamLots.length;m++){
		if(id==dreamLots[m]._id){
			lot = dreamLots[m]._lot;
			break;
		}
	}
	var popup = '<div class="instantWinPopUp">'
	popup += '<div class="siteBlock">';
	popup += '<h1>Instant Win Confirmation</h1>';
	popup += '<p>Please confirm that you would like to purchase the lot below for the amount specified</p>';
	popup += '</div>';
	popup += '<div class="siteBlock">';
	popup += '<table style="width:100%; font-size:12px;">';
	popup += '<tr><td class="infoCell" style="width:120px;">Lot ID:</td>';
	popup += '<td class="inputCell" style="width:auto; text-align:left;">'+lot.id+'</td></tr>';
	popup += '<tr><td class="infoCell" style="width:120px;">Lot Title:</td>';
	popup += '<td class="inputCell" style="width:auto; text-align:left;">'+lot.title+'</td></tr>';
	popup += '<tr><td class="infoCell" style="width:120px;">Instant Win Price:</td>';
	popup += '<td class="inputCell" style="width:auto; text-align:left;">&pound;'+formatNumber(lot.buy_now_price)+'</td></tr>';
	popup += '<tr><td colspan="2" style="text-align:center; padding-top:10px; padding-bottom:10px;"><a href="javascript:confirmInstantWin('+lot.id+','+lot.buy_now_price+');" class="bidButton"><span>Confirm Bid</span></a></td></tr>';
	popup += '</table>';
	popup += '</div>';
	popup+='</div>';
	showPopUp(popup);
}
function placeBid(id,currentAsking){
	var found=false;
	var correct=false;
	for(var m=0;m<dreamLots.length;m++){
		if(dreamLots[m]._id==id){
			found=true;
			if(currentAsking==parseFloat(dreamLots[m]._lot.current_asking)){
				dreamLots[m]._isProcessing=true;
				correct=true;
			}
		}
	}
	if((found)&&(correct)){
		var bidBtn = document.getElementById('auctionBid_'+id);
		bidBtn.innerHTML = '<a class="bidButton" title="Processing Bid" ><span>Processing Bid</span></a>';
		if(xmlHttp!=null){
			dreamQuery = 'placebid';
			var url=siteRoot+'includes/javascript-data-queries.php?id='+dreamQuery+'&lot_id='+id+'&user_id='+userID+'&bid_amount='+currentAsking;
			xmlHttp.onreadystatechange = dreamStateChanged;
			xmlHttp.open("GET",url,true);
			xmlHttp.send(null);
		}
	}
}
function serverTimerUpdate(){
	serverTime++;
	for(var m=0;m<dreamLots.length;m++){
		dreamLots[m]._updateLotData();
	}
	if(inTransit==false){
		if(delayCount==10){
			delayCount=0;
			refreshDelay();
		} else {
			delayCount++;
		}
	}
}
function rollOverLogin(id){
	document.getElementById('bidBtn_'+id).innerHTML = '<span>Login to Bid</span>';
	for(var m=0;m<dreamLots.length;m++){
		if(dreamLots[m]._id==id){
			dreamLots[m]._rolledover=true;
		}
	}
}
function rollOutLogin(id){
	for(var m=0;m<dreamLots.length;m++){
		if(dreamLots[m]._id==id){
			dreamLots[m]._rolledover=false;
		}
	}
}
function formatNumber(num){    
    var n = num.toString();
    var nums = n.split('.');
    var newNum = "";
    if (nums.length > 1)
    {
        var dec = nums[1].substring(0,2);
		if(dec.length==2){
	        newNum = nums[0] + "." + dec;
		} else if(dec.length==1){
			newNum = nums[0] + "." + dec + "0";
		} else {
			newNum = nums[0] + ".00";
		}
    }
    else
    {
    newNum = num;
    }
    return newNum;
}
function addLot(id,type){
	if(dreamLots==null){
		dreamLots = new Array();
	}
	dreamLots[dreamLots.length] = new DreamLot(id);
}
function removeLot(id){
	for(var i=0;i<dreamLots.length;i++){
		if(dreamLots[i]._id==id){
			var bin = dreamLots.splice(id,1);
			break;
		}
	}
}
function removeLots(){
	dreamLots = null;
	dreamlots = new Array();
}
function beginUpdates(){
	requestUpdate();
}
function stopUpdates(){
	if(timeUpdateStarted){
		clearInterval(serverTimeUpdate);
		timeUpdateStarted=false;
	}
}
function refreshDelay(){
	requestUpdate();
}
function requestUpdate(){
	inTransit=true;
	var strRequest = '';
	for(var i=0;i<dreamLots.length;i++){
		if(i>0){
			strRequest += '|';
		}
		strRequest += dreamLots[i]._id;
	}
	if(strRequest!=''){
		if(xmlHttp!=null){
			dreamQuery = 'screenupdate';
			var url=siteRoot+'includes/javascript-data-queries.php?id='+dreamQuery+'&ids='+strRequest;
			xmlHttp.onreadystatechange = dreamStateChanged;
			xmlHttp.open("GET",url,true);
			xmlHttp.send(null);
		}
	}
}
function dreamStateChanged(){
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
		switch(dreamQuery){
			case 'screenupdate':
				if(!timeUpdateStarted){
					serverTimeUpdate = setInterval(serverTimerUpdate,1000);
					timeUpdateStarted=true;
				}
				var str = xmlHttp.responseText;
				var time = str.split("_");
				if(time.length>3){
					str = time[2];
					for(var i=3;i<time.length;i++){
						str += '_'+time[i];
					}
				}
				serverTime = parseInt(time[1]);
				userID = parseInt(time[0]);
				time = null;
				var arr = str.split(':');
				var aler = '';
				for(var i=0;i<arr.length;i++){
					var arr2 = arr[i].split('|');
					var obj = new Object();
					for(var m=0;m<arr2.length;m++){
						var fields = arr2[m].split('=');
						aler += ', '+fields[0]+'='+fields[1];
						if(fields[0]=='id'){
							obj[fields[0]] = parseInt(fields[1]);
						} else {
							obj[fields[0]] = fields[1];
						}
					}
					for(var m=0;m<dreamLots.length;m++){
						if(obj.id==dreamLots[m]._id){
							dreamLots[m]._setLotData(obj);
							dreamLots[m]._updateLotData();
						}
					}
				}
				break;
			case 'placebid':
				var spl = xmlHttp.responseText;
				spl = spl.split("|");
				var code = spl[0];
				
				for(var m=0;m<dreamLots.length;m++){
					dreamLots[m]._isProcessing=false;
				}
				var bidBtn = document.getElementById('auctionBid_'+spl[1]);
				switch(parseInt(code)){
					case 1://late bid
						refreshDelay();
						bidBtn.innerHTML = '<a class="bidButton" title="Processing Bid" ><span style="background-color:#FF0000;">Late Bid</span></a>';
						break;
					case 2://successful bid
						refreshDelay();
						bidBtn.innerHTML = '<a class="bidButton" title="Processing Bid" ><span style="background-color:#23d934;">Successful Bid</span></a>';
						break;
					case 3:
						//create div pop up
						var popup = '<div style="width:400px; text-align:center;"><h1>System Error: Unable to place bid</h1><p>We are sorry but an error has occured when trying to place your bid, please refresh the page and try again.</p><p>If this issue continues please <a href="'+siteRoot+'contactus.php" title="Click here to contact us">contact us</a>.</p></div>';
						showPopUp(popup);
						break;
					case 4:
						var popup = '<div style="width:400px; text-align:center;"><h1>Error: Banned from Bidding</h1><p>We are sorry but your account has been blocked from bidding, please <a href="'+siteRoot+'contactus.php" title="Click here to contact us">contact us</a> for more information.</p></div>';
						showPopUp(popup);
						break;
				}
				break;
			case 'placeinstantwin':
				closePopUp();
				switch(parseInt(xmlHttp.responseText)){
					case 1://late bid
						refreshDelay();
						break;
					case 2://successful bid
						refreshDelay();
						break;
					case 3:
						//create div pop up
						var popup = '<div style="width:400px; text-align:center;"><h1>System Error: Unable to place bid</h1><p>We are sorry but an error has occured when trying to place your bid, please refresh the page and try again.</p><p>If this issue continues please <a href="'+siteRoot+'contactus.php" title="Click here to contact us">contact us</a>.</p></div>';
						showPopUp(popup);
						break;
					case 4:
						var popup = '<div style="width:400px; text-align:center;"><h1>Error: Banned from Bidding</h1><p>We are sorry but your account has been blocked from bidding, please <a href="'+siteRoot+'contactus.php" title="Click here to contact us">contact us</a> for more information.</p></div>';
						showPopUp(popup);
						break;
				}
				break;
			case 'placemaximumbid':
				closePopUp();
				switch(parseInt(xmlHttp.responseText)){
					case 0://unsuccessful
						refreshDelay();
						break;
					case 1://successful bid
						refreshDelay();
						break;
				}
				break;
			case 'totalbids':
				document.getElementById('total_bids').innerHTML = 'Total Bids Left: '+xmlHttp.responseText;
				break;
		}
	}
	inTransit=false;
}
var alertCheck=false;
//lot class
function DreamLot(id){
	this._id = id;
}
DreamLot.prototype._id = null;
DreamLot.prototype._lot = null;
DreamLot._isProcessing = false;
DreamLot.prototype._flashed = false;
DreamLot.prototype._oldham = -1;
DreamLot.prototype._rolledover = false;
DreamLot.prototype._setLotData = function(obj){
	var _this = this;
	_this._lot = obj;
}

DreamLot.prototype._updateLotData = function(){
	var _this = this;
	if(_this._lot!=null){
		var rrp = document.getElementById('auctionRRP_'+_this._id);
		var hammer = document.getElementById('auctionCurrentBid_'+_this._id);
		var asking = document.getElementById('auctionAsking_'+_this._id);
		var cBidder = document.getElementById('auctionBidder_'+_this._id);
		var timeRem = document.getElementById('auctionTime_'+_this._id);
		var bidBtn = document.getElementById('auctionBid_'+_this._id);
		var bidType = document.getElementById('auctionCurrentBidType_'+_this._id);
		var instWinSBtn = document.getElementById('instantWin-small_'+_this._id);
		var instWinLBtn = document.getElementById('instantWin-large_'+_this._id);
		if(_this._flashed){
			if(hammer!=null){
				hammer.style.color = '#666666';
			}
			if(asking!=null){
				asking.style.color = '#666666';
			}
			if(bidType!=null){
				bidType.style.color = '#666666';
			}
			_this._flashed=false;
		}
		if(rrp!=null){
			rrp.innerHTML = 'RRP &pound;'+formatNumber(_this._lot.retail_price);
		}
		if(hammer!=null){
			if(_this._lot.hammer_price!=_this._oldham){
				hammer.style.color = '#FF0000';
				_this._flashed = true;
				_this._oldham = _this._lot.hammer_price;
			}
			hammer.innerHTML = 'Current Bid: &pound;'+formatNumber(_this._lot.hammer_price);
		}
		if(asking!=null){
			if(_this._flashed){
				asking.style.color = '#00FF00';
			}
			asking.innerHTML = 'Asking: &pound;'+formatNumber(_this._lot.current_asking);
		}
		if(bidType!=null){
			var bidTypeVal = 'Currently No Bids';
			if(parseFloat(_this._lot.hammer_price)>0){
				switch(parseInt(_this._lot.bid_type)){
					case 0:
						bidTypeVal = 'Single Bid';
						break;
					case 1:
						bidTypeVal = 'Autobid';
						break;
					case 2:
						bidTypeVal = 'Instant Win';
						break;
				}
			}
			if(_this._flashed){
				bidType.style.color = '#00FF00';
			}
			bidType.innerHTML = bidTypeVal;
		}
		var tLot = _this._lot;
		if(parseInt(tLot.winning_user_id)>0){
			if(cBidder!=null){
				cBidder.innerHTML = 'Current Bidder: '+tLot.winning_username;
			}
		}
		if(instWinSBtn!=null){
			if(userID!=0){
				var hamLimit = (parseFloat(_this._lot.hammer_price)+(parseFloat(_this._lot.hammer_price)*0.15));
				if(_this._lot.buy_now_price!=0 && parseFloat(_this._lot.buy_now_price)>hamLimit){
					instWinSBtn.innerHTML = '<a class="instantWin" href="javascript:placeInstantWin('+_this._lot.id+');" title="Click here to bid"><span>Instant Win: &pound;'+formatNumber(_this._lot.buy_now_price)+'</span></a><br /><span style="font-size:10px;">(Please note clicking this button is a commitment to buy)</span>';
				} else if(_this._lot.buy_now_price!=0 && parseFloat(_this._lot.buy_now_price)<=hamLimit){
					instWinSBtn.innerHTML = '<a class="instantWin" title=""><span>Instant Win Removed</span></a>';
				}
			} else {
				instWinSBtn.innerHTML = '<a class="instantWin" href="'+siteRoot+'login.php" title="Click here to login now"><span>Log In To Bid</span></a>';
			}
		}
		if(instWinLBtn!=null){
			if(userID!=0){
				if(_this._lot.buy_now_price!=0 && _this._lot.buy_now_price>(_this._lot.hammer_price+(_this._lot.hammer_price*0.15))){
					instWinLBtn.innerHTML = '<a class="instantWin" href="javascript:placeInstantWin('+_this._lot.id+');" title="Click here to bid"><span>Instant Win: &pound;'+formatNumber(_this._lot.buy_now_price)+'</span></a><br /><span style="font-size:10px;">(Please note clicking this button is a commitment to buy)</span>';
				} else if(_this._lot.buy_now_price!=0 && _this._lot.buy_now_price<(_this._lot.hammer_price+(_this._lot.hammer_price*0.15))){
					instWinLBtn.innerHTML = '<a class="instantWin" title=""><span>Instant Win Removed</span></a>';
				}
			} else {
				instWinLBtn.innerHTML = '<a class="instantWin" href="'+siteRoot+'login.php" title="Click here to login now"><span>Log In To Bid</span></a>';
			}
		}
		if(!_this._isProcessing){
			if((parseInt(tLot.status)==0) && ((parseInt(tLot.start_time)-serverTime)<0)){
				timeRem.innerHTML = 'Not Started, Bid to Start';
				bidCode= '';
				if(bidBtn!=null){
					if(userID!=0){
						bidLink = '<a class="bidButton" href="javascript:placeBid('+_this._lot.id+','+_this._lot.current_asking+');" title="Click here to bid &pound;'+formatNumber(_this._lot.current_asking)+'"><span>BID &pound;'+formatNumber(_this._lot.current_asking)+'</span></a>';
					} else {
						bidLink = '<a class="bidButton"href="'+siteRoot+'login.php" id="bidBtn_'+_this._lot.id+'" title="Click here to bid &pound;'+formatNumber(_this._lot.current_asking)+'" onmouseout="javascript:rollOutLogin('+_this._lot.id+');" onmouseover="javascript:rollOverLogin('+_this._lot.id+');"><span>BID &pound;'+formatNumber(_this._lot.current_asking)+'</span></a>';
					}
					if(!_this._rolledover){
						bidBtn.innerHTML = bidLink;
					}
				}
			} else if((parseInt(_this._lot.status)==0) && ((parseInt(_this._lot.start_time)-serverTime)>0)){
				var timeDiff = parseInt(_this._lot.start_time)-serverTime;
				var days = Math.floor(timeDiff/86400);
				timeDiff-= days*86400;
				var hours = Math.floor(timeDiff/3600);
				timeDiff -= hours*3600;
				var mins = Math.floor(timeDiff/60);
				timeDiff -= mins*60;
				totalTime='';
				if(days>0){
					totalTime += days.toString()+'d ';
				}
				if((hours>0)||(days>0)){
					totalTime += hours.toString()+'h ';
				}
				if((mins>0)||(days>0)||(hours>0)){
					totalTime += mins.toString()+'m ';
				}
				if((timeDiff>0)||(days>0)||(hours>0)||(mins>0)){
					totalTime += timeDiff.toString()+'s';
				}
				if(timeDiff>0){
					timeRem.innerHTML = 'starts in:<br />'+totalTime;
				} else {
					timeRem.innerHTML = '<span class="checkingTime">Checking..</span>';
				}
				if(bidBtn!=null){
					bidBtn.innerHTML = '';
				}
			} else if(parseInt(_this._lot.status)>1){
				if(bidBtn!=null){
					bidBtn.innerHTML = '<a class="bidButton"><span style="background-color:#FF0000;">Ended</span></a>';
				}
			} else {
				var timeDiff = (parseInt(_this._lot.end_time))-serverTime;
				if(timeDiff<0){
					timeDiff=0;
				}
				var days = Math.floor(timeDiff/86400);
				timeDiff-= days*86400;
				var hours = Math.floor(timeDiff/3600);
				timeDiff -= hours*3600;
				var mins = Math.floor(timeDiff/60);
				timeDiff -= mins*60;
				if(timeDiff<0){
					timeDiff=0;
				}
				totalTime='';
				if(days>0){
					totalTime += days.toString()+'d ';
				}
				if((hours>0)||(days>0)){
					totalTime += hours.toString()+'h ';
				}
				if((mins>0)||(days>0)||(hours>0)){
					totalTime += mins.toString()+'m ';
				}
				if((timeDiff>0)||(days>0)||(hours>0)||(mins>0)){
					totalTime += timeDiff.toString()+'s';
				}
				if(timeDiff>0){
					timeRem.innerHTML = 'Time Remaining: <span>'+totalTime+'</span><br />';
				} else {
					timeRem.innerHTML = '<span class="checkingTime">Checking..</span>';
				}
				bidCode= '';
				if(bidBtn!=null){
					if(parseInt(tLot.winning_user_id)==0){
						if(userID!=0){
							bidLink = '<a class="bidButton"href="javascript:placeBid('+_this._lot.id+','+_this._lot.current_asking+');" title="Click here to bid &pound;'+formatNumber(_this._lot.current_asking)+'"><span>BID &pound;'+formatNumber(_this._lot.current_asking)+'</span></a>';
						} else {
							bidLink = '<a class="bidButton"href="'+siteRoot+'login.php" id="bidBtn_'+_this._lot.id+'" title="Click here to bid &pound;'+formatNumber(_this._lot.current_asking)+'" onmouseout="javascript:rollOutLogin('+_this._lot.id+');" onmouseover="javascript:rollOverLogin('+_this._lot.id+');"><span>BID &pound;'+formatNumber(_this._lot.current_asking)+'</span></a>';
						}
					} else if(parseInt(_this._lot.winning_user_id)==userID){
						bidLink = '<a class="bidButton"><span style="background-color:#23d934;">You&rsquo;re in the lead!</span></a>';
					} else {
						if(userID!=0){
							bidLink = '<a class="bidButton"href="javascript:placeBid('+_this._lot.id+','+_this._lot.current_asking+');" title="Click here to bid &pound;'+formatNumber(_this._lot.current_asking)+'"><span>BID &pound;'+formatNumber(_this._lot.current_asking)+'</span></a>';
						} else {
							bidLink = '<a class="bidButton"href="'+siteRoot+'login.php" id="bidBtn_'+_this._lot.id+'" title="Click here to bid &pound;'+formatNumber(_this._lot.current_asking)+'" onmouseout="javascript:rollOutLogin('+_this._lot.id+');" onmouseover="javascript:rollOverLogin('+_this._lot.id+');"><span>BID &pound;'+formatNumber(_this._lot.current_asking)+'</span></a>';
						}
					}
					if(!_this._rolledover){
						bidBtn.innerHTML = bidLink;
					}
				}
			}
		}
	}
}
//Lot Builder Class
function LotBuilder(xml){
	this._xml = xml;
	this._init();
}
LotBuilder.prototype._xml = null;
LotBuilder.prototype._data = null;
LotBuilder.prototype._init = function(){
	var xml = this._xml;
	var _this = this;
	this._data = new Object();
	this._images = new Array();
	for(var i=0;i<xml.childNodes.length;i++){
		if(xml.childNodes[i].nodeName!="images"){
			if(xml.childNodes[i].firstChild!=null){
				this._data[xml.childNodes[i].nodeName] = xml.childNodes[i].firstChild.data;
			} else {
				this._data[xml.childNodes[i].nodeName] = null;
			}
		} else {
			for(var m=0;m<xml.childNodes[i].childNodes.length;m++){
				var nObj = new Object();
				nObj._imagepath = xml.childNodes[i].childNodes[m].firstChild.data;
				nObj._imagewidth = xml.childNodes[i].childNodes[m].getAttribute('imagewidth');
				nObj._imageheight = xml.childNodes[i].childNodes[m].getAttribute('imageheight');
				this._images[this._images.length] = nObj;
			}
		}
	}
}
//Bidder Controller Class
function BidderController(lotId,user_id){
	this._id = lotId;
	this._userId = user_id;
	this._init();
	this._this = this;
	this._currentAsking = 0;
	this._refreshRate = 10;
	this._refreshCount = 0;
	this._clockTimer = 0;
	this._imagelistwidth = 100;
	this._imagelistheight = 75;
	this._imagelistint = 0;
}
BidderController.prototype._xmlHttp = undefined;
BidderController.prototype._id = null;
BidderController.prototype._userId = null;
BidderController.prototype._lot = null;
BidderController.prototype._currentAsking = null;
BidderController.prototype._this = this;
BidderController.prototype._servertime = 0;
BidderController.prototype._refreshRate = null;
BidderController.prototype._refreshCount=null;
BidderController.prototype._imagelistwidth = null;
BidderController.prototype._imagelistheight = null;
BidderController.prototype._imagelistx = 0;
BidderController.prototype._imagelistmove = null;
BidderController.prototype._imagelistint = 0;
BidderController.prototype._init = function(){
	var url="includes/javascript-data-queries.php";
	url=url+'?id=timed_lot&lotId='+this._id;
	this._xmlHttp = this._createXMLHttpRequest();
	if(this._xmlHttp!=null){
		var me = this;
		this._xmlHttp.onreadystatechange = function(){me._onDataInit();}
		this._xmlHttp.open("GET",url,true);
		this._xmlHttp.send(null);
	}
}
BidderController.prototype._requestTimeRefresh = function(){
	var url="includes/javascript-data-queries.php";
	url=url+'?id=timed_lot&lotId='+this._id;
	this._xmlHttp = this._createXMLHttpRequest();
	if(this._xmlHttp!=null){
		var me = this;
		this._xmlHttp.onreadystatechange = function(){me._onDataRefresh();}
		this._xmlHttp.open("GET",url,true);
		this._xmlHttp.send(null);
	}
}
BidderController.prototype._updateServerTime = function(){
	this._servertime++;
	var timer = this._getTimeRemaining();
	document.getElementById('bidder_time_remaining').innerHTML = timer;
	this._refreshCount++;
	if(this._refreshCount==this._refreshRate){
		if((this._lot._data.date_ended-this._servertime)<30){
			this._refreshRate=3;
		}
		this._refreshCount=0;
		this._requestTimeRefresh();
	}
}
BidderController.prototype._changeTime = function(){
	timedLot._updateServerTime();
}
BidderController.prototype._getTimeRemaining = function() {
	var bid_counter = '';
	if(this._lot._data.date_started<this._servertime){
		if(this._servertime>this._lot._data.date_ended){
			bid_counter = 'auction ended';
			clearInterval(this._clockTimer);
		} else {
			var val = this._lot._data.date_ended-this._servertime;
			var days = Math.floor(val/86400);
			val -= days*86400;
			var hours = Math.floor(val/3600);	
			val -= hours*3600;
			var mins = Math.floor(val/60);
			val -= mins*60;
			var secs = val;
			if(days>0){
				bid_counter+= days.toString()+'d ';
			}
			if(hours>0){
				bid_counter+= hours.toString()+'h ';
			}
			if(mins>0){
				bid_counter+= mins.toString()+'m ';
			}
			if(secs>0){
				bid_counter+= secs.toString()+'s ';
			}
		}
	} else {
		var val = this._lot.date_started-this._servertime;
		var days = Math.floor(val/86400);
		val -= days*86400;
		var hours = Math.floor(val/3600);
		val -= hours*3600;
		var mins = Math.floor(val/60);
		val -= mins*60;
		var secs = val;
		if(days>0){
			bid_counter+= days.toString()+'d ';
		}
		if(hours>0){
			bid_counter+= hours.toString()+'h ';
		}
		if(mins>0){
			bid_counter+= mins.toString()+'m ';
		}
		if(secs>0){
			bid_counter+= secs.toString()+'s ';
		}
	}
	
	return bid_counter;
}
BidderController.prototype._createBid = function(){
	if(this._userId!=null && this._userId>0){
		var url="includes/javascript-data-queries.php";
		url=url+'?id=timed_lot_bid&lotId='+this._id+'&userId='+this._userId+'&bidAmount='+this._currentAsking;
		if(this._xmlHttp!=null){
			var me = this;
			this._xmlHttp.onreadystatechange = function(){me._onDataComplete();}
			this._xmlHttp.open("GET",url,true);
			this._xmlHttp.send(null);
		}
	}
}
BidderController.prototype._updateBidderScreen = function(){
	var doc = document.getElementById('bidder_container');
	var html = '';
	html += '<div id="bidder_image_container">';
	//image code here
	html += '</div>';
	html += '<div id="bidder_detail_container">';
	//data code here
	document.getElementById('bidder_description').innerHTML = this._lot._data.description;
	document.getElementById('bidder_lot_no').innerHTML =  'Lot '+this._lot._data.lot_no+this._lot._data.a;
	document.getElementById('bidder_hammer_price').innerHTML = '&pound;'+number_format(this._lot._data.hammer_price);
	document.getElementById('bidder_username').innerHTML = this._lot._data.username;
	document.getElementById('bidder_time_remaining').innerHTML = this._getTimeRemaining();
	this._currentAsking = this._getNextAsking();
	if(this._userId!=null && this._userId>0){
		if(this._lot._data.date_ended<this._servertime){
			document.getElementById('bidder_bid_button').disabled = true;
			document.getElementById('bidder_bid_button').value = 'Auction Ended';
			document.getElementById('bidder_bid_button').style.color = '#999999';
		} else {
			if(parseInt(this._lot._data.buyer_id)==this._userId){
				document.getElementById('bidder_bid_button').disabled = true;
				document.getElementById('bidder_bid_button').value = 'In The Lead';
			} else {
				document.getElementById('bidder_bid_button').disabled = false;
				document.getElementById('bidder_bid_button').value = 'Bid '+number_format(this._currentAsking);
			}
		}
	}
	var nearCheck = parseFloat(this._lot._data.buy_now)*0.85;
	if((parseFloat(this._lot._data.buy_now)>0) && (parseFloat(this._lot._data.hammer_price)>nearCheck)){
		document.getElementById('bidder_buy_now').innerHTML = '';
		document.getElementById('bidder_buy_now').style.height = '0px';
		document.getElementById('bidder_buy_now').style.hidden = 'hidden';
	}
}

BidderController.prototype._imageSlideLeft = function(){
	var me = this;
	this._imagelistint = setInterval(me._imageListSlideLeft,10);
	var rightArrow = document.getElementById('bidder_image_right_arrow');
	rightArrow.style.opacity = 0.8;
	rightArrow.style.filter = 'alpha(opacity=' + 80 + ')';
}
BidderController.prototype._imageSlideRight = function(){
	var me = this;
	this._imagelistint = setInterval(me._imageListSlideRight,10);
	var leftArrow = document.getElementById('bidder_image_left_arrow');
	leftArrow.style.opacity = 0.8;
	leftArrow.style.filter = 'alpha(opacity=' + 80 + ')';
}
BidderController.prototype._imageListSlideStop = function(){
	clearInterval(timedLot._imagelistint);
	var leftArrow = document.getElementById('bidder_image_left_arrow');
	leftArrow.style.opacity = 0.5;
	leftArrow.style.filter = 'alpha(opacity=' + 50 + ')';
	var rightArrow = document.getElementById('bidder_image_right_arrow');
	rightArrow.style.opacity = 0.5;
	rightArrow.style.filter = 'alpha(opacity=' + 50 + ')';
}
BidderController.prototype._imageListSlideLeft = function(){
	if(timedLot._imagelistx<(timedLot._imagelistmove*-1)){
		clearInterval(timedLot._imagelistint);
	} else {
		timedLot._imagelistx-=4;
		var block = document.getElementById('bidder_image_list_block');
		block.style.left = timedLot._imagelistx+'px';
	}
}
BidderController.prototype._imageListSlideRight = function(){
	if(timedLot._imagelistx>=0){
		clearInterval(timedLot._imagelistint);
	} else {
		timedLot._imagelistx+=4;
		var block = document.getElementById('bidder_image_list_block');
		block.style.left = timedLot._imagelistx+'px';
	}
}
BidderController.prototype._loadLargeImage = function(i){
	var large = document.getElementById('bidder_image_large');
	var imgNo = i+1;
	large.innerHTML = '<img src="'+this._lot._images[i]._imagepath+'" title="Image '+imgNo+' of '+this._lot._data.description+'" />';
}
BidderController.prototype._loadImages = function(){
	var large = document.getElementById('bidder_image_large');
	var list = document.getElementById('bidder_image_list');
	large.innerHTML = '<img src="'+this._lot._images[0]._imagepath+'" title="Image 1 of '+this._lot._data.description+'" />';
	var html = '';
	var imageHTML = '';
	var totalWidth=this._lot._images.length*(this._imagelistwidth+10);
	for(var i=0;i<this._lot._images.length;i++){
		var imgWid=this._imagelistwidth;
		var imgHei=this._imagelistheight;
		if(this._lot._images[i]._imagewidth>this._lot._images[i]._imageheight){
			imgHei = (this._lot._images[i]._imageheight/this._lot._images[i]._imagewidth)*imgWid;
		} else {
			imgWid = (this._lot._images[i]._imagewidth/this._lot._images[i]._imageheight)*imgHei;
		}
		var extraWid = this._imagelistwidth+10;
		imageHTML +='<div class="bidder_image_list_extra" style="width:'+extraWid+'px;"><a onclick="javascript:timedLot._loadLargeImage('+i+');"><img src="'+this._lot._images[i]._imagepath+'" style="width:'+imgWid+'px; height:'+imgHei+'px;" /></a></div>';
	}
	var totalHeight = this._imagelistheight;
	html += '<div id="bidder_image_list_block" style="width:'+totalWidth+'px; height:'+totalHeight+'px; padding-top:5px; padding-bottom:5px; position:relative; z-index:1;">';
	html += imageHTML;
	totalHeight+=10;
	list.style.height = totalHeight+'px';
	list.style.overflow = "hidden";
	html += '</div>';
	html += '<div id="bidder_image_left_arrow" style="width:17px; height:'+totalHeight+'px; position:relative; float:left; z-index:100; top:-'+totalHeight+'px; left:0px;"><a onmouseover="javascript:timedLot._imageSlideRight();" onmouseout="javascript:timedLot._imageListSlideStop();"><img src="images/icons/leftarrow.png"></a></div>';
	html += '<div id="bidder_image_right_arrow" style="width:17px; height:'+totalHeight+'px; position:relative; float:right; z-index:100; top:-'+totalHeight+'px; right:0px;"><a onmouseover="javascript:timedLot._imageSlideLeft();" onmouseout="javascript:timedLot._imageListSlideStop();"><img src="images/icons/rightarrow.png"></a></div>';
	this._imagelistmove = totalWidth-450;
	list.innerHTML = html;
}
BidderController.prototype._createBidderScreen = function(){
	var doc = document.getElementById('bidder_container');
	var html = '';
	html += '<div id="bidder_image_container">';
	html += '<div id="bidder_image_large">';
	html += '</div>';
	html += '<div id="bidder_image_list">';
	html += '</div>';
	//image code here
	html += '</div>';
	html += '<div id="bidder_detail_container">';
	//data code here
	html += '<h1 id="bidder_description">'+this._lot._data.description+'</h1>';
	html += '<span id="bidder_lot_no">Lot '+this._lot._data.lot_no+this._lot._data.a+'</span>';
	html += '<hr />';
	html += '<table style="width:100%;">';
	html += '<tr><td class="bidder_info_cell">Current Hammer:</td><td class="bidder_input_cell" id="bidder_hammer_price">&pound;'+number_format(this._lot._data.hammer_price)+'</td></tr>';
	html += '<tr><td class="bidder_info_cell">Current Bidder:</td><td class="bidder_input_cell" id="bidder_username">'+this._lot._data.username+'</td></tr>';
	if(this._lot._data.date_started<this._servertime){
		html += '<tr><td class="bidder_info_cell">Time Remaining:</td><td class="bidder_input_cell" id="bidder_time_remaining">'+this._getTimeRemaining()+'</td></tr>';
	} else {
		html += '<tr><td class="bidder_info_cell">Auction Starts In:</td><td class="bidder_input_cell" id="bidder_time_remaining">'+this._getTimeRemaining()+'</td></tr>';
	}
	this._currentAsking =this._getNextAsking()
	if(this._lot._data.date_ended<this._servertime){
		html += '<tr><td colspan="2" style="text-align:center; padding-bottom:10px; padding-top:10px;"><input type="button" id="bidder_bid_button" value="Auction Ended" disabled="disabled" style="color:#999999;" /></td></tr>';
	} else {
		if(this._userId!=null && this._userId>0){
			if(parseInt(this._lot._data.buyer_id)==this._userId){
				html += '<tr><td colspan="2" style="text-align:center; padding-bottom:10px; padding-top:10px;"><input type="button" id="bidder_bid_button" value="In The Lead" disabled="disabled" onclick="javascript:timedLot._createBid();" /></td></tr>';
			} else {
				html += '<tr><td colspan="2" style="text-align:center; padding-bottom:10px; padding-top:10px;"><input type="button" id="bidder_bid_button" value="Bid '+number_format(this._currentAsking)+'" onclick="javascript:timedLot._createBid();" /></td></tr>';
			}
		} else {
			html += '<tr><td colspan="2" style="text-align:center; padding-bottom:10px; padding-top:10px;"><input type="button" id="bidder_bid_button" value="Login To Bid Now" /></td></tr>';
		}
	}
	html += '<tr><td class="bidder_info_cell">Delivery Charge:</td><td class="bidder_input_cell">&pound;'+number_format(this._lot._data.delivery)+'</td></tr>';
	html += '</table>';
	html += '</div>';
	var nearCheck = parseFloat(this._lot._data.buy_now)*0.85;
	if((parseFloat(this._lot._data.buy_now)>0) && (parseFloat(this._lot._data.hammer_price)<nearCheck)){
		html += '<div id="bidder_buy_now">';
		html += '<div id="bidder_buy_now_left">';
		html += '<img src="images/icons/instantwin.png" title="Chance to beat the bidders" />';
		html += '</div>';
		html += '<div id="bidder_buy_now_right">';
		html += '<span>Really want this item? take the chance to beat the bidders with our instant win!</span><br /><br />';
		html += '<span>Our instant win price is: </span><span id="buy_now_price">&pound;'+number_format(parseFloat(this._lot._data.buy_now))+'</span>';
		html += '</div>';
		html += '</div>';
	}
	
	
	doc.innerHTML = html;
	this._loadImages();
	this._clockTimer = setInterval(this._changeTime,1000);
}
BidderController.prototype._getNextAsking = function(){
	if(this._lot._data.bidding_type==1){
		var nHam = parseFloat(this._lot._data.hammer_price)+parseFloat(this._lot._data.increment);
		return nHam;
	}
}
BidderController.prototype._createXMLHttpRequest= function(){
	try {
		//firefox, opera & Safari
		var xmlHttp = new XMLHttpRequest();
	} catch(e) {
		try {
			var xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e){
			try {
				var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e){
				xmlHttp=null;	
			}
		}
	}
	return xmlHttp;
}
BidderController.prototype._onDataInit = function(){
	if (this._xmlHttp.readyState==4 || this._xmlHttp.readyState=="complete"){
		this._servertime = this._xmlHttp.responseXML.documentElement.getAttribute('servertime');
		switch(this._xmlHttp.responseXML.documentElement.nodeName){
			case 'lotdata':
				this._lot = new LotBuilder(this._xmlHttp.responseXML.documentElement);
				this._createBidderScreen();
				break;
		}
	}
}
BidderController.prototype._onDataRefresh = function(){
	if (this._xmlHttp.readyState==4 || this._xmlHttp.readyState=="complete"){
		this._servertime = this._xmlHttp.responseXML.documentElement.getAttribute('servertime');
		switch(this._xmlHttp.responseXML.documentElement.nodeName){
			case 'lotdata':
				this._lot = new LotBuilder(this._xmlHttp.responseXML.documentElement);
				this._updateBidderScreen();
				break;
		}
	}
}
BidderController.prototype._onDataComplete = function(){
	if (this._xmlHttp.readyState==4 || this._xmlHttp.readyState=="complete"){
		this._servertime = this._xmlHttp.responseXML.documentElement.getAttribute('servertime');
		switch(this._xmlHttp.responseXML.documentElement.nodeName){
			case 'lotbid':
				this._xmlHttp.responseXML.documentElement.getAttribute('responsecode');
				this._requestTimeRefresh();
				break;
		}
	}
}
function loadAjaxBidderController(id,userId){
	timedLot = new BidderController(id,userId);
	var loader = document.getElementById('bidder_loader');
	loader.innerHTML = '';
}
function number_format(num){    
    var n = num.toString();
    var nums = n.split('.');
    var newNum = "";
    if (nums.length > 1){
		var dec = nums[1];
		if(dec.length<2){
			dec+= '0';
		}
        newNum = nums[0] + "." + dec;
    } else {
	    newNum = num.toString()+".00";
    }
    return newNum;
}
