// For a more flexible event registration routine, see
// http://simon.incutio.com/archive/2004/05/26/addLoadEvent

function attachFormHandlers()
{
  // Ensure we're working with a 'relatively' standards 
  // compliant browser
  if (document.getElementsByTagName)
  {
    var objForm = document.getElementsByTagName('form');

    for (var iCounter=0; iCounter<objForm.length; iCounter++)
      objForm[iCounter].onsubmit = function(){ return checkForm(this, (iCounter-1)); }
  }
  if(window.startList) { //if using anything less than IE7, this function will be included and run. this function allows the popup menu to work in older browsers
	startList();  
  }
}

function custom_validation(validation_switch) {
	//alert(validation_switch);
	var str = '';
	var prog_submitted = false;
	
	if(validation_switch=="add_dept") {
		if(document.getElementById('department_type_id').value!='1') {
			if(document.getElementById('faculty_area_id').value=='' || document.getElementById('faculty_area_id').value=='0') {
				alert("If the department type is not Central Office, you must specify which faculty area the department falls under. Please select a faculty area.");
				return false;
			}
		}
	}
	
	if(validation_switch=="add_programme") {
		for(var i=0;i<document.getElementById('number_of_forms').value;i++) {
			if(document.getElementById('prog_title_'+i).value!='') { //only validate programs that have a title filled in.
				if(!isNotEmpty(document.getElementById('department_id_1_'+i).options[document.getElementById('department_id_1_'+i).selectedIndex].value) && !isNotEmpty(document.getElementById('department_id_2_'+i).options[document.getElementById('department_id_2_'+i).selectedIndex].value)) {
					str = str + ' - ' + " Department\n";	
				}
				if(!isNotEmpty(document.getElementById('category_1_'+i).options[document.getElementById('category_1_'+i).selectedIndex].value) && !isNotEmpty(document.getElementById('category_2_'+i).options[document.getElementById('category_2_'+i).selectedIndex].value)) {
					str = str + ' - ' + " Category\n";	
				}
				if(!isNotEmpty(document.getElementById('prog_study_level_'+i).options[document.getElementById('prog_study_level_'+i).selectedIndex].value)) {
					str = str + ' - ' + " Study Level\n";
				}
				prog_submitted = true;
			} 
		}
		if(!prog_submitted) {
			alert("Please submit at least 1 program title");
			return false;
		}
		if(str!='') {
			alert("Please enter at least one value for:\n"+str);
			return false;
		}
	}
	
	if(validation_switch=="edit_programme") {
		if(document.getElementById('prog_title').value!='') { //only validate programs that have a title filled in.
			if(!isNotEmpty(document.getElementById('department_id_1').options[document.getElementById('department_id_1').selectedIndex].value) && !isNotEmpty(document.getElementById('department_id_2').options[document.getElementById('department_id_2').selectedIndex].value)) {
				str = str + ' - ' + " Department\n";	
			}
			if(!isNotEmpty(document.getElementById('category_1').options[document.getElementById('category_1').selectedIndex].value) && !isNotEmpty(document.getElementById('category_2').options[document.getElementById('category_2').selectedIndex].value)) {
				str = str + ' - ' + " Category\n";	
			}
			if(!isNotEmpty(document.getElementById('prog_study_level').options[document.getElementById('prog_study_level').selectedIndex].value)) {
				str = str + ' - ' + " Study Level\n";
			}
			if(!isNotEmpty(document.getElementById('prog_study_mode').options[document.getElementById('prog_study_mode').selectedIndex].value)) {
				str = str + ' - ' + " Study Mode\n";
			}
			prog_submitted = true;
		} 
		if(!prog_submitted) {
			alert("Please submit a program title");
			return false;
		}
		if(str!='') {
			alert("Please enter at least one value for:\n"+str);
			return false;
		}
	}
	
	if(validation_switch=="add_contact") {
		if((document.getElementById('firstname').value=="" || document.getElementById('lastname').value=="") && document.getElementById('position').value=="") {
			alert("You must supply either: \n - A first name and last name\n - Position");
			return false;
		}
		if(document.getElementById('email').value=="" && document.getElementById('phone').value=="") {
			alert("You must supply either: \n - Phone Number\n - Email Address");
			return false;
		}
	}
	
	if(validation_switch=="add_scholarship") {
		if(isNumber(document.getElementById('value').value) && !isNotEmpty(document.getElementById('currency').options[document.getElementById('currency').selectedIndex].value)) {
			alert("Please enter a currency for the value of the scholarship");
			return false;
		}
	}
	
	if(validation_switch=="prog_acc") {
		if(document.getElementById('acc_title').value=="" || !isNotEmpty(document.getElementById('acc_body').options[document.getElementById('acc_body').selectedIndex].value)) {
			alert("Please supply: \n - Accreditation Title \n - Accreditation Body");
			return false;
		}
	}
	
	if(validation_switch=="prog_acc_body") {
		if(document.getElementById('organisation_name').value=="" || document.getElementById('description').value=="" || document.getElementById('website').value=="") {
			alert("Please supply: \n - Organisation Name \n - Description \n - Website");
			return false;
		}
	}
	
	if(validation_switch=="edit_stats1") {
		var str = '';
		personnel_arr = document.getElementById('personnel').value.split(",");
		percentage_arr = document.getElementById('percentage').value.split(",");
		numeric_arr = document.getElementById('numeric').value.split(",");
		currency_arr = document.getElementById('currency').value.split(",");
		
		for(var i=0;i<personnel_arr.length;i++) {
			if(document.getElementById('st_'+personnel_arr[i]+'_value').value!="" && !isNumber(document.getElementById('st_'+personnel_arr[i]+'_value').value)) {
				str = str + ' - ' + document.getElementById('st_'+personnel_arr[i]+'_value').title + ' (must be a full number)\n';
			}
			if(document.getElementById('st_'+personnel_arr[i]+'_fte').value!="" && !isNumber(document.getElementById('st_'+personnel_arr[i]+'_fte').value)) {
				str = str + ' - ' + document.getElementById('st_'+personnel_arr[i]+'_fte').title + ' (must be a full number)\n';
			}
		}
		for(var i=0;i<numeric_arr.length;i++) {
			if(document.getElementById('st_'+numeric_arr[i]+'_value').value!="" && !isNumber(document.getElementById('st_'+numeric_arr[i]+'_value').value)) {
				str = str + ' - ' + document.getElementById('st_'+numeric_arr[i]+'_value').title + ' (must be a full number)\n';
			}
		}
		for(var i=0;i<percentage_arr.length;i++) {
			if(document.getElementById('st_'+percentage_arr[i]+'_value').value!="" && !isNumber(document.getElementById('st_'+percentage_arr[i]+'_value').value)) {
				str = str + ' - ' + document.getElementById('st_'+percentage_arr[i]+'_value').title + ' (must be a full number)\n';
			}
		}
		for(var i=0;i<currency_arr.length;i++) {
			if(document.getElementById('st_'+currency_arr[i]+'_value').value!="" && !isNumber(document.getElementById('st_'+currency_arr[i]+'_value').value)) {
				str = str + ' - ' + document.getElementById('st_'+currency_arr[i]+'_value').title + ' (must be a full number)\n';
			}
			if(document.getElementById('st_'+currency_arr[i]+'_value').value!="" && !isNotEmpty(document.getElementById('st_'+currency_arr[i]+'_currency').options[document.getElementById('st_'+currency_arr[i]+'_currency')].value)) {
				str = str + ' - ' + document.getElementById('st_'+currency_arr[i]+'_currency').title + '\n';
			}
		}
		if(str!='') {
			alert('Please review the value(s) you provided for: \n' + str);
		}
		return false;
	}
	
	return true;
}

function checkForm(objForm, counter)
{
  var arClass, bValid, str='', found_invalid=false;
  var objField = objForm.getElementsByTagName('*');

  for (var iFieldCounter=0; iFieldCounter<objField.length; iFieldCounter++)
  {
    // Allow for multiple values being assigned to the class attribute
    arClass = objField[iFieldCounter].className.split(' ');
    for (var iClassCounter=0; iClassCounter<arClass.length; iClassCounter++)
    {
	  bValid = true;
	  extra_txt = '';
	  switch (arClass[iClassCounter])
      {
        case 'string':
           bValid = isString(objField[iFieldCounter].value.replace(/^\s*|\s*$/g, ''));
		   if(!bValid) found_invalid=true;
           break;
        case 'number' :
           bValid = isNumber(objField[iFieldCounter].value);
		   if(!bValid) { found_invalid=true; extra_txt = " (must be a whole number)"; }
           break;
        case 'number_or_empty' :
           if(objField[iFieldCounter].value!='') {
           	bValid = isNumber(objField[iFieldCounter].value);
           } else {
           	bValid = true;
           }
		   if(!bValid) { found_invalid=true; extra_txt = " (must be a whole number)"; }
           break;
        case 'email' :
           bValid = isEmail(objField[iFieldCounter].value);
		   if(!bValid) { found_invalid=true; extra_txt = " (must be a valid email address)"; }
		   break;
        case 'select_box' :
           bValid = isNotEmpty(objField[iFieldCounter].options[objField[iFieldCounter].selectedIndex].value);
		   if(!bValid) found_invalid=true;
           break;
        case 'select_box_multiple' :
           bValid = isNotEmpty(objField[iFieldCounter].options.selectedIndex);
           if(!bValid) found_invalid=true;           
           break
      }

      if (bValid == false)
      {
        // If this field is invalid, leave the testing early,
        // and alert the visitor to this error
        str = str + ' - ' + (objField[iFieldCounter].title!='' ? objField[iFieldCounter].title : objField[iFieldCounter].name) + extra_txt + '\n';
      }
    }
  }
	if(found_invalid) {
		alert('Please review the value(s) you provided for: \n' + str);
		return false;
	} else {
		//alert('dave debugging: ' + counter);
		if(!custom_validation(document.forms[counter].id)) { return false };		
        return true;
	}
}

function isString(strValue)
{
  return (typeof strValue == 'string' && strValue != '' && isNaN(strValue));
}

function isNumber(strValue)
{
  return (!isNaN(strValue) && strValue != '');
}

function isEmail(strValue)
{
  var objRE = /^[\w-\.\']{1,}\@([\da-zA-Z-]{1,}\.){1,}[\da-zA-Z-]{2,}$/;

  return (strValue != '' && objRE.test(strValue));
}

function isNotEmpty(strValue)
{
  return ( strValue != '' && strValue != '0' && strValue != -1);
}

function isNumberKey(evt) {
	var charCode = (evt.which) ? evt.which : event.keyCode
	if (charCode > 31 && (charCode < 48 || charCode > 57)) {
		alert("Only numbers are allowed in this field. Please do not use at commas (,) or dots (.)");
		return false;
	}		
	return true;
}
function isFloatKey(evt) {
	evt = (evt) ? evt : event;
	var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
	if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode!= 46){
		alert("For float numbers only dot (.) is allowed. Please do not use commas (,) or any letters.");		
		return false;
	}
	return true;
}
function calcHead(stat_id) {
	var ft_val = document.getElementById('full_time_' + stat_id).value;
	var pt_val = document.getElementById('part_time_' + stat_id).value;
	ft_val = Number(ft_val);
	pt_val = Number(pt_val);		
	var total = (ft_val + pt_val);
	document.getElementById('headcount_' + stat_id).value = total;
}

function calcFTE(stat_id) {
	var ft_val = document.getElementById('full_time_' + stat_id).value;
	var pt_val = document.getElementById('part_time_' + stat_id).value;
	ft_val = Number(ft_val);
	pt_val = Number(pt_val);		
	var total = (ft_val + pt_val/3);
	total = Math.round(total);
	document.getElementById('fte_' + stat_id).value = total;
}
