//Form reset handler
function form_Reset(e)
{
	//Clear the generated textbox
	var inputID=getCheckedRadio(document.forms[0][NAMEPREFIX+'QueryTypeRadioList']).value;
	setTimeout(function()
	{
		document.getElementById(IDPREFIX+inputID+'TextBox').value='';
		reimbursementOptionDropDownList_Change({target:document.getElementById(IDPREFIX+'ReimbursementOptionDropDownList')});
	},0);
	//This is silly, reset might not cause change event to fire so we must do it manually
	document.forms[0][NAMEPREFIX+'QueryTypeRadioList'][0].checked=true;
	queryType_Click();
}
//Clears Required fields validator, it is used as a validation summary.
function clearRequiredFieldsValidator()
{
	var requiredFieldsValidator=document.getElementById(IDPREFIX+'RequiredFieldsValidator');
	while(true===requiredFieldsValidator.hasChildNodes())
	{
		requiredFieldsValidator.removeChild(requiredFieldsValidator.firstChild);
	}
}
//Callbacks with the parameters from the form.
function doAsyncCall(e)
{
	var arg,evt,tagName,i,requiredFieldsValidator;
	arg={};
	evt=new CommonEvent(e);
	requiredFieldsValidator=document.getElementById(IDPREFIX+'RequiredFieldsValidator');
	tagName=evt.sender.tagName.toLowerCase();
	arg.IsValid=true;
	validateTextBoxes(null,arg);
	if(!arg.IsValid)
	{
		clearRequiredFieldsValidator();
		for(i=0;i<Page_Validators.length;i++)
		{
			if((false===Page_Validators[i].isvalid)&&(requiredFieldsValidator!==Page_Validators[i]))
			{
				requiredFieldsValidator.appendChild(document.createTextNode(Page_Validators[i].title));
				requiredFieldsValidator.appendChild(document.createElement('br'));
			}
		}
		if(null===requiredFieldsValidator.firstChild)
		{
			requiredFieldsValidator.appendChild(document.createTextNode(requiredFieldsValidator.title));
		}
		document.getElementById(IDPREFIX+'RequiredFieldsValidator').style.visibility='visible';
		evt.cancel();
		return false;
	}
	if('form'===tagName)
	{
		evt.cancel();
		return false;
	}
	document.getElementById(IDPREFIX+'RequiredFieldsValidator').style.visibility='hidden';
	var action=evt.sender.id.replace('Button','').replace(IDPREFIX,'');
	var deduction=document.getElementById(IDPREFIX+'DeductionTextBox').value;
	var loan=document.getElementById(IDPREFIX+'LoanTextBox').value;
	var payments=document.getElementById(IDPREFIX+'PaymentsTextBox').value;
	var interest=document.getElementById(IDPREFIX+'InterestTextBox').value;
	var reimbursementOption=document.getElementById(IDPREFIX+'ReimbursementOptionDropDownList').value;
	var queryType=getCheckedRadio(document.forms[0][NAMEPREFIX+'QueryTypeRadioList']).value;
	var callback=null;
	switch (queryType)
	{
		case 'Deduction':
			callback=window[IDPREFIX+'DeductionCallBack'];
			break;
		case 'Loan':
			callback=window[IDPREFIX+'LoanCallBack'];
			break;
		case 'Payments':
			callback=window[IDPREFIX+'PaymentsCallBack'];
			break;
		case 'Interest':
			callback=window[IDPREFIX+'InterestCallBack'];
			break;
	}
	if(null!==callback)
	{
		addClass('CallBackInProgress',document.body,true);
		callback.Callback('Field',queryType,deduction,loan,payments,interest,reimbursementOption);
	}
	if('Board'===action)
	{
		addClass('CallBackInProgress',document.body,true);
		window[IDPREFIX+'PaymentsBoardCallBack'].Callback(action,queryType,deduction,loan,payments,interest,reimbursementOption);
	}
	if(('input'===tagName)&&('submit'===evt.sender.type))
	{
		evt.cancel();
		return false;
	}
	return true;
}
function removeBoard(e)
{
	var board=document.getElementById(IDPREFIX+'PaymentsBoardCallBack_div');
	if(null!==board)
	{
		while(true===board.hasChildNodes())
		{
			board.removeChild(board.firstChild);
		}
	}
}
//Clears the textual input related to the currently checked radio button
function clearTextBox(e)
{
	var id,radios,radio;
	radios=document.forms[0][NAMEPREFIX+'QueryTypeRadioList'];
	radio=getCheckedRadio(radios);
	id=IDPREFIX+radio.value+'TextBox';
	document.getElementById(id).value='';
}
//Removes dashes / minus signs from the sender text box
function removeDashes(e)
{
	var evt;
	evt=new CommonEvent(e);
	evt.sender.value=evt.sender.value.replace(/-/g,'');
}
//TextBox init, attaches events and (dis)allows focus
function initTextBox(textbox,disable)
{
	attachEventListener('focus',textbox,textBox_Focus);
	attachEventListener('blur',textbox,textBox_Blur);
	attachEventListener('change',textbox,clearTextBox);
	attachEventListener('change',textbox,removeBoard);
	attachEventListener('keyup',textbox,removeDashes);
	allowFocusFor(textbox,!disable);
}
//Page initialization
function body_Load()
{
	//Form and inputs
	//Form
	var loanForm=document.forms[0];
	//Select
	var reimbursementOptionDropDownList=document.getElementById(IDPREFIX+'ReimbursementOptionDropDownList');
	//Radios
	var deductionRadio=document.getElementById(IDPREFIX+'QueryTypeRadioList_0');
	var loanRadio=document.getElementById(IDPREFIX+'QueryTypeRadioList_1');
	var paymentsRadio=document.getElementById(IDPREFIX+'QueryTypeRadioList_2');
	var interestRadio=document.getElementById(IDPREFIX+'QueryTypeRadioList_3');
	//Textboxes
	var deductionTextBox=document.getElementById(IDPREFIX+'DeductionTextBox');
	var loanTextBox=document.getElementById(IDPREFIX+'LoanTextBox');
	var paymentsTextBox=document.getElementById(IDPREFIX+'PaymentsTextBox');
	var interestTextBox=document.getElementById(IDPREFIX+'InterestTextBox');
	//GridView container
	var tableContainer=document.getElementById(IDPREFIX+'TableContainer');
	//Buttons
	var fieldButton=document.getElementById(IDPREFIX+'FieldButton');
	var boardButton=document.getElementById(IDPREFIX+'BoardButton');
	
	//Form reset
	attachEventListener('reset',loanForm,form_Reset);
	//Form submit
	attachEventListener('submit',loanForm,doAsyncCall);//Gecko needs this, it allows us to prevent doing a form.submit() when doing async calls
	//LoanType changed
	attachEventListener('change',reimbursementOptionDropDownList,reimbursementOptionDropDownList_Change);
	//QueryType clicked
	attachEventListener('click',deductionRadio,queryType_Click);
	attachEventListener('click',loanRadio,queryType_Click);
	attachEventListener('click',paymentsRadio,queryType_Click);
	attachEventListener('click',interestRadio,queryType_Click);
	//TextBoxes focused / lost focus
	initTextBox(deductionTextBox,false);
	initTextBox(loanTextBox,false);
	initTextBox(paymentsTextBox,false);
	initTextBox(interestTextBox,false);
	//Assign async callbacks to FieldButton and BoardButton
	attachEventListener('click',fieldButton,doAsyncCall);
	attachEventListener('click',boardButton,doAsyncCall);
	allowFocusFor(document.getElementById(IDPREFIX+getCheckedRadio(document.forms[0][NAMEPREFIX+'QueryTypeRadioList']).value+'TextBox'),false);
	
	//Empty required fields validator - it is used as a validation summary
	clearRequiredFieldsValidator();
}

//Enable/Disable the appropritate TextBox - the disabled TextBox's value is reset
function queryType_Click(e)
{
	if(hasClass('Disabled',(document.getElementById(IDPREFIX+getCheckedRadio(document.forms[0][NAMEPREFIX+'QueryTypeRadioList']).value+'TextBox'))))
	{
		return;//No need to do anything, user clicked an already selected radio button
	}
	removeBoard(null);
	var queryType=document.forms[0][NAMEPREFIX+'QueryTypeRadioList'];
	for(var i=0;i<queryType.length;i++)
	{
		allowFocusFor(document.getElementById(IDPREFIX+queryType[i].value+'TextBox'),true);
	}
	var text=document.getElementById(IDPREFIX+getCheckedRadio(document.forms[0][NAMEPREFIX+'QueryTypeRadioList']).value+'TextBox');
	allowFocusFor(text,false);
	text.value='';
}

//Update the deduction table header and remove the payments board.
function reimbursementOptionDropDownList_Change(e)
{
	var evt,label,values;
	evt=new CommonEvent(e);
	label=document.getElementById(IDPREFIX+'DeductionHeaderLabel');
	values=label.title.split('/');
	if(label.firstChild.nodeValue===values[0])
	{
		label.firstChild.nodeValue=values[1];
	}
	else
	{
		label.firstChild.nodeValue=values[0];
	}
	document.getElementById(IDPREFIX+getCheckedRadio(document.forms[0][NAMEPREFIX+'QueryTypeRadioList']).value+'TextBox').value='';
	removeBoard(null);
}

//Removes the focus from the sending object and sets it on the next available input, also making it 'disabled' looking
function allowFocusFor(element,allow)
{
	if('undefined'!==typeof element.readOnly)
	{
		if(false===allow)
		{
			addClass('Disabled',element,false);
		}
		else
		{
			removeClass('Disabled',element,true);
		}
		element.readOnly=!allow;
	}
}

//Validates that at least 3 of the TextBoxes are filled and clears the TextBox which is about to receive a new value
//Also attempts to prevent conflicting data to the server
function validateTextBoxes(source,args)
{
	//Check empties & NaNs
	var empties=0;
	var loanForm=document.forms[0];
	var deduction=loanForm[IDPREFIX+'DeductionTextBox'].value;
	var loan=loanForm[IDPREFIX+'LoanTextBox'].value;
	var payments=loanForm[IDPREFIX+'PaymentsTextBox'].value;
	var interest=loanForm[IDPREFIX+'InterestTextBox'].value;
	var checkedRadio=getCheckedRadio(loanForm[NAMEPREFIX+'QueryTypeRadioList']);
	var action=checkedRadio.value;
	document.getElementById(IDPREFIX+checkedRadio.value+'TextBox').value='';
	if(0===deduction.length){empties++;}else{args.IsValid=((args.IsValid)&&(!isNaN(deduction)));}
	if(0===loan.length){empties++;}else{args.IsValid=((args.IsValid)&&(!isNaN(loan)));}
	if(0===payments.length){empties++;}else{args.IsValid=((args.IsValid)&&(!isNaN(payments)));}
	if(0===interest.length){empties++;}else{args.IsValid=((args.IsValid)&&(!isNaN(interest)));}
	//parsing the fields
	deduction=Number(loanForm[IDPREFIX+'DeductionTextBox'].value);
	loan=Number(loanForm[IDPREFIX+'LoanTextBox'].value);
	payments=Number(loanForm[IDPREFIX+'PaymentsTextBox'].value);
	interest=Number(loanForm[IDPREFIX+'InterestTextBox'].value);
	args.IsValid=((args.IsValid) && (1>=empties));
	switch(action)
	{
		case 'Deduction':
			if ((0 === loan) || (0 === payments) || 0 > interest)
			{args.IsValid=false;}
			break;
		case 'Loan':
			if ((0 === payments) || (0 === deduction) || (0 > interest))
			{args.IsValid=false;}
			break;
		case 'Payments':
			if ((0 === loan) || (0 > interest) || (0 >= deduction) || //no loan/no interest/no deduction
			((deduction < (interest / 1200) * loan))||//Will take forever to return
			(deduction>loan))
			{args.IsValid=false;}
			break;
		case 'Interest':
			if ((0 === loan) || (0 === payments) || (0 === deduction) ||//no loan/no payments/returning nothing each month.
			(deduction * payments < loan))//Not repaying enough
			{args.IsValid=false;}
			break;
	}
	if(('Payments'!==action)&&('Deduction'!==action))
	{
		args.IsValid=((args.IsValid) && deduction>(loan*(interest/12)));//Paying too much
	}
	if(600<payments)//Too long
	{
		args.IsValid=false;
	}
}

function callback_Complete(param)
{
	var error=null;
	error=document.getElementById('error');
	removeClass('CallBackInProgress',document.body,false);
	if(null!==error)
	{
		alert(error.value);
		error.parentNode.removeChild(error);
	}
	else
	{
		if('Board'===param)
		{
			if('function'===typeof scrollPaymentsBoard)
			{
				scrollPaymentsBoard();
				detachEventListener('resize',window,loanResizeHandler);
				attachEventListener('resize',window,loanResizeHandler);
			}
		}
		else
		{
			initTextBox(document.getElementById(IDPREFIX+param+'TextBox'),true);
		}
	}
}
