/* Pubmed Javascript functions
 *
 * General:
 *   Pmed_OpenWin(fname,wininfo)
 *	 Pmed_IsEmpty(sString)
 *	 Pmed_EmailValid(sString)
 *	 Pmed_GetLength(sString)
 *
 * Saved Searches:
 *	 Pmed_DeleteSearch(searchid) 
 *
 * Search Page: 
 *	 Pmed_AddTerm(sString,sFormField)
 *   Pmed_ValidateSearchForm()
 *	 Pmed_AddTermToParent(sString, sFormField)
 *	 Pmed_ValidateSearchDates(iWhat)
 *
 * Results and Abstracts:
 *   Pmed_CheckBoxes()
 *	 Pmed_CheckBoxes()
 *	 Pmed_ValidateCheckBoxes() 
 *
 * Login/Registration:
 *   Pmed_ValidateLogin()
 *	 Pmed_ValidateRegForm()
 *
 * Feedback:
 *	 Pmed_ValidateFeedback()
*/	 

/* General vars */
var undef;				//so we can match up with undefined

/* GENERAL FUNCTIONS */
function Pmed_OpenWin(fname,wname,wininfo) {
	var vPopWin = window.open(fname,wname,wininfo);
		vPopWin.Focus;
}

// check the email address given is valid
function Pmed_EmailValid(sString) {
	sPattern = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/i;   // a standard email address pattern.
	return sPattern.test(sString); // return boolean
}

// return the length of hte string
function Pmed_GetLength(sString) {
	if (sString == undef) {
		return 0;
	} else {
		return sString.length;
	}
}


// check if a string is empty or not
function Pmed_IsEmpty(sString) {
	if (sString == "") {
		return true; // it is empty
	}
	// otherwise it is not empty
	return false;
}


/* SAVED SEARCHES */
function Pmed_DeleteSearch(searchid) {
	// confirm that the person wants to delete the search
	if (confirm('Are you sure?')) {
		self.location = "SavedSearches.aspx?qsDel=" + searchid;
	} 
}

/* SEARCH PAGE FUNCTIONS */
// Add a term to the search box (from another window)
function Pmed_AddTermToParent(sString, sFormField)
{
	var sForm = window.opener.document.forms[0];
	// Find the correct form element to add the text to
	for (i=0; i <= sForm.elements.length - 1; i++) { // loop through each of the form elements.
		if (sForm.elements[i].name == sFormField) {
			sPointer = sForm.elements[i]; // a pointer to the form element
			if (sForm.elements[i].name == "frmJournal") {
				sPointer.value = sString; // Replace the term to the end of the current string						
			} else {
				sPointer.value += " " + sString; // Add the term to the end of the current string			
			}

		}
	}
}

// Add a term to the search box.
function Pmed_AddTerm(sString, sFormField) {
	var sForm = document.forms[0];  // pointer to the search form
	// Find the correct form element to add the text to
	for (i=0; i <= sForm.elements.length - 1; i++) { // loop through each of the form elements.
		if (sForm.elements[i].name == sFormField) {
			sPointer = sForm.elements[i]; // a pointer to the form element
			sPointer.value += sString; // Add the term to the end of the current string
			sForm.elements[i].focus();
		}
	}
}

// Search form validation.
function Pmed_ValidateSearchForm()
{
	/* Validation on this form is as follows:
		- make sure there is something in the search box
		- make sure the dates are ok:
			- one or other date restrictions
			- if FROM date selected, must be less than TO date
			- it TO date selected, must select FROM date
		- no need to validate the filters */

	var sForm = document.forms[0];  // pointer to the search form
	var bErr = false; // boolean - has there been an error
	var bDateErr = false; // boolean - has there been a dates error?
	var sErr = "Please correct the following on the search form: \n";
		sErr += "------------------------------------------------------ \n\n" ;

	// search criteria
	var sCrit = sForm.frmSearchKeyword.value;	
	var sAuth = sForm.frmAuthor.value;	
	var sJour = sForm.frmJournal.value;	
	if (Pmed_IsEmpty(sCrit) && Pmed_IsEmpty(sAuth) && Pmed_IsEmpty(sJour)) {
		sErr += " - Please enter some search criteria.\n";
		bErr = true;
	}

	// dates
	var sSince = sForm.frmWithin[sForm.frmWithin.selectedIndex].value;
	var sFDate = sForm.frmFrom[sForm.frmFrom.selectedIndex].value;
	var sEDate = sForm.frmTo[sForm.frmTo.selectedIndex].value;
	
	// check only one type of restriction has been applied
	if ((sSince != "NA") && ((sFDate != "NA") || (sEDate != "NA"))) { 
		sErr += " - You may only apply one of the date restriction options to a particular search \n";
		bErr = true;		
	}
	
	// if its the FROM - TO restriction, make sure its valid
	if (sFDate != "NA") { // To date must be selected and greater than this one
		if (sEDate == "NA") {
			sErr += " - Please select a TO date. \n";
			bErr = true;	
			bDateErr= true;					
		} else if (sEDate < sFDate) { // not good
			sErr += " - The TO date must be after the FROM date. \n";
			bErr = true;
			bDateErr= true;	
		}
	}
	
	if (sEDate != "NA" && !bDateErr) { // From date must be less than To date
		if 	(sFDate == "NA") {
			sErr += " - Please select a FROM date. \n";
			bErr = true;	
			bDateErr= true;					
		} else if (sFDate > sEDate) { // not good
			sErr += " - The FROM date must be before the TO date. \n";
			bErr = true;	
			bDateErr= true;				
		}
	}

	if (bDateErr) { // reset the To/From drop downs
		sForm.frmFrom[0].selected = 1;
		sForm.frmTo[0].selected = 1;		
	}
	
	// if there have been any errors then show the error
	if (bErr) {
		alert(sErr);
		return false;
	}
}



// Validate the search box client side. Only one form of date restriction may be applied.
function Pmed_ValidateSearchDates(iWhat) {
	// users can select either a since date or a date inbetween X and X..
	// iWhat tells us what was clicked to give us the event:
	//
	// iWhat = 1 := clicked on frmWithin (last 30 days)
	// iWhat = 2 := clicked on date limitations
	
	var sForm = document.forms[0];
	var strError = "";
	var since = sForm.frmWithin[sForm.frmWithin.selectedIndex].value;
	var s_date = sForm.frmFrom[sForm.frmFrom.selectedIndex].value;
	var e_date = sForm.frmTo[sForm.frmTo.selectedIndex].value;

	if ((since != "NA") && ((s_date != "NA") || (e_date != "NA"))) { 
		strError += "You may only apply one of the date restriction options to a particular search";
	}
	
	
	if (iWhat == 1) { // the frmWithin was clicked. clear the other two
		sForm.frmFrom.selectedIndex = 0;
		sForm.frmTo.selectedIndex = 0;
	} else {
		sForm.frmWithin.selectedIndex = 0; // clear the within range
	}
	
	if (! strError == "") {
		alert(strError);
	}
}

// Saved search details validation.
function Pmed_ValidateSearchDetails()
{
	/* Validation on this form is as follows:
		- make sure there is something in the search box
		- make sure the dates are ok:
			- one or other date restrictions
			- if FROM date selected, must be less than TO date
			- it TO date selected, must select FROM date
		- no need to validate the filters */

	var sForm = document.forms[0];  // pointer to the search form
	var sType = sForm.frmType.value; // either 'saved' or 'alert'
	var bErr = false; // boolean - has there been an error
	var bDateErr = false; // boolean - has there been a dates error?
	var sErr = "Please correct the following on the form: \n";
		sErr += "------------------------------------------------ \n\n" ;

	// search criteria
	var sCrit = sForm.frmSearchKeyword.value;	
	var sAuth = sForm.frmAuthor.value;	
	var sJour = sForm.frmJournal.value;	
	if (Pmed_IsEmpty(sCrit) && Pmed_IsEmpty(sAuth) && Pmed_IsEmpty(sJour)) {
		sErr += " - Please enter some search criteria.\n";
		bErr = true;
	}

	if (sType == "alert") { // its a search alert - we must check the rest of the form
		// search alert 
			var sAlertName = sForm.frmAlertName.value;
			var sEmail = sForm.frmEmailAddr.value;
			
		// the alert name
			if (Pmed_IsEmpty(sAlertName)) {
				sErr += " - Please give your search alert a name \n";
				bErr = true;				
			}
	
		// email address - required and must be valid format
			if (!Pmed_EmailValid(sEmail)) { // check the email address is valid, if not append to the error message
				sErr += " - Email address is invalid \n";
				bErr = true;				
			}			
	}

	// if there have been any errors then show the error
	if (bErr) {
		alert(sErr);
		return false;
	}
}

//Check all 'articles' checkboxes on page.
function Pmed_CheckBoxes()
{
	var i;
	for (i=0; i<document.forms[0].Articles.length; i++ )
	{
		document.forms[0].Articles[i].checked=true;
	}
}

//Check at least one checkbox is ticked.
function Pmed_ValidateCheckBoxes()
{
	var i;
	if ( document.forms[0].Articles.value!=null)
	{
		if (document.forms[0].Articles.checked)
		{
			return true
		}
	}
	else
	{
		for (i=0; i<document.forms[0].Articles.length; i++ )
		{
			if(document.forms[0].Articles[i].checked)
			{
				return true;
			}
		}
	}
	alert("Please select at least one abstract by clicking in a checkbox");
	return false;
}

 /* Login/Registration */
 
function Pmed_ValidateLogin() { 
	// validate the login form 
	var sForm = document.forms[0];
	var sErr = ""; // we will build this up to store the error message if there is one
	var sUN = sForm.frmUserName.value;
	var sPW = sForm.frmPassword.value;
		
		
	//check the username		
		if (Pmed_IsEmpty(sUN) || (Pmed_GetLength(sUN) < 2)) {
			sErr += "Please enter a valid username\n";
		}
		
	// check the password
		if (Pmed_IsEmpty(sPW) || (Pmed_GetLength(sPW) < 2)) {
			sErr += "Please enter a valid password\n";
		}

	// Any errors?		
		if (sErr != "") { // there has been an error
			sErr = "Login Error\n--------------------------------------------------------------\n" + sErr;
			alert(sErr);
			return false;
		}
		else {
			return true;
		}
}
 
/* Validate the registration form */
function Pmed_ValidateRegForm() {
	// validate the registration form 
	var sForm = document.forms[0];
	var sErr = ""; // we will build this up to store the error message if there is one

	// validate the following fields:	
	var sUN = sForm.txtUsername.value;	// required - GT 5 chars
	var sPW = sForm.txtPassword.value;	// required - GT 5 chars
	var sPWConf = sForm.txtPasswordConf.value; // must be the same as sPW
	var sEmail = sForm.txtEmail.value; // not required - but if entered must be valid
		
	//check the username
		if (Pmed_IsEmpty(sUN) || (Pmed_GetLength(sUN) < 2)) {
			sErr += "Please enter a valid username\n";
		}

	// check the password
		if (Pmed_IsEmpty(sPW) || (Pmed_GetLength(sPW) < 2)) {
			sErr += "Please enter a valid password\n";
		} else {
			if (sPW != sPWConf) {
				sErr += "Passwords do not match, please re-enter\n";
			}
		}

	// Email
		if (! Pmed_IsEmpty(sEmail)) {
			if (! Pmed_EmailValid(sEmail)) {
				sErr += "Email address is invalid\n";
			}
		}

	// Any errors?
		if (sErr != "") { // there has been an error
			sErr = "Registration Error \n------------------------------------------\n" + sErr;
			alert(sErr);
			return false;
		}
		else {
			return true;
		}
}

/* Feedback */

function Pmed_ValidateFeedback() {
	var sEmail = document.forms[0].txtEmail.value;
	
	if (Pmed_EmailValid(sEmail)) {
		return true;
	} else {
		alert('Email address is invalid, please re-enter.');
		return false;
	}
}
