var badFields = "";          // variable to store bad fields
var badLabels = "";          // variable to store labels of bad fields for coloring
var badInstructions = "";    // variable to store instructions to bad fields

// Array variables
var requiredFieldsArray = ["patientsLastName","patientsFirstName","patientsDOB","patientsHomePhone1","patientsHomePhone2","patientsHomePhone3","physiciansName","physiciansPhone1","physiciansPhone2","physiciansPhone3","modality1","region1","insuredsID","caseManagerName","caseManagerPhone1","caseManagerPhone2","caseManagerPhone3","emailAddress","carrier", "AuthorizedDateStart", "AuthorizedDateEnd", "preCertificationNumber"];
var labelArray = ["PatientName", "DateOfBirth", "Address", "City", "State", "Zip", "HomePhone", "WorkPhone", "ReferringPhysician", "PhysicianPhoneNumber", "Modality", "Region", "RuleOut", "ClaimNumber", "CaseManagerName", "CaseManagerPhone", "CaseManagerNotes", "EmailAddress", "Carrier","ClaimType", "AuthorizedDateStart", "AuthorizedDateEnd", "PreCertificationNumber"];

function isValidAppointment(form) {
	badFields = "";
	badLabels = "";
	badInstructions = "";
	document.all["error"].innerHTML = "";
	
	// START VALIDATION CHECKS
	if (form.patientsLastName.value=="") {
		addField("patientsLastName");
		addLabel("lblPatientName");
		addInstruction("Enter Patient's Last Name");
	}
	if (form.patientsFirstName.value=="") {
		addField("patientsFirstName");
		addLabel("lblPatientName");
		addInstruction("Enter Patient's First Name");
	}
	if (!isValidDate(form.patientsDOB.value)) {
		addField("patientsDOB");
		addLabel("lblDateOfBirth");
		addInstruction("Patient's Date of Birth not a valid date");
	}
	if (form.patientsDOL.value!=""){
		if (!isValidDate(form.patientsDOL.value)) {
			addField("patientsDOL");
			addLabel("lblDateOfLoss");
			addInstruction("Patient's Date of Loss not a valid date");
		}
	}
	if (form.patientsZip.value!="" && !isValidZip(form.patientsZip.value)) {
		addField("patientsZip");
		addLabel("lblZip");
		addInstruction("Invalid Zip Code.");
	}
	if (!isValidPhone(form.patientsHomePhone1.value, form.patientsHomePhone2.value, form.patientsHomePhone3.value)) {
		addField("patientsHomePhone1");
		addField("patientsHomePhone2");
		addField("patientsHomePhone3");
		addLabel("lblHomePhone");
		addInstruction("Patient's Home Phone not a valid phone number");
	}
	if (form.patientsWorkPhone1.value != "" || form.patientsWorkPhone2.value != "" || form.patientsWorkPhone3.value != "") {
		if (!isValidPhone(form.patientsWorkPhone1.value, form.patientsWorkPhone2.value, form.patientsWorkPhone3.value)) {
			addField("patientsWorkPhone1");
			addField("patientsWorkPhone2");
			addField("patientsWorkPhone3");
			addLabel("lblWorkPhone");
			addInstruction("Patient's Work Phone not a valid phone number");
		}
	}
	if (form.physiciansName.value=="") {
		addField("physiciansName");
		addLabel("lblReferringPhysician");
		addInstruction("Enter Referring Physician");
	}
	if (!isValidPhone(form.physiciansPhone1.value, form.physiciansPhone2.value, form.physiciansPhone3.value)) {
		addField("physiciansPhone1");
		addField("physiciansPhone2");
		addField("physiciansPhone3");
		addLabel("lblPhysicianPhoneNumber");
		addInstruction("Physician's Phone Number not a valid phone number");
	}
	if (form.modality1.selectedIndex == 0) {
		addField("modality1");
		addLabel("lblModality");
		addInstruction("Select a Modality")
	}
	if (form.region1.selectedIndex == 0) {
		addField("region1");
		addLabel("lblRegion");
		addInstruction("Select a Region")
	}
	if (form.carrier.selectedIndex == 0) {
		addField("carrier");
		addLabel("lblCarrier");
		addInstruction("Select a Carrier");
	}
//	if (form.carrier.options[form.carrier.selectedIndex].text=="OTHER") {
//		if (form.carrierName.value=="") {
//			addField("carrierName");
//			addLabel("lblCarrierName");
//			addInstruction("You selected OTHER as the carrier. Enter a Carrier Name");
//		}
//	}
	if (form.insuredsID.value=="") {
		addField("insuredsID");
		addLabel("lblClaimNumber");
		addInstruction("Enter Claim Number");
	}
	if (!isRadioSelected(form.claimType)) {
		addLabel("lblClaimType");
		addInstruction("Select a Claim Type");
	}
	
	//DBM - Validate pre-cert and the date ranges
    if (form.preCertificationNumber.value=="") {
        addField("preCertificationNumber");
        addLabel("lblPreCertificationNumber");
        addInstruction("Enter a pre-certification number");
    }
        
    if (!isValidDateRange(form.AuthorizedDateStart.value, form.AuthorizedDateEnd.value)) {
        addField("AuthorizedDateStart");
        addField("AuthorizedDateEnd");
        addLabel("lblAuthorizedDateStart");
        addLabel("lblAuthorizedDateEnd");
        addInstruction("Enter a valid authorized date range");
    }
	//DBM End
	
	if (form.caseManagerName.value=="") {
		addField("caseManagerName");
		addLabel("lblCaseManagerName");
		addInstruction("Enter Case Manager");
	}
	if (!isValidPhone(form.caseManagerPhone1.value, form.caseManagerPhone2.value, form.caseManagerPhone3.value)) {
		addField("caseManagerPhone1");
		addField("caseManagerPhone2");
		addField("caseManagerPhone3");
		addLabel("lblCaseManagerPhone");
		addInstruction("Case Manager's Phone Number not a valid phone number");
	}
	if (!isValidEmail(form.emailAddress.value)) {
		addField("emailAddress");
		addLabel("lblEmailAddress");
		addInstruction("Your Email Address not valid");
	}
	// CHECK IF VALIDATED
	if (badFields.length > 0) {
		clearAppointment(form);
		clearLabels();
		setIncompleteFields(form);
		setIncompleteLabels();
		writeErrors();
		alert("Please enter the fields in red. Refer to top for error description.");
		return false;
	}
	else
		return true;
}

function clearAppointment(form) {
	// set all fields to white
	for (var i=0; i<form.elements.length; i++) {
		if (form.elements[i].type != "submit")
			form.elements[i].style.backgroundColor = "#FFFFFF";	
	}
	// set required fields to required color
	for (var i=0; i<requiredFieldsArray.length; i++) {
		var objField = eval("form." + requiredFieldsArray[i]);
		objField.style.backgroundColor = "#EEEEEE";
	}
}

function setIncompleteFields(form) {
	var badFieldsArray = badFields.substr(0,badFields.length-1).split(",");
	var objField;
	
	// color all bad fields red
	for (var i=0; i<badFieldsArray.length; i++) {
		objField = eval("form." + badFieldsArray[i]);
		objField.style.backgroundColor = "#FFCCCC";
	}
	
	// set focus to first incomplete field
	objField = eval("form." + badFieldsArray[0]);
	if (objField.type.indexOf("select")<0)
		objField.select();
	objField.focus();
}

function setIncompleteLabels() {
	var badLabelsArray = badLabels.substr(0,badLabels.length-1).split(",");
	for (var i=0; i<badLabelsArray.length; i++) {
		var objLabel = eval("document.all['" + badLabelsArray[i] + "']");
		//objLabel.style.backgroundColor = "red";
		objLabel.style.color = "red";
		//objLabel.style.border = "solid 1px white";
	}
}

function clearLabels() {
	for (var i=0; i<labelArray.length; i++) {
		var objLabel = eval("document.all['lbl" + labelArray[i] + "']");
		objLabel.style.backgroundColor = "transparent";
		objLabel.style.color = "black";
		objLabel.style.border = "solid 0px transparent";
	}
}

// WRITES ERRORS ON PAGE
function writeErrors() {
	document.all["error"].innerHTML = "<ul>";
	var instructionsArray = badInstructions.substr(0,badInstructions.length-1).split(",");
	for (var i=0; i<instructionsArray.length; i++)
		document.all["error"].innerHTML = document.all["error"].innerHTML + "<li>" + instructionsArray[i] + ".</li>";
	document.all["error"].innerHTML = document.all["error"].innerHTML + "</ul>";
}

//****************************************************************
//* FUNCTIONS CHECK WHETHER STRING IS LOCATED INSIDE LIST STRING *
//****************************************************************

function addLabel(addValue) {
	if (badLabels.indexOf(addValue) < 0)
		badLabels = badLabels + addValue + ",";
}

function addField(addValue) {
	if (badFields.indexOf(addValue) < 0)
		badFields = badFields + addValue + ",";
}

function addInstruction(addValue) {
	if (badInstructions.indexOf(addValue) < 0)
		badInstructions = badInstructions + addValue + ",";
}

//************************
//* Validation Functions *
//************************

function isValidDate(tDate) {
	var datePattern = /\d{1,2}[/]\d{1,2}[/]\d{4}/;
	var result = tDate.match(datePattern);
	if (result != null)
		return true;
	else
		return false;
}

function isValidDateRange(startDate, endDate) {
    //first validate the dates
    if (isValidDate(startDate) && isValidDate(endDate)) {
        dtStartDate = new Date(startDate)
        dtEndDate = new Date(endDate)
        //the start date has to be before the end date
        if (dtStartDate > dtEndDate) {
            return false;
        }
        else {
            return true;
        }
    }
    //one of the dates is invalid, so it's not a valid range
    return false;
    
}
function isValidPhone(tPhone1, tPhone2, tPhone3) {
	var tPhone = "" + tPhone1 + tPhone2 + tPhone3  // string added in front to make sure string concatenation, not math addition
	var phonePattern = /\d{10}/
	var result = tPhone.match(phonePattern);
	if (result != null)
		return true;
	else
		return false;
}

function isValidZip(tZip) {
	var zipPattern = /\d{5}/
	var result = tZip.match(zipPattern);
	if (result != null)
		return true;
	else
		return false;
}

function isValidEmail(tEmail) {
	var emailPattern = /[a-zA-Z0-9]+[@][a-zA-z0-9]+[.]\w+/
	var result = tEmail.match(emailPattern);
	if (result != null)
		return true;
	else
		return false;
}

//***********************
//* Timestamp Function  *
//***********************
function writeTime() {
	var today = new Date();
	var todayDate = (today.getMonth() + 1) + "/" + (today.getDate()) + "/" + (today.getYear());
	var todayTime;
	
	// add zero b4 seconds and minutes if less than 10
	var todayMinutes;
	var todaySeconds;
	if (today.getMinutes()<10)
		todayMinutes = "0" + today.getMinutes();
	else
		todayMinutes = today.getMinutes();
	
	if (today.getSeconds()<10)
		todaySeconds = "0" + today.getSeconds();
	else
		todaySeconds = today.getSeconds();
		
	if (today.getHours() > 12)
		todayTime = (today.getHours() - 12) + ":" + (todayMinutes) + ":" + (todaySeconds) + " PM";
	else {
		if (today.getHours() == 0)
			todayTime = (today.getHours() + 12) + ":" + (todayMinutes) + ":" + (todaySeconds) + " AM";
		else {
			if (today.getHours() == 12)
				todayTime = (today.getHours()) + ":" + (todayMinutes) + ":" + (todaySeconds) + " PM";
			else
				todayTime = (today.getHours()) + ":" + (todayMinutes) + ":" + (todaySeconds) + " AM";
		}
	}
	document.all["timeStamp"].innerHTML = todayDate + " " + todayTime;
	setTimeout("writeTime()",1000)
}

//This Function Calls The Calendar.html file
function DoCal(szTarget, szFieldLabel) {
	var szDate  = window.showModalDialog("Calendar.html",szFieldLabel,"dialogHeight:230px;dialogWidth:220px;center=1;status=0");
	if((szDate != "") && (szDate != "undefined")) { 
		szTarget.value = szDate; }
}

// This function checks to see if "OTHER" is selected and activates/deactivates the carrier name field
function CheckCarrier() {
//	if (document.appointment.carrier.options[document.appointment.carrier.selectedIndex].text=="OTHER") {
//		document.appointment.carrierName.disabled = false;
//		var lbl = document.getElementById("lblCarrierName");
//		lbl.style.color = "white";
//		lbl.style.fontWeight = "bold";
//		var obj = document.getElementById("carrierName");
//		obj.style.backgroundColor = "#EEEEEE";
//		obj.select();
//		obj.focus();
//	}
//	else {
//		document.appointment.carrierName.disabled = true;	
//		var lbl = document.getElementById("lblCarrierName");
//		lbl.style.color = "black";
//		lbl.style.fontWeight = "normal";
//		var obj = document.getElementById("carrierName");
//		obj.style.backgroundColor = "white";
//	}
}


function isRadioSelected (rdo) {
	var select = false;
	for (var i=0; i<rdo.length; i++) {
		if (rdo[i].checked) {
			select = true;
			break;
		}
	}
	return select;
}