/* 	Author: 	Matt Smith
				Justin Raney
				Brian Raney
	Description: This file describes actions that can be taken on form objects
		such as copying values and form validation
*/

// ************* GLOBAL VARIABLES **************
// An array of field names that are required to be filled
//var REQ_FIELDS = new Array();
var ERR_PREFIX = "err_";
var ERR_GLOBAL = "err_global";
/////// PATTERNS TO MATCH /////////////////
PATTERN_EMAIL = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
PATTERN_PHONE = /^[ ]*[(]{0,1}[ ]*[0-9]{3,3}[ ]*[)]{0,1}[-]{0,1}[ ]*[0-9]{3,3}[ ]*[-]{0,1}[ ]*[0-9]{4,4}[ ]*$/;
PATTERN_ZIP = /^\d{5}$/;

// ********* FUNCTIONS ****************
function autofill(fieldName, fieldValue, overwrite)
/*	Desciption: Takes a value and fills in the given field
	Input:	fieldName: The id of the field the value will be copied into
			fieldValue: The value that is copied into the field
			overwrite: a boolean value that determines if a value is already there,
						if it can be overwritten
	Output: None
 	Notes:
*/
{
  var fieldToFill;
  
  if(overwrite || document.getElementById(fieldName).value=="")
  {
    document.getElementById(fieldName).value = fieldValue;
  }
}

function clearReqErrs(REQ_FIELDS)
/*	Desciption: Clears the screen of any errors previously displayed
	Input: None
	Output: Removes error messages from the screen
	Notes:
*/
{
	// loops through the required fields and clears the errors
	for(x=0; x<REQ_FIELDS.length; x++)
	{
		field = document.getElementById(REQ_FIELDS[x]);
		if(!field){continue;}
		
		dispErr(ERR_PREFIX+field.id, "");
	}
	dispErr("err_global", "");
}

function dispErr(errID, errMessage)
/*	Desciption: Displays an error message in the area specified by errID
		Input: errID: The id of the span tag to display the error in
			errMessage: The message to display
	Output: Display the error to the screen
	Notes:
*/
{	
	err = document.getElementById(errID);	
	if(err)
	{
		err.innerHTML = errMessage.fontcolor("Red");		
	}
}


function checkRequiredQuickSearch(errMessage, errMessageGlobal)
/*	Desciption: Checks to makes sure that a value has been entered in the required fields on the quicksearch form
	Input: None
	Output: The function writes error messages in corresponding span tags
		and returns true if there was no error, false otherwise
	Notes:
*/
{
	var field = null;

	var ALL_FIELDS = new Array();

	// replace all apostrophes
	ALL_FIELDS = document.getElementsByTagName("input");
	q = /\'/g;
	for (i = 0; i < ALL_FIELDS.length; i++) {
		ALL_FIELDS[i].value = ALL_FIELDS[i].value.replace(q, ""); 
	}
	
	var isErr = false;

	field = document.getElementById("quickSearch");
	
	if(field.value == ""){

		isErr = true;
		dispErr(ERR_PREFIX + field.id, errMessage);
	}

	if(isErr){dispErr("err_globalQS", errMessageGlobal);}
		
	return !isErr;
}

function checkRequired(errMessage, errMessageGlobal)
/*	Desciption: Checks to makes sure that a value has been entered in the required fields
	Input: None
	Output: The function writes error messages in corresponding span tags
		and returns true if there was no error, false otherwise
	Notes:
*/
{	
	//var errMessage = "This field is required";
	//var errMessageGlobal = "Please fill in all the required fields."
	var isErr = false;
	var field = null;
	var REQ_FIELDS = new Array();
	var ALL_FIELDS = new Array();

	// replace all apostrophes
	ALL_FIELDS = document.getElementsByTagName("input");
	q = /\'/g;
	for (i = 0; i < ALL_FIELDS.length; i++) {
		ALL_FIELDS[i].value = ALL_FIELDS[i].value.replace(q, ""); 
	}

	
	REQ_FIELDS = document.getElementById("required").value.split(',');
	clearReqErrs(REQ_FIELDS);
	
	// loops through the required fields and checks for errors
	for(x=0; x<REQ_FIELDS.length; x++)
	{
		//alert("loop " + x);
		field = document.getElementById(REQ_FIELDS[x]);
		
		if(!field){continue;}
		// determines the field type
		if (!field.type) {
			field.type='text';
		}
		//alert (field.name + ' ' + field.type + " '" + field.value + "' ");
		switch(field.type.toLowerCase())
		{
			case 'text':
				if(field.value == ""){					
					isErr = true;
					dispErr(ERR_PREFIX + field.id, errMessage);
				}
				break;
			case 'textarea':
				if(field.value == ""){
					isErr = true;
					dispErr(ERR_PREFIX + field.id, errMessage);
				}
				break;
			case 'password':
				if(field.value == ""){
					isErr = true;
					dispErr(ERR_PREFIX + field.id, errMessage);
				}
				break;								
			case 'select-one':				
				if(!field.selectedIndex){
					isErr = true;
					dispErr(ERR_PREFIX + field.id, errMessage);
				}
				if(field.value == ""){
					isErr = true;
					dispErr(ERR_PREFIX + field.id, errMessage);
				}
				break;
		}
	}
	
	// displays the global error message
	if(isErr){dispErr("err_global", errMessageGlobal);}
	
	return !isErr;
}

function checkPattern(fieldID, pattern, errMessage, errMessageGlobal)
/*	Desciption: checks to see if the value in the field fits the pattern given
	Input: fieldID: The id to the text field that contains the value
		pattern: The pattern to match.  Serveral predefined patterns
			are at the top of this document
		errMessage: The message to display in the error tag for that field
		errMessageGlobal: The general error message to display for the user
	Output: Returns true if the pattern matches, false otherwise
	Notes: This function also returns true if the object does not exist or if the value is blank
*/
{
	var isValid = false;	
	var evalue = document.getElementById(fieldID).value;

	if(!evalue){return true;}
	
	isValid = evalue.match(pattern);
	
	if(!isValid)
	{
		if(errMessage){dispErr(ERR_PREFIX+fieldID, errMessage)};
		if(errMessageGlobal){dispErr(ERR_GLOBAL, errMessageGlobal)};
	}
	else
	{
		dispErr(ERR_PREFIX+fieldID, "");
	}	
	
	return isValid;
}


function checkField(fieldID, validationType, errMessage, errMessageGlobal)
/*	Desciption: checks to see if the value in the field fits the validation given
	Input: fieldID: The id to the text field that contains the value
		validationType: The validation to check the field against.  
		errMessage: The message to display in the error tag for that field
		errMessageGlobal: The general error message to display for the user
	Output: Returns true if the validation succeeds, false otherwise
	Notes: This function also returns true if the object does not exist or if the value is blank
*/
{
	var isValid = false;
	var fvalue = document.getElementById(fieldID).value;

	if(!fvalue){return true;}
	
	// validation cases:
	switch(validationType) 
	{		
		case "integer":
			
			if (parseInt(fvalue) == fvalue) {
				isValid = true;
			}
			break;				
	}
	
	if(!isValid)
	{
		if(errMessage){dispErr(ERR_PREFIX+fieldID, errMessage)};
		if(errMessageGlobal){dispErr(ERR_GLOBAL, errMessageGlobal)};
	}
	else
	{
		dispErr(ERR_PREFIX+fieldID, "");
	}
	
	return isValid;
}

function checkPasswords(pass1ID, pass2ID)
/*	Desciption: Validates value in form to see if it matches the form of an email address
	Input: emailID: The id to the text field for the email address
	Output: returns a boolean if it was valid and displays an error message
	Notes: Inputting the ID incase we ever use email text field of a different name or there is more
		than one email on the page to validate
*/
{
	var isMatch = true;
	var pass1 = document.getElementById(pass1ID);
	var pass2 = document.getElementById(pass2ID);
	
	if(!pass1.value || !pass2.value || (pass1.value != pass2.value)){
		isMatch = false;
	}
	
	if(!isMatch)
	{
		dispErr(ERR_PREFIX+pass1ID, "Your passwords do not match");
		dispErr(ERR_GLOBAL, "Please reenter your password");
		pass1.value = '';
		pass2.value = '';
	}

	
	return isMatch;
}

function checkUser(usernameID)
{
	var username = document.getElementById(usernameID);
	no_user = false;
	if(username)
	{
		http.open('GET', 'lib/xml/newmemberdata.php?type=2&' + 'username=' + username, false);
		//http.onreadystatechange = handleCheckUser;
		http.send(null);
		if(http.responseText != 0)
		{
			no_user=false;
			dispErr(ERR_PREFIX+usernameID, "User already exists");
			dispErr(ERR_GLOBAL, "Please enter a new user name");			
		}
		else
		{
			no_user=true;
		}
	}
	
	return no_user;

}

var httpBook = xmlRequest();
var LOADING_STATE = 1;
var COMPLETE_STATE = 4;

bookID = 0;

function fill_book_data(bookIDtemp, thisObj)
{			
	//alert("entering function");
	
	url = String(location.href);
	url = url.toString();
	
	len = url.lastIndexOf("/");	
	subUrl = url.substring(0,len+1);
		
	origSource = thisObj.src;		// saves original state of image	
	
	spans = document.getElementsByTagName('span');	// get all span objects
	imgs = document.getElementsByTagName('img');	// get all img objects
	
	// concatenate spans array and imgs array into searchedElements array		
	searchedElements = new Array(imgs.length + spans.length);	
	k = spans.length;
	
	for (i = 0; i < spans.length; i++) {		
		searchedElements[i] = spans[i];		// load spans objects into searchedElements one at a time
	}	
	for (i = 0; i < imgs.length; i++) {		
		searchedElements[i + k] = imgs[i];	// load imgs objects into searchedElements one at a time
	}	
	
	for(i=0; i<searchedElements.length; i++){
		
		element = searchedElements[i]; 
				
		if (String(element.id).substring(0,4) == "book"){	// if span with 'book' in id, set innerHTML to ""
			element.innerHTML = "";			
		}
		if (String(element.src) == subUrl + "images/minus.gif"){	// if img source = 'minus.gif' set img source to 'plus.gif'			
			element.src = "images/plus.gif";			
		}
	}	
	
	
	if (origSource == subUrl + "images/plus.gif") {		
		thisObj.src = subUrl + "images/minus.gif";
		thisObj.alt = "less details";
		
		bookID = bookIDtemp;	// set global: 'bookID' = local parameter bookIDtemp function handle_book_data_state won't accept parameters ??
	
		httpBook.open('GET', 'lib/xml/getbookdata.php?bookID=' + bookID, true);		
		
		httpBook.onreadystatechange = handle_book_data_state;	
		httpBook.send(null);		
	}	
	else {				
		thisObj.src = subUrl + "images/plus.gif";
	}
		
		
}

function handle_book_data_state()
{	
	
	switch(httpBook.readyState) 
	{
		
		case COMPLETE_STATE:				
			
			data = httpBook.responseText.split('|');
			author = data[0];
			edition = data[1];
			notes = data[2];			
			isbn = data[3];
			dateUpdated = data[4];




			imgurl = "http://images.amazon.com/images/P/" + isbn + ".01._SCTZZZZZZZ_.jpg";

			bookData = "  <table bgcolor='#ececec' width='100%'> <tr> <td> </td> <td align='center' width=\"84\" nowrap background=\"images/noimage.png\" style=\"background-repeat:no-repeat; background-position:center;\"> <img src = " + imgurl + " border = 0> </td><td valign = top> <table><tr><td valign = top> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>Author: </strong> " + author + "  </td> </tr> <tr> <td>  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>Edition: </strong> " + edition + "  </td> </tr>  <tr>  <td>    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>Notes: </strong> " + notes + "  </td></tr> <tr>  <td>    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>Date Updated: </strong> " + dateUpdated + "  </td></tr></table> </td> </tr> </table>";
	
		
			location_span = document.getElementById("book" + bookID);			
			
			location_span.innerHTML = bookData;			
			
			break;
		case LOADING_STATE:			
			
			break;		
	}
}