var global_element = null;
var checked = false;
var checkflag = false;
var good_form = true;

function focusIt(){
	if (global_element != null){
		global_element.select();
		global_element.focus();
	}
}
var subtotal;

function subCalc(the_form) {
	subtotal = 0;
	var subtemp = 0;
    good_form = true;

 form = document.vita_form;	

// put the prices and form fields into parallel arrays.
 var price_array = new Array()
  price_array[0] = 199;
  price_array[1] = 199;
  price_array[2] = 199;
  price_array[3] = 199;
  price_array[4] = 25;  
  
 var item_array = new Array()
  item_array[0] = the_form.bluelink;
  item_array[1] = the_form.solar1;
  item_array[2] = the_form.solar1_and_batteries;
  item_array[3] = the_form.solar1_x2;
  item_array[4] = the_form.solar1_x2_and_batteries;  
  
 var quant_array = new Array()
  quant_array[0] = the_form.bluelink_quant;
  quant_array[1] = the_form.solar1_quant;
  quant_array[2] = the_form.solar1_and_batteries_quant;
  quant_array[3] = the_form.solar1_x2_quant;
  quant_array[4] = the_form.solar1_x2_and_batteries_quant;  

 var sub_array = new Array()
  sub_array[0] = the_form.sub0;
  sub_array[1] = the_form.sub1;
  sub_array[2] = the_form.sub2;
  sub_array[3] = the_form.sub3;      
  sub_array[4] = the_form.sub4;   

 for(i = 0; i < price_array.length; i++) {
   if (item_array[i].checked) {
	checkflag = true;
    // If there is no quantity selected, make the quantity 1.
    if(quant_array[i].value < 1) {
	 quant_array[i].value = 1;
	}
	// Give subtemp the value or the price times the quantity.
	subtemp = (price_array[i] * quant_array[i].value);
	// Put the converted string into the form field.
	sub_array[i].value = checkAmount(subtemp);
	// Add the converted number value to subtotal.
	subtotal += roundFloat(subtemp);

   }
   // If the item isn't checked, put nothing into the subtotal field.
   else if(!item_array[i].checked) {
	if((quant_array[i].value != '')&&(!checkflag)){
	  alert("You haven't selected a product. Please click the boxes on the left to select products before entering a quantity.")	
	}
    sub_array[i].value = '';
	quant_array[i].value='';
   }

 }
  form.total.value = checkAmount(subtotal);
  
 return subtotal;
}

function initForm(){
	// Function to run the form once, just in case the user refreshed with products selected. 
	subCalc(document.vita_form);
}

function roundFloat(num) {
 num = parseFloat(num);
 num = Math.round(100*num)/100
 if(isNaN(num)){
	alert("You have entered a non-number as a quantity. Please enter a number");
	num = 0;
	good_form = false;
 }
 

 return num
}

function checkAmount(num) {
   // Convert into a floating point number.
   num = parseFloat(num)
   // Round the number off.
   if(isNaN(num)){
   	  num = 0;		
   }
   num = Math.round(100*num)/100
   // Turn into a string.
   num = String(num)
   // Look for a decimal point. If none, add it and two zeros.
   if (num.indexOf(".") == -1) {
      num = num + ".00";
   }
   // If the decimal point is the second last position, add a zero
   if (num.indexOf(".") == num.length -2) {
     num = num + "0";
   }
   num = "$" + num;
   // Return the converted string.
   return num
}

// Functions for Form Validation:

function stripSpace(element,id){
	  // convert the data to a string.
			var el_str = String(element.value);
		
  	//check for any spaces and remove them.
			el_str = el_str.replace(/ /g,'');

    // put the spaceless content back into the field.
			document.getElementById(id).value = el_str;
	  
		
			return el_str;

}

// Email Validation:
function validateEmailAddress(id)
{

	var user_good = false;
	var domain_good = false;
	var tld_good = false;
    var element = document.getElementById(id);

		
		//call function to strip spaces.
    el_str = stripSpace(element,id);

    element = document.getElementById(id);

		//split the address up at the @ symbol
		var address_array = el_str.split('@');
		
		// THe user name is the beginning, Sherlock.
		var user_name = address_array[0];
		
		//make sure that there is only one @ symbol
		if(address_array.length > 2){
			alert('You have too many "@" symbols in your address. Only one is allowed in a proper address.');
			global_element = element;
			focusIt();
			return false;
		}
		if(address_array.length == 1){
			alert('Your email address does not contain an "@" symbol. Every email address must have this symbol.');
			global_element = element;
			focusIt();
			return false;
		}
		
		// Assuming that the @ symbol is present, split the part after it up at the period
		var non_user_string = address_array[1]
		var non_user_array = non_user_string.split('.');
 
        // Make sure there is at LEAST 1 dot.
		if (non_user_array.length == 1){
			alert('Your email address does not contain a dot (".", or period character).\n This is necessary for a proper email address such as "john@xyz.com"');
			global_element = element;
			focusIt();
			return false;			
		}
		
		// check the location of the dot. There could be more than one, so get the last one. The rest is the domain name.
		var last_dot = non_user_array[non_user_array.length-1];
	
    
		// No restrictions on the length of the TLD, because of the recent '.museum' addition.
		// However, we should make sure it's not an illegal 1 character TLD.
		if(last_dot.length < 2){
			alert('Please check the last part of your email address (you entered "'+last_dot+'"). It should end with something like .com, .net, .org, .co.uk, .ca, etc. \n A single letter at the end is incorrect.');
			global_element = element;
			focusIt();
			return false;			
		}
		// Check each section of the email after the @ to make sure they are not less than 2 characters.
		for (i=0; i<non_user_array.length -1; i++){
			if(non_user_array[i].length < 2){
				alert('The second part of your email address (before the ".", and after the "@" symbol) is too short. It must be at least 2 characters, such as "user@domain.com"');
				global_element = element;
				focusIt();
				return false;				
			}
		}
		
		//find out where the @ symbol is, and give the user explicit feedback about it if there is a problem.
		var at_location = el_str.indexOf('@');
		if (at_location == 0){
			alert('Your "@" symbol is at the beginning of your email address. This is incorrect. \n Email addresses take the form: username@domain.com');
			global_element = element;
			focusIt();
			return false;			
		}
		// Extract the domain name. We will assume it's the first part after the @ symbol.
		var domain_name = non_user_array[0];
		// Assuming the TLD is the last part
		var tld = non_user_array[non_user_array.length-1];
		
		// NOTE: There can be more sections, but it's impossible to know if the middle ones are a 2 part TLD or a domain.
		// Example: steve@support.apple.com vs. liz@royalty.co.uk 
		// Therefore, we will run the domain rex ex checking on any extra parts. 		
		
		// Once proper form and length is determined, use regular expressions to check for proper characters now.
		
		var user_patt = new RegExp(/[^a-zA-Z0-9_\-\.]/);
		var domain_patt = new RegExp(/[^a-zA-Z0-9\-\.]/);
		var tld_patt = new RegExp (/[^a-zA-Z]/);
		
   if(user_name.match(user_patt)!=null){
		  username_problem = user_name.match(user_patt);
			alert('The "'+username_problem+'" character in the "'+user_name+'" part of your email address is not allowed. Please fix it.');
			global_element = element;
			focusIt();
	 }
	 else{
		 user_good = true; 
	 }
	
   if(domain_name.match(domain_patt)!=null){
		  domain_problem = domain_name.match(domain_patt);
			alert('The "'+domain_problem+'" character in the "'+domain_name+'" part of your email address is not allowed. Please fix it.');
			global_element = element;
			focusIt();
	 }
	 else{
		 domain_good = true; 
	 }

   if(tld.match(tld_patt)!=null){
		  tld_problem = tld.match(tld_patt);
			alert('The "'+tld_problem+'" character in the "'+tld+'" part of your email address is not allowed. Please fix it.');
			global_element = element;
			focusIt();
	 }
	 else{
		 tld_good = true; 
	 }
					
		
// if((!element.value.match(regex)) && (element.value.length < 64))
   if((user_good) && (domain_good) && (tld_good))

		{
     //alert('good email');
				global_element = null;
				return true;
    }
    else
    {
			   if(!checked){
	/*				  id_string = id.toString();
						which_type = id.substring(0,4);
						if(which_type == 'ship'){which_type += 'p';}
						problem = element.value.match(regex);
					  alert('There seems to be a problem with your '+which_type+'ing email address. \n The "'+problem+'" character is not allowed.');
						*/
						global_element = element;
						focusIt();
				 }
            return false;	
    }
}

function validatePhone(id)
{
    var regex = new RegExp(/[^0-9\-\.]/);
    var element = document.getElementById(id);
    if(element.value.length < 9){
		alert('Your telephone number consists of only '+element.value.length+' digits. It must contain at least 9 digits.');
		global_element = element;
		focusIt();
		return false;
	}
	if(element.value.length > 32){
		alert('Your telephone number consists of '+element.value.length+' digits. This is longer than the allowed 32 digits.');
		global_element = element;
		focusIt();
		return false;			
	}
    if(!element.value.match(regex)){
		global_element = null;
        return true;
    }
    else{				  
		problem = element.value.match(regex);
	    alert('There seems to be a problem with your telephone number:  \n The "'+problem+'" character is not allowed.');
		global_element = element;
		focusIt();
        return false;	
    }
}

function validatePostalCode(id)
{
    var regex = new RegExp(/[^a-zA-Z0-9\ \-\.]/);

    var element = document.getElementById(id);
    if(element.value.length > 3 && element.value.length <= 16){
		global_element = null;
        return true;
	}
    else{
		alert("Your postal code/zip is either too short \(less than 3 digits\) or too long \(greater than 16 digits\).\n Please check it and re-enter.");
		global_element = element;
		focusIt();
		return false;
	}

    if(!element.value.match(regex)){
		global_element = null;
        return true;
    }
    else{
		problem = element.value.match(regex);
        alert('There seems to be a problem with your postal code:  \n The "'+problem+'" character is not allowed.');
		global_element = element;
		focusIt();
		return false;			
    }
}

function showMessage(checkflag,text){
  var message1="There are some problems with your information: ";	
  if(!checkflag){
	document.getElementById("msg").style.display="block";
	document.getElementById("msg").innerHTML = message1 + text;
	return false;
  }
  else{
    document.getElementById("msg").style.display="none";
	document.getElementById("msg").innerHTML = "";
  }	
}

function checkForm(){
   subCalc(document.vita_form);
   //before anything else, check if a product has been ordered. 
   if(subtotal < 1){
	  alert("You have not selected any products. \n Please click one of the boxes next to a product to select it.");   
	  return false;
   }
   if(!good_form){
	  alert("You have entered a non-number as a quantity for the products above. The form cannot submit. \n Please enter a valid number"); 
	  return false;
   }

   var flagged = false
   var problem = "";
   
   var required_fields = new Array();
   required_fields[0] = "first_name";
   required_fields[1] = "last_name";
   required_fields[2] = "email";   
   required_fields[3] = "phone";
   required_fields[4] = "add1";   
   required_fields[5] = "city";   
   required_fields[6] = "post_zip";
   
   var field_names = new Array();
   field_names[0] = "First Name";
   field_names[1] = "Last Name";
   field_names[2] = "Email Address";
   field_names[3] = "Phone Number";
   field_names[4] = "Address";
   field_names[5] = "City";
   field_names[6] = "Postal Code/Zip";   
	
   for (i=0; i<required_fields.length; i++){
	 current_obj = document.getElementById(required_fields[i]);
	 
	 if(current_obj.value == ""){
		 flagged=true;
		 problem += field_names[i] + "\n";
	 }
   }
   if (flagged){
	   alert("Several fields are empty. You need to fill out the following fields:\n"+problem);
	   showMessage(false,"Required fields are not filled in.");
	   return false;
   }

	
  checked_email = validateEmailAddress("email");
  showMessage(checked_email,"Please fix your email address."); 
  if(!checked_email){return false}
  
  checked_phone = validatePhone("phone");
  showMessage(checked_phone,"Please fix your phone number.");
  if(!checked_phone){return false}
  
  checked_postal = validatePostalCode("post_zip");
  showMessage(checked_postal,"Please fix your postal code / zip code");  
  if(!checked_postal){return false}

  selected_province = document.getElementById("state_province");
  if(selected_province.selectedIndex == 0){
	 alert("You need to select a state or province.");
	 showMessage(false, "Please select a state or province from the list");
	 return false;
  }

  //Everything is good, submit the form. 
  document.vita_form.action = "order1ng/HiQFM.php";
  alert("Thank you for your order. We will call you at the number you provided to finalize your payment.");
  document.vita_form.submit();
}

