var validators = new Array();
var _form = null;
var _division_confirm = false;
var _test_confirm = false;

var moz = true;
if (typeof document.all == 'object')
{
	moz = false;
}

function _has_value(_value)
{
	if (_value.replace(/\s/g, "") == "")
	{
		return false;
	}
	else
	{
		return true;
	}
}

function _get_id()
{
	var _href = location.href.split('?');
	if (_href.length == 2)
	{
		var _qs = _href[1].split('&');
		for (var i = 0; i < _qs.length; i++)
		{
			var _parts = _qs[i].split('=');
			if (_parts[0] == 'id')
			{
				return _parts[1];
			}
		}
	}
	return null;
}

function setObjectContent(obj, content)
{
	if (moz)
	{
		obj.textContent = content;
	}
	else
	{
		obj.innerText = content;
	}
}

function ValidateDivision(frm)
{
	if (document.forms[0].active[1].checked == true)
	{
		if (_division_confirm == true)
		{
			return ValidateForm(frm);
		}
		else if (confirm("You have marked this Division Inactive so it will no longer be visible within the MIHS Portal. Do you want to continue?"))
		{
			_division_confirm = true;
			return ValidateForm(frm);
		}
		else
		{
			return false;
		}
	}
	else
	{
		return ValidateForm(frm);
	}
}

function ValidateTest(frm)
{
	// Check to see if the division has been set
	div = document.forms[0].division
	if(div.value > 0) {
	} else {
		alert('Please select a Division.');
		return false;
	}
	
	a = document.forms[0].alcohol_result;
	d = document.forms[0].drug_result;
	if(a.value == 1 && d.value == 1) {
		// If both are "Negative" close test
		document.forms[0].status_closed.checked = true;
		//_test_confirm = true;
	}

	if (document.forms[0].status_closed.checked == true)
	{
		if (_test_confirm == true)
		{
			return ValidateForm(frm);
		}
		else if (confirm("You have marked this Test closed so it will no longer be editable within the MIHS Portal. Do you want to continue?"))
		{
			_test_confirm = true;
			return ValidateForm(frm);
		}
		else
		{
			return false;
		}
	}
	else
	{
		return ValidateForm(frm);
	}
}

function ValidateForm(frm)
{
	_form = frm.id;
	var valid = true;
	for (i in validators)
	{
		if (i != "extend")
		{
			validators[i].Validate();
			_v = validators[i];
			while (typeof _v.valid == 'undefined')
			{
				_v = _v.base;
			}
			if (_v.valid == false)
			{
				valid = false;
			}
		}
	}
	for (i in validators)
	{
		if (i != "extend")
		{
			_v = validators[i];
			while (typeof _v.valid == 'undefined')
			{
				_v = _v.base;
			}
			if (_v.valid == null)
			{
				window.setTimeout("Validate_SubmitTimer()", 250);
				return false;
			}
		}
	}
	return valid;
}

function Validate_SubmitTimer()
{
	var valid = true;
	for (i in validators)
	{
		if (i != "extend")
		{
			_v = validators[i];
			while (typeof _v.valid == 'undefined')
			{
				_v = _v.base;
			}
			if (_v.valid == null)
			{
				window.setTimeout("Validate_SubmitTimer()", 250);
				return false;
			}
			
			if (_v.valid == false)
			{
				valid = false;
			}
		}
	}
	if (valid == true)
	{
		SimulateSubmit();
	}
}

function SimulateSubmit()
{
	if (moz)
	{
		var evt = document.createEvent("MouseEvent");
		evt.initMouseEvent("click", true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
		document.forms[0].submit.dispatchEvent(evt);
	}
	else
	{
		document.forms[0].submit.click();
	}
}

function Validator_OnChange(fieldname)
{
	validators[fieldname].Validate();
}

function BaseValidator(field, fieldName, required, inline)
{
	/*
	if (typeof validators[field.name] != 'undefined')
	{
		alert(fieldName + ": you cannot assign two validators to this field.");
	}
	*/

	this.field = field;
	this.fieldName = fieldName;
	this.required = required;
	this.valid = null;
	
	if (inline == true)
	{
		var span = document.createElement("span");
		span.id = field.name + "-validator";
		span.className = "validator-error";
		span.innerHTML = "&nbsp;";
		
		if (moz)
		{
			this.field.parentNode.insertBefore(span, this.field.nextSibling);
		}
		else
		{
			this.field.parentElement.insertBefore(span, this.field.nextSibling);
		}
		
		eval("this.field.onchange = function() { Validator_OnChange('" + field.name + "'); }");
	}

	validators[field.name] = this;
}

BaseValidator.prototype.Validate = function() {
	if (this.required == false || _has_value(this.field.value))
	{
		this.setValid();
	}
	else
	{
		this.setInvalid("* " + this.fieldName + " is a required field.");
	}	
}

BaseValidator.prototype.setValid = function() {
	validators[this.field.name].valid = true;
	
	var div = document.getElementById(this.field.name + '-validator');
	if (div) div.innerHTML = "&nbsp;";
}

BaseValidator.prototype.setInvalid = function(invalidString) {
	validators[this.field.name].valid = false;
	
	var div = document.getElementById(this.field.name + '-validator');
	if (div) div.innerHTML = '<font color=red>'+invalidString+'</font>';
}

BaseValidator.prototype.setValidAlert = function(invalidString) {
//	validators[this.field.name].valid = true;
	validators[this.field.name].valid = false;
	
	var div = document.getElementById(this.field.name + '-validator');
	if (div) div.innerHTML = '<font color=red>'+invalidString+'</font>';
}

function PasswordValidator(field, fieldName, required, inline)
{
	this.base = new BaseValidator(field, fieldName, required, inline);
	validators[field.name] = this;
}

PasswordValidator.prototype.Validate = function()
{
	if (this.base.required == true && !_has_value(this.base.field.value))
	{
		this.base.setInvalid("* " + this.base.fieldName + " is a required field.");
	}
	else if (this.base.field.value.length < 5)
	{
		this.base.setInvalid("* " + this.base.fieldName + " must be at least 5 characters long.");
	}
	else if (this.base.field.value.length > 10)
	{
		this.base.setInvalid("* " + this.base.fieldName + " must be no more than 10 characters long.");
	}
	else if (!this.base.field.value.match(/(\d+[a-z]+)|([a-z]+\d+)/i))
	{
		this.base.setInvalid("* " + this.base.fieldName + " must contain both letters and numbers.");
	}
	else
	{
		this.base.setValid();
	}
}

function RegexValidator(field, fieldName, required, inline, rex, formatExample)
{
	this.base = new BaseValidator(field, fieldName, required, inline);
	this.regex = rex;
	this.formatExample = formatExample;
	this.valid = null;
	validators[field.name] = this;
}

RegexValidator.prototype.Validate = function() {
	if(this.base.required == false && !_has_value(this.base.field.value)) {
		this.base.setValid();
	}
	else if (this.base.required == true && !_has_value(this.base.field.value))
	{
		this.base.setInvalid("* " + this.base.fieldName + " is a required field.");
	}
	else if (this.regex.test(this.base.field.value))
	{
		this.base.setValid();
	}
	else
	{
		this.base.setInvalid("* " + this.base.fieldName + " must have the format: " + this.formatExample);
	}
}

function MIHSMaskValidator(field, fieldName, required, inline)
{
	//this.base = new RegexValidator(field, fieldName, required, inline, /^\d{3}-\d{5,6}$/i, "400-12345 or 400-123456");
	this.base = new RegexValidator(field, fieldName, required, inline, /^\d{3}\w{0,1}-\d{5,6}$/i, "###{A}-######");
}

function PostalValidator(field, fieldName, required, inline)
{
	this.base = new RegexValidator(field, fieldName, required, inline, /^(\s*[a-ceghj-npr-tvxy]\d[a-z](\s)?\d[a-z]\d\s*)|(\d{5}(-\d{4})?)$/i, "T1A 1A1");
}

function PhoneValidator(field, fieldName, required, inline)
{
	this.base = new RegexValidator(field, fieldName, required, inline, new RegExp("^(\\(?\\d{3}\\)?[-\\s.]?\\d{3}[-.]\\d{4})$"), "(123) 123-1234");
}

function EmailValidator(field, fieldName, required, inline)
{
	this.base = new RegexValidator(field, fieldName, required, inline, new RegExp("^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$"), "user@host.com");
}

function DateValidator(field, fieldName, required, inline)
{
	this.base = new RegexValidator(field, fieldName, required, inline, new RegExp("^(\\d{2})-(\\d{2})-(\\d{4})$"), "mm-dd-yyyy");
	this.valid = null;
	validators[field.name] = this;
}

function TimeValidator(field, fieldName, required, inline)
{
	this.base = new RegexValidator(field, fieldName, required, inline, new RegExp("^(\\d{2}):(\\d{2})$"), "HH:MM");
	this.valid = null;
	validators[field.name] = this;
}

function TextValidator(field, fieldName, required, inline)
{
	this.base = new RegexValidator(field, fieldName, required, inline, new RegExp("^([^0-9]+)$"), "a-Z");
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this;
}

DateValidator.prototype.Validate = function() {
	if (this.base.base.required == true && !_has_value(this.base.base.field.value))
	{
		this.base.base.setInvalid("* " + this.base.base.fieldName + " is a required field.");
	}
	else
	{
		var arr = this.base.regex.exec(this.base.base.field.value);
		if (arr == null)
		{
			this.base.base.setInvalid("* " + this.base.base.fieldName + " must have the format: " + this.base.formatExample);
		}
		else
		{
			var daysInMonth = DaysArray(12);
			if (RegExp.$1 > 12)
			{
				this.base.base.setInvalid("* " + this.base.base.fieldName + " must specify a valid month.");
			}
			else if ((RegExp.$2 > daysInMonth[parseInt(RegExp.$1)]) || (parseInt(RegExp.$1) == '2' && RegExp.$2 > daysInFebruary(parseInt(RegExp.$3))))
			{
				this.base.base.setInvalid("* " + this.base.base.fieldName + " must specify a valid day of the month.");
			}
			else
			{
				this.base.base.setValid();
			}
		}
	}
}

TimeValidator.prototype.Validate = function() {
	if (this.base.base.required == true && !_has_value(this.base.base.field.value))
	{
		this.base.base.setInvalid("* " + this.base.base.fieldName + " is a required field.");
	}
	else
	{
		var arr = this.base.regex.exec(this.base.base.field.value);
		if (arr == null)
		{
			this.base.base.setInvalid("* " + this.base.base.fieldName + " must have the format: " + this.base.formatExample);
		}
		else
		{
			if (RegExp.$1 > 23)
			{
				this.base.base.setInvalid("* Hours must be between 0 and 23.");
			}
			else if (RegExp.$2 > 59)
			{
				this.base.base.setInvalid("* Minutes must be between 0 and 59.");
			}
			else
			{
				this.base.base.setValid();
			}
		}
	}
}

function AjaxValidator(field, fieldName, required, inline, url, keys, onComplete)
{
	this.base = new BaseValidator(field, fieldName, required, inline);
	this.url = url;
	this.keys = keys;
	this.onComplete = onComplete;
	validators[field.name] = this;
}

AjaxValidator.prototype.Validate = function() {
	if (this.base.required == true && !_has_value(this.base.field.value))
	{
		this.base.setInvalid("* " + this.base.fieldName + " is a required field.");
	}
	else
	{
		this.base.valid = null;
		
		var _parameters = this.base.field.name + '=' + this.base.field.value;
		
		if (_get_id())
		{
			_parameters += "&id=" + _get_id();
		}
		for (var i = 0; i < this.keys.length; i++)
		{
			_parameters += "&" + this.keys[i] + "=" + this.base.field.form.elements[this.keys[i]].value;
		}
		
		var myAjax = new Ajax.Request(
			this.url,
			{
				method: 'get',
				parameters: _parameters,
				onComplete: this.onComplete
			}
		);
	}
}

function Company_Validate(xmlRequest, field)
{
	var xml = xmlRequest.responseXML;
	var companynamecheck = xml.getElementsByTagName('companynamecheck');
	if (companynamecheck.length != 1)
	{
		//alert('Error: Invalid XML response (companynamecheck tag not found).');
		Validator_OnChange(field);
	}
	else
	{
		var result = companynamecheck[0].getElementsByTagName('result');
		if (result.length != 1)
		{
			alert('Error: Invalid XML response (result tag not found).');
		}
		else
		{
			if (result[0].getAttribute("error") == "true")
			{
				alert('Error: incorrect parameters.');
			}
			else
			{
				if (result[0].getAttribute("exists") == "false")
				{
					validators[field].base.setValid();
				}
				else if (result[0].getAttribute("exists") == "true")
				{
					validators[field].base.setInvalid("* " + validators[field].base.fieldName + ": this company already appears to exist in the system.");
				}
				else
				{
					alert('Error: Invalid XML response (exists value not supported).');
				}
			}
		}
	}
}

function Division_Validate(xmlRequest, field)
{
	var xml = xmlRequest.responseXML;
	var companynamecheck = xml.getElementsByTagName('divisionnamecheck');
	if (companynamecheck.length != 1)
	{
		//alert('Error: Invalid XML response (divisionnamecheck tag not found).');
		Validator_OnChange(field);
	}
	else
	{
		var result = companynamecheck[0].getElementsByTagName('result');
		if (result.length != 1)
		{
			alert('Error: Invalid XML response (result tag not found).');
		}
		else
		{
			if (result[0].getAttribute("error") == "true")
			{
				alert('Error: incorrect parameters.');
			}
			else
			{
				if (result[0].getAttribute("exists") == "false")
				{
					validators[field].base.setValid();
				}
				else if (result[0].getAttribute("exists") == "true")
				{
					validators[field].base.setInvalid("* " + validators[field].base.fieldName + ": this division already appears to exist in the system.");
				}
				else
				{
					alert('Error: Invalid XML response (exists value not supported).');
				}
			}
		}
	}
}

function User_Validate(xmlRequest, field)
{
	var xml = xmlRequest.responseXML;
	var usernamecheck = xml.getElementsByTagName('usernamecheck');
	if (usernamecheck.length != 1)
	{
		//alert('Error: Invalid XML response (usernamecheck tag not found).');
		Validator_OnChange(field);
	}
	else
	{
		var result = usernamecheck[0].getElementsByTagName('result');
		if (result.length != 1)
		{
			alert('Error: Invalid XML response (result tag not found).');
		}
		else
		{
			if (result[0].getAttribute("error") == "true")
			{
				alert('Error: incorrect parameters.');
			}
			else
			{
				if (result[0].getAttribute("exists") == "false")
				{
					validators[field].base.setValid();
				}
				else if (result[0].getAttribute("exists") == "true")
				{
					validators[field].base.setInvalid("* " + validators[field].base.fieldName + ": this user already appears to exist in the system.");
				}
				else
				{
					alert('Error: Invalid XML response (exists value not supported).');
				}
			}
		}
	}
}

function Employee_Validate(xmlRequest, field)
{
	var xml = xmlRequest.responseXML;
	var employeenamecheck = xml.getElementsByTagName('employeenamecheck');
	if (employeenamecheck.length != 1)
	{
		//alert('Error: Invalid XML response (usernamecheck tag not found).');
		Validator_OnChange(field);
	}
	else
	{
		var result = employeenamecheck[0].getElementsByTagName('result');
		if (result.length != 1)
		{
			alert('Error: Invalid XML response (result tag not found).');
		}
		else
		{
			if (result[0].getAttribute("error") == "true")
			{
				alert('Error: incorrect parameters.');
			}
			else
			{
				if (result[0].getAttribute("exists") == "false")
				{
					validators[field].base.setValid();
				}
				else if (result[0].getAttribute("exists") == "true")
				{
					validators[field].base.setValidAlert("* " + validators[field].base.fieldName + ": this employee already appears to exist in the system.");
				}
				else
				{
					alert('Error: Invalid XML response (exists value not supported).');
				}
			}
		}
	}
}

function MIHS_Validate(xmlRequest, field)
{
	var xml = xmlRequest.responseXML;
	var employeenamecheck = xml.getElementsByTagName('mihsidcheck');
	if (employeenamecheck.length != 1)
	{
		//alert('Error: Invalid XML response (mihsidcheck tag not found).');
		Validator_OnChange(field);
	}
	else
	{
		var result = employeenamecheck[0].getElementsByTagName('result');
		if (result.length != 1)
		{
			alert('Error: Invalid XML response (result tag not found).');
		}
		else
		{
			if (result[0].getAttribute("error") == "true")
			{
				alert('Error: incorrect parameters.');
			}
			else
			{
				if (result[0].getAttribute("exists") == "false")
				{
					validators[field].base.base.setValid();
				}
				else if (result[0].getAttribute("exists") == "true")
				{
					validators[field].base.base.setValidAlert("* " + validators[field].base.base.fieldName + ": there is already a test in the system matching this MIHS ID.");
				}
				else
				{
					alert('Error: Invalid XML response (exists value not supported).');
				}
			}
		}
	}
}

function CompanyValidator(field, fieldName, required, inline)
{
	eval("var _onComplete = function(xmlRequest) { Company_Validate(xmlRequest, '" + field.name + "'); }");
	this.base = new AjaxValidator(field, fieldName, required, inline, '/portal/checkcompanyname.php', new Array(), _onComplete);
}

function UserValidator(field, fieldName, required, inline)
{
	eval("var _onComplete = function(xmlRequest) { User_Validate(xmlRequest, '" + field.name + "'); }");
	this.base = new AjaxValidator(field, fieldName, required, inline, '/portal/checkusername.php', new Array(), _onComplete);
}

function MIHSValidator(field, fieldName, required, inline)
{
	eval("var _onComplete = function(xmlRequest) { MIHS_Validate(xmlRequest, '" + field.name + "'); }");
	this.field = field;
	this.fieldName = fieldName;
	this.required = required;
	this.inline = inline;
	this.base = new AjaxValidator(field, fieldName, required, inline, '/portal/checkmihsid.php', new Array(), _onComplete);
	this.mask = new MIHSMaskValidator(field, fieldName, required, inline);
	validators[field.name] = this;
}

MIHSValidator.prototype.Validate = function() {
	this.mask.base.Validate();
	if (validators[this.field.name].valid == true)
	{
		this.base.Validate();
	}
}

function DivisionValidator(field, fieldName, required, inline)
{
	eval("var _onComplete = function(xmlRequest) { Division_Validate(xmlRequest, '" + field.name + "'); }");
	this.base = new AjaxValidator(field, fieldName, required, inline, '/portal/checkdivisionname.php', new Array("company"), _onComplete);
}

function EmployeeValidator(field, fieldName, required, inline)
{
	eval("var _onComplete = function(xmlRequest) { Employee_Validate(xmlRequest, '" + field.name + "'); }");
	this.base = new AjaxValidator(field, fieldName, required, inline, '/portal/checkemployeename.php', new Array("first_name", "division"), _onComplete);
}

function SATKValidator(field, fieldName, required, inline)
{
	eval("var _onComplete = function(xmlRequest) { SATK_Validate(xmlRequest, '" + field.name + "'); }");
	this.base = new AjaxValidator(field, fieldName, required, inline, '/portal/checksatk.php', new Array(), _onComplete);
}

function SATK_Validate(xmlRequest, field)
{
	// If lab or doctor field has a value, validate satk field
	var labSelect = document.getElementById('lab');
	var mroSelect = document.getElementById('mro');
	var old_satk = document.getElementById('old_satk_number');
	var new_satk = document.getElementById('satk_number');
	var xml = xmlRequest.responseXML;
	var satkcheck = xml.getElementsByTagName('satkcheck');
	if (satkcheck.length != 1)
	{
		//alert('Error: Invalid XML response (satkcheck tag not found).');
		Validator_OnChange(field);
	}
	else
	{
		var result = satkcheck[0].getElementsByTagName('result');
		if (result.length != 1)
		{
			alert('Error: Invalid XML response (result tag not found).');
		}
		else
		{
			if (result[0].getAttribute("error") == "true")
			{
				if(labSelect.value || mroSelect.value) {
					// alert('Error: incorrect parameters.');
					//alert('You must enter a Custody Control Form # if a Lab or MRO is selected.');
					validators[field].base.setValidAlert("* " + validators[field].base.fieldName + ": Required if a Lab or MRO is selected.");
				} else {
					validators[field].base.setValid();
				}
			}
			else
			{
				if (result[0].getAttribute("exists") == "false")
				{
					validators[field].base.setValid();
				}
				else if (result[0].getAttribute("exists") == "true")
				{
					if(new_satk.value==old_satk.value){
						validators[field].base.setValid();
					}else{
						validators[field].base.setValidAlert("* " + validators[field].base.fieldName + ": this already appears to exist in the system.");
					}
				}
				else
				{
					alert('Error: Invalid XML response (exists value not supported).');
				}
			}
		}
	}
}

