// <!--

// Dearest reader,
//
//    If you are reading this,
//    chances are that you're
//    a web developer.  If so,
//    DO NOT DO ANYTHING I DO
//    ON THIS SITE.  Everything
//    here is an UGLY UGLY UGLY
//    TERRIBLE NO GOOD HACK
//    and the skies will rain
//    FIRE if you lack the shame
//    or restraint to avoid
//    writing code of this
//    'caliber'.
//
//              Love,
//                Jason Scheirer.

function hideandshow(idOne, idTwo)
{
	document.getElementById(idOne).style.display='none';
	document.getElementById(idTwo).style.display='inline';
	// window.status = 'Woo hoo: ' + idOne + '; ' + idTwo; 
	return false;
}

function changeTheTime(inputID)
{
	hourComp = parseInt(document.getElementById(inputID+"_hour").value);
	ampmComp = document.getElementById(inputID+"_ampm").value;
	minuteComp = document.getElementById(inputID+"_minute").value;
	if (ampmComp == 1)
	{
		hourComp = (hourComp + 12);
		if (hourComp == 24)
			hourComp = 12;
	} else {
		if (hourComp == 12)
			hourComp = 0;
	}
	timeComp = ((hourComp < 10)?"0":"") + hourComp + ":" + ((minuteComp < 10)?"0":"") + minuteComp + ":00";
	document.getElementById(inputID).value = timeComp;
}

function changeUsername()
{
	var firstname = document.getElementById("firstname").value;
	var surname = document.getElementById("surname").value;
	var nUname = firstname.substr(0, 1).toLowerCase() + surname.toLowerCase();
	document.getElementById("username").value = nUname;
}

function confirmSend(formElement)
{
	if (confirm("Are you sure you want to submit this form?"))
		return true;
	return false;
}

function isValidEmail(addressS)
{
	emailRegexp = RegExp('^[A-Za-z0-9._\-]+[@]([A-Za-z0-9\-]+[.])+(com|net|edu|us|gov)$', 'i');
	if (emailRegexp.test(addressS))
	{
		return true;
	}
	return false;
}

function fixUserSelectInputs()
{
	var inputsonpage = document.getElementsByTagName('INPUT');
	for (i=0; i<inputsonpage.length; i++)
/*		if (inputsonpage[i].className == 'userselect')
		{
			inputsonpage[i].style.display='none';
			var elementToApply = inputsonpage[i];
			var myButton = document.createElement("span");
			idName = elementToApply.id;
			if (idName == "")
			{
				idName = "UserSelectEl" + i;
				elementToApply.id = idName;
			}
			personName = elementToApply.value;
			if (personName == "")
				personName = "Click to Select a User";
			buttonHTML = "<button onclick=\"window.open('index.php?action=directory&popup=1&divid="+idName+"', 'user', 'status,width=800,height=400,scrollbars');return false;\"><img src=\"/images/person_icon.gif\"> <span style=\"text-decoration: underline;\" id=\""+idName+"_name\">"+personName+"</span></button>";
			myButton.innerHTML = buttonHTML;
			elementToApply.parentNode.insertBefore(myButton, elementToApply);
		} else */ if (inputsonpage[i].className == 'timeselect') {
			var timeRegExp = RegExp(/([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})/);
			var CTimeComponent = inputsonpage[i].value;
			var results = timeRegExp.exec(CTimeComponent);
			hour = 9; minute = 45; ampm = 0;
			if (results)
			{
				hour = results[1]; minute = results[2];
				if (hour >= 12)
				{
					ampm = 1;
					hour -= 12;
				}
				else if (hour == 0)
					hour = 12;
			}
			var elementToApply = inputsonpage[i];
			var idName = elementToApply.id;
			if (idName == "")
			{
				idName = "TIMESelectEl" + i;
				elementToApply.id = idName;
			}
			var myButton = document.createElement("span");
			var hourDropDown = "<select width=\"10\" id=\""+idName+"_hour\" onClick=\"changeTheTime('"+idName+"')\" onChange=\"changeTheTime('"+idName+"')\">\n";
			for (var p=1; p<=12; p++)
			{
				hourDropDown += "<option "+((hour==p)?"selected=\"selected\"":"")+" value=\""+p+"\">"+p+"</option>";
			}
			hourDropDown += "</select>";
			var minuteDropDown = "<select width=\"10\" id=\""+idName+"_minute\" onClick=\"changeTheTime('"+idName+"')\" onChange=\"changeTheTime('"+idName+"')\">\n";
			for (var p=0; p<60; p+=5)
			{
				minuteDropDown += "<option "+((minute==p)?"selected=\"selected\"":"")+" value=\""+p+"\">"+((p < 10)?"0":"")+p+"</option>";
			}
			minuteDropDown += "</select>";
			AMPMDropDown = "<select width=\"10\" id=\""+idName+"_ampm\" onClick=\"changeTheTime('"+idName+"')\" onChange=\"changeTheTime('"+idName+"')\"><option "+((ampm==0)?"selected=\"selected\"":"")+" value=\"0\">AM</option><option "+((ampm==1)?"selected=\"selected\"":"")+" value=\"1\">PM</option></select>";
			myButton.innerHTML = hourDropDown + ":" + minuteDropDown + AMPMDropDown;
			elementToApply.parentNode.insertBefore(myButton, elementToApply);
		}
}

function ChangeWindow(username, fullname, divid)
{
	//window.opener.document.getElementById(divid+'_name').innerHTML=fullname;
	window.opener.document.getElementById(divid).value=username;
	window.close();
}

function ChangeWindowVal(fulldate, divid)
{
	window.opener.document.getElementById(divid).value=fulldate;
	window.opener.document.getElementById(divid).onchange();
	window.close();
}

function toggleBar()
{
	// var isSBSet = document.cookie.charAt(document.cookie.indexOf('sidebar') + 8);
	hide = document.getElementById('sidebar');
	show = document.getElementById('showbar');
	if (hide.style.display == 'none')
		{p=hide;hide=show;show=p;}
	hide.style.display='none';
	show.style.display='block';
	
	// if (isSBSet == '1')
	//	isSBSet = '0';
	// else
	//	isSBSet = '1';
	// var ssIsSet = document.cookie.indexOf('sidebar') + 8;
	// document.cookie = document.cookie.substring(0, ssIsSet) + isSBSet + document.cookie.substr(ssIsSet + 1);
	// window.status = document.cookie + " --- " + document.cookie.charAt(document.cookie.indexOf('sidebar') + 8) + " --- " + isSBSet;
}

function addARow()
{
	var emt = document.getElementById('extramuraltable');
	var myCurNum = emt.childNodes.length + 1;
	// document.getElementById('extramuraltextbox').style.display = 'none';
	var itemInnerHtml = "Agency: <input name=\"agency_"+myCurNum+"\" onkeyup=\"checkIfLastRow(this)\" type=\"text\" size=\"10\"> Title: <input name=\"title_"+myCurNum+"\" onkeyup=\"checkIfLastRow(this)\" size=\"15\"> Your Status: <select name=\"yourstatus_"+myCurNum+"\" onChange=\"checkIfLastRow(this)\"> <option value=\"PI\">P.I.</option><option value=\"CoPi\">Co-P.I.</option><option value=\"CoI\">Co-I</option></select><br />Amount Requested: <input type=\"text\" name=\"amountreq_"+myCurNum+"\" onkeyup=\"checkIfLastRow(this)\" size=\"6\"><br />Period: <input type=\"text\" name=\"period_"+myCurNum+"\" onkeyup=\"checkIfLastRow(this)\" size=\"7\"> Status: <input type=\"text\" name=\"status_"+myCurNum+"\" onkeyup=\"checkIfLastRow(this)\" size=\"7\"> <br />Amount Awarded: <input type=\"text\" name=\"amountrew_"+myCurNum+"\" onkeyup=\"checkIfLastRow(this)\" size=\"6\"><hr />";
	var rowToAdd = document.createElement('div');
	rowToAdd.innerHTML = itemInnerHtml;
	emt.appendChild(rowToAdd);
	document.getElementById('exmuralc').value = myCurNum;
}

function elementHasNoEmptyInputs(elToCheck)
{
	var inputsToCheck = elToCheck.getElementsByTagName('INPUT');
	for (var i=0; i<inputsToCheck.length; i++)
	{
		if (inputsToCheck[i].value == '')
		{
			return 0;
		}
	}
	return 1;
}

function checkIfLastRow(elementToCheck)
{
	var myRef = elementToCheck;
	while (myRef.tagName != "DIV")
	{
		myRef = myRef.parentNode;
	}
	if (myRef == document.getElementById('extramuraltable').lastChild)
	{
		if (elementHasNoEmptyInputs(myRef)) {
			addARow();
		}
	}
	// document.getElementById('extramuraltextbox').value = generateTableText();
}

function parse_float_element(stparse)
{
	return parseFloat(stparse.replace(/[,]/g, ""));
}

function validateCommitteePreferenceForm()
{
	window.status = '['+document.cf_form.name.value+']';
	if (document.cf_form.name.value == "" || document.cf_form.department == "")
	{
		document.getElementById("invalid_error").style.display='block';
		document.getElementById("invalid_error_2").style.display='block';
		document.cf_form.submit_button.disabled = true;
		return false;
	}
	document.getElementById("invalid_error").style.display='none';
	document.getElementById("invalid_error_2").style.display='none';
	document.cf_form.submit_button.disabled = false;
	return true;
}

function validateOmnibusApplication()
{
	var isValid = 1;
	
	// Check first section: name, title, fiscal year, etc.
		firstSection = new Array(
			document.theform.first_name,
			document.theform.last_name,
			document.theform.title,
			document.theform.department,
			document.theform.fiscal_year,
			document.theform.proposal_title
		);
		firstOkay = 1;
		for (i=0; i<firstSection.length; i++)
		{
			if (firstSection[i].value == "")
			{
				firstOkay = 0;
				firstSection[i].style.background = '#FFCCCC';
			} else
				firstSection[i].style.background = 'white';
		}
		document.getElementById('first_section_error').style.display = ((firstOkay == 1)?'none':'block');
		isValid = ((isValid == 1)?firstOkay:0);
	// Check for email addresses.
		if (isValidEmail(document.theform.email.value) && isValidEmail(document.theform.ccemail.value))
		{
			document.theform.email.style.background = 'white';
			document.theform.ccemail.style.background = 'white';
			document.getElementById('email_section_error').style.display = 'none';
		} else {
			isValid = 0;
			if (!isValidEmail(document.theform.email.value))
				document.theform.email.style.background = '#FFCCCC';
			if (!isValidEmail(document.theform.ccemail.value))
				document.theform.ccemail.style.background = '#FFCCCC';
			document.getElementById('email_section_error').style.display = 'block';
		}
	
	// Check second section: human/animal subjects
		if ( (document.theform.human_subjects.value == "") || (document.theform.animal_subjects.value == ""))
		{
			isValid = 0;
			document.getElementById('second_section_error').style.display = 'block';
			if (document.theform.human_subjects.value == "")
				document.theform.human_subjects.style.background = '#FFCCCC';
			else
				document.theform.human_subjects.style.background = 'white';
			if (document.theform.animal_subjects.value == "")
				document.theform.animal_subjects.style.background = '#FFCCCC';
			else
				document.theform.animal_subjects.style.background = 'white';
		} else {
			document.getElementById('second_section_error').style.display = 'none';
			document.theform.human_subjects.style.background = 'white';
			document.theform.animal_subjects.style.background = 'white';
		}
	
	// Check third section: total requested
		var max_amount = (document.theform.travel_only.value=='yes'?1400:2700);
		var totalreq = parse_float_element(document.theform.total_requested.value);
		if (isNaN(totalreq))
			totalreq = 0;
		if ( (totalreq < 0.01) || (totalreq > max_amount) )
		{
			isValid = 0;
			document.getElementById('third_section_error').style.display = 'block';
			document.theform.total_requested.style.background = '#FFCCCC';
		} else {
			document.getElementById('third_section_error').style.display = 'none';
			document.theform.total_requested.style.background = 'white';
		}
		document.theform.total_requested.value = totalreq;
	
	problemdiv = document.getElementById('problems_with_form');
	savesubmit = document.getElementById('save_and_submit');
	if (!savesubmit)
		savesubmit = document.createElement('input');
	if (isValid)
	{
		problemdiv.style.display = 'none';
		savesubmit.disabled = false;
	} else {
		problemdiv.style.display = 'block';
		savesubmit.disabled = true;
	}
	
	// Make total amount
	var est_total = 0.0;
	// Research assistant
		pay = parse_float_element(document.theform.res_assist_pay.value);
		hours = parse_float_element(document.theform.res_assist_hours.value);
		rate = pay*hours;
		if (!isNaN(rate))
			est_total += rate;
	// Clerical assistant
		pay = parse_float_element(document.theform.cler_assist_pay.value);
		hours = parse_float_element(document.theform.cler_assist_hours.value);
		rate = pay*hours;
		if (!isNaN(rate))
			est_total += rate;
	var TheRest = new Array(
		document.theform.permequip_cost,
		document.theform.expsupp_cost,
		document.theform.otherexp_cost,
		document.theform.reg_fees,
		document.theform.subsistence,
		document.theform.transportation,
		document.theform.meeting_trans,
		document.theform.meeting_subsistence
	);
	for (i=0; i<TheRest.length; i++)
	{
		if(!isNaN(parse_float_element(TheRest[i].value)))
			est_total += parse_float_element(TheRest[i].value);
	}
	document.theform.total_estimated.value = est_total;
	return isValid;
}

function checkTextArea(area, id_of_wc, id_of_lc)
{
	var theVal = area.value;
	var whereweare = 0;
	var lines = 1;
	var cols = area.cols;
	while (whereweare < theVal.length)
	{
		var findText = theVal.indexOf('\n', whereweare);
		if ( (findText > whereweare + cols) | (findText == -1))
		{
			if (findText == -1) {
				lines += ((theVal.length - whereweare)/cols)+1;
				whereweare = theVal.length;
			} else {
				lines += ((findText - whereweare)/cols)+1;
				whereweare = findText+1;
			}
			if (whereweare > theVal.length)
				whereweare = theVal.length;
		} else {
			whereweare = findText + 1;
			lines += 1;
		}
		//window.status = "We're at "+whereweare+"/"+theVal.length
		//	+ " -- " + theVal.indexOf('\n', whereweare);
	}
	wordRe = /([a-zA-Z0-9-]+)/g;
	wordcount = 0;
	while (wordRe.exec(theVal))
		wordcount++;
	if (id_of_wc != "")
		document.getElementById(id_of_wc).innerHTML = wordcount;
	if (id_of_lc != "")
		document.getElementById(id_of_lc).innerHTML = parseInt(lines);
	area.rows = lines;
}

function check_sql_textarea(elcheck)
{
	if (elcheck.value.charAt(elcheck.value.length-1) == ';')
		elcheck.form.submit();
	checkTextArea(elcheck, '', '');
}

function fixSlashedDate(eltofix)
{
	var myRe = /^([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{1,4})$/i;
	var varyu = eltofix.value;
	var myRes = myRe.exec(varyu)
	if (myRes)
	{
		var month = parseInt(myRes[1]);
		var day = parseInt(myRes[2]);
		var year = parseInt(myRes[3]);
		if (month < 10)
			month = "0" + month;
		if (day < 10)
			day = "0" + day;
		if (year < 100)
			year += 1900;
		if (year < 1940)
			year += 100;
		formatString = year + "-" + month + "-" + day;
		eltofix.value = formatString;
	}
}

var date_max = 1;

function change_date_rows()
{
	totalstring = '';
	els = document.getElementById('date_container').childNodes;
	for(i=0; i<els.length; i++)
	{
		if (els[i].tagName == 'DIV')
			totalstring += (totalstring==''?'':';')+els[i].getElementsByTagName('input')[0].value+'@'+els[i].getElementsByTagName('input')[1].value;
	}
	document.getElementById('select_date_text').value = totalstring;
	return false;
}

function add_date_row()
{
	html = document.getElementById('date_row_1').innerHTML.replace(/(row_|El)([0-9]+)/g, "row_"+(++date_max));
	el = document.createElement('div');
	el.innerHTML = html;
	el.setAttribute('id', 'date_row_'+(date_max));
	// alert(html);
	(document.getElementById('add_date_button').parentNode).insertBefore(el, document.getElementById('add_date_button'));
	return change_date_rows();
}

function delete_date_row(el)
{
	// window.status = (el.parentNode.getAttribute('id'));
	if (el.parentNode.getAttribute('id') != 'date_row_1')
		ppp = el.parentNode.parentNode.removeChild(el.parentNode);
	return change_date_rows();
}

function validateEmail(address) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   //var reg = /^[a-z0-9._\-]+[@]([a-z0-9\-]+[.])+(com|net|edu|us|gov|uk)\$/i;
   if(reg.test(address) == false) {
      return false;
   }
   else{
	   return true;
   }
}

function regents_validate() {
	if (document.getElementById('aaemail').value.length ==0 ) {
		alert("Please input your accounting assistant email!");
		return false;
	}
	else {
		if ( validateEmail(document.getElementById('aaemail').value) != true) {
			alert('Invalid email address!');
			return false;
		}
	}
	if (document.getElementById('proposal_title').value.length ==0 ){
		alert("Please input your topic title!");
		return false;
	}
	return true;
}

function cor_validate() {
	if (document.getElementById('aaemail').value.length ==0 ) {
		alert("Please input your accounting assistant email!");
		return false;
	}
	else {
		if ( validateEmail(document.getElementById('aaemail').value) != true) {
			alert('Invalid email address!');
			return false;
		}
	}
	if (document.getElementById('proposal_title').value.length ==0 ){
		alert("Please input your proposal title!");
		return false;
	}
	return true;
}
	
// -->
