function populateSpecialCalculatedAmount(me, sourceField, multiplierField, destinationField)
{	
	
	//find the incremental id from the me field e.g. BankCardType_1
	var incrementId = me.id.substring(me.id.lastIndexOf('_')+1)
	//append the incrementid to the field names
	sourceField += '_' + incrementId;
	multiplierField += '_' + incrementId;
	destinationField += '_' + incrementId;

	//call the normal populate calculated amount method
	populateCalculatedAmount(sourceField, multiplierField, destinationField);
}


function populateNormalFields(fieldName) {
	var sourceFieldName = 'CalcVar_' + fieldName;
	var multiplierFieldName = 'CalcVar_' + fieldName + 'Freq';
	var destinationFieldName = fieldName + 'Amount';
	
	populateCalculatedAmount(sourceFieldName, multiplierFieldName, destinationFieldName);
}

/************************************************************************/ 
//	 populateCalculatedAmount
/************************************************************************/
/// Calculate the monthly value depending on the multiplier value
/// The daily value is calcualted first and is then multiplied by 30.33 to get the monthly equivalent
///	sourceValue - Textbox that user enters amount in
/// multiplierField - Dropdown box that the user selects the frequency
/// destinationField - Readonly text box that the new value needs to be populated in
function populateCalculatedAmount(sourceField, multiplierField, destinationField)
{	

	var sourceValue = document.getElementById(sourceField).value;
	var multiplierValue = document.getElementById(multiplierField).value;
	var dSubTotal;
	switch (multiplierValue)
	{
		case '52':
		//weekly
			dSubTotal = sourceValue / 7;
			break;
		case '26':
		//fortnightly
			dSubTotal = sourceValue / 14;			
			break;
		case '12':
		//monthly
			dSubTotal = sourceValue / 30.33;
			break;
		case '4':
		//quarterly
			dSubTotal = sourceValue / 90.99;
			break;
		case '2':
		//half yearly
			dSubTotal = sourceValue / 182.02;
			break;
		case '1':
		//annually
			dSubTotal = sourceValue / 364.04;
			break;
		case '':
			dSubTotal = 0;
			break;			
	}
	var monthlyTotal = dSubTotal * 30.33;
	//assign the monthly total to the fields monthly amount display
	document.getElementById(destinationField).value = formatCurrency(monthlyTotal);	

	//now recalculate the subtotals for everything
	
	//set the expenses total					
	var expenseTotal = GetMonthlyExpenses() + GetLivingExpenses() + GetRentExpenses() + GetOtherExpenses();
	document.getElementById('ExpensesTotal').value = formatCurrency(expenseTotal);
	
	//set the income total
	var incomeTotal = toInt(document.getElementById('SalaryAfterTaxAmount')) + toInt(document.getElementById('ExistingRentalIncomeAmount'))	+ toInt(document.getElementById('ProposedRentalIncomeAmount')) + getTotalValue('OtherIncomes', 'OtherIncomeAmount');
	document.getElementById('TotalMonthlyIncome').value = formatCurrency(incomeTotal);
		
	//set the total uncommitted income
	document.getElementById('UncommittedIncome').value = formatCurrency(toInt(document.getElementById('TotalMonthlyIncome')) - toInt(document.getElementById('ExpensesTotal')));
	
}

function GetMonthlyExpenses()
{	
	var subTotal;		
	subTotal = toInt(document.getElementById('OtherHLRepaymentsAmount'))
				+ toInt(document.getElementById('ProposedNewNBRepaymentsAmount'))
				+ toInt(document.getElementById('GovtStudentLoanAmount'))
				+ toInt(document.getElementById('PersonalLoanRepaymentsAmount'))
				+ toInt(document.getElementById('CreditRepaymentsAmount'))
				+ toInt(document.getElementById('HirePurchaseAmount'));		
	document.getElementById('RepaymentsSubTotal').value = formatCurrency(subTotal);	
	return subTotal;
}

function GetLivingExpenses()
{
	var subTotal;	
	subTotal = toInt(document.getElementById('MotorVehicleAmount'))
				+ toInt(document.getElementById('UtilitiesAmount'))
				+ toInt(document.getElementById('RatesAmount'))
				+ toInt(document.getElementById('HomeInsuranceAmount'))
				+ toInt(document.getElementById('HouseholdAmount'))
				+ toInt(document.getElementById('EducationAmount'));	
	document.getElementById('LivingExpensesSubTotal').value = formatCurrency(subTotal);
	return subTotal;
}


function GetOtherExpenses()
{
	var subTotal;	
	subTotal = toInt(document.getElementById('OtherInsuranceAmount'))
				+ toInt(document.getElementById('SuperannuationAmount'))
				+ toInt(document.getElementById('OtherExpAmount'));
	document.getElementById('OtherExpensesSubTotal').value = formatCurrency(subTotal);
	return subTotal;
}

function GetRentExpenses()
{	
	var subTotal;	
	subTotal = toInt(document.getElementById('RentAmount'));
	document.getElementById('RentAmountDisplay').value = formatCurrency(subTotal);
	return subTotal;
}

/**************************
Formatting and Utility Functions
**************************/
function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}

function toInt(object)
{	
	if (object == null)
		return 0;
	else
	{
		//replace any currency characters and convert it to an integer
		number = Number(object.value.replace('$','').replace(new RegExp(/,/g), ''));
		//alert(object.value.replace('$','').replace(new RegExp(/,/g), ''));
		if (number == 'NaN')
			number = 0;		
		return number;
	}
}

/************************************************************************/
// doClone
// called when an 'add' link is clicked on
// 'this' refers to the link element, which is used to store info about
// the cloning process.
//
// This method is also called on postback to recreate clones that have been posted
/************************************************************************/ 
function doClone(copyItem, insertAt){
	
	this.prev = document.getElementById(insertAt);	

	if(!this.incrementIdentity)
		this.incrementIdentity = incrementId;
	
	if(!this.count)
		this.count=1;
	
	if(!this.getTotal)
		this.getTotal = getTheTotal;	
	
	
	var copy = document.getElementById(copyItem).cloneNode(true); // Deepcopy								

	this.incrementIdentity(copy);	
		
	var inputs = copy.getElementsByTagName("input");
	for (var i=0; i<inputs.length; i++){
		this.incrementIdentity(inputs[i]);
		//inputs[i].value=''; Conflicts with Radio Buttons. It clears the value.
		inputs[i].name=inputs[i].id;
		}
	inputs = null; // delete the reference, in case it is accidentally referenced later
	
	//this is specific to the budget calculator only - 
	//get the field named otherincomeamount (which is a span) and append the increment number
	var span = copy.getElementsByTagName("span");
	//as long as there is only one, go ahead
	if (span.length == 1) {
		this.incrementIdentity(span[0]);
		span[0].name = span[0].id;
	}
	span = null;
	
		
	var pselects = this.prev.getElementsByTagName("select"); 
	var selects = copy.getElementsByTagName("select"); 
	
	for (var i=0; i<selects.length; i++)
	{		
		this.incrementIdentity(selects[i]);
		//fireCloneEvent(pselects[i]);
		selects[i].name = selects[i].id;
	}selects=null;
	
	
	var files = copy.getElementsByTagName("file");
	for (var i=0; i<files.length; i++)
		this.incrementIdentity(files[i]);
		//files[i].name = files[i].id;
	files=null;
	
	var textareas = copy.getElementsByTagName("textarea");
	for (var i=0; i<textareas.length; i++){
		this.incrementIdentity(textareas[i]);
		//textareas[i].name = textareas[i].id;
		textareas[i].value='';
	}
	textareas=null;
	
	var labels = copy.getElementsByTagName("label");
	for(var i=0; i<labels.length; i++)				
	{
		if(labels[i].attributes && labels[i].attributes["for"] && labels[i].attributes["for"].value)
			labels[i].attributes["for"].value = labels[i].attributes["for"].value.split("_")[0] + "_" + this.count;

		labels[i].innerHTML = labels[i].innerHTML.replace(" a ", " another ")
		labels[i].innerHTML = labels[i].innerHTML.replace(" an ", " another ");
		
	}labels=null;
	
	var hrs = copy.getElementsByTagName("hr");
	for(var i=0; i<hrs.length; i++)
	{
		hrs[i].style.display = "block";
	
	}				
	
	var pees = copy.getElementsByTagName("p");
	for(var i=pees.length-1; i>=0; i--)
	{
		if(pees[i].className == 'fielderror')
			pees[i].parentNode.removeChild(pees[i]);
	
	}pees=null;
	
	var anchors = copy.getElementsByTagName("a");
	for(var i=0; i<anchors.length; i++)
	{
		
		this.incrementIdentity(anchors[i]);
		
		if(anchors[i].href && anchors[i].href.indexOf('javascript:Remove()') != -1)
		{			
			anchors[i].href = anchors[i].href.replace('javascript:Remove()', 'javascript:RemoveElement("' + copy.id + '");');
			
		}		
	}anchors=null;

	this.prev.parentNode.insertBefore(copy, this.prev);//this.prev.nextSibling);
	
	// Create a doubly linked list
	this.prev.next = copy;
	copy.prev = this.prev;
	copy.next = this;
	this.prev = copy;
	
	this.count++;
}

function incrementId(element){
		
		if(element.className =='error')
			element.className = '';			
		
				
		for (i=0; i<element.attributes.length; i++)
		{
			var pos = element.attributes[i].value.indexOf("[AddKeyHere]");
			if (pos>=0)
			{					
				element.attributes[i].value = replaceAll(element.attributes[i].value, '[AddKeyHere]', '_' + this.count.toString());				
			}
			
		}
		
		if(element.id)
		{				
			//Check if the id itself has an underscore			
			if (element.id.split("_")[1] == '' || typeof(element.id.split("_")[1]) == 'undefined')			
				element.id = element.id.split("_")[0] + "_" + this.count;			
			else
				element.id = element.id.split("_")[0] + "_" + element.id.split("_")[1] + "_" + this.count;
		}
					
		if(element.name)
		{	
			//Check if the name itself has an underscore			
			if (element.name.split("_")[1] == '' || typeof(element.id.split("_")[1]) == 'undefined')			
				element.name = element.name.split("_")[0] + "_" + this.count;							
			else
				element.name = element.name.split("_")[0] + "_" + element.name.split("_")[1] + "_" + this.count;			
		}		

		
			
		if(document.getElementById("Proxy_"+element.id))
		{
			var before = this.id + "::"+ element.id+"::\n"+element.value;
			element.value = document.getElementById("Proxy_"+element.id).innerHTML;
			if(element.targetCombo) element.targetCombo.doFilter();
			// Handy for debuggering:
			//alert(before+"\n"+element.value);
		}
	
	};


/************************************************************************/ 
// RemoveElement ... when the remove link is clicked on
/************************************************************************/ 
function RemoveElement(ElementToBeRemoved){
	var toBeRemoved = document.getElementById(ElementToBeRemoved)

	if (toBeRemoved)
		toBeRemoved.parentNode.removeChild(toBeRemoved);
	//if (ev)
	//	ev.preventDefault()
}

function getTheTotal(){ 

		var p = this.prev;
		var count = 2; // The existing one plus the new one
		while(p.prev)
		{
			p = p.prev;
			count++
		}
		return count;		
	};
	
function getTotalValue(outerDiv, partField)
{		
	var total = 0;
	var divs = findElement(this.document, outerDiv, 'Div');		
	var inputs = findElement(divs, partField, 'input');
	for (i=0; i<inputs.length; i++)
	{
		total = total + toInt(inputs[i]);
	}	
	return Number(total);
}

function findElement(rootElement, elmentName, tagType)
{
	var tags = document.getElementsByTagName(tagType);
	var fields = new Array();
	var count = 0;	
	for (i=0; i<tags.length; i++)
	{	
		//alert(i);		
		if (tags[i].id != '')
		{			
			var pos = tags[i].id.indexOf(elmentName);
			if (pos>=0)
			{				
				//return tags;
				fields[count] = tags[i];
				count = count + 1;				
			}
		}
	}				
	return fields;
}




