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

	//auction details
	var intLotID = 0;
	var tsStartTS = 0;
	var tsEndedTS = 0;
	var strTopBidFullname = 0;
	var strCurrentPrice = '';
	var strPrevPrice = '';
	var bFinished = false;
	var htmlBidHistory = '';
	var intBidPrice = 0;
	var intBidValue = 0;

	//status flags
	var bInitialised = false;//set to true, when 1st response from server arrives
	var bAuctionInProgress = true; //true if at least one auction is in progress(if closed will be updated with 1st ajax sync)
	var bRequestInProgress = false; //rtue if ajax call in progress
	var bBidInProgress = false;//true if ajax bid in progress
	var intResetStatus = 1;
	var intStatus = 0;//can be 0 normal,1 wait 2 success
	var intPrevStatus = 1;//prvious status
	//member details
	var intNumberOfBids = 0;//current number of members bids
	var intBidsPlaced = 0;
	//time vars
	var tsServer = 0; //server timestamp.
	var tsLastCall = 0;//ts of last succ ajax call
	var tmsTimeAjaxStart = 0; //timestamp (in ms) of beginning of request
	var tmsTimeAjaxEnd = 0; //timestamp (in ms) of end of request
	var tsSyncAjaxCall = 0; //timestamp of sync. ajax call
	//sync behav control
	var intAjaxMin = 2;//min delay between ajax sync calls
	var intAjaxCurr = 0;//delay for init sync

function StartUp(strLotID, intInitBidsPlaced, intInitBidPrice, intInitBidValue) {
	//auction IDs to be monitored by this object
	intLotID = parseInt(strLotID);
	//update init values
	intBidsPlaced = intInitBidsPlaced;
	intBidPrice = intInitBidPrice;
	intBidValue = intInitBidValue;
	//start the show
	tmrMain = setInterval(fncMainLoop, 1000);
}//end of function StartUp

function fncMainLoop () {
	if (bInitialised) {
		//update server ts
		tsServer++;
		fncRenderAll();
	} else {
		fncRenderBuyNow();
	}
	//ajax sync
	if (bAuctionInProgress && !bRequestInProgress ) {
		intAjaxCurr--;
		if (intAjaxCurr< 1) {
			intAjaxCurr= intAjaxMin;
			fncMakeSyncRequest();
		}
	}
}//end of fncMainLoop

function fncMakeSyncRequest () {
	if (bRequestInProgress) return;
	bRequestInProgress = true;
	var strUrl = '';
	var dtNow = new Date();
	tsTimeSyncStart = dtNow.getTime();
	strUrl = intLotID + '';
	if (strUrl.length > 0) {
		strUrl = "/ajax/feedets.php?aid=" + strUrl;
		//make request
		$.ajax({type: "GET",url: strUrl,datatype: "xml",cache: false,timeout:10000,
				error: fncHandleErrorSyncRequest,success: fncHandleSuccessSyncRequest});
	}
}//end of fncMakeAjaxRequest
function fncHandleSuccessSyncRequest(xmlData, textStatus) {
	var dtNow = new Date();
	tsTimeSyncEnd = dtNow.getTime();
	fncProcessAjaxData(xmlData);
	bRequestInProgress = false;
}//end of function HandleSuccessAjaxRequest
//function handling error ajax request
function fncHandleErrorSyncRequest(XMLHttpRequest, textStatus, errorThrown) {
	var dtNow = new Date();
	tsTimeSyncEnd = dtNow.getTime();
	bRequestInProgress = false;
}//end of function HandleErrorAjaxRequest

function fncProcessAjaxData(xmlData) {
	//read auction details
	$('adts',xmlData).each(function(i) {
		//retrieve info
		strNewFullname = '' + $(this).find("nm").text();
		strNewPrice = '' + $(this).find("vl").text();
		intNewEndedTS = '' + $(this).find("tr").text();
		bNewFinished = ($(this).find("clsd").text() == '0')?false:true;
		//validate
		if ((strNewFullname.length > 0)
			&& (strNewPrice.length > 0)
			&& (intNewEndedTS.length > 0)) {
			bInitialised = true;
			strTopBidFullname = strNewFullname;
			strCurrentPrice = strNewPrice;
			tsEndedTS = parseInt(intNewEndedTS);
			bFinished = bNewFinished;
		}
	});

	//bid history
	htmlNewBidHistory = '';
	$('bid',xmlData).each(function(i) {
		strBidderName = $(this).find("nm").text();
		strBidderPrice = $(this).find("vl").text();
		//Build row HTML data and store in string
		htmlNewBidHistory += '	<li class=\"name\">' + strBidderName + '</li>\n';
		htmlNewBidHistory += '	<li class=\"bid\">' + strBidderPrice + '</li>\n';
	});
	if (htmlNewBidHistory.length > 0) {htmlBidHistory = "<ul>" + htmlNewBidHistory + "</ul>"}

	//server time sync
	var tsTemp= parseInt($('response',xmlData).find("svrt").text());
	if (tsTemp>tsLastCall) {
		tsLastCall = tsTemp;
		if (Math.abs(tsServer-tsLastCall) >2) {
			tsServer= tsLastCall;
		}
	}
}//end of function fncProcessAjaxData


//bidding
function fncMakeAjaxBid(){
	if (!bAuctionInProgress) return;
	if (!bInitialised) return;
	if (bBidInProgress) return;
	//status to wait
	intStatus = 1;
	//$('#imgStatus').attr('src','/media/images/wait.gif');
	//do the job
	bBidInProgress = true;
	strUrl = '';
	strUrl += intLotID + '';
	if (strUrl.length > 0) {
		strUrl = "/ajax/makebid.php?aid=" + strUrl;
		$.ajax({type: "GET",url: strUrl,datatype: "xml",cache: false,timeout:10000,
				error: fncHandleErrorAjaxBid,success: fncHandleSuccessAjaxBid});
	}
}//end of function function fncMakeAjaxBid
function fncHandleSuccessAjaxBid(xmlData, textStatus) {
	bBidInProgress = false;
	//intNumberOfBids -= 1;
	intStatus = 2;
	intResetStatus = 4;
	//get remaining bids
	var intTemp= $('response',xmlData).find("brem").text();
//alert(intTemp );
	if ((intTemp > 0)
		&& (!(intTemp==intNumberOfBids))) {
		intNumberOfBids = intTemp;
		intBidsPlaced += 1;
//alert(intNumberOfBids );
	}
	//get data
	fncProcessAjaxData(xmlData);
	fncRenderAuction();
	fncRenderBuyNow();
}//end of function fncHandleSuccessAjaxBid

//function handling error ajax request
function fncHandleErrorAjaxBid(XMLHttpRequest, textStatus, errorThrown) {
	intStatus = 3;
	intResetStatus = 10;
	alert("An error has occured, your bid was not accepted. Please try to reload page and bid again.")
	bBidInProgress = false;
}//end of function fncHandleErrorAjaxBid

//##############################################
// RENDERING FUNCTIONS
function fncRenderAll() {
	if (!bInitialised) return;
	fncRenderAuction();
	//history
	if (htmlBidHistory.length > 0) {
		htmlToRender = htmlBidHistory;
	} else {
		htmlToRender = 'No bidders yet. <br /><br /> Be the first to grab this bargain';
	}
	$('#bidlist').attr('innerHTML',htmlToRender);
	//timer
	var intTemp = tsEndedTS - tsServer;
	if ((intTemp>0) && (intTemp<10)) {
		$('#buyquick').show();
	} else {
		$('#buyquick').hide();
	}
	strTemp=bFinished?'Closed':(FormatCountdownString(intTemp, false));
	$('#countdown').text(strTemp);
}//end of function fncRenderAll

function fncRenderAuction() {
	if (bFinished) {
		fncCloseAuction();
	}
	if (!bInitialised) return;
	//bid count
	$('#bidcount').text(intNumberOfBids);
	$('#bidder').text(strTopBidFullname);
	$('#flashAmount').attr('innerHTML',strCurrentPrice);
	if ((strPrevPrice.length > 0) && (strPrevPrice != strCurrentPrice)){
		$('#flashAmount').css("background-color","red").animate({ backgroundColor: "white" }, 800);
	}
	strPrevPrice = strCurrentPrice;
	//status
	if (intResetStatus>0) {
		intResetStatus--;
		if (intResetStatus == 0) {
			intStatus = 0;
		}
	}
	if (intPrevStatus!=intStatus) {
		if (intStatus == 3) $('#imgStatus').attr('src','/media/images/sterr.gif')
		else if (intStatus == 1) $('#imgStatus').attr('src','/media/images/stwait.gif')
	//	else if (intStatus == 2) $('#imgStatus').attr('src','/media/images/stsucc.gif')
		else $('#imgStatus').attr('src','/media/images/stempty.gif');
		intPrevStatus = intStatus;
	}
}//end of function RenderAuction

function fncRenderBuyNow() {
//	var strBidPrice = '';
//	var strBnHeadline = '';
//	var strBnFormula = '';
//	var intActBidPrice = 0;
//	intActBidPrice = intBidPrice - intBidsPlaced;
//	if (intActBidPrice <= 0) {
//		strBidPrice = 'for free';
//	} else {
//		strBidPrice = intActBidPrice + ' bid';
//		if (intActBidPrice > 1) {
//			strBidPrice+= 's';
//		}
//	}
//	if (intActBidPrice > 0 ) {
//		strBnHeadline = 'Buy now for ' + strBidPrice + ' (inc P&amp;P)';
//		strBnFormula = '(' + strBidPrice + ' = ' + FormatPoundPrice(intBidValue * intActBidPrice);
//		strBnFormula+= ' at ' + FormatPoundPrice(intBidValue) + ' per bid)';
//	} else {
//		strBnHeadline = 'Get it now for free';
//		strBnFormula = '';
//	}
//	$('#phBnHeadline').html(strBnHeadline);
//	$('#phBnFormula').html(strBnFormula);
}//end of function fncRenderBuyNow


function fncCloseAuction() {
	strTimeleft = 'Closed';
	bAuctionInProgress = false;
	$('.rollover').attr("src","/media/images/btn_bigbidc.png");
}//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 = '';
	} 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) {
			strTimeleft = intHours + "h " + intMinutes + "m " +intSeconds + "s";
			if (intDays>0) {strTimeleft = intDays + "d " + 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);
			//if (intDays>0) {strTimeleft = intDays + "d " + strTimeleft;}
		}
	}
	return strTimeleft;
}//end of function FormatCountdownString()

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

function FormatPoundPrice(intPriceInPence) {
	var strPriceF = '';
	if (intPriceInPence>99) {
		var dblPoundPrice = (intPriceInPence/100);
		var intPoundPrice = Math.floor(dblPoundPrice);
		var intPencePrice = Math.round((dblPoundPrice - intPoundPrice) * 100);
		if (intPencePrice == 0) {
			intPencePrice = '00';
		}
		strPriceF = '<strong>&pound;' + (intPoundPrice) + '.' + intPencePrice + '</strong>';
	} else if (intPriceInPence>0) {
		strPriceF = intPriceInPence + 'p';
	} else {
		strPriceF = 'Free...';
	}
	return strPriceF;
}//end of function FormatPoundPrice