/*	prescription_validation.js - 2011 08 01 - Aaron Cooke
 *  -----------------------------------------------------
 *	This object handles most of the form validation and events for the prescription form
 *  in the prescription section of the checkout page. It's roughly organized as follows:
 *
 *		(Lines 1-80)		Comments
 *		(Lines 80-140)		Public Variables And Functions
 *		(Lines 140-360)		Private Variables And Potentially Re-Usable Functions
 *		(Lines 360-1060)	Private Functions For Validation Triggered By Continue onClick Event
 *		(Lines 1060-1400)	Private Functions For Validation Triggered By Sph And Cyl Control OnClick Or OnKeyPress Events
 *		(Lines 1400-1650)	Private Functions For Validation Triggered By OnClick Event Of Specific Radio Buttons
 *		(Lines 1650-1690)	Private Functions For Validation Triggered By OnClick Or OnKeyPress Events Of Shipping State Control
 *
 *	Generally speaking, functions in this object appear in the order in which they're called.
 *
 *  initialize()
 *  ------------
 *  Call this before attempting to use this class. Bad things will happen if you don't.
 *
 *  validateSphAndCyl()
 *  -------------------
 *  This function is called whenever the rx/sph or cyl controls in the new
 *  prescription form experience the onlick or onkeyup events. It takes the values from all four
 *  controls and runs them through a series of functions (starting at around line 1000) that compares
 *  these values against an algorithm constructed from the data in the spreadsheet provided
 *  by Warby Parker. This sequence of functions is also called once during form validation after the Continue
 *  button is clicked.
 *
 *  validateWhetherStateRequiresVerification()
 *  ------------------------------------------
 *  This function is called whenever a value is selected in the shipping-state select control. If
 *  the selected state requires prescription verification, the prescription-verification-method UL
 *  will appear. Otherwise, it will be hidden. The internal functions corresponding to this
 *  validation can be found at the end of this file.
 *
 *  handlePrescriptionControlClicked()
 *  ----------------------------------
 *  This function is called whenever one of the important radio buttons in the prescription checkout
 *  are clicked. This sequence of functions causes the corresponding display element and its
 *	children to become visible. It hides all display elements associated with sibling radio elements
 *  and any child display elements of those siblings. It also resets value of the children of the sibling
 *  display elements, clears any instances of the has-error style class and clears and hides the
 *  validation-problem element. The display element hierarchy is as follows:
 *
 *  prescription-glasses-control
 *		saved-prescription-control
 *  		saved-prescription-list
 *  	new-prescription-list
 *  		new-prescription-table
 *  		prescription-verification-method
 *		dont-have-control
 *  		dont-have-list
 *		call-doctor-control
 *  		call-doctor-list
 *  	need-bifocals-control
 *  		need-bifocals-div
 *  reading-glasses-control
 *		reading-glasses-list
 *  non-prescription-glasses-control
 *		non-prescription-glasses-list
 *
 *	validateControls()
 *	------------------
 *	This function is called whenever the OnClick even of the Continue button is triggered. The sequence of
 *	functions it triggers follows the hierarchy shown above such that only the necessary validations are
 *  performed. Any failed validation causes the {this.isValid} property to be set to {false}. Failed validations also
 *	set the corresponding property in the {currentValidationResult} object to be set to {true}. Once validation is
 *  complete, the state of the form controls, the contents of the validation-problem display element and the
 *	display state of this element are updated accordingly.
 *
 */

function PrescriptionFormValidator()
{
	/* PUBLIC VARIABES */

	this.isValid = true;
	this.formState = 0;
	this.maxNameLength = 90;
	this.maxDoctorNameLength = 90;
	this.maxClinicNameLength = 90;
	this.slideDuration = 400;

	/* PUBLIC FUNCTIONS */

	this.initialize = function()
	{
		currentValidationState = new ValidationStates();
		assignControlIds("");
		validationMessages = new Array();
		that.isValid = true;
	}
	this.toggleSavedPrescriptionDisplay = function(controlNode)
	{
		if (typeof(controlNode.id) != "undefined")
		{
			handleLinkClick(controlNode.id);
		}
	}
	this.validateSphAndCyl = function(controlNode)
	{
		/* RESET THE CONTROL ID ARRAY TO REFLECT THE CONTROL THAT WAS JUST CLICKED */
		var controlId = "";
		if ((typeof(controlNode) != "undefined") && (typeof(controlNode.id) != "undefined"))
		{
			controlId = controlNode.id;
		}
		assignControlIds(controlId);

		/* ONLY RESET THESE VALUES BUT RETAIN THE STATE OF EVERYTHING ELSE */
		currentValidationState.cannotFillLeftPrescription = false;
		currentValidationState.cannotFillRightPrescription = false;
		currentValidationState.cannotFillLeftAndRightPrescriptionTogether = false;

		ValidationOfSphAndCyl("control_onchange");

		/* CLEAR ANY EXISTING VALIDATION MESSAGES AND THEN REASSIGN BASED ON CONTROL STATES.*/
		validationMessages = new Array();
		assignValidationMessages();
		updateControlStyles();
		showValidationMessages();
	}
	this.validateWhetherStateRequiresVerification = function(controlNode)
	{
		/* RESET THE CONTROL ID ARRAY TO REFLECT THE CONTROL THAT WAS JUST CLICKED */
		var controlId = "";
		if ((typeof(controlNode) != "undefined") && (typeof(controlNode.id) != "undefined"))
		{
			controlId = controlNode.id;
		}
		assignControlIds(controlId);
		updateVerificationState();
	}
	this.handlePrescriptionControlClicked = function(controlId)
	{
		assignControlIds(controlId);
		var idParts = controlId.split("~");
		if (idParts.length == 2)
		{
			prescriptionVerificationMethod(idParts[0]);
		}
		else
		{
			prescription_control_clicked(controlId);
		}
		showValidationMessages();
	}
	this.handleSavedPrescriptionControlClicked = function(controlId)
	{
		if (typeof(controlId) == "string")
		{
			savedPrescriptionControlClicked(controlId);
		}
	}
	this.highIndexCheckboxMarked = function(checkboxMarked)
	{
		/* RESET THE CONTROL ID ARRAY TO REFLECT THE CONTROL THAT WAS JUST CLICKED */
		var controlId = "";
		if ((typeof(checkboxMarked) == "object") && (checkboxMarked !== null) && (typeof(checkboxMarked.id) == "string"))
		{
			controlId = checkboxMarked.id;
		}
		assignControlIds(controlId);
		handleCheckboxClickEvent(checkboxMarked);
	}
	this.validateControls = function()
	{
		currentValidationState = new ValidationStates();
		assignControlIds("");
		validationMessages = new Array();
		that.isValid = true;

		/* VALIDATION OF THE FORM STARTS AT THE ROOT CONTROLS (PRESCRIPTION, READING-GLASSES,
		OR NON-PRESCRIPTION) AND PROCEEDS ACCORDINGLY. */
		validateGlassesTypeControls();
		assignValidationMessages();
		updateControlStyles();
		showValidationMessages();
	}
	this.validateControls_MyAccount = function(submitButton)
	{
		if ((typeof(submitButton) != "undefined") && (typeof(submitButton.id) != "undefined"))
		{
			showHighIndexColorbox = false; /* WE DONT WANT THE HIGH INDEX COLORBOX TO APPEAR WHEN UPDATING IN MY PRESCRIPTIONS */
			currentValidationState = new ValidationStates();
			assignControlIds(submitButton.id);
			validationMessages = new Array();
			that.isValid = true;

			/* VALIDATION OF THE FORM STARTS AT THE BRANCH FOR NEW PRESCRIPTION VALIDATION AND
			PROCEEDS ALONG THE NORMAL PATH FROM THERE. */
			validateNewPrescriptionForm();
			assignValidationMessages();
			updateControlStyles();
			showValidationMessages();
			showHighIndexColorbox = true; /* WE DONT WANT THE HIGH INDEX COLORBOX TO APPEAR WHEN UPDATING IN MY PRESCRIPTIONS */
		}
	}

	/* PRIVATE VARIABLES */

	var glassesTypeIds = ["prescription-glasses-control", "reading-glasses-control", "non-prescription-glasses-control"];
	var prescriptionSourceIds = ["saved-prescription-control", "new-prescription-control", "dont-have-control", "call-doctor-control", "need-bifocals-control"];
	var verificationIds = ["select-presciption_upload", "fax-prescription", "contact-doctor"];
	var callDoctorIds = ["name-of-doctor", "name-of-clinic", "state-of-doctor", "birth-date", "high-index-lenses-02"];
	var readingGlassesIds = ["reading-glasses-prescription"];
	var nonPrescriptionIds = ["blank-lenses-control", "will-replace-control"];

	var statesThatRequireVerification = ["Alaska", "Alabama", "Arizona", "California", "Connecticut", "Florida", "Georgia", "Kentucky", "Maine", "Massachusetts", "North Carolina", "New Jersey", "Nevada", "New York", "Ohio", "Rhode Island", "South Carolina", "Tennessee", "Vermont", "Washington"];

	var validationMessages = new Array();
	var oldRxAndCylText = new Array("Plano", "0.00", "Plano", "0.00");
	var showHighIndexColorbox = true;
	var that = this;
	
	// REGEX BELOW SHOULD ALLOW THE FOLLOWING GENERAL PATTERNS CHARACTERISISTICS
	// -- DELIMITER CHARACTERS OF DASH, DOT, SPACE OR NONE
	// -- 1 TO 4 NUMBER EXTENSION WITH EXTENSION POSSIBLY PRECEDED
	// BY 'x', 'X', 'ex', 'EX', 'ext', 'EXT', 'ex.', 'EX.', 'ext.', 'EXT.',
	// 'extension' OR 'Extension'
	// -- 7, 10, 11, 12 OR 15 DIGIT NUMBERS
	// -- POSSIBLE USE OF '+' AT BEGINNING OF 12 AND 15 DIGIT NUMBERS
	// -- POSSIBLE WRAPPING OF AREA CODE WITH PARANTHESES INSTEAD OF USING DELIMITERS
	var sevenDigitPhone = /^\d{3}[\. -]?\d{4}( ([xX] ?|[eE][xX][tT]?\.? ?|[eE]xtension )\d{1,4})?$/;
	var tenDigitPhone = /(^1?[\. -]?\d{3}[\. -]?|^\(\d{3}\) ?)\d{3}[\. -]?\d{4}( ([xX] ?|[eE][xX][tT]?\.? ?|[eE]xtension )\d{1,4})?$/;
	var twelveDigitPhone = /^\+?\d?\d[\. -]?(\d{3}[\. -]?|\(\d{3}\))\d{3}[\. -]?\d{4}( ([xX] ?|[eE][xX][tT]?\.? ?|[eE]xtension )\d{1,4})?$/;
	var fifteenDigitPhone = /^\+?\d?\d[\. -]?\d{3}[\. -]?(\d{3}[\. -]?|\(\d{3}\))\d{3}[\. -]?\d{4}( ([xX] ?|[eE][xX][tT]?\.? ?|[eE]xtension )\d{1,4})?$/;
	
	// REGEX BELOW SHOULD ALLOW THE FOLLOWING GENERAL PATTERNS CHARACTERISISTICS
	// -- MM/DD/CCYY
	// -- YEARS IN THE 20TH OR 21ST CENTURY
	// -- LEADING ZEROES ON MONTHS OR DAYS ARE OPTIONAL
	// -- USE OF SLASH OR DASH AS DELIMITER
	// -- FEBRUARY 29TH IS ALLOWED BUT NOT CHECKED AGAINST THE YEAR VALUE
	var datePattern = /((^0?2[\/](0?\d|[12]\d))|((^0?[469]|^11)[\/](0?\d|[12]?\d|30))|((^1[02]|^0?[13578])[\/](0?\d|[12]?\d|3[01])))[\/][12][90]\d{2}$/;
	
	/* INTERNAL CLASSES THAT MUST BE INITIALIZED */

	var PrescriptionFormControlIdValues = function()
	{
		this.title = "title";
		this.rightRxId = "right_rx_id";
		this.rightCylId = "right_cyl_id";
		this.rightAxisId = "right_axis_id";
		this.leftRxId = "left_rx_id";
		this.leftCylId = "left_cyl_id";
		this.leftAxisId = "left_axis_id";
		this.binocularPd = "pd_id";
		this.leftMonocularPd = "left_pd_id";
		this.rightMonocularPd = "right_pd_id";
		this.hiddenHighIndex = "use-high-index-lenses";
		this.highIndex01 = "use-high-index-lenses-01";
		this.highIndex02 = "use-high-index-lenses-02";
		this.highIndex03 = "use-high-index-lenses-03";
		this.verificationMethod = "prescription-verification-method";
		this.selectPresciptionUpload = "select-prescription_upload";
		this.prescriptionUpload = "prescription-upload";
		this.uploadInstructions = "upload-instructions";
		this.faxPrescription = "fax-prescription";
		this.faxInstructions = "fax-instructions";
		this.contactDoctor = "contact-doctor";
		this.callDoctorToVerify = "call-doctor-to-verify";
		this.doctorNameToVerify = "name-of-doctor-to-verify";
		this.clinicNameToVerify = "name-of-clinic-to-verify";
		this.phoneNumberToVerify = "phone-number-of-doctor-to-verify";
		this.birthDateToVerify = "birth-date-to-verify";
		this.hiddenDoctor = "doctor-name-to-submit";
		this.hiddenClinic = "clinic-name-to-submit";
		this.hiddenPhoneNumber = "phone-number-to-submit";
		this.hiddenState = "doctor-state-to-submit";
		this.hiddenBirthDate = "birth-date-to-submit";
		this.doctorName = "name-of-doctor";
		this.clinicName = "name-of-clinic";
		this.doctorPhone = "phone-number-of-doctor";
		this.doctorState = "state-of-doctor";
		this.birthDate = "birth-date";
		this.validationProblem = "validation-problem";
		this.shippingState = "shipping-state";
		this.leftSphCylValState = "left_sph_cyl_val_state";
		this.rightSphCylValState = "right_sph_cyl_val_state";
		this.highIndexColorbox = "high-index-lens-content";
		this.hasSelectedHighIndex = "has-selected-high-index";
		this.prescriptionStateRequiresVerification = "state-requires-verification";
		this.viewDown = "view-down";
		this.editDown = "edit-down";
		this.verificationDown = "verification-down";
	}
	var prescriptionControlIds = new PrescriptionFormControlIdValues();

	var ValidationStates = function()
	{
		this.glassesTypeNotMarked = false;
		this.prescriptionSourceNotMarked = false;
		this.savedPrescriptionNotMarked = false;
		this.bifocalsProgressiveSourceMarked = false;
		this.nonPrescriptionIntentNotMarked = false;
		this.readingGlassesPrescriptionIsNull = false;
		this.rightAxisNonZeroWhenRightCylIsZero = false;
		this.leftAxisNonZeroWhenLeftCylIsZero = false;
		this.binocularMonocularEnumeration = -1;
		this.prescriptionNameIsNull = false;
		this.prescriptionNameContainsInvalidCharacters = false;
		this.prescriptionNameTooLong = false;
		this.shippingStateNotSelected = false;
		this.verificationMethodNotMarked = false;
		this.prescriptionFileNotUploaded = false;
		this.verificationDoctorNameAndClinicNameBothEmpty = false;
		this.verificationDoctorNameTooLong = false;
		this.verificationDoctorNameContainsInvalidCharacters = false;
		this.verificationClinicNameTooLong = false;
		this.verificationClinicNameContainsInvalidCharacters = false;
		this.verificatinoDoctorClinicStateNotSelected = false;
		this.verificationDoctorPhoneNumberEmpty = false;
		this.verificationDoctorPhoneNumberNotValid = false;
		this.verificationBirthDateEmpty = false;
		this.verificationBirthDateFormatInvalid = false;
		this.verificationBirthDateBeforeMinimum = false;
		this.verificationBirthDateAfterToday = false;
		this.doctorNameAndClinicNameBothEmpty = false;
		this.doctorNameTooLong = false;
		this.doctorNameContainsInvalidCharacters = false;
		this.clinicNameTooLong = false;
		this.clinicNameContainsInvalidCharacters = false;
		this.doctorClinicStateNotSelected = false;
		this.doctorPhoneNumberEmpty = false;
		this.doctorPhoneNumberNotValid = false;
		this.birthDateEmpty = false;
		this.birthDateFormatInvalid = false;
		this.birthDateBeforeMinimum = false;
		this.birthDateAfterToday = false;
		this.cannotFillLeftPrescription = false;
		this.cannotFillRightPrescription = false;
		this.cannotFillLeftAndRightPrescriptionTogether = false;
	}
	var currentValidationState = new ValidationStates();

	// REUSABLE FUNCTIONS THAT ARE PROBABLY IN OTHER LIBRARIES
 	var isNull = function(varToCheck)
	{
		var checkResult = true;
		if (typeof(varToCheck) != "object")
		{
			checkResult = false;
		}
		else if (varToCheck !== null)
		{
			checkResult = false;
		}
		return checkResult;
	}
	var isNonNullObject = function(varToCheck)
	{
		var checkResult = true;
		if (typeof(varToCheck) != "object")
		{
			var isSafari = (navigator.userAgent.toLowerCase().indexOf("safari") > 1);
			if ((isSafari) && (typeof(varToCheck) != "function"))
			{
				checkResult = false;
			}
			else if (!isSafari)
			{
				checkResult = false;
			}
		}
		else if (varToCheck === null)
		{
			checkResult = false;
		}
		return checkResult;
	}
	var isEmptyString = function(varToCheck)
	{
		var checkResult = true;
		if (typeof(varToCheck) != "string")
		{
			checkResult = false;
		}
		else if (varToCheck != "")
		{
			checkResult = false;
		}
		return checkResult;
	}
	var isNonEmptyString = function(varToCheck)
	{
		var checkResult = true;
		if (typeof(varToCheck) != "string")
		{
			checkResult = false;
		}
		else if (varToCheck == "")
		{
			checkResult = false;
		}
		return checkResult;
	}
	var isArray = function(varToCheck)
	{
		var checkResult = true;
		if (!isNonNullObject(varToCheck))
		{
			checkResult = false;
		}
		else if (typeof(varToCheck.length) != "number")
		{
			checkResult = false;
		}
		else if (typeof(varToCheck.push) != "function")
		{
			checkResult = false;
		}
		else if (typeof(varToCheck.pop) != "function")
		{
			checkResult = false;
		}
		return checkResult;
	}
	var getElementArray = function(idList)
	{
		var elementArray = new Array();
		if (isArray(idList))
		{
			var idCount = idList.length;
			for (var i = 0 ; i < idCount ; i++)
			{
				var element = document.getElementById(idList[i]);
				if (element !== null)
				{
					elementArray.push(element);
				}
			}
		}
		return elementArray;
	}
	var confirmOneRadioIsMarked = function(elementList)
	{
		var markedElement = null;
		if (isArray(elementList))
		{
			var elementCount = elementList.length;
			var count = 0;
			var keepLooping = true;
			while ((keepLooping) && (count < elementCount))
			{
				if (isRadioButton(elementList[count]))
				{
					if (elementList[count].checked)
					{
						markedElement = elementList[count];
						keepLooping = false;
					}
				}
				count++;
			}
		}
		return markedElement;
	}
	var isRadioButton = function(elementToCheck)
	{
		var checkResult = true;
		if (!isNonNullObject(elementToCheck))
		{
			checkResult = false;
		}
		else if ((typeof(elementToCheck.nodeName) != "string") || (elementToCheck.nodeName.toUpperCase() != "INPUT"))
		{
			checkResult = false;
		}
		else if ((typeof(elementToCheck.type) != "string") || (elementToCheck.type.toUpperCase() != "RADIO"))
		{
			checkResult = false;
		}
		else if (typeof(elementToCheck.checked) != "boolean")
		{
			checkResult = false;
		}
		return checkResult;
	}
	var getDelimitedString = function(arrayPassed, delimiterPassed)
	{
		var text = "";
		var delimiter = "";
		if (isArray(arrayPassed))
		{
			if (typeof(delimiterPassed) == "string")
			{
				delimiter = delimiterPassed;
			}
			var arrayLength = arrayPassed.length;
			if (arrayLength == 1)
			{
				text = arrayPassed[0];
			}
			else if (arrayLength > 1)
			{
				text = arrayPassed[0];
				for (var i = 1 ; i < arrayLength ; i++)
				{
					text += delimiter;
					text += arrayPassed[i];
				}
			}
		}
		return text;
	}
	var arrayContainsValue = function(arrayToSearch, valueToFind)
	{
		var containsResult = false;
		if ((isArray(arrayToSearch)) && (typeof(valueToFind) == "string"))
		{
			var arrayLength = arrayToSearch.length;
			for (var i = 0 ; i < arrayLength ; i++)
			{
				if (arrayToSearch[i].toString() == valueToFind)
				{
					containsResult = true;
					i = arrayLength;
				}
			}
		}
		return containsResult;
	}
	var getChildrenOfParentWithNodeName = function(parent, nodeNameToFind)
	{
		var elements = new Array();
		if ((isValidParent(parent)) && (typeof(nodeNameToFind) == "string"))
		{
			var children = parent.childNodes;
			var childCount = children.length;
			for (var i = 0 ; i < childCount ; i++)
			{
				if ((typeof(children[i].nodeName) == "string") && (children[i].nodeName == nodeNameToFind))
				{
					elements.push(children[i]);
				}
			}
		}
		return elements;
	}
	var isValidParent = function(parentToCheck)
	{
		var checkResult = true;
		if (!isNonNullObject(parentToCheck))
		{
			checkResult = false;
		}
		else if (!isNonNullObject(parentToCheck.childNodes))
		{
			checkResult = false;
		}
		else if (typeof(parentToCheck.childNodes.length) != "number")
		{
			checkResult = false;
		}
		return checkResult;
	}
	var stringContainsInvalidCharacters = function(stringToCheck)
	{
		var containsInvalidCharacters = false;
		if (typeof(stringToCheck) == "string")
		{
			var text = stringToCheck.toUpperCase();
			var textLength = text.length;
			var charCode = 0;
			var validCharacter = false;
			for (var i = 0 ; i < textLength ; i++)
			{
				charCode = text.charCodeAt(i);

				if ((charCode >= 48) && (charCode <= 57))
				{
					validCharacter = true;
				}
				else if ((charCode >= 65) && (charCode <= 90))
				{
					validCharacter = true;
				}
				else if ((charCode == 32) || (charCode == 45) || (charCode == 39) || (charCode == 46) || (charCode == 44) || (charCode == 34))
				{
					validCharacter = true;
				}

				if (!validCharacter)
				{
					containsInvalidCharacters = true;
					i = textLength;
				}
				else
				{
					validCharacter = false;
				}
			}
		}
		return containsInvalidCharacters;
	}
	var getCurrentDate = function()
	{
		var rightNow = new Date();
		var year = rightNow.getFullYear();
		var month = rightNow.getMonth() + 1;
		var day = rightNow.getDate();
		return new Date(year, month, day);
	}
	var isValidPhoneNumber = function(phoneNumberToValidate)
	{
		var isValid = false;
		if (typeof(phoneNumberToValidate) == "string")
		{
			if (sevenDigitPhone.test(phoneNumberToValidate))
			{
				isValid = true;
			}	
			else if (tenDigitPhone.test(phoneNumberToValidate))
			{
				isValid = true;
			}
			/*else if (twelveDigitPhone.test(phoneNumberToValidate))
			{
				isValid = true;
			}
			else if (fifteenDigitPhone.test(phoneNumberToValidate))
			{
				isValid = true;
			}*/
		}
		return isValid;
	}
	var updateControlClasses = function(controlId, hasError)
	{
		if ((isNonEmptyString(controlId)) && (typeof(hasError) == "boolean"))
		{
			var control = document.getElementById(controlId);
			if (control !== null)
			{
				var controlClasses = control.className;
				var indexOfResult = controlClasses.indexOf("has-error");
				if ((hasError) && (indexOfResult == -1))
				{
					if (controlClasses.length == 0)
					{
						control.className = "has-error";
					}
					else
					{
						control.className += " has-error";
					}
				}
				if ((!hasError) && (indexOfResult != -1))
				{
					var newClasses = "";
					var classArray = controlClasses.split(" ");
					var classCount = classArray.length;
					for (var i = 0 ; i < classCount ; i++)
					{
						if (classArray[i] != "has-error")
						{
							newClasses += classArray[i];
						}
					}
					control.className = newClasses;
				}
			}
		}
	}

	/* PRIVATE FUNCTIONS FOR FORM VALIDATION THAT OCCURS WHEN CONTINUE
	BUTTON EXPERIENCES ONCLICK EVENT */

	var assignControlIds = function(currentId)
	{
		var newIdText = "";
		if (isNonEmptyString(currentId))
		{
			var idParts = currentId.split("~");
			if (idParts.length == 2)
			{
				newIdText = "~" + idParts[1];
			}
		}

		prescriptionControlIds.title = "title" + newIdText;
		prescriptionControlIds.rightRxId = "right_rx_id" + newIdText;
		prescriptionControlIds.rightCylId = "right_cyl_id" + newIdText;
		prescriptionControlIds.rightAxisId = "right_axis_id" + newIdText;
		prescriptionControlIds.leftRxId = "left_rx_id" + newIdText;
		prescriptionControlIds.leftCylId = "left_cyl_id" + newIdText;
		prescriptionControlIds.leftAxisId = "left_axis_id" + newIdText;
		prescriptionControlIds.binocularPd = "pd_id" + newIdText;
		prescriptionControlIds.leftMonocularPd = "left_pd_id" + newIdText;
		prescriptionControlIds.rightMonocularPd = "right_pd_id" + newIdText;
		prescriptionControlIds.hiddenHighIndex = "use-high-index-lenses" + newIdText;
		prescriptionControlIds.highIndex01 = "high-index-lenses-01" + newIdText;
		prescriptionControlIds.highIndex02 = "high-index-lenses-02";
		prescriptionControlIds.highIndex03 = "high-index-lenses-03";
		prescriptionControlIds.verificationMethod = "prescription-verification-method" + newIdText;
		prescriptionControlIds.selectPresciptionUpload = "select-prescription_upload" + newIdText;
		prescriptionControlIds.prescriptionUpload = "prescription-upload" + newIdText;
		prescriptionControlIds.uploadInstructions = "upload-instructions" + newIdText;
		prescriptionControlIds.faxPrescription = "fax-prescription" + newIdText;
		prescriptionControlIds.faxInstructions = "fax-instructions" + newIdText;
		prescriptionControlIds.contactDoctor = "contact-doctor" + newIdText;
		prescriptionControlIds.callDoctorToVerify = "call-doctor-to-verify" + newIdText;
		prescriptionControlIds.doctorNameToVerify = "name-of-doctor-to-verify" + newIdText;
		prescriptionControlIds.clinicNameToVerify = "name-of-clinic-to-verify" + newIdText;
		prescriptionControlIds.phoneNumberToVerify = "phone-number-of-doctor-to-verify" + newIdText;
		prescriptionControlIds.birthDateToVerify = "birth-date-to-verify" + newIdText;
		prescriptionControlIds.hiddenDoctor = "doctor-name-to-submit" + newIdText;
		prescriptionControlIds.hiddenClinic = "clinic-name-to-submit" + newIdText;
		prescriptionControlIds.hiddenPhoneNumber = "phone-number-to-submit" + newIdText;
		prescriptionControlIds.hiddenState = "doctor-state-to-submit" + newIdText;
		prescriptionControlIds.hiddenBirthDate = "birth-date-to-submit" + newIdText;
		prescriptionControlIds.doctorName = "name-of-doctor" + newIdText;
		prescriptionControlIds.clinicName = "name-of-clinic" + newIdText;
		prescriptionControlIds.doctorPhone = "phone-number-of-doctor" + newIdText;
		prescriptionControlIds.doctorState = "state-of-doctor" + newIdText;
		prescriptionControlIds.birthDate = "birth-date" + newIdText;
		prescriptionControlIds.validationProblem = "validation-problem" + newIdText;
		prescriptionControlIds.shippingState = "shipping-state" + newIdText;
		prescriptionControlIds.leftSphCylValState = "left_sph_cyl_val_state" + newIdText;
		prescriptionControlIds.rightSphCylValState = "right_sph_cyl_val_state" + newIdText;
		prescriptionControlIds.highIndexColorbox = "high-index-lens-content";
		prescriptionControlIds.hasSelectedHighIndex = "has-selected-high-index" + newIdText;
		prescriptionControlIds.prescriptionStateRequiresVerification = "state-requires-verification" + newIdText;
		prescriptionControlIds.viewDown = "view-down" + newIdText;
		prescriptionControlIds.editDown = "edit-down" + newIdText;
		prescriptionControlIds.verificationDown = "verification-down" + newIdText;
	}

	var showValidationMessages = function()
	{
		var element = document.getElementById(prescriptionControlIds.validationProblem);
		if (element !== null)
		{
			if (validationMessages.length > 0)
			{
				element.innerHTML = getDelimitedString(validationMessages, "<br/>");
				element.style.display = "block";
	            //scroll to validation messages
	            jQuery('html,body').animate({scrollTop:jQuery('#'+prescriptionControlIds.validationProblem.replace('~','\\~')).offset().top},500);
			}
			else
			{
				element.style.display = "none";
				element.innerHTML = "";
			}
		}
	}
	var validateGlassesTypeControls = function()
	{
		var elementArray = getElementArray(glassesTypeIds);
		var glassesElement = confirmOneRadioIsMarked(elementArray);
		if (glassesElement !== null)
		{
			switch (glassesElement.id)
			{
				case "prescription-glasses-control":
					validatePrescriptionSourceControls();
					break;
				case "reading-glasses-control":
					validateReadingGlassesControls();
					break;
				case "non-prescription-glasses-control":
					validateNonPrescriptionGlassesControls();
					break;
				default:
					// INSERT SOME SORT OF ERROR HANDLING CODE HERE
					that.isValid = false;
					break;
			}
		}
		else
		{
			that.isValid = false;
			currentValidationState.glassesTypeNotMarked = true;
		}
	}
	var validatePrescriptionSourceControls = function()
	{
		var elementArray = getElementArray(prescriptionSourceIds);
		var prescriptionSourceElement = confirmOneRadioIsMarked(elementArray);
		if (prescriptionSourceElement !== null)
		{
			switch (prescriptionSourceElement.id)
			{
				case "saved-prescription-control":
					validateSavedPrescriptionControls();
					break;
				case "new-prescription-control":
					validateNewPrescriptionForm();
					break;
				case "dont-have-control":
					handlePreferHighIndexCheckbox(prescriptionControlIds.highIndex02);
					break;
				case "call-doctor-control":
					validateCallDoctorForm();
					break;
				case "need-bifocals-control":
					that.isValid = false;
					currentValidationState.bifocalsProgressiveSourceMarked = true;
					break;
				default:
					// INSERT SOME SORT OF ERROR HANDLING CODE HERE
					that.isValid = false;
					break;
			}
		}
		else
		{
			that.isValid = false;
			currentValidationState.prescriptionSourceNotMarked = true;
		}
	}
	var validateReadingGlassesControls = function()
	{
		var elementArray = getElementArray(readingGlassesIds);
		var readingElement = document.getElementById(elementArray[0].id);
		if (readingElement !== null)
		{
			var selectedValue = readingElement.options[readingElement.selectedIndex].text;
			//debug.line("Reading Glasses Strength : " + selectedValue);
			if (readingElement.options[readingElement.selectedIndex].value === 'null') {
                that.isValid = false;
                currentValidationState.readingGlassesPrescriptionIsNull = true;
			}
		}
		else
		{
			// INSERT SOME SORT OF ERROR HANDLING CODE HERE
			that.isValid = false;
		}
	}
	var validateNonPrescriptionGlassesControls = function()
	{
		var elementArray = getElementArray(nonPrescriptionIds);
		var nonPrescriptionElement = confirmOneRadioIsMarked(elementArray);
		if (nonPrescriptionElement !== null)
		{
			switch (nonPrescriptionElement.id)
			{
				case "blank-lenses-control":
					// DO NOTHING AT THIS TIME
					break;
				case "will-replace-control":
					// DO NOTHING AT THIS TIME
					break;
				default:
					// INSERT SOME SORT OF ERROR HANDLING CODE HERE
					that.isValid = false;
					break;
			}
		}
		else
		{
			that.isValid = false;
			currentValidationState.nonPrescriptionIntentNotMarked = true;
		}
	}
	var validateSavedPrescriptionControls = function()
	{
		var savedList = document.getElementById("saved-prescription-list");
		var markedPrescription = null;
		if (savedList !== null)
		{
			var listElements = getChildrenOfParentWithNodeName(savedList, "LI");
			var savedPrescriptions = new Array();
			var idCount = listElements.length;
			var savedPrescription = null;
			for (var i = 0 ; i < idCount ; i++)
			{
				savedPrescription = document.getElementById("prescription-" + listElements[i].id);
				if (savedPrescription !== null)
				{
					savedPrescriptions.push(document.getElementById("prescription-" + listElements[i].id));
				}
			}
			markedPrescription = confirmOneRadioIsMarked(savedPrescriptions);
			if (markedPrescription === null)
			{
				that.isValid = false;
				currentValidationState.savedPrescriptionNotMarked = true;
			}
		}
	}
	var validateNewPrescriptionForm = function()
	{
		validateCylAndAxis("Left");
		validateCylAndAxis("Right");
		ValidationOfSphAndCyl("continue onclick");
		validateMonocularAndBinocular();
		validateNameTextInput();
		validateStateSelection();
	}
	var validateCylAndAxis = function(sideToValidate)
	{
		var cyl = null;
		var axis = null;
		if (sideToValidate == "Left")
		{
			cyl = document.getElementById(prescriptionControlIds.leftCylId);
			axis = document.getElementById(prescriptionControlIds.leftAxisId);
		}
		else if (sideToValidate == "Right")
		{
			cyl = document.getElementById(prescriptionControlIds.rightCylId);
			axis = document.getElementById(prescriptionControlIds.rightAxisId);
		}

		if ((cyl !== null) && (axis !== null))
		{
			var cylValue = cyl.options[cyl.selectedIndex].text;
			var axisValue = axis.options[axis.selectedIndex].text;
			if ((cylValue == "0.00") && (axisValue != "0"))
			{
				that.isValid = false;
				if (sideToValidate == "Right")
				{
					currentValidationState.rightAxisNonZeroWhenRightCylIsZero = true;
				}
				else
				{
					currentValidationState.leftAxisNonZeroWhenLeftCylIsZero = true;
				}
			}
		}
		else
		{
			// INSERT SOME SORT OF ERROR HANDLING CODE HERE
			that.isValid = false;
		}
	}
	var validateMonocularAndBinocular = function()
	{
		currentValidationState.binocularMonocularEnumeration = 0;
		var binocularPd = document.getElementById(prescriptionControlIds.binocularPd);
		var leftMonocularPd = document.getElementById(prescriptionControlIds.leftMonocularPd);
		var rightMonocularPd = document.getElementById(prescriptionControlIds.rightMonocularPd);

		if (binocularPd === null)
		{
			// INSERT SOME SORT OF ERROR HANDLING CODE HERE
			that.isValid = false;
		}
		else if (binocularPd.options[binocularPd.selectedIndex].text != "n/a")
		{
			currentValidationState.binocularMonocularEnumeration += 1;
		}

		if (leftMonocularPd === null)
		{
			// INSERT SOME SORT OF ERROR HANDLING CODE HERE
			that.isValid = false;
		}
		else if (leftMonocularPd.options[leftMonocularPd.selectedIndex].text != "n/a")
		{
			currentValidationState.binocularMonocularEnumeration += 2;
		}

		if (rightMonocularPd === null)
		{
			// INSERT SOME SORT OF ERROR HANDLING CODE HERE
			that.isValid = false;
		}
		else if (rightMonocularPd.options[rightMonocularPd.selectedIndex].text != "n/a")
		{
			currentValidationState.binocularMonocularEnumeration += 4;
		}

		// ACOOKE 2011 10 16 - COMMENTED OUT THE BINOCULAR AND MONOCULAR PD VALIDATION AT CLIENT'S REQUEST
		if ((currentValidationState.binocularMonocularEnumeration != 1) && (currentValidationState.binocularMonocularEnumeration != 6))
		{
			//that.isValid = false;
		}
	}
	var validateNameTextInput = function()
	{
		var nameElement = document.getElementById(prescriptionControlIds.title);
		if (nameElement !== null)
		{
			if (nameElement.value == "")
			{
				that.isValid = false;
				currentValidationState.prescriptionNameIsNull = true;
			}
			else
			{
				if (stringContainsInvalidCharacters(nameElement.value))
				{
					that.isValid = false;
					currentValidationState.prescriptionNameContainsInvalidCharacters = true;
				}
				if (nameElement.value.length > that.maxNameLength)
				{
					that.isValid = false;
					currentValidationState.prescriptionNameTooLong = true;
				}
			}
		}
		else
		{
			// INSERT SOME SORT OF ERROR HANDLING CODE HERE
			that.isValid = false;
		}
	}
	var validateStateSelection = function()
	{
		var stateSelect = document.getElementById(prescriptionControlIds.shippingState);
		if (stateSelect !== null)
		{
			var stateSelected = "";
			if (typeof(stateSelect.selectedIndex) != "undefined")
			{
				stateSelected = stateSelect.options[stateSelect.selectedIndex].text.toUpperCase();
			}

			if ((stateSelected == "SELECT A STATE/PROVINCE") || (stateSelected == "SELECT"))
			{
				that.isValid = false;
				currentValidationState.shippingStateNotSelected = true;
			}
			else if (doesStateRequireVerification(stateSelected))
			{
				validatePrescriptionVerification();
			}
		}
		else
		{
			// INSERT SOME SORT OF ERROR HANDLING CODE HERE
			that.isValid = false;
		}
	}
	var validatePrescriptionVerification = function()
	{
		var idList = new Array(prescriptionControlIds.selectPresciptionUpload, prescriptionControlIds.faxPrescription, prescriptionControlIds.contactDoctor);
		var elementArray = getElementArray(idList);
		var verificationElement = confirmOneRadioIsMarked(elementArray);
		if (verificationElement !== null)
		{
			switch (verificationElement.id)
			{
				case prescriptionControlIds.selectPresciptionUpload:
					validateUploadedPrescription();
					break;
				case prescriptionControlIds.faxPrescription:
					// DO NOTHING AT THIS TIME
					break;
				case prescriptionControlIds.contactDoctor:
					validateCallDoctorToVerifyForm();
					break;
				default:
					// INSERT SOME SORT OF ERROR HANDLING CODE HERE
					that.isValid = false;
					break;
			}
		}
		else
		{
			currentValidationState.verificationMethodNotMarked = true;
			that.isValid = false;
		}
	}
	var validateUploadedPrescription = function()
	{
		var fileUploadElement = document.getElementById(prescriptionControlIds.prescriptionUpload);
		if (fileUploadElement !== null)
		{
			if (fileUploadElement.value == ""&&jQuery(fileUploadElement).is(":visible"))
			{
				that.isValid = false;
				currentValidationState.prescriptionFileNotUploaded = true;
			}
		}
		else
		{
			// INSERT SOME SORT OF ERROR HANDLING CODE HERE
			that.isValid = false;
		}
	}
	var validateCallDoctorToVerifyForm = function()
	{
		validateDoctorAndClinicNameToVerify();
		validateDoctorPhoneNumberToVerify();
		validateDateOfBirthToVerify();
		if (that.isValid)
		{
			setHiddenDoctorFields("verification");
		}
	}
	/* ACOOKE : 2011 08 25 : USING THIS FUNCTION TWICE. SHOULD REFACTOR AND RE-USE
	CODE, BUT GETTING THIS DONE IS MORE IMPORTANT RIGHT NOW. */
	var validateDoctorAndClinicNameToVerify = function()
	{
		var doctorName = document.getElementById(prescriptionControlIds.doctorNameToVerify);
		var clinicName = document.getElementById(prescriptionControlIds.clinicNameToVerify);
		if ((doctorName !== null) && (clinicName !== null))
		{
			if ((doctorName.value == "") && (clinicName.value == ""))
			{
				that.isValid = false;
				currentValidationState.verificationDoctorNameAndClinicNameBothEmpty = true;
			}
			else
			{
				if (doctorName.value != "")
				{
					if (stringContainsInvalidCharacters(doctorName.value))
					{
						that.isValid = false;
						currentValidationState.verificationDoctorNameContainsInvalidCharacters = true;
					}
					if (doctorName.value.length > that.maxDoctorNameLength)
					{
						that.isValid = false;
						currentValidationState.verificationDoctorNameTooLong = true;
					}
				}
				if (clinicName.value != "")
				{
					if (stringContainsInvalidCharacters(clinicName.value))
					{
						that.isValid = false;
						currentValidationState.verificationClinicNameContainsInvalidCharacters = true;
					}
					if (clinicName.value.length > that.maxClinicNameLength)
					{
						that.isValid = false;
						currentValidationState.verificationClinicNameTooLong = true;
					}
				}
			}
		}
		else
		{
			// INSERT SOME SORT OF ERROR HANDLING CODE HERE
			that.isValid = false;
		}
	}
	// ACOOKE : 2001 11 05 : ADDING VALIDATION FOR THE DOCTOR PHONE NUMBER TO VERIFY FIELD. THE
	// REGEX EXPRESSION FOR PHONE NUMBERS IS DEFINED UP IN THE PRIVATE VARIABLES SECTION
	// OF THIS FILE.
	var validateDoctorPhoneNumberToVerify = function()
	{
		var phoneNumber = document.getElementById(prescriptionControlIds.phoneNumberToVerify);
		if (phoneNumber !== null)
		{
			if (phoneNumber.value == "")
			{
				that.isValid = false;
				currentValidationState.verificationDoctorPhoneNumberEmpty = true;
			}
			else
			{
				if (!isValidPhoneNumber(phoneNumber.value))
				{
					that.isValid = false;
					currentValidationState.verificationDoctorPhoneNumberNotValid = true;
				}
			}
		}
		else
		{
			// INSERT SOME SORT OF ERROR HANDLING CODE HERE			
			that.isValid = false;
		}
	}
	// ACOOKE : 2011 08 25 : TODO : REFACTOR TO COMBINE THIS AND CODE FOR CALL DOCTOR RX SOURCE
	var validateDateOfBirthToVerify = function()
	{
		var dateOfBirth = document.getElementById(prescriptionControlIds.birthDateToVerify);
		if (dateOfBirth !== null)
		{
			if (dateOfBirth.value == "")
			{
				that.isValid = false;
				currentValidationState.verificationBirthDateEmpty = true;
			}
			else
			{
				if(!datePattern.test(dateOfBirth.value))
				{
					that.isValid = false;
					currentValidationState.verificationBirthDateFormatInvalid = true;
				}
				else
				{
					var dateParts = dateOfBirth.value.split("/");
					if (dateParts.length != 3)
					{
						that.isValid = false;
						currentValidationState.verificationBirthDateFormatInvalid = true;
					}
					else
					{
						var rightNow = new getCurrentDate();
						var minimumDate = new Date(1900, 1, 1);

						var year = parseInt(dateParts[2]);
						var day = parseInt(dateParts[1]);
						var month = parseInt(dateParts[0]);
						var birthDateValue = new Date(year , month, day);

						var nowValueOf = rightNow.valueOf();
						var birthValueOf = birthDateValue.valueOf();

						if (birthValueOf < minimumDate)
						{
							that.isValid = false;
							currentValidationState.verificationBirthDateBeforeMinimum = true;
						}
						if (birthValueOf > nowValueOf)
						{
							that.isValid = false;
							currentValidationState.verificationBirthDateAfterToday = true;
						}
					}
				}
			}
		}
		else
		{
			// INSERT SOME SORT OF ERROR HANDLING CODE HERE	
			that.isValid = false;
		}
	}
	var validateCallDoctorForm = function()
	{
		validateDoctorAndClinicName();
		validateDoctorClinicState();
		validateDoctorPhoneNumber();
		validateDateOfBirth();
		if (that.isValid)
		{
			setHiddenDoctorFields("source");
			handlePreferHighIndexCheckbox(prescriptionControlIds.highIndex03);
		}
	}
	// ACOOKE : 2011 08 25 : TODO : REFACTOR TO COMBINE THIS AND CODE FOR CALL DOCTOR RX SOURCE
	var validateDoctorAndClinicName = function()
	{
		var doctorName = document.getElementById("name-of-doctor");
		var clinicName = document.getElementById("name-of-clinic");
		if ((doctorName !== null) && (clinicName !== null))
		{
			if ((doctorName.value == "") && (clinicName.value == ""))
			{
				that.isValid = false;
				currentValidationState.doctorNameAndClinicNameBothEmpty = true;
			}
			else
			{
				if (doctorName.value != "")
				{
					if (stringContainsInvalidCharacters(doctorName.value))
					{
						that.isValid = false;
						currentValidationState.doctorNameContainsInvalidCharacters = true;
					}
					if (doctorName.value.length > that.maxDoctorNameLength)
					{
						that.isValid = false;
						currentValidationState.doctorNameTooLong = true;
					}
				}

				if (clinicName.value != "")
				{
					if (stringContainsInvalidCharacters(clinicName.value))
					{
						that.isValid = false;
						currentValidationState.clinicNameContainsInvalidCharacters = true;
					}
					if (clinicName.value.length > that.maxClinicNameLength)
					{
						that.isValid = false;
						currentValidationState.clinicNameTooLong = true;
					}
				}
			}
		}
		else
		{
			// INSERT SOME SORT OF ERROR HANDLING CODE HERE	
			that.isValid = false;
		}
	}
	var validateDoctorClinicState = function()
	{
		var doctorState = document.getElementById("state-of-doctor");
		if (doctorState !== null)
		{
			var doctorStateValue = doctorState.options[doctorState.selectedIndex].text;
			if ((doctorStateValue == "Select A State/Province") || (doctorStateValue == "Select"))
			{
				that.isValid = false;
				currentValidationState.doctorClinicStateNotSelected = true;
			}
		}
		else
		{
			// INSERT SOME SORT OF ERROR HANDLING CODE HERE
			that.isValid = false;
		}
	}
	// ACOOKE : 2001 11 05 : ADDING VALIDATION FOR THE DOCTOR PHONE NUMBER FIELD. THE
	// REGEX EXPRESSION FOR PHONE NUMBERS IS DEFINED UP IN THE PRIVATE VARIABLES SECTION
	// OF THIS FILE.
	var validateDoctorPhoneNumber = function()
	{
		var phoneNumber = document.getElementById(prescriptionControlIds.doctorPhone);
		if (phoneNumber !== null)
		{
			if (phoneNumber.value == "")
			{
				that.isValid = false;
				currentValidationState.doctorPhoneNumberEmpty = true;
			}
			else
			{
				if (!isValidPhoneNumber(phoneNumber.value))
				{
					that.isValid = false;
					currentValidationState.doctorPhoneNumberNotValid = true;
				}
			}
		}
		else
		{
			// INSERT SOME SORT OF ERROR HANDLING CODE HERE
			that.isValid = false;
		}
	}
	// ACOOKE : 2011 08 25 : USING THIS FUNCTION TWICE. SHOULD REFACTOR AND RE-USE
	// CODE, BUT GETTING THIS DONE IS MORE IMPORTANT RIGHT NOW.
	var validateDateOfBirth = function()
	{
		var dateOfBirth = document.getElementById(prescriptionControlIds.birthDate);
		if (dateOfBirth !== null)
		{
			if (dateOfBirth.value == "")
			{
				that.isValid = false;
				currentValidationState.birthDateEmpty = true;
			}
			else
			{
				if (!datePattern.test(dateOfBirth.value))
				{
					that.isValid = false;
					currentValidationState.birthDateFormatInvalid = true;
				}
				else
				{
					var dateParts = dateOfBirth.value.split("/");
					if (dateParts.length != 3)
					{
						that.isValid = false;
						currentValidationState.birthDateFormatInvalid = true;
					}
					else
					{
						var rightNow = new getCurrentDate();
						var minimumDate = new Date(1900, 1, 1);

						var year = parseInt(dateParts[2]);
						var day = parseInt(dateParts[1]);
						var month = parseInt(dateParts[0]);
						var birthDateValue = new Date(year , month, day);

						var nowValueOf = rightNow.valueOf();
						var birthValueOf = birthDateValue.valueOf();

						if (birthValueOf < minimumDate)
						{
							that.isValid = false;
							currentValidationState.birthDateBeforeMinimum = true;
						}
						if (birthValueOf > nowValueOf)
						{
							that.isValid = false;
							currentValidationState.birthDateAfterToday = true;
						}
					}
				}
			}
		}
		else
		{
			// INSERT SOME SORT OF ERROR HANDLING CODE HERE
			that.isValid = false;
		}
	}
	var setHiddenDoctorFields = function(source)
	{
		if ((typeof(source) == "string") && (that.isValid))
		{
			var hiddenDoctor = document.getElementById(prescriptionControlIds.hiddenDoctor);
			var hiddenClinic = document.getElementById(prescriptionControlIds.hiddenClinic);
			var hiddenPhoneNumber = document.getElementById(prescriptionControlIds.hiddenPhoneNumber);
			var hiddenState = document.getElementById(prescriptionControlIds.hiddenState);
			var hiddenBirthDate = document.getElementById(prescriptionControlIds.hiddenBirthDate);

			var doctorSource = null;
			var clinicSource = null;
			var phoneSource = null;
			var stateSource = null;
			var birthDateSource = null;

			if (source == "verification")
			{
				doctorSource = document.getElementById(prescriptionControlIds.doctorNameToVerify);
				clinicSource = document.getElementById(prescriptionControlIds.clinicNameToVerify);
				phoneSource = document.getElementById(prescriptionControlIds.phoneNumberToVerify);
				stateSource = document.getElementById(prescriptionControlIds.shippingState);
				birthDateSource = document.getElementById(prescriptionControlIds.birthDateToVerify);
			}
			else
			{
				doctorSource = document.getElementById(prescriptionControlIds.doctorName);
				clinicSource = document.getElementById(prescriptionControlIds.clinicName);
				phoneSource = document.getElementById(prescriptionControlIds.doctorPhone);
				stateSource = document.getElementById(prescriptionControlIds.doctorState);
				birthDateSource = document.getElementById(prescriptionControlIds.birthDate);
			}
			
			updateHiddenField(doctorSource, hiddenDoctor);
			updateHiddenField(clinicSource, hiddenClinic);
			updateHiddenField(phoneSource, hiddenPhoneNumber);
			updateHiddenField(stateSource, hiddenState);
			updateHiddenField(birthDateSource, hiddenBirthDate);
		}
	}
	var updateHiddenField = function(sourceElement, hiddenElement)
	{
		if (hiddenElement !== null)
		{
			hiddenElement.value = (sourceElement !== null) ? sourceElement.value : "";
		}
		else 
		{
			// INSERT SOME SORT OF ERROR HANDLING CODE HERE
			that.isValid = false;				
		}
	}
	var assignValidationMessages = function()
	{
		if (currentValidationState.glassesTypeNotMarked)
		{
			validationMessages.push("You must select the type of glasses that you will need.");
		}
		if (currentValidationState.prescriptionSourceNotMarked)
		{
			validationMessages.push("For prescription glasses, you must select a source for the prescription.");
		}
		if (currentValidationState.savedPrescriptionNotMarked)
		{
			validationMessages.push("A saved prescription must be selected if this source is chosen.");
		}
		if (currentValidationState.bifocalsProgressiveSourceMarked)
		{
			validationMessages.push("We need to know how we are going to get your prescription. Please check one of the Choices in this section.");
		}
		if (currentValidationState.nonPrescriptionIntentNotMarked)
		{
			validationMessages.push("No Non Prescription Use Marked");
		}
		if (currentValidationState.readingGlassesPrescriptionIsNull)
		{
    		validationMessages.push("Select a strength for your reading glasses.");
		}
		if ((currentValidationState.rightAxisNonZeroWhenRightCylIsZero) || (currentValidationState.leftAxisNonZeroWhenLeftCylIsZero))
		{
			validationMessages.push("A non-zero Axis value cannot be selected if zero is selected for Cyl.");
		}
		// ACOOKE 2011 10 16 - COMMENTED OUT THE BINOCULAR AND MONOCULAR PD VALIDATION AT CLIENT'S REQUEST
		//if (currentValidationState.binocularMonocularEnumeration == 0)
		//{
			//validationMessages.push("A Binocular Pupillary Distance or Left and Right Monocular Pupillary Distance values must be selected.");
		//}
		//if ((currentValidationState.binocularMonocularEnumeration == 2) || (currentValidationState.binocularMonocularEnumeration == 4))
		//{
			//validationMessages.push("Both Left and Right Monocular Pupillary Distance values must be selected.");
		//}
		//if ((currentValidationState.binocularMonocularEnumeration == 3) || (currentValidationState.binocularMonocularEnumeration == 5) || (currentValidationState.binocularMonocularEnumeration == 7))
		//{
			//validationMessages.push("Binocular and Monocular Pupillary Distance values cannot be selected at the same time.");
		//}
		if (currentValidationState.prescriptionNameIsNull)
		{
			validationMessages.push("You must enter a valid name for the new prescription.");
		}
		if (currentValidationState.prescriptionNameContainsInvalidCharacters)
		{
			validationMessages.push("The prescription name can only contain letters, numbers, spaces, commas, periods, hypens, apostrophes and quotation markes.");
		}
		if (currentValidationState.prescriptionNameTooLong)
		{
			validationMessages.push("The prescription name cannot be more than " + that.maxNameLength.toString() + " characters in length.");
		}
		if (currentValidationState.shippingStateNotSelected)
		{
			validationMessages.push("When entering a new prescription you must select the state/region to which the glasses or sunwear will be shipped.");
		}
		if (currentValidationState.verificationMethodNotMarked)
		{
			validationMessages.push("You are shipping to a state that requires prescription verification. You must select a verification method.");
		}
		if (currentValidationState.prescriptionFileNotUploaded)
		{
			validationMessages.push("You must upload a prescription file if you select the 'Upload A File' verification method.");
		}
		if (currentValidationState.doctorNameAndClinicNameBothEmpty)
		{
			validationMessages.push("You must enter a valid name into at least the Doctor Name or Clinic Name field.");
		}
		if (currentValidationState.doctorNameTooLong)
		{
			validationMessages.push("The doctor name cannot be more than " + that.maxDoctorNameLength.toString() + " characters in length");
		}
		if (currentValidationState.doctorNameContainsInvalidCharacters)
		{
			validationMessages.push("The doctor name can only contain letters, numbers, spaces, commas, periods, hypens, apostrophes and quotation markes.");
		}
		if (currentValidationState.clinicNameTooLong)
		{
			validationMessages.push("The doctor name cannot be more than " + that.maxClinicNameLength.toString() + " characters in length");
		}
		if (currentValidationState.clinicNameContainsInvalidCharacters)
		{
			validationMessages.push("The clinic name can only contain letters, numbers, spaces, commas, periods, hyphens, apostrophes and quotation markes.");
		}
		if (currentValidationState.doctorClinicStateNotSelected)
		{
			validationMessages.push("You must select the state where the doctor or clinic is located.");
		}
		if (currentValidationState.doctorPhoneNumberEmpty)
		{
			validationMessages.push("You must enter a phone number for your doctor.");
		}
		if (currentValidationState.doctorPhoneNumberNotValid)
		{
			validationMessages.push("Please enter a valid phone number. For example 987-654-321-1234 x5678.");
		}
		if (currentValidationState.birthDateEmpty)
		{
			validationMessages.push("You must enter a valid birth date.");
		}
		if (currentValidationState.birthDateFormatInvalid)
		{
			validationMessages.push("The birth date entered must be formatted 'mm/dd/ccyy'.");
		}
		if (currentValidationState.birthDateBeforeMinimum)
		{
			validationMessages.push("The birth date entered cannot be prior to '01/01/1900'.");
		}
		if (currentValidationState.birthDateAfterToday)
		{
			validationMessages.push("The birth date entered cannot be after today.");
		}
		if (currentValidationState.verificationDoctorNameAndClinicNameBothEmpty)
		{
			validationMessages.push("You must enter a valid name into at least the Doctor Name or Clinic Name field.");
		}
		if (currentValidationState.verificationDoctorNameTooLong)
		{
			validationMessages.push("The doctor name cannot be more than " + that.maxDoctorNameLength.toString() + " characters in length");
		}
		if (currentValidationState.verificationDoctorNameContainsInvalidCharacters)
		{
			validationMessages.push("The doctor name can only contain letters, numbers, spaces, commas, periods, hypens, apostrophes and quotation markes.");
		}
		if (currentValidationState.verificationClinicNameTooLong)
		{
			validationMessages.push("The doctor name cannot be more than " + that.maxClinicNameLength.toString() + " characters in length");
		}
		if (currentValidationState.verificationClinicNameContainsInvalidCharacters)
		{
			validationMessages.push("The clinic name can only contain letters, numbers, spaces, commas, periods, hyphens, apostrophes and quotation markes.");
		}
		if (currentValidationState.verificationDoctorPhoneNumberEmpty)
		{
			validationMessages.push("You must enter a phone number for your doctor.");
		}
		if (currentValidationState.verificationDoctorPhoneNumberNotValid)
		{
			validationMessages.push("Please enter a valid phone number. For example 987-654-321-1234 x5678.");
		}
		if (currentValidationState.verificationBirthDateEmpty)
		{
			validationMessages.push("You must enter a valid birth date.");
		}
		if (currentValidationState.verificationBirthDateFormatInvalid)
		{
			validationMessages.push("The birth date entered must be formatted 'mm/dd/ccyy'.");
		}
		if (currentValidationState.verificationBirthDateBeforeMinimum)
		{
			validationMessages.push("The birth date entered cannot be prior to '01/01/1900'.");
		}
		if (currentValidationState.verificationBirthDateAfterToday)
		{
			validationMessages.push("The birth date entered cannot be after today.");
		}
		if ((currentValidationState.cannotFillLeftPrescription) || (currentValidationState.cannotFillRightPrescription) || (currentValidationState.cannotFillLeftAndRightPrescriptionTogether))
		{
			validationMessages.push("Warby Parker cannot fill this prescription. Please consider purchasing Non-Prescription Glasses with blank lenses.");
		}
	}
	// ACOOKE 2011 10 16 - COMMENTED OUT THE BINOCULAR AND MONOCULAR PD VALIDATION AT CLIENT'S REQUEST
	var updateControlStyles = function()
	{
		/* UPDATE NEW PRESCRIPTION FORM CONTROLS FROM VALIDATION RESULTS */
		updateControlClasses(prescriptionControlIds.rightAxisId, currentValidationState.rightAxisNonZeroWhenRightCylIsZero);
		updateControlClasses(prescriptionControlIds.leftAxisId, currentValidationState.leftAxisNonZeroWhenLeftCylIsZero);
		switch (currentValidationState.binocularMonocularEnumeration)
		{
			case 6:
			case 1:
				updateControlClasses(prescriptionControlIds.binocularPd, false);
				updateControlClasses(prescriptionControlIds.leftMonocularPd, false);
				updateControlClasses(prescriptionControlIds.rightMonocularPd, false);
				break;
			case 0:
			case 7:
				//updateControlClasses(prescriptionControlIds.binocularPd, true);
				//updateControlClasses(prescriptionControlIds.leftMonocularPd, true);
				//updateControlClasses(prescriptionControlIds.rightMonocularPd, true);
				break;
			case 2:
				//updateControlClasses(prescriptionControlIds.binocularPd, false);
				//updateControlClasses(prescriptionControlIds.leftMonocularPd, false);
				//updateControlClasses(prescriptionControlIds.rightMonocularPd, true);
				break;
			case 3:
				//updateControlClasses(prescriptionControlIds.binocularPd, true);
				//updateControlClasses(prescriptionControlIds.leftMonocularPd, true);
				//updateControlClasses(prescriptionControlIds.rightMonocularPd, false);
				break;
			case 4:
				//updateControlClasses(prescriptionControlIds.binocularPd, false);
				//updateControlClasses(prescriptionControlIds.leftMonocularPd, true);
				//updateControlClasses(prescriptionControlIds.rightMonocularPd, false);
				break;
			case 5:
				//updateControlClasses(prescriptionControlIds.binocularPd, true);
				//updateControlClasses(prescriptionControlIds.leftMonocularPd, false);
				//updateControlClasses(prescriptionControlIds.rightMonocularPd, true);
				break;

		}
		if ((currentValidationState.prescriptionNameIsNull) || (currentValidationState.prescriptionNameContainsInvalidCharacters) || (currentValidationState.prescriptionNameTooLong))
		{
			updateControlClasses(prescriptionControlIds.title, true);
		}
		else
		{
			updateControlClasses(prescriptionControlIds.title, false);
		}

		/* UPDATE PRESCRIPTION VERIFICATION FORM CONTROLS FROM VALIDATION RESULTS */
		updateControlClasses(prescriptionControlIds.shippingState, currentValidationState.shippingStateNotSelected);
		updateControlClasses(prescriptionControlIds.prescriptionUpload, currentValidationState.prescriptionFileNotUploaded);
		if ((currentValidationState.verificationDoctorNameAndClinicNameBothEmpty) || (currentValidationState.verificationDoctorNameTooLong) || (currentValidationState.verificationDoctorNameContainsInvalidCharacters))
		{
			updateControlClasses(prescriptionControlIds.doctorNameToVerify, true);
		}
		else
		{
			updateControlClasses(prescriptionControlIds.doctorNameToVerify, false);
		}
		if ((currentValidationState.verificationDoctorNameAndClinicNameBothEmpty) || (currentValidationState.verificationClinicNameTooLong) || (currentValidationState.verificationClinicNameContainsInvalidCharacters))
		{
			updateControlClasses(prescriptionControlIds.clinicNameToVerify, true);
		}
		else
		{
			updateControlClasses(prescriptionControlIds.clinicNameToVerify, false);
		}
		if ((currentValidationState.verificationDoctorPhoneNumberNotValid) || (currentValidationState.verificationDoctorPhoneNumberEmpty))
		{
			updateControlClasses(prescriptionControlIds.phoneNumberToVerify, true);
		}
		else
		{
			updateControlClasses(prescriptionControlIds.phoneNumberToVerify, false);
		}
		if ((currentValidationState.verificationBirthDateEmpty) || (currentValidationState.verificationBirthDateFormatInvalid) || (currentValidationState.verificationBirthDateBeforeMinimum) || (currentValidationState.verificationBirthDateAfterToday))
		{
			updateControlClasses(prescriptionControlIds.birthDateToVerify, true);
		}
		else
		{
			updateControlClasses(prescriptionControlIds.birthDateToVerify, false);
		}

		/* UPDATE CONTACT DOCTOR FORM CONTROLS FROM VALIDATION RESULTS */
		if ((currentValidationState.doctorNameAndClinicNameBothEmpty) || (currentValidationState.doctorNameTooLong) || (currentValidationState.doctorNameContainsInvalidCharacters))
		{
			updateControlClasses("name-of-doctor", true);
		}
		else
		{
			updateControlClasses("name-of-doctor", false);
		}
		if ((currentValidationState.doctorNameAndClinicNameBothEmpty) || (currentValidationState.clinicNameTooLong) || (currentValidationState.clinicNameContainsInvalidCharacters))
		{
			updateControlClasses("name-of-clinic", true);
		}
		else
		{
			updateControlClasses("name-of-clinic", false);
		}
		if (currentValidationState.doctorClinicStateNotSelected)
		{
			updateControlClasses("state-of-doctor", true);
		}
		else
		{
			updateControlClasses("state-of-doctor", false);
		}
		if ((currentValidationState.doctorPhoneNumberEmpty) || (currentValidationState.doctorPhoneNumberNotValid))
		{
			updateControlClasses(prescriptionControlIds.doctorPhone, true);
		}
		else
		{
			updateControlClasses(prescriptionControlIds.doctorPhone, false);
		}
		if ((currentValidationState.birthDateEmpty) || (currentValidationState.birthDateFormatInvalid) || (currentValidationState.birthDateBeforeMinimum) || (currentValidationState.birthDateAfterToday))
		{
			updateControlClasses("birth-date", true);
		}
		else
		{
			updateControlClasses("birth-date", false);
		}

		/* UPDATE NEW PRESCRIPTION FORM CONTROLS FROM VALIDATION OF PRESCRIPTION STRENGTH */
		if (currentValidationState.cannotFillLeftAndRightPrescriptionTogether)
		{
			updateControlClasses(prescriptionControlIds.rightRxId, true);
			updateControlClasses(prescriptionControlIds.rightCylId, true);
			updateControlClasses(prescriptionControlIds.leftRxId, true);
			updateControlClasses(prescriptionControlIds.leftCylId, true);
		}
		else
		{
			if (currentValidationState.cannotFillLeftPrescription)
			{
				updateControlClasses(prescriptionControlIds.leftRxId, true);
				updateControlClasses(prescriptionControlIds.leftCylId, true);
			}
			else
			{
				updateControlClasses(prescriptionControlIds.leftRxId, false);
				updateControlClasses(prescriptionControlIds.leftCylId, false);
			}
			if (currentValidationState.cannotFillRightPrescription)
			{
				updateControlClasses(prescriptionControlIds.rightRxId, true);
				updateControlClasses(prescriptionControlIds.rightCylId, true);
			}
			else
			{
				updateControlClasses(prescriptionControlIds.rightRxId, false);
				updateControlClasses(prescriptionControlIds.rightCylId, false);
			}
		}
	}

	// PRIVATE FUNCTIONS RELATED TO PRESCRIPTION STATE CALCULATION THAT'S TRIGGERED
	// WHEN A VALUE IS SELECTED IN RIGHT_RX_ID, RIGHT_CYL_ID, LEFT_RX_ID, LEFT_CYL_ID
	var ValidationOfSphAndCyl = function(callingEvent)
	{
		if ((callingEvent !== null) && (typeof(callingEvent) == "string") && (callingEvent != ""))
		{
			var newRxAndCylText = getNewSphAndCylText();
			var valuesHaveChanged = false;
			if (callingEvent == "control onchange")
			{
				for (var i = 0 ; i < 4 ; i++)
				{
					if (newRxAndCylText[i] != oldRxAndCylText[i])
					{
						valuesHaveChanged = true;
						i = 4;
					}
				}
			}
			else
			{
				valuesHaveChanged = true;
			}

			if (valuesHaveChanged)
			{
				var leftHiddenElement = document.getElementById(prescriptionControlIds.leftSphCylValState);
				var rightHiddenElement = document.getElementById(prescriptionControlIds.rightSphCylValState);
				if ((leftHiddenElement !== null) && (rightHiddenElement !== null))
				{
					var newRxAndCylValues = getNewSphAndCylValues();
					var newLeftState = getStateFromSphAndCyl(newRxAndCylValues[2], newRxAndCylValues[3]);
					var newRightState = getStateFromSphAndCyl(newRxAndCylValues[0], newRxAndCylValues[1]);

					if (newLeftState == 8)
					{
						currentValidationState.cannotFillLeftPrescription = true;
						that.isValid = false;
					}
					if (newRightState == 8)
					{
						currentValidationState.cannotFillRightPrescription = true;
						that.isValid = false;
					}

					if ((newLeftState.toString() != leftHiddenElement.value) || (newRightState.toString() != rightHiddenElement.value))
					{
						updateControlStates(newLeftState, newRightState);
					}

					leftHiddenElement.value = newLeftState;
					rightHiddenElement.value = newRightState;
				}
			}
		}
	}
	var getNewSphAndCylText = function()
	{
		var newRightRxText = null;
		var newRightCylText = null;
		var newLeftRxText = null;
		var newLeftCylText = null;

		var rightSph = document.getElementById(prescriptionControlIds.rightRxId);
		if (rightSph !== null)
		{
			newRightRxText = rightSph.options[rightSph.selectedIndex].text;
		}
		var rightCyl = document.getElementById(prescriptionControlIds.rightCylId);
		if (rightCyl !== null)
		{
			newRightCylText = rightCyl.options[rightCyl.selectedIndex].text;
		}
		var leftRx = document.getElementById(prescriptionControlIds.leftRxId);
		if (leftRx !== null)
		{
			newLeftRxText = leftRx.options[leftRx.selectedIndex].text;
		}
		var leftCyl = document.getElementById(prescriptionControlIds.leftCylId);
		if (leftCyl !== null)
		{
			newLeftCylText = leftCyl.options[leftCyl.selectedIndex].text;
		}

		// GETS A TEXT ARRAY THAT CONTAINS THE TEXT VALUES OF THE SPH AND CYL CONTROLS

		var newTextArray = new Array();
		newTextArray.push(newRightRxText);
		newTextArray.push(newRightCylText);
		newTextArray.push(newLeftRxText);
		newTextArray.push(newLeftCylText);
		return newTextArray;
	}
	var getNewSphAndCylValues = function()
	{
		var newRightRxValue = null;
		var newRightCylValue = null;
		var newLeftRxValue = null;
		var newLeftCylValue = null;

		var rightSph = document.getElementById(prescriptionControlIds.rightRxId);
		if (rightSph !== null)
		{
			newRightRxValue = parseCylOrRxToFloat(rightSph.options[rightSph.selectedIndex].text);
		}
		var rightCyl = document.getElementById(prescriptionControlIds.rightCylId);
		if (rightCyl !== null)
		{
			newRightCylValue = parseCylOrRxToFloat(rightCyl.options[rightCyl.selectedIndex].text);
		}
		var leftRx = document.getElementById(prescriptionControlIds.leftRxId);
		if (leftRx !== null)
		{
			newLeftRxValue = parseCylOrRxToFloat(leftRx.options[leftRx.selectedIndex].text);
		}
		var leftCyl = document.getElementById(prescriptionControlIds.leftCylId);
		if (leftCyl !== null)
		{
			newLeftCylValue = parseCylOrRxToFloat(leftCyl.options[leftCyl.selectedIndex].text);
		}

		// GETS AN ARRAY OF FLOAT VALUES CORRESPONDING TO THE RX AND CYL CONTROLS
		var newValueArray = new Array();
		newValueArray.push(newRightRxValue);
		newValueArray.push(newRightCylValue);
		newValueArray.push(newLeftRxValue);
		newValueArray.push(newLeftCylValue);

		return newValueArray;
	}
	var parseCylOrRxToFloat = function(valueText)
	{
		var valueResult = null;
		if ((valueText !== null) && (typeof(valueText) == "string"))
		{
			if (valueText == "Plano")
			{
				valueResult = 0.0;
			}
			else
			{
				valueResult = parseFloat(valueText);
				if (valueResult == NaN)
				{
					valueResult = null;
				}
			}
		}
		return valueResult;
	}
	var getStateFromSphAndCyl = function(sphValue, cylValue)
	{
		// THIS FUNCTION FIGURES OUT WHERE IN THE WARBY PARKER SPREADSHEET
		// THE PRESCRIPTION LIES
		var finalState = 0;
		if ((typeof(sphValue) == "number") && (typeof(cylValue) == "number"))
		{
			spcySum = sphValue + cylValue;
			if (spcySum < 0.00)
			{
				if (spcySum > -4.00) // BLOCK An - LENSE WILL BE POLYCARBONATE
				{
					finalState = 1;
				}
				else if (spcySum > -10.25) // BLOCK Bn - HIGH INDEX PREFERENCE POPUP DISPLAYED
				{
					finalState = 2;
				}
				else // BLOCK Dn - WARBY PARKER CANNOT FILL
				{
					finalState = 8;
				}
			}
			else
			{
				if (spcySum < 4.00)  // BLOCK Ap - LENSE WILL BE POLYCARBONATE
				{
					finalState = 1;
				}
				else if (spcySum < 6.25) // BLOCK Bp - HIGH INDEX PREFERENCE POPUP DISPLAYED
				{
					finalState = 2;
				}
				else // BLOCK Dp - WARBY PARKER CANNOT FILL
				{
					finalState = 8;
				}
			}
		}
		return finalState;
	}
	var updateControlStates = function(leftEyeState, rightEyeState)
	{
		if ((isValidEyeState(leftEyeState)) && (isValidEyeState(rightEyeState)))
		{
			var leftHiddenElement = document.getElementById(prescriptionControlIds.leftSphCylValState);
			var rightHiddenElement = document.getElementById(prescriptionControlIds.rightSphCylValState);
			var oldFinalState = getFinalState(leftHiddenElement.value, rightHiddenElement.value);
			var newFinalState = getFinalState(leftEyeState, rightEyeState);

			if ((oldFinalState != newFinalState) && (oldFinalState > 0) && (newFinalState > 0))
			{
				switch (newFinalState)
				{
					case 8:

						updateAllCheckboxes(false);
						useHighIndexLenses(false);
						break;

					case 2:

						var hasSelected = document.getElementById(prescriptionControlIds.hasSelectedHighIndex);
						if (hasSelected !== null)
						{
							if (hasSelected.value == "0")
							{
								updateAllCheckboxes(false);
								getHighIndexChoiceFromUser();
							}
							else
							{
								if (hasSelected.value == "1")
								{
									updateAllCheckboxes(true);
									useHighIndexLenses(true);
								}
								else
								{
									updateAllCheckboxes(false);
									useHighIndexLenses(false);
								}
							}
						}
						break;

					case 1:

						updateAllCheckboxes(false);
						useHighIndexLenses(false);
						break;

					default:

						// DO NOTHING FOR NOW
						break;
				}
			}
		}
	}
	var isValidEyeState = function(eyeStateToCheck)
	{
		var checkResult = true;
		if (typeof(eyeStateToCheck) != "number")
		{
			checkResult = false;
		}
		else if ((eyeStateToCheck != 1) && (eyeStateToCheck != 2) && (eyeStateToCheck != 4) && (eyeStateToCheck != 8))
		{
			checkResult = false;			
		}
		return checkResult;
	}
	var getFinalState = function(leftEyeState, rightEyeState)
	{
		var leftValue = parseInt(leftEyeState,10);
		var rightValue = parseInt(rightEyeState,10);
		var finalState = 0;
		if ((!isNaN(leftValue)) || (!isNaN(rightValue)))
		{
			finalState = leftValue | rightValue;
			if (finalState > 3)
			{
				finalState = 8;
			}
			else if (finalState > 1)
			{
				finalState = 2;
			}
			else
			{
				finalState = 1;
			}
		}
		return finalState;
	}
	var getHighIndexChoiceFromUser = function()
	{
		var contentNode = document.getElementById(prescriptionControlIds.highIndexColorbox);
		if ((showHighIndexColorbox) && (contentNode !== null) && (typeof(contentNode.innerHTML) != "undefined"))
		{
			var contentMarkup = contentNode.innerHTML;
			var currentIndex = contentMarkup.indexOf("highIndexId", 0);
			while (currentIndex > -1)
			{
				contentMarkup = contentMarkup.replace("highIndexId", prescriptionControlIds.highIndex01);
				currentIndex = contentMarkup.indexOf("highIndexId", currentIndex);
			}

			var setUserSelected = function()
			{
				var hasSelected = document.getElementById(prescriptionControlIds.hasSelectedHighIndex);
				var highIndexHidden = document.getElementById(prescriptionControlIds.hiddenHighIndex);
				if ((highIndexHidden !== null) && (hasSelected !== null))
				{
					if ((hasSelected.value == "0") || (hasSelected.value == "1"))
					{
						hasSelected.value = "1";
						updateAllCheckboxes(true);
						useHighIndexLenses(true);
					}
					else
					{
						hasSelected.value = "2";
						updateAllCheckboxes(false);
						useHighIndexLenses(false);
					}
				}
			}

			var jOb = jQuery.noConflict();
			jOb(document).bind("cbox_cleanup", setUserSelected);
			jOb["colorbox"]({html:contentMarkup});
		}
	}

	/* PRIVATE FUNCTIONS RELATED TO CONTROLLING THE DISPLAY STATE OF FORM ELEMENTS
	WHEN VARIOUS RADIO BUTTONS WITHIN THE CONTROL ARE MARKED OR UNMARKED */

	var prescription_control_clicked = function(controlId)
	{
		if (isNonEmptyString(controlId))
		{
			var prescription_glasses_list = document.getElementById('prescription-glasses-list');
			var reading_glasses_list = document.getElementById('reading-glasses-list');
			var non_prescription_glasses_list = document.getElementById('non-prescription-glasses-list');

			var keepGoing = true;
			if ((prescription_glasses_list === null) || (reading_glasses_list === null) || (non_prescription_glasses_list === null))
			{
				keepGoing = false;
			}

			if (keepGoing)
			{
				switch (controlId)
				{
					case 'prescription-glasses-control':

						SlideDownDisplayElement(prescription_glasses_list);

						SlideUpDisplayElement(reading_glasses_list);
						ResetAllControlChildren(reading_glasses_list);
						SlideUpDisplayElement(non_prescription_glasses_list);
						ResetAllControlChildren(non_prescription_glasses_list);
						break;

					case 'reading-glasses-control':

						SlideUpDisplayElement(prescription_glasses_list);
						ResetAllControlChildren(prescription_glasses_list);

						SlideDownDisplayElement(reading_glasses_list);

						SlideUpDisplayElement(non_prescription_glasses_list);
						ResetAllControlChildren(non_prescription_glasses_list);
						prescription_submission_method(controlId);
						break;

					case 'non-prescription-glasses-control':

						SlideUpDisplayElement(prescription_glasses_list);
						ResetAllControlChildren(prescription_glasses_list);
						SlideUpDisplayElement(reading_glasses_list);
						ResetAllControlChildren(reading_glasses_list);

						SlideDownDisplayElement(non_prescription_glasses_list);

						prescription_submission_method(controlId);
						break;

					default:

						prescription_submission_method(controlId);
						break;
				}

				showValidationMessages();
			}
		}
	}
	var prescription_submission_method = function(controlId)
	{
		var saved_prescription_list = document.getElementById('saved-prescription-list');
		var new_prescription_table = document.getElementById('new-prescription-table');
		var prescription_verification_method = document.getElementById(prescriptionControlIds.verificationMethod);
		var dont_have_list = document.getElementById('dont-have-list');
		var call_doctor_list = document.getElementById('call-doctor-list');
		var need_bifocals_div = document.getElementById('need-bifocals-div');

		var keepGoing = true;
		if ((saved_prescription_list === null) || (new_prescription_table === null) || (prescription_verification_method === null) || (dont_have_list === null) || (call_doctor_list === null) || (need_bifocals_div === null))
		{
			keepGoing = false;
		}

		if (keepGoing)
		{
			switch (controlId)
			{
				case 'saved-prescription-control':

					SlideUpDisplayElement(new_prescription_table);
					ResetAllControlChildren(new_prescription_table);
					SlideVerificationMethodElement("up");
					SlideUpDisplayElement(dont_have_list);
					ResetAllControlChildren(dont_have_list);
					SlideUpDisplayElement(call_doctor_list);
					resetHiddenDoctorFields();
					ResetAllControlChildren(call_doctor_list);
					SlideUpDisplayElement(need_bifocals_div);
					ResetAllControlChildren(need_bifocals_div);
					useHighIndexLenses(false);
					prescriptionVerificationMethod(controlId);
					break;

				case 'new-prescription-control':

					ResetAllControlChildren(saved_prescription_list);

					SlideDownDisplayElement(new_prescription_table);

					SlideUpDisplayElement(dont_have_list);
					ResetAllControlChildren(dont_have_list);
					SlideUpDisplayElement(call_doctor_list);
					resetHiddenDoctorFields();
					ResetAllControlChildren(call_doctor_list);
					SlideUpDisplayElement(need_bifocals_div);
					ResetAllControlChildren(need_bifocals_div);
					useHighIndexLenses(false);
					break;

				case 'dont-have-control':

					ResetAllControlChildren(saved_prescription_list);
					SlideUpDisplayElement(new_prescription_table);
					ResetAllControlChildren(new_prescription_table);
					SlideVerificationMethodElement("up");

					ResetAllControlChildren(dont_have_list);
					SlideDownDisplayElement(dont_have_list);

					SlideUpDisplayElement(call_doctor_list);
					ResetAllControlChildren(call_doctor_list);
					resetHiddenDoctorFields();
					SlideUpDisplayElement(need_bifocals_div);
					ResetAllControlChildren(need_bifocals_div);
					useHighIndexLenses(false);
					prescriptionVerificationMethod(controlId);
					break;

				case 'call-doctor-control':

					ResetAllControlChildren(saved_prescription_list);
					SlideUpDisplayElement(new_prescription_table);
					ResetAllControlChildren(new_prescription_table);
					SlideVerificationMethodElement("up");
					SlideUpDisplayElement(dont_have_list);
					ResetAllControlChildren(dont_have_list);

					ResetAllControlChildren(call_doctor_list);
					SlideDownDisplayElement(call_doctor_list);

					SlideUpDisplayElement(need_bifocals_div);
					ResetAllControlChildren(need_bifocals_div);
					useHighIndexLenses(false);
					prescriptionVerificationMethod(controlId);
					break;

				case 'need-bifocals-control':

					ResetAllControlChildren(saved_prescription_list);
					SlideUpDisplayElement(new_prescription_table);
					ResetAllControlChildren(new_prescription_table);
					SlideVerificationMethodElement("up");
					SlideUpDisplayElement(dont_have_list);
					ResetAllControlChildren(dont_have_list);
					SlideUpDisplayElement(call_doctor_list);
					ResetAllControlChildren(call_doctor_list);
					resetHiddenDoctorFields();

					SlideDownDisplayElement(need_bifocals_div);
					useHighIndexLenses(false);

					prescriptionVerificationMethod(controlId);
					break;

				case 'select-prescription_upload':
				case 'fax-prescription':
				case 'contact-doctor':

					prescriptionVerificationMethod(controlId);
					break;

				default:

					ResetAllControlChildren(saved_prescription_list);
					SlideUpDisplayElement(new_prescription_table);
					ResetAllControlChildren(new_prescription_table);
					SlideVerificationMethodElement("up");
					SlideUpDisplayElement(dont_have_list);
					ResetAllControlChildren(dont_have_list);
					SlideUpDisplayElement(call_doctor_list);
					ResetAllControlChildren(call_doctor_list);
					resetHiddenDoctorFields();
					SlideUpDisplayElement(need_bifocals_div);
					useHighIndexLenses(false);
					prescriptionVerificationMethod(controlId);
					break;
			}
		}
	}
	var resetHiddenDoctorFields = function()
	{
		var hiddenDoctor = document.getElementById(prescriptionControlIds.hiddenDoctor);
		var hiddenClinic = document.getElementById(prescriptionControlIds.hiddenClinic);
		var hiddenState = document.getElementById(prescriptionControlIds.hiddenState);
		var hiddenPhone = document.getElementById(prescriptionControlIds.hiddenPhoneNumber);
		var hiddenBirthDate = document.getElementById(prescriptionControlIds.hiddenBirthDate);

		if (hiddenDoctor !== null)
		{
			hiddenDoctor.value = "";
		}
		if (hiddenClinic !== null)
		{
			hiddenClinic.value = "";
		}
		if (hiddenState !== null)
		{
			hiddenState.value = "";
		}
		if (hiddenPhone !== null)
		{
			hiddenPhone.value = "";
		}
		if (hiddenBirthDate !== null)
		{
			hiddenBirthDate.value = "";
		}
	}
	var prescriptionVerificationMethod = function(controlId)
	{
		var upload_prescription  = document.getElementById(prescriptionControlIds.prescriptionUpload);
		var upload_instructions = document.getElementById(prescriptionControlIds.uploadInstructions);
		var fax_instructions = document.getElementById(prescriptionControlIds.faxInstructions);
		var call_doctor_to_verify = document.getElementById(prescriptionControlIds.callDoctorToVerify);

		var keepGoing = true;
		if ((upload_prescription === null) || (upload_instructions === null) || (fax_instructions === null) || (call_doctor_to_verify === null))
		{
			keepGoing = false;
		}

		if (keepGoing)
		{
			switch (controlId)
			{
				case 'select-prescription_upload':

					SlideDownDisplayElement(upload_instructions);
					SlideUpDisplayElement(fax_instructions);
					SlideUpDisplayElement(call_doctor_to_verify);
					ResetAllControlChildren(call_doctor_to_verify);
					resetHiddenDoctorFields();
					break;

				case 'fax-prescription':

					SlideUpDisplayElement(upload_instructions);
					ResetAllControlChildren(upload_prescription);
					SlideDownDisplayElement(fax_instructions);
					SlideUpDisplayElement(call_doctor_to_verify);
					ResetAllControlChildren(call_doctor_to_verify);
					resetHiddenDoctorFields();
					break;

				case 'contact-doctor':

					SlideUpDisplayElement(upload_instructions);
					ResetAllControlChildren(upload_prescription);
					SlideUpDisplayElement(fax_instructions);
					SlideDownDisplayElement(call_doctor_to_verify);
					break;

				default:

					SlideVerificationMethodElement("up");
					resetHiddenDoctorFields();
					break;
			}
		}
	}
	var ResetAllControlChildren = function(currentNode)
	{
		if ((typeof(currentNode) == "object") && (currentNode !== null))
		{
			if (currentNode.childNodes.length > 0)
			{
				for (var i = 0 ; i < currentNode.childNodes.length ; i++)
				{
					ResetAllControlChildren(currentNode.childNodes[i]);
				}
			}

			if (ValidControlElement(currentNode.nodeName))
			{
				if (currentNode.type == "radio")
				{
					currentNode.checked = false;
				}
				else if (currentNode.type == "checkbox")
				{
					var highIndexPreference = document.getElementById(prescriptionControlIds.hasSelectedHighIndex);
					if (highIndexPreference !== null)
					{
						if (highIndexPreference.value == 2)
						{
							currentNode.checked = false;
						}
						else
						{
							currentNode.checked = true;
						}
					}
				}
				else if (currentNode.nodeName == "SELECT")
				{
					updateControlClasses(currentNode.id, false);
					var optionCount = currentNode.options.length;
					for (var i = 0 ; i < optionCount ; i++)
					{
						if (currentNode.options[i].defaultSelected)
						{
							currentNode.selectedIndex = i;
							i = optionCount;
						}
					}
				}
				else if ((currentNode.type == 'text') || (currentNode.type == 'file'))
				{
					updateControlClasses(currentNode.id, false);
					currentNode.value = "";
				}
				else if (currentNode.type == "hidden")
				{
					switch (currentNode.id)
					{
						case "verification-down":

							// DO NOTHING FOR NOW
							break;

						default:

							currentNode.value = "0";
							break;
					}
				}
			}
		}
	}
	var ValidControlElement = function(controlName)
	{
		var isValid = false;
		if (typeof(controlName) == "string")
		{
			if ((controlName == "INPUT") || (controlName == "TEXTAREA") || (controlName == "SELECT") || (controlName == "OPTION"))
			{
				isValid = true;
			}
		}
		return isValid;
	}
	var SlideVerificationMethodElement = function(direction)
	{
		if (typeof(direction) == "string")
		{
			var verificationMethod = document.getElementById(prescriptionControlIds.verificationMethod);
			var verificationDown = document.getElementById(prescriptionControlIds.verificationDown);
			var stateRequiresVerification = document.getElementById(prescriptionControlIds.prescriptionStateRequiresVerification);

			if ((verificationMethod !== null) && (verificationDown !== null) && (stateRequiresVerification !== null))
			{
				switch (direction.toLowerCase())
				{
					case "up":

						if (verificationDown.value == "1")
						{
							SlideUpDisplayElement(verificationMethod);
							ResetAllControlChildren(verificationMethod);
							resetHiddenDoctorFields();
							HandleVerificationElement(prescriptionControlIds.uploadInstructions);
							HandleVerificationElement(prescriptionControlIds.faxInstructions);
							HandleVerificationElement(prescriptionControlIds.callDoctorToVerify);

							verificationDown.value = "0";
							stateRequiresVerification.value = "0";
						}
						break;

					case "down":

						if (verificationDown.value == "0")
						{
							SlideDownDisplayElement(verificationMethod);

							verificationDown.value = "1";
							stateRequiresVerification.value = "1";
						}
						else
						{
							ResetAllControlChildren(verificationMethod);
							resetHiddenDoctorFields();
							HandleVerificationElement(prescriptionControlIds.uploadInstructions);
							HandleVerificationElement(prescriptionControlIds.faxInstructions);
							HandleVerificationElement(prescriptionControlIds.callDoctorToVerify);
						};
						break;

					default:

						// DO NOTHING FOR NOW
						break;
				}
			}
		}
	}
	var HandleVerificationElement = function(elementId)
	{
		if (typeof(elementId) == "string")
		{
			var element = document.getElementById(elementId);
			if (element !== null)
			{
				SlideUpDisplayElement(element);
			}
		}
	}
	var SlideDownDisplayElement = function(controlToSlide)
	{
		if ((isNonNullObject(controlToSlide)) && (isNonEmptyString(controlToSlide.id))) 
		{
			var length = controlToSlide.id.split("~").length;
			if (length == 2)
			{
				if ((typeof(that.slideDuration) != "number") || (that.slideDuration <= 0))
				{
					that.slideDuration = 400;
				}

                if (jQuery("#"+controlToSlide.id.replace('~','\\~')+' input[type="file"]').length
                    &&j.browser.msie&&j.browser.version < 8) controlToSlide.style.display = "block";
                else jQuery("#"+controlToSlide.id.replace('~','\\~')).slideDown(that.slideDuration);
			}
			else
			{
                jQuery("#" + controlToSlide.id).slideDown()
			}
		}

	}
	var SlideUpDisplayElement = function(controlToSlide)
	{
		if ((isNonNullObject(controlToSlide)) && (isNonEmptyString(controlToSlide.id))) 
		{
			var length = controlToSlide.id.split("~").length;
			if (length == 2)
			{
				if ((typeof(that.slideDuration) != "number") || (that.slideDuration <= 0))
				{
					that.slideDuration = 400;
				}
				
                if (jQuery("#"+controlToSlide.id.replace('~','\\~')+' input[type="file"]').length
                    &&j.browser.msie&&j.browser.version < 8) controlToSlide.style.display = "none";
				else jQuery("#" + controlToSlide.id.replace('~','\\~')).slideUp(that.slideDuration);
			}
			else
			{
                jQuery("#" + controlToSlide.id).slideUp()
			}
		}
	}

	/* PRIVATE FUNCTIONS RELATED TO SHIPPING STATE VERIFICATION */
	var updateVerificationState = function()
	{
		var selectControl = document.getElementById(prescriptionControlIds.shippingState);
		if (selectControl !== null)
		{
			var stateSelected = selectControl.options[selectControl.selectedIndex].text.toUpperCase();
			var direction = "up";
			if (doesStateRequireVerification(stateSelected))
			{
				direction = "down";
			}
			SlideVerificationMethodElement(direction);
		}
	}
	var doesStateRequireVerification = function(stateName)
	{
		var verificationRequired = false;
		var stateCount = statesThatRequireVerification.length
		for (var i = 0 ; i < stateCount ; i++)
		{
			if (stateName == statesThatRequireVerification[i].toUpperCase())
			{
				verificationRequired = true;
				i = stateCount;
			}
		}
		return verificationRequired;
	}

	/* PRIVATE FUNCTIONS RELATED TO UPDATING CHECKBOX STATES WHEN ANY CHECKBOX IS CLICKED */
	var handlePreferHighIndexCheckbox = function(checkboxId)
	{
		if (typeof(checkboxId) == "string")
		{
			var checkbox = document.getElementById(checkboxId);
			var hiddenHighIndex = document.getElementById(prescriptionControlIds.hasSelectedHighIndex);
			if ((checkbox !== null) && (hiddenHighIndex !== null))
			{
				if (checkbox.checked)
				{
					hiddenHighIndex.value = "1";
				}
				else
				{
					hiddenHighIndex.value = "2";
				}
			}
		}
	}
	var handleCheckboxClickEvent = function(checkboxMarked)
	{
		if ((typeof(checkboxMarked) == 'object') && (checkboxMarked !== null))
		{
			var highIndexPreference = document.getElementById(prescriptionControlIds.hasSelectedHighIndex);
			if (highIndexPreference !== null)
			{
				if (checkboxMarked.checked)
				{
					highIndexPreference.value = "1";
				}
				else
				{
					highIndexPreference.value = "2";
				}
			}

			var hiddenCheckbox = document.getElementById(prescriptionControlIds.hiddenHighIndex);
			if (hiddenCheckbox !== null)
			{
				if ((hiddenCheckbox.value == "1") && (!checkboxMarked.checked))
				{
					updateAllCheckboxes(false);
				}
				else if ((hiddenCheckbox.value == "0") && (checkboxMarked.checked))
				{
					updateAllCheckboxes(true);
				}
			}
		}
	}
	var updateAllCheckboxes = function(setValue)
	{
		if (typeof(setValue) == "boolean")
		{
			var hiddenCheckbox = document.getElementById(prescriptionControlIds.hiddenHighIndex)
			var checkbox01 = document.getElementById(prescriptionControlIds.highIndex01);
			var checkbox02 = document.getElementById(prescriptionControlIds.highIndex02);
			var checkbox03 = document.getElementById(prescriptionControlIds.highIndex03);

			if (checkbox01 !== null)
			{
				checkbox01.checked = setValue;
			}
			if (checkbox02 !== null)
			{
				checkbox02.checked = setValue;
			}
			if (checkbox03 !== null)
			{
				checkbox03.checked = setValue;
			}
		}
	}
	var useHighIndexLenses = function(useHighIndex)
	{
		var hiddenHighIndex = document.getElementById(prescriptionControlIds.hiddenHighIndex);
		if ((hiddenHighIndex !== null) && (typeof(useHighIndex) == "boolean"))
		{
			if (useHighIndex)
			{
				hiddenHighIndex.value = "1";
			}
			else
			{
				hiddenHighIndex.value = "0";
			}
		}
	}
	var resetHiddenHighIndexField = function()
	{
		// DO NOTHING FOR NOW
	}

	/* PRIVATE FUNCTIONS RELATED TO MARKING AND SHOWING OR HIDING SAVED PRESCRIPTIONS */

	var handleLinkClick = function(linkId)
	{
		if (isNonEmptyString(linkId))
		{
			var splitId = linkId.split("_");
			if ((splitId.length == 2) && (splitId[0] != ""))
			{
				var element = document.getElementById(splitId[0]);
				if ((element !== null) && (typeof(element.style) != "undefined"))
				{
					if ((element.style.display == "none") || (element.style.display == ""))
					{
						SlideDownDisplayElement(element);
						element.style.display = "block";
						var linkElement = document.getElementById(linkId);
						if (linkElement !== null)
						{
							if (typeof(linkElement.textContent) != "undefined")
							{
								linkElement.textContent = "Hide";
							}
							else if (typeof(linkElement.innerText) != "undefined")
							{
								linkElement.innerText = "Hide";
							}
						}
					}
					else
					{
						SlideUpDisplayElement(element);
						var linkElement = document.getElementById(linkId);
						if (linkElement !== null)
						{
							if (typeof(linkElement.textContent) != "undefined")
							{
								linkElement.textContent = "View";
							}
							else if (typeof(linkElement.innerText) != "undefined")
							{
								linkElement.innerText = "View";
							}
						}
					}
				}
			}
		}
	}
	var savedPrescriptionControlClicked = function(controlId)
	{
		var savedPrescriptionControl = document.getElementById("saved-prescription-control");
		if (savedPrescriptionControl !== null)
		{
			savedPrescriptionControl.checked = true;
			prescription_control_clicked("saved-prescription-control");
		}
	}
}

