var debug = false;
if(debug) { alert('v 00.00.01'); }


/**********************************************************
 *** UI FUNCTION: btnHover()                            ***
 *** -------------------------------------------------- ***
 *** Switches between images with filenames ending in   ***
 *** -on or -off before the file extention.             ***
 **********************************************************/
function btnHover(button, active) {

	var ext = button.src.substr(button.src.lastIndexOf("."), 4);
	
	if(active) {
		button.src = button.src.substring(0, button.src.lastIndexOf("-")) + "-on" + ext;
	} else {
		button.src = button.src.substring(0, button.src.lastIndexOf("-")) + "-off" + ext;
	}

}


/**********************************************************
 *** PRIMARY FUNCTION: openPopup()                      ***
 *** -------------------------------------------------- ***
 *** Opens a popup window with the specified URL.       ***
 **********************************************************/
function openPopup(url) {
	window.open(url, "Popup", "location=0,status=1,scrollbars=1,toolbar=0,width=600,height=600,resizable=1");
}


/**********************************************************
 *** UI FUNCTION: toggleDisplay()                       ***
 *** -------------------------------------------------- ***
 *** Shows, Hides, or Toggles the display of an element.***
 **********************************************************/
function toggleDisplay(id, action) {

	action = action.toLowerCase();
	
	var el = document.getElementById(id);
	
	switch(action) {
		case 's':
			el.style.display = 'block';
			break;

		case 'h':
			el.style.display = 'none';
			break;

		case 't':
			if(el.style.display == 'none') {
				el.style.display = 'block';
			} else {
				el.style.display = 'none';
			}
			break;
	}
			
}


/**********************************************************
 *** FORM VALIDATION FUNCTION: validateForm()           ***
 *** -------------------------------------------------- ***
 *** Calls individual validations for form fields.      ***
 **********************************************************/
function validateForm() {

	if(debug) { alert("Stage 1: true"); }
  // Set object variables for the form fields
  var fm_dea     = document.getElementById('dea');
  var fm_fname   = document.getElementById('fname');
  var fm_lname   = document.getElementById('lname');
  var fm_addr1   = document.getElementById('addr1');
  var fm_city    = document.getElementById('city');
  var fm_state   = document.getElementById('state');
  var fm_zip     = document.getElementById('zip');
  var fm_phone   = document.getElementById('phone');
  var fm_fax     = document.getElementById('fax');
  var fm_email   = document.getElementById('email');
  var fm_agree   = document.getElementById('agree_cb');

  var fm_degree    = new Array();
      fm_degree    = document.forms[0]["degree[]"];
  var fm_specialty = new Array();
      fm_specialty = document.forms[0]["specialty[]"];

  var fm_discussed  = new Array();
  		fm_discussed  = document.forms[0]["discussed"];
  var fm_dr_visit   = new Array();
  		fm_dr_visit   = document.forms[0]["plan_visit"];
  var fm_on_prov    = new Array();
  		fm_on_prov    = document.forms[0]["on_provigil"];
  var fm_time_taken = new Array();
  		fm_time_taken = document.forms[0]["time_taken"];
  var fm_stay_awake = new Array();
  		fm_stay_awake = document.forms[0]["stay_awake"];
  		
	var error_msg = "The following errors occured:\t\t\n\n";
	var errors    = false;
	
	if(debug) { alert("Stage 2: " + errors); }

  // Call "Required" validation for DEA field
  if(typeof(fm_dea) != "undefined" && fm_dea != null) {
		if(validateRequired(fm_dea) == false) {
			error_msg += " - Please enter a valid \"DEA number\".\t\n";
			errors = true;

		// Call "Text Only" validation for DEA field
		} else if(validateDEA(fm_dea) == false) {
			error_msg += " - The \"DEA number\" is invalid.\t\n";
			errors = true;
		}
	}

	if(debug) { alert("Stage 3: " + errors); }

  // Call "Required" validation for First Name field
  if(typeof(fm_fname) != "undefined" && fm_fname != null) {
		if(validateRequired(fm_fname) == false) {
			error_msg += " - Please specify your \"First name\".\t\n";
			errors = true;

		// Call "Text Only" validation for Name field
		} else if(validateTextOnly(fm_fname) == false) {
			error_msg += " - \"First name\" may only contain the letters A through Z.\t\n";
			errors = true;
		}
	}
	if(debug) { alert("Stage 4: " + errors); }

  // Call "Required" validation for Last Name field
  if(typeof(fm_lname) != "undefined" && fm_lname != null) {
		if(validateRequired(fm_lname) == false) {
			error_msg += " - Please specify your \"Last name\".\t\n";
			errors = true;

		// Call "Text Only" validation for Name field
		} else if(validateTextOnly(fm_lname) == false) {
			error_msg += " - \"Last name\" may only contain the letters A through Z.\t\n";
			errors = true;
		}
	}
	if(debug) { alert("Stage 5: " + errors); }

  // Call "Required" validation for Addr1 field
  if(typeof(fm_addr1) != "undefined" && fm_addr1 != null) {
		if(validateRequired(fm_addr1) == false) {
			error_msg += " - Please enter your \"Mailing address\".\t\n";
			errors = true;
		}
	}
	if(debug) { alert("Stage 6: " + errors); }

  // Call "Required" validation for City field
  if(typeof(fm_city) != "undefined" && fm_city != null) {
		if(validateRequired(fm_city) == false) {
			error_msg += " - Please enter your \"City\".\t\n";
			errors = true;
		}
	}
	if(debug) { alert("Stage 7: " + errors); }

  // Call "Required" validation for State field
  if(typeof(fm_state) != "undefined" && fm_state != null) {
		if(validateRequired(fm_state) == false) {
			error_msg += " - Please select your \"State\".\t\n";
			errors = true;
		}
	}
	if(debug) { alert("Stage 8: " + errors); }

  // Call "Required" validation for Zip field
  if(typeof(fm_zip) != "undefined" && fm_zip != null) {
		if(validateRequired(fm_zip) == false) {
			error_msg += " - Please enter your \"Zip code\".\t\n";
			errors = true;

		// Check for a minimum length of 5
		} else if(fm_zip.value.length < 5) {
			error_msg += " - \"Zip code\" must be at least 5 digits.\t\n";
			errors = true;

		// Call "Numeric Only" validation for Zip field
		} else if(validateNumericOnly(fm_zip) == false) {
			error_msg += " - \"Zip code\" may only contain the numbers 0-9 and a dash.\t\n";
			errors = true;
		}
	}
	if(debug) { alert("Stage 8: " + errors); }

  // Call "Required" validation for Phone field
  if(typeof(fm_phone) != "undefined" && fm_phone != null) {
		if(validateRequired(fm_phone) == false) {
			error_msg += " - Please enter your \"Phone number\".\t\n";
			errors = true;

		// Call phone validation for Phone field
		} else if(validatePhone(fm_phone) == false) {
			error_msg += " - Your \"Phone number\" does not appear to be formatted correctly.\t\n";
			errors = true;
		}
	}
	if(debug) { alert("Stage 9: " + errors); }

  // Call validation for Fax field
  if(typeof(fm_fax) != "undefined" && fm_fax != null) {
		if(validatePhone(fm_fax) == false) {
			error_msg += " - Your \"Fax number\" does not appear to be formatted correctly.\t\n";
			errors = true;
		}
	}
	if(debug) { alert("Stage 9: " + errors); }

  // Call "Required" validation for Email field
  if(typeof(fm_email) != "undefined" && fm_email != null) {
		if(validateRequired(fm_email) == false) {
			error_msg += " - Please enter a valid \"Email address\".\t\n";
			errors = true;

		// Call "Email" validation for Email field
		} else if(validateEmail(fm_email) == false) {
			error_msg += " - The \"Email address\" is not formatted correctly.\t\n";
			errors = true;
		}
	}
	if(debug) { alert("Stage 10: " + errors); }

	// Validate required for degree checkboxes if they exist
  if(typeof(fm_degree) != "undefined" && fm_degree != null) {
		var degree_checked = false;
		for(i = 0; i < fm_degree.length; i++) {
			if(fm_degree[i].checked) {
				degree_checked = true;
			}
		}
		if(!degree_checked) {
			error_msg += " - Please select at least one \"Degree\".\t\n";
			errors = true;
		}
	}
	if(debug) { alert("Stage 11: " + errors); }

  // Validate required for specialty checkboxes if they exist
  if(typeof(fm_specialty) != "undefined" && fm_specialty != null) {
		var specialty_checked = false;
		for(i = 0; i < fm_specialty.length; i++) {
			if(fm_specialty[i].checked) {
				specialty_checked = true;
			}
		}
		if(!specialty_checked) {
			error_msg += " - Please select at least one \"Specialty\".\t\n";
			errors = true;
		}
	}
	if(debug) { alert("Stage 12: " + errors); }

  // Validate required for Discussed with Doctor if it exists
  if(typeof(fm_discussed) != "undefined" && fm_discussed != null) {
		var discussed_checked = false;
		for(i = 0; i < fm_discussed.length; i++) {
			if(fm_discussed[i].checked) {
				discussed_checked = true;
			}
		}
		if(!discussed_checked) {
			error_msg += " - Please indicate if you have discussed your ES with your doctor.\t\n";
			errors = true;
		}
	}
	if(debug) { alert("Stage 12: " + errors); }

  // Validate required for Plan Doctor Visit if it exists
  if(typeof(fm_dr_visit) != "undefined" && fm_dr_visit != null) {
		var dr_visit_checked = false;
		for(i = 0; i < fm_dr_visit.length; i++) {
			if(fm_dr_visit[i].checked) {
				dr_visit_checked = true;
			}
		}
		if(!dr_visit_checked) {
			error_msg += " - Please indicate if you plan to visit a doctor in the future.\t\n";
			errors = true;
		}
	}
	if(debug) { alert("Stage 12: " + errors); }

  // Validate required for On Provigil if it exists
  if(typeof(fm_on_prov) != "undefined" && fm_on_prov != null) {
		var on_prov_checked = false;
		for(i = 0; i < fm_on_prov.length; i++) {
			if(fm_on_prov[i].checked) {
				on_prov_checked = true;
				
				// Validate required for Time Taken only if On Provigil is 'Yes'
				if(i == 0) {
					if(typeof(fm_time_taken) != "undefined" && fm_time_taken != null) {
						var time_taken_checked = false;
						for(i = 0; i < fm_time_taken.length; i++) {
							if(fm_time_taken[i].checked) {
								time_taken_checked = true;
							}
						}
						if(!time_taken_checked) {
							error_msg += " - Please indicate how long you have been taking PROVIGIL.\t\n";
							errors = true;
						}
					}
				
				}
			}
		}
		if(!on_prov_checked) {
			error_msg += " - Please indicate if you are currently taking PROVIGIL.\t\n";
			errors = true;
		}
	}
	if(debug) { alert("Stage 12: " + errors); }


  // Validate required for Stay Awake if it exists
  if(typeof(fm_stay_awake) != "undefined" && fm_stay_awake != null) {
		var stay_awake_checked = false;
		for(i = 0; i < fm_stay_awake.length; i++) {
			if(fm_stay_awake[i].checked) {
				stay_awake_checked = true;
			}
		}
		if(!stay_awake_checked) {
			error_msg += " - Please indicate if you are currently able to stay awake throughout the day.\t\n";
			errors = true;
		}
	}
	if(debug) { alert("Stage 12: " + errors); }


  // Confirm that "Agree" is checked
  if(typeof(fm_agree) != "undefined" && fm_agree != null) {
		if(fm_agree.checked == false) {
			error_msg += "\nNote: You must agree to opt in before submitting this form.\t\n";
			errors = true;
		}
	}
	if(debug) { alert("Stage 13: " + errors); }

  // If there are errors, display them
  if(errors) {
  	alert(error_msg);
  	return false;
	
	// Otherwise, return true...
  } else {
	  return true;
	}

} // End: validateForm()

/**********************************************************
 *** FORM VALIDATION FUNCTION: validateRequired()       ***
 *** -------------------------------------------------- ***
 *** Checks for empty input fields.                     ***
 **********************************************************/
function validateRequired(field) {
  if (field.value == null || field.value == "") {
    return false;
   } else {
    return true;
  }
}

/**********************************************************
 *** FORM VALIDATION FUNCTION: validateTextOnly()       ***
 *** -------------------------------------------------- ***
 *** Checks for non Alpha characters (allows spaces).   ***
 **********************************************************/
function validateTextOnly(field) {
  if(field.value.search(/[^a-zA-Z\s-]/) == -1) {
    return true;
  } else {
    return false;
  }
}

/**********************************************************
 *** FORM VALIDATION FUNCTION: validateNumericOnly()    ***
 *** -------------------------------------------------- ***
 *** Checks for non numeric characters (allows dash).   ***
 **********************************************************/
function validateNumericOnly(field) {
  if(field.value.search(/[^0-9-]/) == -1) {
    return true;
  } else {
    return false;
  }
}

/**********************************************************
 *** FORM VALIDATION FUNCTION: validateDEA()            ***
 *** -------------------------------------------------- ***
 *** Checks for a properly formatted DEA number.        ***
 **********************************************************/
function validateDEA(field) {
	var valid = true;
	
  if(field.value.search(/[^a-zA-Z0-9]/) == -1) {
		var chars = field.value.toUpperCase().split('');
		
		// First check for proper size
		if(chars.length != 9) {
			return false;
		}

		// First check for valid Registrant Type
		if(chars[0].search(/[ABCDEFGHJKLMNPRSTUX]/) == -1) {
			return false;
		}
		
		// Then check for valid 2nd letter (first letter of last name)
		if(chars[1].search(/[A-Z]/) != -1) {
			var lname = document.getElementById('lname');
			
			if(lname != null && lname.value != "") {
				
				var lnames = lname.value.toUpperCase().split("");
				if(chars[1] != lnames[0]) { return false; }
				
			}
		} else { return false; }
		
		// Then check that the next 7 digits are numbers
		for(var i=2; i < chars.length; i++) {
			chars[i] = chars[i] * 1;
			if(typeof(chars[i]) != 'number') { return false; }
		}
		
		// Compute and check algorithm
		var checksum = ((chars[2] + chars[4] + chars[6]) + ((chars[3] + chars[5] + chars[7]) * 2));
		var digits = String(checksum).split("");
		
		checksum = digits[digits.length - 1];
		
		if(checksum != chars[8]) {
			return false;
		}

	} else {
		return false;
	}
  
  return true;
}


/**********************************************************
 *** FORM VALIDATION FUNCTION: validatePhone()          ***
 *** -------------------------------------------------- ***
 *** Checks for a properly formatted phone number.      ***
 **********************************************************/
function validatePhone(field) {
  
  // Split the field value into individual characters
  var digits = field.value.split('');

  // In case of international number, exit
  if(digits[0] == "+" || digits.length == 0 || field.value == " ") {
    return true;
  }

  // Remove any character that is not a number
  for(var i = 0; i < digits.length; i++) {
    if(isNaN(digits[i]) || digits[i] == " ") { 
      digits.splice(i,1);
      i--;
    }
  }

  // Rmove a leading 1 in the case of 11 digits (i.e. - 1(555)555-5555)
  if(digits.length == 11 && digits[0] == 1) {
    digits.splice(0,1);
  }

  // If the phone number is not 10 digits, fail and alert the user
  if(digits.length != 10) {
    return false;
  }
  
  // Format the actual mask
  var tel = "(";
  for(var i = 0; i < digits.length; i++) {
    if(i == 3) { tel += ') ' }
    if(i == 6) { tel += '-' }
    tel += digits[i];
  }

  // Repopulate the form field.
  field.value = tel;

  return true;

} // End: validatePhone()


/**********************************************************
 *** FORM VALIDATION FUNCTION: validateEmail()          ***
 *** -------------------------------------------------- ***
 *** Checks for properly forms email addresses x@y.c.   ***
 **********************************************************/
function validateEmail(field) {
  var apos     = field.value.indexOf("@");
  var dotpos   = field.value.lastIndexOf(".");
  var spacepos = field.value.indexOf(" ");
  
  if (apos < 1 || dotpos - apos < 2 || spacepos != -1) {
    return false;
  } else {
    return true;
  }
}

/**********************************************************
 *** FORM VALIDATION FUNCTION: validateEmail2()         ***
 *** -------------------------------------------------- ***
 *** Checks for properly forms email addresses x@y.c.   ***
 **********************************************************/
function validateEmail2() {
  var fm_email   = document.getElementById('INDIVIDUALCONTROL_email');

	if(fm_email.value == null || fm_email.value == "") {
		alert("The following errors have occurred:\n\n - You must enter a valid email address\n");
		return false;
	}

  var apos   = fm_email.value.indexOf("@");
  var dotpos = fm_email.value.lastIndexOf(".");
  if (apos < 1 || dotpos - apos < 2) {
  	alert("The following errors have occurred:\n\n - You must enter a valid email address\n");
    return false;
  } else {
    return true;
  }
}


/*******************************************************************
 *** Functions for Adding Print / Close Links                    ***
 ***-------------------------------------------------------------***
 *** Print and Close links are added via javascript so that they ***
 *** will not show up for users who have javascript turned off.  ***
 ***                                                             ***
 *** To use, simply place <div class="print_link">&nbsp;</div>   ***
 *** or <div class="close_link">&nbsp;</div> when you want print ***
 *** or cloase links to appear.                                  ***
 *******************************************************************/


function addLinks() {
	var closeLinks = getElementsByClass('close_link');

	if(closeLinks != null) {
		for(var i=0; i<closeLinks.length; i++) {
			addCloseLink(closeLinks[i]);
		}
	}

	var printLinks = getElementsByClass('print_link');

	if(printLinks != null) {
		for(var i=0; i<printLinks.length; i++) {
			addPrintLink(printLinks[i]);
		}
	}
}

function addCloseLink(el) {
	var code = "<a href='#' onclick='window.close(); return false'>Close Window</a>"
	el.innerHTML += code;
}

function addPrintLink(el) {
	var code = "<a href='#' onclick='window.print(); return false'><img class='icon' src='images/Icon-Print.gif' alt='' />Print</a>"
	el.innerHTML += code;
}

/* Set up event listeners to add print and close links */
if (document.addEventListener) {
  window.addEventListener ("load", addLinks, false);
} else if (document.attachEvent) {
  window.attachEvent ("onload", addLinks);
} else {
  window.onload = addLinks;
} 

function getElementsByClass(class_name) { 
	var all_tags = document.getElementsByTagName('*');
	var arr = [];
	for(var i=0; i < all_tags.length; i++)  {
		if(all_tags[i].className == class_name) { 
			arr.push(all_tags[i]);
		}
	}
	
	if(arr.length > 0) {
		return arr;
	} else {
		return null;
	}
		
} 


