
// Create a new calculator object
var FSC = new FSCalc();

$(document).ready(function(){

	// Form reset button
	$('#formreset').click(function(){
		$('#calculatedFields input').val(''); // $('#calculatedFields input').each(function() { $(this).val('') });
	});

	// Empty all fields/uncheck all radios
	$('#Calculator input[type="text"]').val('');
	$('#Calculator input[type="radio"]').attr('checked',false)

	// deactive fields in inactive sections
	$('fieldset.inactive input').attr('disabled',true);

	// If presets are set, fill out form
	if(FSCpresets) {
		for(p in FSCpresets) {
			// if it's a yes/no radio
			if(FSCpresets[p] === 'yes' || FSCpresets[p] === 'no') {
				// check to appropriate radio
				$("input:radio[@name='"+p+"'][@value='"+FSCpresets[p]+"']").attr('checked','checked');
			}
			// Otherwise it's a number, set the form field w/ the correct value
			else {
				$('#'+p).val(FSCpresets[p]);
				updateAll();
			}
		}
	}

	// Hidden by default so noscript users see only the noscript message, show it
	$("#Calculator").show();

	// Focus on the first field
	$('#monthlyEarned').focus();
	
	// -- Help popup/overlay ----------------------
	$('#helpWindow').jqm({
		trigger: 'a.help',
		onHide: function(hash) {
			hash.o.remove();
			hash.w.hide();
			$('#helpText').html('Please wait... <img src="images/busy.gif" alt="loading" />');
		}
	});

	$('a.help').click(function() {
		var helpfile = 'help/'+ $(this).attr('href').substr(6) + '.html';
		$('#helpText').load(helpfile);
	});

	// "get link" link and pop-over window
	$('#linkWindow').jqm({
		trigger: '.getLink'
	});
	$('.getLink').click(function(){
		var link = getCalculatorLink();
		$('a.calcLink').attr('href',link);
		$('input.calcLinkInput').val(link).select().focus();
		return false;
	});

	// "print" link
	$('.print').click(function() {
		window.open(getPrintableLink(), 'print');
		return false;
	});


	// "results" window
	$('#resultsWindow').jqm({
		trigger: '#showResultsLink'
	});
	$('#showResultsLink').click(function(){
		var link = getCalculatorLink();
		$('a.calcLink').attr('href',link);
		$('input.calcLinkInput').val(link).select().focus();
		$('#resultsMax').html(FSC.getMaxAllotment());
		$('#resultsAllotment').html(FSC.fval('allotment')?FSC.fval('allotment'):'0');
	});

	// -- Input field change detection --------------------------
	var poll = null;
	$('#Calculator input[type="text"]')
	.change(function() {
		$(this).trigger('calcChange');
	})
	.focus(function(){
		var $that = $(this);
		var prev = $that.val();
		poll = setInterval(function(){
 			if($that.val() != prev) {
		 		prev = $that.val();
 				$that.change();				
 			}
		}, 200);
	})
	.blur(function(){
		clearInterval(poll);
	});

	$('#Calculator input[type="radio"]').click(function() {
		$(this).trigger('calcChange');
	});


	// -- Handle input field changes ------------------------------
	$('#Calculator input').bind('calcChange', function(){
		var id = $(this).attr('id');
		var val = $(this).val();
		log(id + " changed to "+ val);

		updateAll();
		
	});
	
}); // end DOM Ready

function updateAll() {
	// Refresh calculator-held values
	FSC.refresh();

	// TODO make this intelligent
	$('#GMI').val(FSC.fval('grossIncome'));
	$('#ME20').val(FSC.fval('ME20'));
	$('#stdDeduction').val(FSC.fval('stdDeduction'));
	$('#daycareDeduction').val(FSC.fval('daycareDeduction'));
	$('#childsupportDeduction').val(FSC.fval('childsupportDeduction'));
	$('#medDeduction').val(FSC.fval('medDeduction'));
	$('#homelessDeduction').val(FSC.fval('homelessDeduction'));
	$('#adjustedIncome').val(FSC.fval('adjustedIncome'));
	$('#totalHousing').val(FSC.fval('totalHousing'));
	$('#shelterDifference').val(FSC.fval('shelterDifference'));
	$('#shelterDeduction').val(FSC.fval('shelterDeduction'));
	$('#monthlyNet').val(FSC.fval('monthlyNet'));
	$('#allotment').val(FSC.fval('allotment'));

	// -- Income section ---------------------------------
	// If income is complete, activate fieldset#household
	if(($('#monthlyEarned').val()) != '' && ($('#monthlyUnearned').val()) != '' &&  FSC.grossIncome >= 0) {
		$('fieldset#Household').removeClass('inactive');
		$('fieldset#Household input').attr('disabled', false);
	}
	else {
		$('fieldset#Household').addClass('inactive');
		$('fieldset#Household input').attr('disabled', true);			
	}
	
	
	// -- Household section --------------------------
	// only show children/dependents if HH > 1 person
	if(FSC.hhSize > 1) {
		$('label[for=numChildren], label[for=numDependents]').show();
	}
	else {
		$('label[for=numChildren], label[for=numDependents]').hide();
	}
	
	// only show daycare if there are children under 2
	if(FSC.numChildren >= 1 || FSC.numDependents >= 1 ) {
		$('label[for=monthlyDaycare]').show();
	}
	else {
		$('label[for=monthlyDaycare]').hide();
		$('#monthlyDaycare').val('');
	}
	
	// only show medical expenses if senior/disabled
	if(FSC.hasDisabled) {
		$('label[for=monthlyDisabled]').show();			
	}
	else {
		$('label[for=monthlyDisabled]').hide();
		$('#monthlyDisabled').val('');			
	}
	
	// If household is complete, activated housing
	var HHcomplete = false;

	// households of 1
	if(FSC.hhSize == 1) {
		// make sure senior/disabled is checked
		if($("input:radio[@name='hasDisabled']:checked").val() == 'no') {
			HHcomplete = true;
		}
		// Make sure we have medical expenses if disabled/senior
		else if( $("input:radio[@name='hasDisabled']:checked").val() == 'yes' ) {
			if($('#monthlyDisabled').val() != '') HHcomplete = true;
		}
	}

	// households of > 1
	else if(FSC.hhSize > 1) {
		
		// make sure senior/disabled is checked
		if($("input:radio[@name='hasDisabled']:checked").val() == 'no') {
			HHcomplete = true;
		}
		// Make sure we have medical expenses if disabled/senior
		else if( $("input:radio[@name='hasDisabled']:checked").val() == 'yes' ) {
			if($('#monthlyDisabled').val() != '') HHcomplete = true;
		}
		
		// make sure we have values in numChildren, numDependents
		if($('#numChildren').val() == '' || $('#numDependents').val() == '') HHcomplete = false;
		
		// if numChildren || numDependents, make sure we have daycare
		if(FSC.numChildren + FSC.numDependents >= 1) {
			if($('#monthlyDaycare').val() == '') HHcomplete = false;
		}
	}

	if(HHcomplete) {
		$('fieldset#Housing').removeClass('inactive');
		$('fieldset#Housing input').attr('disabled', false);
	}
	else {
		$('fieldset#Housing').addClass('inactive');
		$('fieldset#Housing input').attr('disabled', true);			
	}

	// -- Housing section --------------------------
	
	// If homeless we need to calculate the verified deduction
	// otherwise , they get unverified deduction
	if($("input:radio[@name='isHomeless']:checked").val() == 'no') {
		$('label[for=housingCosts], #payHeatWrapper').show();

		if($("input:radio[@name='payHeat']:checked").val() == 'no') {
			$('#payUtilsWrapper').show();
		}
		else {
			$('#payUtilsWrapper, #payPhoneWrapper').hide();
			if(HHcomplete && $('#housingCosts').val() !== "" && $("input:radio[@name='payHeat']:checked").length) { 
				showShowResults();
			}
		}
		
		if($("input:radio[@name='payUtils']:checked").val() == 'no') {
			$('#payPhoneWrapper').show();
		}
		else {
			$('#payPhoneWrapper').hide();
			if(HHcomplete && $('#housingCosts').val() !== "" && $("input:radio[@name='payUtils']:checked").length) { 
				showShowResults();
			}
		}

		if(HHcomplete && $('#housingCosts').val() !== "" && $("input:radio[@name='payPhone']:checked").length) { 
			showShowResults();
		}

	}
	else {
		$('.notHomeless').hide();
		$('#housingCosts').val('');
		$('fieldset#Housing input[type=radio].utils').attr('checked',false);
		if(HHcomplete && $("input:radio[@name='isHomeless']:checked").length ) { 
			showShowResults();
		};
	}	

}



// generate a link to this page with form values as GET params
function getCalculatorLink() {

	var base = window.location.href;

	// Strip off previous get params and ? if exists,
	var qloc = base.indexOf('?');
	if(qloc > -1) base = base.substr(0, qloc);

	return base +'?'+ $('#CalculatorForm').serialize();
}

// Gets link to printable result
function getPrintableLink() {
	// Get regular link, append calculated fields to serialized values
	var calcLink = getCalculatorLink();
	// enable disabled form fields so .serialize works
	$('#calculatedFieldsForm input').attr('disabled',false);
	calcLink += '&'+ $('#calculatedFieldsForm').serialize();
	$('#calculatedFieldsForm input').attr('disabled',true);

	// replace calculator.php with calculator-print.php, which is lame but whatever
	return calcLink.replace('calculator.php','calculator-print.php');
}

function showShowResults() {
	// If monthly alottment is empty, set to 0
	if($('#allotment').val() === "") {
		$('#allotment').val("0");
	}
	$('.showResults').show();
}
