var userHasBeenValidated = false;

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("You have not yet registered a credit card on file yet.  This must be done before you can bid.\n\nA new secure window to the MyProfile page will open allowing you to enter a credit card number.");
			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,width=725,height=750");
			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 trackedBoxesChecked(inForm)
{
	var fieldNameExp = new RegExp("^trackitem");
	for(var i=0; i<inForm.elements.length; i++)
	{
		var elementName = new String(inForm.elements[i].name);
		if( (inForm.elements[i].type == "checkbox") && (elementName.match(fieldNameExp) != null) )
		{ // must be a checkbox field and have a name that matches the reg expression in order to check for validity
			if(inForm.elements[i].checked == 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 and track buttons
function disableSubmit(inForm) {
	inForm.cmdSubmitBid.disabled = true;
	if(inForm.btnTrack1)
	{
		inForm.btnTrack1.disabled = true;
	}
	if(inForm.btnTrack2)
	{
		inForm.btnTrack2.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;
	}
	if(inForm.btnTrack1)
	{
		inForm.btnTrack1.disabled = false;
	}
	if(inForm.btnTrack2)
	{
		inForm.btnTrack2.disabled = false;
	}
}

// Universal form submission handler - track, bid and usercheck
function submitAll(inForm)
{
	// Bids are present - they supersede tracking
	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
	}
	// Track items
	else if(trackedBoxesChecked(inForm))
	{
		// Handles track btn press
		var myAction;
		if(inForm.trackAction.value)
		{
			myAction = inForm.trackAction.value;
		}
		else
		{
			myAction = "/common/track_results.php?return=" + encodeURIComponent(location.href);
		}
		inForm.action = myAction;
		return true;
	}
	// Handles the blank form error handling - no bids, no tracks
	else
	{
		return checkBids(inForm);
	}
 	return false;
}

function checkTrackItems(inForm)
{
	if (!trackedBoxesChecked(inForm))
	{
		alert("You must select at least one item to track.");
		return false;
	}
	else
	{
		return true;
	}
}

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 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;
		}
	}
}

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()
	{
		this.container.innerHTML = '$' + this.fElem.value + ' 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.';
}
