// PoundBid.com core v2.0.1 (2009-04-03)
// Copyright (c) 2009 - Forge Ltd.
// Written by Lukas

//object Auction prototype
function NewAuction(LotID, CloseInSeconds, StartTS, LastBidder, Price, Closed) {
	this.LotID = LotID;
	this.CloseInSeconds = CloseInSeconds;
	this.StartTS = StartTS;
	this.LastBidder = LastBidder;
	this.Price = Price;
	this.Finished= Closed;
}//end of object Auction prototype


bInitialised = false;//set to true, when 1st response from server arrives
tsServer = 0; //server timestamp.
tsLastCall = 0;//ts of last succ ajax call
bRequestInProgress = false; //rtue if ajax call in progress
bAuctionInProgress = true; //true if at least one auction is in progress
tmsTimeAjaxStart = 0; //timestamp (in ms) of beginning of request
tmsTimeAjaxEnd = 0; //timestamp (in ms) of end of request
tsSyncAjaxCall = 0; //timestamp of sync. ajax call
arrAuctions = new Array();//holds all auction objects
var intAjaxMin = 2;
var intAjaxCurr = 0;

function StartUp(arrActiveLotIDs) {
	//auction IDs to be monitored by this object
	if (typeof(arrActiveLotIDs) == "undefined") {
		arrLotIDs = new Array();
	} else {
		arrLotIDs = arrActiveLotIDs;
	}
	//start the show
	tmrMain = setInterval(fncMainLoop, 1000);
}


//assign methods and events
function fncIsInitialised() {
	return (tsServer> 0);
}

function fncBell() {
	alert('ding dong' + tmsTimeAjaxStart );
}




function fncStoreAuction(objAuction) {
	var intFound = -1;
	var intI = 0;
	for (intI = 0;intI< arrAuctions.length; intI++) {
		if (arrAuctions[intI].LotID == objAuction.LotID) {
			intFound = intI;
		}
	}
	if (intFound> -1) {
		if (arrAuctions[intFound].Price != objAuction.Price) {
			fncRenderAuction(objAuction, true);
		}
		arrAuctions[intFound] = objAuction;
	} else {
		arrAuctions[intI] = objAuction;
	}
}//end of function fncStoreAuction

function fncRemoveAuction(objAuction) {
	var intFound = -1;
	var intI = 0;
	for (intI = 0;intI< arrAuctions.length; intI++) {
		if (arrAuctions[intI].LotID == objAuction.LotID) {
			intFound = intI;
		}
	}
	if (intFound> -1) {
		arrAuctions.splice(intFound,1);
	}
}//end of function fncRemoveAuction

function fncMainLoop () {
	if (fncIsInitialised()) {
		//update server
		tsServer++;
		var intI = 0;
		for (intI = 0;intI< arrAuctions.length; intI++) {
			//amend times
			arrAuctions[intI].CloseInSeconds--;
			fncRenderAuction(arrAuctions[intI],false);
		}
	}

	if (bAuctionInProgress && !bRequestInProgress ) {
		//ajax update
		intAjaxCurr--;
		if (intAjaxCurr< 1) {
			intAjaxCurr= intAjaxMin;
			fncMakeAjaxRequest();
		}

	}
}//end of this.MainLoop

function fncMakeAjaxRequest () {
	if (this.bRequestInProgress) return;
	bRequestInProgress = true;
	var dtNow = new Date();
	tsTimeSyncStart = dtNow.getTime();
	strUrl = '';
	for (LotID in arrLotIDs) {	strUrl += arrLotIDs[LotID] + '|';}
	if (strUrl.length > 0) {strUrl = strUrl.substr(0,(strUrl.length - 1));}
	if (strUrl.length > 0) {
		strUrl = "/ajax/feedhome.php?ids=" + strUrl;
		if (tsLastCall > 0) {strUrl+= "&check=" + tsLastCall;	}
		//make request
		$.ajax({
			type: "GET",
			url: strUrl,
			datatype: "xml",
			cache: false,
			error: fncHandleErrorAjaxRequest,
			success: fncHandleSuccessAjaxRequest
			});
	}
}//end of fncMakeAjaxRequest


function fncHandleSuccessAjaxRequest(xmlData, textStatus) {
	var dtNow = new Date();
	tsTimeSyncEnd = dtNow.getTime();
	var objAuction = false;
	//read auction details
	$('lot',xmlData).each(function(i) {
		strLotID = $(this).find("lotid").text();
		strTopBidName = $(this).find("topbidname").text();
		strTopBidValue = $(this).find("topbidvalue").text();
		intCloseInSeconds = $(this).find("closein").text();
		intStartTS = parseInt($(this).find("start").text());
		bClosed = ($(this).find("closed").text() == '0')?'0':'CLOSED';
		objAuction = new NewAuction(strLotID, intCloseInSeconds, intStartTS, strTopBidName, strTopBidValue, bClosed);
		fncStoreAuction(objAuction);
	});
	var tsTemp= parseInt($('response',xmlData).find("svrt").text() );
	if (tsTemp>0) {
		if (Math.abs(tsServer-tsTemp) >2) {
			tsServer= tsTemp;
		}
		tsLastCall = tsServer;
	}

	bRequestInProgress = false;
}//end of function HandleSuccessAjaxRequest

//function handling error ajax request
function fncHandleErrorAjaxRequest(XMLHttpRequest, textStatus, errorThrown) {
	bRequestInProgress = false;
}//end of function HandleErrorAjaxRequest





//##############################################
// RENDERING FUNCTIONS
function fncRenderAuction(objAuction,bFlash) {
	if (objAuction.Finished == "CLOSED") {
		//render auction as closed
		fncCloseAuction(objAuction);
		//remove from buffer
		fncRemoveAuction(objAuction);
		return;
	}
	if (bFlash==undefined) {
		bFlash= false;
	} else {
		if (bFlash) {bFlash= true;}
	}
	var strID = '#L' + objAuction.LotID;
	var strTemp = '';
	strTemp= FormatCountdownString(objAuction.CloseInSeconds, false);
	$(strID + ' .ajaxtime').text(strTemp);
	if (objAuction.StartTS> tsServer) {
		strTemp= ' (starts in ' + FormatCountdownString(objAuction.CloseInSeconds, true) + ')';
	} else {
		strTemp= ' (ends in ' +  FormatCountdownString(objAuction.CloseInSeconds, true) + ')';
		//strTemp = tsServer + ' ' + objAuction.StartInSeconds;
	}
	$(strID + ' .datetext').text(strTemp);

	$(strID + ' .topbidder').text(objAuction.LastBidder);

	if (bFlash) {
		strTemp= objAuction.Price;
		$(strID + ' .flashAmount').attr('innerHTML',strTemp);
		$(strID + ' .flashAmount').css("background-color","red").animate({ backgroundColor: "white" }, 800);
	}
}//end of function RenderAuction




function RenderCountdown() {
	if (!bAuctionInProgress ) {
		strTimeleft = 'Closed';
	}
	if (strTimeleft.length > 0) {
		//update timer element
		$('#countdown').text(strTimeleft);
		//update homepage timer
		$('.ajaxtime').text(strTimeleft);
	}
//	}
}//function RenderCountdown

function fncCloseAuction(objAuction) {
	var strID = '#L' + objAuction.LotID;
	strTimeleft = 'Closed';
	$('#buyquick').css("display","none");
	$(strID + ' .bidbutton').attr('class','bidbuttonclosed')
	$(strID + ' .ajaxtime').text('Closed');
}//end of function CloseAuction()






//function updates timer element (currently div with id="timer")
function FormatCountdownString (intTimeRem, bChars) {
	var strTimeleft = '';
	if (intTimeRem < 1) {strTimeleft = 'Going...';
	} else if (intTimeRem == 'CLOSED') {strTimeleft = 'Closed';
	} else if (intTimeRem < 2) {strTimeleft = 'Going...';
	} else if (intTimeRem < 4) {strTimeleft = 'Going..';
	} else if (intTimeRem < 6) {strTimeleft = 'Going.';
	} else {
		var intDays=Math.floor(intTimeRem / 86400);
		var intHours=Math.floor((intTimeRem - (intDays * 86400)) / 3600);
		var intMinutes=Math.floor((intTimeRem - (intDays * 86400) - (intHours * 3600)) / 60);
		var intSeconds=Math.floor(intTimeRem - (intDays * 86400) - (intHours * 3600) - (intMinutes * 60));
		if (bChars) {
			var strS = "";
			strTimeleft = FormatDigit(intHours)+ ":" + FormatDigit(intMinutes) + ":" + FormatDigit(intSeconds);
			if (intDays>0) {
				if (intDays > 1) { strS = "s"; }
				strTimeleft = intDays + " day" + strS + " + " + strTimeleft;}
		} else {
			intHours=Math.floor(intTimeRem  / 3600);
			intMinute = Math.floor((intTimeRem - (intHours * 3600)) / 60);
			intSecond = Math.floor(intTimeRem - (intHours * 3600) - (intMinute * 60));

			strTimeleft = FormatDigit(intHours)+ ":" + FormatDigit(intMinutes) + ":" + FormatDigit(intSeconds);
		}
	}
	return strTimeleft;
}//end of function FormatCountdownString()

function FormatDigit(intNumber) {
	return (intNumber < 10)?("0" + intNumber):(intNumber);
}//end of function FormatDigit()







//####################################################

//Ajax buffer
function AxReqBuffer(size) {
	if (size == undefined) {
		size = 5;
	}
	this.ItemNum = 0;
	this.ItemAct = -1;
	this.ItemMax = size;
	this.Requests = new Array();

	this.AmendPointer = fncAmendPointer
	this.AddItem = fncAddItem
	this.GetItem = fncGetItem
}

function fncAmendPointer(intDelta) {
	intNewOne = this.ItemAct + intDelta;
	if (intNewOne>=this.ItemMax) {intNewOne-=this.ItemMax;}
	if (intNewOne<0) {intNewOne+=this.ItemMax;}
	return intNewOne;
}//end of function fncAmendPointer

function fncAddItem(objItem) {
	this.ItemAct= this.AmendPointer(1);
	this.Requests[this.ItemAct] = objItem;
	this.ItemNum++;
	if (this.ItemNum > this.ItemMax) {this.ItemNum--;}
}//end of function fncAddItem
function fncGetItem(intItemIndex){
	intIdx = this.AmendPointer(intItemIndex +  this.ItemMax - this.ItemNum);
alert (this.ItemNum + ' act:' + this.ItemAct + ' req:' + intItemIndex + ' real:' + intIdx);
	if (this.Requests[intIdx] != undefined) {
		objResult = this.Requests[intIdx];
	} else {
		objResult = false;
	}
	return objResult;
}//end of function fncGetItem

