﻿/*
appportal.js

Code specific to Community Services, Department of Human Services NSW Application Portal (more generic methods found in tools.js)
*/


function SaveWarning() {
	var msg = "WARNING! \n\nIf you leave this page without saving, any new data entered (or changes) will be lost.";
	msg += "\n\nTo make sure you have saved, please click [Cancel] and then use the [Save and go to previous section] or [Save and go to next section] buttons.";
	msg += "\n\nIf after clicking this button you remain in this section, it means that there is a problem with your data and it HAS NOT BEEN SAVED.";
	msg += "\n\nTherefore, you need to scroll to the bottom of the page, read the red error message and correct the invalid data.";
	msg += "\n\nThen click the [Save and go to previous section] or [Save and go to next section] buttons again to save.";
	msg += "\n\nIf you are sure you have saved, click [OK] to leave this page.";
	return confirm(msg);
}

// hide submit button (prevent double submission)
// apparently a later version of ASP.NET will include a Button attribute DisableOnSubmit="true"
// if so delete this and use that.
function HideButton(Button) {
	// hide
	Button.className += " unpressable";
	
	// bring it back (if not submitted because of client-side validators etc) after 10 secs
	setTimeout("ShowHiddenButtons();", 10000);
}
function ShowHiddenButtons() {
	$(".unpressable").removeClass("unpressable");
}

function MakeHelpLink(AnchorName) {
	var s = "<a href='Public/Help.htm#" + AnchorName + "' target='blank'>";
	s += "<img src='media/images/other/questionmark16.gif' title='Click to see help for this question' />";
	s += "</a>";
	return s;
}

// moves lower task rows up if you delete a task row
function MoveRowUp(ControlId) {

	// eg: get "3" from "CapacityBuilding_Using_community_infrastructure-3-TaskTextBox"
	var rowIndex = parseInt(GetAt(ControlId, "-", 1));

	// get task description and timeframe from next task row down
	var nextRowTaskBoxId = ControlId.replace(rowIndex, rowIndex + 1)
	var nextRowTaskVal = $("#" + nextRowTaskBoxId).val();
	var nextRowTimeVal = $("#" + nextRowTaskBoxId).parent().next().children(0).val();

	// replace current row (which is blank) with next row's values
	$("#" + ControlId).val(nextRowTaskVal);
	$("#" + ControlId).parent().next().children(0).val(nextRowTimeVal);

	// empty the next row's boxes
	$("#" + nextRowTaskBoxId).val("");
	$("#" + nextRowTaskBoxId).parent().next().children(0).val("");

	// if the row after has values, cascade those down to, and so on
	var afterNextRowTaskBoxId = nextRowTaskBoxId.replace(rowIndex + 1, rowIndex + 2)
	var afterNextRowTaskVal = $("#" + afterNextRowTaskBoxId).val();
	var afterNextRowTimeVal = $("#" + afterNextRowTaskBoxId).parent().next().children(0).val();
	if (afterNextRowTaskVal != null || afterNextRowTimeVal != null) {
		MoveRowUp(nextRowTaskBoxId);
	}

	// get next row's id and delete it
	//var rowId = $("#" + ControlId).parent().parent().attr("id");
	//DeleteTaskRow(rowId);
}

function ValidateTaskName(ControlId, RowIndex, IsFirstTaskRow) {

	StripPunctuationFromTag(ControlId);

	var taskVal = $("#" + ControlId).val();
	if (taskVal == "") {
		var timeBoxId = ControlId.replace("TaskTextBox", "TimeFrameTextBox");
		var timeVal = $("#" + timeBoxId).val();
		if (timeVal != "") {
			alert("Task description is missing for " + ControlId + ". If you enter the months under timeframe, you must also enter a task description.");
		}
		else {
			// row is totally blank, move up
			MoveRowUp(ControlId);
		}
	}
	
}

function ValidateTimeframe(ControlId) {

	// prepare an error message to check the value
	var isValid = true;
	var msg = "Invalid number of months in Timeframe for task " + ControlId + ". ";
	var val = $("#" + ControlId).val();

	if (val != "") {
		// check it's a number
		if (isNaN(val)) {
			msg += "The value given is not a number. ";
			isValid = false;
		}
		// check it's <=36 and >=1
		else if (val < 1 || val > 36) {
			msg += "The number of months must be between 1 and 36. ";
			isValid = false;
		}

	}
	else {

		// check if the task box is also blank
		var taskBoxId = $("#" + ControlId).parent().prev().children(0).attr("id");
		var taskBoxVal = $("#" + taskBoxId).val();
		if (taskBoxVal == "") {
			// both blank, move row up
			MoveRowUp(taskBoxId, false);
		}
		else {
			// task is not blank, only timeframe
			msg += "For each task you enter, you must also enter the timeframe in months. ";
			isValid = false;
		}
	}


	// if invalid, delete it and tell them
	if (isValid == false) {
		alert(msg);
		$("#" + ControlId).val("");
	}	 
}


// There are certain JS scripts/functions that run after certain events,
// e.g.: when you click other, a function runs to make the "specify other" tect box appear
// this function runs all of them (handy for when reloading answers from the DB, etc).
function RefreshClient() {

	// s1
	ToggleOther($("[id$='OrganisationTypeList']")[0], "OrgTypeOtherSpan");

	// s2
	Change2BTitle();
	ToggleEnabledByClass($("[id$='IsPartnerAgencyList']")[0], "Yes", "twoa");
	ToggleOther($("[id$='AgreementTypeList']")[0], "AgreementTypeOtherSpan");

	// s3
	ShowLgaList(true);
	UpdatePrimaryList();

	// s4
	ToggleOther($("[id$='CommunityOfIdentityList']")[0], "IdentityOtherSpan");
	ToggleOther($("[id$='PriorityGroupList']")[0], "PriorityGroupOtherSpan");
	ToggleDisplayById($("[id$='ConsultedList_2']")[0], "Other groups", "ConsultedOtherSpan");

	ToggleDisplayById($("[id$='MetObligationsYN']")[0], 'No', 'MetObligationsNoDiv');

	// show any previously selected activities
	ShowActivities($("input[id*='CapacityBuildingCheckBox']")[0], true);
	ShowActivities($("input[id*='SectorDevelopmentCheckBox']")[0], true);
	ShowActivities($("input[id*='SkillsDevelopmentCheckBox']")[0], true);

	ShowActivityTasks($("[id$='CapacityBuildingList_0']")[0], "CapacityBuilding", true);
	ShowActivityTasks($("[id$='CapacityBuildingList_1']")[0], "CapacityBuilding", true);
	ShowActivityTasks($("[id$='CapacityBuildingList_2']")[0], "CapacityBuilding", true);
	ShowActivityTasks($("[id$='CapacityBuildingList_3']")[0], "CapacityBuilding", true);
	ShowActivityTasks($("[id$='CapacityBuildingList_4']")[0], "CapacityBuilding", true);
	ShowActivityTasks($("[id$='SkillsDevelopmentList_0']")[0], "SkillsDevelopment", true);
	ShowActivityTasks($("[id$='SkillsDevelopmentList_1']")[0], "SkillsDevelopment", true);
	ShowActivityTasks($("[id$='SkillsDevelopmentList_2']")[0], "SkillsDevelopment", true);
	ShowActivityTasks($("[id$='SkillsDevelopmentList_3']")[0], "SkillsDevelopment", true);
	ShowActivityTasks($("[id$='SectorDevelopmentList_0']")[0], "SectorDevelopment", true);
	ShowActivityTasks($("[id$='SectorDevelopmentList_1']")[0], "SectorDevelopment", true);
	ShowActivityTasks($("[id$='SectorDevelopmentList_2']")[0], "SectorDevelopment", true);
	ShowActivityTasks($("[id$='SectorDevelopmentList_3']")[0], "SectorDevelopment", true);

	// budget
	SumByClassName("WagesCosts1", "SubTotalWagesYear1");
	SumByClassName("WagesCosts2", "SubTotalWagesYear2");
	SumByClassName("WagesCosts3", "SubTotalWagesYear3");
	//AddOnCosts('1'); happens in above calls anyway
	//AddOnCosts('2');
	//AddOnCosts('3');
	
	
	SumByClassName("AdminCosts1", "SubTotalAdminYear1");
	SumByClassName("AdminCosts2", "SubTotalAdminYear2");
	SumByClassName("AdminCosts3", "SubTotalAdminYear3");

	SumByClassName("ProjectCosts1", "SubTotalProjectCostsYear1");
	SumByClassName("ProjectCosts2", "SubTotalProjectCostsYear2");
	SumByClassName("ProjectCosts3", "SubTotalProjectCostsYear3");
	
	ShowElementIfNotBlank($("[id$='OtherYear1']")[0], 'ProjectCostsOtherSpan');
	ShowElementIfNotBlank($("[id$='OtherYear2']")[0], 'ProjectCostsOtherSpan');
	ShowElementIfNotBlank($("[id$='OtherYear3']")[0], 'ProjectCostsOtherSpan');

	ShowElementIfNotBlank($("[id$='AdminOtherYear1']")[0], 'AdminOtherSpan');
	ShowElementIfNotBlank($("[id$='AdminOtherYear1']")[0], 'AdminOtherSpan');
	ShowElementIfNotBlank($("[id$='AdminOtherYear1']")[0], 'AdminOtherSpan');


	//alert("Did a RefreshClient()");
}

function ShowLgaList(IsJustARefresh) {
	// hide all
	$("[id*='LgaList']").hide();

	// if user just changed regions, cancel all their old choices
	if (!IsJustARefresh) {
		$("[id*='LgaList']").val("");
	}
	
	var lgaList = ChooseLgaListByRegion();
	if (lgaList != null)
	{
		lgaList.show()	
		
		// also show div for choosing primary
		$("[id$='ChoosePrimaryDiv']").show();
	}
}

function ChooseLgaListByRegion() {

	// if a region chosen, 
	var region = $("[id*='RegionList']").val();
	if (region.length > 0) {

		// return lga list for that region
		var regionNoSpaces = region.split(' ').join('');
		return $("[id*='" + regionNoSpaces + "LgaList']");
	}
	else {
		return null;
	}
}

// Uses jquery.selectboxes.min.js (see http://www.texotela.co.uk/code/jquery/select/ )
function UpdatePrimaryList() {
	//$("[id*='MetroWestLgaList']").copyOptions("[id$='PrimaryList']");
	
	//CopyOptions($("[id*='MetroWestLgaList']"), "[id$='PrimaryList']");
	
//	var lgaList = ChooseLgaListByRegion();
//	lgaList.copyOptions("[id$='PrimaryList']");
}


function CopyOptions(from, to, which) {
	var w = which || "selected";
	if ($(to).size() == 0) return from;
	from.each(
		function() {
			if (from.nodeName.toLowerCase() != "select") return from;
			// get options
			var o = this.options;
			// get number of options
			var oL = o.length;
			for (var i = 0; i < oL; i++) {
				if (w == "all" || (w == "selected" && o[i].selected)) {
					$(to).addOption(o[i].value, o[i].text);
				}
			}
		}
	);
	return from;
};




function TestSection1() {

	$("[id*='AbnTextBox']")[0].value = '29007350629';
	$("[id*='TradingNameTextBox']")[0].value = 'TradingNameTextBox';
	$("[id*='OrganisationTypeList_3']").attr("checked", true); 	//Other
	$("#OrgTypeOtherSpan").show();
	$("[id*='OrgTypeOtherTextBox']")[0].value = 'OrgTypeOtherTextBox';
	$("[id*='IncorporationNumberTextBox']")[0].value = 'IncorpNumTextBox';
	$("[id*='GstList_1']").attr("checked", true);
	$("[id*='ContactTitleList']").val("Mr");
	$("[id*='ContactFirstNameTextBox']")[0].value = 'ContactFirstNameTextBox';
	$("[id*='ContactLastnameTextBox']")[0].value = 'ContactLastnameTextBox';
	$("[id*='ContactPositionTextBox']")[0].value = 'ContactPositionTextBox';
	$("[id*='ContactStreetTextBox']")[0].value = 'ContactStreetTextBox';
	$("[id*='ContactTownTextBox']")[0].value = 'ContactTownTextBox';
	$("[id*='ContactStateList']").val("NSW");
	$("[id*='ContactPostcodeTextBox']")[0].value = '2000';
	$("[id*='PostalStreetTextBox']")[0].value = 'PostalStreetTextBox';
	$("[id*='PostalTownTextBox']")[0].value = 'PostalTownTextBox';
	$("[id*='PostalStateList']").val("QLD");
	$("[id*='PostalPostcodeTextBox']")[0].value = '4001';
	$("[id*='ContactPhoneTextBox']")[0].value = '02 1111 2222';
	$("[id*='ContactFaxTextBox']")[0].value = '02 1111 3333';
	$("[id*='ContactMobileTextBox']")[0].value = '0411 111 222';
	$("[id*='ContactEmailTextBox']")[0].value = 'Contact@EmailTextBox.com';
	
	RefreshClient();
}
function TestSection2() {

	$("[id*='IsPartnerAgencyList_0']").attr("checked", true);
	$("[id*='AgreementTypeList_2']").attr("checked", true);
	$("[id*='AgreementTypeOtherSpan']").show();
	$("[id*='AgreementTypeOtherTextBox']").val("ATOther");
	$("[id*='PartnerAgencyNameTextBox']").val("PartnerAgencyNameTextBox");
	$("[id*='OrgTitleList']").val("Mr");
	$("[id*='OrgFirstNameTextBox']").val('OrgFirstNameTextBox');
	$("[id*='OrgLastnameTextBox']").val("OrgLastnameTextBox");
	$("[id*='OrgStreetTextBox']").val("OrgStreetTextBox");
	$("[id*='OrgTownTextBox']").val("OrgTownTextBox");
	$("[id*='OrgStateList']").val("NSW");
	$("[id*='OrgPostcodeTextBox']").val("2000");
	$("[id*='OrgPostalStreetTextBox']").val("OrgPostalStreetTextBox");
	$("[id*='OrgPostalTownTextBox']").val("OrgPostalTownTextBox");
	$("[id*='OrgPostalStateList']").val("VIC");
	$("[id*='OrgPostalPostcodeTextBox']").val("3001");
	$("[id*='OrgPhoneTextBox']").val("02 1111 3333");
	$("[id*='OrgFaxTextBox']").val("02 1111 4444");
	$("[id*='OrgMobileTextBox']").val("0411 222 333");
	$("[id*='OrgEmailTextBox']").val("Org@EmailTextBox.com");

	RefreshClient();
}


function TestSection3() {
	$("[id*='DirectServiceYN_1']").attr("checked", true);
	$("[id*='EligibleYN_1']").attr("checked", true);
	$("[id*='DuplicatingYN_1']").attr("checked", true);
	$("[id*='PreviouslyYN_1']").attr("checked", true);
	$("[id*='ExtensionYN_1']").attr("checked", true);
	$("[id*='OngoingYN_1']").attr("checked", true);
	$("[id*='DirectYN_1']").attr("checked", true);

	$("[id*='RegionList']").val("Metro West");
	ShowLgaList(false);
	$("[id*='MetroWestLgaList']").children("option:nth(2)").attr("selected", true);
	$("[id*='MetroWestLgaList']").children("option:nth(1)").attr("selected", true);

	$("[id*='CommunityStrengthList_0']").attr("checked", true);
	$("[id*='CommunityStrengthList_4']").attr("checked", true);

	$("[id*='CapacityBuildingCheckBox']").attr("checked", true);
	//$("[id*='SectorDevelopmentCheckBox']").val(0);
	$("[id*='SkillsDevelopmentCheckBox']").attr("checked", true);
	$("[id*='HowCapacityTextBox']").val("HowCapacityTextBox");

	RefreshClient();

	/*
	$("[id*='']").attr("checked", true;)
	$("[id*='']").val("");
	*/
}

function TestSection4() {


	$("[id*='CommunityOfLocationList']").children("option:nth(2)").attr("selected", true);

	$("[id*='CommunityOfIdentityList']").children("option:nth(20)").attr("selected", true);
	$("[id*='IdentityOtherTextBox']").val("IdentityOtherTextBox");

	$("[id*='PriorityGroupList']").children("option:nth(19)").attr("selected", true);
	$("[id*='PriorityGroupList']").children("option:nth(20)").attr("selected", true);
	$("[id*='PriorityGroupOtherTextbox']").val("PriorityGroupOtherTextbox");

	$("[id*='WhyPriorityTextBox']").val("WhyPriorityTextBox");
	$("[id*='HowHelpPriorityGroupsTextBox']").val("HowHelpPriorityGroupsTextBox");
	$("[id*='EvidenceOfSupportTextBox']").val("EvidenceOfSupportTextBox");
	$("[id*='EvidenceOfPriorityTextBox']").val("EvidenceOfPriorityTextBox");
	$("[id*='ConsultedList_0']").attr("checked", true);
	$("[id*='ConsultedOtherTextBox']").val("ConsultedOtherTextBox");
	$("[id*='ConsultationDescriptionTextBox']").val("ConsultationDescriptionTextBox");

	$("[id*='ProjectNameTextBox']").val("ProjectNameTextBox");
	$("[id*='ProjectResultsTextBox']").val("ProjectResultsTextBox");


	$("[id*='CapacityBuildingList_0']").attr("checked", true);
	$("[id*='SkillsDevelopmentList_0']").attr("checked", true);

	$("[id*='ExecutiveSummaryTextBox']").val("ExecutiveSummaryTextBox");
	$("[id*='HowResultsHelpTextBox']").val("HowResultsHelpTextBox");
	$("[id*='HowBuildCommunityTextBox']").val("HowBuildCommunityTextBox");
	$("[id*='HowEndTextBox']").val("HowEndTextBox");
	$("[id*='OrganisationCapacityTextBox']").val("OrganisationCapacityTextBox");
	$("[id*='ManagementTextBox']").val("ManagementTextBox");

	$("[id*='MetObligationsYN_1']").attr("checked", true);
	$("[id*='MetObligationsNoTextBox']").val("MetObligationsNoTextBox");
	$("[id*='DurationList_2']").attr("checked", true);
	$("[id*='TotalFundingTextBox']").val("30000");

	$("[id*='Wage1Position']").val("Wage1Position");
	$("[id*='Wage1Award']").val("wage1award wage1award wage1award ");
	$("[id*='Wage1Hours']").val("1");
	$("[id*='Wage1Year1']").val("1");
	$("[id*='Wage1Year2']").val("1");
	$("[id*='Wage1Year3']").val("1");
	$("[id*='Wage2Position']").val("Wage2Position");
	$("[id*='Wage2Award']").val("wage2award wage2award wage2award wage2award ");
	$("[id*='Wage2Hours']").val("2");
	$("[id*='Wage2Year1']").val("2");
	$("[id*='Wage2Year2']").val("2");
	$("[id*='Wage2Year3']").val("2");
	$("[id*='Wage3Position']").val("Wage3Position");
	$("[id*='Wage3Award']").val("wage3award wage3award wage3award wage3award ");
	$("[id*='Wage3Hours']").val("3");
	$("[id*='Wage3Year1']").val("3");
	$("[id*='Wage3Year2']").val("3");
	$("[id*='Wage3Year3']").val("3");
	$("[id*='OnCostYear1']").val("1");
	$("[id*='OnCostYear2']").val("1");
	$("[id*='OnCostYear3']").val("1");
	$("[id*='AuditYear1']").val("1");
	$("[id*='AuditYear2']").val("1");
	$("[id*='AuditYear3']").val("1");
	$("[id*='RentYear1']").val("1");
	$("[id*='RentYear2']").val("1");
	$("[id*='RentYear3']").val("1");
	$("[id*='AdminYear1']").val("1");
	$("[id*='AdminYear2']").val("1");
	$("[id*='AdminYear3']").val("1");
	$("[id*='AdminOtherYear1']").val("1");
	$("[id*='AdminOtherYear2']").val("1");
	$("[id*='AdminOtherYear3']").val("1");
	$("[id*='AdminOtherTextBox']").val("Cleaning");
	$("[id*='PrintingYear1']").val("1");
	$("[id*='PrintingYear2']").val("1");
	$("[id*='PrintingYear3']").val("1");
	$("[id*='AdvertisingYear1']").val("1");
	$("[id*='AdvertisingYear2']").val("1");
	$("[id*='AdvertisingYear3']").val("1");
	$("[id*='ConsultationsYear1']").val("1");
	$("[id*='ConsultationsYear2']").val("1");
	$("[id*='ConsultationsYear3']").val("1");
	$("[id*='CoordinationYear1']").val("1");
	$("[id*='CoordinationYear2']").val("1");
	$("[id*='CoordinationYear3']").val("1");
	$("[id*='EducationYear1']").val("1");
	$("[id*='EducationYear2']").val("1");
	$("[id*='EducationYear3']").val("1");
	$("[id*='TravelYear1']").val("1");
	$("[id*='TravelYear2']").val("1");
	$("[id*='TravelYear3']").val("1");
	$("[id*='TranslationYear1']").val("1");
	$("[id*='TranslationYear2']").val("1");
	$("[id*='TranslationYear3']").val("1");
	$("[id*='EvaluationYear1']").val("1");;
	$("[id*='EvaluationYear2']").val("1");;
	$("[id*='EvaluationYear3']").val("1"); ;
	$("[id*='InfrastructureYear1']").val("9980");
	$("[id*='InfrastructureYear2']").val("9980");
	$("[id*='InfrastructureYear3']").val("9980");
	$("[id*='OtherYear1']").val("1");
	$("[id*='OtherYear2']").val("1");
	$("[id*='OtherYear3']").val("1");
	$("[id*='ProjectCostsOtherTextBox']").val("ProjectCostsOtherTextBox");
	//$("[id*='GrandTotalYear1']").val("10000");
	//$("[id*='GrandTotalYear2']").val("10000");
	//$("[id*='GrandTotalYear3']").val("10000");
	$("[id*='OtherFundingSourceTextBox']").val("OtherFundingSourceTextBox");
	$("[id*='OtherFundingYear1TextBox']").val("1");
	$("[id*='OtherFundingYear2TextBox']").val("1");
	$("[id*='OtherFundingYear3TextBox']").val("1");
	$("[id*='NonMonetaryTextBox']").val("NonMonetaryTextBox");
	$("[id*='AuditCostsTextBox']").val("Audit will cost at least 1000");

	// update "other" toggles etc
	RefreshClient();
}



function AddOnCosts(ColumnNumber) {
	var sum = 0;

	var num = parseFloat($("span[id$='SubTotalWagesYear" + ColumnNumber + "']").text());
	if (!isNaN(num)) {
		sum += num;
	}
	num = parseFloat($("input[id$='OnCostYear" + ColumnNumber + "']").val());
	if (!isNaN(num)) {
		sum += num;
	}

	$("span[id$='SubTotalWagesOnCostsYear" + ColumnNumber + "']").text(sum);
}


function SumByClassName(ClassName, SumControlId) {
	var sum = 0;
	$("." + ClassName).each(function(i) {
		var num = parseFloat(this.value);
		if (!isNaN(num)) {
			sum += num;
		}
	});
	$("span[id*='" + SumControlId + "']").text(sum);

	// also total wages + on-costs
	if (ClassName.substring(0, 10) == "WagesCosts") {
		AddOnCosts("1");
		AddOnCosts("2");
		AddOnCosts("3");
	}

	// update the grand totals too
	UpdateGrandTotal(1);
	UpdateGrandTotal(2);
	UpdateGrandTotal(3);
}

function SumByClass(ClassElement, SumControlId) {
	var classToSum = ClassElement.className;
	SumByClassName(classToSum, SumControlId);
}

function UpdateGrandTotal(Year) {
	//alert('in UpdateGrandTotal()');
	var sub1 = parseFloat($("span[id$='SubTotalWagesOnCostsYear" + Year + "']").text());
	var sub2 = parseFloat($("span[id$='SubTotalAdminYear" + Year + "']").text());
	var sub3 = parseFloat($("span[id$='SubTotalProjectCostsYear" + Year + "']").text());
	var grand = sub1 + sub2 + sub3;
	$("span[id$='GrandTotalYear" + Year + "']").text(grand);
	//alert('grand=' + grand);
}

function ShowElementIfNotBlank(Control, ElementId) {
	var v = Control.value;
	if (!isNaN(v)) {
		var f = parseFloat(v);
		if (f > 0) {
			$("#" + ElementId).show()
		} 
	}
}

function EnableClassBySingleCheckBox(Control, ClassToToggle) {
	$("." + ClassToToggle).attr('disabled', Control.checked)
}

// checks a string is alphanumeric only
function StripPunctuation(source) {
	return source.replace(/[^\w ]/g, "");
}

function StripPunctuationFromTag(TagId) {
	var s = $("#" + TagId).val();
	$("#" + TagId).val(StripPunctuation(s));
}

function ShowActivityTasks(CheckBox, Category, RefreshOnly) {

	// figure out which activity this CheckBox applies to
	var activityListName = CheckBox.id.splitAndReturn("_", 1, true);
	var listIndex = CheckBox.id.splitAndReturn("_", 0, true);
	var activityName = $("label[for$='" + activityListName + "_" + listIndex + "']").text();
	var activityNameUnderscored = activityName.replace(/ /gi, "_");
	var activityFullName = Category + "_" + activityNameUnderscored;

	// if checked
	if (CheckBox.checked) {
		// create a task row for that activity
		CreateActivityRow(activityName, Category);

		// show table and title for task rows for this activity (may be visible already)
		$("#" + Category + "Table").show();
		$("#" + Category + "TableTitle").show();

	}
	// else delete task rows for this activity, if any
	else {
		
		// if this is a user clicking it, not a refresh, confirm they understand before deleting
		var deleteConfirmed = true;
		if (!RefreshOnly) {
			deleteConfirmed = confirm("This will delete any task information you have entered for this activity in question 11.\n\nPress OK to delete, otherwise press CANCEL:");
		}
		
		// delete task rows for this activity
		if (deleteConfirmed) {

			// remove task rows if any
			$("tr[id*='" + activityFullName + "']").remove();

			// remove add task button
			$("#" + activityFullName + "-NewButton").remove();

			// if that was the last row for this SAD category, hide table and title
			if ($("tr[id*='" + Category + "']").length == 0) {
				$("#" + Category + "Table").hide();
				$("#" + Category + "TableTitle").hide();
			}
		}
		else {
			CheckBox.checked = true;
		}
	}
}

function CreateActivityRow(ActivityName, Category) {
	CreateTaskOrActivityRow(true, ActivityName, Category);
}

function CreateTaskRow(ActivityName, Category) {
	CreateTaskOrActivityRow(false, ActivityName, Category);
}

function CreateTaskOrActivityRow(IsActivityNotTask, ActivityName, Category) {

	var taskLimit = 5; 		// max no of tasks per activity
	var taskMaxLength = 300; 	// max chars in task desc textbox

	var table = $("#" + Category + "Table")[0];
	var rowCount = table.rows.length;

	// create unique activity identifier for naming controls etc
	var activityNameUnderscored = ActivityName.replace(/ /gi, "_");
	// some duplicate activity names in different categories, so fully qualify
	var activityFullName = Category + "_" + activityNameUnderscored;

	// the number of tasks for this activity is stored in a hidden field.
	// we need it's name as we'll be either creating it or reading from it
	var activityTaskCountHiddenFieldName = activityFullName + "-CurrentCount";


	// check if task count already set for this activity
	var activityTaskCount;
	var val = $("#" + activityTaskCountHiddenFieldName).val();
	if (val == null || val == "") {
		activityTaskCount = 1;
	}
	else {
		activityTaskCount = parseInt(val);
	}

	// the activity row is the first task row for that activity, with the name in it
	var activityRowId = activityFullName + "-1";

	// treat first task row for activity differently (to additional task rows)
	var firstCellText;
	var rowId;
	var rowInsertPoint;



	if (IsActivityNotTask) {

		// if this activity is already in the table, quit (don't add it again)
		if ($("#" + activityRowId)[0] != null) {
			return;
		}

		firstCellText = ActivityName;
		rowId = activityRowId;
		rowInsertPoint = rowCount;
	}
	else {
		firstCellText = " ";

		// increment and save current count of activity tasks 
		activityTaskCount += 1;
		$("#" + activityTaskCountHiddenFieldName).val(activityTaskCount);

		rowId = activityFullName + "-" + activityTaskCount;
		rowInsertPoint = $("#" + activityRowId)[0].rowIndex + (activityTaskCount - 1);
	}

	// add row
	var row = table.insertRow(rowInsertPoint);
	row.id = rowId;


	// add first cell (activity name - or blank if task)
	var cell0 = row.insertCell(0);
	cell0.setAttribute("style", "width:14em;");
	cell0.setAttribute("width", "220"); // for ie6
	var textNode = document.createTextNode(firstCellText);
	cell0.appendChild(textNode);

	if (IsActivityNotTask) {
		// add the hidden field counting total task rows to that cell
		var hid = document.createElement("input");
		hid.type = "hidden";
		hid.name = activityTaskCountHiddenFieldName;
		hid.id = hid.name;
		hid.value = "1";
		cell0.appendChild(hid);
	}

	// middle cell (tasks)
	var cell1 = row.insertCell(1);
	var task = document.createElement("input");
	task.type = "text";
	//task.name = "Task" + rowCount + "TextBox";
	task.name = rowId + "-TaskTextBox";
	task.id = task.name;
	task.setAttribute("style", "width:20em;");
	task.setAttribute("width", "250"); // for ie6
	task.maxLength = taskMaxLength;
	//task.setAttribute("maxlength", taskMaxLength.toString());
	task.setAttribute("onkeyup", "StripPunctuationFromTag('" + task.id + "');"); // validation (alphanums only)
	task.setAttribute("onpaste", "StripPunctuationFromTag('" + task.id + "');"); // validation (alphanums only)
	task.setAttribute("onblur", "ValidateTaskName('" + task.id + "', " + activityTaskCount + ", " + IsActivityNotTask + ");"); // validation (alphanums only)
	cell1.appendChild(task);

	// last cell (timeframe)
	var cell2 = row.insertCell(2);
	var time = document.createElement("input");
	time.type = "text";
	//time.name = "TimeFrame" + rowCount + "TextBox";
	time.name = rowId + "-TimeFrameTextBox";
	time.id = time.name;
	time.className = "timeframebox";
	time.setAttribute("style", "width:30px;");
	time.setAttribute("width", "30"); // for ie6
	time.setAttribute("maxlength", "2");
	//time.setAttribute("onkeyup", "ValidateTimeframe('" + time.id + "');"); // validation (number, 1-36)
	time.setAttribute("onpaste", "ValidateTimeframe('" + time.id + "');"); // validation (number, 1-36)
	time.setAttribute("onblur", "ValidateTimeframe('" + time.id + "');"); // validation (number, 1-36)
	cell2.appendChild(time);

	// add " months"
	var monthsText = document.createTextNode(" months");
	cell2.appendChild(monthsText);

	/*
	// add delete button
	$(document.createElement("span"))
			.attr({ id: rowId + "-DeleteButton", name: rowId + "-DeleteButton", title: "delete this row" })
			.addClass("smallButton")
			.text("X")
			.appendTo(cell2)
			.click(function() { DeleteTaskRow(rowId); });
	*/

	// if limit not reached yet, allow adding tasks
	if (IsActivityNotTask) {
		// create an empty row for the [add task] button
		var newButtonRow = $(document.createElement("tr")).appendTo(table);
		$(document.createElement("td")).appendTo(newButtonRow);
		var midCell = $(document.createElement("td")).appendTo(newButtonRow);
		$(document.createElement("td")).appendTo(newButtonRow);

		// create [add task] button
		$(document.createElement("span"))
			.attr({ id: activityFullName + "-NewButton", name: activityFullName + "-NewButton" })
			.addClass("smallButton")
			.text("add another task")
			.appendTo(midCell)
			.click(function() { CreateTaskRow(ActivityName, Category) });

		// add spacer
		$(document.createElement("div")).html(" &nbsp; ").appendTo(midCell);
	}
	else if (activityTaskCount >= taskLimit) {
		// if limit reached, hide 'add another task' button
		$("#" + activityFullName + "-NewButton").hide();
	}


	// set answer if there is one already saved
	var existingAnswer = $("input[id*='" + rowId + "-Answer']").val();
	var existingAnswerName = "";
	var existingAnswerMonths = "";
	if (existingAnswer != null && existingAnswer != "") {
		existingAnswerName = existingAnswer.split('|')[0];
		existingAnswerMonths = existingAnswer.split('|')[1];
	}
	$("input[id*='" + rowId + "-TaskTextBox']").val(existingAnswerName);
	$("input[id*='" + rowId + "-TimeFrameTextBox']").val(existingAnswerMonths);

	// if there are more tasks for this activity, show those
	var savedCount;
	var sc = $("input[id*='" + activityFullName + "-SavedCount']").val();
	if (sc != null && sc != "") {
		savedCount = parseInt(sc);
		if (savedCount > activityTaskCount) {
			CreateTaskRow(ActivityName, Category);
		}
	}

}

// remove row and any hidden answer data
function DeleteRowIfBlankAndExtra(RowID) {
	$("tr[id*='" + RowID + "']").remove();
	$("input[id*='" + RowID + "']").remove();
}

function DeleteTaskRow(RowId) {

	// remove row and any hidden answer data
	$("tr[id*='" + RowId + "']").remove();
	$("input[id*='" + RowId + "']").remove();

	// decrement task row count for this activity
	var activityTaskCountHiddenFieldName = RowId.substring(0, RowId.length - 2) + "-CurrentCount";
	var activityTaskCount = $("#" + activityTaskCountHiddenFieldName).val();
	activityTaskCount -= 1;
	$("#" + activityTaskCountHiddenFieldName).val(activityTaskCount);
}



// When a top-level service activities list is checked, show the corresponding list. When unchecked, hide it.
// (if RefreshOnly, don't alert user about unclicking - they haven't just clicked it, it's just a refresh (e.g.: load existing page))
function ShowActivities(CheckBox, RefreshOnly) {

	// figure out which list this CheckBox applies to
	var listName = CheckBox.id.trimLeftUpToLast("_");
	listName = listName.replace("CheckBox", "");
	
	// show if checked, hide if unchecked
	var displayMode = "block";
	if (!CheckBox.checked) {
	
		// don't let them uncheck parent if any children are still checked, 
		// unless they're sure they want to delete it all
		if ($("input:checked[id*='" + listName + "']")[0] != null) {

			var deleteConfirmed = true;
			if (!RefreshOnly) {
				deleteConfirmed = confirm("This will delete any activity and task information you have entered for this SAD category in Section 4, questions 10 and 11.\n\nPress OK to delete, otherwise press CANCEL:");
			}

			if (deleteConfirmed) {

				// hide list
				displayMode = "none";
				
				// hide table and title (may be hidden already)
				$("#" + listName + "Table").hide();
				$("#" + listName + "TableTitle").hide();
				
				// remove task tr
				$("tr[id*='" + listName + "']").remove();
				
				// remove [add task] span's tr
				$("span[id*='" + listName + "'][id$='NewButton']").parent().parent().remove();
				
			}
			else {
				CheckBox.checked = true;
			}
		
		}
		else {
			displayMode = "none";
		}
	}

	// show/hide the corresponding list (and it's title label)
	$("span[id$='" + listName + "List']").css("display", displayMode);
	$("span[id$='" + listName + "Label']").css("display", displayMode);


	// if hiding, uncheck too
	if (displayMode == "none") {
		$("input[id*='" + listName + "List_']").attr('checked', false);
	}
}


// changes title of 2b depnding on whether applicant organisation or partnet agency
function Change2BTitle() {

	var yesOrNo = $("input:checked[id*='IsPartnerAgencyList']")[0];
	if (yesOrNo != null && yesOrNo.value == "Yes") {
		$("#TwoBTitle")[0].innerHTML = "2B: Partner Agency Details";
	}
	else {
		$("#TwoBTitle")[0].innerHTML = "2B: Applicant Organisation Details";
	}
}

// shows hidden rows
function ShowSectionOneQuestions() {
	$(".section1 tr").show();
}

function ToggleOther(Control, OtherId) {
	ToggleDisplayById(Control, "Other", OtherId); 
}

// Shows elements with the given class if the given list control (e.g.: radio button list) 
// has the given Value (otherwise, hides them). 
// e.g.: If 2.1 is "Yes", shows the section 2A rows.
function ToggleDisplayByClass(Control, Value, Class) {
	ToggleDisplay(Control, Value, Class, ".");
}

// Same as ToggleDisplayByClass() but uses element's id, not class name.
function ToggleDisplayById(Control, Value, Id) {
	ToggleDisplay(Control, Value, Id, "#");
}

// Same as ToggleDisplayByClass, but toggles whether elements are enabled or disabled.
function ToggleEnabledByClass(Control, Value, Class) {
	ToggleEnabled(Control, Value, Class, ".");
}
// Same as ToggleEnabledByClass, but uses element's id, not class name.
function ToggleEnabledById(Control, Value, Id) {
	ToggleEnabled(Control, Value, Id, "#");
}
// Toggle the display of elements with a given Selector (class or id) 
// based on whether a given list Control (e.g.: radio button inputs)
// is equal to a given Value.
// If Selector is a class name, SelectorPrefix should be "." or if it's an id, use "#"
function ToggleDisplay(Control, Value, Selector, SelectorPrefix) {

	ToggleControl(Control, Value, Selector, SelectorPrefix, false);
}

// Same as ToggleDisplay() but toggles whether elements are enabled or disabled.
function ToggleEnabled(Control, Value, Selector, SelectorPrefix) {

	ToggleControl(Control, Value, Selector, SelectorPrefix, true);
}

// Toggle the display (show/hide) or the ableness (enable/disable) of elements with a 
// given Selector (class or id) based on whether a given list Control (e.g.: radio button inputs)
// is equal to a given Value.
// If Selector is a class name, SelectorPrefix should be "." or if it's an id, use "#"
function ToggleControl(Control, Value, Selector, SelectorPrefix, EnableNotShow) {

	// make jQuery for getting the selected list control (or options)
	var query;// = "[id*='" + Control.id + "']";
	if (Control.tagName.toLowerCase() == "select") {
		query = "#" + Control.id + " option:selected";
	}
	else {
		query = "input:checked[id*='" + Control.id + "']";
	}
	var selections = $(query);

	if (Control.type == "checkbox") {
		selections = selections.next();//.text();
	}
//	else {
//		selections = selections.text();
//	}

	// determine if any value(s) selected in the list control match the specified Value
	var hasMatch = false;
	var selectionValue;
	if (selections[0] != null) {
		for (var i = 0; i < selections.length; i++) {
		
			// the text we need to match is either the "value" or the "text" of the next html tag
//			if (Control.type == "checkbox") {
//				selectionValue = selections[i].next().text();
//			}
//			else {
//			selectionValue = selections[i]; // .value
			//			}

			// the text we need to match is either the "value" or if that's null (like for a checkbox's label), the innerText
			if (selections[i].value != null) {
				selectionValue = selections[i].value;
			}
			else {
				selectionValue = $(selections[i]).text();	//.innerText;
			}
			
			if (selectionValue == Value) {
				hasMatch = true;
				break;
			}
		} 
	}

	// if any matches were found (e.g.: Value "Other" was selected in Control "PriorityGroupsList" )
	if (hasMatch) {
		
		// enable or show the given controls (elements with Selector's class/id)
		if (EnableNotShow) {
			$(SelectorPrefix + Selector).attr('disabled', false)
		}
		else {
			$(SelectorPrefix + Selector).show();
		}
	}
	else {
	
		// disable or hide the given controls
		if (EnableNotShow) {
			$(SelectorPrefix + Selector).attr('disabled', true)
		}
		else {
			$(SelectorPrefix + Selector).hide();
		}
	}
}




// Takes the street, town, state, and postcode parts of one address and copies
// it to another (depending on whether you just ticked or unticked "same as above").
function CopyAddress(CheckBox, Source, Target) {

	// if ticked, copy source values (unless blank)
	if (CheckBox.checked) {

		// get the source textboxes ($= is 'ends with', so: "inputs whose id ends with")
		var streetBox = $("textarea[id$='" + Source + "StreetTextBox']")[0];
		var townBox = $("input[id$='" + Source + "TownTextBox']")[0];
//		var stateBox = $("input[id$='" + Source + "StateTextBox']")[0];
		var stateBox = $("input[id$='" + Source + "StateList']").value;
		var postcodeBox = $("input[id$='" + Source + "PostcodeTextBox']")[0];
//        var stateList=document.getElementById(Source+"StateList");
//        var stateBox=stateList.options[stateList.selectedIndex].value;

		// copy to destination textboxen (unless source is blank)
		if (streetBox != null) {
			$("textarea[id$='" + Target + "StreetTextBox']")[0].value = streetBox.value;
		}
		if (townBox != null) {
			$("input[id$='" + Target + "TownTextBox']")[0].value = townBox.value;
		}
		if (stateBox != null) {
			$("input[id$='" + Target + "StateList']").val(stateBox.value);
//			$("input[id$='" + Target + "StateTextBox']")[0].value = stateBox.value;

		}
		if (postcodeBox != null) {
			$("input[id$='" + Target + "PostcodeTextBox']")[0].value = postcodeBox.value;
		}
	}
}
