// Utilities.js

// Replaces the standard client validation function with our own which
// sets the focus on validation summary if page is not valid

var validControlColors = new Hashtable();

var invalidFieldColor = 'red';

function ValidatorDisplayReplacement(val)
{
	//Call the old implementation first
	ValidatorUpdateDisplayOld(val);
	
	//And then update our own display
	var ctv = document.getElementById(val.controltovalidate);
	
	var allValidatorsValid = true;
	
	for (i = 0; i < Page_Validators.length; i++)
	{
        if (Page_Validators[i].controltovalidate == val.controltovalidate &&
			!Page_Validators[i].isvalid)
        {
			allValidatorsValid = false;
            
            break;
        }
	}
	
	if (ctv != null)
	{
		// always back up the original color of the control
		
		if (ctv.style.backgroundColor != invalidFieldColor)
		{
			validControlColors.put(ctv.id, ctv.style.backgroundColor);
		}
		
		if (val.enabled != false &&
			!(val.isvalid && allValidatorsValid))
		{
			ctv.style.backgroundColor = invalidFieldColor;
		}
		else
		{
			ctv.style.backgroundColor = validControlColors.get(ctv.id);
		}
	}
}

// This function is responsible for re-calculation of all the totals
// for all the customers

var totalsUpdater;
var fieldValueChanged = true;

function StartUpdatingTotals()
{
	totalsUpdater = setInterval('UpdateTotals()', 50);
}

function GetTextValue(controlID)
{
	var retVal = 0;
	
	var control = document.getElementById(controlID);
	
	if (control != null)
	{
		var iVal = control.value;
		
		if (!isNaN(iVal) &&
			iVal.length > 0)
		{
			retVal = parseFloat(iVal);
		}
	}
	
	return retVal;
}

// Finds the first child control that can take focus and focuses on it

function focusOnCustomer(focusControl)
{
	var bFocused = false;
	
	// first search all the children for a focus control

	for (var i = 0; i < focusControl.children.length; i++)
	{
		if (focusControl.children[i].tagName.toUpperCase() == 'TABLE')
		{
			focusControl.children[i].focus();
			
			bFocused = true;
			
			break;
		}
	}
	
	// then search all the children
	
	if (!bFocused)
	{
		for (var i = 0; i < focusControl.children[i].length; i++)
		{
			bFocused = focusOnCustomer(focusControl.children[i]);
			
			if (bFocused)
			{
				break;
			}
		}
	}
	
	return bFocused;
}

function PageValidateReplacement()
{
	//Call the old implementation first
	var isValid = Page_ClientValidateOld(); 
		
	//and then call our extension
	if (!isValid)
	{
		var vsSummary = document.getElementById('ValidationSummary');
		
		if (vsSummary != null &&
			vsSummary.focus != null)
		{
			vsSummary.focus();
		}
	}

	return isValid;
}

// Replaces the standard client validation function with our own which
// sets the focus on validation summary if page is not valid

function HookPageClientValidate()
{
	if( typeof( ValidatorUpdateDisplay ) == "function" )
	{ 
		ValidatorUpdateDisplayOld = ValidatorUpdateDisplay; 
		ValidatorUpdateDisplay = ValidatorDisplayReplacement;
	}
	
	if( typeof( Page_ClientValidate ) == "function" )
	{ 
		Page_ClientValidateOld = Page_ClientValidate; 
		Page_ClientValidate = PageValidateReplacement;
	}
}

// Shows the selected customer set (1 or 2)
// The page should have the div-s named control1, control2 etc. that
// should contain the corresponding controls
// Also page can have the selectedCustomerSet hidden control to preserve
// the currently shown set between postbacks

function ShowCustomerSet(setNumber)
{
	var xControl1 = document.getElementById('control1');
	var xControl2 = document.getElementById('control2');
	var xControl3 = document.getElementById('control3');
	var xControl4 = document.getElementById('control4');
	
	if (xControl1 != null &&
		xControl2 != null &&
		xControl3 != null &&
		xControl4 != null)
	{
		xControl1.style.visibility = (setNumber == '1' ? 'visible' : 'hidden');
		xControl1.style.display = (setNumber == '1' ? 'block' : 'none');

		xControl2.style.visibility = xControl1.style.visibility;
		xControl2.style.display = xControl1.style.display

		xControl3.style.visibility = (setNumber == '2' ? 'visible' : 'hidden');
		xControl3.style.display = (setNumber == '2' ? 'block' : 'none');

		xControl4.style.visibility = xControl3.style.visibility
		xControl4.style.display = xControl3.style.display
		
		focusOnCustomer((setNumber == '1') ? xControl1 : xControl3);
	}

	var xSelectedCustomerSet = document.getElementById('selectedCustomerSet');
	
	if (xSelectedCustomerSet != null)
	{
		xSelectedCustomerSet.value = setNumber;
	}
	
	return false;
}

//this function only allows the user to type in a number	
function NumOnly()
{
	//alert(window.event.keyCode);
	if (window.event.keyCode < 48 || window.event.keyCode > 57 && window.event.keyCode != 45)
	{
		window.event.keyCode = 1;
		return;
	}
}

//A phone number verifier
function PhoneOnly()
{
	if (!((window.event.keyCode >= 48 && window.event.keyCode <= 57) ||
		window.event.keyCode == 45 ||
		window.event.keyCode == 40 ||
		window.event.keyCode == 41 ||
		window.event.keyCode == 43))
	{
		window.event.keyCode = 1;
		return;
	}
}

function DecimalOnly()
{
	if (!((window.event.keyCode >= 48 && window.event.keyCode <= 57) ||
		window.event.keyCode == 46))
	{
		window.event.keyCode = 1;
		return;
	}
}

function DigitsOnly()
{
	if (!(window.event.keyCode >= 48 && window.event.keyCode <= 57))
	{
		window.event.keyCode = 1;
		return;
	}
}

function ChartNumberOnly()
{
	if (!(window.event.keyCode >= 48 && window.event.keyCode <= 57) &&
		!(window.event.keyCode >= 65 && window.event.keyCode <= 90) &&
		!(window.event.keyCode >= 97 && window.event.keyCode <= 122))
	{
		window.event.keyCode = 1;
		return;
	}
}

function DateOnly()
{
	if (!((window.event.keyCode >= 48 && window.event.keyCode <= 57) ||
		window.event.keyCode == 47))
	{
		window.event.keyCode = 1;
		return;
	}
}

///Clears Contents of ClipBoard so User Can't
//Paste into a Control. Used to Stop Users Pasting into
//a Number Only Control
function DisablePaste()
{
	window.clipboardData.setData("Text", '');
}

//Set selected item by selected value in list control
function SetSelectedValue(objSelect, selectedValue)
{
	var selectedIndex = -1;
	var colOptions = objSelect.options;
	for(var i=0; i<colOptions.length; i++)
	{
		if (colOptions[i].value == selectedValue)
		{
			objSelect.selectedIndex = i;
			break;
		}
	}
	
	return selectedIndex;
}

function ValidateDateObject(source, arguments)
{
	arguments.IsValid =	ValidateDateFormat(arguments.Value);
}

//Check date format if date field is not empty
function ValidateDateFormat(str)
{
	if (str == "")
		{
			//return true if string is empty
			return true;
		}
	else
		{
			if (str.match(/^(\d{1,2})\/(\d{1,2})\/(\d{1,4})$/) == null)
				{
					return false;
				}
			else
				{
					var day = RegExp.$1;
					var month = RegExp.$2;
					var year = RegExp.$3;
					
					//check if digits are correct.
					return (day>0 && day<32 && month>0 && month<13 && year>1760 && year<3000);
				}
		}
}

function UpdateValidatorsView()
{
	for (var i = 0; i < Page_Validators.length; i++)
	{
		ValidatorValidate(Page_Validators[i]);
	}
	
	for (var i = 0; i < Page_Validators.length; i++)
	{
		ValidatorUpdateDisplay(Page_Validators[i]);
	}
}

// formats the specified number to the 2 decimal places 
function FormatDecimal(num)
{
	var form = new NumberFormat(num);
	
	form.setPlaces(2);
	form.setSeparators(false);

	return form.toFormatted();
}

// This is an encapsulation of Application Status enumeration. Needed for
// some pages to enable or disable special validation

function ApplicationStatus()
{
	this.Lead = 1;
	this.NewApplication = 2;
	this.AIP = 3;
	this.InstructValuation = 4;
	this.LoanOfferDocumentsOutstanding = 5;
	this.SubmitLoanOffer = 6;
	this.AwaitingLoanOffer = 7;
	this.CompletionDocsOutstanding = 8;
	this.FileClear = 9;
	this.AwaitingChequeIssue = 10;
	this.Closed = 11;
}

// This is an encapsulation of Customer Type enumeration. Needed for some
// pages to enable or disable the validation

function CustomerType()
{
	this.FirstTimeBuyer = 1;
	this.Investor = 2;
	this.Commercial = 3;
	this.TradeUp = 4;
	this.TradeDown = 5;
	this.SelfBuild = 6;
	this.Remortgage = 7;
	this.TopUp = 8;
}

// This function if responsible for updating the enabled/disabled state
// and the state of the validators

var pageStateUpdater;
var pageStateChanged = true;

function StartUpdatingPageState()
{
	pageStateUpdater = setInterval('UpdatePageState()', 70);
}

// Obtains the formatted float value from the specified input field
function GetFloatValue(controlID)
{
	var retVal = 0;
	
	var control = document.getElementById(controlID);
	
	if (control != null)
	{
		var iVal = control.value;
		
		if (!isNaN(iVal) &&
			iVal.length > 0)
		{
			retVal = parseFloat(iVal);
		}
	}
	
	return retVal;
}
