
var tableMaster, tableQuestionList, tableQuestionGroup;
var tableQuestionListContainer, tableQuestionGroupContainer;
var tableAdvice, tableRoadmap;
var divQuestionList, divQuestionListHeader, divQuestionListBody, divQuestionListPhoto;
var divQuestionGroup, divQuestionGroupHeader, divQuestionGroupBody;
var divQuestionAdvice, divQuestionAdviceHeader, divQuestionAdviceBody;
var cellTabRoadmap, cellTabAdvice;
var imageTabHelp, imageTabHelpDeselect, imageTabHelpAdvice, imageTabHelpRoadmap;
var resizerQuestionList, resizerQuestionListStatic;
var fieldForm, selectForm;
var pageSubmit, pageSubmitSource;
var xDragHorz, xDragHorzMax;
var divQuestionGroupWidth, divQuestionListWidth;
var documentWidth, documentHeight;

var resizerQuestionListDefaultX = 190;
var divQuestionGroupWidthMin = 450;
var divQuestionListWidthMin = 220;
var divQuestionAdviceHeight = 200;
var pageMarginHorz = 90;
var pageMarginVert = 128;
var panelGapHorzResizer = 25;
var cellMarginExpand = 18;
var pageLoaded = false, pageChanged = false, pageSaved = false;
var itemSet, currentRow, currentCell;
var i;
var changeCount = 0;
var dataString, outputString, idx;
var charactersFloat = "1234567890-.,";
var charactersInteger = "1234567890-,";
var contentNew;

var adviceHeaderTextCell, adviceHeaderNavCell;
var popupWindow;
var popupImageWait, popupImageWaitSource;
var radioNameValue = "";
var tabContent;

//Assign variables, resize items, register for drag/drop
function windowLoad() {
	var divOtherHeight;

	pageLoaded=true;
	pageChanged=false;
	changeCount=0;
	pageSaved=false;

	fieldForm = document.getElementById("fieldForm");
	selectForm = document.getElementById("selectForm");
	jspForm = document.getElementById("jspForm");
	formFieldFirstFocus();

	popupWindow= document.getElementById("popupWindow");
	popupImageWait= document.getElementById("popupImageWait");
	popupImageWaitSource= document.getElementById("popupImageWaitSource");
	
	tabContent = document.getElementById("tab-content");
	tabPageContent = document.getElementById("tab-page-content");
	tabPageMenu = document.getElementById("tab-page-menu");

	documentHeight = window.innerHeight; //parseFloat(document.body.offsetHeight);
	if (!documentHeight) {
		documentHeight = document.body.clientHeight;
	}
	documentWidth = window.innerWidth; //parseFloat(document.body.offsetWidth);
	if (!documentWidth) {
		documentWidth = document.body.clientWidth;		
	}
	tableMaster= document.getElementById("tableMaster");
	tableQuestionList= document.getElementById("tableQuestionList");
	tableQuestionListContainer= document.getElementById("tableQuestionListContainer");
	tableQuestionGroup= document.getElementById("tableQuestionGroup");
	tableQuestionGroupContainer= document.getElementById("tableQuestionGroupContainer");
	tableAdvice= document.getElementById("tableAdvice");
	divQuestionList= document.getElementById("divQuestionList");
	divQuestionListHeader= document.getElementById("divQuestionListHeader");
	divQuestionListBody= document.getElementById("divQuestionListBody");
	divQuestionListPhoto= document.getElementById("divQuestionListPhoto");
	divQuestionGroup= document.getElementById("divQuestionGroup");
	divQuestionGroupHeader= document.getElementById("divQuestionGroupHeader");
	divQuestionGroupBody= document.getElementById("divQuestionGroupBody");
	divQuestionAdvice= document.getElementById("divQuestionAdvice");
	divQuestionAdviceHeader= document.getElementById("divQuestionAdviceHeader");
	divQuestionAdviceBody= document.getElementById("divQuestionAdviceBody");
	imageTabHelp= document.getElementById("imageTabHelp");
	imageTabHelpAdvice= document.getElementById("imageTabHelpAdvice");
	imageTabHelpDeselect= document.getElementById("imageTabHelpDeselect");
	resizerQuestionList= document.getElementById("resizerQuestionList");
	resizerQuestionListStatic= document.getElementById("resizerQuestionListStatic");
	adviceHeaderTextCell = document.getElementById("adviceHeaderTextCell");
	adviceHeaderNavCell = document.getElementById("adviceHeaderNavCell");

	windowResize();
};

//Resize table and div elements when window resizes
function windowResize() {
	var divOtherHeight;
	documentHeight = window.innerHeight; //parseFloat(document.body.offsetHeight);
	if (!documentHeight) {
		documentHeight = document.body.clientHeight;
	}
	documentWidth = window.innerWidth; //parseFloat(document.body.offsetWidth);
	if (!documentWidth) {
		documentWidth = document.body.clientWidth;		
	}
		
	//divQuestionGoupWidth =  parseInt(divQuestionGroup.offsetParent.offsetWidth);
	divQuestionGoupWidth =  parseInt(divQuestionGroup.offsetWidth);

	//Get heights
	divOtherHeight = 0;
	if (parseInt(divQuestionAdvice.offsetHeight) > 1) {
		divOtherHeight = parseInt(divOtherHeight) + parseInt(divQuestionAdvice.offsetHeight);
	}

	if (divOtherHeight > 0)	divOtherHeight = divOtherHeight + 16;

  tabContent.style.height = parseInt(documentHeight) - 195;
  tabContent.style.width = parseInt(documentWidth) - 75;
  tabPageContent.style.height = parseInt(documentHeight) - 195;
  tabPageContent.style.width = parseInt(documentWidth) - 295;
  tabPageMenu.style.height = parseInt(documentHeight) - 195;
  tabPageMenu.style.width = parseInt(210);

};


function divResizeDuringLoad() {

    documentHeight = window.innerHeight; //parseFloat(document.body.offsetHeight);
    if (!documentHeight) {
        documentHeight = document.body.clientHeight;
    }
    documentWidth = window.innerWidth; //parseFloat(document.body.offsetWidth);
    if (!documentWidth) {
        documentWidth = document.body.clientWidth;       
    }

    tabContent = document.getElementById("tab-content");
    tabPageContent = document.getElementById("tab-page-content");
    tabPageMenu = document.getElementById("tab-page-menu");

    tabContent.style.height = parseInt(documentHeight) - 195;
    tabContent.style.width = parseInt(documentWidth) - 75;
    tabPageContent.style.height = parseInt(documentHeight) - 195;
    tabPageContent.style.width = parseInt(documentWidth) - 295;
    tabPageMenu.style.height = parseInt(documentHeight) - 195;
    tabPageMenu.style.width = parseInt(210);


};

//Sets cursor to stated type
function setCursor(curtype) {
	if (document.all) document.body.style.cursor=curtype;
}

//Runs when question list resizer (vertical resizer drag) is dragged
function resizerQuestionListDrag(x, y) {
	//Set resizer position keeping between min and max
	//documentWidth = parseFloat(window.innerWidth);
	xDragHorz = parseFloat(x);
	xDragHorzMax = documentWidth - divQuestionGroupWidthMin - pageMarginHorz - 20;
	if (xDragHorzMax < divQuestionListWidthMin + panelGapHorzResizer) {
		resizerQuestionList.style.left = parseInt(divQuestionList.offsetWidth + panelGapHorzResizer);
		return;
	}
	if (xDragHorz > xDragHorzMax) {
		resizerQuestionList.style.left = parseInt(divQuestionList.offsetWidth + panelGapHorzResizer);
		return;
		//xDragHorz = xDragHorzMax;
	}
	if (xDragHorz < divQuestionListWidthMin + panelGapHorzResizer) {
		resizerQuestionList.style.left = parseInt(divQuestionList.offsetWidth + panelGapHorzResizer);
		return;
		//xDragHorz = divQuestionListWidthMin + panelGapHorzResizer;
	}

	//Set width of question list div based on resizer position
	divQuestionListWidth = xDragHorz - panelGapHorzResizer;


	if (divQuestionListWidth > (xDragHorzMax - panelGapHorzResizer)) {
		divQuestionListWidth = xDragHorzMax - panelGapHorzResizer;
	}
	if (divQuestionListWidth < divQuestionListWidthMin) {
		divQuestionListWidth = divQuestionListWidthMin;          
	}
	divQuestionGroupWidth = documentWidth - divQuestionListWidth - pageMarginHorz - 5;
	if (divQuestionGroupWidth < divQuestionGroupWidthMin) {
		divQuestionGroupWidth = divQuestionGroupWidthMin;          
	}
	divQuestionListWidth = documentWidth - divQuestionGroupWidth - pageMarginHorz - 5;
	if (divQuestionListWidth < divQuestionListWidthMin) {
		divQuestionListWidth = divQuestionListWidthMin;          
	}
	
	//Assign values
	divQuestionList.style.width = divQuestionListWidth;
	divQuestionGroup.style.width = divQuestionGroupWidth;
	//resizerQuestionList.style.left = divQuestionListWidth + panelGapHorzResizer;
	dependentElementsResize();
};

//Finish drag sequence
function resizerQuestionListDragEnd(x, y) {
	//Position resizer, turn off highlight, store position in a cookie
	if (!this.over)	this.onmouseout();
	//xDragHorz = parseFloat(x);
	//createCookie("pplanLeftPanelWidth", xDragHorz, 1); 
	//resizerQuestionList.style.left = xDragHorz;
	resizerQuestionList.style.left = parseInt(divQuestionList.offsetWidth + panelGapHorzResizer);
	resizerHighlightOff;
	createCookie("pplanLeftPanelWidth", parseInt(divQuestionList.offsetWidth + panelGapHorzResizer), 1);

};

//Set min and max limits for resizer drag
function resizerQuestionListSetLimits() {
	//documentHeight = window.innerHeight; //parseFloat(document.body.offsetHeight);
	//documentWidth = window.innerWidth; //parseFloat(document.body.offsetWidth);
	xDragHorzMax = documentWidth - divQuestionGroupWidthMin - pageMarginHorz + panelGapHorzResizer;
	resizerQuestionList.maxX = xDragHorzMax;
	resizerQuestionList.minX = divQuestionListWidthMin + panelGapHorzResizer;
	window.status = divQuestionListWidthMin + "   " + xDragHorzMax;
};

//Turn highlight on for resizer
function resizerHighlightOn() {
	this.over = true;
	resizerQuestionListStatic.style.backgroundColor = "#c0c0c0";
};

//Turn highlight off for resizer
function resizerHighlightOff() {
	this.over = false;
	if (Drag.obj != this) resizerQuestionListStatic.style.backgroundColor = "#ffffff";
};

//Expand and show advice div/panel
function adviceExpand() {
	var groupHeight;
	
	//documentHeight = parseFloat(document.body.offsetHeight) - 18;
	//groupHeight = parseFloat(document.body.offsetHeight) - 18 - pageMarginVert - parseInt(divQuestionAdviceHeight) + cellMarginExpand;
	//divQuestionGroup.style.height = groupHeight;
	divQuestionAdvice.style.display="block";
	divQuestionAdvice.style.height = divQuestionAdviceHeight;
	divQuestionAdvice.style.padd = 0;
//	divQuestionRoadmap.style.display = "none";
//	divQuestionRoadmap.style.height = 1;
//	divQuestionRoadmap.style.padd = 0;
	imageTabHelp.src = imageTabHelpAdvice.src;
	//tabContent.style.height = groupHeight;
	tabPageContent.style.height = parseInt(documentHeight - 195 - divQuestionAdviceHeight);
};

//Contract and hide advice div/panel
function adviceContract() {
	//var groupHeight;
	//documentHeight = parseFloat(document.body.offsetHeight);
//	divOtherHeight = 0;
	//groupHeight = parseFloat(document.body.offsetHeight) - pageMarginVert;
	divQuestionAdvice.style.display="none";
	divQuestionAdvice.style.height = 1;
	divQuestionAdvice.style.padd = 0;
	//divQuestionGroup.style.height = groupHeight;
	imageTabHelp.src = imageTabHelpDeselect.src;
  //tabContent.style.height = groupHeight;
  tabPageContent.style.height = parseInt(documentHeight - 195);
};

//Toggle advice beteen contracted and expanded
function adviceToggle() {
	if ((parseInt(divQuestionAdvice.style.height) > 1)) {
		adviceContract();
	} else {
		adviceExpand();
		helpTextSelect("helpPage","");
	}
}


//Hide all help cells
function helpHideCells() {
	var tableAdvice;
	//Assign question list cell background
	tableAdvice = self.document.getElementById("tableAdvice");
	itemSet = tableAdvice.getElementsByTagName("td");
	for (i = 0; i < itemSet.length; i++) {
		itemID = itemSet[i].getAttribute("id");
		itemSet[i].style.display = "none";
	}
	itemSet = tableAdvice.getElementsByTagName("tr");
	for (i = 0; i < itemSet.length; i++) {
		itemID = itemSet[i].getAttribute("id");
		itemSet[i].style.display = "none";
	}
};

//Show page help for current page
function helpSelectPage() {
	helpHideCells();
	document.getElementById("helpPage").style.display = "block";
};

//Show the actual help cells -- called on by helpTextSelect and helpTextDisplay
function helpTextShow(cellID, cellSuffix) {
	helpHideCells();
	divQuestionAdvice.style.display="none";
	divQuestionAdvice.style.display="block";
	imageTabHelp.src = imageTabHelpAdvice.src;
	currentRow = document.getElementById(cellID + cellSuffix);
	currentRow.style.display = "block";
	itemSet = currentRow.getElementsByTagName("td");
	for (i = 0; i < itemSet.length; i++) {
		itemSet[i].style.display = "block";
	}
	adviceHeaderTextCell.innerHTML = document.getElementById(cellID+"_headerTextCell").innerHTML;
	adviceHeaderNavCell.innerHTML = document.getElementById(cellID+"_headerNavCell").innerHTML;
	adviceExpand();
}

//Display help for current question when question is clicked
//Does not do anything if help is not already shown (see helpTextDisplay below)
function helpTextSelect(cellID, cellSuffix) {
	if ((parseInt(divQuestionAdvice.style.height) > 1)) {
		helpTextShow(cellID, cellSuffix);
	}
};

//Display help for current question when question is clicked
//Does not do anything if help is not already shown (see helpTextDisplay below)
function helpTextSelectLabel(cellID, cellSuffix, element) {
	//Set radio button to null if it has already been clicked
	if (radioNameValue == (element.name + "_" + element.value)) {
		radioNameValue = "ned";
		element.value = "ned";
		element.checked = false;
	} else {
		radioNameValue = element.name + "_" + element.value;
	}
	//Show help text
	if ((parseInt(divQuestionAdvice.style.height) > 1)) {
		helpTextShow(cellID, cellSuffix);
	}
};

//Display help for question when label is clicked
function helpTextDisplay(cellID, cellSuffix) {
	//Hide current block if already showing and clicked again
	if ((parseInt(divQuestionAdvice.style.height) > 1)) {
		if (document.getElementById(cellID + cellSuffix).style.display == "block") {
			helpHideCells();
			adviceContract();
			return;
		}
	}
	//Otherwise select the help
	helpTextShow(cellID, cellSuffix)
};


//Display a group given the group number
function pagelistToggleVisibleOld(tabset, tabsetPageset) 
{
	var groupTableID, groupMapCurrentID, groupMapScrollID; 
	var itemSet, tableQuestionGroup, tableQuestionList;
	var groupNumberScroll, scrollTopNew, scrollBottomNew, divHeight;
	var groupMapShow;
	var tabCell, headerCell, tabPrefix, cellPrefix;

	tabPrefix = tabset + "_";
	cellPrefix = tabsetPageset + "_";
	
	tabCell = document.getElementById(tabset + "_header_row");
	headerCell = document.getElementById(tabsetPageset + "_header_row");
	
	//Show/Hide rows 
	tableQuestionList = document.getElementById("tableQuestionList");
	itemSet = tableQuestionList.getElementsByTagName("tr");
	for(var i = 0; i < itemSet.length; i++) {
		itemID = itemSet[i].getAttribute("id");
		if (itemID.substring(0, tabPrefix.length) == tabPrefix) {
			if (itemID.substring(0, cellPrefix.length) == cellPrefix) {
				if (itemID.indexOf("_header") > 0) {
					itemSet[i].style.display = 'block';
				} else {
					if(itemSet[i].style.display == 'block') {
					//if(headerCell.style.display == 'block') {
						itemSet[i].style.display = 'none';
					} else {
						itemSet[i].style.display = 'block';
					}
				}
			} 
		}
	}

	//Show/Hide cells
	itemSet = tableQuestionList.getElementsByTagName("td");
	for(var i = 0; i < itemSet.length; i++) {
		itemID = itemSet[i].getAttribute("id");
		if (itemID.substring(0, tabPrefix.length) == tabPrefix) {
			if (itemID.substring(0, cellPrefix.length) == cellPrefix) {
				if (itemID.indexOf("_header") > 0) {
					itemSet[i].style.display = 'block';
				} else {
					if(itemSet[i].style.display == 'block') {
					//if(headerCell.style.display == 'block') {
						itemSet[i].style.display = 'none';
					} else {
						itemSet[i].style.display = 'block';
					}
				}
			} 
		} 
	}

	//Scroll, now that cells are shown/hidden
	//divQuestionListBody.scrollTop = parseInt(tableQuestionList.offsetTop) + 2;
	//divQuestionListBody.scrollTop = 2;
	scrollTopNew = (parseInt(tabCell.offsetTop) + 2);
	scrollBottomNew = (parseInt(headerCell.offsetTop) + parseInt(headerCell.offsetHeight) + 2);
	divHeight = parseInt(divQuestionList.style.offsetHeight);
	if (scrollBottomNew < divHeight) {
		scrollTopNew = 2;
	} else {
		scrollTopNew = divHeight - scrollBottomNew;
	}
	//alert(parseInt(parseInt(tableQuestionList.offsetTop) + 2) + "  " + scrollTopNew);

}

//Display a group given the group number
function pagelistToggleVisible(tabset, tableID) 
{
	var itemSet;
	var divHeight, scrollTopNew, scrollBottomNew;
	var tabCell, tabTable, newDisplay;
	
	tabCell = document.getElementById(tabset + "_header_row");
	tabTable = document.getElementById(tableID);
	//scrollTopNew = (parseInt(tabCell.offsetTop) + 2);

	//Determine if showing or hiding 
	if (tabTable.style.display == 'block') {
		newDisplay = 'none';
	} else {
		newDisplay = 'block';
	}
	//Hide cells
	itemSet = tabTable.getElementsByTagName("td");
	for(var i = 0; i < itemSet.length; i++) {
		itemSet[i].style.display = newDisplay;
	}
	//Hide rows
	itemSet = tabTable.getElementsByTagName("tr");
	for(var i = 0; i < itemSet.length; i++) {
		itemSet[i].style.display = newDisplay;
	}
	//Hide table
	tabTable.style.display = newDisplay;

	//Scroll, now that cells are shown/hidden
	scrollTopNew = (parseInt(tabTable.offsetParent.offsetTop) + parseInt(tabTable.offsetTop)+ 2);
	scrollBottomNew = (parseInt(tabTable.offsetParent.offsetTop) + parseInt(tabTable.offsetTop) + parseInt(tabTable.offsetHeight) + 2);
	//scrollTopNew = parseInt(tabTable.offsetTop)+ 2;
	//scrollBottomNew = parseInt(tabTable.offsetTop) + parseInt(tabTable.offsetHeight) + 2;
	divHeight = parseInt(divQuestionList.offsetHeight);
	if (scrollBottomNew <= divHeight) {
		scrollTopNew = 2;
	} else {
		scrollTopNew = scrollBottomNew - divHeight + (parseInt(tabTable.offsetHeight) * 0.5) + parseInt(tabCell.offsetHeight) ;
	}
	divQuestionListBody.scrollTop = scrollTopNew;

}

//Edit notes for current question and save to hidden note field
function noteEdit(noteField) {
	var noteText, noteInput
	noteInput = document.getElementById(noteField);
	noteText = noteInput.value;
	noteText = prompt("Enter notes for " + noteField, noteText);
	if (noteText == null) {
		//noteInput.value = "";
	} else {
		if (noteText.length > 0) {
			noteInput.value = noteText;
		} else {
			noteInput.value = "";
		}
	}
};

//---------------------------------------------------------
//FORM MANIPULATION
//---------------------------------------------------------

// Reset form
function formReset() {


	popupWindowHide();
	pageSaved = false;
	pageChanged = false;
	changeCount = 0;

	if(document.fieldForm) {
		fieldForm.reset();
	} else if (document.jspForm){
		jspForm.reset();
	} else if(document.selectForm){
		selectForm.reset();
	}
}

//Reset form with verification
function formResetVerify() {
	var outputMessage;
	outputMessage = "Do you want to reset the form and wipe out all changes since the last save?";
	popupWindowShow("Reset form data?", outputMessage, 2, "Yes", "javascript:formReset();", "No", "javascript:popupWindowHide();", false);
}

//Submit form, setting pageSubmit to previous page (form save/previous)
function submitPagePrevious() {
	if(pageChanged) {
		popupWindowSubmitSaveWait();
	} else {
		popupWindowSubmitRetrieveWait();
	}
	if(document.fieldForm) {
		pageSubmit = document.getElementById("pageSubmit");
		pageSubmitSource = document.getElementById("pageSubmitPrevious");
		pageSubmit.value = pageSubmitSource.value;
		pageSaved = true;
		pageChanged = false;
		changeCount = 0;
		fieldForm.target = "";
		fieldForm.submit();
	} else if (document.jspForm) {
		pageSaved = true;
		pageChanged = false;
		changeCount = 0;
		jspForm.target = "";
		jspForm.submit();
	} else {
		// do nothing
	}
};

//Submit form, setting pageSubmit to current page (form save/reload)
function submitPageCurrent() {
	if(pageChanged) {
		popupWindowSubmitSaveWait();
	} else {
		popupWindowSubmitRetrieveWait();
	}
	if(document.fieldForm) {
		pageSubmit = document.getElementById("pageSubmit");
		pageSubmitSource = document.getElementById("pageSubmitCurrent");
		pageSubmit.value = pageSubmitSource.value;
		pageSaved = true;
		pageChanged = false;
		changeCount = 0;
		fieldForm.target = "";
		fieldForm.submit();
	} else if (document.jspForm) {
		pageSaved = true;
		pageChanged = false;
		changeCount = 0;
		jspForm.target = "";
		jspForm.submit();
	} else {
		// do nothing
	}
};

//Submit form, setting pageSubmit to next page (form save/next)
function submitPageNext() {
	if(pageChanged) {
		popupWindowSubmitSaveWait();
	} else {
		popupWindowSubmitRetrieveWait();
	}
	if(document.fieldForm) {
		pageSubmit = document.getElementById("pageSubmit");
		pageSubmitSource = document.getElementById("pageSubmitNext");
		pageSubmit.value = pageSubmitSource.value;
		pageSaved = true;
		pageChanged = false;
		changeCount = 0;
		fieldForm.target = "";
		fieldForm.submit();
	} else if (document.jspForm) {
		pageSaved = true;
		pageChanged = false;
		changeCount = 0;
		jspForm.target = "";
		jspForm.submit();
	} else {
		// do nothing
	}
};

//Submit form, setting pageSubmit to specified page 
function submitPage(pageLocation) {
	if(pageChanged) {
		popupWindowSubmitSaveWait();
	} else {
		popupWindowSubmitRetrieveWait();
	}
	if(document.fieldForm && pageChanged) {
		pageSubmit = document.getElementById("pageSubmit");
		pageSubmit.value = pageLocation
		pageSaved = true;
		pageChanged = false;
		changeCount = 0;
		if(stringEndsWith(pageLocation, "NW")) {
			fieldForm.target = "_blank";
			fieldForm.submit();
			popupWindowHide();
		} else {
			fieldForm.target = "";
			fieldForm.submit();
		}
	} else if (document.jspForm && pageChanged) {
		pageSaved = true;
		changeCount = 0;
		if(stringEndsWith(pageLocation, "NW")) {
			jspForm.target = "_blank";
			jspForm.submit();
			popupWindowHide();
		} else {
			jspForm.target = "";
			jspForm.submit();
		}
	} else {
		if(stringEndsWith(pageLocation, "NW")) {
			window.open("viewpage.html?_Page=" + pageLocation, pageLocation);
			popupWindowHide();
		} else {
			window.location = "viewpage.html?_Page=" + pageLocation;
		}
	}
};

//Submit select form, warning if main form not saved
function submitSelectSelectForm() {
	pageSaved = true;
	if (pageChanged) {
		alert("Page has changed.  Please save results using the save/reload button at the bottom of the page before switching.");
		return;
	}
	//if(fieldForm.onsubmit()){
	popupWindowSubmitSaveWait();
	selectForm.submit();
	//}
};

// Submit on number change select 
function submitSelectNumberField(field, content, labelShort) {
   //if (confirm("Update page to refect the changes made to '" + labelShort.toLowerCase() + "'?")) {
   //    submitPageCurrent();
   //} 
   popupWindowSubmitVerify('Update Page?','Do you want to update the page to reflect this change?')
};

// Submit on number change button
function submitSelectNumberChange(selectField, valueChange, dataFieldID) {
	var valueNew;
	var dataField;
	var dataFieldValue;

	dataField = document.getElementById(dataFieldID);
	dataFieldValue = parseInt(dataField.value);
	if (isNaN(dataFieldValue)) {
		dataFieldValue = 1;
	}
	valueNew = dataFieldValue + parseInt(valueChange);
	if (valueNew < 0) {
		valueNew = 0;
	}
	dataField.value = valueNew;
	selectField.value = valueNew;
	//alert(valueNew)
	submitPageCurrent();
}

// Move to first field on form
function formFieldFirstFocus() {
	if (fieldForm) {
		for (i=0;i< fieldForm.elements.length; ++i ) {
			if ( !(fieldForm.elements[i].type == "hidden")) {
				fieldForm.elements[i].focus();
				break;
			}
		}
	} else if (jspForm) {
		for (i=0;i< jspForm.elements.length; ++i ) {
			if ( !(jspForm.elements[i].type == "hidden")) {
				jspForm.elements[i].focus();
				break;
			}
		}
	} else if (document.forms.length > 0) {
		for (i=0;i< document.forms[0].elements.length; ++i ) {
			if ( !(document.forms[0].elements[i].type == "hidden")) {
				//alert("setting focus to:" + document.forms[0].elements[i].name + document.forms[0].elements[i].type 
				//	  + document.forms[0].elements[i].options);
				document.forms[0].elements[i].focus();
				break;
			}
		}
	}
}

//---------------------------------------------------------
//WINDOW EVENTS
//---------------------------------------------------------

function windowBeforeUnload() {
	if (pageChanged) {
		if ((! pageSaved)) {
			//alert("Saving current page");
			submitPageCurrent();
		}
	}
};

function windowOnChange() {
	pageChanged = true;
	changeCount++;
	//alert("page changed: " + pageChanged + " changed " + changeCount + " times.");
};


//---------------------------------------------------------
//SHOWING/HIDING, POP-UP WINDOW FUNCTIONS
//---------------------------------------------------------

// Toggle item visible status
function elementVisibleToggle(elementID) {
  if (document.getElementById(elementID).style.display != "none") {
    document.getElementById(elementID).style.display = "none";
  } else {
    document.getElementById(elementID).style.display = "block";
  }
}

// Set item visible status
function elementVisibleSet(elementID, visibleStatus) {
	if (visibleStatus) {
		document.getElementById(elementID).style.display = "block";
	} else {
		document.getElementById(elementID).style.display = "none";
	}
}

function elementValueSet(elementID, aValue) {
	document.getElementById(elementID).value = aValue;
}

// Show the popup window
function popupWindowShow(titleText, messageText, buttonCount, 
						 buttonOneText, buttonOneLink, buttonTwoText, buttonTwoLink, showImageWait) {

	// Hide elements
	popupWindow.style.display="none";
	document.getElementById("popupMessageCell").style.display="none";
	document.getElementById("popupImageWaitCell").style.display="none";
	document.getElementById("popupButtonSingleCell").style.display="none";
	document.getElementById("popupButtonDoubleCell").style.display="none";

	// Set values
	document.getElementById("popupTitleText").innerHTML = titleText;
	document.getElementById("popupMessageText").innerHTML = messageText;
	document.getElementById("popupButtonSingleOne").innerHTML = buttonOneText;
	document.getElementById("popupButtonSingleOne").href = buttonOneLink;
	//document.getElementById("popupButtonSingleCellOne").onclick = buttonOneLink;
	document.getElementById("popupButtonDoubleOne").innerHTML = buttonOneText;
	document.getElementById("popupButtonDoubleOne").href = buttonOneLink;
	//document.getElementById("popupButtonDoubleCellOne").onclick = buttonOneLink;
	document.getElementById("popupButtonDoubleTwo").innerHTML = buttonTwoText;
	document.getElementById("popupButtonDoubleTwo").href = buttonTwoLink;
	//document.getElementById("popupButtonDoubleCellTwo").onclick = buttonOneLink;

	// Show message
	document.getElementById("popupMessageCell").style.display="block";

	// Show image
	if (showImageWait) {
		popupImageWait.src = popupImageWaitSource.src;
		document.getElementById("popupImageWaitCell").style.display="block"
		document.getElementById("popupImageWaitCell").style.width="100%"
	}

	// Show button tables
	if (buttonCount == 1) {
		document.getElementById("popupButtonSingleCell").style.display="block";
	}
	if (buttonCount == 2) {
		document.getElementById("popupButtonDoubleCell").style.display="block";
	}

	// Show window
	popupWindow.style.left = parseInt((documentWidth - parseInt(popupWindow.style.width))/2);
	popupWindow.style.top = parseInt((documentHeight)/3);
	popupWindow.style.display="block";
}

// Show popup window for submit save wait
function popupWindowSubmitSaveWait() {
	 popupWindowShow("Saving Data", "Saving data to server.", 0, "", "", "", "", true);
}

// Show popup window for submit save wait
function popupWindowSubmitRetrieveWait() {
	 popupWindowShow("Retrieving Page", "Retrieving page from server.", 0, "", "", "", "", true);
}

// Show popup window with verify options
function popupWindowSubmitVerify(titleText, messageText) {
	popupWindowShow(titleText, messageText, 2, "Yes", "javascript:submitPageCurrent();", "No", "javascript:popupWindowHide();", false);
}

// Show popupw indow with alert options
function popupWindowAlert(titleText, messageText, cmd) {
//	popupWindowShow(titleText, messageText, 2, "OK", "javascript:popupWindowHide();", "Update Later", cmd, false);
	popupWindowShow(titleText, messageText, 1, "OK", "javascript:popupWindowHide();", "", "", false);
}

// Show popup window with verify options
function popupWindowVerify(titleText, messageText, buttonOneText, buttonOneLink, buttonTwoText, buttonTwoLink) {
	popupWindowShow(titleText, messageText, 2, buttonOneText, buttonOneLink, buttonTwoText, buttonTwoLink, false);
}

// Show popup window with verify options for photo upload
function popupWindowAlertPhoto(elementID) {
	//if ((document.getElementById(elementID).value.length = 0) || (document.getElementById(elementID).value == null)) {
	//	return;
	//}
	if (document.getElementById(elementID).value.length > 0) {
		var messageTextPhoto;
		messageTextPhoto = "Uploading images can take several minutes.  A one megabyte " +
					 "photo can take ten minutes or more to upload at dialup speeds, and " +
					 "thirty seconds or more when using DSL or Cable. <br><br>" + 
					 "If you do not have the time right now to submit a large photo, either reduce " +
					 "the size of the image or clear the filename and try again later. \n\n" +
					 "Also, please note that new images will not show up until the next time you log " +
					 "into the KidsFirst! application.";
	  var cmd = "javascript:clearPhotoField(\""+elementID+"\");javascript:popupWindowHide();";
	
	  popupWindowAlert("Verify Photo Upload", messageTextPhoto, cmd);
	}
}

function clearPhotoField(elementID) {
	var obj = document.getElementById(elementID);
	obj.value = null;
}

//Hide the popup window
function popupWindowHide() {
	popupWindow.style.display="none";
}                                                          


//---------------------------------------------------------
//FIELD FORMATTING FUNCTIONS
//---------------------------------------------------------

// Replaces all occurrences of "from" with "to" in a string
function replaceAll( str, from, to ) {
    idx = str.indexOf( from );
    while ( idx > -1 ) {
        str = str.replace( from, to );
        idx = str.indexOf( from );
    }
    return str;
}

// Format Social Security Number Function  "123-45-6789" 
function fieldFormatSSN(field,content) {
	dataString = field.value;
	if (getSelectionStart(field) < dataString.length) {
	  return;
	}
	dataString = replaceAll(dataString, "-", "");
	outputString = dataString.substring(0, 3) 
	if (dataString.length >= 3) {
		outputString += "-" + dataString.substring(3,5);
	}
	if (dataString.length >= 5) {
		outputString += "-" + dataString.substring(5, 9);
	}
	field.value = outputString;
};

// Format Phone Number Function  "(123)456-7890" 
function fieldFormatPhone(field,content) {
	dataString = field.value;
	dataString = replaceAll(dataString, "(", "");
	dataString = replaceAll(dataString, ")", "");
	dataString = replaceAll(dataString, "-", "");
	dataString = replaceAll(dataString, ".", "");
	dataString = replaceAll(dataString, " ", "");
	outputString = "(" + dataString.substring(0, 3) + ")";
	if (dataString.length >= 3) {
		outputString += " " + dataString.substring(3,6);
	}
	if (dataString.length >= 5) {
		outputString += "-" + dataString.substring(6, 10);
	}
	field.value = outputString;
};

// Format Date Function  "11/04/1994" 
function fieldFormatDate(field,content) {
	dataString = field.value;
	dataString = replaceAll(dataString, "-", "");
	dataString = replaceAll(dataString, "/", "");
	dataString = replaceAll(dataString, "\\", "");
	outputString = dataString.substring(0, 2); 
	if (dataString.length >= 2) {
		outputString += "/" + dataString.substring(2,4);
	}
	if (dataString.length >= 4) {
		outputString += "/" + dataString.substring(4, 8);
	}
	field.value = outputString;
};

// Format Time Function  "12:35" 
function fieldFormatTime(field,content) {
   if ( content.length==2) {
	   if ( content.indexOf(":") < 0) {
		   field.value = field.value+":" ;
	   }
    }
};

// Format integer
function fieldFormatInteger(field,content) {
	contentNew = "";
	for (i=0; i<content.length; i++) {
		if (charactersInteger.indexOf(content.charAt(i),0) < 0) {
			alert("Please enter whole numbers, not letters or periods.");
		} else {
			contentNew = contentNew + content.charAt(i);
		}
	}
	field.value = (contentNew) ;
};

// Format float
function fieldFormatFloat(field,content) {
	contentNew = "";
	for (i=0; i<content.length; i++) {
		if (charactersFloat.indexOf(content.charAt(i),0) < 0) {
			alert("Please enter numbers, not letters.");
		} else {
			contentNew = contentNew + content.charAt(i);
		}
	}
	field.value = (contentNew) ;
};

//Selection start, and/or curent caret position
function getSelectionStart(o) {
	if (o.createTextRange) {
		var r = document.selection.createRange().duplicate()
		r.moveEnd('character', o.value.length)
		if (r.text == '') return o.value.length
		return o.value.lastIndexOf(r.text)
	} else return o.selectionStart
}

//Selection end
function getSelectionEnd(o) {
	if (o.createTextRange) {
		var r = document.selection.createRange().duplicate()
		r.moveStart('character', -o.value.length)
		return r.text.length
	} else return o.selectionEnd
}


//---------------------------------------------------------
//To-Do page manipulation
//---------------------------------------------------------

//Select all items
function selectAllToDo(isSet) {
	var form = document.forms.fieldForm;
	var elements = form.elements;

	for( i=0; i<elements.length; ++i) {
		if(elements[i].name == 	"todo_page" && elements[i].disabled != true) {
			elements[i].checked = isSet;
		}
	}
};

//Select current section
function selectToDoSection(sectionVariableArray, isSet) {
	var form = document.forms.fieldForm;
	var elements = form.elements;

	for( i=0; i<elements.length; ++i) {
		if(elements[i].name == 	"todo_page" && elements[i].disabled != true) {
			var elementValue = elements[i].value;
			for( j=0; j<sectionVariableArray.length; j++) {
				if(sectionVariableArray[j] == elementValue) {
					elements[i].checked = isSet;
					break;
				}
			}
		}
	}
};


//---------------------------------------------------------
//MISCELLANEOUS FUNCTIONS
//---------------------------------------------------------

// Check if string starts with 
function stringBeginsWith(sourceString, checkString) {
	if(parseInt(sourceString.indexOf(checkString)) == 0){
		return true;
	} else {
		return false;
	}
}

// Check if string ends with 
function stringEndsWith(sourceString, checkString) {
	//alert(sourceString.lastIndexOf(checkString) + "  " + sourceString.length + "  " + checkString.length + "  " + parseInt(sourceString.length - checkString.length));
	if(parseInt(sourceString.lastIndexOf(checkString)) == (parseInt(sourceString.length) - parseInt(checkString.length))){
		return true;
	} else {
		return false;
	}
}


//---------------------------------------------------------
//TEST FUNCTIONS
//---------------------------------------------------------

// Test function to show innerHTML
function testInnerShow(elementID) {
	var testInnerShowField;
	popupWindow = document.getElementById('popupOKbuttonLink');
	testInnerShowField = document.getElementById('innershow');
	testInnerShowField.value = popupWindow.href;
	popupWindow.href="javascript:alert('it worked')";
}

// Set item visible status
function windowDrag(elementID) {
	alert("dragging");
	//document.getElementByID("ChildMedical_additionalHealthInfo(0)").value = event.xDragHorz + " " + event.clientX;
}      


