/***
 * used specifcally with the ViewSearch.action URL and expects
 * show_$listno to be available in the DOM
 * 
 * @param {listingObject} lo
 * 
 * listing object from LiveBidModule.js is the input param.
 * 
 */

//number formater taken from:
//http://www.mredkj.com/javascript/nf_api.html
var nf = new NumberFormat("0"); //defualt number formatter

//default values for currency
nf.setCurrency(true);
nf.setCommas(true);
nf.setCurrencyValue("$");

//number format for bid input field, no $ sign required, no comma required
var inputNf = new NumberFormat("0");
inputNf.setCommas(false);

//specify when to start flashing the time left field
var FLASH_LESS_THEN_SECONDS = 10;

var SHOW_RUNNING_BID_HISTORY = "N";
var SHOW_USER_MAX_BID = "N";

function maskUsername(userNameToMask) {
	// check if userName contains @
	var pos = userNameToMask.indexOf("@");
	if( pos>=0 && 
			( window.allowUsernameMasking === undefined || 
				( window.allowUsernameMasking !== undefined && allowUsernameMasking == "Y" ) ) )
	{
		userNameToMask = userNameToMask.substr(0,pos);
		if( userNameToMask.length > 3)
		{
			userNameToMask = ".." + userNameToMask.substr(2,userNameToMask.length-3);
			userNameToMask = userNameToMask + "...";
		}
		else
		{
			userNameToMask = "...";
		}		
	}
	return userNameToMask;
}


/**
 * utility function to format numeric input fields
 * @param {String} numStr
 */
function formatInputFieldAmount(numStr) {
	inputNf.setNumber(numStr);
	return inputNf.toFormatted();
} //END: formatInputFieldAmount

function formatLBHTMLOutput(tlDays, tlHours, tlMinutes, tlSeconds ,amt, bidder, lid, listingStatus, auctType, auctResMet,latestBidderName) {

	//rc will store the resulting HTML
	var rc = "";
	
	//put together the final time string
	var tlStr = "";
	if (tlDays=="0" && tlHours=="0" && tlMinutes=="0" && tlSeconds=="0") {
		if (listingStatus==null || listingStatus!="Y") {
			tlStr = "Closing...";
		}
		else if ((bidder==null || bidder=="") || (auctType=="R" && auctResMet=="N")) {
			tlStr = "Closed";
		} //no winer
		else {
			tlStr = "SOLD!";
		}
	} //No time left in the auction
	else if (tlDays!="0") {
		tlStr = tlStr + tlDays + "D:" + padZero(tlHours) + ":" + padZero(tlMinutes) + ":" + padZero(tlSeconds);
	}
	else {
		//no days left
		if (tlHours!="0") {
			tlStr = tlStr + padZero(tlHours) + ":" + padZero(tlMinutes) + ":" + padZero(tlSeconds);
		} 
		else {
			//no days, no hours left
			tlStr = tlStr + padZero(tlMinutes) + ":" + padZero(tlSeconds);
		} //END: no days, no hours left
	} //END: no days left
	
	//format the amount properly
	nf.setNumber(amt);
	
	//build the div element for the current bid
	rc = "<div style='white-space: nowrap; position: relative; right: -10px;' class='money' id='bidamt_"+lid+"'>";	
	rc = rc + nf.toFormatted();	
	
	//currency conversion link
	//	rc = rc + "<img style='position: absolute; right: -10px; top: -10px; cursor: pointer;' src='http://llpromo.bidz.com/img/currency_btn.gif' onclick='showConvertedCurrency("+ lid + "," + amt +")' />"; 	
	rc = rc + " <a style='font-size: 10px;' href='javascript:showConvertedCurrency("+ lid + "," + amt +")'>(Convert)</a>";
	//rc = rc + "<div style='display: none; position: absolute; top: -15px; right: 30px; border: solid 1px #c5effd; background-color: #f5fcff; font-size: 10px; z-index: 200;' id='currencyBox_" + lid + "'><div style='text-align: right; margin: 0.4em; z-index: 201;' id ='currency_" + lid + "'></div></div>";
	rc = rc + "</div>";
	
	
	//start the bidder name div
	rc = rc + "<div class='curwinner' id='curwinner_"+lid+"'>";
	
	if (bidder!=null && bidder!=""){
		if( bidder==currentUser) {
		rc = rc + "<span style='color: #0c3;'>" + maskUsername(bidder) +"</span> ";
		}	
		else //if (bidder!="") 
		{
			//mask username
			rc = rc + maskUsername(bidder);
		}	
		//else { rc = rc + "<br/>"; }
	}
	else {
		
		if (latestBidderName!=null && latestBidderName !="") { 
			logToWindow("in condition:  If the bidding is completed with no winner : latest bidder exists but winner is null");
			rc = rc + "No Winner" +"<br />";
		}
		else
		{
			rc = rc + "<br/>";
		}
	}
	rc = rc + "</div>";
	
	
	//start the time left div
	rc = rc + "<div class='time' id='time_"+lid+"'>";
	rc = rc + tlStr;
	rc = rc + "</div>";
	
	return rc;
} //END: formatLBHTMLOutput

//pre-pend a zero if the length of the string is less then 2
function padZero(s) {
	if (s.length<2){
		return "0" + s;
	}
	
	return s;
} //END: padZero

 function updateShowcaseView(lo) {
 	//logToWindow("updateShowcaseView Called: " + lo.listingID);
	
	var elementName = "#show_" + lo.listingID;
	//div where we display Save percentage
	var saveElement = "#sv_" + lo.listingID;
	var priceElement = "#pr_" + lo.listingID;
	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);
	}
	
	//split time left into an array from comma separated
	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];
	
	var finalHTML = formatLBHTMLOutput(tlDays, tlHours, tlMinutes, tlSeconds, lo.currentBid, lo.currentWinner, lo.listingID, lo.closedStatus, lo.auctionType, lo.reserveStatus, lo.latestBidderName);
	
	$(elementName).html(finalHTML);
	
	//logToWindow("value of div:" + $(elementName).innerHTML);
	
	var inputName = "input_" + lo.listingID;
	
	if (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
	
	logToWindow( "currentBid : " +  lo.currentBid + "prevBid : " + lo.prevBid +
 	  "currWinner :" + lo.currentWinner + " latestBidder name : " + lo.latestBidderName +
 	  " latest bidder bid : "+ lo.latestBidderBid);
		
	//check if the previous and current bids are different
	if (lo.prevBid!=lo.currentBid) {
		//we have to signal a new bid to the user
		
		var bidderElementName = "#curwinner_" + lo.listingID;
		var amountElementName = "#bidamt_" + lo.listingID;
		
		
		if (lo.latestBidderName!=null && lo.latestBidderName!="" && lo.latestBidderName != lo.currentWinner ) {
			showRunnerUpAndThenWinner(bidderElementName, amountElementName,elementName, lo.latestBidderName, lo.currentWinner, lo.currentBid, lo.latestBidderBid, lo.listingID);
		}
		else {
			$(elementName).css("backgroundColor", "lightgreen");
			setTimeout("resetBackground('"+elementName+"')", 700);
		}
				
		// update running bid history with new bid
		if(SHOW_RUNNING_BID_HISTORY =="Y"){
			var isOutBidSame = false;
			if (lo.latestBidderName != lo.currentWinner){
				//add the latest bidder info to history even though he is not winner
				addToRunningHistory(lo.listingID, lo.latestBidderName, lo.latestBidderBid, isOutBidSame);
				//current bid is current winning bid and latest bid is a bid placed recently
				if (lo.currentBid == lo.latestBidderBid){ 
					isOutBidSame =true;
				}
				//add the actual winner info to running history
				addToRunningHistory(lo.listingID, lo.currentWinner, lo.currentBid, isOutBidSame);
			}
			else 
			{
				//if latest bidder is a winner
				addToRunningHistory(lo.listingID, lo.currentWinner, lo.currentBid, isOutBidSame);
			}
		}//end: running history update 
		
		if (SHOW_USER_MAX_BID =="Y"){	
			var valueElementName = '#userMaxBid_'+ lo.listingID;
			var userproxy = $(valueElementName).html();			
			if (userproxy != null){
				userproxy = userproxy.trim();
			}
			if (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){
					disableUserMaxBid(lo.listingID);
				}
			}
		}//SHOW_USER_MAX_BID
		
		//update preferred currency values
		var currencyDivElementName = "#currencyBox_"+lo.listingID;
		if ($(currencyDivElementName).css("display") == 'block'){
			updatePreferredCurrencyValues("#currency_"+lo.listingID,lo.currentBid);
		}
				
	}
	
	//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 = "#time_" + lo.listingID;
			$(timeLeftName).css("backgroundColor", "orange"); //orange
			setTimeout("resetBackground('"+timeLeftName+"')", 700);
		} //END: Flash time left
	} //END: only seconds left
 } //END: updateShowcaseView
 
 function showRunnerUpAndThenWinner(bidderElementName, amountElementName, elementName, latestBidderName, currWinner, currentBid, latestBid, listingId) {
 	
 	var rc = "";
 	//let's show the runner up as yellow 	
 	$(elementName).css("backgroundColor", "#ffa");

 	$(bidderElementName).html(latestBidderName);
 	nf.setNumber(latestBid);
 	
 	rc = "<b>" + nf.toFormatted(); 	
 	rc = rc + " <a style='font-size: 10px;' href='javascript:showConvertedCurrency("+ listingId + "," + latestBid +")'>(Convert)</a>";
 	rc = rc + "</b>";
 	
 	$(amountElementName).html(rc) ;
 	//now that we are yellow, let's wait only a 1 second, then show the right person in green
 	setTimeout("showWinnerAfterRunnerUp('"        + bidderElementName
 	                                      + "','" + amountElementName 
 	                                      + "','" + elementName 
 	                                      + "','" + currWinner 
 	                                      + "','" + currentBid 
 	                                      + "','" + listingId+ "')", 1000);
 } //END: showRunnerUpAndThenWinner
 
 function showWinnerAfterRunnerUp(bidderElementName, amountElementName,elementName, currWinner, currentBid, listingId) {
 	
 	var rc = "";
 	$(elementName).css("backgroundColor", "lightgreen");
 	
 	$(bidderElementName).html(currWinner) ;
 	nf.setNumber(currentBid);
 	rc = "<b>" + nf.toFormatted(); 	
 	rc = rc + " <a style='font-size: 10px;' href='javascript:showConvertedCurrency("+ listingId + "," + currentBid +")'>(Convert)</a>";
 	rc = rc + "</b>";
 	
 	$(amountElementName).html(rc) ;
    
    setTimeout("resetBackground('"+elementName+"')", 700);
    
    
 } //END: showWinnerAfterRunnerUp 

/***
 * Lock the input field by setting a global var.
 * Only 1 input field can have focus on the screen any
 * a given time so an array is not required.
 * 
 * @param {String} lid
 */

var lockedInputField = null;

function lockInputField (elemId) {
	lockedInputField = elemId;
} //END: lockInputField

function unlockInputField (elemId) {
	lockedInputField = null;
} //END: unlockInputField
 
 function resetBackground(elem) {
 	$(elem).css("backgroundColor", "white");
 } //END: resetBackground
 
 function updateLBStatusView(statusStr, errorText) {
 	logToWindow("updateLBStatusView called with status:" + statusStr + "and error text:" + errorText);
	
	if (statusStr==STATUS_STARTED) {
    	$('#LBStatus').html("Streaming <A HREF='javascript:LBClient.stop(NO_ERROR)' style='color: #fff;'>ON</A>");
	} //streaming on
	else {
		var appendError = "";
		if (errorText!=NO_ERROR) {
			appendError = " (Communication Error)";
		}
		$('#LBStatus').html("Streaming <A HREF='javascript:LBClient.start()' style='color: #fff;'>OFF</A>" + appendError);
	}
 } //END: updateLBStatusView
 
 
 
