/***
 * 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";

/**
 * 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 = "\u0627\u0644\u0625\u063a\u0644\u0627\u0642 \u0639\u0644\u0649:";
		}
		else if ((bidder==null || bidder=="") || (auctType=="R" && auctResMet=="N")) {
			tlStr = "\u0623\u063a\u0644\u0642";
		} //no winer
		else {
			tlStr = "\u0645\u0628\u0627\u0639!";
		}
	} //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 +")'>\u0627\u0644\u0633\u0639\u0631 \u0628\u0639\u0645\u0644\u0627\u062a \u0623\u062e\u0631\u0649</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;'>" + bidder +"</span> ";
		}	
		else //if (bidder!="") 
		{
			rc = rc + 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;
	
	//update save percentage div
	if ($(saveElement) && $(priceElement)){
		var comparePrice = $(priceElement).firstChild.nodeValue;
		var savingMoney = comparePrice - lo.currentBid;
		savingMoney = Math.round(savingMoney);
		//var savingPercentage = ((comparePrice - lo.currentBid)/comparePrice)*100;
		//savingPercentage = Math.round(savingPercentage);
		//nf.setNumber(savingPercentage/100);
		nf.setNumber(savingMoney);
		//$(saveElement).firstChild.nodeValue = nf.toPercentage();
		$(saveElement).firstChild.nodeValue = nf.toFormatted();
	}
	
	// hide until feature is needed for Search.vm
	//var fivepaysElement = "five_" + lo.listingID;
	//if($(fivepaysElement) && lo.currentBid > 250){
	//	var fivePayments = lo.currentBid / 5;
	//	fivePayments = Math.ceil(fivePayments);
	//	nf.setNumber(fivePayments);
	//	$(fivepaysElement).firstChild.nodeValue = '5 payments of ' + nf.toFormatted();
	//}
	
	//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).innerHTML = 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).value = inputNf.toFormatted();		
	} //END: if not locked
	
	logToWindow( "\u0639\u0631\u0636 \u0627\u0644\u0633\u0639\u0631 \u0627\u0644\u062d\u0627\u0644\u064a: " +  lo.currentBid + "\u0639\u0631\u0636 \u0627\u0644\u0633\u0639\u0631 \u0627\u0644\u0633\u0627\u0628\u0642: " + lo.prevBid +
 	  "\u0627\u0644\u0641\u0627\u0626\u0632 \u0627\u0644\u062d\u0627\u0644\u064a:" + lo.currentWinner + " \u0627\u0633\u0645 \u0627\u0644\u0645\u0632\u0627\u064a\u062f \u0627\u0644\u0623\u062e\u064a\u0631: " + lo.latestBidderName +
 	  " \u0639\u0631\u0636 \u0633\u0639\u0631 \u0627\u0644\u0645\u0632\u0627\u064a\u062f \u0627\u0644\u0623\u062e\u064a\u0631: "+ 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).style.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).innerHTML;			
			if (userproxy != null){
				userproxy = userproxy.trim();
			}
			if (userproxy !=""){		
				logToWindow("\u0627\u0644\u0628\u0631\u0648\u0643\u0633\u064a \u0627\u0644\u062e\u0627\u0635 \u0628\u0627\u0644\u0645\u0633\u062a\u062e\u062f\u0645: " + userproxy);
				userproxy = userproxy.substring(1,userproxy.length);
				userproxy = userproxy.replace(',','');
				logToWindow("\u0627\u0644\u0628\u0631\u0648\u0643\u0633\u064a \u0627\u0644\u062e\u0627\u0635 \u0628\u0627\u0644\u0645\u0633\u062a\u062e\u062f\u0645 \u062f\u0648\u0646 \u0639\u0644\u0627\u0645\u0629 \u0627\u0644\u062f\u0648\u0644\u0627\u0631 $: " + 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).style.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).style.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).style.backgroundColor = "#ffa";

 	$(bidderElementName).innerHTML = latestBidderName ;
 	nf.setNumber(latestBid);
 	
 	rc = "<b>" + nf.toFormatted(); 	
 	rc = rc + " <a style='font-size: 10px;' href='javascript:showConvertedCurrency("+ listingId + "," + latestBid +")'>\u0627\u0644\u0633\u0639\u0631 \u0628\u0639\u0645\u0644\u0627\u062a \u0623\u062e\u0631\u0649</a>";
 	rc = rc + "</b>";
 	
 	$(amountElementName).innerHTML = 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).style.backgroundColor = "lightgreen";
 	
 	$(bidderElementName).innerHTML = currWinner ;
 	nf.setNumber(currentBid);
 	rc = "<b>" + nf.toFormatted(); 	
 	rc = rc + " <a style='font-size: 10px;' href='javascript:showConvertedCurrency("+ listingId + "," + currentBid +")'>\u0627\u0644\u0633\u0639\u0631 \u0628\u0639\u0645\u0644\u0627\u062a \u0623\u062e\u0631\u0649</a>";
 	rc = rc + "</b>";
 	
 	$(amountElementName).innerHTML = 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).style.backgroundColor = "white";
 } //END: resetBackground
 
 function updateLBStatusView(statusStr, errorText) {
 	logToWindow("updateLBStatusView called with status:" + statusStr + "and error text:" + errorText);
	
	if (statusStr==STATUS_STARTED) {
    	$('LBStatus').innerHTML = "\u062c\u0627\u0631\u064a <A HREF='javascript:LBClient.stop(NO_ERROR)' style='color: #fff;'>\u064a\u0639\u0645\u0644</A>";
	} //streaming on
	else {
		var appendError = "";
		if (errorText!=NO_ERROR) {
			appendError = " (\u062e\u0637\u0623 \u0641\u064a \u0627\u0644\u0627\u062a\u0635\u0627\u0644)";
		}
		$('LBStatus').innerHTML = "\u062c\u0627\u0631\u064a <A HREF='javascript:LBClient.start()' style='color: #fff;'>\u062e\u0627\u0631\u062c</A>" + appendError;
	}
 } //END: updateLBStatusView
 
 
 