function countryMatchesState(state, country) {
	var provinces = new Array("AB","BC","MB","NB","NF","NT","NS","NU","ON","PE","QC","SK","YT");
	var isProvince = false;
	for ( var i = 0; i < provinces.length; i++ ) {
		if (state.options[state.selectedIndex].value == provinces[i]) isProvince = true;
	}
	if (country.options[country.selectedIndex].value == 'Canada' && isProvince) return true;
	if (country.options[country.selectedIndex].value == 'USA' && !isProvince) return true;
	// else
	return false;
}

function checkEmail(email) {
	var at = email.value.indexOf("@");
	var dot = email.value.lastIndexOf(".");
	var last = email.value.length - 1;
	if ( at < 1 || dot - at < 2 || last - dot > 3 || last - dot < 2 ) {
		return false;
	}
	return true;
}

function validate(theform) { 
  var required_text = new Array('FIRST_NAME', 'LAST_NAME', 'ADDRESS1', 'CITY', 'ZIP/PC', 'EMAIL', 'EMAIL_bis');
  var missing_required = 'A required field is missing.';

  // text fields
  for (var i = 0; i < required_text.length ; i++) {
    if (theform[required_text[i]].value == '') {
      alert(missing_required);
      theform[required_text[i]].focus();
      return false;
    }
  }
  
  // STATE/PROV
  var state = theform['STATE/PROV'];
  var country = theform['COUNTRY'];
  
  if ( state.options[state.selectedIndex].value == null || state.options[state.selectedIndex].value == '' ) {
    alert(missing_required);
    state.focus();
    return false;
  }
  

  if ( country.options[country.selectedIndex].value == null || country.options[country.selectedIndex].value == '' ) {
    alert(missing_required);
    country.focus();
    return false;
  }
  
  if ( country.options[country.selectedIndex].value != null && country.options[country.selectedIndex].value != '' ) {
    if ( countryMatchesState(state, country) == false ) {
  		alert('The state/province you have chosen is not valid with the country you have chosen.');
  		state.focus();
  		return false;
    }
  }

  // EMAIL
  var email = theform['EMAIL'];
  
  if (email.value != null && email.value != '') {
    if ( checkEmail(email) == false ) {
  			alert('Please enter a valid e-mail address.');
			email.focus();
	    return false;
	  }
	}

  var email_bis = theform['EMAIL_bis'];

  if (email_bis.value != null && email.value != '') {
    if ( checkEmail(email_bis) == false ) {
      alert('Please enter a valid e-mail address.');
      email_bis.focus();
      return false;
    }
    if ( email.value != email_bis.value )
    {
      alert('Please make sure the e-mail address is the same in both fields.');
      email.focus();
      return false;
    }
  }
}
