var userHasBeenValidated = false;

// global arrays for keeping track of price entered and priceWithBP so that we don't have to fetch priceWithBP if value has not been altered
var priceWithBP = new Array();
var priceEntered = new Array();

function userCheckBatchBid(inForm)
{
	// Check for blank login fields
	if(inForm.elements["txtEmail_Address"].value == "")
	{
		alert('Please enter your User Name.');
		inForm.elements["txtEmail_Address"].focus();
	}
	else if(inForm.elements["txtPassword"].value == "")
	{
		alert('Please enter your Password.');
		inForm.elements["txtPassword"].focus();
	}
	else
	{
		// check (via AJAX) whether the user is eligible to bid
		var rtnResult = isEligibleToBid(inForm.elements["txtEmail_Address"].value, inForm.elements["txtPassword"].value, inForm.elements["s"].value);
		if(rtnResult == '0')
		{
			alert("Bidding requires a validated credit card or establishing credit with Heritage.\n\nAfter you click OK, a new secure window to MyProfile will open, where you can qualify immediately and find instructions for qualifying without a credit card.");
			window.open('/common/myprofilecc.php', "CCenter", "status=no,copyhistory=no,menubar=no,dependent=yes,directories=no,location=no,toolbar=no,titlebar=no,scrollbars=yes,resizable=yes");
			inForm.elements["txtEmail_Address"].focus();
		}
		else if(rtnResult != 'none' && rtnResult != '1') // got an error
		{
			alert(rtnResult);
			inForm.elements["txtEmail_Address"].focus();
		}
		else
		{
			userHasBeenValidated = true;
			return true;
		}

	}
	return false;
}

function hasBids(inForm)
{
	var fieldNameExp = new RegExp("^txtBulkBid_Sale_");
	for(var i=0; i<inForm.elements.length; i++)
	{
		var elementName = new String(inForm.elements[i].name);
		if( (inForm.elements[i].type == "text") && (elementName.match(fieldNameExp) != null) )
		{ // must be a text field and have a name that matches the reg expression in order to check for validity
			if(inForm.elements[i].value != '') // something is entered
			{
				return true;
			}
		}
	}
	return false;
}

// Disable submit buttons
function disableSubmit(inForm) {
	inForm.cmdSubmitBid.disabled = true;
}

// Disable confirm button
function disableConfirm(inForm) {
	inForm.confirmBtn.disabled = true;
}

function enableAll(inForm) {
	inForm.cmdSubmitBid.disabled = false;
	if(inForm.confirmBtn)
	{
		inForm.confirmBtn.disabled = false;
	}
}

function trackCheckAll(inForm,intControl,strExp)
{
	var checkStatus = eval("inForm.trackAll" + intControl + ".checked");
	for(var i=0; i<inForm.elements.length; i++)
	{
		if( (inForm.elements[i].type == "checkbox") && (inForm.elements[i].name.search("^" + strExp) != -1) )
		{ // must be a checkbox field and have a name that matches the reg expression in order to check for validity
			inForm.elements[i].checked = checkStatus;
		}
	}
}

// Universal form submission handler - bid and usercheck
function submitAll(inForm)
{
	// Bids are present
	if(hasBids(inForm))
	{
		// now go check that the bids are valid
		if(checkBids(inForm))
		{ // bids are valid
			// User credentials has been verified
			if(userHasBeenValidated)
			{
				// Handles Confirm btn press
				// Enable login fields for parameter passing
				if(inForm.confirmBtn.hasFocus)
				{
					disableConfirm(inForm);
					setLoginFields('on', inForm);
					return true;
				}
				else
				{
					enableAll(inForm);
				}
			}
			else
			{ // user not validated
				// User has yet to be verified - check login
				if(userCheckBatchBid(inForm))
				{
					document.getElementById('cmdSubmitBid').value='Confirm Below';
					setLoginFields('off', inForm);
					disableSubmit(inForm);
					document.getElementById('batchBidConfirm').style.display='block';
					document.getElementById('confirmBtn').focus();
				}
				else
				{
					enableAll(inForm);
				}
			}
		} // end bids are valid
	}
	// Handles the blank form error handling - no bids
	else
	{
		return checkBids(inForm);
	}
 	return false;
}

function checkBids(rfrm)
{
	var blnBidEntered = false;
	var fieldNameExp = new RegExp("^txtBulkBid_Sale_");
	for(var i=0; i<rfrm.elements.length; i++)
	{
		var elementName = new String(rfrm.elements[i].name);
		if( (rfrm.elements[i].type == "text") && (elementName.match(fieldNameExp) != null) )
		{ // must be a text field and have a name that matches the reg expression in order to check for validity
			if(rfrm.elements[i].value != '') // something is entered
			{
				blnBidEntered = true;
				if(! isValidBidSyntax(rfrm.elements[i].value))
				{ // bad syntax
					alert("Your bid must be a whole dollar amount.  Do not include the dollar sign ($) or decimal points.");
					rfrm.elements[i].focus();
					return false;
				}
			}
		}
	}
	if(! blnBidEntered)
	{
		alert("You must enter at least one bid in order to Batch Bid.");
		return false;
	}
	return true;
}

function isValidBidSyntax(input)
{ // checks the syntax of the bid for validity
	var bidExp = new RegExp("^[0-9]+$");
	return (input.match(bidExp) != null);
}

function openMultiBidWindow()
{
	window.open('/common/popup.php?popup=multibidding', "", "status=no,copyhistory=no,menubar=no,dependent=yes,directories=no,location=no,toolbar=no,titlebar=no,scrollbars=yes,width=400,height=300");
}

function setLoginFields(flag, inForm)
{
	switch(flag)
	{
		case 'on':
			inForm.elements["txtEmail_Address"].disabled = false;
			inForm.elements["txtPassword"].disabled = false;
			break;
		case 'off':
			inForm.elements["txtEmail_Address"].disabled = true;
			inForm.elements["txtPassword"].disabled = true;
			break;
	}
}

function confirmBatchBid(btn)
{
	var inForm = btn.form;
	disableConfirm(inForm);
	setLoginFields('on', inForm);
}

function cancelBatchBid( inObj )
{
	// Find form given the link
	var inForm = inObj.f;
	// Use a new popup to verify if user really wants to cancel
	var confirmCancel = confirm("All bid information will be discarded and cannot be retrieved. Click \"OK\" to discard your bid information.");
	if(confirmCancel == true)
	{
		userHasBeenValidated = false;
		inForm.elements['cmdSubmitBid'].value = 'Submit Bids';
		document.getElementById('batchBidConfirm').style.display='none';
		setLoginFields('on', inForm);
		resetBatchBids( inForm );
	 	enableAll(inForm);
	}
}

function initBatchBids( f )
{
	var i = 0, elem;
	while ( elem = f.elements[i++] )
	{
		if ( /^txtBulkBid.*\d$/.test( elem.name ) )
		{
			// closure-safe reference
			updateBidConfirm( elem.form.elements[elem.name] );
		}
	}
}

function resetBatchBids( f )
{
	f.reset();
	var list = document.getElementById( 'batchBidList' );
	for ( var i = 0; i < list.childNodes.length; i++ )
	{
		list.childNodes[i].style.display = 'none';
	}
}

function updateBidConfirm( trigger )
{
	var f = trigger.form;
	var i = 0;

	var hdnElem = f.elements[trigger.name+'_NextAmount'];
	var saleNo	= trigger.name.match( /Sale_(\d+)/ )[1];
	var lotNo	= trigger.name.match( /Lot_(\d+)/ )[1];


	if ( typeof trigger.confirmObj == 'undefined' || trigger.confirmObj == null )
	{
		trigger.confirmObj = new confirmElement( trigger, hdnElem, saleNo, lotNo );
	}
	trigger.confirmObj.update();
}

var confirmElement = function( formElem, minBidElem, saleNo, lotNo )
{
	var div = document.createElement( 'div' );
	this.container = document.getElementById( 'batchBidList' ).appendChild( div );
	this.fElem = formElem;
	this.mElem = minBidElem;
	this.saleNo = saleNo;
	this.lotNo = lotNo;

	this.update = function()
	{
		var trimmedValue = this.fElem.value.replace( /^\s+|\s+$/, '' );
		var newValue = trimmedValue || 0;
		if ( /^[0-9\.]+$/.test( trimmedValue ) )
		{
			/*
			Commented code is for another ticket, #34707
			if ( trimmedValue != parseInt( trimmedValue, 10 ) )
			{
				if ( confirm( 'Bids must be in whole dollar amounts (no cents).\n\nClick [OK] to drop cents from this bid and proceed\nClick [Cancel] to remit the bid.' ) )
				{
					this.fElem.value = parseInt( trimmedValue, 10 );
				} else {
					this.fElem.value = '';
				}
				return;
			}
			else*/ if ( newValue < parseInt( minBidElem.value, 10 ) && newValue != 0 )
			{
				alert( 'The bid you entered is lower than the minimum bid!\n Please enter a dollar value of at least the minimum bid of $' + this.mElem.value );
				this.fElem.value = '';
				this.fElem.focus();
				this.fElem.select();
				this.updateDisplay();
			}
		}
		else if (!( '0' == trimmedValue || '' == trimmedValue ))
		{
			alert( 'All bids must be in whole dollar amounts.\nPlease do not use commas or decimal places.' );
			this.fElem.value = '';
			this.fElem.focus();
			this.fElem.select();
			this.updateDisplay();
		}
		if ( newValue == 0 || newValue == '' )
		{
			this.container.style.display = 'none';
		} else {
			this.container.style.display = 'block';
			this.updateDisplay();
		}
	}

	this.updateDisplay = function()
	{
		/** priceEntered is a global array in which preious price entered is stored.
		  * Used so that we don't make the ajax call to get amountWithBP
		 */
		if (priceEntered[this.saleNo + '_' + this.lotNo] != this.fElem.value)
		{

			priceEntered[this.saleNo + '_' + this.lotNo] = 	this.fElem.value;

			$.ajax({
				type: 'POST',
				url: '/c/webservices/get-price-with-bp.zx',
				async : false,
				data: {
					saleNo	:	this.saleNo,
					lotNo	:	this.lotNo,
					amount	:	this.fElem.value
				},
				dataType: 'xml',
				success: function( responseData )
				{
					var amountWithBP, saleNo, lotNo;

					amountWithBP 	= $(responseData).find('amountWithBP').text();
					saleNo 			= $(responseData).find('saleNo').text();
					lotNo 			= $(responseData).find('lotNo').text();

					// priceWithBP is a global array to store the amountWithBP
					priceWithBP[saleNo + '_' + lotNo] = amountWithBP;
				}
			});
		}

		this.container.innerHTML = '$' + this.fElem.value + ' ($' + priceWithBP[this.saleNo + '_' + this.lotNo] 
                    + ' w/BP <img class="explanation tooltipAnchor jqtBuyersPremium" src="/c/s/i/ui/bid-box/btn-explain.gif" /> ) on Auction #' + this.saleNo + ', Lot #' + this.lotNo;
	}
}

/////////////////////////// AJAX stuff below  //////////////////////////////////

document.writeln('<scr' + 'ipt language="JavaScript" src="/common/includes/ajax.js"></scr' + 'ipt>');
document.writeln('<scr' + 'ipt language="JavaScript" src="/common/includes/md5.js"></scr' + 'ipt>');
var myResult; // this is the result from the xml response
var errMsg; // the resulting error message, if there is one

function isEligibleToBid(email, pass, seed)
{ // checks to see if the user is eligible to bid

	myResult = errMsg = '';
	createRequestObject();
	sendRequest('/common/xml/eligibleToBid.php', 'email=' + encodeURIComponent(email) + '&pass=' + encodeURIComponent(hex_md5(hex_md5(pass.toLowerCase()) + seed)), 'POST', false);

	if(errMsg != 'none') // got an error with username/password
		return errMsg;
	else // got a result
		return myResult;

}

function AJAXsuccess()
{
	var response  = http_request.responseXML.documentElement;
	myResult    = response.getElementsByTagName('result')[0].firstChild.data;
	errMsg = response.getElementsByTagName('errMsg')[0].firstChild.data; // must have some value or craps out in IE
}

function AJAXfailure()
{
	errMsg = 'There was an error trying to complete your request.  Please try again later.';
}

