// !!IMPORTANT!! The following code requires jquery
 // check required fields,i.e. input items with class equals required, using jquery.
   

function check_required_fields() {

   // check required fields,i.e. input items with class equals required, using jquery.
   var inputs = $("form .required");
   var isValid = true;
   
   // values is either a string, for a single value, or an array
   var numInputs = inputs.length;   
   for(i = 0; i < numInputs; i++) {
	  
      if($.trim(inputs[i].value) == "") {
		 
		 isValid = false;
		 break;  // break as soon as we find a missing value
		 
	  }
   
   }
   
   return isValid;
   
}


function check_email() {
 
   var isValid = true;
   var email_re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
  
   email = $(".email").val();
  
   if(email.search(email_re) == -1) {
  
      isValid = false;
	
   }	
   
   return isValid;
}


function check_quantities() {

   var products = $("form .product");
   var isValid = true;
   
   var numProducts = products.length;
  
   for(i = 0; i < numProducts; i++) {
   
      if(parseInt(products[i].value) > 500) {
	  
	     isValid = false;
		 break;
	  }
   
   }
   
   return isValid;
}


function check_product_exists() {

   var products = $("form .product");
   var product_exists = false;
  
   var numProducts = products.length;
   
   for(i = 0; i < numProducts; i++) {
   
      if(parseInt(products[i].value) > 0){
	  
	     product_exists = true;
		 break;
	  }
   
   }
   
   return product_exists;

}


// validates literature form submissions
function validate_literature_form() {
 
   var msg = '';
   var valid = true;
   
   // check that all required fields have values
   valid = check_required_fields();
   
   if(!valid) {
    
      msg = 'Please complete all required fields.\n\n';
   
   }
   
  
   // check that the email is valid
   valid = check_email();
   
   if(!valid) {
    
      msg = msg + 'You have entered an invalid email address.\n\n';
   
   }
   
   
   // check that the product quantities are valid
   valid = check_quantities();
   
   if(!valid) {
    
      msg = msg + 'Product quantities cannot exceed 500.\n\n';
   
   }
   
  
   // check that there is at least one product. (it was intentional that this is separate from the check_quantities function
   valid = check_product_exists();
   
   if(!valid) {
    
      msg = msg + 'Please select at least one product.\n\n';
   
   }
   
   
   // check that quantity of products, i.e. input names prepended with product_, is not greater than 500
   if(msg != '') {
   
      alert(msg);
	 
	  return false;
   
   }
   
   else {
        
      return true;
   
   }
   
}