function CommaFormatted(amount) {
	amount = new String(amount);
	var neg = '';
	if(/-/.test(amount)) {
		neg = "-";
		amount = amount.replace("-", "");
	}
	var delimiter = ",";
	var n = amount.split(".")[0];
	var d = amount.split(".")[1];
	var a = [];
	while(n.length > 3)
	{
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0) { 
		a.unshift(n); 
	}
	n = a.join(delimiter);
	amount = neg + n + "." + d;
	return amount;
}

function writeSavingsToPage(country) {
	if(country == "au") {
		// PAYG/AGENCY
		var a = new Number($('#yearly_income').attr("value").replace(",", ""));
		var b = a / 1.09;
		var c;
		// work out c
		if(b > 150000) c = (b - 150000) * 0.45 + 47100;
		else if(b > 75000) c = (b - 75000) * 0.4 + 17100;
		else if(b > 30000) c = (b - 30000) * 0.3 + 3600;
		else if(b > 6000) c = (b - 6000) * 0.15;
		else c = 0;

		// write to workable variables
		var net_pay = b - c;
		var effective_tax_rate = c / a * 100;
		var annual_saving = 0;
		var monthly_net_pay = (b - c) / 12;
		
		// write to DOM
		$('fieldset#result table tbody tr:eq(0) td:eq(1)').empty().append(CommaFormatted(new Number(a).toFixed(2)));
		$('fieldset#result table tbody tr:eq(1) td:eq(1)').empty().append(CommaFormatted(new Number(net_pay).toFixed(2)));
		$('fieldset#result table tbody tr:eq(2) td:eq(1)').empty().append(CommaFormatted(new Number(effective_tax_rate).toFixed(2)));
		$('fieldset#result table tbody tr:eq(3) td:eq(1)').empty().append(CommaFormatted(new Number(annual_saving).toFixed(2)));
		$('fieldset#result table tbody tr:eq(4) td:eq(1)').empty().append(CommaFormatted(new Number(monthly_net_pay).toFixed(2)));
		
		// INDEPENDENT CONTRACTOR
		var b = (a / 1.066) * 0.7;
		var c;
		// work out c
		if(b > 150000) c = (b -150000) * 0.45 + 47100;
		else if(b > 75000) c = (b-75000) * 0.4 + 17100;
		else if(b > 30000) c = (b - 30000) * 0.3 + 3600;
		else if(b > 6000) c = (b - 6000) * 0.15;
		else c = 0;
		var d = (a / 1.066) * 0.3;
		var e;
		// work out e
		if(d > 150000) e = (d - 150000) * 0.45 + 47100;
		else if(d > 75000) e = (d - 75000) * 0.4 + 17100;
		else if(d > 30000) e = (d - 30000) * 0.3 + 3600;
		else if(d > 6000) e = (d - 6000) * 0.15;
		else e = 0;
		var f = c + e;
		
		// write to workable variables
		var net_pay = a - (a * 0.066) - f;
		var effective_tax_rate = f/a * 100;
		var annual_saving = c - f;
		var monthly_net_pay = (a - (a * 0.066) - f) /12;
		// write to DOM
		$('fieldset#result table tbody tr:eq(0) td:eq(2)').empty().append(CommaFormatted(new Number(a).toFixed(2)));
		$('fieldset#result table tbody tr:eq(1) td:eq(2)').empty().append(CommaFormatted(new Number(net_pay).toFixed(2)));
		$('fieldset#result table tbody tr:eq(2) td:eq(2)').empty().append(CommaFormatted(new Number(effective_tax_rate).toFixed(2)));
		$('fieldset#result table tbody tr:eq(3) td:eq(2)').empty().append(CommaFormatted(new Number(annual_saving).toFixed(2)));
		$('fieldset#result table tbody tr:eq(4) td:eq(2)').empty().append(CommaFormatted(new Number(monthly_net_pay).toFixed(2)));
	}
	
	if (country == "uk") {
		// Agency PAYE
		var a = new Number($('#yearly_income').attr("value").replace(",", ""));
		var b = a;
		var c;
		// work out c
		if(a > 34600) c = (a - 34600) * 0.4 + 7344;
		else if(a > 7451) c = (a - 7451) * 0.22 + 2230;
		else if(a>5220) c = (a - 5220) * 0.1;
		else c = 0;
		
		if(a > 5225) d = (a - 5225) * 0.11;
		else d = 0;

		// write to workable variables
		var net_pay = a - c - d;
		var effective_tax_rate = c / a * 100;
		var annual_saving = 0;
		var monthly_net_pay = (a - c - d) / 12;
		
		// write to DOM
		$('fieldset#result table thead tr:eq(1) td:eq(1)').empty().append("Agency PAYE");
		
		$('fieldset#result table tbody tr:eq(0) td:eq(1)').empty().append(CommaFormatted(new Number(a).toFixed(2)));
		$('fieldset#result table tbody tr:eq(1) td:eq(1)').empty().append(CommaFormatted(new Number(net_pay).toFixed(2)));
		$('fieldset#result table tbody tr:eq(2) td:eq(1)').empty().append(CommaFormatted(new Number(effective_tax_rate).toFixed(2)));
		$('fieldset#result table tbody tr:eq(3) td:eq(1)').empty().append(CommaFormatted(new Number(annual_saving).toFixed(2)));
		$('fieldset#result table tbody tr:eq(4) td:eq(1)').empty().append(CommaFormatted(new Number(monthly_net_pay).toFixed(2)));
		
		// Freelance PAYE
		var b = a - (a * 3.06) - 8000;
		var e;
		// work out e
		if(b > 34600) e = (b - 34600) * 0.4 + 7344;
		else if(b > 7451) e = (b - 7451) * 0.22 + 2230;
		else if(b > 5220) e = (b - 5220) * 0.1;
		else e = 0;
		
		var f;
		// work out f
		if(b > 5225) f = (b - 5225) * 0.11;
		else f = 0;
		
		// write to workable variables
		var net_pay = a - e - f;
		var effective_tax_rate = e/a * 100;
		var annual_saving = (a - c - d) - (a - e - f);
		var monthly_net_pay = (a - e - f) / 12;

		// write to DOM
		$('fieldset#result table thead tr:eq(1) td:eq(2)').empty().append("Freelance PAYE");
		
		$('fieldset#result table tbody tr:eq(0) td:eq(2)').empty().append(CommaFormatted(new Number(a).toFixed(2)));
		$('fieldset#result table tbody tr:eq(1) td:eq(2)').empty().append(CommaFormatted(new Number(net_pay).toFixed(2)));
		$('fieldset#result table tbody tr:eq(2) td:eq(2)').empty().append(CommaFormatted(new Number(effective_tax_rate).toFixed(2)));
		$('fieldset#result table tbody tr:eq(3) td:eq(2)').empty().append(CommaFormatted(new Number(annual_saving).toFixed(2)));
		$('fieldset#result table tbody tr:eq(4) td:eq(2)').empty().append(CommaFormatted(new Number(monthly_net_pay).toFixed(2)));

		// Limited Coy
		var b = a - (a * 0.35);
		var g;
		if(b > 34600) g = (b - 34600) * 0.4 + 7344;
		else if(b > 7451) g = (b - 7451) * 0.22 + 2230;
		else if(b > 5220) g = (b - 5220) * 0.1;
		else g = 0;
		
		var h;
		if(b > 5225) h = (b - 5225) * 0.11 + 52;
		else h = 52;
		
		// write to workable variables
		var net_pay = a - g - h;
		var effective_tax_rate = g / a * 100;
		var annual_saving = (a - c - d) - (a - g - h);
		var monthly_net_pay = (a - g - h) / 12;

		// add extra column
		$('fieldset#result table tr').append("<td></td>");

		// write to DOM
		$('fieldset#result table thead tr:eq(1) td:eq(3)').empty().append("Limited Coy");
		
		$('fieldset#result table tbody tr:eq(0) td:eq(3)').empty().append(CommaFormatted(new Number(a).toFixed(2)));
		$('fieldset#result table tbody tr:eq(1) td:eq(3)').empty().append(CommaFormatted(new Number(net_pay).toFixed(2)));
		$('fieldset#result table tbody tr:eq(2) td:eq(3)').empty().append(CommaFormatted(new Number(effective_tax_rate).toFixed(2)));
		$('fieldset#result table tbody tr:eq(3) td:eq(3)').empty().append(CommaFormatted(new Number(annual_saving).toFixed(2)));
		$('fieldset#result table tbody tr:eq(4) td:eq(3)').empty().append(CommaFormatted(new Number(monthly_net_pay).toFixed(2)));
	}
}

// hide navigation function - made external so flash can access it
function hideNavigation() {
	if($('div#navigation').css("display") == "inline") {
		$('div#navigation').hide();
	}
}

// DOM ready Events
$(function () {
	
	/*
	
	Show/hide subscribe box
	
	*/
	$('#emailsubscribe').hide();
	
	$('#subscribe_link').click(function() {
		$('#emailsubscribe').toggle();
		$('#news').toggle();
	})
	
	/*
	
	Navigation events
	
	*/
	
	if($('#contentpage')[0]) {
		$('#contentpage #hero').hover( function() {
			$(this).addClass("over");
			$('#logo').addClass("hover");
		}, function() {
			$(this).removeClass("over");
			$('#logo').removeClass("hover");
		});

		$('#contentpage #logo').hover( function() {
			$('#hero').addClass("over");
		}, function() {
			$('#hero').removeClass("over");
		});
	
		// header area click
		$('#contentpage #logo, #contentpage #hero').click( function() {
			// set navigation height
			$('div#navigation').css("height", $('#hero')[0].offsetHeight + $('#banner .columnwrap')[0].offsetHeight);
			if($('div#navigation').html().length == 0) {
				// load flash
				var so = new SWFObject("/templates/freelance/flash/preloader.swf", "navigation_swf", "950", "100%", "7", "#000000");
				so.write("navigation");
			}
			// show navigation
			$('div#navigation').css("display", "inline");
			// disable default event
			return false;
		});
		
		// navigation rolloff
		$('#subbanner, #content').hover(function(){
			hideNavigation();
		}, function() {});
		
		/*
		
		Earning calculator rules
		
		*/
		
		$('#working_weeks, #working_hours, #working_rate').keyup( function() {
			if($('#working_weeks').attr("value") && $('#working_hours').attr("value") && $('#working_rate').attr("value")) {
				$('#yearly_income').attr({ value: CommaFormatted(($('#working_weeks').attr("value") * $('#working_hours').attr("value") * $('#working_rate').attr("value")).toFixed(2)) });
			}
		});
		
		$('#yearly_income').keyup( function() {
			if($('#yearly_income').attr("value")) {
				$('#working_rate').attr({ value: ($('#yearly_income').attr("value").replace(",", "") / ($('#working_weeks').attr("value") * $('#working_hours').attr("value"))).toFixed(2) });
			}
		});
		
		$('#working_weeks, #working_hours, #working_rate').blur( function() {
			// if empty, set to 0
			if(!$(this).attr("value")) $(this).attr( { value: 0.00 });
			// trim to two decimal places
			$(this).attr( { value: new Number($(this).attr("value")).toFixed(2) });
		});
		
		$('#yearly_income').blur( function() {
			// if empty, set to 0
			if(!$(this).attr("value")) $(this).attr( { value: 0.00 });
			// trim to two decimal places
			$(this).attr( { value: CommaFormatted(new Number($(this).attr("value").replace(",","")).toFixed(2)) });
		});
		
		$('#calculate_earnings img, #recalculate img').hover( function() {
			$(this).attr({ src: $(this).attr("src").replace('.gif', '_1.gif')});
		}, function() {
			$(this).attr({ src: $(this).attr("src").replace('_1.gif', '.gif')});
		});
		
		$('#calculate_earnings').click( function() {
			if($('#working_rate').attr("value") == 0) {
				$('#working_rate').attr( { value: new Number(prompt("Please enter your hourly rate:", "")).toFixed(2) });
				$('#yearly_income').attr({ value: (Math.round($('#working_weeks').attr("value")) * Math.round($('#working_hours').attr("value")) * Math.round($('#working_rate').attr("value"))).toFixed(2) })
			}
			writeSavingsToPage(document.forms[1].country.options[document.forms[1].country.selectedIndex].value);
			$('fieldset#earning_calculator').hide();
			$('fieldset#result').show();
			$('select#country')[0].disabled = true;
			$('input#yearly_income')[0].disabled = true;
			return false;
		});
		
		$('#recalculate').click( function () {
			$('fieldset#earning_calculator').show();
			$('fieldset#result').hide();
			$('select#country')[0].disabled = false;
			$('input#yearly_income')[0].disabled = false;
			// remove additional column if necessary
			if($('fieldset#result table thead tr:eq(1) td:eq(3)')[0]) {
				$('fieldset#result table thead tr:eq(1) td:eq(3)').remove();

				$('fieldset#result table tbody tr:eq(0) td:eq(3)').remove();
				$('fieldset#result table tbody tr:eq(1) td:eq(3)').remove();
				$('fieldset#result table tbody tr:eq(2) td:eq(3)').remove();
				$('fieldset#result table tbody tr:eq(3) td:eq(3)').remove();
				$('fieldset#result table tbody tr:eq(4) td:eq(3)').remove();
			}
			return false;
		})
	};
	
	/*
	
	Create anchors from content areas: See anchor_create.js for more details
	
	*/
	
	if($('div#pagecontents ul').length > 0) {
		new Anchors($('p.pagesection'), $('div#pagecontents ul'), 'li', $('div.column h2'));
		// add forward/back jump links
		$('p.pagesection span.location').each(function(i) {
			var length = $('p.pagesection').length;
			// if first and last
			if(i == 0 && i == (length - 1)) {
				$(this).append((i + 1) + '/' + length);
			} else
			// if first
			if(i == 0) {
				$(this).append((i + 1) + '/' + length +  ' <a href="#anchor_' + (i + 1) + '">&rarr;</a>');
			} else
			// if last
			if(i == (length - 1)) {
				$(this).append('<a href="#anchor_' + (i - 1) + '">&larr;</a> ' + (i + 1) + '/' + length);
			}
			// else
			else {
				$(this).append('<a href="#anchor_' + (i - 1) + '">&larr;</a> ' + (i + 1) + '/' + length +  ' <a href="#anchor_' + (i + 1) + '">&rarr;</a>');
			}
		});
		// add scrollto events to any anchor element within div#pagecontents ul
		$('div#pagecontents ul a, p.pagesection span.location a').click(function() {
			$("#" + this.href.split("#")[1]).ScrollTo(150);
			return false;
		});
		$('a.backtotop').click(function() {
			$('div#page').ScrollTo(150);
			return false;
		})
	};
	
	/*
	
	Select default country
	
	*/
	
	// hide state selector
	
	$("select#country").change(function() {
		if($(this).val() != "Australia") {
			$("select#state").hide();
			$("#state-label").hide();
		} else {
			$("select#state").show();
			$("#state-label").show();
		}
	});
	
	/*if($('select#country')[0]) {
		var splitBySlashes = document.location.href.split("/");
		var auMatch = new RegExp('au');
		var ukMatch = new RegExp('uk');
		
		if(auMatch.test(splitBySlashes[splitBySlashes.length - 2])) {
			$('select#country option:eq(0)')[0].selected = true;
		}
		if(ukMatch.test(splitBySlashes[splitBySlashes.length - 2])) {
			$('select#country option:eq(1)')[0].selected = true;
		}
	}*/
});