var oFieldTypes;
var oOptionList;
var arFieldList;
var bAddFieldModeOn = false;
var iAddFieldRowCount = 0;
var iAddFieldUniqueIndex = 0;
var giMenuVisible = false;
var SelectedRowId = null;
var AboveOrBelow = false; // above=true, below=false
var OriginalRowClass = '';
var SelectedRowGIID = null;
var DeleteIconPath;
var FieldNameText;
var confirmUnsaved;
var confirmText;
var donationDriverAmount = 0;
var hasDesignations = false;

function TableRow_HoverIn(prmTableRow, prmInstanceId)
{
	if (!giMenuVisible)
	{
		//OriginalRowClass = prmTableRow.className;
		prmTableRow.className = 'hovered';
		//show grouping instance toolbar
		var tb = document.getElementById('spGITB_' + prmInstanceId);
		tb.style.visibility = 'visible';
		SelectedRowGIID = prmInstanceId;
	}
} // TableRow_HoverIn


function TableRow_HoverOut(prmTableRow, prmInstanceId)
{
	if (!giMenuVisible)
	{
		//prmTableRow.className = OriginalRowClass;
		prmTableRow.className = '';
		//hide grouping instance toolbar
		var tb = document.getElementById('spGITB_' + prmInstanceId);
		tb.style.visibility = 'hidden';
		SelectedRowGIID = null;
	}
} // TableRow_HoverOut


function UpdateLabelSuccess(sPrmResponse, oEventArgs) 
{
	//alert("response=" + sPrmResponse);
	//giLoading_ShowHide(false);
	if (sPrmResponse.trim().toLowerCase() != "true")
	{
		alert("Error saving changes (" + sPrmResponse + ")!");
		imgLoading_ShowHide(false, oEventArgs.ID, oEventArgs.modifier); //hide loading
	}
	else
	{
		imgSuccess_ShowHide(true, oEventArgs.ID, oEventArgs.modifier); //show success
		setTimeout(function () { imgSuccess_ShowHide(false, oEventArgs.ID, oEventArgs.modifier) }, idbmsDelay); //delay hide success
	}
} // UpdateLabelSuccess


function UpdateLabel(iPrmGroupingInstanceId, sPrmLabel) 
{
	//giLoading_ShowHide(true);
	imgLoading_ShowHide(true, iPrmGroupingInstanceId);
	
	//create dummy object to pass to ajax runner
	var objDummy = {};
	objDummy.ID = iPrmGroupingInstanceId;

	var ar = new AjaxRunner();
	ar.Url = "/idbms/ui/ajax/vg_handler.aspx";
	// 11/06/2007 - JM - (see #1101) Added gfid so we only update the last updated date for the form we are on.
	ar.Querystring = GroupQueryString + "&giid=" + iPrmGroupingInstanceId + "&gfid=" + CONST_CURRENTGFID; // GroupQueryString is defined by vg2
	ar.AddFormValue("cmd", "updatelabel");
	ar.AddFormValue("label", sPrmLabel);
	ar.OnSuccess = UpdateLabelSuccess;
	ar.Execute(null, objDummy);
} // UpdateLabel


function UpdateDesc(iPrmGroupingConfigId, sPrmDescription) 
{
	//giLoading_ShowHide(true);
	imgLoading_ShowHide(true, iPrmGroupingConfigId, 'desc_');
	
	//create dummy object to pass to ajax runner
	var objDummy = {};
	objDummy.ID = iPrmGroupingConfigId;
	objDummy.modifier = 'desc_';

	var ar = new AjaxRunner();
	ar.Url = "/idbms/ui/ajax/vg_handler.aspx";
	ar.Querystring = GroupQueryString + "&gcid=" + iPrmGroupingConfigId; // GroupQueryString is defined by vg2
	ar.AddFormValue("cmd", "updatedesc");
	ar.AddFormValue("description", sPrmDescription);
	ar.OnSuccess = UpdateLabelSuccess;
	ar.Execute(null, objDummy);
} // UpdateDesc


/*
function giLoading_ShowHide(bShow)
{
	var load = document.getElementById('giLoading');
	if (bShow)
		load.style.display = '';
	else
		load.style.display = 'none';
} //giLoading_ShowHide
*/

function imgLoading_ShowHide(bShow, iPrmId, sPrmModifier)
{
	//if modifier is passed in as null, make it blank
	if (!sPrmModifier) { sPrmModifier = ''; }
	var imgLoading = document.getElementById('imgLoading_' + sPrmModifier + iPrmId);
	var imgSuccess = document.getElementById('imgSuccess_' + sPrmModifier + iPrmId);
	if (imgLoading && imgSuccess)
	{
		if (bShow) //always swap with success on show
		{
			imgLoading.style.display = '';
			imgSuccess.style.display = 'none';
		}
		else //always hide both on hide
		{
			imgLoading.style.display = 'none';
			imgSuccess.style.display = 'none';
		}
	} //null check
} //imgLoading_ShowHide

function imgSuccess_ShowHide(bShow, iPrmId, sPrmModifier)
{
	//if modifier is passed in as null, make it blank
	if (!sPrmModifier) { sPrmModifier = ''; }
	var imgLoading = document.getElementById('imgLoading_' + sPrmModifier + iPrmId);
	var imgSuccess = document.getElementById('imgSuccess_' + sPrmModifier + iPrmId);
	if (imgLoading && imgSuccess)
	{
		if (bShow) //always swap with loading on show
		{
			imgLoading.style.display = 'none';
			imgSuccess.style.display = '';
		}
		else //always hide both on hide
		{
			imgLoading.style.display = 'none';
			imgSuccess.style.display = 'none';
		}
	} //null check
} //imgSuccess_ShowHide

function btnDeleteInstance_Click(prmGroupingInstanceId, prmModuleId)
{
	if (confirm("Are you sure?"))
	{
		imgLoading_ShowHide(true, prmGroupingInstanceId); //show loading
		var ar = new AjaxRunner();
		ar.Url = "/idbms/ui/ajax/vg_handler.aspx";
		ar.Querystring = GroupQueryString + "&giid=" + prmGroupingInstanceId + "&miid=" + prmModuleId + "&gfid=" + CONST_CURRENTGFID; // GroupQueryString is defined in vg2
		//alert(ar.Querystring + " " + );
		ar.AddFormValue("cmd", "deletefield");
		ar.OnSuccess = DeleteInstanceSuccess;
		var oDummy = {};
		oDummy.ID = prmGroupingInstanceId;
		ar.Execute(null, oDummy);
	}
} //btnDeleteInstance_Click

function DeleteInstanceSuccess(response, oPrmEventArgs)
{
	var giid = oPrmEventArgs.ID;
	if (response == 'true')
	{
		//show success
		imgSuccess_ShowHide(true,giid);
		//reload ajax
		//setTimeout(function () { RadAjaxPanel_Reload(CONST_CURRENTGFID); }, idbmsDelay);
		setTimeout(function () { window.location = GetCurrentUrlWithoutGFID() + '&gfid=' + CONST_CURRENTGFID; }, idbmsDelay);
	}
	else
	{
		//hide loading
		imgLoading_ShowHide(false, giid);
		//error - todo no alert?
		alert(response);
	}
} //DeleteInstanceSuccess

function InstanceBeforeDock(prmDrag, prmDock, prmOver)
{
	var giidover = -1;
	var gfid = prmDrag.GetAttribute('GFID');
	var giid = prmDrag.GetAttribute('GIID');
	if ((gfid > 0) && (giid > 0))
	{
		//get order id
		if (prmOver != null)
		{
			giidover = prmOver.GetAttribute('GIID');
		}
		
		//don't sort if they are trying to put it in the same place
		if (giid != giidover)
		{
			//show loading (this function is in view_grouping2.js)
			imgLoading_ShowHide(true, giid);

			//ajax
			var ar = new AjaxRunner();
			ar.Url = '/idbms/ui/ajax/vg_handler.aspx';
			ar.Querystring = GroupQueryString + '&gfid=' + gfid + '&cmd=sortfield&giid=' + giid + '&giidover=' + giidover;
			ar.OnSuccess = InstanceSortFinish;

			//create dummy object to pass to execute()
			var EventArgs = {"ID":giid}; 
			ar.Execute(null, EventArgs);
		} // sort is different
	} // valid gfid and giid
} //InstanceBeforeDock

function InstanceSortFinish(response, EventArgs)
{
	var giid = EventArgs.ID;
	if (response == 'true')
	{
		//hide loading, show success
		imgSuccess_ShowHide(true, giid);
		//delay hide success
		setTimeout(function () { imgSuccess_ShowHide(false, giid);  window.location = window.location; }, idbmsDelay);
	}
	else
	{
		alert(response); //todo?
	}
} //InstanceSortFinish


function AddField(gfid, tblId, oPanel)
{
	//check gfid first
	if (bAddFieldModeOn && gfid != iCurrentGFID && iCurrentGFID > 0)
	{
		//cancel add in progress
		if (confirm(confirmUnsaved))//'This will remove unsaved changes. Are you sure?'))
		{
			CancelAddFields(true, oPanel);
		}
		else { return; }
	}
	iCurrentGFID = gfid;
	var tbl = document.getElementById(tblId);
	if (tbl)
	{
		//alert("tblid=" + tblId + ", tbl=" + tbl + ", rows=" + tbl.rows.length);
		//insert row at the bottom
		var newRow = tbl.insertRow(tbl.rows.length);
		newRow.id = 'gr_' + gfid + '_' + iAddFieldUniqueIndex;
		var newCell0 = newRow.insertCell(0);
		newCell0.setAttribute('valign', 'bottom');
		//add cancel img
		var img = document.createElement('img');
		img.src = DeleteIconPath;//'/images/Icons/v2/delete.gif';
		img.style.cursor = 'pointer';
		img.onclick = CreateCancelAddFieldDelegate(gfid,tblId,iAddFieldUniqueIndex,oPanel);
		img.setAttribute('align', 'texttop');
		newCell0.appendChild(img);
		newCell0.appendChild(document.createTextNode("\u00a0")); //space
		//text box
		var newInput = document.createElement('input');
		newInput.id = 'gn_' + gfid + '_' + iAddFieldUniqueIndex;
		newInput.type = 'text';
		newInput.value = FieldNameText; //'Field Name';
		newInput.setAttribute('maxLength', 128); // 03/06/2007 - JM - set max length per ticket number #267
		//focus
		setTimeout(function () { newInput.select(); newInput.focus(); },10);
		newCell0.appendChild(newInput);
		//cell 2
		var newCell1 = newRow.insertCell(1);
		newCell1.setAttribute('nowrap', 'nowrap');
		newCell1.setAttribute('valign', 'bottom');
		//dropdown
		var dd = document.createElement('select');
		dd.id = 'gt_' + gfid + '_' + iAddFieldUniqueIndex;
		if (!oFieldTypes) { oFieldTypes = GetFieldTypes(); }
		var tehLoopIndex = 0;
		var tehIndexToSelect = 0;
		for (var i in oFieldTypes)
		{
			var op = new Option(oFieldTypes[i], i); //field_type_id is the key for the array
			if (i == 1) { op.selected = true; tehIndexToSelect = tehLoopIndex; } //auto-select textbox
			dd.options[tehLoopIndex++] = op;
		}
		//to appease IE6
		dd.selectedIndex = tehIndexToSelect;
		newCell1.appendChild(dd);
		newCell1.appendChild(document.createTextNode("\u00a0")); //space
		//required checkbox
		var cb = document.createElement('input');
		cb.style.margin = '0px';
		cb.id = 'cb_' + gfid + '_' + iAddFieldUniqueIndex;
		cb.type = 'checkbox';
		var label = document.createElement('label');
		label.setAttribute('for', cb.id);
		label.innerHTML = ' Required?';
		newCell1.appendChild(cb);
		newCell1.appendChild(label);
		//add field mode - todo - disable all other toolbars' add field buttons on the page
		if (!bAddFieldModeOn) { AddFieldModeOnOff(true, gfid); }
		//add field to list
		AddFieldToList(iAddFieldUniqueIndex, gfid, tblId);
		
		
		//lastly, increment counts
		iAddFieldRowCount++;
		iAddFieldUniqueIndex++;
	} //null check
	//Hide ButtonSave and Next when adding fields
	if ($('divButtons') != null) $('divButtons').style.display = 'none';
} //AddField


function CreateCancelAddFieldDelegate(gfid, tblId, tblRowIndex, oPanel)
{
	return function () { CancelAddField(gfid,tblId,tblRowIndex, oPanel); }; 
} //CreateCancelAddFieldDelegate


function CancelAddField(gfid, tblId, tblRowIndex, oPanel)
{
	var maintbl = document.getElementById(tblId);
	if (maintbl)
	{
		//loop through rows to find the one with the right id
		var rowindex = -1;
		for (var i=0; i<maintbl.rows.length; i++)
		{
			if (maintbl.rows[i].id == 'gr_' + gfid + '_' + tblRowIndex)
			{
				rowindex = i;
			}
		}
		//delete
		if (rowindex > -1)
		{
			maintbl.deleteRow(rowindex);
			iAddFieldRowCount--;
			//remove from list
			RemoveFieldFromList(tblRowIndex);
		}
		//if no more, hide controls
		if (iAddFieldRowCount == 0)
		{
			AddFieldModeOnOff(false, gfid);
			ShowHideGroupingError(false, gfid, null, oPanel);
		}
	} //null check
	//Hide ButtonSave and Next when adding fields
	if ($('divButtons') != null) $('divButtons').style.display = '';
} //CancelAddField


function AddFieldModeOnOff(bOn, gfid)
{
	bAddFieldModeOn = bOn;
	//show save/cancel buttons
	ShowHideAddFieldModeControls(bOn, gfid);
} //AddFieldMode


function ShowHideAddFieldModeControls(bShow, gfid)
{
	var span = document.getElementById('spGroupingToolbarControls_' + gfid);
	if (span)
	{
		if (bShow) { span.style.display = ''; }
		else { span.style.display = 'none'; }
	}
} //ShowHideAddFieldModeControls


// JDB 6/12/2008 Single Table - adding control id to the url
function SaveAddFields(gfid, gid, oPanel, cid, prmModuleId) // quick add fields
{
	//hide error (if it's there)
	ShowHideGroupingError(false, gfid, null, oPanel);
	//validate
	var xml = '<root>\n';
	var arNewFieldNames = [];
	for (var id in arFieldList)
	{
		var obj = arFieldList[id];
		if (id && obj)
		{
			var txt = document.getElementById('gn_' + obj.gfid + '_' + obj.id);
			var dd = document.getElementById('gt_' + obj.gfid + '_' + obj.id);
			var cb = document.getElementById('cb_' + obj.gfid + '_' + obj.id);
			if (txt && dd && cb)
			{
				//if (console && console.log) console.log('txt: ' + txt.value + ', dd: ' + dd.value);
				if (txt.value.trim() == '' || dd.value.trim() == '')
				{
					//error, required
					ShowHideGroupingError(true, gfid, 'All fields are required.', oPanel);
					return;
				}
				if (arNewFieldNames[txt.value.trim().toLowerCase()] == true)
				{
					//error, unique
					ShowHideGroupingError(true, gfid, 'All field names must be unique.', oPanel);
					return;
				}
				else
				{
					//add to array
					arNewFieldNames[txt.value.trim().toLowerCase()] = true;
					//add to xml
					xml += '<newfield>\n<name><![CDATA[' + txt.value.trim() + ']]></name>\n';
					xml += '<type>' + dd.value + '</type>\n';
					xml += '<required>' + cb.checked + '</required>\n</newfield>\n';
				}
			} //null check
		} //null check
	} //field list loop
	//close xml
	xml += '</root>';
	//null object
	arNewFieldNames = null;
	//if (console && console.log)
	//{
		//console.log('xml: ' + xml);
	//}
	//hide buttons, show loading
	AddFieldModeOnOff(false, gfid);
	ShowHideToolbarLoading(true, gfid, true);
	//ajax
	var ar = new AjaxRunner();
	ar.Url = '/idbms/ui/ajax/vg_handler.aspx';
	// 10/11/2007 - JM - (see #2671, #2673) Added gfid so it can be used to look stuff up in vg_handler
	// JDB 6/12/2008 Single Table - adding control id to the url
	ar.Querystring = GroupQueryString + '&cid=' + cid + '&cmd=addfields&grpid=' + gid + "&miid=" + prmModuleId + "&gfid=" + gfid; //pass grouping id
	ar.AddFormValue("newfieldsxml", xml);
	ar.OnSuccess = SaveAddFieldsFinished;
	//create dummy object to pass to execute()
	var oDummy = {};
	oDummy.ID = gfid;
	oDummy.oPanel = oPanel;
	ar.Execute(null, oDummy);
	
} //SaveAddFields


function SaveAddFieldsFinished(response, oArgs)
{
	var gfid = oArgs.ID;
	var oPanel = oArgs.oPanel;
	if (response == 'true')
	{
		if ($('divButtons') != null) $('divButtons').style.display = '';
		//show success
		ShowHideToolbarLoading(true, gfid, false);
		//delay reload ajax panel
		//setTimeout(function () { RadAjaxPanel_Reload(CONST_CURRENTGFID); }, idbmsDelay);
		setTimeout(function () { window.location = GetCurrentUrlWithoutGFID() + '&gfid=' + CONST_CURRENTGFID; }, idbmsDelay);
	}
	else
	{
		//hide loading
		ShowHideToolbarLoading(false, gfid);
		//show errors passed back in response
		ShowHideGroupingError(true, gfid, response, oPanel);
		//turn on add field mode again
		AddFieldModeOnOff(true, gfid);
	}
} //SaveAddFieldsFinished


function CancelAddFields(bNoConfirm, oPanel)
{
	if (!bNoConfirm)
	{
		if (!confirm(confirmText)){ return; } //'Are you sure?')) 
	}
	//build a list of tbl row indexes
	var indexes = [];
	var maintbl;
	var gfid;
	//get the row index for every field in the array
	//if (console && console.log) console.log('field list count: ' + arFieldList.length);
	for (var id in arFieldList)
	{
		var obj = arFieldList[id];
		if (id && obj)
		{
			if (!maintbl) { maintbl = document.getElementById(obj.tblId); }
			if (!gfid) { gfid = obj.gfid; }
			//if (console && console.log) console.log('maintbl.rows.length: ' + maintbl.rows.length);
			for (var i=0; i<maintbl.rows.length; i++)
			{
				//if (console && console.log) console.log('maintbl.rows[i].id: ' + maintbl.rows[i].id);
				if (maintbl.rows[i].id == 'gr_' + gfid + '_' + obj.id)
				{
					indexes[indexes.length] = i; //add it to the end
					//if (console && console.log) console.log('breaking...');
					break; //we've found this field, exit this 2nd loop
				}
			}
		} //null id and obj
		//else { alert('null id or obj!'); }
	} //loop every field
	if (maintbl && gfid)
	{
		//if (console && console.log) console.log('indexes count: ' + indexes.length);
		//need to loop backwards so it removes the rows correctly (cause they are at the bottom of the table)
		for (var i=indexes.length-1; i>=0; i--)
		{
			//if (console && console.log) console.log('index: ' + indexes[i]);
			maintbl.deleteRow(indexes[i]);
		}
		iAddFieldRowCount = 0;
		AddFieldModeOnOff(false, gfid);
		arFieldList = [];
		//hide drop panel if it's showing
		ShowHideGroupingError(false, gfid, null, oPanel);
	
	} //tbl null check
	
	if ($('divButtons') != null) $('divButtons').style.display = '';
} //CancelAddFields


function SetupGroupingToolbar()
{
	//setup array
	arFieldList = [];
} //SetupGroupingToolbar


function AddFieldToList(id, gfid, tblId)
{
	//if (console && console.log) console.log('adding field to list! -- ' + id);
	//id is the unique index
	var obj = {};
	obj.id = id;
	obj.gfid = gfid;
	obj.tblId = tblId;
	arFieldList[id] = obj;
} //AddFieldToList


function RemoveFieldFromList(id)
{
	arFieldList[id] = null;
} //RemoveFieldFromList

function SetDonationDriverAmount(prmAmount)
{
	donationDriverAmount = prmAmount;
	// If we have designations, then update that label as well.
	if (hasDesignations) 
	{
		DesignationsSum();
	}

	CalculateScheduledPayments();
	if (RecalculatePct)
	{
		RecalculatePct();
	}
} // SetDonationDriverAmount

function CalculateScheduledPayments()
{
	//dummy function so the above function won't freak out if scheduled payments control isn't on the page
} // CalculateScheduledPayments

function DesignationsSum()
{
	var vSum = 0;
	jQuery("table.idbmsCampaignDesignations input[type='text']").each(function(k, v) {
		vSum += Number(v.value);
	});

	if (vSum > 0) 
	{
		hasDesignations = true;
		vSum = (donationDriverAmount - vSum).toFixed(2);
		jQuery('span.idbmsCampaignDesignationsMessage').html(DesignationsSumVerbiageItem.replace("##value##", vSum.toString()));

		if (vSum == 0) {
			btnNextDesignations = true;
		} else {
			btnNextDesignations = false;
		}

	} else {
		hasDesignations = false;
		jQuery('span.idbmsCampaignDesignationsMessage').html("");
		btnNextDesignations = true;
	}

	EnableNextButton();
}

// PaulS - Sprint 2009.12.03 - Light Authentication
// We now have multiple different pieces of functionality looking to enable / disable the next button.
// This will ensure that all items are met before enabling the button.
var btnNextDesignations = true;
var btnNextLightAuth = true;
function EnableNextButton()
{
	if (btnNextDesignations && btnNextLightAuth)
	{
		jQuery('input#rg_gfid_' + CONST_CURRENTGFID + '_btnNext').removeAttr("disabled");
	} else
	{
		jQuery('input#rg_gfid_' + CONST_CURRENTGFID + '_btnNext').attr("disabled", "disabled");
	}
}

// PaulS - Sprint 2009.12.03 - Light Authentication
// This will attach the handler to the email control. It is called from script that is generated in
// vg2 based on if light auth being enabled on the form and the email control being on this step
// of the from.
var emAjaxInd = "lightAuthAjaxPanel";			// Our <div> id for the Lightauth messages.
var emAjaxInd2 = "#" + emAjaxInd;				// Same just formatted for jQuery.
var hasConfirm = false;							// Indicator to let us know if we are using the confirm control.
var lightAuthAttempts = 0; 						// Number of lightauth attempts made.
var emTextBox1 = "_TextBox1";					// Textbox 1.
var emTextBox2 = emTextBox1 + "_Confirm";		// Confirmation text box.
function InitializeLightAuth(prmEmailControlId)
{
	// Get our email text box controls.
	emTextBox1 = "#" + prmEmailControlId + "_TextBox1";

	// If we already have a value, then skip the ICP check.
	if (jQuery(emTextBox1).val() != "") { return; }
	
	emTextBox2 = emTextBox1 + "_Confirm";

	// Check if we have a confirmation box.
	hasConfirm = (jQuery(emTextBox2).length > 0);

	// <div> that is injected after the email control. This will hold our messages to the user.
	var emAjaxDiv = "<div id=\"" + emAjaxInd + "\" style=\"display: none;\"></div>";

	// Disable the btnNext.
	btnNextLightAuth = false;
	EnableNextButton();
	
	// Check to see if we are using a confirmation control.
	if (hasConfirm)
	{
		// Put our light auth message div after the confirmation box.
		jQuery(emTextBox2).parent().append(emAjaxDiv);
		
		// Blur event for the text box.
		jQuery(emTextBox1).blur(function(e)
		{
			var email1 = jQuery(this).val();
			var email2 = jQuery(emTextBox2).val();
			if (email1 != "")
			{
				if (email1 == email2)
				{
					CallLightAuthAjax(prmEmailControlId, email1);
				}
			}
		});
		
		// Blur event for the confirmation box.
		jQuery(emTextBox2).blur(function(e)
		{
			var email1 = jQuery(emTextBox1).val();
			var email2 = jQuery(this).val();
			if (email1 != "")
			{
				if (email1 == email2)
				{
					CallLightAuthAjax(prmEmailControlId, email1);
				} else
				{
					// Emails do not match. We need to let the user know as the button
					// will be disabled and they check on post back cannot happen.
					ShowLightAuthWarning(true, laEmailsMatch);
				}
			}
		});
	} else
	{
		// Put out light auth message div after the text box.
		jQuery(emTextBox1).parent().append(emAjaxDiv);

		jQuery(emTextBox1).blur(function(e)
		{
			var email1 = jQuery(this).val();
			if (email1 != "")
			{
				CallLightAuthAjax(prmEmailControlId, email1);
			}
		});
	}
}

// PaulS - Sprint 2009.12.03 - Light Authentication
// This function will make an ajax call to the light auth handler to look
// up an e-mail address that was entered into a form. Upon return, it will
// popup a window if it found a member record to prompt the user.
function CallLightAuthAjax(prmEmailControlId, prmEmail)
{
	ShowLightAuthWarning(false, "");
	
	// Prevent us from making the call if we are over our max attempts.
	if (lightAuthAttempts >= lightAuthMaxAttempts)
	{
		return;
	}
	
	// Emails match, call the ajax to find a match.
	ShowLightAuthAjax(true, lightAuthAjaxMessage);
	
	var ar = new AjaxRunner();
	ar.Url = "/controls/LightAuthenticationUI/LightAuth_handler.aspx";
	ar.Querystring = GroupQueryString + "&cid=" + FormId + "&tid=" + lightAuthTempId;
	ar.AddFormValue("cmd", "lalookup");
	ar.AddFormValue("em", prmEmail);
	ar.OnSuccess = function(sPrmResponse, oEventArgs)
	{
		// Hide our ajax indicator.
		ShowLightAuthAjax(false);

		if (sPrmResponse.toString().length <= 20)
		{
			if (sPrmResponse == "NOTFOUND")
			{
				lightAuthAttempts++;
				if (lightAuthAttempts >= lightAuthMaxAttempts)
				{
					// After our two attepmts, skip light auth.
					SkipLightAuth();
				} else
				{
					ShowLightAuthWarning(true, laNotFound);
				}
			} else if (sPrmResponse.match(/^\d:\d+$/))
			{
				// Response should come back [maptype]:[member_id]
				//                           0:123456789
				var svars = sPrmResponse.split(":");
				
				// We found an existing mapping.
				btnNextLightAuth = true;
				EnableNextButton();
				AddMemberid(svars[0], svars[1]);
			} else
			{
				// We only found a non-member account or had an unexpected error. Let them pass.
				SkipLightAuth();
			}
		} else
		{
			// We found something we need to ask about.
			jQuery("body").append("<div id=\"tboxladiv\" style=\"display: none;\">" + sPrmResponse + "</div>");
			tb_show("", "#TB_inline?height=300&width=600&modal=true&inlineId=tboxladiv", false); // TB_iframe=1&
		}
	};
	ar.OnError = function()
	{
		// If we get an error, let them proceed through the form.
		SkipLightAuth();
	};
	ar.Execute();
}

// PaulS - Sprint 2009.12.03 - Light Authentication
// Shows the light auth ajax spinner.
function ShowLightAuthAjax(prmShow, prmMessage)
{
	if(prmShow)
	{
		jQuery(emAjaxInd2).addClass("idbmsLightAuthAjaxMessage");
		jQuery(emAjaxInd2).html(prmMessage);
		jQuery(emAjaxInd2).show();
	} else
	{
		jQuery(emAjaxInd2).hide();
		jQuery(emAjaxInd2).empty();
		jQuery(emAjaxInd2).removeClass("idbmsLightAuthAjaxMessage");
	}
}

// PaulS - Sprint 2009.12.03 - Light Authentication
// Shows the light auth warning message.
function ShowLightAuthWarning(prmShow, prmMsg)
{
	if(prmShow)
	{
		jQuery(emAjaxInd2).addClass("warning");
		// The warning class that is used is from Calendar.css which has a 450px width. causing us to go wide.
		// Prevent that.
		jQuery(emAjaxInd2).css("max-width", "300px");
		jQuery(emAjaxInd2).html(prmMsg);
		jQuery(emAjaxInd2).show();
	} else
	{
		jQuery(emAjaxInd2).hide();
		jQuery(emAjaxInd2).empty();
		jQuery(emAjaxInd2).css("max-width", "");
		jQuery(emAjaxInd2).removeClass("warning");
	}
}

// PaulS - Sprint 2009.12.03 - Light Authentication
// This will allow the user to skip by the light auth fucntionality.
function SkipLightAuth()
{
	// Doing this will disable any future calls.
	lightAuthAttempts = lightAuthMaxAttempts;
	ShowLightAuthAjax(false, "");
	ShowLightAuthWarning(false, "");
	btnNextLightAuth = true;
	EnableNextButton();
}

// PaulS - Sprint 2009.12.03 - Light Authentication
// This will be when the we find a match for the email, but the user says it is not them.
function LightAuthNotMe()
{
	SkipLightAuth();
	tb_remove();
	jQuery("#tboxladiv").remove();
}

// PaulS - Sprint 2009.12.03 - Light Authentication
// This is called when the user says 'yes', this is me. It will make another ajax
// call to the light auth handler and create a mapping for the member.
function LightAuthItsMe(prmId)
{
	// Doing this will disable any future calls.
	lightAuthAttempts = lightAuthMaxAttempts;

	ShowLightAuthWarning(false, "");
	tb_remove();
	jQuery("#tboxladiv").remove();
	
	btnNextLightAuth = true;
	EnableNextButton();

	// Now add our hidden fields. We do not need to make the ajax call any more because VG2
	// will now create the ic member mapping after it creates the new non-member account.
	AddMemberid("2", prmId);
}

// PaulS - Sprint 2009.12.03 - Light Authentication - Since we could have members sharing an e-mail address,
// make sure we put the member_id in the form so that we can pick up the correct one in Vg2.
function AddMemberid(prmMaptype, prmMember)
{
	jQuery(emTextBox1).parent().append("<input type=\"hidden\" name=\"_IC_MAPTYPE_\" value=\"" + prmMaptype + "\" />");
	jQuery(emTextBox1).parent().append("<input type=\"hidden\" name=\"_IC_MEMBERID_\" value=\"" + prmMember + "\" />");
}