
/***
 * Input is a comma separated string for time left. The actual HTML will be
 * returned by the function and used in the display div
 * 
 * @param {String} commaTimeStr
 */

var listingClosed = false;

function formatProductTimeLeft(commaTimeStr, closedStatus, bidder, auctType, auctResMet, winSound, listingID) {
	
	var tlArray = commaTimeStr.split(","); 
	
	//assign the array values
	var tlDays     = tlArray[0];
	var tlHours    = tlArray[1];
	var tlMinutes  = tlArray[2];
	var tlSeconds  = tlArray[3];
	
	var retStr = "";
	if (tlDays>0) {
		retStr = retStr + tlDays + " Day(s), " + tlHours + " Hours " + tlMinutes + " Minutes " +  tlSeconds + " Seconds";
	}
	else {
		//no days left
		if (tlHours>0) { //hours left
			retStr = retStr + tlHours + " Hours " + tlMinutes + " Minutes " +  tlSeconds + " Seconds";
		} //END: hours left
		else if (tlMinutes>0 || tlSeconds>0){
			//no hours left
			retStr = retStr + tlMinutes + " Minutes " +  tlSeconds + " Seconds";
		} //no hours left
	} //days left

	return retStr;
} //END: formatProductTimeLeft


function updateProductView(lo) {
 	//logToWindow("updateProductView Called: " + lo.listingID);
	
	var tlArray = lo.TimeLeft.split(","); 
	
	//assign the array values
	var tlDays     = tlArray[0];
	var tlHours    = tlArray[1];
	var tlMinutes  = tlArray[2];
	var tlSeconds  = tlArray[3];
	
	logToWindow("Auction Type: " + lo.auctionType);
	logToWindow("Reserve Status: " + lo.reserveStatus);
	logToWindow("winner name: " + lo.currentWinner);
	logToWindow("latest bidder name: " + lo.latestBidderName);
	logToWindow("prevBid: " + lo.prevBid);
	logToWindow("current bid: " + lo.currentBid);
	logToWindow("latest bidder bid: " + lo.latestBidderBid);
	logToWindow("win sound: " + lo.winSound);
	logToWindow("avatar Name: " + lo.avatarName);
	
	//consider reserve price auctions, and showing status
	if (lo.auctionType=="R") {
		//is the status met?
		var reserveTip = document.getElementById('reserve_tip');
		var reserveTip1 = document.getElementById('reserve_tip1');
		
		if (lo.reserveStatus=="Y") {
			//let's hide the message
			//$('ReserveRow').style.display = "none";
			if (reserveTip1)
			{
				$('#reserve_tip1').hide();
			}
			if (reserveTip)
			{
				$('#reserve_tip').html("Reserve OFF");
			}
			//$('reserve_tip1').style.display = "none";
			//$('reserve_tip').innerHTML = "Reserve OFF";
		}
		else {
			//let's show the message that reserve is not met
			//$('ReserveRow').style.display = "";
			if (reserveTip1)
			{
				$('#reserve_tip1').show();
			}
			//$('reserve_tip1').style.display = "";
		}
	} //END: reserve price

	// determine if the auction is closed, sold or both
	var isSold   = false;
	var isClosed = false;

	var timeLeft = formatProductTimeLeft(lo.TimeLeft, lo.closedStatus, lo.currentWinner, lo.auctionType, lo.reserveStatus, lo.winSound, lo.listingID);
	if (timeLeft == "")
	{
		logToWindow("closedStatus: " + lo.closedStatus);
		logToWindow("bidder: " + lo.currentWinner);
		logToWindow("auctType: " + lo.auctionType);
		logToWindow("winSound: " + lo.winSound);
		
		if (lo.closedStatus=="N") {
			isSold   = false;
			isClosed = false;
		} //not closed yet
		else if (lo.closedStatus=="Y" && lo.currentWinner!="" && lo.auctionType!="R") {
			isSold = true;
			isClosed = true; 
			logToWindow("in condition: closedStatus=='Y' && bidder!='' && auctType!='R'");
		} //regular auction closed with high bidder: sold
		else if (lo.closedStatus=="Y" && lo.auctionType=="R" && lo.reserveStatus!="N") {
			isSold = true;
			isClosed = true; 
			logToWindow("in condition: closedStatus=='Y' && auctType=='R' && auctResMet!='N'");
		} //reserve auction closed and met: sold
		else if (lo.closedStatus=="Y") {
			isSold   = false;
		    isClosed = true;
			logToWindow("in condition: closedStatus=='Y'");
		} //closed but not sold in iether case
		
		//otherwise the default is closing pending
		
		logToWindow("isSold: " + isSold);
		logToWindow("isClosed: " + isClosed);
		
		if (isClosed && isSold) {
			timeLeft = timeLeft + "Sold!";
			insertFW(lo.winSound, 5500);				
			listingClosed = true;
			if (lo.currentWinner==currentUser || currentUser == "")
			{
				$('#payNowSection').show();
			}
		} //sold status
		else if (isClosed && !isSold) {
			timeLeft = timeLeft + "This Auction is Closed.";
			listingClosed = true;		
		} //closed status, no winner
		
		else {
			//no confirmed status yet
			timeLeft = timeLeft + "<i>Closing...</i>";
		}		
	}

	if (listingClosed)
	{
		$('#BidArea').hide();
	}

	$('#TimeLeft').html('<B>' + timeLeft + '</B>');
	
	nf.setNumber(lo.currentBid);
	$('#WinningBid').html("<b>" + nf.toFormatted() + " USD</b>"+ " <a style='font-size: 10px; cursor: pointer;' href='javascript:showConvertedCurrency("+ lo.listingID + "," + lo.currentBid +")'>(Convert)</a>");
	
	var saveElement = "#Saving";
	var priceElement = "#MSRP";
	var savingString = "";
	
	//update save percentage div
	if ($(saveElement) && $(priceElement)){
		var comparePrice = $(priceElement).text();
		var savingMoney = comparePrice - lo.currentBid;
		savingMoney = Math.round(savingMoney);
		var savingPercentage = ((comparePrice - lo.currentBid)/comparePrice)*100;
		savingPercentage = Math.floor(savingPercentage);
		nf.setNumber(savingMoney);
		savingString = nf.toFormatted();
		nf.setNumber(savingPercentage/100);
		savingString = savingString + ' (' + nf.toPercentage() + ')';
		$(saveElement).text(savingString);
	}
	
	if (lo.currentWinner && lo.currentWinner!="") {
		var innerHtml="";
		if (lo.currentWinner==currentUser) {
		//show winner in green if it's the current user
			innerHtml = innerHtml + "<b><font color='#00CC33'>" + maskUsername(lo.currentWinner) + "</font></b>";
		}
		else if (lo.currentWinner!=currentUser) {
		//otherwise show the current winner in a normal font
		//mask current winner username
			innerHtml = innerHtml + "<b>" + maskUsername(lo.currentWinner) + "</b>";
		}
				
		$('#CurrentWinner').html(innerHtml);
		if($('#WinnerAvatar'))
		{
			var avatarInnerHtml = "";
			if( lo.avatarName == "" )
			{
				lo.avatarName = "0";
			}
			if( avatarSmallImageHost )
			{
				avatarInnerHtml = '<IMG src="'+avatarSmallImageHost+lo.avatarName+'.jpg">';		
			}
			else
			{
				avatarInnerHtml = '<IMG src="http://llfull.bidz.com/avatars/50x50/'+lo.avatarName+'.jpg">';		
			}
			if( $('#WinnerAvatar').html() != avatarInnerHtml)
			{
				$('#WinnerAvatar').html(avatarInnerHtml);
			}
		}
	}
	else {
		var innerHtml="";
		if (lo.latestBidderName && lo.latestBidderName !="") { 
			logToWindow("in condition:  If the bidding is completed with no winner : latest bidder exists but winner is null");
			innerHtml = innerHtml + "<b>No Winner </b>";
			$('#CurrentWinner').html(innerHtml);
		}
	}
	
	$('#NumBids').html("<b>" + lo.numberOfBids + "</b>");
	
	// lo.listingID, lo.closedStatus
	
	$('#CloseTime').html("<b>" + lo.closeTime + "</b>");

	var inputName = "BidField";
	//alert("nextbid " + lo.nextBid);
	if (!listingClosed && (lockedInputField==null || lockedInputField!=inputName)) {
		//only update the input value if the field is not locked for editing
		inputNf.setNumber(lo.nextBid);
		$("#" + inputName).val(inputNf.toFormatted());		
	} //END: if not locked
	
	//check if the previous and current bids are different
	if (lo.prevBid!=lo.currentBid) {
	
		var bidderElementName = "#CurrentWinner";
		var amountElementName = "#WinningBid";
		
		
		if (lo.latestBidderName!=null && lo.latestBidderName!="" && lo.latestBidderName != lo.currentWinner ) {
			prod_showRunnerUpAndThenWinner(bidderElementName, amountElementName, lo.latestBidderName, lo.currentWinner, lo.currentBid, lo.latestBidderBid, lo.listingID);
		}
		else {
			//we have to signal a new bid to the user
			$('#CurrentWinner').css("backgroundColor", "lightgreen");
			setTimeout("resetBackground('"+'#CurrentWinner'+"')", 700);
		}
		playDingSound();
	}
	
	//time left flashing - less then 10 seconds
	if (tlDays=="0" && tlHours=="0" && tlMinutes=="0") {
		var secondsLeftInt = parseInt (tlSeconds, 10); //make sure to parse in base 10
		if (secondsLeftInt<=FLASH_LESS_THEN_SECONDS && secondsLeftInt>0) {
			var timeLeftName = "#TimeLeft";
			$(timeLeftName).css("backgroundColor", "orange"); //orange
			setTimeout("resetBackground('"+timeLeftName+"')", 700);
		} //END: Flash time left
	} //END: only seconds left
	
	var valueElementName = '#userProxyValue_'+ lo.listingID;
	var userproxy = $(valueElementName).html();	
	if (userproxy != null){
		userproxy = userproxy.trim();
	}
	if (userproxy != null && userproxy !=""){		
		logToWindow("user proxy: " + userproxy);
		userproxy = userproxy.substring(1,userproxy.length);
		userproxy = userproxy.replace(',','');
		logToWindow("user proxy without $ sign: " + userproxy);
		var userProxyDouble = parseFloat (userproxy);
		logToWindow("userProxyDouble " + userProxyDouble);
		var currentBidDouble = parseFloat(lo.currentBid);
		logToWindow("currentBidDouble " + currentBidDouble);
		
		if (userProxyDouble <= currentBidDouble){
			disableUserProxy(lo.listingID);
		}
	}//END :if (userproxy !="")
	
	//update preferred currency values
	var currencyDivElementName = "#currencyBox_"+lo.listingID;
		if ($(currencyDivElementName).css("display") == 'block'){
			updatePreferredCurrencyValues("#currency_"+lo.listingID,lo.currentBid);
		}

	return lo.closedStatus == "Y";
 } //END: updateShowcaseView
 
 function prod_showRunnerUpAndThenWinner(bidderElementName, amountElementName, latestBidderName, currWinner, currentBid, latestBid, listingId) {
 		
 	//let's show the runner up as yellow
 	$(bidderElementName).css("backgroundColor", "#ffa");
 	$(amountElementName).css("backgroundColor", "#ffa");

 	$(bidderElementName).html( "<b>" + maskUsername(latestBidderName) +"</b>");
 	nf.setNumber(latestBid);
 	$(amountElementName).html("<b>" + nf.toFormatted() + " USD</b>" + " <a style='font-size: 10px; cursor: pointer;' href='javascript:showConvertedCurrency("+ listingId + "," + latestBid +")'>(Convert)</a>");
 	
 	//now that we are yellow, let's wait only a 1 second, then show the right person in green
 	setTimeout("prod_showWinnerAfterRunnerUp('"        + bidderElementName
 	                                      + "','" + amountElementName 
 	                                      + "','" + currWinner 
 	                                      + "','" + currentBid
 	                                      + "','" + listingId + "')", 1000);
 } //END: showRunnerUpAndThenWinner
 
 function prod_showWinnerAfterRunnerUp(bidderElementName, amountElementName, currWinner, currentBid, listingId) {
 	
 	$(bidderElementName).css("backgroundColor", "lightgreen");
 	$(amountElementName).css("backgroundColor", "lightgreen");
 	
 	$(bidderElementName).html("<b>" + maskUsername(currWinner) +"</b>");
 	nf.setNumber(currentBid);
 	$(amountElementName).html("<b>" + nf.toFormatted() + " USD</b>" + " <a style='font-size: 10px; cursor: pointer;' href='javascript:showConvertedCurrency("+ listingId + "," + currentBid +")'>(Convert)</a>");
 
    setTimeout("resetBackground('"+bidderElementName+"')", 700);
    setTimeout("resetBackground('"+amountElementName+"')", 700);
    
    
    
 } //END: showWinnerAfterRunnerUp 
 
 
 
/*function insertFW(country, duration) {
	var fw = new SWFObject("/bzJApp/views/flash/fireworks.swf", "fireworks", "350", "270", "8", "#ffffff");
		
	logToWindow("insertFW - country: " + country);
				
	fw.addParam("quality", "high");
	fw.addParam("wmode", "transparent");
	fw.addVariable("country", country);
	fw.addVariable("duration", duration);
	fw.write("fireworks");
			
	//alert("insertFW - country: " + country);
				
	playFireworksSound(country);
	return true;
}*/

function insertFW(country, duration) {
	var params = {bgcolor: "#ffffff", quality: "high", wmode: "transparent"};
	var flashvars = {country: country, duration: duration};
	var attributes = { id: "fworks", name: "fworks", allowFullScreen: "false"};
	swfobject.embedSWF("/bzJApp/views/flash/fireworks.swf", "fireworks_target", "350", "270", "8", "false", flashvars, params, attributes);
	
	logToWindow("insertFW - country: " + country);
	playFireworksSound(country);
	return true;	
}

function hideFW() {
	document.getElementById('fireworks').style.display = 'none';
} //END: hideFW


/***
 * refreshes the current product page, usually at auction close
 */
function refreshProductPage() {
	location.href = currentPage;
} //END: refreshProductPage

/**
 * display the paynow link if the winner is this user, otherwise blank
 * out the bid button.
 */
/*
function displayPayNowLink(inBidder) {
	var str = "";
	
	if (currentUser==inBidder) {
		//show the payment link
		str = str + "<td class='small' height='25'></td><td class='txt' style='white-space: nowrap;'>";
		str = str + "<a href='" + payNowLink + "'><strong>Click Here to Pay Now</strong></a></td>";
	}
	else {
		str = str + "<TD colspan='2'></td>";
	}
	
	//replace the bid button with payment info
	$("BidArea").innerHTML = str;
} //END: displayPayNowLink
*/

