//Begin script that validates proper text entry in form
// Copyright 2003 OCLC Online Computer Library Center
//Modified 
//	09/23/2004 Ed Roberts (ejnr@u.washington.edu
//	Separated out into separate JavaScript file
//
//	10/29/2004 ejnr@u.washington.edu
//	Added functions for building QP form
//
//  7/20/2005 ejnr@u.washington.edu
//  Added remote_addr argument to buildForm() to add IP address field to the submitted information

var dodson	= new Array("Allergy","Cardiology","Dermatology","Emergency Medicine","Gastroenterology","General Internal Medicine","Gerontology","Hematology","Infectious Diseases","Medicine","Metabolism, Endocrinology, & Nutrition","Oncology","Pathology","Pulmonary & Critical Care","Radiation Oncology","Rheumatology","UW Medical Center");
var fuller	= new Array("UW Medicine");
var howard	= new Array("Harborview Medical Center","Neurological Surgery","Obstetrics & Gynecology","Orthopaedics","Pathology","Radiology","Surgery");
var jankowski 	= new Array("Pharmacy","Pharmacy Services","Rehabilitation Medicine","School of Dentistry","School of Pharmacy");
var lee 	= new Array("Alcohol & Drug Abuse Institute","Institute on Aging","Psychiatry & Behavioral Sciences","School of Social Work","Social Workers");
var mctaggart 	= new Array("Grants & Funding","Research Funding Service");
var minie	= new Array("Biochemistry","Bioengineering","Bioinformatics","Genome Sciences","Immunology","Molecular and Cellular Biology Program","Molecular Biology Consultation","Pathobiology");
var oberg	= new Array("Medical Genetics","Medical Students","Microbiology","Multicultural Affairs","Neurology");
var rambo	= new Array ("Biostatistics","Epidemiology","Medical Education and Biomedical Informatics","School of Medicine","School of Public Health and Community Medicine");
var rich 	= new Array("Anesthesiology","Physiology & Biophysics","School of Nursing");
var roberts 	= new Array("Anesthesiology","Biological Structure","Rehabilitation Medicine");
var safranek 	= new Array("Environmental and Occupational Health Sciences","Family Medicine","Hall Health","Health Services","MEDEX Northwest","School of Public Health & Community Medicine","WRITE","WWAMI");
var stanna	= new Array("Pediatrics","School of Medicine","UW Physicians Network","WWAMI");
var schnall 	= new Array("Multicultural Affairs","Ophthalmology","Pediatrics","School of Nursing");
var welton	= new Array("Biostructures","Immunology","Psychiatry");
var weum	= new Array("Center on Human Development & Disability","Comparative Medicine","Medical History & Ethics","Otolaryngology","Primate Research Center","Urology");
var harper	= new Array("Harborview Medical Center","Neurological Surgery","Obstetrics & Gynecology","Orthopaedics","Pathology","Radiology","Surgery");

var recipients = new Array();
recipients[dodson] = "Sherry Dodson";
recipients[fuller] = "Sherrilynne Fuller";
recipients[howard] = "Ellen Howard";
recipients[harper] = "Amy Harper";
recipients[jankowski] = "Terry Ann Jankowski";
recipients[lee] = "Angela Lee";
recipients[mctaggart] = "Bonnie McTaggart";
recipients[minie] = "Mark Minie";
recipients[oberg] = "Lisa Oberg";
recipients[rambo] = "Neil Rambo";
recipients[rich] = "Joanne Rich";
recipients[roberts] = "Edward Roberts";
recipients[safranek] = "Sarah Safranek";
recipients[stanna] = "Leilani St. Anna";
recipients[schnall] = "Janet Schnall";
recipients[welton] = "Nanette Welton";
recipients[weum] = "Colleen Weum";

function buildOpts(liaison){
	numDepts = liaison.length;
	document.forms["entryform1"].field5.options[0] = new Option("- Select One -","0");
	for(i=0;i <= numDepts;i++){
		document.forms["entryform1"].field5.options[eval(i+1)] = new Option(liaison[i],liaison[i]);
	}
	document.forms["entryform1"].field5.options[eval(numDepts+1)] = new Option("Other","Other");
}

function buildForm(key,remote_addr){
 	var recipient;
	if(!key) {
		recipient = "the Health Sciences Library";
	} else {
		recipient = recipients[key];
	}
	//actually write the form out
	document.writeln('<div id="questionpoint">');
	document.writeln('<p style="margin-left: 10px;">Send a question to ' + recipient + '.<br/><span style="font-size: x-small;">Asterisk (*) denotes required field.</span></p>');
	document.writeln('<form method=post onSubmit="return checkIt(this)" name="entryform1" action="http://www.questionpoint.org/crs/servlet/org.oclc.ask.AskPatronQuestion">');
	document.writeln('<table><tr><td>');
    document.writeln('<label for="email" accesskey="E">*E-mail:&nbsp;</label>');
	document.writeln('</td><td>');
    document.writeln('<input type="text" name="email" id="email" maxlength="100">');
	document.writeln('</td></tr><tr><td>');
    document.writeln('<label for="name" accesskey="N">*Name:&nbsp;</label> ');
    document.writeln('</td><td>');
    document.writeln('<input type="text" name="name" id="name" maxlength="255">');
    document.writeln('</td></tr><tr><td>');
    document.writeln('<label for="field4" accesskey="U">*UW Affiliation:&nbsp;</label>');
    document.writeln('</td><td>');
    document.writeln('<select id="field4" name="field4">');
	document.writeln('<option value="0">- Select One -</option>');
    document.writeln('<option value="Undergraduate">Undergraduate Student </option>');
    document.writeln('<option value="Graduate">Graduate Student </option>');
    document.writeln('<option value="Faculty">Faculty </option>');
    document.writeln('<option value="Staff">Staff </option>');
    document.writeln('<option value="Alumni">Alumni </option>');
    document.writeln('<option value="Not_Affiliated">Not Affiliated </option>');
    document.writeln('</select>');
    document.writeln('</td></tr><tr><td>');
	document.writeln('<label for="field5" accesskey="D">Department:</label>');
	document.writeln('</td><td>');
//if no key is passed then provide a write-in form field
	if(!key){
		document.writeln('<input type="text" name="field5" id="field5" maxlength="255">');
//if a key is passed then provide a select box of relevant departments
	} else {
		document.writeln('<select name="field5">');
		buildOpts(key);
		document.writeln('</select>');
		document.writeln('</td></tr><tr><td>');
		document.writeln('<label for="field6" accesskey="O">Other department:&nbsp;</label>');
		document.writeln('</td><td>');
		document.writeln('<input type="text" name="field6" id="field6" maxlength="255">');
		document.writeln('<input type="hidden" name="label6" value="Other Department" />');
	}
    	document.writeln('</td></tr><tr><td>');
    	document.writeln('<label for="question" accesskey="Q">*Question:&nbsp;</label>');
    	document.writeln('</td><td>');
    	document.writeln('<textarea name="question" id="question"></textarea>');
		document.writeln('</td></tr><tr><td colspan="2">');
		document.writeln('<input type="button" name="Submit" value="Submit question" onClick="submitForm(document.entryform1)">');
    	document.writeln('<input type="reset" name="Reset" value="Reset form">');
		document.writeln('</td></tr></table>');
    	document.writeln('<input type="hidden" name="source" value="3">');
    	document.writeln('<input type=hidden name="language" value="1">');
    	document.writeln('<input type=hidden name="library" value="10750">');
    	document.writeln('<input type=hidden name="label2" value="Pass question to" />');
    	document.writeln('<input type=hidden name="field2" id="field2" value="' + recipient + '"/>');
		document.writeln('<input type=hidden name="label3" value="From page" />');
		document.writeln('<input type=hidden name="field3" id="field3" value="' + document.location + '"/>');
		document.writeln('<input type=hidden name="label4" value="UW Affiliation">');
		document.writeln('<input type="hidden" name="label5" value="Department" />');
		document.writeln('<input type="hidden" name="label7" value="IP Address"/>');
		document.writeln('<input type="hidden" name="field7" id="field7" value="' + remote_addr + '"/>');
		document.writeln('</form>');
		document.writeln('</div>');

// Not sure whether we need this link for Patron logins or not.
//	document.writeln('<p><a href="http://www.questionpoint.org/crs/html/home/patron_authorize.htm">Check Your Questions and Answers</a></p>');
}


      function submitForm(form) {
       if (checkIt(form)) {
         form.submit();
// to troubleshoot comment out the line above
// and uncomment the line below to see what values are being submitted
//	alert('Submitting form with values:\nEmail: '+form.email.value+'\nFrom page: '+form.field3.value+'\nName: '+form.name.value+'\nPass question to: '+form.field2.value+'\nQuestion: '+form.question.value + '\nUW Affiliation: ' + form.field4.options[form.field4.selectedIndex].value + '\nDepartment: ' + form.field5.value + '\nIP Address: '+form.field7.value);
       }
      }

      function checkIt(form) {
	  //variables that store contents of e-mail address and question fields for validation
	  //Create a variable like these for each text or textarea field that you want to require patron to complete
	  //Then add a check for the contents of the variable where indicated (see "Make sure the E-mail address
	  // contains some data" for an example)
      var email = form.email.value;
      var question = form.question.value;
      var id = form.field2.value;
      var lib = form.library.value;
      var name = form.name.value;
      var field4 = form.field4.selectedIndex;

	  //variable that contains contents of message to display to patron if required field(s) are blank
      var msg = '';
 
//	  Check to ensure that you changed the "library" hidden field
      if( (lib == '1') || (lib.length < 1) ) {
      alert("The library supplying this form has an error in the form. Please contact this library and alert them to the problem\r\n");
      return false;
      }

	  //Make sure the Question field contains some data
      if(question.length < 1) {
      if(msg.length > 0)
      msg+=', ';
      msg += 'Question';
      form.question.focus(); // inserted ejnr to put cursor in relevant form field @ fault
      }

      if(field4==0){
      if(msg.length > 0)
      msg+=', ';
      msg += 'UW Affiliation';
      form.field4.focus();
      }

          //Make sure the Name field contains some data
      if(name.length < 1) {
      if(msg.length > 0)
      msg+=', ';
      msg += 'Name';
      form.name.focus(); // inserted ejnr to put cursor in relevant form field @ fault
      }

          // Make sure the E-mail address field contains some data
      if(email.length < 1) {
      if(msg.length > 0)
      msg+=', ';
      msg += 'E-mail address';
      form.email.focus();  // inserted ejnr to put cursor in relevant form field @ fault
     }


	  //Display alert box for patron; he/she left at least one required field blank
      if (msg != '')
      {
      alert("One or more required fields are blank\r\n" + msg);
      return false;
      }

 	  //Check the format of the e-mail address for common errors
      if (emailCheck(email, true, form)) {      
      return true;
      }
      else {
      form.email.select(); // inserted ejnr to put cursor in relevant form field @ fault
      return false;
      }
     }

//Check for common errors in entering e-mail addresses
function emailCheck (emailStr, alertflag, form) {

var emailPat=/^(.+)@(.+)$/		
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
var validChars="\[^\\s" + specialChars + "\]"
var quotedUser="(\"[^\"]*\")"
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
var atom=validChars + '+'
var word="(" + atom + "|" + quotedUser + ")"
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
var matchArray=emailStr.match(emailPat)

if (matchArray==null) {
        if (alertflag)
	alert("Email address seems incorrect (check @ and .'s)")
	return false
}

var user=matchArray[1]
var domain=matchArray[2]

// See if "user" is valid 
if (user.match(userPat)==null) {
    // user is not valid
     if (alertflag) 
    alert("The username doesn't seem to be valid.")
    return false
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
   host name) make sure the IP address is valid. */
var IPArray=domain.match(ipDomainPat)

if (IPArray!=null) {
    // this is an IP address
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
      if (alertflag)
	        alert("Destination IP address is invalid!")
		return false
	    }
    }
    return true;
}

// Domain is symbolic name
var domainArray=domain.match(domainPat)
if (domainArray==null) {
      if (alertflag)
	alert("The domain name doesn't seem to be valid.")
    return false
}

var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
musExp = /.museum/

isMus = domain.search(musExp)

if ( ( (domArr[domArr.length-1].length < 2) || (domArr[domArr.length-1].length > 6) ) ||
	(domArr[domArr.length-1].length == 5) ||
	( (domArr[domArr.length-1].length == 6) && (isMus == -1) ) ) {
	  // the address must end in a two, three, or four letter word or .museum
		if (alertflag) 	
			alert("The address must end in a three or four-letter domain, two-letter country, or .museum.")
	   return false
}

// Make sure there's a host name preceding the domain.
if (len<2) {
   var errStr="This address is missing a hostname!"
      if (alertflag) 
   alert(errStr)
   return false
}

// If we've gotten this far, everything's valid!
return true;
}
//End validation script
