// Mumsurvey common javascript functions
var undefined;

// do an onload alert if php has set a variable (used for warnings / errors)
function onLoadEvent()
{
	if(window.message !== undefined) alert(window.message);
}

// open up a stripped out window for quick help windows
function openPopup(url)
{
	window.open(url, Math.floor(Math.random()*1000), 'width=400, height=500, resizable=yes, scrollbars=yes, toolbar=no, location=no, directories=no, status=no, menubar=no, copyhistory=no');
}

// ask for confirmation before refreshing a page with a delete method
function deleteConfirm(id)
{
	if(confirm('Are you sure you want to delete this item? This action is irrevocable.'))
	{
		document.location.href = '?method=delete&id=' + id;
	}
}

// clears all checkboxes but the last one
function clearCheckboxes(id)
{
	
	totalBoxes =  getLastCheckbox(id);
	
	if(document.getElementById(id + '_' + totalBoxes).checked)
	{
		for(i=1; i<totalBoxes; i++)
		{
			document.getElementById(id + '_' + i).checked = false;
		}
	}
}

// clears the last checkbox
function clearLastCheckbox(id)
{
	lastBox = getLastCheckbox(id);
	document.getElementById(id + '_' + lastBox).checked = false;
}

// gets the last checkbox number for a specified id
function getLastCheckbox(id)
{
	var totalBoxes = 0;
	for(i=1; i<200; i++)
	{
		if(document.getElementById(id + '_' + i) == null)
		{
			totalBoxes = i - 1;
			break;
		}
	}
	return(totalBoxes);
}

// only allows numerals
function restrictInput(type, chr)
{
	switch(type)
	{
		case 'numeric':
			var key = getKey(chr);
			var pattern = /[0-9\x08\x76\x00]/;
			if(key.search(pattern) == -1) return false;
			else return true;
		
		default:
			return false;
	}
}

// equiv. of php's chr()
function getKey(e)
{
	if (window.event)
	{
		return String.fromCharCode(window.event.keyCode);
	} else if (e)
	{
		return String.fromCharCode(e.which);
	} else return null;
}

// if dropdopwn[src] == val then disable target, otherwise enable it
function enableTextBoxOnDropdownVal(target, src, val)
{
	srcElement = document.getElementById(src);
	targElement = document.getElementById(target);
	
	if(srcElement.options[srcElement.selectedIndex].value == val)
	{
		targElement.disabled = false;
	} else
	{
		targElement.disabled = true;
	}
}

window.onload = onLoadEvent;